from hashlib import sha256 from pathlib import Path from . import engine from .config import certificate WEBROOT = Path("/var/lib/coulobre-acme") HOOK_DIRECTORY = Path("/etc/letsencrypt/renewal-hooks/deploy") def configure_webroot(hosts, panel_host): engine.root_directory(WEBROOT) vhosts = [] for host in sorted(hosts): redirect = "" if host == panel_host: redirect = ( ' RedirectMatch permanent "^/(?!\\.well-known/' 'acme-challenge/)(.*)$" ' f'"https://{host}/$1"\n' ) vhosts.append( f"\n ServerName {host}\n" f' DocumentRoot "{WEBROOT}"\n' f' \n' " Options None\n AllowOverride None\n" " Require all denied\n \n" f' \n' " Require all granted\n \n" f"{redirect}\n" ) engine.put_file( Path("/etc/apache2/sites-available/001-coulobre-acme.conf"), "\n".join(vhosts), ) engine.run("a2enmod", "alias", label="Enable Apache redirects") engine.run( "a2ensite", "001-coulobre-acme.conf", label="Enable ACME challenges" ) engine.run( "apache2ctl", "configtest", label="Validate the ACME virtual hosts" ) engine.systemctl("enable", "--now", "apache2.service") engine.systemctl("reload", "apache2.service") def issue(host, email, services, *, webroot=False): method = ("--webroot", "-w", WEBROOT) if webroot else ("--standalone",) engine.run( "certbot", "certonly", "--non-interactive", "--agree-tos", "--email", email, "--cert-name", host, "--keep-until-expiring", "--domains", host, *method, label=f"Issue the certificate for {host}. Check /var/log/letsencrypt", timeout=600, ) directory = Path("/etc/letsencrypt/live") / host certificate( { "certificate": str(directory / "fullchain.pem"), "key": str(directory / "privkey.pem"), }, host, ) for parent in (HOOK_DIRECTORY.parent, HOOK_DIRECTORY): engine.root_directory(parent) fingerprint = sha256(host.encode("ascii")).hexdigest()[:24] engine.put_file( HOOK_DIRECTORY / f"coulobre-{fingerprint}", "#!/bin/sh\n" f'[ "${{RENEWED_LINEAGE:-}}" = "{directory}" ] || exit 0\n' "exec /usr/bin/systemctl try-reload-or-restart " f"{' '.join(services)}\n", mode=0o755, ) engine.systemctl("enable", "--now", "certbot.timer")