diff --git a/src/coulobre/hosting/templates/hosting/apache-vhost.conf b/src/coulobre/hosting/templates/hosting/apache-vhost.conf index 3098aee..70bef32 100644 --- a/src/coulobre/hosting/templates/hosting/apache-vhost.conf +++ b/src/coulobre/hosting/templates/hosting/apache-vhost.conf @@ -1,7 +1,7 @@ - + ServerName $domain DocumentRoot "$document_root" - +$tls_settings AllowOverride None Options None diff --git a/src/coulobre/hosting/test_web_node_tls.py b/src/coulobre/hosting/test_web_node_tls.py new file mode 100644 index 0000000..cd8ad73 --- /dev/null +++ b/src/coulobre/hosting/test_web_node_tls.py @@ -0,0 +1,171 @@ +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import call, patch + +from django.test import SimpleTestCase + +from coulobre.web_node import WebSite +from coulobre.web_node_apply import SitePaths +from coulobre.web_node_tls import enable_https, https_status + + +class WebNodeTLSTests(SimpleTestCase): + def setUp(self): + directory = Path(self.enterContext(TemporaryDirectory())) + self.site = WebSite(42, "example.org") + self.state = directory / "state" + self.state.mkdir() + (self.state / "apply.lock").touch() + self.http = directory / "sites-available" / "coulobre-42.conf" + http_enabled = directory / "sites-enabled" / self.http.name + for path in (self.http, http_enabled): + path.parent.mkdir() + self.http.write_text(self.site.render("apache"), encoding="utf-8") + self.tls = self.http.with_name("coulobre-42-https.conf") + self.enabled = http_enabled.with_name(self.tls.name) + paths = SitePaths( + directory / "account", + self.http, + http_enabled, + directory / "php.conf", + directory / "site.sock", + ) + certbot = directory / "letsencrypt" + self.live = certbot / "live" / "coulobre-42" + self.archive = certbot / "archive" / "coulobre-42" + for path in (self.live, self.archive): + path.mkdir(parents=True) + for name in ("fullchain", "privkey"): + target = self.archive / f"{name}1.pem" + target.touch() + (self.live / f"{name}.pem").symlink_to(target) + + self.enterContext( + patch("coulobre.web_node_tls.os.geteuid", return_value=0) + ) + self.enterContext( + patch("coulobre.web_node_tls.STATE_DIRECTORY", self.state) + ) + self.enterContext(patch("coulobre.web_node_tls.CERTBOT_ROOT", certbot)) + self.enterContext( + patch( + "coulobre.web_node_tls.SitePaths.for_site", return_value=paths + ) + ) + self.enterContext( + patch( + "coulobre.web_node_tls.require_root_directory", + side_effect=self.require_fixture_directory, + ) + ) + self.enterContext( + patch( + "coulobre.web_node_apply.read_root_file", + side_effect=Path.read_text, + ) + ) + self.files = self.enterContext( + patch("coulobre.web_node_tls.check_root_file") + ) + self.reservation = self.enterContext( + patch("coulobre.web_node_tls.check_reservation") + ) + self.enterContext(patch("coulobre.web_node_tls.check_installation")) + self.ssl = self.enterContext( + patch("coulobre.web_node_tls.ssl.SSLContext") + ) + self.runner = self.enterContext( + patch("coulobre.web_node_tls.run", return_value=" ssl_module") + ) + self.recovery = self.enterContext(patch("coulobre.web_node_apply.run")) + + @staticmethod + def require_fixture_directory(path): + if not path.is_dir(): + raise FileNotFoundError(path) + + def test_enables_https_alongside_the_existing_http_site(self): + previous = self.http.read_text() + enable_https(self.site) + enable_https(self.site) + + self.assertEqual(self.http.read_text(), previous) + self.assertEqual(self.enabled.resolve(), self.tls) + content = self.tls.read_text() + self.assertIn("", content) + self.assertIn('DocumentRoot "/srv/coulobre/web/42/public"', content) + self.assertIn("proxy:unix:/run/php/coulobre-42.sock", content) + self.assertIn( + f'SSLCertificateFile "{self.live}/fullchain.pem"', content + ) + self.assertIn( + f'SSLCertificateKeyFile "{self.live}/privkey.pem"', content + ) + self.files.assert_any_call(self.archive / "privkey1.pem", mode=0o600) + self.ssl.return_value.load_cert_chain.assert_called_with( + self.archive / "fullchain1.pem", + self.archive / "privkey1.pem", + password="", + ) + self.runner.assert_any_call( + "/usr/bin/openssl", + "verify", + "-trusted", + str(self.archive / "fullchain1.pem"), + "-partial_chain", + "-purpose", + "sslserver", + "-verify_hostname", + "example.org", + str(self.archive / "fullchain1.pem"), + ) + self.assertEqual( + self.runner.call_args_list[-2:], + [ + call("/usr/sbin/apache2ctl", "configtest"), + call("/usr/sbin/service", "apache2", "reload"), + ], + ) + + def test_rejects_lineage_links_outside_the_account_archive(self): + private_key = self.live / "privkey.pem" + private_key.unlink() + foreign = self.archive.parent / "foreign-key.pem" + foreign.touch() + private_key.symlink_to(foreign) + + with self.assertRaisesMessage(ValueError, "to point into"): + enable_https(self.site) + + self.assertFalse(self.tls.exists()) + self.ssl.assert_not_called() + + def test_failed_reload_removes_https_files_and_restores_apache(self): + def command(*args): + if args[-1] == "reload": + raise ValueError("Reload failed.") + return " ssl_module" + + self.runner.side_effect = command + with self.assertRaisesMessage(ValueError, "Reload failed."): + enable_https(self.site) + + self.assertTrue(self.http.exists()) + self.assertFalse(self.tls.exists()) + self.assertFalse(self.enabled.is_symlink()) + self.recovery.assert_called_once_with( + "/usr/sbin/service", "apache2", "reload" + ) + + def test_status_reports_absence_and_drift_without_rewriting_files(self): + self.assertEqual(https_status(self.site)["state"], "not_installed") + self.reservation.assert_not_called() + enable_https(self.site) + self.assertEqual(https_status(self.site)["state"], "configured") + + self.tls.write_text("changed", encoding="utf-8") + report = https_status(self.site) + + self.assertEqual(report["state"], "needs_attention") + self.assertIn("Existing configuration differs", report["problem"]) + self.assertEqual(self.tls.read_text(), "changed") diff --git a/src/coulobre/node_files.py b/src/coulobre/node_files.py index 0f20e68..e3ddfef 100644 --- a/src/coulobre/node_files.py +++ b/src/coulobre/node_files.py @@ -22,6 +22,11 @@ def check_root_directory(path): def read_root_file(path, *, mode=None): + check_root_file(path, mode=mode) + return path.read_text(encoding="utf-8") + + +def check_root_file(path, *, mode=None): info = path.lstat() if ( not stat.S_ISREG(info.st_mode) @@ -31,7 +36,6 @@ def read_root_file(path, *, mode=None): raise ValueError(f"Expected a root-controlled file at {path}.") if mode is not None and stat.S_IMODE(info.st_mode) != mode: raise ValueError(f"Expected permissions {mode:04o} on {path}.") - return path.read_text(encoding="utf-8") def write_new_file(path, content, *, mode, group=None): diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 5f57885..4b42ecd 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -66,12 +66,12 @@ class WebSite: "socket_path": f"/run/php/{service_user}.sock", } - def render(self, configuration): + def render(self, configuration, *, port=80, tls_settings=""): resource = files("coulobre.hosting").joinpath( "templates", "hosting", CONFIGURATIONS[configuration] ) return Template(resource.read_text(encoding="utf-8")).substitute( - self.configuration() + self.configuration(), port=port, tls_settings=tls_settings ) @@ -95,6 +95,15 @@ def main(argv=None): "status", help="Check a site's local configuration and services." ) status.add_argument("manifest", type=Path) + https = commands.add_parser( + "enable-https", + help="Enable HTTPS with an existing Certbot certificate.", + ) + https.add_argument("manifest", type=Path) + https_status = commands.add_parser( + "https-status", help="Check a site's local HTTPS configuration." + ) + https_status.add_argument("manifest", type=Path) restore = commands.add_parser( "restore-directadmin", help="Restore a DirectAdmin website into an empty web root.", @@ -127,6 +136,17 @@ def main(argv=None): report = site_status(site) print(json.dumps(report, indent=2)) return 0 if report["state"] == "configured" else 2 + elif args.command == "enable-https": + from .web_node_tls import enable_https + + enable_https(site) + print(f"Enabled HTTPS for {site.domain}.") + elif args.command == "https-status": + from .web_node_tls import https_status + + report = https_status(site) + print(json.dumps(report, indent=2)) + return 0 if report["state"] == "configured" else 2 elif args.command == "restore-directadmin": from .web_node_restore import restore_website diff --git a/src/coulobre/web_node_apply.py b/src/coulobre/web_node_apply.py index 7a04fd1..760abc3 100644 --- a/src/coulobre/web_node_apply.py +++ b/src/coulobre/web_node_apply.py @@ -6,6 +6,7 @@ import pwd import stat import subprocess import time +from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path @@ -261,23 +262,10 @@ def check_public_directory(path, uid, gid): def install_configurations(site, apache, enabled, pool, socket): - created = [] - reload_attempts = [] - try: - for path, name in ((apache, "apache"), (pool, "php-fpm")): - content = site.render(name) - if os.path.lexists(path): - check_configuration(path, content) - else: - write_new_file(path, content, mode=0o644) - created.append(path) - - link_target = Path("../sites-available") / apache.name - if os.path.lexists(enabled): - check_site_link(enabled, link_target) - else: - enabled.symlink_to(link_target) - created.append(enabled) + with configuration_installation() as (created, reload_attempts): + install_configuration(apache, site.render("apache"), created) + install_configuration(pool, site.render("php-fpm"), created) + enable_apache_site(apache, enabled, created) run("/usr/sbin/php-fpm8.5", "--test") run("/usr/sbin/apache2ctl", "configtest") @@ -286,6 +274,31 @@ def install_configurations(site, apache, enabled, pool, socket): wait_for_socket(socket) reload_attempts.append("apache2") run("/usr/sbin/service", "apache2", "reload") + + +def install_configuration(path, content, created): + if os.path.lexists(path): + check_configuration(path, content) + else: + write_new_file(path, content, mode=0o644) + created.append(path) + + +def enable_apache_site(apache, enabled, created): + link_target = Path("../sites-available") / apache.name + if os.path.lexists(enabled): + check_site_link(enabled, link_target) + else: + enabled.symlink_to(link_target) + created.append(enabled) + + +@contextmanager +def configuration_installation(): + created = [] + reload_attempts = [] + try: + yield created, reload_attempts except (OSError, ValueError, KeyboardInterrupt) as error: failures = [] for path in reversed(created): diff --git a/src/coulobre/web_node_tls.py b/src/coulobre/web_node_tls.py new file mode 100644 index 0000000..3ec8204 --- /dev/null +++ b/src/coulobre/web_node_tls.py @@ -0,0 +1,141 @@ +import fcntl +import os +import ssl +from contextlib import contextmanager +from pathlib import Path + +from .node_files import check_root_file, require_root_directory +from .web_node_apply import ( + STATE_DIRECTORY, + SitePaths, + check_configuration, + check_installation, + check_reservation, + check_site_link, + configuration_installation, + enable_apache_site, + install_configuration, + run, +) + +CERTBOT_ROOT = Path("/etc/letsencrypt") + + +def enable_https(site): + if os.geteuid() != 0: + raise ValueError("Run enable-https as root on the web node.") + + paths = SitePaths.for_site(site) + apache, enabled = https_paths(paths) + with locked_web_node(fcntl.LOCK_EX): + check_reservation(site) + check_installation(site, paths) + if "ssl_module" not in run("/usr/sbin/apache2ctl", "-M"): + raise ValueError("Enable Apache's ssl module on the web node.") + 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 https_status(site): + if os.geteuid() != 0: + raise ValueError("Run https-status as root on the web node.") + + report = {**site.manifest(), "state": "not_installed", "problem": None} + paths = SitePaths.for_site(site) + apache, enabled = https_paths(paths) + try: + for directory in (apache.parent, enabled.parent): + require_root_directory(directory) + if not (os.path.lexists(apache) or os.path.lexists(enabled)): + return report + with locked_web_node(fcntl.LOCK_SH): + check_reservation(site) + check_installation(site, paths) + check_configuration(apache, https_configuration(site)) + check_site_link(enabled, Path("../sites-available") / apache.name) + run("/usr/sbin/apache2ctl", "configtest") + except (OSError, ValueError) as error: + return {**report, "state": "needs_attention", "problem": str(error)} + return {**report, "state": "configured"} + + +@contextmanager +def locked_web_node(mode): + try: + require_root_directory(STATE_DIRECTORY) + except FileNotFoundError: + raise ValueError( + "Apply the site manifest before enabling HTTPS." + ) from None + lock_path = STATE_DIRECTORY / "apply.lock" + check_root_file(lock_path) + with lock_path.open("r") as lock: + fcntl.flock(lock, mode) + yield + + +def https_paths(paths): + name = f"{paths.apache.stem}-https.conf" + return paths.apache.with_name(name), paths.enabled.with_name(name) + + +def https_configuration(site): + name = f"coulobre-{site.account_id}" + lineage = CERTBOT_ROOT / "live" / name + archive = CERTBOT_ROOT / "archive" / name + for directory in (lineage, archive): + try: + require_root_directory(directory) + except FileNotFoundError: + raise ValueError( + f"Obtain the Certbot certificate named {name}." + ) from None + + certificate = lineage / "fullchain.pem" + private_key = lineage / "privkey.pem" + resolved = [] + for source in (certificate, private_key): + target = source.resolve(strict=True) + if target.parent != archive: + raise ValueError(f"Expected {source} to point into {archive}.") + resolved.append(target) + chain_file, key_file = resolved + check_root_file(chain_file) + check_root_file(key_file, mode=0o600) + try: + ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER).load_cert_chain( + chain_file, key_file, password="" + ) + except ssl.SSLError: + raise ValueError( + "Could not load the Certbot certificate and private key." + ) from None + run( + "/usr/bin/openssl", + "verify", + "-trusted", + str(chain_file), + "-partial_chain", + "-purpose", + "sslserver", + "-verify_hostname", + site.domain, + str(chain_file), + ) + + return site.render( + "apache", + port=443, + tls_settings=( + "\n" + " SSLEngine On\n" + " SSLProtocol -all +TLSv1.2 +TLSv1.3\n" + f' SSLCertificateFile "{certificate}"\n' + f' SSLCertificateKeyFile "{private_key}"\n' + ), + )