1244 lines
55 KiB
Python
Executable File
1244 lines
55 KiB
Python
Executable File
#!/usr/bin/python3
|
|
"""Apply the configuration to the running system.
|
|
|
|
Regenerates the configuration files first, then does everything that needs
|
|
the live system: routes, DNS-derived identity, WireGuard keys, firewall rules
|
|
and service reloads. Idempotent - a second run changes nothing.
|
|
|
|
Until a run has succeeded (SETUP_DONE), every run starts the bootstrap
|
|
service, BOOTSTRAP_UNITS, which shows the progress and the failure recorded in
|
|
SETUP_STATE on linuxmanager.BOOTSTRAP_PORTS, and the firewall opens those ports on the
|
|
internal interface. The first successful run writes SETUP_DONE, closes the
|
|
ports and stops the bootstrap service; a failed run leaves it running.
|
|
|
|
Interface names come from the configuration and are never guessed. The
|
|
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
|
|
import pathlib
|
|
import re
|
|
import secrets
|
|
import shutil
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import traceback
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
|
|
|
|
import ldap
|
|
|
|
import linuxmanager
|
|
import linuxmanager_auth
|
|
import linuxmanager_dns
|
|
import linuxmanager_ldap
|
|
import linuxmanager_pki
|
|
import linuxmanager_sites
|
|
import linuxmanager_users
|
|
from linuxmanager import fail, warn
|
|
|
|
BEFORE_RULES = pathlib.Path('/etc/ufw/before.rules')
|
|
UFW_DEFAULTS = pathlib.Path('/etc/default/ufw')
|
|
WG_DIR = pathlib.Path('/etc/wireguard')
|
|
WEB_STATE = linuxmanager.WEB_STATE
|
|
|
|
#: The state, the current step and the failure of the last run, which the bootstrap service shows.
|
|
SETUP_STATE = pathlib.Path('/run/linux-manager/setup.json')
|
|
|
|
#: Written once a run has succeeded; until then setup runs the bootstrap service and opens its ports.
|
|
SETUP_DONE = pathlib.Path('/var/lib/linux-manager/setup.done')
|
|
|
|
#: The unit of the bootstrap service, whose ports are linuxmanager.BOOTSTRAP_PORTS.
|
|
BOOTSTRAP_UNITS = ('linux-manager-bootstrap.service',)
|
|
|
|
#: The default admin of the Manager, {"username", "password"}, which the package's postinst writes from
|
|
#: its debconf answers; setup creates the account and removes the file.
|
|
MANAGER_ADMIN = pathlib.Path('/etc/linux-manager/manager-admin.json')
|
|
|
|
#: The password of the metrics service account, which setup makes and keeps (root only).
|
|
METRICS_SECRET = pathlib.Path('/etc/linux-manager/metrics.secret')
|
|
|
|
#: The schedule of the backup timer, written from backup.schedule.
|
|
BACKUP_SCHEDULE = pathlib.Path('/etc/systemd/system/linux-manager-backup.timer.d/schedule.conf')
|
|
|
|
#: The configuration of Caddy, the HTTPS proxy, which the package's drop-in for caddy.service names;
|
|
#: Caddy runs as the user and group CADDY_GROUP, which the caddy package creates.
|
|
CADDYFILE = pathlib.Path('/etc/caddy/linux-manager.Caddyfile')
|
|
CADDY_UNIT = 'caddy.service'
|
|
CADDY_GROUP = 'caddy'
|
|
|
|
#: 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')
|
|
|
|
#: 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 the HTTPS names Caddy serves when they come from no ACME CA.
|
|
CADDY_HTTPS_DIR = pathlib.Path('/etc/caddy/linux-manager-https')
|
|
|
|
#: The units of Avahi, which announces <host name>.local with mDNS while wan.local_fqdn is not set.
|
|
AVAHI_UNITS = ('avahi-daemon.socket', 'avahi-daemon.service')
|
|
|
|
#: The UDP port of mDNS.
|
|
MDNS_PORT = 5353
|
|
|
|
#: The unit of dnsmasq, the resolver of the remote access clients.
|
|
RESOLVER_UNIT = 'linux-manager-resolver.service'
|
|
|
|
#: The unit of rclone's WebDAV server of the sites' folders.
|
|
WEBDAV_UNIT = 'linux-manager-webdav.service'
|
|
|
|
#: The unit that installs the packages of a feature with install-packages, outside setup; {} is the feature.
|
|
INSTALL_UNIT = 'linux-manager-install@{}.service'
|
|
|
|
#: The timer of linux-manager-ca maintain, which keeps the CRLs fresh.
|
|
PKI_TIMER = 'linux-manager-pki.timer'
|
|
|
|
#: The system's side of console login (linuxmanager_users.console): nslcd's configuration, which serves the posixAccounts
|
|
#: of the directory with console login on, the name service switch, the sudo rule of their group, and the drop-in of
|
|
#: sshd that lets them sign in with their password while ssh.ldap_login is true.
|
|
NSLCD_CONF = pathlib.Path('/etc/nslcd.conf')
|
|
NSSWITCH = pathlib.Path('/etc/nsswitch.conf')
|
|
SUDOERS = pathlib.Path('/etc/sudoers.d/linux-manager')
|
|
SSHD_DROPIN = pathlib.Path('/etc/ssh/sshd_config.d/linux-manager.conf')
|
|
PAM_SESSION = pathlib.Path('/etc/pam.d/common-session')
|
|
|
|
#: The kernel settings setup writes while the router or the VPN is on: forwarding for both, and a loose rp_filter for
|
|
#: the router's asymmetric forwarding between its interfaces.
|
|
SYSCTL_CONF = pathlib.Path('/etc/sysctl.d/99-linux-manager.conf')
|
|
|
|
FILTER_ANCHOR = '# End required lines'
|
|
|
|
#: Configuration options left out wherever the configuration is shown.
|
|
SECRET_OPTION = re.compile(r'(^psk$)|secret|password|token|_key$|^database$')
|
|
|
|
BLOCKS = (
|
|
('# IPSEC RULES START', '# IPSEC RULES END'),
|
|
('# WIREGUARD RULES START', '# WIREGUARD RULES END'),
|
|
('# OPENVPN RULES START', '# OPENVPN RULES END'),
|
|
('# P2S DNS RULES START', '# P2S DNS RULES END'),
|
|
('# WEB RULES START', '# WEB RULES END'),
|
|
('# BOOTSTRAP RULES START', '# BOOTSTRAP RULES END'),
|
|
('# MANAGER RULES START', '# MANAGER RULES END'),
|
|
('# HTTPS RULES START', '# HTTPS RULES END'),
|
|
('# MDNS RULES START', '# MDNS RULES END'),
|
|
('# METRICS RULES START', '# METRICS RULES END'),
|
|
('# SITES RULES START', '# SITES RULES END'),
|
|
('# DNS RULES START', '# DNS RULES END'),
|
|
('# ROUTER FORWARD RULES START', '# ROUTER FORWARD RULES END'),
|
|
('# ROUTER NAT RULES START', '# ROUTER NAT RULES END'),
|
|
('# ROUTER MSS RULES START', '# ROUTER MSS RULES END'),
|
|
)
|
|
|
|
|
|
def run(args, check=True):
|
|
result = subprocess.run(args, capture_output=True, text=True)
|
|
if check and result.returncode != 0:
|
|
fail(f'{" ".join(args)} failed: {result.stderr.strip()}')
|
|
return result
|
|
|
|
|
|
def apply_routes(ctx):
|
|
"""Route the protected subnets via the configured internal interface.
|
|
|
|
validate() has already confirmed the interface exists.
|
|
"""
|
|
gateway = ctx['int_gateway_ip']
|
|
iface = ctx['int_iface']
|
|
for cidr in ctx['local_cidr_list']:
|
|
run(['ip', 'route', 'replace', cidr, 'via', gateway, 'dev', iface])
|
|
|
|
|
|
def resolve_public_ip(fqdn):
|
|
try:
|
|
return socket.getaddrinfo(fqdn, None, socket.AF_INET)[0][4][0]
|
|
except socket.gaierror as exc:
|
|
fail(f'cannot resolve {fqdn} for local_id_mode=public_ip: {exc}')
|
|
|
|
|
|
def setup_wireguard(ctx):
|
|
"""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'
|
|
pub_file = WG_DIR / 'wg0.pub'
|
|
|
|
if not key_file.exists() or key_file.stat().st_size == 0:
|
|
result = run(['wg', 'genkey'])
|
|
key_file.write_text(result.stdout)
|
|
os.chmod(key_file, 0o600)
|
|
|
|
result = subprocess.run(['wg', 'pubkey'], input=key_file.read_text(),
|
|
capture_output=True, text=True)
|
|
if result.returncode != 0:
|
|
fail(f'wg pubkey failed: {result.stderr.strip()}')
|
|
pub_file.write_text(result.stdout)
|
|
os.chmod(pub_file, 0o644)
|
|
|
|
|
|
def strip_blocks(text):
|
|
"""Remove every block this package owns, and the blank line before it."""
|
|
lines = text.splitlines(keepends=True)
|
|
starts = {start for start, _ in BLOCKS}
|
|
ends = {end for _, end in BLOCKS}
|
|
|
|
out = []
|
|
skipping = False
|
|
for line in lines:
|
|
stripped = line.strip()
|
|
if not skipping and stripped in starts:
|
|
while out and out[-1].strip() == '':
|
|
out.pop()
|
|
skipping = True
|
|
continue
|
|
if skipping:
|
|
if stripped in ends:
|
|
skipping = False
|
|
continue
|
|
out.append(line)
|
|
return ''.join(out)
|
|
|
|
|
|
def filter_block(ctx):
|
|
lines = []
|
|
|
|
if linuxmanager.s2s_ready(ctx) or linuxmanager.p2s_ready(ctx):
|
|
lines += [
|
|
'',
|
|
'# IPSEC RULES START',
|
|
'-A ufw-before-input -p udp --dport 500 -j ACCEPT',
|
|
'-A ufw-before-input -p udp --dport 4500 -j ACCEPT',
|
|
'-A ufw-before-input -p esp -j ACCEPT',
|
|
'-A ufw-before-input -m policy --dir in --pol ipsec -j ACCEPT',
|
|
'-A ufw-before-output -m policy --dir out --pol ipsec -j ACCEPT',
|
|
'-A ufw-before-forward -m policy --dir in --pol ipsec -j ACCEPT',
|
|
'-A ufw-before-forward -m policy --dir out --pol ipsec -j ACCEPT',
|
|
'# IPSEC RULES END',
|
|
]
|
|
|
|
if linuxmanager.wg_ready(ctx):
|
|
lines += [
|
|
'',
|
|
'# WIREGUARD RULES START',
|
|
f'-A ufw-before-input -p udp --dport {ctx["wg_listen_port"]} -j ACCEPT',
|
|
'# WIREGUARD RULES END',
|
|
]
|
|
|
|
if linuxmanager.openvpn_ready(ctx):
|
|
device = ctx['openvpn_device']
|
|
lines += [
|
|
'',
|
|
'# OPENVPN RULES START',
|
|
f'-A ufw-before-input -i {ctx["wan_iface"]} -p {ctx["openvpn_protocol"]} --dport {ctx["openvpn_port"]} -j ACCEPT',
|
|
]
|
|
for subnet in ctx['local_cidr_list']:
|
|
lines += [
|
|
f'-A ufw-before-forward -i {device} -d {subnet} -j ACCEPT',
|
|
f'-A ufw-before-forward -o {device} -s {subnet} -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT',
|
|
]
|
|
lines += ['# OPENVPN RULES END']
|
|
|
|
pools = linuxmanager.vpn_pools(ctx)
|
|
# The remote access clients' resolver answers on the addresses of p2s.dns_listen.
|
|
if pools and ctx['p2s_resolver_addrs']:
|
|
lines += ['', '# P2S DNS RULES START']
|
|
for pool in pools:
|
|
for address in ctx['p2s_resolver_addrs']:
|
|
lines += [
|
|
f'-A ufw-before-input -s {pool} -d {address} -p udp --dport 53 -j ACCEPT',
|
|
f'-A ufw-before-input -s {pool} -d {address} -p tcp --dport 53 -j ACCEPT',
|
|
]
|
|
lines += ['# P2S DNS RULES END']
|
|
|
|
# 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))
|
|
|
|
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']
|
|
|
|
# Without wan.local_fqdn, Avahi answers mDNS queries for <host name>.local on the internal side.
|
|
if ctx['mdns'] and internal:
|
|
lines += ['', '# MDNS RULES START', f'-A ufw-before-input -i {internal} -p udp --dport {MDNS_PORT} -j ACCEPT',
|
|
'# MDNS RULES END']
|
|
|
|
if not SETUP_DONE.exists() and ctx['int_iface']:
|
|
lines += [
|
|
'',
|
|
'# BOOTSTRAP RULES START',
|
|
*(f'-A ufw-before-input -i {ctx["int_iface"]} -p tcp --dport {port} -j ACCEPT'
|
|
for port in linuxmanager.BOOTSTRAP_PORTS),
|
|
'# BOOTSTRAP RULES END',
|
|
]
|
|
|
|
lines += ['', '# MANAGER RULES START', *opened(linuxmanager.manager_listen(), linuxmanager.manager_port()),
|
|
'# MANAGER RULES END']
|
|
|
|
if linuxmanager.metrics_ready(ctx):
|
|
lines += ['', '# METRICS RULES START', *opened(ctx['metrics_listen'], ctx['metrics_port']),
|
|
'# METRICS RULES END']
|
|
|
|
# The ACME CA reaches the HTTP challenge on the external interface while it issues the server's certificate; the
|
|
# HTTPS ports are open on both.
|
|
if interfaces:
|
|
ports = [port for wanted, port in ((ctx['web_enabled'] or ctx['pki_acme'], ctx['https_web_port']),
|
|
(True, ctx['https_manager_port']),
|
|
(linuxmanager.metrics_ready(ctx), ctx['metrics_https_port']),
|
|
(linuxmanager.webdav_ready(ctx), ctx['webdav_port'])) if wanted]
|
|
lines += [
|
|
'',
|
|
'# 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 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',
|
|
]
|
|
|
|
# Each site's port is open on the interfaces of its listen; a site with a certificate of Let's Encrypt needs the HTTP
|
|
# challenge on the external interface.
|
|
by_listen = {'internal': [ctx['int_iface']], 'external': [ctx['wan_iface']],
|
|
'both': [ctx['int_iface'], ctx['wan_iface']]}
|
|
sites = ctx['sites'] or []
|
|
rules = sorted({(name, site['port']) for site in sites for name in by_listen[site['listen']] if name})
|
|
if ctx['wan_iface'] and any(site['tls'] == 'acme' for site in sites):
|
|
rules = sorted(set(rules) | {(ctx['wan_iface'], linuxmanager.ACME_HTTP_PORT)})
|
|
if rules:
|
|
lines += [
|
|
'',
|
|
'# SITES RULES START',
|
|
*(f'-A ufw-before-input -i {name} -p tcp --dport {port} -j ACCEPT' for name, port in rules),
|
|
'# SITES RULES END',
|
|
]
|
|
|
|
dns_interfaces = (list(dict.fromkeys(name for name in by_listen[ctx['dns_listen']] if name))
|
|
if linuxmanager.dns_ready(ctx) else [])
|
|
if dns_interfaces:
|
|
lines += [
|
|
'',
|
|
'# DNS RULES START',
|
|
*(f'-A ufw-before-input -i {name} -p {protocol} --dport 53 -j ACCEPT'
|
|
for name in dns_interfaces for protocol in ('udp', 'tcp')),
|
|
'# DNS RULES END',
|
|
]
|
|
|
|
if linuxmanager.routing_ready(ctx):
|
|
lines += ['', '# ROUTER FORWARD RULES START']
|
|
for subnet in ctx['local_cidr_list']:
|
|
lines += [
|
|
f'-A ufw-before-forward -s {subnet} -o {ctx["wan_iface"]} -j ACCEPT',
|
|
f'-A ufw-before-forward -d {subnet} -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT',
|
|
]
|
|
lines += ['# ROUTER FORWARD RULES END']
|
|
|
|
return ''.join(line + '\n' for line in lines)
|
|
|
|
|
|
def nat_and_mangle_block(ctx):
|
|
lines = []
|
|
|
|
if linuxmanager.routing_ready(ctx):
|
|
subnets = ctx['local_cidr_list']
|
|
lines += [
|
|
'',
|
|
'# ROUTER NAT RULES START',
|
|
'*nat',
|
|
':POSTROUTING ACCEPT [0:0]',
|
|
'-F POSTROUTING',
|
|
]
|
|
# Every RETURN precedes every MASQUERADE, so traffic bound for a tunnel
|
|
# escapes NAT; each ready connection pairs its local and remote subnets.
|
|
for connection in ctx['connections']:
|
|
if not connection['ready']:
|
|
continue
|
|
for subnet in connection['local_cidr_list']:
|
|
for cidr in connection['remote_cidr_list']:
|
|
lines.append(f'-A POSTROUTING -s {subnet} -d {cidr} -j RETURN')
|
|
for subnet in subnets:
|
|
lines.append(
|
|
f'-A POSTROUTING -s {subnet} -o {ctx["wan_iface"]} -j MASQUERADE')
|
|
lines += ['COMMIT', '# ROUTER NAT RULES END']
|
|
elif not ctx['router_enabled'] and ctx['wan_iface'] and linuxmanager.vpn_pools(ctx):
|
|
# Without the router the remote access clients reach the server's networks from its own address.
|
|
lines += [
|
|
'',
|
|
'# ROUTER NAT RULES START',
|
|
'*nat',
|
|
':POSTROUTING ACCEPT [0:0]',
|
|
'-F POSTROUTING',
|
|
*(f'-A POSTROUTING -s {pool} -o {ctx["wan_iface"]} -j MASQUERADE' for pool in linuxmanager.vpn_pools(ctx)),
|
|
'COMMIT',
|
|
'# ROUTER NAT RULES END',
|
|
]
|
|
|
|
if ctx['router_enabled'] or ctx['vpn_enabled']:
|
|
lines += [
|
|
'',
|
|
'# ROUTER MSS RULES START',
|
|
'*mangle',
|
|
':FORWARD ACCEPT [0:0]',
|
|
'-A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu',
|
|
'COMMIT',
|
|
'# ROUTER MSS RULES END',
|
|
]
|
|
|
|
return ''.join(line + '\n' for line in lines)
|
|
|
|
|
|
def _insert_after_line(text, marker, block):
|
|
lines = text.splitlines(keepends=True)
|
|
for index, line in enumerate(lines):
|
|
if line.strip() == marker:
|
|
lines.insert(index + 1, block)
|
|
return ''.join(lines)
|
|
return None
|
|
|
|
|
|
def nat_rules(text):
|
|
"""The POSTROUTING rules of the package's NAT block in the text of before.rules."""
|
|
lines = [line.strip() for line in text.splitlines()]
|
|
start, end = '# ROUTER NAT RULES START', '# ROUTER NAT RULES END'
|
|
if start not in lines or end not in lines:
|
|
return []
|
|
return [line for line in lines[lines.index(start):lines.index(end)] if line.startswith('-A POSTROUTING ')]
|
|
|
|
|
|
def remove_stale_nat(original, text):
|
|
"""Delete from the running nat table the rules of the old NAT block that the new one no longer has; ufw reload
|
|
leaves the nat table alone."""
|
|
wanted = set(nat_rules(text))
|
|
for rule in nat_rules(original):
|
|
if rule not in wanted:
|
|
run(['iptables', '-t', 'nat', '-D', *rule.split()[1:]], check=False)
|
|
|
|
|
|
def setup_ufw(ctx):
|
|
"""Rewrite the package's blocks in before.rules. Returns True on change."""
|
|
if not BEFORE_RULES.is_file():
|
|
fail(f'{BEFORE_RULES} does not exist')
|
|
|
|
if UFW_DEFAULTS.is_file():
|
|
text = UFW_DEFAULTS.read_text(encoding='utf-8')
|
|
updated = ''.join(
|
|
'DEFAULT_FORWARD_POLICY="ACCEPT"\n'
|
|
if line.startswith('DEFAULT_FORWARD_POLICY=') else line
|
|
for line in text.splitlines(keepends=True)
|
|
)
|
|
if updated != text:
|
|
UFW_DEFAULTS.write_text(updated, encoding='utf-8')
|
|
|
|
original = BEFORE_RULES.read_text(encoding='utf-8')
|
|
text = strip_blocks(original)
|
|
|
|
result = _insert_after_line(text, FILTER_ANCHOR, filter_block(ctx))
|
|
if result is None:
|
|
fail(f'{BEFORE_RULES}: anchor "{FILTER_ANCHOR}" not found')
|
|
text = result
|
|
|
|
result = _insert_after_line(text, 'COMMIT', nat_and_mangle_block(ctx))
|
|
if result is None:
|
|
fail(f'{BEFORE_RULES}: no COMMIT line found')
|
|
text = result
|
|
|
|
if text == original:
|
|
return False
|
|
BEFORE_RULES.write_text(text, encoding='utf-8')
|
|
remove_stale_nat(original, text)
|
|
return True
|
|
|
|
|
|
def unit_is_active(unit):
|
|
return run(['systemctl', 'is-active', '--quiet', unit],
|
|
check=False).returncode == 0
|
|
|
|
|
|
def manage_strongswan(ctx, changed):
|
|
"""Make sure the IPsec daemon is running and holding the current config.
|
|
|
|
strongswan.service loads swanctl configuration itself on start
|
|
(ExecStartPost) and re-reads it on reload, so starting it is enough on a
|
|
cold boot and a reload is the right response to a configuration change.
|
|
"""
|
|
wanted = linuxmanager.s2s_ready(ctx) or linuxmanager.p2s_ready(ctx)
|
|
if not wanted:
|
|
if unit_is_active('strongswan'):
|
|
run(['systemctl', 'disable', '--now', 'strongswan'], check=False)
|
|
return
|
|
|
|
if not unit_is_active('strongswan'):
|
|
run(['systemctl', 'enable', '--now', 'strongswan'], check=False)
|
|
elif 'swanctl' in changed:
|
|
run(['systemctl', 'reload', 'strongswan'], check=False)
|
|
|
|
|
|
def manage_wireguard(ctx, changed):
|
|
"""Bring wg0 up when WireGuard is configured, and down when it is not."""
|
|
unit = 'wg-quick@wg0'
|
|
|
|
if not linuxmanager.wg_ready(ctx):
|
|
if unit_is_active(unit):
|
|
run(['systemctl', 'disable', '--now', unit], check=False)
|
|
return
|
|
|
|
if not unit_is_active(unit):
|
|
run(['systemctl', 'enable', '--now', unit], check=False)
|
|
elif 'wireguard' in changed:
|
|
run(['systemctl', 'restart', unit], check=False)
|
|
|
|
|
|
def manage_directory():
|
|
"""Provision the user directory in slapd, whether or not a P2S system is configured; the problem, or ''."""
|
|
if linuxmanager_ldap.ensure_services() or not unit_is_active('slapd'):
|
|
result = run(['systemctl', 'restart', 'slapd'], check=False)
|
|
if result.returncode != 0:
|
|
return f'slapd cannot be restarted: {result.stderr.strip()}'
|
|
try:
|
|
linuxmanager_ldap.provision()
|
|
except Exception as exc:
|
|
return f'the user directory cannot be provisioned: {exc!r}'
|
|
return ''
|
|
|
|
|
|
def manage_admin():
|
|
"""Create the Manager's default admin from MANAGER_ADMIN, then remove the file; the problem, or ''.
|
|
|
|
The admin is a Manager-only account and a member of the admins group, which is created with it
|
|
when it does not exist.
|
|
"""
|
|
if not MANAGER_ADMIN.exists():
|
|
return ''
|
|
try:
|
|
answers = json.loads(MANAGER_ADMIN.read_text(encoding='utf-8'))
|
|
name, password = answers['username'], answers['password']
|
|
with linuxmanager_users.session() as connection:
|
|
linuxmanager_users.add(connection, name, password, {})
|
|
try:
|
|
linuxmanager_users.group_member_add(connection, linuxmanager_users.ADMIN_GROUP, name)
|
|
except linuxmanager_users.Failure as failure:
|
|
if failure.status != 3:
|
|
raise
|
|
linuxmanager_users.group_add(connection, linuxmanager_users.ADMIN_GROUP, 'Router administrators', [name])
|
|
MANAGER_ADMIN.unlink()
|
|
except (OSError, ValueError, KeyError, TypeError, ldap.LDAPError, linuxmanager_users.Failure) as exc:
|
|
return f'the Manager admin cannot be created from {MANAGER_ADMIN}: {exc}'
|
|
return ''
|
|
|
|
|
|
def manage_metrics_account(ctx):
|
|
"""Keep the service account metrics.service_account names, whose password is in METRICS_SECRET; the problem, or ''.
|
|
|
|
While metrics are enabled, setup owns the account, an internal service account: it adds it as a service account
|
|
with a random password and the labels of linuxmanager_users.internal_accounts when it is missing, sets those labels
|
|
when they differ, and gives it a new random password, ending any lockout, when METRICS_SECRET is missing or does
|
|
not hold its password. The password of a disabled account is left as it is. An account of that name that is not a
|
|
service account is left alone and is a problem.
|
|
"""
|
|
if not linuxmanager.metrics_ready(ctx):
|
|
return ''
|
|
name = ctx['metrics_service_account']
|
|
wanted = linuxmanager_users.internal_accounts().get(name, {})
|
|
try:
|
|
linuxmanager_users.check_name(name)
|
|
try:
|
|
password = METRICS_SECRET.read_text(encoding='utf-8').strip()
|
|
except OSError:
|
|
password = ''
|
|
with linuxmanager_users.session() as connection:
|
|
try:
|
|
current = linuxmanager_users.entry(connection, name)
|
|
except linuxmanager_users.Failure as failure:
|
|
if failure.status != 3:
|
|
raise
|
|
current = None
|
|
if current is not None and not linuxmanager_users.service(current):
|
|
return f'metrics.service_account: {name} is a user, not a service account'
|
|
if current is not None and any(linuxmanager_users.summary(current)[key] != value for key, value in wanted.items()):
|
|
linuxmanager_users.update_service(connection, name, wanted)
|
|
# An administrator who disabled the account meant it; its password is left as it is.
|
|
if current is not None and not linuxmanager_users.summary(current)['enabled']:
|
|
return ''
|
|
valid = False
|
|
if current is not None and password:
|
|
try:
|
|
linuxmanager_users.login(name, password, None)
|
|
valid = True
|
|
except linuxmanager_users.Failure:
|
|
pass
|
|
if not valid:
|
|
password = secrets.token_urlsafe(32)
|
|
METRICS_SECRET.touch(mode=0o600)
|
|
METRICS_SECRET.chmod(0o600)
|
|
METRICS_SECRET.write_text(password + '\n', encoding='utf-8')
|
|
if current is None:
|
|
linuxmanager_users.add(connection, name, password, wanted, service=True)
|
|
else:
|
|
linuxmanager_users.passwd(connection, name, password)
|
|
linuxmanager_users.unlock(connection, name)
|
|
except (OSError, ldap.LDAPError, linuxmanager_users.Failure) as exc:
|
|
return f'the metrics service account cannot be kept: {exc}'
|
|
return ''
|
|
|
|
|
|
def write_if_changed(path, text, mode=0o644):
|
|
"""Write the file when its content differs; whether it was written."""
|
|
try:
|
|
if path.read_text(encoding='utf-8') == text:
|
|
return False
|
|
except OSError:
|
|
pass
|
|
path.write_text(text, encoding='utf-8')
|
|
path.chmod(mode)
|
|
return True
|
|
|
|
|
|
def manage_sysctl(ctx):
|
|
"""Write SYSCTL_CONF while the router or the VPN is on, remove it while both are off, and apply the settings when
|
|
the file changed. Removing the file leaves the running values alone, as Docker also needs forwarding."""
|
|
if ctx['router_enabled'] or ctx['vpn_enabled']:
|
|
lines = ['net.ipv4.ip_forward = 1']
|
|
if ctx['router_enabled']:
|
|
lines += ['net.ipv4.conf.all.rp_filter = 0', 'net.ipv4.conf.default.rp_filter = 0']
|
|
changed = write_if_changed(SYSCTL_CONF, ''.join(line + '\n' for line in lines))
|
|
else:
|
|
changed = SYSCTL_CONF.exists()
|
|
SYSCTL_CONF.unlink(missing_ok=True)
|
|
if changed:
|
|
run(['sysctl', '--system'], check=False)
|
|
|
|
|
|
def manage_console(cfg):
|
|
"""Make the system serve console login; the problem, or ''.
|
|
|
|
The local group linuxmanager_ldap.CONSOLE_GROUP is created when missing, and sudo lets its members run any command
|
|
with their password. nslcd serves the directory's posixAccounts with console login on through the local socket,
|
|
and checks their passwords by binding as the user; the passwd line of the name service switch gains ldap, which
|
|
restarts the web service, and PAM creates a home at the first login. While ssh.ldap_login is true, sshd accepts the password of the group's members;
|
|
a drop-in sshd -t refuses is removed again.
|
|
"""
|
|
group = linuxmanager_ldap.CONSOLE_GROUP
|
|
try:
|
|
grp.getgrnam(group)
|
|
except KeyError:
|
|
result = run(['groupadd', '--system', group], check=False)
|
|
if result.returncode != 0:
|
|
return f'the group {group} cannot be created: {result.stderr.strip()}'
|
|
|
|
rule = f'%{group} ALL=(ALL:ALL) ALL\n'
|
|
try:
|
|
if not SUDOERS.is_file() or SUDOERS.read_text(encoding='utf-8') != rule:
|
|
staged = SUDOERS.with_name('.linux-manager.new')
|
|
staged.write_text(rule, encoding='utf-8')
|
|
staged.chmod(0o440)
|
|
checked = run(['visudo', '-cf', str(staged)], check=False)
|
|
if checked.returncode != 0:
|
|
staged.unlink()
|
|
return f'the sudo rule of {group} is refused: {checked.stdout.strip()} {checked.stderr.strip()}'
|
|
staged.replace(SUDOERS)
|
|
|
|
uri = 'ldapi://' + linuxmanager_ldap.SLAPD_SOCKET.replace('/', '%2f') + '/'
|
|
nslcd = '\n'.join([
|
|
'uid nslcd',
|
|
'gid nslcd',
|
|
f'uri {uri}',
|
|
f'base {linuxmanager_ldap.BASE}',
|
|
'filter passwd (&(objectClass=posixAccount)(linuxManagerConsoleLogin=TRUE))',
|
|
f'nss_min_uid {linuxmanager_ldap.CONSOLE_UID_MIN}',
|
|
'pam_authz_search (&(objectClass=posixAccount)(objectClass=oathTOTPUser)(uid=$username)(linuxManagerConsoleLogin=TRUE))',
|
|
'pam_password_prohibit_message The password is changed in the Manager or with linux-manager-user.',
|
|
'',
|
|
])
|
|
if write_if_changed(NSLCD_CONF, nslcd, 0o640) or not unit_is_active('nslcd'):
|
|
os.chown(NSLCD_CONF, 0, grp.getgrnam('nslcd').gr_gid)
|
|
run(['systemctl', 'enable', 'nslcd'], check=False)
|
|
run(['systemctl', 'restart', 'nslcd'], check=False)
|
|
|
|
lines = NSSWITCH.read_text(encoding='utf-8').splitlines(keepends=True)
|
|
switched = [line.rstrip('\n') + ' ldap\n' if line.startswith('passwd:') and 'ldap' not in line.split() else line
|
|
for line in lines]
|
|
if switched != lines:
|
|
NSSWITCH.write_text(''.join(switched), encoding='utf-8')
|
|
# A running process keeps the name service switch it read first, so the web service's shell would not find
|
|
# the console accounts of the directory until it restarts.
|
|
run(['systemctl', 'try-restart', 'linux-manager-web.service'], check=False)
|
|
|
|
if 'pam_mkhomedir' not in PAM_SESSION.read_text(encoding='utf-8'):
|
|
run(['pam-auth-update', '--enable', 'mkhomedir'], check=False)
|
|
|
|
if cfg['ssh']['ldap_login']:
|
|
changed = write_if_changed(SSHD_DROPIN, f'Match Group {group}\n PasswordAuthentication yes\n')
|
|
else:
|
|
changed = SSHD_DROPIN.exists()
|
|
SSHD_DROPIN.unlink(missing_ok=True)
|
|
if changed:
|
|
checked = run(['sshd', '-t'], check=False)
|
|
if checked.returncode != 0:
|
|
SSHD_DROPIN.unlink(missing_ok=True)
|
|
return f'sshd refuses {SSHD_DROPIN}: {checked.stderr.strip()}'
|
|
if unit_is_active('ssh'):
|
|
run(['systemctl', 'reload', 'ssh'], check=False)
|
|
except (OSError, KeyError) as exc:
|
|
return f'console login cannot be set up: {exc}'
|
|
return ''
|
|
|
|
|
|
def manage_openvpn(ctx, changed):
|
|
"""Run the OpenVPN server when it is configured, and stop it when it is not."""
|
|
unit = 'openvpn-server@linux-manager'
|
|
|
|
if not linuxmanager.openvpn_ready(ctx):
|
|
if unit_is_active(unit):
|
|
run(['systemctl', 'disable', '--now', unit], check=False)
|
|
return
|
|
|
|
if not unit_is_active(unit):
|
|
run(['systemctl', 'enable', '--now', unit], check=False)
|
|
elif 'openvpn' in changed or 'swanctl' in changed:
|
|
run(['systemctl', 'restart', unit], check=False)
|
|
|
|
|
|
def caddy_address(host, port, tls):
|
|
"""The address of a site block of the Caddyfile: the host, an IPv6 address in brackets, and the port, with http://
|
|
for a plain HTTP site; no host answers any name."""
|
|
host = f'[{host}]' if ':' in host else host
|
|
return f'{"http://" if tls == "none" else ""}{host}:{port}'
|
|
|
|
|
|
def manage_mdns(ctx):
|
|
"""Run Avahi, which announces <host name>.local, one of the HTTPS names, with mDNS, while wan.local_fqdn is not set,
|
|
and stop it while it is."""
|
|
active = unit_is_active(AVAHI_UNITS[1])
|
|
if ctx['mdns'] and not active:
|
|
run(['systemctl', 'enable', '--now', *AVAHI_UNITS], check=False)
|
|
elif not ctx['mdns'] and active:
|
|
run(['systemctl', 'disable', '--now', *AVAHI_UNITS], check=False)
|
|
|
|
|
|
def manage_resolver(changed):
|
|
"""Run dnsmasq, the resolver of the remote access clients, while configure wrote its configuration, restarting it when
|
|
that changed, and stop it when not. It starts after systemd-resolved has left the addresses it takes."""
|
|
if not linuxmanager.RESOLVER_CONF.exists():
|
|
if unit_is_active(RESOLVER_UNIT):
|
|
run(['systemctl', 'disable', '--now', RESOLVER_UNIT], check=False)
|
|
return
|
|
if not unit_is_active(RESOLVER_UNIT):
|
|
run(['systemctl', 'enable', '--now', RESOLVER_UNIT], check=False)
|
|
elif 'resolver' in changed:
|
|
run(['systemctl', 'restart', RESOLVER_UNIT], check=False)
|
|
|
|
|
|
def manage_caddy(cfg, ctx):
|
|
"""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.
|
|
|
|
CADDYFILE serves over plain HTTP the web service on web.port while it is enabled and the manager on its port, and
|
|
while metrics are enabled the metrics service on metrics.port. While https.disable_auto_redirect is off, a request
|
|
of the web service for an HTTPS host is redirected (308) to https.web_port, and every request of the manager to
|
|
https.manager_port, on the host it named when that is an HTTPS host, else on the first HTTPS name. 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 the HTTPS hosts: the HTTPS names
|
|
(linuxmanager.https_names) and, with https.ip_sans and a certificate of its own, the addresses its certificate
|
|
names; a client without SNI gets the certificate of the first HTTPS name. 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 web.port, the Manager's port, https.web_port
|
|
and https.manager_port, ahead of the redirect to HTTPS, 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.
|
|
"""
|
|
sites = ctx['sites']
|
|
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():
|
|
run(['systemctl', 'enable', '--now', CADDY_UNIT], check=False)
|
|
return
|
|
try:
|
|
group = grp.getgrnam(CADDY_GROUP).gr_gid
|
|
except KeyError:
|
|
fail(f'the group {CADDY_GROUP} does not exist; is the caddy package installed?')
|
|
https = True
|
|
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:
|
|
credentials = {name: linuxmanager_pki.authority_files(name) for name in wanted}
|
|
except ldap.LDAPError as exc:
|
|
warn(f'the ACME servers and the sites of issuing CAs are left out: the PKI cannot be read: {exc}')
|
|
credentials = {}
|
|
authorities = [name for name, files in credentials.items() if files is not None]
|
|
for site in sites:
|
|
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]
|
|
for folder in (CADDY_PKI_DIR.iterdir() if CADDY_PKI_DIR.is_dir() else []):
|
|
if folder.name not in authorities:
|
|
shutil.rmtree(folder)
|
|
for name in authorities:
|
|
folder = CADDY_PKI_DIR / name
|
|
for path in (CADDY_PKI_DIR, folder):
|
|
path.mkdir(mode=0o750, exist_ok=True)
|
|
os.chown(path, 0, group)
|
|
for file, data in zip(('cert.pem', 'key.pem'), credentials[name]):
|
|
copied |= linuxmanager_pki.write(folder / file, data, 0o640)
|
|
os.chown(folder / file, 0, group)
|
|
files = {site['name']: site for site in sites if site['tls'] == 'file'}
|
|
for folder in (CADDY_SITES_DIR.iterdir() if CADDY_SITES_DIR.is_dir() else []):
|
|
if folder.name not in files:
|
|
shutil.rmtree(folder)
|
|
for name, site in files.items():
|
|
folder = CADDY_SITES_DIR / name
|
|
for path in (CADDY_SITES_DIR, folder):
|
|
path.mkdir(mode=0o750, exist_ok=True)
|
|
os.chown(path, 0, group)
|
|
for file, data in (('cert.pem', site['certificate']), ('key.pem', site['private_key'])):
|
|
copied |= linuxmanager_pki.write(folder / file, data.strip().encode() + b'\n', 0o640)
|
|
os.chown(folder / file, 0, group)
|
|
linuxmanager_sites.ensure_folders(site['name'] for site in sites)
|
|
names = linuxmanager.issuing_cas(cfg)
|
|
hosts = [*ctx['https_names'], *(ctx['https_ips'] if own is not None else [])]
|
|
caddy_ctx = dict(ctx, https=https, manager_port=linuxmanager.manager_port(),
|
|
redirect=https and not cfg['https']['disable_auto_redirect'],
|
|
https_name=ctx['https_names'][0],
|
|
https_hosts=[f'[{host}]' if ':' in host else host for host in hosts],
|
|
redirect_hosts=[host for host in hosts if ':' not in host],
|
|
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=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']]
|
|
or [caddy_address('', site['port'], site['tls'])],
|
|
'cert': str(CADDY_SITES_DIR / site['name'] / 'cert.pem'),
|
|
'key': str(CADDY_SITES_DIR / site['name'] / 'key.pem')} for site in sites])
|
|
changed = linuxmanager.render(linuxmanager._jinja_env(), caddy_ctx, 'Caddyfile.j2', CADDYFILE, 0o640)
|
|
os.chown(CADDYFILE, 0, group)
|
|
if not unit_is_active(CADDY_UNIT):
|
|
run(['systemctl', 'enable', '--now', CADDY_UNIT], check=False)
|
|
elif changed or copied:
|
|
run(['systemctl', 'reload', CADDY_UNIT], check=False)
|
|
|
|
|
|
def install_packages(feature):
|
|
"""Start the installation of the packages of a feature by INSTALL_UNIT, which runs setup again, and say so."""
|
|
unit = INSTALL_UNIT.format(feature)
|
|
run(['systemctl', 'start', '--no-block', unit], check=False)
|
|
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 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:
|
|
return
|
|
linuxmanager_sites.ensure_folders([])
|
|
run(['systemctl', 'enable', '--now', WEBDAV_UNIT], check=False)
|
|
|
|
|
|
def site_addresses(cfg, ctx):
|
|
"""The pairs of a host name and the server's address of dns_address of each enabled site with dns router: public,
|
|
wan.public_address; internal, the internal interface's; external, the external interface's first. A site whose
|
|
address is not known gets none, with a warning."""
|
|
addresses = {'public': cfg['wan']['public_address'].strip(), 'internal': ctx['int_addr'],
|
|
'external': next(iter(ctx['local_addr_list']), '')}
|
|
pairs = []
|
|
for site in ctx['sites']:
|
|
if site['dns'] != 'router':
|
|
continue
|
|
address = addresses[site['dns_address']]
|
|
if not address:
|
|
warn(f'site {site["name"]}: the server has no {site["dns_address"]} address, so its host names get no '
|
|
'records')
|
|
continue
|
|
pairs += [(host, address) for host in site['hosts']]
|
|
return pairs
|
|
|
|
|
|
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 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
|
|
of the enabled sites with dns router get records of the server's address they choose (site_addresses), and the
|
|
domains keep those they have while the sites cannot be read.
|
|
"""
|
|
if not linuxmanager.dns_ready(ctx):
|
|
if unit_is_active(linuxmanager_dns.UNIT):
|
|
run(['systemctl', 'disable', '--now', linuxmanager_dns.UNIT], check=False)
|
|
linuxmanager.remove(linuxmanager_dns.PDNS_CONF)
|
|
if linuxmanager_dns.DATABASE_SECRET.is_file():
|
|
try:
|
|
linuxmanager_dns.apply(cfg, [])
|
|
except linuxmanager_dns.DatabaseError as exc:
|
|
warn(str(exc))
|
|
return
|
|
addresses = {'internal': [ctx['int_addr']], 'external': ctx['local_addr_list'],
|
|
'both': [ctx['int_addr'], *ctx['local_addr_list']]}[ctx['dns_listen']]
|
|
addresses = [address for address in addresses if address]
|
|
if not addresses:
|
|
warn(f'the name server does not run: the interfaces of dns.listen {ctx["dns_listen"]} have no address')
|
|
return
|
|
try:
|
|
linuxmanager_auth.provision_database(linuxmanager_dns.DATABASE, linuxmanager_dns.DATABASE_SECRET)
|
|
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():
|
|
return
|
|
os.chown(linuxmanager_dns.PDNS_CONF, 0, grp.getgrnam(linuxmanager_dns.GROUP).gr_gid)
|
|
linuxmanager_dns.provision()
|
|
if ctx['sites'] is not None:
|
|
linuxmanager_dns.apply(cfg, site_addresses(cfg, ctx))
|
|
except (OSError, KeyError, linuxmanager_dns.DatabaseError) as exc:
|
|
warn(f'the name server cannot be set up: {exc}')
|
|
return
|
|
if not unit_is_active(linuxmanager_dns.UNIT):
|
|
run(['systemctl', 'enable', '--now', linuxmanager_dns.UNIT], check=False)
|
|
elif changed:
|
|
run(['systemctl', 'restart', linuxmanager_dns.UNIT], check=False)
|
|
|
|
|
|
def manage_metrics(ctx):
|
|
"""Run the metrics service while metrics are enabled, and stop it when not.
|
|
|
|
The service reads its settings itself, so it is restarted only to run the code of a new package version, which
|
|
every run of setup after an upgrade does.
|
|
"""
|
|
unit = 'linux-manager-metrics.service'
|
|
if not linuxmanager.metrics_ready(ctx):
|
|
run(['systemctl', 'disable', '--now', unit], check=False)
|
|
return
|
|
run(['systemctl', 'enable', unit], check=False)
|
|
run(['systemctl', 'restart', unit], check=False)
|
|
|
|
|
|
def manage_backup(cfg):
|
|
"""Run the backup timer on backup.schedule while backups are enabled, and stop it when not.
|
|
|
|
The schedule is a drop-in of the timer, BACKUP_SCHEDULE, which replaces the OnCalendar of the shipped unit.
|
|
"""
|
|
unit = 'linux-manager-backup.timer'
|
|
if not cfg['backup']['enabled']:
|
|
run(['systemctl', 'disable', '--now', unit], check=False)
|
|
if BACKUP_SCHEDULE.exists():
|
|
BACKUP_SCHEDULE.unlink()
|
|
run(['systemctl', 'daemon-reload'], check=False)
|
|
return
|
|
text = f'[Timer]\nOnCalendar=\nOnCalendar={cfg["backup"]["schedule"]}\n'
|
|
if not BACKUP_SCHEDULE.exists() or BACKUP_SCHEDULE.read_text(encoding='utf-8') != text:
|
|
BACKUP_SCHEDULE.parent.mkdir(parents=True, exist_ok=True)
|
|
BACKUP_SCHEDULE.write_text(text, encoding='utf-8')
|
|
run(['systemctl', 'daemon-reload'], check=False)
|
|
run(['systemctl', 'restart', unit], check=False)
|
|
run(['systemctl', 'enable', '--now', unit], check=False)
|
|
|
|
|
|
def run_platform_setup(cfg, ctx):
|
|
"""Let the platform module apply its own state, if it defines any."""
|
|
module = linuxmanager.platform_module(cfg)
|
|
apply = getattr(module, 'apply', None)
|
|
if apply is None:
|
|
return
|
|
try:
|
|
apply(ctx)
|
|
except Exception as exc:
|
|
fail(f'platform module {module.__name__} failed: {exc}')
|
|
|
|
|
|
def refresh_docker_rules():
|
|
"""Apply the new settings to the Docker rules while Docker is running.
|
|
|
|
When Docker is not running, linux-manager-docker applies them after
|
|
docker.service starts. The restart is waited for, so the rules are in place
|
|
when this setup ends; linux-manager-docker is therefore not ordered after
|
|
linux-manager-setup.
|
|
"""
|
|
if unit_is_active('docker.service'):
|
|
run(['systemctl', 'restart', 'linux-manager-docker.service'], check=False)
|
|
|
|
|
|
def refresh_web(cfg, ctx):
|
|
"""Hand the web service the features and facts it shows.
|
|
|
|
The service reads the file at each request: the features of the server,
|
|
the configuration without its secret options and the facts resolved from
|
|
the system, which it cannot work out with the standard library alone. The
|
|
file is readable by root only. The service follows a changed address or
|
|
port itself. Secret options are left out at every level, so also from each
|
|
site-to-site connection.
|
|
"""
|
|
def public(options):
|
|
return {option: public(value) if isinstance(value, dict) else value
|
|
for option, value in options.items()
|
|
if isinstance(value, dict) or not SECRET_OPTION.search(option)}
|
|
|
|
WEB_STATE.parent.mkdir(parents=True, exist_ok=True)
|
|
WEB_STATE.touch(mode=0o600)
|
|
WEB_STATE.chmod(0o600)
|
|
WEB_STATE.write_text(json.dumps({
|
|
'router': bool(ctx['router_enabled']),
|
|
'vpn': bool(ctx['vpn_enabled']),
|
|
'site_to_site': [connection['name'] for connection in ctx['connections'] if connection['ready']],
|
|
'p2s': bool(linuxmanager.p2s_ready(ctx)),
|
|
'wireguard': bool(linuxmanager.wg_ready(ctx)),
|
|
'openvpn': bool(linuxmanager.openvpn_ready(ctx)),
|
|
'configuration': public(cfg),
|
|
'network': {
|
|
'external_interface': ctx['wan_iface'],
|
|
'internal_interface': ctx['int_iface'],
|
|
'external_addresses': ctx['local_addr_list'],
|
|
'internal_address': ctx['int_addr'],
|
|
'internal_gateway': ctx['int_gateway_ip'],
|
|
'https_names': ctx['https_names'],
|
|
'https_addresses': ctx['https_ips'],
|
|
'local_cidrs': ctx['local_cidr_list'],
|
|
'client_dns': ctx['p2s_resolver_addrs'] if linuxmanager.RESOLVER_CONF.exists() else [],
|
|
'site_to_site': [{
|
|
'name': connection['name'],
|
|
'local_identity': connection['local_id'],
|
|
'remote_identity': connection['remote_id'],
|
|
'local_cidrs': connection['local_cidr_list'],
|
|
'remote_cidrs': connection['remote_cidr_list'],
|
|
} for connection in ctx['connections']],
|
|
},
|
|
}) + '\n', encoding='utf-8')
|
|
|
|
|
|
def progress(state, step, error=None):
|
|
"""Record where setup is in SETUP_STATE: running, deferred, done or failed, the step, and the error of a failure."""
|
|
SETUP_STATE.parent.mkdir(parents=True, exist_ok=True)
|
|
SETUP_STATE.write_text(json.dumps({
|
|
'state': state,
|
|
'step': step,
|
|
'error': error,
|
|
'time': time.strftime('%Y-%m-%dT%H:%M:%S%z'),
|
|
}) + '\n', encoding='utf-8')
|
|
|
|
|
|
def start_bootstrap():
|
|
"""Start the bootstrap service while no run has succeeded."""
|
|
if not SETUP_DONE.exists():
|
|
for unit in BOOTSTRAP_UNITS:
|
|
run(['systemctl', 'start', '--no-block', unit], check=False)
|
|
|
|
|
|
def end_bootstrap(ctx):
|
|
"""After the first successful run: write SETUP_DONE, close the bootstrap ports and stop the bootstrap service."""
|
|
if SETUP_DONE.exists():
|
|
return
|
|
SETUP_DONE.parent.mkdir(parents=True, exist_ok=True)
|
|
SETUP_DONE.touch()
|
|
if setup_ufw(ctx):
|
|
run(['ufw', 'reload'], check=False)
|
|
for unit in BOOTSTRAP_UNITS:
|
|
run(['systemctl', 'stop', unit], check=False)
|
|
|
|
|
|
def main():
|
|
start_bootstrap()
|
|
progress('running', 'configuration')
|
|
cfg = linuxmanager.load_config()
|
|
if linuxmanager.deferred(cfg):
|
|
print('linux-manager: platform is none, configuration deferred; '
|
|
f'set general.platform in {linuxmanager.CONFIG_FILE}')
|
|
progress('deferred', 'configuration', f'general.platform is none; set it in {linuxmanager.CONFIG_FILE}')
|
|
return 0
|
|
# Until a run has succeeded, a file that names no HTTPS certificate source leaves the choice to this run.
|
|
if not SETUP_DONE.exists() and not linuxmanager.read_settings().get('https', {}).get('certificate'):
|
|
cfg['https']['certificate'] = ''
|
|
|
|
# The directory holds the PKI, which the configuration needs; its problem ends setup only after every other step.
|
|
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)
|
|
|
|
progress('running', 'kernel settings')
|
|
manage_sysctl(ctx)
|
|
|
|
progress('running', 'routes')
|
|
if linuxmanager.routing_ready(ctx):
|
|
apply_routes(ctx)
|
|
|
|
if ctx['local_fqdn'] and any(connection['local_id_mode'] == 'public_ip' for connection in ctx['connections']):
|
|
progress('running', 'public address')
|
|
address = resolve_public_ip(ctx['local_fqdn'])
|
|
ctx, more = linuxmanager.configure(cfg, public_ip=address)
|
|
changed |= more
|
|
|
|
# The enabled sites while sites are on, None while they cannot be read.
|
|
ctx['sites'] = []
|
|
if cfg['sites']['enabled']:
|
|
progress('running', 'web sites')
|
|
try:
|
|
ctx['sites'] = linuxmanager_sites.served()
|
|
except linuxmanager_sites.DatabaseError as exc:
|
|
warn(str(exc))
|
|
ctx['sites'] = None
|
|
|
|
progress('running', 'WireGuard keys')
|
|
setup_wireguard(ctx)
|
|
|
|
progress('running', 'firewall')
|
|
rules_changed = setup_ufw(ctx)
|
|
status = run(['ufw', 'status'], check=False)
|
|
if not status.stdout.startswith('Status: active'):
|
|
# Only ever enable the firewall after making sure SSH survives it.
|
|
run(['ufw', 'allow', '22/tcp'], check=False)
|
|
run(['ufw', '--force', 'enable'])
|
|
elif rules_changed:
|
|
run(['ufw', 'reload'])
|
|
|
|
progress('running', 'strongSwan')
|
|
manage_strongswan(ctx, changed)
|
|
progress('running', 'WireGuard')
|
|
manage_wireguard(ctx, changed)
|
|
|
|
if not problem:
|
|
failed_step = 'Ubuntu Linux Manager admin'
|
|
progress('running', failed_step)
|
|
problem = manage_admin()
|
|
if not problem:
|
|
failed_step = 'metrics service account'
|
|
progress('running', failed_step)
|
|
problem = manage_metrics_account(ctx)
|
|
if not problem:
|
|
failed_step = 'console login'
|
|
progress('running', failed_step)
|
|
problem = manage_console(cfg)
|
|
progress('running', 'OpenVPN')
|
|
manage_openvpn(ctx, changed)
|
|
progress('running', 'HTTPS proxy')
|
|
manage_caddy(cfg, ctx)
|
|
progress('running', 'mDNS')
|
|
manage_mdns(ctx)
|
|
progress('running', 'WebDAV')
|
|
manage_webdav(ctx)
|
|
progress('running', 'name server')
|
|
manage_dns(cfg, ctx)
|
|
progress('running', 'PKI timer')
|
|
run(['systemctl', 'enable', '--now', PKI_TIMER], check=False)
|
|
|
|
if 'resolved' in changed:
|
|
progress('running', 'resolver')
|
|
run(['systemctl', 'restart', 'systemd-resolved'], check=False)
|
|
progress('running', 'resolver of the remote access clients')
|
|
manage_resolver(changed)
|
|
|
|
progress('running', 'platform module')
|
|
run_platform_setup(cfg, ctx)
|
|
progress('running', 'Docker rules')
|
|
refresh_docker_rules()
|
|
progress('running', 'web service state')
|
|
refresh_web(cfg, ctx)
|
|
progress('running', 'metrics service')
|
|
manage_metrics(ctx)
|
|
progress('running', 'backup timer')
|
|
manage_backup(cfg)
|
|
if problem:
|
|
progress('failed', failed_step, problem)
|
|
print(f'linux-manager: error: {problem}', file=sys.stderr)
|
|
return 1
|
|
progress('done', 'done')
|
|
end_bootstrap(ctx)
|
|
return 0
|
|
|
|
|
|
def record_failure(error):
|
|
"""Mark the run failed in the step SETUP_STATE holds."""
|
|
try:
|
|
step = json.loads(SETUP_STATE.read_text(encoding='utf-8')).get('step')
|
|
except (OSError, ValueError):
|
|
step = None
|
|
progress('failed', step, error)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
# 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)
|