Files
coulobre/src/coulobre/web_node_tls.py
T

303 lines
9.4 KiB
Python

import fcntl
import os
import ssl
import subprocess
import uuid
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,
check_installation,
check_reservation,
check_site_link,
configuration_installation,
enable_apache_site,
install_configuration,
locked_web_node,
run,
)
CERTBOT_ROOT = Path("/etc/letsencrypt")
ACME_WEBROOT = Path("/var/www/coulobre-acme")
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))
ensure_certificate(site)
enable_https(site)
def ensure_certificate(site):
if os.path.lexists(certificate_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, *, force=False):
command = (
"/usr/bin/certbot",
"certonly",
"--non-interactive",
"--force-renewal" if force else "--keep-until-expiring",
"--webroot",
"--webroot-path",
str(ACME_WEBROOT),
"--cert-name",
certbot_lineage(site).name,
"--domains",
site.domain,
)
try:
subprocess.run(
command,
check=True,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=120,
env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C"},
)
except FileNotFoundError:
raise ValueError("Install Certbot on the web node.") from None
except subprocess.TimeoutExpired:
raise ValueError(
"Certbot timed out. Check the HTTP-01 route and the Certbot log."
) from None
except subprocess.CalledProcessError:
raise ValueError(
"Certbot could not obtain the certificate. Check its account, "
"the HTTP-01 route, and the Certbot log on the web node."
) from None
def enable_https(site):
if os.geteuid() != 0:
raise ValueError("Run enable-https as root on the web node.")
with locked_web_node(fcntl.LOCK_EX):
paths = SitePaths.for_site(site)
apache, enabled = https_paths(paths)
check_https_prerequisites(site, paths)
install_https_configuration(
site, apache, enabled, socket_path=paths.apache_socket
)
def install_https_configuration(site, apache, enabled, *, socket_path=None):
config = https_configuration(site, socket_path=socket_path)
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):
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.")
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}
try:
apache, enabled = https_paths(SitePaths.for_site(site))
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):
paths = SitePaths.for_site(site)
check_reservation(site)
check_installation(site, paths)
check_configuration(
apache,
https_configuration(site, socket_path=paths.apache_socket),
)
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"}
def https_paths(paths):
name = f"{paths.apache.stem}-https.conf"
return paths.apache.with_name(name), paths.enabled.with_name(name)
def certbot_lineage(site):
name = site.name if isinstance(site, WebAlias) else site.service_user
return CERTBOT_ROOT / "live" / name
def custom_lineage(site):
from .web_node_apply import STATE_DIRECTORY
return STATE_DIRECTORY / "certificates" / site.service_user
def certificate_lineage(site):
if not isinstance(site, WebAlias):
active = custom_lineage(site) / "active"
if os.path.lexists(active):
return active
return certbot_lineage(site)
def resolved_certificate_files(site):
lineage = certificate_lineage(site)
if lineage.name == "active":
require_root_directory(lineage.parent)
info = lineage.lstat()
try:
revision = uuid.UUID(os.readlink(lineage))
except (OSError, ValueError):
raise ValueError(
"The uploaded certificate directory is unexpected."
) from None
if info.st_uid != 0 or str(revision) != os.readlink(lineage):
raise ValueError(
"The uploaded certificate directory is unexpected."
)
archive = lineage.parent / str(revision)
lineage = archive
else:
archive = CERTBOT_ROOT / "archive" / lineage.name
for directory in {lineage, archive}:
try:
require_root_directory(directory)
except FileNotFoundError:
raise ValueError(
f"Obtain the certificate for {site.domain}."
) from None
resolved = []
for source in (lineage / "fullchain.pem", lineage / "privkey.pem"):
target = source.resolve(strict=True)
if target.parent != archive:
raise ValueError(
"Expected certificate files to point into a managed folder."
)
resolved.append(target)
return tuple(resolved)
def https_configuration(site, *, socket_path=None):
chain_file, key_file = resolved_certificate_files(site)
validate_certificate_files(site, chain_file, key_file)
return render_https_configuration(site, socket_path=socket_path)
def validate_certificate_files(site, chain_file, key_file):
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 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),
)
def render_https_configuration(site, *, socket_path=None):
lineage = certificate_lineage(site)
certificate = lineage / "fullchain.pem"
private_key = lineage / "privkey.pem"
return site.render(
"apache",
port=443,
socket_path=socket_path,
tls_settings=(
"\n"
" SSLEngine On\n"
" SSLProtocol -all +TLSv1.2 +TLSv1.3\n"
f' SSLCertificateFile "{certificate}"\n'
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