feature: the VPN, the router, the name server and WebDAV are components switched on the System tab and installed on demand, Caddy from the Ubuntu archive is a dependency and serves every HTTP and HTTPS port, HTTPS is chosen at install, its certificate is of the Servers Issuing CA or self-signed by default, of ACME or of another CA, the issuing CAs are in one tab, a locked account is unlocked again, the name of a CA is fixed once the CA exists, and a run of setup is no longer cut short by a change.
Release / release (push) Failing after 8s

This commit is contained in:
slawek committed 2026-11-24 05:51:27 +01:00
1 parent a649331aa2
commit a7bfabcb89
97 files changed
+4498 -1834

No files matched your search

+106 -76
View File
@@ -16,6 +16,7 @@ firewall and NAT rules are written against them, so choosing the wrong one
would be a silent and security-relevant mistake.
"""
import fcntl
import grp
import json
import os
@@ -27,6 +28,7 @@ import socket
import subprocess
import sys
import time
import traceback
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
@@ -71,9 +73,6 @@ CADDYFILE = pathlib.Path('/etc/caddy/linux-manager.Caddyfile')
CADDY_UNIT = 'caddy.service'
CADDY_GROUP = 'caddy'
#: The unit that installs Caddy from https.caddy_source with linux-manager-caddy, outside setup.
CADDY_INSTALL_UNIT = 'linux-manager-caddy.service'
#: The certificates and keys of the issuing CAs behind Caddy's ACME server and the sites of tls ca, <name>/cert.pem and
#: key.pem.
CADDY_PKI_DIR = pathlib.Path('/etc/caddy/linux-manager-pki')
@@ -81,6 +80,9 @@ CADDY_PKI_DIR = pathlib.Path('/etc/caddy/linux-manager-pki')
#: The certificates and keys of the sites of tls file, <site>/cert.pem and key.pem.
CADDY_SITES_DIR = pathlib.Path('/etc/caddy/linux-manager-sites')
#: The certificate and key of wan.local_fqdn Caddy serves when they come from no ACME CA.
CADDY_HTTPS_DIR = pathlib.Path('/etc/caddy/linux-manager-https')
#: The unit of dnsmasq, the resolver of the remote access clients.
RESOLVER_UNIT = 'linux-manager-resolver.service'
@@ -155,8 +157,8 @@ def resolve_public_ip(fqdn):
def setup_wireguard(ctx):
"""Generate the WireGuard key pair when it does not exist."""
if not ctx['wg_enabled']:
"""Generate the WireGuard key pair when it does not exist, once the VPN's packages are installed."""
if not ctx['wg_enabled'] or not ctx['vpn_installed']:
return
WG_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
key_file = WG_DIR / 'wg0.key'
@@ -262,16 +264,18 @@ def filter_block(ctx):
]
lines += ['# P2S DNS RULES END']
# The web service, the Manager and the metrics service choose their interfaces themselves, so their ports are open on
# both; without the router both are the one interface.
# Caddy serves the plain HTTP ports of the web service, the Manager and the metrics service on every address; each is
# open on the interfaces its listen names, where internal is the external interface without the router.
internal = ctx['int_iface'] if ctx['router_enabled'] else ctx['wan_iface']
listened = {'internal': [internal], 'external': [ctx['wan_iface']], 'both': [internal, ctx['wan_iface']]}
interfaces = list(dict.fromkeys(name for name in (ctx['int_iface'], ctx['wan_iface']) if name))
if ctx['web_enabled'] and interfaces:
lines += [
'',
'# WEB RULES START',
*(f'-A ufw-before-input -i {name} -p tcp --dport {ctx["web_port"]} -j ACCEPT' for name in interfaces),
'# WEB RULES END',
]
def opened(choice, port):
return [f'-A ufw-before-input -i {name} -p tcp --dport {port} -j ACCEPT'
for name in dict.fromkeys(listened[choice]) if name]
if ctx['web_enabled']:
lines += ['', '# WEB RULES START', *opened(ctx['web_listen'], ctx['web_port']), '# WEB RULES END']
if not SETUP_DONE.exists() and ctx['int_iface']:
lines += [
@@ -282,25 +286,15 @@ def filter_block(ctx):
'# BOOTSTRAP RULES END',
]
if interfaces:
port = linuxmanager.manager_port()
lines += [
'',
'# MANAGER RULES START',
*(f'-A ufw-before-input -i {name} -p tcp --dport {port} -j ACCEPT' for name in interfaces),
'# MANAGER RULES END',
]
lines += ['', '# MANAGER RULES START', *opened(linuxmanager.manager_listen(), linuxmanager.manager_port()),
'# MANAGER RULES END']
if linuxmanager.metrics_ready(ctx) and interfaces:
lines += [
'',
'# METRICS RULES START',
*(f'-A ufw-before-input -i {name} -p tcp --dport {ctx["metrics_port"]} -j ACCEPT' for name in interfaces),
'# METRICS RULES END',
]
if linuxmanager.metrics_ready(ctx):
lines += ['', '# METRICS RULES START', *opened(ctx['metrics_listen'], ctx['metrics_port']),
'# METRICS RULES END']
# Let's Encrypt reaches the HTTP challenge on the external interface, and the CA files published on port 80 are
# read on both; the HTTPS ports are open on both.
# The ACME CA reaches the HTTP challenge on the external interface while it issues the server's certificate, and
# the CA files published on port 80 are read on both; the HTTPS ports are open on both.
if linuxmanager.https_ready(ctx) and interfaces:
publish = ctx['pki_publish']
ports = [port for wanted, port in ((ctx['web_enabled'] or 'https' in publish or ctx['pki_acme'],
@@ -314,7 +308,7 @@ def filter_block(ctx):
'',
'# HTTPS RULES START',
*([f'-A ufw-before-input -i {ctx["wan_iface"]} -p tcp --dport {linuxmanager.ACME_HTTP_PORT} -j ACCEPT']
if ctx['wan_iface'] and 'http-80' not in publish else []),
if ctx['wan_iface'] and 'http-80' not in publish and ctx['https_certificate'] == 'acme' else []),
*(f'-A ufw-before-input -i {name} -p tcp --dport {port} -j ACCEPT' for name in interfaces for port in ports),
'# HTTPS RULES END',
]
@@ -752,42 +746,28 @@ def manage_resolver(changed):
def manage_caddy(cfg, ctx):
"""Run Caddy, the HTTPS proxy of the server's services and the server of the web sites, while either is wanted, and
stop it when not.
"""Run Caddy, a dependency of the package, which serves every HTTP and HTTPS port of the server's services and the
web sites; the services listen on loopback only.
While HTTPS is ready, CADDYFILE serves the web service on https.web_port, the manager on
https.manager_port, while metrics are enabled the metrics service on metrics.https_port, and while
WebDAV is ready WebDAV on sites.webdav_port, all for wan.local_fqdn with a certificate from Let's Encrypt, and all
calling the service on its loopback address. It also serves the CA files of linuxmanager_pki.PUBLISH_DIR at /pki/ on
the endpoints of pki.publish that are Caddy's, and an ACME server at /acme/<name>/ on https.web_port for each
issuing CA with acme and a certificate.
CADDYFILE serves over plain HTTP the web service on web.port while it is enabled, the manager on its port, or a
redirect (308) to its HTTPS address while HTTPS is ready and https.disable_auto_redirect is off, and while metrics
are enabled the metrics service on metrics.port. While HTTPS is ready, it serves the web service on
https.web_port, the manager on https.manager_port, while metrics are enabled the metrics service on
metrics.https_port, and while WebDAV is ready WebDAV on sites.webdav_port, all for wan.local_fqdn. Every site calls
its service on its loopback port. The certificate comes from the ACME CA of https.acme_provider, the global issuer,
with https.certificate acme, and otherwise is the one linuxmanager_pki.https_files gives, written to
CADDY_HTTPS_DIR; while that cannot be read, the HTTPS sites are left out, so that no ACME CA is asked for it. It
also serves the CA files of linuxmanager_pki.PUBLISH_DIR at /pki/ on the endpoints of pki.publish that are Caddy's,
and an ACME server at /acme/<name>/ on https.web_port for each issuing CA with acme and a certificate.
It serves each site of ctx's sites from its folder, with the TLS of the site: an issuing CA of tls ca issues its
certificates, and the certificate and key of tls file are written to CADDY_SITES_DIR/<name>. The certificates and
keys of the issuing CAs of both are copied to CADDY_PKI_DIR. While the sites cannot be read (ctx's sites is None),
the Caddyfile is left as it is.
Caddy is installed by CADDY_INSTALL_UNIT, outside setup, when it is missing or when
https.caddy_source is upstream and Caddy's repository is not configured; the unit restarts
setup, whose next run serves with it.
"""
sites = ctx['sites']
if not linuxmanager.https_ready(ctx) and not sites:
if sites is None:
return
linuxmanager.remove(CADDYFILE)
if unit_is_active(CADDY_UNIT):
run(['systemctl', 'disable', '--now', CADDY_UNIT], check=False)
return
source = cfg['https']['caddy_source']
if shutil.which('caddy') is None or (source == 'upstream' and not linuxmanager.CADDY_APT_SOURCE.is_file()):
run(['systemctl', 'start', '--no-block', CADDY_INSTALL_UNIT], check=False)
warn(f'Caddy is installed from the {source} source by {CADDY_INSTALL_UNIT}, which runs setup again')
return
if source == 'ubuntu' and linuxmanager.CADDY_APT_SOURCE.is_file():
warn("https.caddy_source ubuntu is ignored: Caddy's repository is configured, and Caddy stays upstream's")
if shutil.which('caddy') is None:
fail('caddy is not installed; it is a dependency of the package')
if sites is None:
warn('the web sites cannot be read; the Caddyfile is left as it is')
if not unit_is_active(CADDY_UNIT) and CADDYFILE.exists():
@@ -798,6 +778,26 @@ def manage_caddy(cfg, ctx):
except KeyError:
fail(f'the group {CADDY_GROUP} does not exist; is the caddy package installed?')
https = linuxmanager.https_ready(ctx)
own = None
if https and cfg['https']['certificate'] != 'acme':
try:
own = linuxmanager_pki.https_files(cfg)
except ldap.LDAPError as exc:
warn(f'the HTTPS sites are left out: the HTTPS certificate cannot be read: {exc}')
https = False
if https and own is None:
warn('the HTTPS sites are left out: the server has no HTTPS certificate yet')
https = False
copied = False
if own is None:
if CADDY_HTTPS_DIR.is_dir():
shutil.rmtree(CADDY_HTTPS_DIR)
else:
CADDY_HTTPS_DIR.mkdir(mode=0o750, exist_ok=True)
os.chown(CADDY_HTTPS_DIR, 0, group)
for file, data in zip(('cert.pem', 'key.pem'), own):
copied |= linuxmanager_pki.write(CADDY_HTTPS_DIR / file, data, 0o640)
os.chown(CADDY_HTTPS_DIR / file, 0, group)
wanted = list(dict.fromkeys([*(ctx['pki_acme'] if https else []),
*(site['ca'] for site in sites if site['tls'] == 'ca')]))
try:
@@ -810,7 +810,6 @@ def manage_caddy(cfg, ctx):
if site['tls'] == 'ca' and site['ca'] not in authorities:
warn(f'site {site["name"]} is left out: issuing CA {site["ca"]} has no certificate')
sites = [site for site in sites if site['tls'] != 'ca' or site['ca'] in authorities]
copied = False
for folder in (CADDY_PKI_DIR.iterdir() if CADDY_PKI_DIR.is_dir() else []):
if folder.name not in authorities:
shutil.rmtree(folder)
@@ -837,12 +836,18 @@ def manage_caddy(cfg, ctx):
linuxmanager_sites.ensure_folders(site['name'] for site in sites)
names = linuxmanager.issuing_cas(cfg)
caddy_ctx = dict(ctx, https=https, manager_port=linuxmanager.manager_port(),
redirect=https and not cfg['https']['disable_auto_redirect'],
web_loopback_port=linuxmanager.WEB_LOOPBACK_PORT,
manager_loopback_port=linuxmanager.MANAGER_LOOPBACK_PORT,
metrics_loopback_port=linuxmanager.METRICS_LOOPBACK_PORT,
https_tls={'cert': str(CADDY_HTTPS_DIR / 'cert.pem'), 'key': str(CADDY_HTTPS_DIR / 'key.pem')}
if own is not None else None,
pki_publish_dir=str(linuxmanager_pki.PUBLISH_DIR),
pki_cas=[{'id': name, 'name': names[name]['name'].strip(),
'cert': str(CADDY_PKI_DIR / name / 'cert.pem'),
'key': str(CADDY_PKI_DIR / name / 'key.pem')} for name in authorities],
acme_cas=[name for name in authorities if https and name in ctx['pki_acme']],
webdav=linuxmanager.webdav_ready(ctx), webdav_loopback_port=linuxmanager.WEBDAV_LOOPBACK_PORT,
webdav=https and linuxmanager.webdav_ready(ctx), webdav_loopback_port=linuxmanager.WEBDAV_LOOPBACK_PORT,
sites=[{'name': site['name'], 'tls': site['tls'], 'ca': site['ca'], 'spa': site['spa'],
'index': site['index_file'], 'root': str(linuxmanager_sites.SITES_DIR / site['name']),
'addresses': [caddy_address(host, site['port'], site['tls']) for host in site['hosts']]
@@ -864,15 +869,24 @@ def install_packages(feature):
warn(f'the packages of {feature} are installed by {unit}, which runs setup again')
def manage_components(cfg):
"""Install the packages of each component of linuxmanager.COMPONENTS whose switch is on, when any is missing or
marked as installed automatically, which apt autoremove would remove: an installation by apt-get marks them as
installed by hand. A component's steps wait for its packages; nothing is removed while a component is off."""
for name, (_, packages) in linuxmanager.COMPONENTS.items():
if linuxmanager.component_on(cfg, name) and (not linuxmanager.packages_installed(packages)
or linuxmanager.packages_automatic(packages)):
install_packages(name)
def manage_webdav(ctx):
"""Run rclone's WebDAV server of the sites' folders while WebDAV is ready, and stop it when not; rclone is installed
when it is missing."""
"""Run rclone's WebDAV server of the sites' folders while WebDAV is ready and rclone is installed
(manage_components), and stop it when not."""
if not linuxmanager.webdav_ready(ctx):
if unit_is_active(WEBDAV_UNIT):
run(['systemctl', 'disable', '--now', WEBDAV_UNIT], check=False)
return
if shutil.which('rclone') is None:
install_packages('webdav')
return
linuxmanager_sites.ensure_folders([])
run(['systemctl', 'enable', '--now', WEBDAV_UNIT], check=False)
@@ -899,7 +913,7 @@ def site_addresses(cfg, ctx):
def manage_dns(cfg, ctx):
"""Run PowerDNS, the primary name server of the domains of linuxmanager_dns, on the addresses of dns.listen while DNS
is enabled, and stop it when not; its packages are installed when they are missing.
is enabled and its packages are installed (manage_components), and stop it when not.
The settings, linuxmanager_dns.PDNS_CONF, are written before the packages are installed, so the server their
installation starts answers on those addresses only, beside systemd-resolved's stub on 127.0.0.53. The host names
@@ -927,7 +941,6 @@ def manage_dns(cfg, ctx):
linuxmanager_dns.PDNS_CONF.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
changed = write_if_changed(linuxmanager_dns.PDNS_CONF, linuxmanager_dns.config_text(addresses), 0o640)
if not linuxmanager_dns.PDNS_SERVER.exists() or not linuxmanager_dns.PDNS_SCHEMA.exists():
install_packages('dns')
return
os.chown(linuxmanager_dns.PDNS_CONF, 0, grp.getgrnam(linuxmanager_dns.GROUP).gr_gid)
linuxmanager_dns.provision()
@@ -1090,6 +1103,8 @@ def main():
failed_step = 'user directory'
progress('running', failed_step)
problem = manage_directory()
progress('running', 'components')
manage_components(cfg)
progress('running', 'configuration')
ctx, changed = linuxmanager.configure(cfg)
@@ -1195,13 +1210,28 @@ def record_failure(error):
if __name__ == '__main__':
# A failing step ends with SystemExit carrying its message (linuxmanager.fail).
try:
code = main()
except SystemExit as exc:
record_failure(str(exc.code))
raise
except Exception as exc:
record_failure(repr(exc))
raise
# The run holds SETUP_RUNNING while it works, and runs again while a request came during it (request_setup).
linuxmanager.SETUP_RUNNING.parent.mkdir(parents=True, exist_ok=True)
running = open(linuxmanager.SETUP_RUNNING, 'a', encoding='utf-8')
fcntl.flock(running, fcntl.LOCK_EX)
while True:
with linuxmanager.setup_lock():
linuxmanager.SETUP_REQUEST.unlink(missing_ok=True)
# A failing step ends with SystemExit carrying its message (linuxmanager.fail).
try:
code = main()
except SystemExit as exc:
record_failure(str(exc.code))
code = exc.code
except Exception as exc:
record_failure(repr(exc))
traceback.print_exc()
code = 1
# The lock is kept to the end of the process, so that a request either comes before this check or finds no run.
lock = linuxmanager.setup_lock()
if not linuxmanager.SETUP_REQUEST.exists():
break
lock.close()
print('linux-manager: another run was requested during this one; running again', flush=True)
fcntl.flock(running, fcntl.LOCK_UN)
sys.exit(code)