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
Release / release (push) Failing after 8s
This commit is contained in:
1 parent
a649331aa2
commit
a7bfabcb89
97 files changed
+4498
-1834
No files matched your search
@@ -7,8 +7,8 @@ this script never writes to /etc and never has to worry about destroying an
|
||||
administrator's edits.
|
||||
|
||||
The candidate is the current /etc/linux-manager/linux-manager.json as it is, or the
|
||||
shipped defaults when there is none, with every debconf answer that was given
|
||||
written over it. Without an answer that changes it, the candidate is the current
|
||||
shipped defaults when there is none, with https.certificate empty for the first
|
||||
setup to choose, with every debconf answer that was given written over it. Without an answer that changes it, the candidate is the current
|
||||
file byte for byte, so
|
||||
an upgrade or a reconfiguration that changes nothing gives ucf nothing to ask;
|
||||
defaults the file leaves out are applied by linuxmanager.load_config() when the
|
||||
@@ -43,6 +43,8 @@ ANSWERS = {
|
||||
'LINUX_MANAGER_EXTERNAL_INTERFACE': (('interfaces', 'external'),),
|
||||
'LINUX_MANAGER_INTERNAL_INTERFACE': (('interfaces', 'internal'),),
|
||||
'LINUX_MANAGER_LOCAL_FQDN': (('wan', 'local_fqdn'),),
|
||||
'LINUX_MANAGER_HTTPS_ENABLED': (('https', 'enabled'),),
|
||||
'LINUX_MANAGER_HTTPS_DISABLE_AUTO_REDIRECT': (('https', 'disable_auto_redirect'),),
|
||||
'LINUX_MANAGER_LOCAL_ID_MODE': ((*FIRST, 'local_id_mode'),),
|
||||
'LINUX_MANAGER_LOCAL_CIDRS': (('local', 'cidrs'), (*FIRST, 'local_cidrs')),
|
||||
'LINUX_MANAGER_INT_GATEWAY_IP': (('local', 'int_gateway_ip'),),
|
||||
@@ -73,6 +75,8 @@ def main():
|
||||
current = None
|
||||
if current is None:
|
||||
cfg = linuxmanager.load_config()
|
||||
# A new installation leaves the source of the HTTPS certificate to its first setup.
|
||||
cfg['https']['certificate'] = ''
|
||||
else:
|
||||
try:
|
||||
cfg = json.loads(current)
|
||||
|
||||
@@ -1,19 +1,31 @@
|
||||
#!/usr/bin/python3
|
||||
"""Install the packages of a feature from the Ubuntu archive, then restart linux-manager-setup without waiting.
|
||||
"""Install the packages of a component from the Ubuntu archive, then have linux-manager-setup run without waiting.
|
||||
|
||||
Run by linux-manager-install@<feature>.service, which linux-manager-setup starts when the feature is on and its packages are
|
||||
missing: webdav (rclone) and dns (PowerDNS with its gpgsql backend). Recommended packages are left out, so PowerDNS
|
||||
comes without its bind backend. A failure is a message on standard error and the exit status 1.
|
||||
Run by linux-manager-install@<component>.service, which linux-manager-setup starts when the component is on and its
|
||||
packages are missing or marked as installed automatically: the components and their packages are
|
||||
linuxmanager.COMPONENTS, the VPN, the router, the name server (PowerDNS with its gpgsql backend) and WebDAV (rclone).
|
||||
Recommended packages are left out, so PowerDNS comes without its bind backend. apt-get marks the packages as installed
|
||||
by hand. Installations of several components run one after another (INSTALL_LOCK), as apt locks its package lists.
|
||||
A run of setup in progress, the one that started the installation, runs again when it ends (request_setup). A failure
|
||||
is a message on standard error and the exit status 1.
|
||||
|
||||
install-packages FEATURE
|
||||
install-packages COMPONENT
|
||||
"""
|
||||
|
||||
import fcntl
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
#: The packages of each feature.
|
||||
FEATURES = {'webdav': ['rclone'], 'dns': ['pdns-server', 'pdns-backend-pgsql']}
|
||||
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
|
||||
|
||||
import linuxmanager # noqa: E402
|
||||
|
||||
#: The packages of each component.
|
||||
FEATURES = {name: packages for name, (_, packages) in linuxmanager.COMPONENTS.items()}
|
||||
|
||||
#: The lock that has the installations of several components run one after another.
|
||||
INSTALL_LOCK = '/run/linux-manager-install.lock'
|
||||
|
||||
#: apt-get, waiting up to ten minutes for dpkg's lock, which a package installation that runs setup holds.
|
||||
APT = ['apt-get', '-o', 'DPkg::Lock::Timeout=600']
|
||||
@@ -23,12 +35,15 @@ def main():
|
||||
if len(sys.argv) != 2 or sys.argv[1] not in FEATURES:
|
||||
sys.exit(f'usage: install-packages {"|".join(FEATURES)}')
|
||||
environment = dict(os.environ, DEBIAN_FRONTEND='noninteractive')
|
||||
lock = open(INSTALL_LOCK, 'w', encoding='utf-8')
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
for args in ([*APT, 'update'], [*APT, '-y', '--no-install-recommends', '-o', 'Dpkg::Options::=--force-confdef',
|
||||
'-o', 'Dpkg::Options::=--force-confold', 'install', *FEATURES[sys.argv[1]]]):
|
||||
print(f'$ {" ".join(args)}', flush=True)
|
||||
if subprocess.run(args, env=environment).returncode != 0:
|
||||
sys.exit(f'install-packages: {args[0]} failed')
|
||||
subprocess.run(['systemctl', 'restart', '--no-block', 'linux-manager-setup.service'])
|
||||
lock.close()
|
||||
linuxmanager.request_setup()
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -12,8 +12,10 @@ import os
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
import jinja2
|
||||
@@ -27,12 +29,21 @@ import linuxmanager_ldap
|
||||
import linuxmanager_pki
|
||||
import linuxmanager_platforms
|
||||
import linuxmanager_status
|
||||
from linuxmanager_net import DEFAULT_LISTEN, LISTEN_CHOICES, LOOPBACK, ConfigError, detect_interfaces, interface_addresses, ip_output
|
||||
from linuxmanager_net import DEFAULT_LISTEN, LISTEN_CHOICES, LOOPBACK, MANAGER_LOOPBACK_PORT, METRICS_LOOPBACK_PORT, \
|
||||
WEB_LOOPBACK_PORT, ConfigError, detect_interfaces, interface_addresses, ip_output
|
||||
|
||||
CONFIG_FILE = pathlib.Path('/etc/linux-manager/linux-manager.json')
|
||||
CONFIG_LOCK = pathlib.Path('/run/linux-manager/config.lock')
|
||||
#: What setup resolved and runs, for the web service (setup's refresh_web).
|
||||
WEB_STATE = pathlib.Path('/run/linux-manager/web.json')
|
||||
#: The unit of linux-manager-setup, which request_setup runs.
|
||||
SETUP_UNIT = 'linux-manager-setup.service'
|
||||
#: The lock under which a run of setup is requested and a run of setup decides whether to run again.
|
||||
SETUP_LOCK = pathlib.Path('/run/linux-manager/setup.lock')
|
||||
#: The lock a run of setup holds while it applies the configuration.
|
||||
SETUP_RUNNING = pathlib.Path('/run/linux-manager/setup.running')
|
||||
#: The file that asks a run of setup in progress to run once more when it ends.
|
||||
SETUP_REQUEST = pathlib.Path('/run/linux-manager/setup.request')
|
||||
TEMPLATE_DIR = pathlib.Path('/usr/share/linux-manager/templates')
|
||||
|
||||
SWANCTL_CONF_D = pathlib.Path('/etc/swanctl/conf.d')
|
||||
@@ -68,14 +79,17 @@ SCHEMA = {
|
||||
'status_content': 'basic', 'shell': False, 'shell_idle_minutes': 15, 'shell_auth_timeout': 15,
|
||||
'log_files': []},
|
||||
'ssh': {'ldap_login': False},
|
||||
'https': {'enabled': True, 'email': '', 'web_port': 7444, 'manager_port': 7443, 'caddy_source': 'ubuntu',
|
||||
'acme_staging': False},
|
||||
'https': {'enabled': True, 'email': '', 'web_port': 7444, 'manager_port': 7443,
|
||||
'disable_auto_redirect': False, 'acme_staging': False, 'certificate': 'self-signed', 'self_signed_days': 365,
|
||||
'acme_provider': 'letsencrypt', 'acme_url': '', 'acme_eab_key_id': '', 'acme_eab_mac_key': '',
|
||||
'zerossl_api_key': ''},
|
||||
'oidc': {'enabled': False},
|
||||
'sites': {'enabled': False, 'upload_max_mb': 512, 'webdav': False, 'webdav_port': 7445},
|
||||
'dns': {'enabled': False, 'secondary': '', 'listen': 'external', 'ttl': 300},
|
||||
'pki': {'root_name': 'Linux Manager Root CA', 'root_days': 7300, 'ca_days': 3650, 'key': 'rsa-4096',
|
||||
'crl_days': 7, 'root_crl_days': 180, 'publish': ['http'], 'p2s_name': 'Linux Manager VPN CA',
|
||||
's2s_name': 'Linux Manager Site-to-Site CA', 'issuing_cas': {}, 'templates': {},
|
||||
's2s_name': 'Linux Manager Site-to-Site CA', 'servers_name': 'Linux Manager Servers CA',
|
||||
'issuing_cas': {}, 'templates': {},
|
||||
'extended_key_usages': {}, 'root': 'local', 'simple_ca_url': ''},
|
||||
'metrics': {'enabled': True, 'listen': 'internal', 'port': 9464, 'https_port': 9465, 'service_account': 'metrics',
|
||||
'otlp_endpoint': '', 'otlp_username': '', 'otlp_password': '',
|
||||
@@ -143,6 +157,16 @@ LOG_FILES_MAX = 32
|
||||
#: The port rclone serves WebDAV on, on the loopback address, behind Caddy.
|
||||
WEBDAV_LOOPBACK_PORT = 7446
|
||||
|
||||
#: The installable components, managed on the Manager's System tab: name -> (section, setting) of their switch and the
|
||||
#: packages linux-manager-install@<name> installs from the Ubuntu archive while the switch is on.
|
||||
STRONGSWAN_PACKAGES = ('strongswan-swanctl', 'charon-systemd', 'libstrongswan-extra-plugins', 'libcharon-extra-plugins')
|
||||
COMPONENTS = {
|
||||
'vpn': (('vpn', 'enabled'), (*STRONGSWAN_PACKAGES, 'openvpn', 'openvpn-auth-ldap', 'wireguard-tools', 'dnsmasq-base')),
|
||||
'router': (('router', 'enabled'), STRONGSWAN_PACKAGES),
|
||||
'dns': (('dns', 'enabled'), ('pdns-server', 'pdns-backend-pgsql')),
|
||||
'webdav': (('sites', 'webdav'), ('rclone',)),
|
||||
}
|
||||
|
||||
#: The largest sites.upload_max_mb, 10 GiB.
|
||||
UPLOAD_MAX_MB = 10240
|
||||
|
||||
@@ -167,17 +191,20 @@ BOOTSTRAP_PORTS = (17081,)
|
||||
MANAGER_CONFIG = pathlib.Path('/etc/linux-manager/manager.json')
|
||||
MANAGER_PORT = 7080
|
||||
|
||||
#: Where linux-manager-setup installs Caddy from, https.caddy_source: the Ubuntu archive or Caddy's own repository.
|
||||
CADDY_SOURCES = ('ubuntu', 'upstream')
|
||||
|
||||
#: The ACME directory of Let's Encrypt's staging environment, Caddy's only CA while https.acme_staging is true.
|
||||
ACME_STAGING_CA = 'https://acme-staging-v02.api.letsencrypt.org/directory'
|
||||
|
||||
#: Caddy's own repository, which https.caddy_source upstream configures: the source, its signing key and their URLs.
|
||||
CADDY_APT_SOURCE = pathlib.Path('/etc/apt/sources.list.d/caddy-stable.sources')
|
||||
CADDY_KEYRING = pathlib.Path('/etc/apt/keyrings/caddy-stable.asc')
|
||||
CADDY_KEY_URL = 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key'
|
||||
CADDY_REPOSITORY = 'https://dl.cloudsmith.io/public/caddy/stable/deb/debian'
|
||||
#: The ACME directory of Let's Encrypt's production CA.
|
||||
ACME_PRODUCTION_CA = 'https://acme-v02.api.letsencrypt.org/directory'
|
||||
|
||||
#: Where the certificate of wan.local_fqdn comes from, https.certificate: ACME, a self-signed certificate, the
|
||||
#: Servers Issuing CA (servers), or a certificate of another CA, imported; self-signed when not set. A new installation's
|
||||
#: configuration file has it empty (generate-config) until the first setup chooses ca or self-signed
|
||||
#: (linuxmanager_pki.provision).
|
||||
HTTPS_CERTIFICATES = ('acme', 'self-signed', 'ca', 'external')
|
||||
|
||||
#: The ACME CA of the server and of the web sites with TLS acme, https.acme_provider.
|
||||
ACME_PROVIDERS = ('letsencrypt', 'zerossl', 'custom')
|
||||
|
||||
#: The key types of the CAs, pki.key, and of the templates.
|
||||
PKI_KEYS = ('rsa-2048', 'rsa-3072', 'rsa-4096', 'ec-p256', 'ec-p384')
|
||||
@@ -224,7 +251,7 @@ PKI_TEMPLATES = {
|
||||
'vpn-server': {'key_usage': ['digital_signature', 'key_encipherment'],
|
||||
'extended_key_usage': ['server_auth', 'ike_intermediate'], 'subject': 'dns', 'sans': ['dns', 'ip']},
|
||||
'vpn-user': {'extended_key_usage': ['client_auth'], 'subject': 'name', 'sans': ['dns', 'email']},
|
||||
'site-to-site': {'key_usage': ['digital_signature', 'key_encipherment'],
|
||||
'mtls': {'key_usage': ['digital_signature', 'key_encipherment'],
|
||||
'extended_key_usage': ['server_auth', 'client_auth'], 'subject': 'dns', 'sans': ['dns', 'ip']},
|
||||
'server': {'key_usage': ['digital_signature', 'key_encipherment'], 'extended_key_usage': ['server_auth'],
|
||||
'subject': 'dns', 'sans': ['dns', 'ip']},
|
||||
@@ -234,8 +261,11 @@ PKI_TEMPLATES = {
|
||||
#: The templates only the server issues: its VPN server certificate and the users' certificates.
|
||||
ROUTER_TEMPLATES = ('vpn-server', 'vpn-user')
|
||||
|
||||
#: The built-in issuing CAs: name -> the pki option of the common name and the templates the CA issues.
|
||||
BUILTIN_CAS = {'p2s': ('p2s_name', ['vpn-server', 'vpn-user']), 's2s': ('s2s_name', ['site-to-site'])}
|
||||
#: The built-in issuing CAs: name -> the pki option of the common name and the templates the CA issues: the VPN, the
|
||||
#: site-to-site connections, and the Servers Issuing CA of mTLS certificates, which also signs the server's HTTPS
|
||||
#: certificate.
|
||||
BUILTIN_CAS = {'p2s': ('p2s_name', ['vpn-server', 'vpn-user']), 's2s': ('s2s_name', ['mtls']),
|
||||
'servers': ('servers_name', ['mtls'])}
|
||||
|
||||
#: A general-purpose issuing CA of pki.issuing_cas: option -> default, the type of the default being the required type.
|
||||
ISSUING_CA = {'name': '', 'templates': [], 'acme': False}
|
||||
@@ -350,6 +380,45 @@ def config_lock():
|
||||
yield
|
||||
|
||||
|
||||
def setup_lock():
|
||||
"""The open SETUP_LOCK, held; closing it releases the lock."""
|
||||
SETUP_LOCK.parent.mkdir(parents=True, exist_ok=True)
|
||||
handle = open(SETUP_LOCK, 'a', encoding='utf-8')
|
||||
fcntl.flock(handle, fcntl.LOCK_EX)
|
||||
return handle
|
||||
|
||||
|
||||
def request_setup(wait=False):
|
||||
"""Have linux-manager-setup apply the configuration; with wait, True when it has applied it and its last run
|
||||
succeeded, without wait, True when the run was requested.
|
||||
|
||||
A run in progress is not cut short: it holds SETUP_RUNNING, and the request, SETUP_REQUEST, has it run once more
|
||||
when it ends, however many requests it got. Without a run in progress the unit is restarted. The request is made
|
||||
under SETUP_LOCK, under which a run of setup also decides whether to end, so no request is missed.
|
||||
"""
|
||||
with setup_lock():
|
||||
SETUP_REQUEST.touch()
|
||||
with open(SETUP_RUNNING, 'a', encoding='utf-8') as running:
|
||||
try:
|
||||
fcntl.flock(running, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
idle = True
|
||||
except BlockingIOError:
|
||||
idle = False
|
||||
if idle:
|
||||
restart = subprocess.run(['systemctl', 'restart', '--no-block', SETUP_UNIT], capture_output=True)
|
||||
if restart.returncode != 0:
|
||||
return False
|
||||
# The unit's start job, the restarted run or the run in progress with its further runs, is waited for.
|
||||
while wait:
|
||||
state = subprocess.run(['systemctl', 'show', '-p', 'Job,ActiveState,Result', SETUP_UNIT],
|
||||
capture_output=True, text=True).stdout
|
||||
values = dict(line.partition('=')[::2] for line in state.splitlines())
|
||||
if not values.get('Job') and values.get('ActiveState') != 'activating':
|
||||
return values.get('ActiveState') == 'active' and values.get('Result') == 'success'
|
||||
time.sleep(1)
|
||||
return True
|
||||
|
||||
|
||||
def save_config(data):
|
||||
"""Write the settings to the configuration file, indented, with mode 0600, replacing it in one step.
|
||||
|
||||
@@ -366,6 +435,19 @@ def save_config(data):
|
||||
raise
|
||||
|
||||
|
||||
def choose_https_certificate(cfg, ctx, source):
|
||||
"""Write https.certificate, empty until then, as source into the configuration file, and into cfg and ctx for the
|
||||
rest of the run: the first setup's choice of the server's HTTPS certificate."""
|
||||
with config_lock():
|
||||
data = read_settings()
|
||||
section = data.get('https')
|
||||
data['https'] = {**(section if isinstance(section, dict) else {}), 'certificate': source}
|
||||
save_config(data)
|
||||
cfg['https']['certificate'] = source
|
||||
ctx['https_certificate'] = source
|
||||
warn(f'https.certificate is set to {source}, chosen by the first setup')
|
||||
|
||||
|
||||
def _split_list(value):
|
||||
return [item.strip() for item in value.split(',') if item.strip()]
|
||||
|
||||
@@ -586,9 +668,24 @@ def validate(cfg):
|
||||
if not item.startswith('/') or '/../' in f'{item}/':
|
||||
raise ConfigError(f'web.log_files: {item!r} is not an absolute path')
|
||||
|
||||
caddy_source = _get(cfg, 'https', 'caddy_source')
|
||||
if caddy_source not in CADDY_SOURCES:
|
||||
raise ConfigError(f'https.caddy_source: {caddy_source!r} is not one of {", ".join(CADDY_SOURCES)}')
|
||||
if _get(cfg, 'https', 'certificate') not in ('', *HTTPS_CERTIFICATES):
|
||||
raise ConfigError(f'https.certificate: {_get(cfg, "https", "certificate")!r} is not one of '
|
||||
f'{", ".join(HTTPS_CERTIFICATES)}, or empty for the next setup to choose')
|
||||
if not 1 <= _get(cfg, 'https', 'self_signed_days') <= 3650:
|
||||
raise ConfigError('https.self_signed_days must be 1 to 3650 days')
|
||||
provider = _get(cfg, 'https', 'acme_provider')
|
||||
if provider not in ACME_PROVIDERS:
|
||||
raise ConfigError(f'https.acme_provider: {provider!r} is not one of {", ".join(ACME_PROVIDERS)}')
|
||||
acme_url = _get(cfg, 'https', 'acme_url')
|
||||
if provider == 'custom' and not acme_url:
|
||||
raise ConfigError('https.acme_url is required while https.acme_provider is custom')
|
||||
if acme_url:
|
||||
parts = urllib.parse.urlsplit(acme_url)
|
||||
if parts.scheme != 'https' or not parts.hostname or parts.fragment:
|
||||
raise ConfigError('https.acme_url must be an https:// URL without a fragment')
|
||||
for option in ('email', 'acme_url', 'acme_eab_key_id', 'acme_eab_mac_key', 'zerossl_api_key'):
|
||||
if any(character.isspace() or character in '{}"' for character in _get(cfg, 'https', option)):
|
||||
raise ConfigError(f'https.{option} must not hold spaces, braces or quotes')
|
||||
|
||||
if _get(cfg, 'oidc', 'enabled') and not (_get(cfg, 'web', 'enabled') and _get(cfg, 'https', 'enabled')
|
||||
and _get(cfg, 'wan', 'local_fqdn')):
|
||||
@@ -634,7 +731,7 @@ def validate(cfg):
|
||||
f'addresses is the resolver of the remote access clients (p2s.dns_listen {resolver_listen}) '
|
||||
'while p2s.enabled, openvpn.enabled or wireguard.enabled is true')
|
||||
|
||||
for option in ('root_name', 'p2s_name', 's2s_name'):
|
||||
for option in ('root_name', 'p2s_name', 's2s_name', 'servers_name'):
|
||||
value = _get(cfg, 'pki', option)
|
||||
if not value or len(value) > CA_NAME_MAX or not value.isprintable():
|
||||
raise ConfigError(f'pki.{option} must have 1 to {CA_NAME_MAX} printable characters')
|
||||
@@ -703,8 +800,8 @@ def validate(cfg):
|
||||
prefix = f'pki.issuing_cas.{name}'
|
||||
if not PKI_NAME.match(name) or name in BUILTIN_CAS or name in ('root', 'upstream'):
|
||||
raise ConfigError(f'{prefix}: an issuing CA name starts with a lowercase letter and has at most 31 '
|
||||
f'lowercase letters, digits and hyphens, and is not root, upstream, '
|
||||
f'{" or ".join(BUILTIN_CAS)}')
|
||||
f'lowercase letters, digits and hyphens, and is not root, upstream or '
|
||||
f'{", ".join(BUILTIN_CAS)}')
|
||||
if not isinstance(authority, dict):
|
||||
raise ConfigError(f'{prefix} must be {TYPE_NAMES[dict]}')
|
||||
_check_options(authority, ISSUING_CA, prefix)
|
||||
@@ -727,6 +824,15 @@ def validate(cfg):
|
||||
|
||||
taken = {web_port: 'web.port', ACME_HTTP_PORT: 'the HTTP challenge',
|
||||
https_ports[0]: 'https.web_port', https_ports[1]: 'https.manager_port'}
|
||||
# Caddy serves the Manager's plain HTTP port and calls the services on their loopback ports.
|
||||
for port, owner in ((manager_port(), f"the Manager's port in {MANAGER_CONFIG}"),
|
||||
(WEB_LOOPBACK_PORT, 'the web service behind Caddy'),
|
||||
(MANAGER_LOOPBACK_PORT, 'the Manager behind Caddy'),
|
||||
(METRICS_LOOPBACK_PORT, 'the metrics service behind Caddy'),
|
||||
(WEBDAV_LOOPBACK_PORT, 'WebDAV behind Caddy')):
|
||||
if port in taken:
|
||||
raise ConfigError(f'{taken[port]}: {port} is the port of {owner}')
|
||||
taken[port] = owner
|
||||
if 'https-default' in publish:
|
||||
if HTTPS_DEFAULT_PORT in taken:
|
||||
raise ConfigError(f'pki.publish: https-default takes port {HTTPS_DEFAULT_PORT}, the port of '
|
||||
@@ -813,13 +919,12 @@ def validate(cfg):
|
||||
f'docker.exposed_ports: {item!r} is not a port or a port range')
|
||||
weight += 2 if ':' in item else 1
|
||||
first, _, last = item.partition(':')
|
||||
if _get(cfg, 'https', 'enabled'):
|
||||
caddy_ports = (ACME_HTTP_PORT, *https_ports, *([HTTPS_DEFAULT_PORT] if 'https-default' in publish else []))
|
||||
for port in caddy_ports:
|
||||
if int(first) <= port <= int(last or first):
|
||||
raise ConfigError(
|
||||
f'docker.exposed_ports: {item!r} takes port {port}, which Caddy serves while '
|
||||
'https.enabled is true')
|
||||
caddy_ports = (web_port, manager_port(), _get(cfg, 'metrics', 'port'),
|
||||
*((ACME_HTTP_PORT, *https_ports, *([HTTPS_DEFAULT_PORT] if 'https-default' in publish else []))
|
||||
if _get(cfg, 'https', 'enabled') else ()))
|
||||
for port in caddy_ports:
|
||||
if int(first) <= port <= int(last or first):
|
||||
raise ConfigError(f'docker.exposed_ports: {item!r} takes port {port}, which Caddy serves')
|
||||
if weight > DOCKER_PORT_LIMIT:
|
||||
raise ConfigError(
|
||||
f'docker.exposed_ports: at most {DOCKER_PORT_LIMIT} ports are allowed, '
|
||||
@@ -847,8 +952,8 @@ def extended_key_usages(cfg):
|
||||
|
||||
|
||||
def issuing_cas(cfg):
|
||||
"""The issuing CAs, name -> {name, templates, acme, builtin}: p2s and s2s (BUILTIN_CAS) with their common names from
|
||||
the pki section, then those of pki.issuing_cas, each filled from ISSUING_CA."""
|
||||
"""The issuing CAs, name -> {name, templates, acme, builtin}: p2s, s2s and servers (BUILTIN_CAS) with their common names
|
||||
from the pki section, then those of pki.issuing_cas, each filled from ISSUING_CA."""
|
||||
found = {name: {'name': _get(cfg, 'pki', option), 'templates': list(templates), 'acme': False, 'builtin': True}
|
||||
for name, (option, templates) in BUILTIN_CAS.items()}
|
||||
for name, options in cfg['pki']['issuing_cas'].items():
|
||||
@@ -870,7 +975,8 @@ def pki_base_urls(cfg):
|
||||
|
||||
|
||||
def manager_port():
|
||||
"""The port of the Manager: port in its settings, or MANAGER_PORT when it is not set or not a port."""
|
||||
"""The port of the Manager, Caddy's plain HTTP site of it: port in its settings, or MANAGER_PORT when it is not set
|
||||
or not a port."""
|
||||
try:
|
||||
port = json.loads(MANAGER_CONFIG.read_text(encoding='utf-8')).get('port')
|
||||
except (OSError, ValueError, AttributeError):
|
||||
@@ -878,6 +984,16 @@ def manager_port():
|
||||
return port if isinstance(port, int) and not isinstance(port, bool) and 1 <= port <= 65535 else MANAGER_PORT
|
||||
|
||||
|
||||
def manager_listen():
|
||||
"""The interfaces the firewall opens the Manager's port on: listen in its settings, one of LISTEN_CHOICES, or
|
||||
DEFAULT_LISTEN when it is not set or not one."""
|
||||
try:
|
||||
choice = json.loads(MANAGER_CONFIG.read_text(encoding='utf-8')).get('listen')
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return DEFAULT_LISTEN
|
||||
return choice if choice in LISTEN_CHOICES else DEFAULT_LISTEN
|
||||
|
||||
|
||||
def oidc_issuer(cfg):
|
||||
"""The issuer of the OpenID Provider: the web service's HTTPS site, without the port when it is HTTPS_DEFAULT_PORT."""
|
||||
port = _get(cfg, 'https', 'web_port')
|
||||
@@ -1034,6 +1150,8 @@ def build_context(cfg, public_ip=None):
|
||||
'mode': _get(cfg, 'general', 'mode') or 'manual',
|
||||
'router_enabled': _get(cfg, 'router', 'enabled'),
|
||||
'vpn_enabled': _get(cfg, 'vpn', 'enabled'),
|
||||
'router_installed': packages_installed(COMPONENTS['router'][1]),
|
||||
'vpn_installed': packages_installed(COMPONENTS['vpn'][1]),
|
||||
'wan_iface': ext_iface,
|
||||
'int_iface': int_iface,
|
||||
'local_addrs': ', '.join(local_addrs),
|
||||
@@ -1080,15 +1198,24 @@ def build_context(cfg, public_ip=None):
|
||||
'ldap_users': linuxmanager_ldap.USERS,
|
||||
'web_enabled': _get(cfg, 'web', 'enabled'),
|
||||
'web_port': _get(cfg, 'web', 'port'),
|
||||
'web_listen': _get(cfg, 'web', 'listen'),
|
||||
'https_enabled': _get(cfg, 'https', 'enabled'),
|
||||
'https_email': _get(cfg, 'https', 'email'),
|
||||
'https_acme_ca': ACME_STAGING_CA if _get(cfg, 'https', 'acme_staging') else '',
|
||||
'https_certificate': _get(cfg, 'https', 'certificate'),
|
||||
'https_acme_provider': _get(cfg, 'https', 'acme_provider'),
|
||||
'https_acme_url': (_get(cfg, 'https', 'acme_url') if _get(cfg, 'https', 'acme_provider') == 'custom'
|
||||
else ACME_STAGING_CA if _get(cfg, 'https', 'acme_staging') else ACME_PRODUCTION_CA),
|
||||
'https_acme_eab': ((_get(cfg, 'https', 'acme_eab_key_id'), _get(cfg, 'https', 'acme_eab_mac_key'))
|
||||
if _get(cfg, 'https', 'acme_eab_key_id') and _get(cfg, 'https', 'acme_eab_mac_key')
|
||||
else None),
|
||||
'https_zerossl_api_key': _get(cfg, 'https', 'zerossl_api_key'),
|
||||
'https_web_port': _get(cfg, 'https', 'web_port'),
|
||||
'https_manager_port': _get(cfg, 'https', 'manager_port'),
|
||||
'pki_publish': _get_list(cfg, 'pki', 'publish'),
|
||||
'pki_acme': [name for name, authority in issuing_cas(cfg).items() if authority['acme']],
|
||||
'metrics_enabled': _get(cfg, 'metrics', 'enabled'),
|
||||
'metrics_port': _get(cfg, 'metrics', 'port'),
|
||||
'metrics_listen': _get(cfg, 'metrics', 'listen'),
|
||||
'metrics_https_port': _get(cfg, 'metrics', 'https_port'),
|
||||
'metrics_service_account': _get(cfg, 'metrics', 'service_account'),
|
||||
'sites_enabled': _get(cfg, 'sites', 'enabled'),
|
||||
@@ -1101,8 +1228,8 @@ def build_context(cfg, public_ip=None):
|
||||
|
||||
|
||||
def s2s_ready(ctx):
|
||||
"""True when the router is on and any site_to_site connection is ready."""
|
||||
return bool(ctx['router_enabled'] and any(connection['ready'] for connection in ctx['connections']))
|
||||
"""True when the router is on and installed and any site_to_site connection is ready."""
|
||||
return bool(ctx['router_enabled'] and ctx['router_installed'] and any(connection['ready'] for connection in ctx['connections']))
|
||||
|
||||
|
||||
def routing_ready(ctx):
|
||||
@@ -1112,19 +1239,21 @@ def routing_ready(ctx):
|
||||
|
||||
|
||||
def p2s_ready(ctx):
|
||||
"""IKEv2 access needs the VPN on, its settings and the server's VPN server certificate, which the P2S CA issues."""
|
||||
return bool(ctx['vpn_enabled'] and ctx['p2s_enabled'] and ctx['p2s_address_pool'] and ctx['local_fqdn']
|
||||
"""IKEv2 access needs the VPN on and installed, its settings and the server's VPN server certificate, which the P2S
|
||||
CA issues."""
|
||||
return bool(ctx['vpn_enabled'] and ctx['vpn_installed'] and ctx['p2s_enabled'] and ctx['p2s_address_pool'] and ctx['local_fqdn']
|
||||
and ctx['server_certificate'])
|
||||
|
||||
|
||||
def wg_ready(ctx):
|
||||
"""WireGuard needs the VPN on and its settings."""
|
||||
return bool(ctx['vpn_enabled'] and ctx['wg_enabled'] and ctx['wg_address'])
|
||||
"""WireGuard needs the VPN on and installed and its settings."""
|
||||
return bool(ctx['vpn_enabled'] and ctx['vpn_installed'] and ctx['wg_enabled'] and ctx['wg_address'])
|
||||
|
||||
|
||||
def openvpn_ready(ctx):
|
||||
"""OpenVPN needs the VPN on, its settings and the server's VPN server certificate, which the P2S CA issues."""
|
||||
return bool(ctx['vpn_enabled'] and ctx['openvpn_enabled'] and ctx['openvpn_pool'] and ctx['local_fqdn']
|
||||
"""OpenVPN needs the VPN on and installed, its settings and the server's VPN server certificate, which the P2S CA
|
||||
issues."""
|
||||
return bool(ctx['vpn_enabled'] and ctx['vpn_installed'] and ctx['openvpn_enabled'] and ctx['openvpn_pool'] and ctx['local_fqdn']
|
||||
and ctx['server_certificate'])
|
||||
|
||||
|
||||
@@ -1150,6 +1279,25 @@ def webdav_ready(ctx):
|
||||
return bool(ctx['webdav_enabled'] and https_ready(ctx))
|
||||
|
||||
|
||||
def packages_installed(packages):
|
||||
"""Whether every one of the packages is installed, as dpkg knows them."""
|
||||
result = subprocess.run(['dpkg-query', '-W', '-f=${db:Status-Status}\n', *packages], capture_output=True, text=True)
|
||||
states = result.stdout.split()
|
||||
return len(states) == len(packages) and all(state == 'installed' for state in states)
|
||||
|
||||
|
||||
def packages_automatic(packages):
|
||||
"""The packages apt marks as installed automatically, which apt autoremove removes once nothing depends on them."""
|
||||
result = subprocess.run(['apt-mark', 'showauto', *packages], capture_output=True, text=True)
|
||||
return result.stdout.split() if result.returncode == 0 else []
|
||||
|
||||
|
||||
def component_on(cfg, name):
|
||||
"""Whether the switch of the component of COMPONENTS is on in the configuration."""
|
||||
section, setting = COMPONENTS[name][0]
|
||||
return bool(cfg[section][setting])
|
||||
|
||||
|
||||
def dns_ready(ctx):
|
||||
"""The name server answers for its domains while dns.enabled is true."""
|
||||
return bool(ctx['dns_enabled'])
|
||||
@@ -1276,6 +1424,9 @@ def configure(cfg=None, public_ip=None):
|
||||
fail(str(failure))
|
||||
except ldap.LDAPError as exc:
|
||||
notices = [f'the PKI is left as it is: the directory cannot be reached: {exc}']
|
||||
# Without the directory the first setup has no Servers Issuing CA to choose.
|
||||
if not cfg['https']['certificate']:
|
||||
choose_https_certificate(cfg, ctx, 'self-signed')
|
||||
for notice in notices:
|
||||
warn(notice)
|
||||
# The WireGuard peers of the users; None keeps those of wg0.conf while the directory cannot be reached.
|
||||
|
||||
@@ -416,7 +416,8 @@ def restore(source, pbs, confirm):
|
||||
if result.returncode != 0:
|
||||
raise Failure(f'pg_restore of {item} failed: {result.stderr.decode(errors="replace").strip()}')
|
||||
subprocess.run(['systemctl', 'start', 'linux-manager-web.service'], capture_output=True)
|
||||
command(['systemctl', 'restart', 'linux-manager-setup.service'])
|
||||
if not linuxmanager.request_setup(wait=True):
|
||||
raise Failure('linux-manager-setup failed; see journalctl -u linux-manager-setup')
|
||||
for unit in RESTORE_RESTARTS:
|
||||
subprocess.run(['systemctl', 'try-restart', unit], capture_output=True)
|
||||
subprocess.run(['ufw', 'reload'], capture_output=True)
|
||||
|
||||
@@ -255,11 +255,11 @@ def domain_remove(name):
|
||||
|
||||
|
||||
def secondary_addresses(cfg):
|
||||
"""The addresses dns.secondary resolves to, which are notified of the zones' changes and may transfer them; none,
|
||||
with a warning, while it is not set or does not resolve."""
|
||||
"""The addresses dns.secondary resolves to, which are notified of the zones' changes and may transfer them; none while
|
||||
it is not set, the domains then having the primary as their only name server, and none, with a warning, while it
|
||||
does not resolve."""
|
||||
secondary = cfg['dns']['secondary'].strip()
|
||||
if not secondary:
|
||||
linuxmanager.warn('dns.secondary is not set: the domains have no secondary name server')
|
||||
return []
|
||||
try:
|
||||
found = socket.getaddrinfo(secondary, 53, proto=socket.IPPROTO_UDP)
|
||||
|
||||
@@ -84,7 +84,10 @@ OVERLAYS = ('ppolicy', 'otp')
|
||||
#: certificate and CRL (cACertificate and certificateRevocationList of RFC 4523), its key, the
|
||||
#: CSR it waits with for its certificate, the number of its last CRL, where the CRL came from,
|
||||
#: and when it was retired; the root also holds the Simple CA token, linuxManagerToken, and the
|
||||
#: name of the Simple CA issuing CA that signs with it, linuxManagerUpstreamName. linuxManagerCertificate is a certificate a CA issued, named by its
|
||||
#: name of the Simple CA issuing CA that signs with it, linuxManagerUpstreamName.
|
||||
#: linuxManagerHostCertificate, cn=https, is the server's HTTPS certificate when no ACME CA or
|
||||
#: issuing CA gives it: the certificate with its chain, its key, the CSR waiting for a certificate
|
||||
#: of another CA and that CSR's key, and its kind, self-signed or external. linuxManagerCertificate is a certificate a CA issued, named by its
|
||||
#: serial number: the certificate, the key the server keeps for its own and the users'
|
||||
#: certificates, its kind, template, names and expiry, and its revocation.
|
||||
SCHEMA_OID = '1.3.6.1.4.1.67380.10.1.2'
|
||||
@@ -134,6 +137,9 @@ SCHEMA_ATTRIBUTE_TYPES = (
|
||||
f"{_OCTETS} )",
|
||||
f"( {SCHEMA_OID}.1.25 NAME 'linuxManagerUpstreamName' DESC 'Linux Manager: the Simple CA issuing CA of the token' "
|
||||
f"{_STRING} )",
|
||||
f"( {SCHEMA_OID}.1.26 NAME 'linuxManagerCertificateChain' DESC 'Linux Manager: a certificate and its chain, PEM' "
|
||||
f"{_OCTETS} )",
|
||||
f"( {SCHEMA_OID}.1.27 NAME 'linuxManagerRequestKey' DESC 'Linux Manager: the private key of a CSR, PEM' {_OCTETS} )",
|
||||
)
|
||||
SCHEMA_OBJECT_CLASSES = (
|
||||
f"( {SCHEMA_OID}.2.1 NAME 'linuxManagerAccount' DESC 'Linux Manager: properties of a user or a Manager-only account' "
|
||||
@@ -150,6 +156,9 @@ SCHEMA_OBJECT_CLASSES = (
|
||||
"linuxManagerSubjectAltName $ linuxManagerNotAfter $ linuxManagerRevoked $ linuxManagerRevocationReason ) )",
|
||||
f"( {SCHEMA_OID}.2.4 NAME 'linuxManagerRole' DESC 'Linux Manager: a role of a resource of the OpenID Provider' SUP top "
|
||||
"STRUCTURAL MUST cn MAY ( description $ member ) )",
|
||||
f"( {SCHEMA_OID}.2.5 NAME 'linuxManagerHostCertificate' DESC 'Linux Manager: a certificate of the server kept with "
|
||||
"its key' SUP top STRUCTURAL MUST cn MAY ( linuxManagerCertificateChain $ linuxManagerPrivateKey $ "
|
||||
"linuxManagerCertificateRequest $ linuxManagerRequestKey $ linuxManagerKind ) )",
|
||||
)
|
||||
|
||||
#: The TOTP parameters: digits, the OID of HMAC-SHA1, seconds per time step, and the time steps accepted before and after now.
|
||||
@@ -173,7 +182,7 @@ CONSOLE_HOMES = '/home'
|
||||
|
||||
#: The ACLs of the database, in order.
|
||||
ACCESS = (
|
||||
'to attrs=linuxManagerPrivateKey,linuxManagerToken by * none',
|
||||
'to attrs=linuxManagerPrivateKey,linuxManagerToken,linuxManagerRequestKey by * none',
|
||||
f'to attrs=userPassword by dn.exact="{MANAGER}" =wx by self =wx by anonymous auth by * none',
|
||||
f'to attrs=oathSecret by dn.exact="{MANAGER}" =w by * none',
|
||||
f'to dn.subtree="{USERS}" by dn.exact="{MANAGER}" manage by * read',
|
||||
|
||||
@@ -7,15 +7,22 @@ this module too.
|
||||
import pathlib
|
||||
import subprocess
|
||||
|
||||
#: The values of web.listen and of the Manager's listen: the interfaces a service listens on.
|
||||
#: The values of web.listen, metrics.listen and of the Manager's listen: the interfaces the firewall opens a service's
|
||||
#: port on.
|
||||
LISTEN_CHOICES = ('internal', 'external', 'both')
|
||||
|
||||
#: The interfaces a service listens on when it is not set.
|
||||
#: The interfaces a service's port is open on when it is not set.
|
||||
DEFAULT_LISTEN = 'both'
|
||||
|
||||
#: The address every service also listens on, where the HTTPS proxy calls it.
|
||||
#: The address the services listen on, where Caddy calls them.
|
||||
LOOPBACK = '127.0.0.1'
|
||||
|
||||
#: The ports the web service, the manager on the server and the metrics service listen on, on LOOPBACK only; Caddy
|
||||
#: serves web.port, the manager's port and metrics.port and calls them.
|
||||
WEB_LOOPBACK_PORT = 7091
|
||||
MANAGER_LOOPBACK_PORT = 7090
|
||||
METRICS_LOOPBACK_PORT = 9474
|
||||
|
||||
|
||||
class ConfigError(Exception):
|
||||
"""A setting is present but malformed."""
|
||||
@@ -68,6 +75,12 @@ def _is_virtual(name):
|
||||
return '/devices/virtual/' in str(link.resolve())
|
||||
|
||||
|
||||
def nics():
|
||||
"""The names of the network interfaces with a device behind them; loopback and virtual interfaces are left out."""
|
||||
directory = pathlib.Path('/sys/class/net')
|
||||
return sorted(path.name for path in directory.iterdir() if not _is_virtual(path.name)) if directory.is_dir() else []
|
||||
|
||||
|
||||
def _addressed_interfaces():
|
||||
"""Names of the NICs holding at least one IPv4 address; virtual interfaces are left out."""
|
||||
names = []
|
||||
@@ -147,7 +160,7 @@ def listen_addresses(configuration, choice):
|
||||
"""The addresses a service listens on for choice of LISTEN_CHOICES, from linux-manager.json read as configuration.
|
||||
|
||||
The internal address comes first; an address not known yet is left out. A choice that is not
|
||||
one of LISTEN_CHOICES is DEFAULT_LISTEN. LOOPBACK is not among them; web_listen adds it.
|
||||
one of LISTEN_CHOICES is DEFAULT_LISTEN. LOOPBACK is not among them.
|
||||
Without the router (router.enabled false) the external interface is also the internal side.
|
||||
"""
|
||||
if choice not in LISTEN_CHOICES:
|
||||
@@ -165,20 +178,9 @@ def listen_addresses(configuration, choice):
|
||||
return list(dict.fromkeys(address for address in addresses if address))
|
||||
|
||||
|
||||
def web_listen(configuration, default_port):
|
||||
"""Where the web service listens, from linux-manager.json read as configuration, as ([(address, port), ...], '').
|
||||
|
||||
The addresses are those of the interfaces web.listen names (listen_addresses), then
|
||||
LOOPBACK, the port web.port, else default_port. While web.enabled is false or no address of
|
||||
an interface is known, the answer is ([], the reason).
|
||||
"""
|
||||
web = _section(configuration, 'web')
|
||||
if web.get('enabled', True) is False:
|
||||
def web_listen(configuration):
|
||||
"""Where the web service listens, from linux-manager.json read as configuration: ([(LOOPBACK, WEB_LOOPBACK_PORT)], ''),
|
||||
Caddy serving web.port, or ([], the reason) while web.enabled is false."""
|
||||
if _section(configuration, 'web').get('enabled', True) is False:
|
||||
return [], 'the web service is disabled in the configuration'
|
||||
port = web.get('port', default_port)
|
||||
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
|
||||
port = default_port
|
||||
addresses = listen_addresses(configuration, web.get('listen', DEFAULT_LISTEN))
|
||||
if not addresses:
|
||||
return [], 'the addresses to listen on are not known yet'
|
||||
return [(address, port) for address in [*addresses, LOOPBACK]], ''
|
||||
return [(LOOPBACK, WEB_LOOPBACK_PORT)], ''
|
||||
@@ -1,7 +1,8 @@
|
||||
"""The server's PKI, for linux-manager-setup, the web service, linux-manager-ca and the user module.
|
||||
|
||||
The root CA signs the issuing CAs, and only them: p2s, which signs the server's VPN server certificate and the users'
|
||||
certificates, s2s, which signs the server's site-to-site certificate and those of its peers, and the general-purpose
|
||||
certificates, s2s, which signs the server's site-to-site certificate and those of its peers, servers, the Servers Issuing
|
||||
CA of mTLS certificates, which signs the server's HTTPS certificate with https.certificate ca, and the general-purpose
|
||||
CAs of pki.issuing_cas. The PKI is kept in ou=pki of the server's directory (linuxmanager_ldap), which root reaches through
|
||||
the local socket. Each CA is an entry cn=<name> of class linuxManagerAuthority, with its certificate, key, CRL and CRL
|
||||
number. Each certificate a CA issued is an entry serialNumber=<serial> of class linuxManagerCertificate under the CA,
|
||||
@@ -101,7 +102,12 @@ OPENVPN_CRL = pathlib.Path('/etc/openvpn/server/linux-manager-crl.pem')
|
||||
TRUST_ANCHOR = pathlib.Path('/usr/local/share/ca-certificates/linux-manager-ca.crt')
|
||||
|
||||
#: The server's own certificates: name -> the issuing CA and the template, and the files strongSwan reads.
|
||||
ROUTER_CERTS = {'vpn-server': ('p2s', 'vpn-server'), 'site-to-site': ('s2s', 'site-to-site')}
|
||||
ROUTER_CERTS = {'vpn-server': ('p2s', 'vpn-server'), 'site-to-site': ('s2s', 'mtls'), 'https': ('servers', 'mtls')}
|
||||
|
||||
#: The server's HTTPS certificate when it is self-signed or of another CA, and the attributes of its entry.
|
||||
HOST_DN = f'cn=https,{linuxmanager_ldap.PKI}'
|
||||
HOST_ATTRIBUTES = ['linuxManagerCertificateChain', 'linuxManagerPrivateKey', 'linuxManagerCertificateRequest',
|
||||
'linuxManagerRequestKey', 'linuxManagerKind']
|
||||
|
||||
#: The component, a section of the configuration, that a built-in issuing CA and the server's certificate it issues
|
||||
#: belong to: provision creates them only while the component's enabled is true.
|
||||
@@ -586,11 +592,11 @@ def is_address(value):
|
||||
|
||||
def router_identities(name, ctx):
|
||||
"""The common name and the subject alternative names of one of the server's certificates (ROUTER_CERTS): the VPN
|
||||
server certificate names wan.local_fqdn, and the site-to-site certificate also the local identity of each
|
||||
server and the HTTPS certificates name wan.local_fqdn, and the site-to-site certificate also the local identity of each
|
||||
site_to_site connection with certificate authentication, the public or the internal address of its
|
||||
local_id_mode; None while such an identity is not known yet."""
|
||||
fqdn = ctx['local_fqdn']
|
||||
if name == 'vpn-server':
|
||||
if name in ('vpn-server', 'https'):
|
||||
return fqdn, [fqdn]
|
||||
names = [fqdn]
|
||||
for connection in ctx['connections']:
|
||||
@@ -663,6 +669,22 @@ def check_source(cfg, entry):
|
||||
'root is fixed once the root exists', 4)
|
||||
|
||||
|
||||
def check_names(cfg, connection):
|
||||
"""Refuse a CA name of the configuration that differs from the common name of the CA's certificate or CSR: the
|
||||
name of a CA is fixed once the CA has its key. pki.root_name counts for a root the server created only."""
|
||||
options = {name: f'pki.{option}' for name, (option, _) in linuxmanager.BUILTIN_CAS.items()}
|
||||
names = {name: (options.get(name, f'pki.issuing_cas.{name}.name'), settings['name'].strip())
|
||||
for name, settings in linuxmanager.issuing_cas(cfg).items()}
|
||||
if cfg['pki']['root'] == 'local':
|
||||
names['root'] = ('pki.root_name', cfg['pki']['root_name'].strip())
|
||||
for name, (option, wanted) in names.items():
|
||||
entry = authority(connection, name)
|
||||
made = entry and (entry['cert'] or (x509.load_pem_x509_csr(entry['csr']) if entry['csr'] else None))
|
||||
if made and common_name(made) != wanted:
|
||||
raise Failure(f'{option} is {wanted!r}, but CA {name} was made as {common_name(made)!r}; the name of a CA '
|
||||
'is fixed once the CA exists', 4)
|
||||
|
||||
|
||||
def jwt_part(text):
|
||||
return base64.urlsafe_b64decode(text + '=' * (-len(text) % 4))
|
||||
|
||||
@@ -843,6 +865,188 @@ def fetch_crls(connection):
|
||||
return notices
|
||||
|
||||
|
||||
def host_entry(connection):
|
||||
"""The server's HTTPS certificate kept at HOST_DN: {chain, key, csr (PEM), request_key, kind}, None when there is
|
||||
none; chain is the certificate followed by its chain."""
|
||||
try:
|
||||
attributes = connection.search_s(HOST_DN, ldap.SCOPE_BASE, attrlist=HOST_ATTRIBUTES)[0][1]
|
||||
except ldap.NO_SUCH_OBJECT:
|
||||
return None
|
||||
chain, key, request_key = (first(attributes, name) for name in
|
||||
('linuxManagerCertificateChain', 'linuxManagerPrivateKey', 'linuxManagerRequestKey'))
|
||||
return {
|
||||
'chain': x509.load_pem_x509_certificates(chain) if chain else [],
|
||||
'key': serialization.load_pem_private_key(key, None) if key else None,
|
||||
'csr': first(attributes, 'linuxManagerCertificateRequest'),
|
||||
'request_key': serialization.load_pem_private_key(request_key, None) if request_key else None,
|
||||
'kind': (first(attributes, 'linuxManagerKind') or b'').decode() or None,
|
||||
}
|
||||
|
||||
|
||||
def update_host(connection, values):
|
||||
"""Set attributes of HOST_DN, adding the entry when it is missing; a value None removes its attribute."""
|
||||
try:
|
||||
connection.search_s(HOST_DN, ldap.SCOPE_BASE, attrlist=['1.1'])
|
||||
except ldap.NO_SUCH_OBJECT:
|
||||
connection.add_s(HOST_DN, ldap.modlist.addModlist({
|
||||
'objectClass': [b'linuxManagerHostCertificate'], 'cn': [b'https'],
|
||||
**{attribute: [value] for attribute, value in values.items() if value is not None}}))
|
||||
return
|
||||
connection.modify_s(HOST_DN, [(ldap.MOD_REPLACE, attribute, [value] if value is not None else [])
|
||||
for attribute, value in values.items()])
|
||||
|
||||
|
||||
def covers(cert, fqdn):
|
||||
"""Whether a DNS name of the certificate is fqdn, or a wildcard of one label that matches it."""
|
||||
for value in san_values(cert):
|
||||
kind, _, name = value.partition(':')
|
||||
name = name.lower()
|
||||
if kind == 'DNS' and (name == fqdn or (name.startswith('*.') and fqdn.partition('.')[2] == name[2:])):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def usable(cert, fqdn):
|
||||
"""Whether the certificate is valid now and names fqdn."""
|
||||
moment = now()
|
||||
return utc(cert, 'not_valid_before') <= moment < utc(cert, 'not_valid_after') and covers(cert, fqdn)
|
||||
|
||||
|
||||
def chain_pem(chain):
|
||||
return b''.join(cert_pem(cert) for cert in chain)
|
||||
|
||||
|
||||
def served_certificate(connection, cfg):
|
||||
"""What Caddy serves for wan.local_fqdn: (served, chain, key), served being https.certificate, or self-signed while
|
||||
the chosen certificate is not available; (acme, [], None) with acme, and (None, [], None) while there is none."""
|
||||
source, fqdn = cfg['https']['certificate'], cfg['wan']['local_fqdn'].strip().lower()
|
||||
if source == 'acme':
|
||||
return 'acme', [], None
|
||||
if source == 'ca':
|
||||
issuer = authority(connection, 'servers')
|
||||
current = holders(connection, 'servers', router_condition('https'))
|
||||
if issuer and issuer['cert'] is not None and current and usable(current[0][1], fqdn):
|
||||
above = x509.load_pem_x509_certificates(upper_chain(connection))
|
||||
return 'ca', [current[0][1], issuer['cert'], *above], current[0][2]
|
||||
entry = host_entry(connection)
|
||||
if entry and entry['chain'] and entry['key'] is not None and usable(entry['chain'][0], fqdn):
|
||||
if entry['kind'] == source or entry['kind'] == 'self-signed':
|
||||
return entry['kind'], entry['chain'], entry['key']
|
||||
return None, [], None
|
||||
|
||||
|
||||
def ensure_host_cert(connection, cfg):
|
||||
"""Make the self-signed certificate of wan.local_fqdn while https.certificate is self-signed, or while the chosen
|
||||
certificate is not available, when there is none, it is due for renewal or it names another name; the notices."""
|
||||
source, fqdn = cfg['https']['certificate'], cfg['wan']['local_fqdn'].strip().lower()
|
||||
if source == 'acme' or not cfg['https']['enabled'] or not fqdn:
|
||||
return []
|
||||
served, _, _ = served_certificate(connection, cfg)
|
||||
if served == source and served != 'self-signed':
|
||||
return []
|
||||
entry = host_entry(connection)
|
||||
current = entry['chain'][0] if entry and entry['kind'] == 'self-signed' and entry['chain'] else None
|
||||
if current is None or renewal_due(current) or not usable(current, fqdn) or common_name(current) != fqdn:
|
||||
template = linuxmanager.pki_templates(cfg)['mtls']
|
||||
key = new_key(template['key'])
|
||||
cert = sign(fqdn, key.public_key(), None, key, cfg['https']['self_signed_days'],
|
||||
leaf_extensions(cfg, template, general_names([fqdn], {'dns'})))
|
||||
update_host(connection, {'linuxManagerCertificateChain': cert_pem(cert), 'linuxManagerPrivateKey': key_pem(key),
|
||||
'linuxManagerKind': b'self-signed'})
|
||||
if source == 'self-signed':
|
||||
return []
|
||||
return [f'the HTTPS certificate of {fqdn} is self-signed until the https.certificate {source} certificate is '
|
||||
'available' + (': import it with linux-manager-ca https import or import-pfx' if source == 'external'
|
||||
else '')]
|
||||
|
||||
|
||||
def https_files(cfg):
|
||||
"""The PEM chain and key Caddy serves for wan.local_fqdn, None with https.certificate acme or while there is none."""
|
||||
with directory() as connection:
|
||||
served, chain, key = served_certificate(connection, cfg)
|
||||
if served in (None, 'acme'):
|
||||
return None
|
||||
return chain_pem(chain), key_pem(key)
|
||||
|
||||
|
||||
def https_status(cfg):
|
||||
"""The server's HTTPS certificate: {source, served, subject, issuer, sans, expires, pending}, served being the
|
||||
source Caddy's certificate comes from, self-signed as the fallback, and pending whether a CSR waits."""
|
||||
with directory() as connection:
|
||||
served, chain, _ = served_certificate(connection, cfg)
|
||||
entry = host_entry(connection)
|
||||
cert = chain[0] if chain else None
|
||||
return {
|
||||
'source': cfg['https']['certificate'], 'served': served,
|
||||
'subject': common_name(cert) if cert is not None else None,
|
||||
'issuer': next((attribute.value for attribute in cert.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)),
|
||||
None) if cert is not None else None,
|
||||
'sans': [value.split(':', 1)[1] for value in san_values(cert)] if cert is not None else [],
|
||||
'expires': iso(utc(cert, 'not_valid_after')) if cert is not None else None,
|
||||
'pending': bool(entry and entry['csr']),
|
||||
}
|
||||
|
||||
|
||||
def https_csr(cfg):
|
||||
"""Make a key and a CSR for wan.local_fqdn, to be signed by another CA, replacing a pending one: {csr} in PEM."""
|
||||
fqdn = cfg['wan']['local_fqdn'].strip().lower()
|
||||
if not fqdn:
|
||||
raise Failure('the server has no wan.local_fqdn', 4)
|
||||
key = new_key(linuxmanager.pki_templates(cfg)['mtls']['key'])
|
||||
request = (x509.CertificateSigningRequestBuilder()
|
||||
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, fqdn)]))
|
||||
.add_extension(x509.SubjectAlternativeName([x509.DNSName(fqdn)]), False)
|
||||
.sign(key, digest(key)))
|
||||
pem = request.public_bytes(serialization.Encoding.PEM)
|
||||
with directory() as connection:
|
||||
update_host(connection, {'linuxManagerCertificateRequest': pem, 'linuxManagerRequestKey': key_pem(key)})
|
||||
return {'csr': pem.decode()}
|
||||
|
||||
|
||||
def keep_external(connection, cfg, chain, key):
|
||||
"""Keep an imported certificate of another CA as the server's HTTPS certificate: it must be the key's, valid now
|
||||
and name wan.local_fqdn; {subject, issuer, expires}."""
|
||||
fqdn = cfg['wan']['local_fqdn'].strip().lower()
|
||||
if cfg['https']['certificate'] != 'external':
|
||||
raise Failure('https.certificate is not external', 4)
|
||||
cert = chain[0]
|
||||
if not same_key(cert.public_key(), key.public_key()):
|
||||
raise Failure('the certificate is not for the key', 2)
|
||||
if not usable(cert, fqdn):
|
||||
raise Failure(f'the certificate is not valid now, or does not name {fqdn}', 2)
|
||||
update_host(connection, {'linuxManagerCertificateChain': chain_pem(chain), 'linuxManagerPrivateKey': key_pem(key),
|
||||
'linuxManagerKind': b'external'})
|
||||
issuer = next((attribute.value for attribute in cert.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)), None)
|
||||
return {'subject': common_name(cert), 'issuer': issuer, 'expires': iso(utc(cert, 'not_valid_after'))}
|
||||
|
||||
|
||||
def import_https_certificate(cfg, text):
|
||||
"""Take the certificate another CA signed for the pending CSR, PEM, followed by its chain."""
|
||||
try:
|
||||
chain = x509.load_pem_x509_certificates(text.strip().encode() if isinstance(text, str) else b'')
|
||||
except ValueError:
|
||||
raise Failure('the certificate is not a PEM certificate', 2)
|
||||
with directory() as connection:
|
||||
entry = host_entry(connection)
|
||||
if entry is None or entry['request_key'] is None:
|
||||
raise Failure('no CSR waits for a certificate: make one with linux-manager-ca https csr', 4)
|
||||
document = keep_external(connection, cfg, chain, entry['request_key'])
|
||||
update_host(connection, {'linuxManagerCertificateRequest': None, 'linuxManagerRequestKey': None})
|
||||
return document
|
||||
|
||||
|
||||
def import_https_pfx(cfg, data, password):
|
||||
"""Take a PKCS#12 file of another CA's certificate, with its key and chain, protected by the password."""
|
||||
try:
|
||||
key, cert, more = pkcs12.load_key_and_certificates(data, password.encode() if password else None)
|
||||
except (ValueError, TypeError):
|
||||
raise Failure('the file is not a PKCS#12 file, or the password is wrong', 2)
|
||||
if key is None or cert is None:
|
||||
raise Failure('the PKCS#12 file holds no key or no certificate', 2)
|
||||
with directory() as connection:
|
||||
return keep_external(connection, cfg, [cert, *more], key)
|
||||
|
||||
|
||||
def provision(cfg, ctx):
|
||||
"""Create what the configuration needs and is missing, and keep it current; the notices to report.
|
||||
|
||||
@@ -852,7 +1056,9 @@ def provision(cfg, ctx):
|
||||
(simple-ca, upstream_sign), or is pending until its certificate is imported (offline, or simple-ca while Simple CA
|
||||
cannot sign). An issuing CA that pki.issuing_cas no longer names is retired; its certificate is revoked on the root
|
||||
CRL, or, with an external root, a notice says to revoke it there. Stale CRLs are signed again or, with simple-ca,
|
||||
fetched, the server's certificates issued or renewed (ensure_router_cert), and the copies of PUBLISH_DIR written. A
|
||||
fetched. While https.certificate is empty, the first setup chooses it: ca when the Servers Issuing CA has its
|
||||
certificate, else self-signed (linuxmanager.choose_https_certificate). The server's certificates are issued or
|
||||
renewed (ensure_router_cert), and the copies of PUBLISH_DIR written. A
|
||||
built-in CA and the server's certificate it issues are created only while their component (BUILTIN_COMPONENTS) is
|
||||
on; switching the component off keeps them. While the VPN is on, each VPN user without a certificate gets one.
|
||||
"""
|
||||
@@ -865,6 +1071,7 @@ def provision(cfg, ctx):
|
||||
|
||||
with directory() as connection:
|
||||
check_source(cfg, authority(connection, 'root'))
|
||||
check_names(cfg, connection)
|
||||
notice = take_setup_code(cfg)
|
||||
if notice:
|
||||
notices.append(notice)
|
||||
@@ -950,9 +1157,14 @@ def provision(cfg, ctx):
|
||||
refresh_crls(connection, cfg, force)
|
||||
if pki['root'] == 'simple-ca':
|
||||
notices.extend(fetch_crls(connection))
|
||||
if not cfg['https']['certificate']:
|
||||
servers = authority(connection, 'servers')
|
||||
linuxmanager.choose_https_certificate(cfg, ctx, 'ca' if servers and servers['cert'] is not None else 'self-signed')
|
||||
https_ca = cfg['https']['enabled'] and cfg['https']['certificate'] == 'ca'
|
||||
for name in ROUTER_CERTS:
|
||||
if component_on(ROUTER_CERTS[name][0]):
|
||||
if component_on(ROUTER_CERTS[name][0]) and (name != 'https' or https_ca):
|
||||
ensure_router_cert(connection, cfg, ctx, name, urls)
|
||||
notices.extend(ensure_host_cert(connection, cfg))
|
||||
publish(connection)
|
||||
p2s = authority(connection, 'p2s')
|
||||
missing = connection.search_s(linuxmanager_ldap.USERS, ldap.SCOPE_ONELEVEL,
|
||||
@@ -1013,8 +1225,9 @@ def install_crls(connection):
|
||||
|
||||
|
||||
def reload_crls(connection):
|
||||
"""Install the CRLs, and have strongSwan load them when they changed; OpenVPN reads its file when it changes."""
|
||||
if install_crls(connection):
|
||||
"""Install the CRLs, and have strongSwan load them when they changed and it is installed; OpenVPN reads its file when
|
||||
it changes."""
|
||||
if install_crls(connection) and shutil.which('swanctl'):
|
||||
subprocess.run(['swanctl', '--load-creds'], capture_output=True, text=True)
|
||||
|
||||
|
||||
@@ -1308,6 +1521,9 @@ def import_ca(cfg, name, text):
|
||||
raise Failure(f'the certificate is not for the key of the CSR of {name}', 2)
|
||||
if not is_ca(cert):
|
||||
raise Failure('the certificate is not a CA certificate', 2)
|
||||
if entry['csr'] is not None and common_name(cert) != common_name(x509.load_pem_x509_csr(entry['csr'])):
|
||||
raise Failure(f'the certificate is for {common_name(cert)!r}, but the CSR of {name} is for '
|
||||
f'{common_name(x509.load_pem_x509_csr(entry["csr"]))!r}', 2)
|
||||
update(connection, name, {'cACertificate;binary': cert_der(cert), 'linuxManagerCertificateRequest': None})
|
||||
record(connection, cert, 'root', 'ca')
|
||||
sign_crl(connection, cfg, name)
|
||||
@@ -1351,15 +1567,19 @@ def import_root_crl(cfg, data):
|
||||
|
||||
def maintain(cfg):
|
||||
"""Sign the stale CRLs again or, with simple-ca, fetch them, publish and install them; the notices, and True when
|
||||
one of the server's certificates is due for renewal or, with simple-ca, an issuing CA waits for Simple CA, which
|
||||
linux-manager-setup does."""
|
||||
one of the server's certificates is due for renewal, the HTTPS certificate among them while the server issues it,
|
||||
or, with simple-ca, an issuing CA waits for Simple CA, which linux-manager-setup does."""
|
||||
with directory() as connection:
|
||||
refresh_crls(connection, cfg)
|
||||
notices = fetch_crls(connection) if cfg['pki']['root'] == 'simple-ca' else []
|
||||
publish(connection)
|
||||
reload_crls(connection)
|
||||
https_ca = cfg['https']['certificate'] == 'ca'
|
||||
due = [current[0][1] for current in (holders(connection, ROUTER_CERTS[name][0], router_condition(name))
|
||||
for name in ROUTER_CERTS) if current]
|
||||
for name in ROUTER_CERTS if name != 'https' or https_ca) if current]
|
||||
served, chain, _ = served_certificate(connection, cfg)
|
||||
if served == 'self-signed':
|
||||
due.append(chain[0])
|
||||
root = authority(connection, 'root')
|
||||
waiting = cfg['pki']['root'] == 'simple-ca' and root is not None and root['token'] is not None and any(
|
||||
entry is not None and entry['cert'] is None and entry['csr'] is not None
|
||||
@@ -1374,7 +1594,8 @@ def acme_url(cfg, name):
|
||||
|
||||
def status(cfg):
|
||||
"""The root, the upstream CA, the issuing CAs, the retired CAs and the warnings, as /ca and linux-manager-ca status
|
||||
show them."""
|
||||
show them. An issuing CA is active, pending while it waits for its certificate, off while it is a built-in CA whose
|
||||
component (BUILTIN_COMPONENTS), named by its component, is off and it was never made, or missing."""
|
||||
moment = now()
|
||||
soon = moment + datetime.timedelta(days=WARN_DAYS)
|
||||
warnings = []
|
||||
@@ -1399,7 +1620,9 @@ def status(cfg):
|
||||
'(&(objectClass=linuxManagerAuthority)(linuxManagerRetired=*))',
|
||||
['cn', 'linuxManagerRetired', 'cACertificate;binary'])
|
||||
router_certs = [current[0][1] for current in (holders(connection, ROUTER_CERTS[name][0], router_condition(name))
|
||||
for name in ROUTER_CERTS) if current]
|
||||
for name in ROUTER_CERTS
|
||||
if name != 'https' or cfg['https']['certificate'] == 'ca') if current]
|
||||
served, chain, _ = served_certificate(connection, cfg)
|
||||
|
||||
source = cfg['pki']['root']
|
||||
token = root_entry['token'] if root_entry else None
|
||||
@@ -1435,9 +1658,12 @@ def status(cfg):
|
||||
for name, settings in linuxmanager.issuing_cas(cfg).items():
|
||||
entry = entries[name]
|
||||
cert = entry['cert'] if entry else None
|
||||
kind = 'active' if cert is not None else 'pending' if entry and entry['csr'] is not None else 'missing'
|
||||
component = BUILTIN_COMPONENTS.get(name)
|
||||
kind = 'active' if cert is not None else 'pending' if entry and entry['csr'] is not None \
|
||||
else 'off' if component and not cfg[component]['enabled'] else 'missing'
|
||||
authorities.append({
|
||||
'name': name, 'common_name': settings['name'], 'state': kind, 'builtin': settings['builtin'],
|
||||
'component': component,
|
||||
'templates': settings['templates'], 'acme': settings['acme'],
|
||||
'subject': common_name(cert) if cert is not None else None,
|
||||
'expires': iso(utc(cert, 'not_valid_after')) if cert is not None else None,
|
||||
@@ -1464,4 +1690,11 @@ def status(cfg):
|
||||
for cert in router_certs:
|
||||
if utc(cert, 'not_valid_after') <= soon:
|
||||
warnings.append(f'the server certificate {common_name(cert)} expires on {iso(utc(cert, "not_valid_after"))}')
|
||||
https_source = cfg['https']['certificate']
|
||||
if cfg['https']['enabled'] and https_source != 'acme':
|
||||
if served != https_source:
|
||||
warnings.append(f'the HTTPS certificate is {"self-signed" if served else "missing"} until the https.certificate '
|
||||
f'{https_source} certificate is available')
|
||||
if served == 'external' and utc(chain[0], 'not_valid_after') <= soon:
|
||||
warnings.append(f'the HTTPS certificate expires on {iso(utc(chain[0], "not_valid_after"))}; import a new one')
|
||||
return {'root': root, 'authorities': authorities, 'retired': retired, 'warnings': warnings}
|
||||
@@ -14,7 +14,7 @@ public (wan.public_address), internal or external. A site may use wan.local_fqdn
|
||||
stays where the domain of wan.local_fqdn is.
|
||||
|
||||
The sites are served while sites.enabled is true; linux-manager-setup writes Caddy's configuration and opens the ports. A
|
||||
site is changed only through this module, which checks it (check), and its callers then restart linux-manager-setup.
|
||||
site is changed only through this module, which checks it (check), and its callers then request a run of linux-manager-setup.
|
||||
|
||||
The files of a site are read and written by path relative to its folder; resolve() refuses a path that leaves it.
|
||||
receive() writes a file from a stream, extract() a zip archive into a folder; both stop at sites.upload_max_mb.
|
||||
@@ -177,7 +177,9 @@ def taken_ports(cfg):
|
||||
cfg['https']['manager_port']: 'https.manager_port', cfg['metrics']['port']: 'metrics.port',
|
||||
cfg['metrics']['https_port']: 'metrics.https_port', linuxmanager.manager_port(): 'the Manager',
|
||||
cfg['sites']['webdav_port']: 'sites.webdav_port', linuxmanager.WEBDAV_LOOPBACK_PORT: 'rclone\'s WebDAV',
|
||||
53: 'DNS'}
|
||||
linuxmanager.WEB_LOOPBACK_PORT: 'the web service behind Caddy',
|
||||
linuxmanager.MANAGER_LOOPBACK_PORT: 'the Manager behind Caddy',
|
||||
linuxmanager.METRICS_LOOPBACK_PORT: 'the metrics service behind Caddy', 53: 'DNS'}
|
||||
for port in linuxmanager.BOOTSTRAP_PORTS:
|
||||
taken[port] = 'the bootstrap service'
|
||||
if cfg['openvpn']['protocol'] == 'tcp':
|
||||
|
||||
@@ -4,12 +4,13 @@ The settings file (CONFIG_FILE unless another is given) sets, all optional: rout
|
||||
listen, bind, port, terraform_dir and iac_tool. bind is the one address to listen on. Without
|
||||
router_url, terraform_dir names the Terraform root module whose output router_web_url gives the
|
||||
URL of the server's web service, read with iac_tool, terraform (the default) or tofu; dev.sh uses
|
||||
it to run the manager on a workstation. A setting that is not given comes from the server's
|
||||
configuration, ROUTER_CONFIG_FILE: without bind the manager listens on the addresses of the
|
||||
interfaces listen names, internal, external or both (the default), and on the loopback address,
|
||||
where the server's HTTPS proxy calls it, router_url is the first address and web.port of the
|
||||
server's web service, and database is the DATABASE database on this host, with the password in
|
||||
DATABASE_SECRET.
|
||||
it to run the manager on a workstation. On the server, where ROUTER_CONFIG_FILE is, the manager
|
||||
listens without bind on linuxmanager_net.MANAGER_LOOPBACK_PORT of the loopback address, where
|
||||
Caddy calls it: Caddy serves port over plain HTTP and https.manager_port over HTTPS, and the
|
||||
firewall opens port on the interfaces listen names, internal, external or both (the default).
|
||||
A setting that is not given comes from the server's configuration: router_url is the web
|
||||
service on its loopback port, and database is the DATABASE database on this host, with the
|
||||
password in DATABASE_SECRET.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -30,7 +31,7 @@ DATABASE_SECRET = '/etc/linux-manager/manager-database.secret'
|
||||
#: The role and the database the manager creates on the server.
|
||||
DATABASE = 'linux-manager-ui'
|
||||
|
||||
#: The port when port is not set.
|
||||
#: The port when port is not set: the port of bind, or on the server Caddy's plain HTTP port of the manager.
|
||||
DEFAULT_PORT = 7080
|
||||
|
||||
#: The port of the server's web service when web.port is not set.
|
||||
@@ -94,16 +95,16 @@ def output_value(outputs, name):
|
||||
|
||||
|
||||
def listen(config_file):
|
||||
"""Where the manager listens, read now: ([(address, port), ...], ''), or ([], the reason) while no address is known."""
|
||||
"""Where the manager listens, read now: [(bind, port)] with bind, else on the server
|
||||
[(LOOPBACK, MANAGER_LOOPBACK_PORT)], as ([(address, port), ...], ''), or ([], the reason) off the server without
|
||||
bind."""
|
||||
configuration = read_json(config_file)
|
||||
bind = text_setting(configuration, 'bind')
|
||||
port = port_setting(configuration.get('port'), DEFAULT_PORT)
|
||||
if bind:
|
||||
return [(bind, port)], ''
|
||||
addresses = linuxmanager_net.listen_addresses(read_json(ROUTER_CONFIG_FILE), text_setting(configuration, 'listen'))
|
||||
if not addresses:
|
||||
return [], "the server's addresses to listen on are not known yet"
|
||||
return [(address, port) for address in [*addresses, linuxmanager_net.LOOPBACK]], ''
|
||||
return [(bind, port_setting(configuration.get('port'), DEFAULT_PORT))], ''
|
||||
if os.path.exists(ROUTER_CONFIG_FILE):
|
||||
return [(linuxmanager_net.LOOPBACK, linuxmanager_net.MANAGER_LOOPBACK_PORT)], ''
|
||||
return [], f'bind is not set, and {ROUTER_CONFIG_FILE} is not here'
|
||||
|
||||
|
||||
def settings(config_file):
|
||||
@@ -128,20 +129,20 @@ def settings(config_file):
|
||||
if password:
|
||||
result['database'] = f'host=localhost dbname={DATABASE} user={DATABASE} password={password}'
|
||||
if not result['router_url']:
|
||||
targets, _ = linuxmanager_net.web_listen(router, ROUTER_PORT)
|
||||
targets, _ = linuxmanager_net.web_listen(router)
|
||||
if targets:
|
||||
result['router_url'] = f'http://{targets[0][0]}:{targets[0][1]}'
|
||||
result['router_url'] = result['router_url'].rstrip('/')
|
||||
return result
|
||||
|
||||
|
||||
def status_url(config_file, host, address, https):
|
||||
"""The URL of the server's status page for a browser that reached the manager as host on its address.
|
||||
def status_url(config_file, host, https):
|
||||
"""The URL of the server's status page for a browser that reached the manager as host.
|
||||
|
||||
On the server, while neither router_url nor terraform_dir is set, it has host, without its
|
||||
port, so the link works by whatever name or address the browser used: with https, a call
|
||||
through the server's HTTPS proxy, https and https.web_port; else, while the server's web
|
||||
service listens on address, http and web.port. Otherwise it is router_url, or '' without one.
|
||||
through Caddy's HTTPS site, https and https.web_port; else, while the web service is enabled,
|
||||
http and web.port, Caddy's plain HTTP site. Otherwise it is router_url, or '' without one.
|
||||
"""
|
||||
configuration = read_json(config_file)
|
||||
try:
|
||||
@@ -155,13 +156,21 @@ def status_url(config_file, host, address, https):
|
||||
if https:
|
||||
options = router.get('https') if isinstance(router.get('https'), dict) else {}
|
||||
return f'https://{name}:{port_setting(options.get("web_port"), ROUTER_HTTPS_PORT)}'
|
||||
targets, _ = linuxmanager_net.web_listen(router, ROUTER_PORT)
|
||||
ports = [port for listened, port in targets if listened == address]
|
||||
if ports:
|
||||
return f'http://{name}:{ports[0]}'
|
||||
web = router.get('web') if isinstance(router.get('web'), dict) else {}
|
||||
if web.get('enabled', True) is not False:
|
||||
return f'http://{name}:{port_setting(web.get("port"), ROUTER_PORT)}'
|
||||
return settings(config_file)['router_url']
|
||||
|
||||
|
||||
def plain_site(config_file):
|
||||
"""The manager's plain HTTP site on the server, served by Caddy: {port, listen}, its port and the interfaces the
|
||||
firewall opens it on, from the settings, with DEFAULT_PORT and linuxmanager_net.DEFAULT_LISTEN when not set."""
|
||||
configuration = read_json(config_file)
|
||||
listen = text_setting(configuration, 'listen')
|
||||
return {'port': port_setting(configuration.get('port'), DEFAULT_PORT),
|
||||
'listen': listen if listen in linuxmanager_net.LISTEN_CHOICES else linuxmanager_net.DEFAULT_LISTEN}
|
||||
|
||||
|
||||
def serve(wanted, handler, log, interval):
|
||||
"""Work out where to listen every interval seconds with wanted, and run an HTTP server of handler at each place.
|
||||
|
||||
|
||||
@@ -84,6 +84,7 @@ import uuid
|
||||
import ldap
|
||||
import ldap.filter
|
||||
import ldap.modlist
|
||||
from ldap.controls import RequestControl
|
||||
import pyotp
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
@@ -150,6 +151,8 @@ GROUP_ATTRIBUTES = ['cn', 'description', 'member']
|
||||
DESCRIPTION_MAX = 256
|
||||
#: The value of pwdAccountLockedTime that disables an account until it is enabled.
|
||||
LOCKED = linuxmanager_ldap.DISABLED.encode()
|
||||
#: The OID of the Relax Rules control.
|
||||
RELAX_RULES = '1.3.6.1.4.1.4203.666.5.12'
|
||||
#: The group whose members manage the server through the web service.
|
||||
ADMIN_GROUP = 'admins'
|
||||
#: The digits of a TOTP code given to login().
|
||||
@@ -720,7 +723,7 @@ def update(connection, name, values):
|
||||
|
||||
def apply_wireguard():
|
||||
"""Have linux-manager-setup write the WireGuard peers of the users into wg0.conf, without waiting for it."""
|
||||
subprocess.run(['systemctl', 'restart', '--no-block', 'linux-manager-setup.service'], capture_output=True)
|
||||
linuxmanager.request_setup()
|
||||
|
||||
|
||||
def update_service(connection, name, values):
|
||||
@@ -793,14 +796,15 @@ def enable(connection, name):
|
||||
|
||||
|
||||
def unlock(connection, name):
|
||||
"""End a lockout after failed binds and clear the failure count; a disabled user stays disabled."""
|
||||
"""End a lockout after failed binds and clear the failure count, with the Relax Rules control; a disabled user
|
||||
stays disabled."""
|
||||
entry(connection, name)
|
||||
current = connection.search_s(dn_of(name), ldap.SCOPE_BASE, attrlist=['pwdAccountLockedTime', 'pwdFailureTime'])[0][1]
|
||||
changes = [(ldap.MOD_DELETE, 'pwdFailureTime', None)] if 'pwdFailureTime' in current else []
|
||||
if 'pwdAccountLockedTime' in current and current['pwdAccountLockedTime'] != [LOCKED]:
|
||||
changes.append((ldap.MOD_DELETE, 'pwdAccountLockedTime', None))
|
||||
if changes:
|
||||
connection.modify_s(dn_of(name), changes)
|
||||
connection.modify_ext_s(dn_of(name), changes, serverctrls=[RequestControl(RELAX_RULES, True)])
|
||||
return summary(entry(connection, name))
|
||||
|
||||
|
||||
|
||||
@@ -54,17 +54,20 @@ Pages:
|
||||
/sites the web sites Caddy serves: the settings of sites, list, add, change and remove (see sites()),
|
||||
and the files of each: list, download, upload, extract a zip archive, create a folder, rename and
|
||||
remove (see Handler.site_files()); a member of a site's editors group may use the site's files
|
||||
/components
|
||||
the installable components, the VPN, the router, the name server and WebDAV: their switches and
|
||||
whether their packages are installed (see components())
|
||||
/dns the primary name server of the server's domains: its settings, and the domains: add, change and
|
||||
remove, each with the records it serves and its manual records (see dns())
|
||||
/postgresql
|
||||
the databases of each PostgreSQL cluster on the server with their sizes, as JSON (see
|
||||
postgresql_databases()); /config has the clusters' settings
|
||||
/.well-known/openid-configuration, /oidc/...
|
||||
while oidc.enabled is true, the OpenID Provider (linuxmanager_oidc), answered only on the
|
||||
loopback address, where Caddy passes the requests of the HTTPS site; POST /oidc/login counts
|
||||
towards the limit of /auth calls
|
||||
while oidc.enabled is true, the OpenID Provider (linuxmanager_oidc), answered only for Caddy's
|
||||
calls of the HTTPS site, from the loopback address with X-Forwarded-Proto https; POST
|
||||
/oidc/login counts towards the limit of /auth calls
|
||||
|
||||
/status/full, /config, /metrics/history, /metrics/settings, /postgresql, /users, /service-accounts, /groups, /site-to-site, /backup, /remote-access, /ca, /logs, /sites, /dns, /shell and /account need an HS256 JWT in an Authorization: Bearer header signed
|
||||
/status/full, /config, /metrics/history, /metrics/settings, /postgresql, /users, /service-accounts, /groups, /site-to-site, /backup, /remote-access, /ca, /logs, /sites, /dns, /components, /shell and /account need an HS256 JWT in an Authorization: Bearer header signed
|
||||
with linuxmanager_auth.WEB_KEY (see linuxmanager_auth.verify). A token of /auth names a user in sub;
|
||||
/account serves that user, and the other paths need a member of linuxmanager_users.ADMIN_GROUP. A
|
||||
token of linux-manager-token has the admin claim and names no user; it may call every path but
|
||||
|
||||
@@ -36,7 +36,7 @@ def backup(method, path, body):
|
||||
current secret
|
||||
POST /backup/run start a backup now, without waiting for it; 409 while one runs
|
||||
|
||||
A change is made as /site-to-site makes one, and applied by restarting linux-manager-setup without waiting for it.
|
||||
A change is made as /site-to-site makes one, and applied by a run of linux-manager-setup, without waiting for it.
|
||||
"""
|
||||
if body == 'invalid' or (body is not None and not isinstance(body, dict)):
|
||||
return 400, {'error': 'the body must be a JSON object'}
|
||||
@@ -80,5 +80,5 @@ def backup(method, path, body):
|
||||
return 500, {'error': f'the configuration cannot be written: {exc}'}
|
||||
except SystemExit as exc:
|
||||
return 500, {'error': str(exc.code)}
|
||||
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
|
||||
linuxmanager.request_setup()
|
||||
return 200, {'settings': backup_settings(cfg['backup'])}
|
||||
@@ -1,6 +1,6 @@
|
||||
"""What the modules of the web service share: the paths of the configuration and of the state linux-manager-setup writes,
|
||||
the limit of request bodies, the HTTP statuses of the failures of the server's modules, reading the configuration and
|
||||
the state, changing a section of the configuration, the state of a unit, and the log."""
|
||||
the state, changing settings of the configuration, the state of a unit, and the log."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
@@ -59,15 +59,17 @@ def unit_state(unit):
|
||||
return result.stdout.strip() if result and result.stdout.strip() else 'unknown'
|
||||
|
||||
|
||||
def section_change(name, body):
|
||||
"""Change any of the settings of the configuration's section as /backup changes its own; the section, or the HTTP
|
||||
status and the error document as a tuple."""
|
||||
settings = {option: body[option] for option in linuxmanager.SCHEMA[name] if option in body}
|
||||
def settings_change(changes):
|
||||
"""Change settings of sections of the configuration in one step, section -> {setting: value}, keeping only the
|
||||
settings of SCHEMA, validated as a whole, and run setup; the configuration, or the HTTP status and the error document
|
||||
as a tuple."""
|
||||
try:
|
||||
with linuxmanager.config_lock():
|
||||
data = linuxmanager.read_settings()
|
||||
current = data.get(name)
|
||||
data[name] = {**(current if isinstance(current, dict) else {}), **settings}
|
||||
for name, body in changes.items():
|
||||
current = data.get(name)
|
||||
data[name] = {**(current if isinstance(current, dict) else {}),
|
||||
**{option: body[option] for option in linuxmanager.SCHEMA[name] if option in body}}
|
||||
cfg = linuxmanager.with_defaults(data)
|
||||
linuxmanager.validate(cfg)
|
||||
linuxmanager.save_config(data)
|
||||
@@ -77,8 +79,15 @@ def section_change(name, body):
|
||||
return 500, {'error': f'the configuration cannot be written: {exc}'}
|
||||
except SystemExit as exc:
|
||||
return 500, {'error': str(exc.code)}
|
||||
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
|
||||
return cfg[name]
|
||||
linuxmanager.request_setup()
|
||||
return cfg
|
||||
|
||||
|
||||
def section_change(name, body):
|
||||
"""Change any of the settings of the configuration's section as /backup changes its own; the section, or the HTTP
|
||||
status and the error document as a tuple."""
|
||||
changed = settings_change({name: body})
|
||||
return changed if isinstance(changed, tuple) else changed[name]
|
||||
|
||||
|
||||
def log(message):
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"""/components: the installable components of the server, which the Manager's System tab switches."""
|
||||
|
||||
import linuxmanager
|
||||
import linuxmanager_net
|
||||
|
||||
from .common import settings_change, unit_state
|
||||
|
||||
|
||||
def router_choices(cfg):
|
||||
"""The interfaces the router may take as its internal one: the NICs but the external interface."""
|
||||
external = cfg['interfaces']['external'].strip()
|
||||
if not external and (cfg['general']['mode'] or 'manual') == 'auto':
|
||||
try:
|
||||
external, _ = linuxmanager_net.detect_interfaces(internal=False)
|
||||
except linuxmanager_net.ConfigError:
|
||||
external = ''
|
||||
return [name for name in linuxmanager_net.nics() if name != external]
|
||||
|
||||
|
||||
def listing(cfg):
|
||||
"""Each component of linuxmanager.COMPONENTS: {name, enabled, state}, state being installing or failed while its
|
||||
installation unit is, else installed or not installed; the router also has available, whether the server has an
|
||||
interface for its internal side or the router is on, the interfaces to choose from, general.mode and its current
|
||||
internal_interface, int_addr and int_gateway_ip."""
|
||||
found = []
|
||||
for name, (_, packages) in linuxmanager.COMPONENTS.items():
|
||||
unit = unit_state(f'linux-manager-install@{name}.service')
|
||||
state = {'activating': 'installing', 'active': 'installing', 'failed': 'failed'}.get(unit) or \
|
||||
('installed' if linuxmanager.packages_installed(packages) else 'not installed')
|
||||
entry = {'name': name, 'enabled': linuxmanager.component_on(cfg, name), 'state': state}
|
||||
if name == 'router':
|
||||
choices = router_choices(cfg)
|
||||
entry.update({'available': entry['enabled'] or bool(choices), 'interfaces': choices,
|
||||
'mode': cfg['general']['mode'] or 'manual',
|
||||
'internal_interface': cfg['interfaces']['internal'].strip(),
|
||||
'int_addr': cfg['local']['int_addr'].strip(),
|
||||
'int_gateway_ip': cfg['local']['int_gateway_ip'].strip()})
|
||||
found.append(entry)
|
||||
return found
|
||||
|
||||
|
||||
def components(method, path, body):
|
||||
"""Answer a /components request: the HTTP status and the JSON document.
|
||||
|
||||
GET /components {"components": [...]} (listing)
|
||||
PUT /components/<name> switch a component: {"enabled"}, for the router switched on also "internal_interface",
|
||||
"int_addr" and "int_gateway_ip" as general.mode needs them; {"components": [...]}
|
||||
|
||||
A switched-on component's packages are installed by linux-manager-setup (linux-manager-install@<name>), which a
|
||||
change starts without waiting for it; switching a component off removes no package. The configuration's validation
|
||||
refuses a change it does not allow, such as the VPN off while IKEv2, OpenVPN or WireGuard is on.
|
||||
"""
|
||||
if body == 'invalid' or (body is not None and not isinstance(body, dict)):
|
||||
return 400, {'error': 'the body must be a JSON object'}
|
||||
body = body or {}
|
||||
parts = path.strip('/').split('/')
|
||||
cfg = linuxmanager.load_config()
|
||||
if method in ('GET', 'HEAD') and parts == ['components']:
|
||||
return 200, {'components': listing(cfg)}
|
||||
if method != 'PUT' or len(parts) != 2 or parts[1] not in linuxmanager.COMPONENTS:
|
||||
return 404, {'error': f'no route {method} {path}'}
|
||||
name, enabled = parts[1], body.get('enabled')
|
||||
if not isinstance(enabled, bool):
|
||||
return 400, {'error': 'enabled must be true or false'}
|
||||
(section, setting), _ = linuxmanager.COMPONENTS[name]
|
||||
changes = {section: {setting: enabled}}
|
||||
if name == 'router' and enabled and not cfg['router']['enabled']:
|
||||
choices = router_choices(cfg)
|
||||
if not choices:
|
||||
return 409, {'error': 'the router needs a second network interface; the server has only one'}
|
||||
values = {key: body.get(key, '') for key in ('internal_interface', 'int_addr', 'int_gateway_ip')}
|
||||
if any(not isinstance(value, str) for value in values.values()):
|
||||
return 400, {'error': 'internal_interface, int_addr and int_gateway_ip must be strings'}
|
||||
if values['internal_interface'] and values['internal_interface'] not in choices:
|
||||
return 400, {'error': f'internal_interface must be one of {", ".join(choices)}'}
|
||||
if values['internal_interface']:
|
||||
changes['interfaces'] = {'internal': values['internal_interface']}
|
||||
if values['int_addr'] or values['int_gateway_ip']:
|
||||
changes['local'] = {'int_addr': values['int_addr'].strip(), 'int_gateway_ip': values['int_gateway_ip'].strip()}
|
||||
changed = settings_change(changes)
|
||||
if isinstance(changed, tuple):
|
||||
return changed
|
||||
return 200, {'components': listing(changed)}
|
||||
@@ -3,7 +3,7 @@
|
||||
import ipaddress
|
||||
|
||||
import linuxmanager
|
||||
from linuxmanager_status import established_each, run
|
||||
from linuxmanager_status import established_each
|
||||
|
||||
from .common import section
|
||||
|
||||
@@ -37,7 +37,7 @@ def site_to_site(method, path, body):
|
||||
DELETE /site-to-site/<name> remove the connection
|
||||
|
||||
A change is made holding linuxmanager.config_lock, checked as linux-manager-setup checks the configuration (400 with
|
||||
the reason), written with linuxmanager.save_config, and applied by restarting linux-manager-setup without waiting for it.
|
||||
the reason), written with linuxmanager.save_config, and applied by a run of linux-manager-setup, without waiting for it.
|
||||
"""
|
||||
if body == 'invalid' or (body is not None and not isinstance(body, dict)):
|
||||
return 400, {'error': 'the body must be a JSON object'}
|
||||
@@ -84,7 +84,7 @@ def site_to_site(method, path, body):
|
||||
return 500, {'error': f'the configuration cannot be written: {exc}'}
|
||||
except SystemExit as exc:
|
||||
return 500, {'error': str(exc.code)}
|
||||
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
|
||||
linuxmanager.request_setup()
|
||||
if method == 'DELETE':
|
||||
return 200, {'name': name, 'removed': True}
|
||||
return (201 if method == 'POST' else 200), connection_of(name, cfg['site_to_site'][name], None)
|
||||
@@ -121,7 +121,7 @@ def remote_access(state, method, path, body):
|
||||
configuration needs of the server (wireguard_server)
|
||||
PUT /remote-access/<system> change any of the settings of the system's section; answers the section
|
||||
|
||||
A change is made as /site-to-site makes one, and applied by restarting linux-manager-setup without waiting for it.
|
||||
A change is made as /site-to-site makes one, and applied by a run of linux-manager-setup, without waiting for it.
|
||||
"""
|
||||
if body == 'invalid' or (body is not None and not isinstance(body, dict)):
|
||||
return 400, {'error': 'the body must be a JSON object'}
|
||||
@@ -151,5 +151,5 @@ def remote_access(state, method, path, body):
|
||||
return 500, {'error': f'the configuration cannot be written: {exc}'}
|
||||
except SystemExit as exc:
|
||||
return 500, {'error': str(exc.code)}
|
||||
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
|
||||
linuxmanager.request_setup()
|
||||
return 200, cfg[system]
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import linuxmanager
|
||||
import linuxmanager_dns
|
||||
from linuxmanager_status import run
|
||||
|
||||
from .common import section_change, unit_state
|
||||
|
||||
@@ -30,7 +29,7 @@ def dns(method, path, query, body):
|
||||
DELETE /dns/domains/<domain>/records
|
||||
remove the manual records of name= and type=, with content= only that one
|
||||
|
||||
A change is applied by restarting linux-manager-setup without waiting for it.
|
||||
A change is applied by a run of linux-manager-setup, without waiting for it.
|
||||
"""
|
||||
if body == 'invalid' or (body is not None and not isinstance(body, dict)):
|
||||
return 400, {'error': 'the body must be a JSON object'}
|
||||
@@ -80,5 +79,5 @@ def dns(method, path, query, body):
|
||||
return 500, {'error': str(exc)}
|
||||
except SystemExit as exc:
|
||||
return 500, {'error': str(exc.code)}
|
||||
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
|
||||
linuxmanager.request_setup()
|
||||
return code, document
|
||||
@@ -18,11 +18,12 @@ import linuxmanager_sites
|
||||
from .auth import auth, auth_wait, refusal
|
||||
from .backup import backup
|
||||
from .common import BODY_LIMIT, CONFIG_FILE, current, log, read_json, section
|
||||
from .components import components
|
||||
from .connectivity import remote_access, site_to_site
|
||||
from .dns import dns
|
||||
from .identities import account, groups, service_accounts, users
|
||||
from .logs import logs
|
||||
from .https import https_settings
|
||||
from .https import PATHS as HTTPS_PATHS, https
|
||||
from .metrics import metrics_history, metrics_settings
|
||||
from .pki import PUBLISHED, ca
|
||||
from .shell import EDITOR_BODY_LIMIT, shell, shell_editor, shell_passkey, shell_ticket
|
||||
@@ -65,14 +66,14 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if self.command not in ('GET', 'HEAD'):
|
||||
self.close_connection = True
|
||||
directory = next((name for name in ('users', 'service-accounts', 'groups', 'account', 'site-to-site', 'backup',
|
||||
'ca', 'shell', 'remote-access', 'logs', 'sites', 'dns')
|
||||
'ca', 'shell', 'remote-access', 'logs', 'sites', 'dns', 'components')
|
||||
if path == f'/{name}' or path.startswith(f'/{name}/')), None)
|
||||
protected = path in ('/status/full', '/config', '/metrics/history', '/metrics/settings', '/https/settings',
|
||||
protected = path in ('/status/full', '/config', '/metrics/history', '/metrics/settings', *HTTPS_PATHS,
|
||||
'/postgresql') or \
|
||||
directory is not None
|
||||
signing = path in ('/auth', '/auth/passkey', '/auth/passkey/complete', '/auth/refresh', '/auth/logout')
|
||||
oidc = (path == '/.well-known/openid-configuration' or path.startswith('/oidc/')) and \
|
||||
self.server.server_address[0] == linuxmanager_net.LOOPBACK
|
||||
self.client_address[0] == linuxmanager_net.LOOPBACK and self.headers.get('X-Forwarded-Proto') == 'https'
|
||||
files = SITE_FILES.match(path) if directory == 'sites' else None
|
||||
query = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query)
|
||||
state = current() if protected or signing else {}
|
||||
@@ -115,8 +116,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
elif path == '/metrics/settings':
|
||||
code, document = metrics_settings(self.command, payload)
|
||||
body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json'
|
||||
elif path == '/https/settings':
|
||||
code, document = https_settings(self.command, payload)
|
||||
elif path in HTTPS_PATHS:
|
||||
code, document = https(self.command, path, payload)
|
||||
body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json'
|
||||
elif directory == 'shell' and (path, self.command) == ('/shell', 'GET'):
|
||||
return shell(self, claims.get('sub'))
|
||||
@@ -160,6 +161,9 @@ class Handler(BaseHTTPRequestHandler):
|
||||
elif directory == 'dns':
|
||||
code, document = dns(self.command, path, query, payload)
|
||||
body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json'
|
||||
elif directory == 'components':
|
||||
code, document = components(self.command, path, payload)
|
||||
body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json'
|
||||
elif directory == 'service-accounts':
|
||||
code, document = service_accounts(self.command, path, payload)
|
||||
body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json'
|
||||
|
||||
@@ -1,33 +1,82 @@
|
||||
"""/https/settings: the settings of HTTPS, of which the API changes the CA of Caddy's certificates."""
|
||||
"""/https: the settings of HTTPS and the server's own HTTPS certificate."""
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
|
||||
import ldap
|
||||
|
||||
import linuxmanager
|
||||
import linuxmanager_pki
|
||||
|
||||
from .common import section_change
|
||||
from .common import PKI_STATUS, section_change
|
||||
|
||||
#: The settings of the https section PUT /https/settings changes.
|
||||
CHANGEABLE = ('acme_staging',)
|
||||
CHANGEABLE = ('acme_staging', 'certificate', 'self_signed_days', 'acme_provider', 'acme_url', 'acme_eab_key_id',
|
||||
'acme_eab_mac_key', 'zerossl_api_key')
|
||||
|
||||
#: The secrets of the https section, which the answers give as <name>_set instead.
|
||||
SECRETS = ('acme_eab_mac_key', 'zerossl_api_key')
|
||||
|
||||
#: The paths of /https.
|
||||
PATHS = ('/https/settings', '/https/csr', '/https/certificate', '/https/pfx')
|
||||
|
||||
|
||||
def https_settings(method, body):
|
||||
"""Answer a /https/settings request: the HTTP status and the JSON document.
|
||||
def shown(settings):
|
||||
"""The https section without its secrets, each replaced by whether it is set."""
|
||||
return {**{key: value for key, value in settings.items() if key not in SECRETS},
|
||||
**{f'{key}_set': bool(settings[key]) for key in SECRETS}}
|
||||
|
||||
GET /https/settings {"settings"}: the https section
|
||||
PUT /https/settings change acme_staging; the other settings of the section are changed on the server with
|
||||
linux-manager-config-edit, and a body naming one is 400
|
||||
|
||||
A change is applied by restarting linux-manager-setup without waiting for it.
|
||||
def https(method, path, body):
|
||||
"""Answer a /https request: the HTTP status and the JSON document.
|
||||
|
||||
GET /https/settings {"settings", "certificate"}: the https section, its secrets as <name>_set, and the
|
||||
server's HTTPS certificate (linuxmanager_pki.https_status)
|
||||
PUT /https/settings change any of CHANGEABLE; the other settings of the section are changed on the server
|
||||
with linux-manager-config-edit, and a body naming one is 400
|
||||
POST /https/csr make a key and a CSR for wan.local_fqdn: {"csr"}
|
||||
PUT /https/certificate take the certificate another CA signed for the CSR, PEM with its chain: {"certificate"}
|
||||
PUT /https/pfx take a PKCS#12 file of another CA's certificate: {"pfx" in base64, "password"}
|
||||
|
||||
A change is applied by a run of linux-manager-setup, without waiting for it.
|
||||
"""
|
||||
if body == 'invalid' or (body is not None and not isinstance(body, dict)):
|
||||
return 400, {'error': 'the body must be a JSON object'}
|
||||
if method in ('GET', 'HEAD'):
|
||||
try:
|
||||
return 200, {'settings': linuxmanager.load_config()['https']}
|
||||
except SystemExit as exc:
|
||||
return 500, {'error': str(exc.code)}
|
||||
if method != 'PUT':
|
||||
return 404, {'error': f'no route {method} /https/settings'}
|
||||
others = sorted(set(body or {}) - set(CHANGEABLE))
|
||||
if others:
|
||||
return 400, {'error': f'https.{", https.".join(others)}: changed on the server with linux-manager-config-edit only'}
|
||||
changed = section_change('https', body or {})
|
||||
return changed if isinstance(changed, tuple) else (200, {'settings': changed})
|
||||
body = body or {}
|
||||
try:
|
||||
cfg = linuxmanager.load_config()
|
||||
if path == '/https/settings' and method in ('GET', 'HEAD'):
|
||||
return 200, {'settings': shown(cfg['https']), 'certificate': linuxmanager_pki.https_status(cfg)}
|
||||
if path == '/https/settings' and method == 'PUT':
|
||||
others = sorted(set(body) - set(CHANGEABLE))
|
||||
if others:
|
||||
return 400, {'error': f'https.{", https.".join(others)}: changed on the server with '
|
||||
'linux-manager-config-edit only'}
|
||||
if 'certificate' in body and body['certificate'] not in linuxmanager.HTTPS_CERTIFICATES:
|
||||
return 400, {'error': f'https.certificate must be one of {", ".join(linuxmanager.HTTPS_CERTIFICATES)}'}
|
||||
changed = section_change('https', body)
|
||||
return changed if isinstance(changed, tuple) else (200, {'settings': shown(changed)})
|
||||
with linuxmanager_pki.locked():
|
||||
if (path, method) == ('/https/csr', 'POST'):
|
||||
return 200, linuxmanager_pki.https_csr(cfg)
|
||||
if (path, method) == ('/https/certificate', 'PUT'):
|
||||
document = linuxmanager_pki.import_https_certificate(cfg, body.get('certificate'))
|
||||
elif (path, method) == ('/https/pfx', 'PUT'):
|
||||
try:
|
||||
data = base64.b64decode(body.get('pfx') or '', validate=True)
|
||||
except (binascii.Error, TypeError):
|
||||
return 400, {'error': 'pfx must be a PKCS#12 file in base64'}
|
||||
password = body.get('password')
|
||||
if password is not None and not isinstance(password, str):
|
||||
return 400, {'error': 'password must be a string'}
|
||||
document = linuxmanager_pki.import_https_pfx(cfg, data, password)
|
||||
else:
|
||||
return 404, {'error': f'no route {method} {path}'}
|
||||
except linuxmanager_pki.Failure as failure:
|
||||
return PKI_STATUS.get(failure.status, 500), {'error': str(failure)}
|
||||
except ldap.LDAPError as exc:
|
||||
return 500, {'error': f'the directory, which holds the certificate, failed: {exc}'}
|
||||
except SystemExit as exc:
|
||||
return 500, {'error': str(exc.code)}
|
||||
linuxmanager.request_setup()
|
||||
return 200, document
|
||||
@@ -7,7 +7,7 @@ import linuxmanager
|
||||
|
||||
#: The units whose journal /logs/journal shows, besides the whole journal: the package's own and the services it runs.
|
||||
JOURNAL_UNITS = ('linux-manager-setup', 'linux-manager-web', 'linux-manager-metrics', 'linux-manager-pki', 'linux-manager-backup',
|
||||
'linux-manager-caddy', 'linux-manager-ui', 'caddy', 'slapd', 'nslcd', 'postgresql', 'strongswan',
|
||||
'linux-manager-ui', 'caddy', 'slapd', 'nslcd', 'postgresql', 'strongswan',
|
||||
'wg-quick@wg0', 'openvpn-server@linux-manager', 'ssh', 'linux-manager-resolver', 'linux-manager-webdav', 'pdns')
|
||||
|
||||
#: The most lines /logs answers, the number it answers without lines, and the most bytes it reads from the end of a file.
|
||||
|
||||
@@ -35,7 +35,7 @@ def metrics_settings(method, body):
|
||||
PUT /metrics/settings change any of the settings of the metrics section; an empty or absent otlp_password keeps
|
||||
the current secret, and an empty otlp_username removes it
|
||||
|
||||
A change is applied by restarting linux-manager-setup without waiting for it.
|
||||
A change is applied by a run of linux-manager-setup, without waiting for it.
|
||||
"""
|
||||
if body == 'invalid' or (body is not None and not isinstance(body, dict)):
|
||||
return 400, {'error': 'the body must be a JSON object'}
|
||||
|
||||
@@ -4,7 +4,6 @@ import ldap
|
||||
|
||||
import linuxmanager
|
||||
import linuxmanager_pki
|
||||
from linuxmanager_status import run
|
||||
|
||||
from .common import PKI_STATUS
|
||||
|
||||
@@ -38,7 +37,7 @@ def ca(method, path, body):
|
||||
answers {"upstream", "expires"}
|
||||
|
||||
A change of the settings is made as /site-to-site makes one; it, a revoked router certificate, an imported root
|
||||
or issuing CA certificate and a new Simple CA token are applied by restarting linux-manager-setup without waiting
|
||||
or issuing CA certificate and a new Simple CA token are applied by a run of linux-manager-setup, without waiting
|
||||
for it.
|
||||
"""
|
||||
if body == 'invalid' or (body is not None and not isinstance(body, dict)):
|
||||
@@ -66,7 +65,7 @@ def ca(method, path, body):
|
||||
with linuxmanager_pki.directory() as connection:
|
||||
linuxmanager_pki.check_source(cfg, linuxmanager_pki.authority(connection, 'root'))
|
||||
linuxmanager.save_config(data)
|
||||
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
|
||||
linuxmanager.request_setup()
|
||||
return 200, {'settings': cfg['pki'], 'templates': linuxmanager.pki_templates(cfg)}
|
||||
with linuxmanager_pki.locked():
|
||||
if route == ('POST', 'certificates'):
|
||||
@@ -98,5 +97,5 @@ def ca(method, path, body):
|
||||
except SystemExit as exc:
|
||||
return 500, {'error': str(exc.code)}
|
||||
if route[1] in ('issuing', 'root') or document.get('reissue'):
|
||||
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
|
||||
linuxmanager.request_setup()
|
||||
return 200, document
|
||||
@@ -10,7 +10,6 @@ import ldap
|
||||
|
||||
import linuxmanager
|
||||
import linuxmanager_sites
|
||||
from linuxmanager_status import run
|
||||
|
||||
from .common import MIB, SITE_STATUS, section_change
|
||||
|
||||
@@ -31,7 +30,7 @@ def sites(method, path, query, body):
|
||||
PUT /sites/<name> change any of the settings of POST but name; an empty or absent private_key keeps the key
|
||||
DELETE /sites/<name> remove the site, with content=true also its folder
|
||||
|
||||
A change is applied by restarting linux-manager-setup without waiting for it.
|
||||
A change is applied by a run of linux-manager-setup, without waiting for it.
|
||||
"""
|
||||
if body == 'invalid' or (body is not None and not isinstance(body, dict)):
|
||||
return 400, {'error': 'the body must be a JSON object'}
|
||||
@@ -68,7 +67,7 @@ def sites(method, path, query, body):
|
||||
return 500, {'error': f'the site cannot be changed: {exc}'}
|
||||
except SystemExit as exc:
|
||||
return 500, {'error': str(exc.code)}
|
||||
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
|
||||
linuxmanager.request_setup()
|
||||
return code, document
|
||||
|
||||
|
||||
|
||||
@@ -232,7 +232,7 @@ def postgresql_databases():
|
||||
|
||||
def details(state):
|
||||
"""What /config shows: the configuration without its secrets, and what the server resolved and runs; caddy is the
|
||||
installed Caddy, {version, source, service}, service the state of caddy.service, null when it is not installed; oidc
|
||||
installed Caddy, {version, service}, service the state of caddy.service, null when it is not installed; oidc
|
||||
is {enabled, issuer} of the OpenID Provider, issuer null while it is disabled; docker.installed is whether
|
||||
docker.service is installed, as docker_status finds it."""
|
||||
configuration = state.get('configuration', {})
|
||||
@@ -252,9 +252,7 @@ def details(state):
|
||||
'rules': lines_of('iptables', '-S', 'LINUX-MANAGER-DOCKER'),
|
||||
},
|
||||
'postgresql': postgresql_configuration(),
|
||||
# Caddy is upstream's once its repository is configured (linux-manager-caddy).
|
||||
'caddy': {'version': caddy, 'source': 'upstream' if linuxmanager.CADDY_APT_SOURCE.is_file() else 'ubuntu',
|
||||
'service': unit_state('caddy.service')} if caddy else None,
|
||||
'caddy': {'version': caddy, 'service': unit_state('caddy.service')} if caddy else None,
|
||||
'oidc': {'enabled': oidc, 'issuer': linuxmanager.oidc_issuer(configuration) if oidc else None},
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@ python3-psycopg to keep the sessions; its settings and its listening loop are in
|
||||
linuxmanager_ui.
|
||||
|
||||
Pages:
|
||||
/api/info the version of this package and the server it manages, as JSON
|
||||
/api/info the URL of the status page of the server it manages, the port and listen of the
|
||||
manager's plain HTTP site, and with a session the version of this package, as JSON
|
||||
/api/session POST signs in through the server's /auth with {"name", "password", "code"?},
|
||||
GET answers the signed-in user, DELETE signs out
|
||||
/api/session/passkey
|
||||
@@ -47,9 +48,9 @@ and logging each failure. Then it listens. Its unit starts it only once wait-for
|
||||
libpq in the linker cache, where psycopg looks it up.
|
||||
|
||||
The service needs nothing else to start and does not end on its own. Every DISCOVERY_SECONDS it
|
||||
works out where to listen, bind or the interfaces listen names, and runs a server at each address
|
||||
(linuxmanager_ui.serve). Every request
|
||||
reads the settings when it is made.
|
||||
works out where to listen, bind, or on the server the loopback port Caddy calls
|
||||
(linuxmanager_ui.listen), and runs a server at each address (linuxmanager_ui.serve). Every
|
||||
request reads the settings when it is made.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -77,11 +78,9 @@ import requests
|
||||
import urllib3
|
||||
|
||||
import linuxmanager_ui
|
||||
from linuxmanager_net import LOOPBACK
|
||||
from linuxmanager_ui import DATABASE, DATABASE_SECRET, ROUTER_CONFIG_FILE
|
||||
|
||||
#: The address a proxy on this host calls from.
|
||||
LOOPBACK = '127.0.0.1'
|
||||
|
||||
CONFIG_FILE = linuxmanager_ui.CONFIG_FILE
|
||||
WEB_DIR = '/usr/share/linux-manager/manager/web'
|
||||
DOCS_DIR = '/usr/share/linux-manager/manager/docs'
|
||||
@@ -792,8 +791,14 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.close_connection = True
|
||||
if route == '/api/info':
|
||||
https = self.proxied() and self.headers.get('X-Forwarded-Proto') == 'https'
|
||||
status = linuxmanager_ui.status_url(CONFIG_FILE, self.headers.get('Host', ''), self.server.server_address[0], https)
|
||||
body = json.dumps({'version': package_version(), 'status_url': status or None}).encode()
|
||||
status = linuxmanager_ui.status_url(CONFIG_FILE, self.headers.get('Host', ''), https)
|
||||
# The version is not told to a browser that has not signed in.
|
||||
try:
|
||||
signed_in = session(settings(), self.session_id(), self.client()) is not None
|
||||
except (Unavailable, psycopg.Error):
|
||||
signed_in = False
|
||||
body = json.dumps({'version': package_version() if signed_in else None, 'status_url': status or None,
|
||||
'manager': linuxmanager_ui.plain_site(CONFIG_FILE)}).encode()
|
||||
code, kind = 200, 'application/json'
|
||||
elif route == '/api/shell' and self.command == 'GET' and self.headers.get('Upgrade', '').lower() == 'websocket':
|
||||
try:
|
||||
|
||||
@@ -23,9 +23,10 @@ prometheus_client, with OpenTelemetry semantic convention names in their Prometh
|
||||
OpenTelemetry Collector's prometheus receiver. It needs HTTP Basic authentication as the service
|
||||
account metrics.service_account names, which linux-manager-setup keeps with the password in
|
||||
/etc/linux-manager/metrics.secret, checked with a bind to the server's directory, so failed attempts
|
||||
lock the account as for any user. The service listens on the interfaces metrics.listen
|
||||
names and on the loopback address, where Caddy serves it over HTTPS at metrics.https_port; the
|
||||
address of a call through Caddy is the last entry of its X-Forwarded-For header.
|
||||
lock the account as for any user. The service listens on the loopback address only, behind
|
||||
Caddy, which serves it over plain HTTP at metrics.port, on the interfaces metrics.listen names
|
||||
in the firewall, and over HTTPS at metrics.https_port; the address of a call through Caddy is
|
||||
the last entry of its X-Forwarded-For header.
|
||||
|
||||
When metrics.otlp_endpoint is set, every sample is also pushed there as an OTLP/HTTP JSON
|
||||
ExportMetricsServiceRequest, with HTTP Basic authentication when metrics.otlp_username is set.
|
||||
@@ -431,19 +432,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
|
||||
def wanted():
|
||||
"""Where the service listens: the addresses of the interfaces metrics.listen names and LOOPBACK, at metrics.port."""
|
||||
configuration = read_json(CONFIG_FILE)
|
||||
metrics = section(configuration, 'metrics')
|
||||
defaults = linuxmanager.SCHEMA['metrics']
|
||||
if metrics.get('enabled', defaults['enabled']) is False:
|
||||
"""Where the service listens: METRICS_LOOPBACK_PORT of LOOPBACK, where Caddy calls it, while metrics are enabled."""
|
||||
metrics = section(read_json(CONFIG_FILE), 'metrics')
|
||||
if metrics.get('enabled', linuxmanager.SCHEMA['metrics']['enabled']) is False:
|
||||
return [], 'metrics are disabled in the configuration'
|
||||
port = metrics.get('port', defaults['port'])
|
||||
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
|
||||
port = defaults['port']
|
||||
addresses = linuxmanager_net.listen_addresses(configuration, metrics.get('listen', defaults['listen']))
|
||||
if not addresses:
|
||||
return [], 'the addresses to listen on are not known yet'
|
||||
return [(address, port) for address in [*addresses, linuxmanager_net.LOOPBACK]], ''
|
||||
return [(linuxmanager_net.LOOPBACK, linuxmanager_net.METRICS_LOOPBACK_PORT)], ''
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -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)
|
||||
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/python3
|
||||
"""Serve the status of the server on its internal address, its external address or both, as web.listen sets.
|
||||
"""Serve the status of the server on the loopback address, behind Caddy, which serves web.port over plain HTTP and
|
||||
https.web_port over HTTPS.
|
||||
|
||||
Run by linux-manager-web.service. Users are managed with linuxmanager_users, the module that
|
||||
linux-manager-user uses too.
|
||||
@@ -12,11 +13,9 @@ logging each failure. Then it listens. Its unit starts it only once wait-for-lib
|
||||
in the linker cache, where psycopg looks it up.
|
||||
|
||||
The service needs nothing else to start and does not end on its own. Every DISCOVERY_SECONDS it
|
||||
works out from /etc/linux-manager/linux-manager.json the addresses of the interfaces web.listen names,
|
||||
internal, external or both, as general.mode directs, with web.port and web.enabled
|
||||
(linuxmanager_net.web_listen), and runs a server on each (linuxmanager_serve.serve): it starts them,
|
||||
moves them when an address or the port changes, and stops them while the service is disabled or
|
||||
no address is known. Every request reads what it needs when it is made: the signing
|
||||
reads web.enabled from /etc/linux-manager/linux-manager.json and listens on
|
||||
linuxmanager_net.WEB_LOOPBACK_PORT of the loopback address while it is on (linuxmanager_net.web_listen,
|
||||
linuxmanager_serve.serve). Every request reads what it needs when it is made: the signing
|
||||
key, the configuration, and the features of the server and the facts shown by /config from
|
||||
/run/linux-manager/web.json, which linux-manager-setup writes. Before setup has written that file
|
||||
the server has no features, and /config shows no configuration or interfaces.
|
||||
@@ -43,9 +42,6 @@ from linuxmanager_web.shell import editor_listen
|
||||
#: Seconds between two attempts of the initialization.
|
||||
INIT_RETRY_SECONDS = 15
|
||||
|
||||
#: The port when web.port is not set.
|
||||
DEFAULT_PORT = 7081
|
||||
|
||||
#: Seconds between two discoveries of where the service should listen.
|
||||
DISCOVERY_SECONDS = 30
|
||||
|
||||
@@ -88,8 +84,8 @@ def main():
|
||||
initialize()
|
||||
threading.Thread(target=editor_listen, name='editor socket', daemon=True).start()
|
||||
try:
|
||||
linuxmanager_serve.serve(lambda: linuxmanager_net.web_listen(read_json(CONFIG_FILE), DEFAULT_PORT), Handler, log,
|
||||
DISCOVERY_SECONDS)
|
||||
linuxmanager_serve.serve(lambda: linuxmanager_net.web_listen(read_json(CONFIG_FILE)), Handler, log,
|
||||
DISCOVERY_SECONDS)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
return 0
|
||||
|
||||
Reference in new issue
Block a user