feature: HTTPS is always on, for wan.local_fqdn or, without it, the host name and its mDNS name, optionally also for the server's addresses, and the redirect to HTTPS covers the status page by name.
Release / release (push) Successful in 23s
Release / release (push) Successful in 23s
This commit is contained in:
1 parent
7efacfa3bb
commit
64c3ae4c36
18 files changed
+317
-187
No files matched your search
@@ -43,7 +43,6 @@ 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')),
|
||||
|
||||
@@ -12,6 +12,7 @@ import os
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -79,7 +80,7 @@ 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,
|
||||
'https': {'email': '', 'web_port': 7444, 'manager_port': 7443, 'ip_sans': False,
|
||||
'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': ''},
|
||||
@@ -172,8 +173,8 @@ UPLOAD_MAX_MB = 10240
|
||||
|
||||
#: Settings that no longer exist, section -> options, left out when the file is read so that a file of an earlier
|
||||
#: version loads: the name server is wan.local_fqdn, a site chooses the address of its records, and the CA certificates
|
||||
#: and CRLs are always published.
|
||||
RETIRED = {'dns': ('nameserver', 'addresses'), 'pki': ('publish',)}
|
||||
#: and CRLs are always published, and HTTPS is always on.
|
||||
RETIRED = {'dns': ('nameserver', 'addresses'), 'pki': ('publish',), 'https': ('enabled',)}
|
||||
|
||||
#: The shortest and the longest dns.ttl, in seconds.
|
||||
DNS_TTL_RANGE = (60, 86400)
|
||||
@@ -684,19 +685,16 @@ def validate(cfg):
|
||||
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, 'https', 'certificate') == 'acme' and not _get(cfg, 'wan', 'local_fqdn'):
|
||||
raise ConfigError('https.certificate: an ACME CA issues the certificate of wan.local_fqdn, which is not set')
|
||||
|
||||
if _get(cfg, 'oidc', 'enabled') and not (_get(cfg, 'web', 'enabled') and _get(cfg, 'https', 'enabled')
|
||||
and _get(cfg, 'wan', 'local_fqdn')):
|
||||
if _get(cfg, 'oidc', 'enabled') and not _get(cfg, 'web', 'enabled'):
|
||||
raise ConfigError('oidc.enabled: the OpenID Provider is the web service served by Caddy at '
|
||||
'https://<wan.local_fqdn>:<https.web_port>, which needs web.enabled, https.enabled and '
|
||||
'wan.local_fqdn')
|
||||
'https://<HTTPS name>:<https.web_port>, which needs web.enabled')
|
||||
|
||||
upload_max = _get(cfg, 'sites', 'upload_max_mb')
|
||||
if not 1 <= upload_max <= UPLOAD_MAX_MB:
|
||||
raise ConfigError(f'sites.upload_max_mb: {upload_max} is not between 1 and {UPLOAD_MAX_MB}')
|
||||
if _get(cfg, 'sites', 'webdav') and not (_get(cfg, 'https', 'enabled') and _get(cfg, 'wan', 'local_fqdn')):
|
||||
raise ConfigError('sites.webdav: WebDAV is served by Caddy at https://<wan.local_fqdn>:<sites.webdav_port>, '
|
||||
'which needs https.enabled and wan.local_fqdn')
|
||||
|
||||
_check_address(_get(cfg, 'wan', 'public_address'), 'wan.public_address')
|
||||
dns = cfg['dns']
|
||||
@@ -805,8 +803,6 @@ def validate(cfg):
|
||||
raise ConfigError(f'{prefix}.templates: {template!r} is not a template')
|
||||
if template in ROUTER_TEMPLATES:
|
||||
raise ConfigError(f'{prefix}.templates: {template} is issued by the P2S CA only')
|
||||
if authority['acme'] and not _get(cfg, 'https', 'enabled'):
|
||||
raise ConfigError(f'{prefix}.acme: the ACME server is Caddy\'s, which needs https.enabled')
|
||||
|
||||
taken = {web_port: 'web.port', ACME_HTTP_PORT: 'the HTTP challenge',
|
||||
https_ports[0]: 'https.web_port', https_ports[1]: 'https.manager_port'}
|
||||
@@ -898,9 +894,7 @@ 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(':')
|
||||
caddy_ports = (web_port, manager_port(), _get(cfg, 'metrics', 'port'),
|
||||
*((ACME_HTTP_PORT, *https_ports)
|
||||
if _get(cfg, 'https', 'enabled') else ()))
|
||||
caddy_ports = (web_port, manager_port(), _get(cfg, 'metrics', 'port'), ACME_HTTP_PORT, *https_ports)
|
||||
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')
|
||||
@@ -973,9 +967,10 @@ def manager_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."""
|
||||
"""The issuer of the OpenID Provider: the web service's HTTPS site on the first HTTPS name, without the port when it
|
||||
is HTTPS_DEFAULT_PORT."""
|
||||
port = _get(cfg, 'https', 'web_port')
|
||||
return f'https://{_get(cfg, "wan", "local_fqdn")}' + ('' if port == HTTPS_DEFAULT_PORT else f':{port}')
|
||||
return f'https://{https_names(cfg)[0]}' + ('' if port == HTTPS_DEFAULT_PORT else f':{port}')
|
||||
|
||||
|
||||
def resolve_psk(connection, name):
|
||||
@@ -1177,7 +1172,9 @@ def build_context(cfg, public_ip=None):
|
||||
'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_names': https_names(cfg),
|
||||
'https_ips': https_addresses(cfg, local_addrs, int_addr),
|
||||
'mdns': not local_fqdn,
|
||||
'https_email': _get(cfg, 'https', 'email'),
|
||||
'https_certificate': _get(cfg, 'https', 'certificate'),
|
||||
'https_acme_provider': _get(cfg, 'https', 'acme_provider'),
|
||||
@@ -1241,9 +1238,30 @@ def vpn_pools(ctx):
|
||||
(wg_ready(ctx), ctx['wg_network'])) if ready]
|
||||
|
||||
|
||||
def https_ready(ctx):
|
||||
"""Caddy serves HTTPS once it is enabled and wan.local_fqdn names the certificate."""
|
||||
return bool(ctx['https_enabled'] and ctx['local_fqdn'])
|
||||
def https_names(cfg):
|
||||
"""The names of the server's HTTPS certificate and sites: wan.local_fqdn alone when it is set, else the host name
|
||||
and <host name>.local, which Avahi announces with mDNS."""
|
||||
fqdn = _get(cfg, 'wan', 'local_fqdn').lower()
|
||||
if fqdn:
|
||||
return [fqdn]
|
||||
host = socket.gethostname().split('.')[0].lower()
|
||||
return [host, f'{host}.local']
|
||||
|
||||
|
||||
def https_addresses(cfg, local_addrs, int_addr):
|
||||
"""The IP addresses of the server's HTTPS certificate and sites while https.ip_sans is on: those of its interfaces
|
||||
and wan.public_address, without link-local ones; [] while it is off."""
|
||||
if not _get(cfg, 'https', 'ip_sans'):
|
||||
return []
|
||||
found = []
|
||||
for value in (*local_addrs, int_addr, _get(cfg, 'wan', 'public_address')):
|
||||
try:
|
||||
address = ipaddress.ip_address(str(value).split('/')[0])
|
||||
except ValueError:
|
||||
continue
|
||||
if not address.is_link_local and str(address) not in found:
|
||||
found.append(str(address))
|
||||
return found
|
||||
|
||||
|
||||
def metrics_ready(ctx):
|
||||
@@ -1252,8 +1270,8 @@ def metrics_ready(ctx):
|
||||
|
||||
|
||||
def webdav_ready(ctx):
|
||||
"""WebDAV of the sites' folders is served by Caddy, on the server's own name, while it is on and HTTPS is ready."""
|
||||
return bool(ctx['webdav_enabled'] and https_ready(ctx))
|
||||
"""WebDAV of the sites' folders is served by Caddy, on the server's HTTPS names, while it is on."""
|
||||
return bool(ctx['webdav_enabled'])
|
||||
|
||||
|
||||
def packages_installed(packages):
|
||||
|
||||
@@ -592,11 +592,14 @@ 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 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."""
|
||||
server certificate names wan.local_fqdn, the HTTPS certificate its HTTPS names and addresses (https_sans), and the
|
||||
site-to-site certificate wan.local_fqdn and 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 in ('vpn-server', 'https'):
|
||||
if name == 'https':
|
||||
return https_sans(ctx)[0], https_sans(ctx)
|
||||
if name == 'vpn-server':
|
||||
return fqdn, [fqdn]
|
||||
names = [fqdn]
|
||||
for connection in ctx['connections']:
|
||||
@@ -620,7 +623,7 @@ def ensure_router_cert(connection, cfg, ctx, name, urls):
|
||||
return
|
||||
subject, sans = identities
|
||||
current = holders(connection, ca, router_condition(name))
|
||||
wanted = {f'IP:{value}' if is_address(value) else f'DNS:{value.lower()}' for value in sans}
|
||||
wanted = san_set(sans)
|
||||
if current:
|
||||
_, cert, _ = current[0]
|
||||
if not renewal_due(cert) and issued_by(cert, issuer['cert']) and common_name(cert) == subject and \
|
||||
@@ -916,10 +919,21 @@ def chain_pem(chain):
|
||||
return b''.join(cert_pem(cert) for cert in chain)
|
||||
|
||||
|
||||
def https_sans(ctx):
|
||||
"""The subject alternative names of the server's HTTPS certificate, the first its common name: its HTTPS names
|
||||
(linuxmanager.https_names) and, while https.ip_sans is on, its addresses (linuxmanager.https_addresses)."""
|
||||
return [*ctx['https_names'], *ctx['https_ips']]
|
||||
|
||||
|
||||
def san_set(values):
|
||||
"""The SAN values of a certificate (san_values) that names the DNS names and IP addresses of values name."""
|
||||
return {f'IP:{value}' if is_address(value) else f'DNS:{value.lower()}' for value in values}
|
||||
|
||||
|
||||
def served_certificate(connection, cfg):
|
||||
"""What Caddy serves for wan.local_fqdn: (served, chain, key), served being https.certificate, or self-signed while
|
||||
"""What Caddy serves for the HTTPS names: (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()
|
||||
source, fqdn = cfg['https']['certificate'], linuxmanager.https_names(cfg)[0]
|
||||
if source == 'acme':
|
||||
return 'acme', [], None
|
||||
if source == 'ca':
|
||||
@@ -935,22 +949,25 @@ def served_certificate(connection, cfg):
|
||||
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:
|
||||
def ensure_host_cert(connection, cfg, ctx):
|
||||
"""Make the self-signed certificate of the HTTPS names and addresses (https_sans) 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
|
||||
other names; the notices."""
|
||||
source, sans = cfg['https']['certificate'], https_sans(ctx)
|
||||
fqdn = sans[0]
|
||||
if source == 'acme':
|
||||
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:
|
||||
if current is None or renewal_due(current) or not usable(current, fqdn) or common_name(current) != fqdn or \
|
||||
set(san_values(current)) != san_set(sans):
|
||||
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'})))
|
||||
leaf_extensions(cfg, template, general_names(sans, {'dns', 'ip'})))
|
||||
update_host(connection, {'linuxManagerCertificateChain': cert_pem(cert), 'linuxManagerPrivateKey': key_pem(key),
|
||||
'linuxManagerKind': b'self-signed'})
|
||||
if source == 'self-signed':
|
||||
@@ -961,7 +978,7 @@ def ensure_host_cert(connection, cfg):
|
||||
|
||||
|
||||
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."""
|
||||
"""The PEM chain and key Caddy serves for the HTTPS names, 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'):
|
||||
@@ -988,14 +1005,13 @@ def https_status(cfg):
|
||||
|
||||
|
||||
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)
|
||||
"""Make a key and a CSR for the HTTPS names (linuxmanager.https_names), to be signed by another CA, replacing a
|
||||
pending one: {csr} in PEM."""
|
||||
names = linuxmanager.https_names(cfg)
|
||||
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)
|
||||
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, names[0])]))
|
||||
.add_extension(x509.SubjectAlternativeName(general_names(names, {'dns', 'ip'})), False)
|
||||
.sign(key, digest(key)))
|
||||
pem = request.public_bytes(serialization.Encoding.PEM)
|
||||
with directory() as connection:
|
||||
@@ -1005,8 +1021,8 @@ def https_csr(cfg):
|
||||
|
||||
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()
|
||||
and name the first HTTPS name (linuxmanager.https_names); {subject, issuer, expires}."""
|
||||
fqdn = linuxmanager.https_names(cfg)[0]
|
||||
if cfg['https']['certificate'] != 'external':
|
||||
raise Failure('https.certificate is not external', 4)
|
||||
cert = chain[0]
|
||||
@@ -1160,11 +1176,11 @@ def provision(cfg, ctx):
|
||||
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'
|
||||
https_ca = cfg['https']['certificate'] == 'ca'
|
||||
for name in ROUTER_CERTS:
|
||||
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))
|
||||
notices.extend(ensure_host_cert(connection, cfg, ctx))
|
||||
publish(connection)
|
||||
p2s = authority(connection, 'p2s')
|
||||
missing = connection.search_s(linuxmanager_ldap.USERS, ldap.SCOPE_ONELEVEL,
|
||||
@@ -1589,7 +1605,7 @@ def maintain(cfg):
|
||||
|
||||
def acme_url(cfg, name):
|
||||
"""The ACME directory of an issuing CA served by Caddy's ACME server."""
|
||||
return f'https://{cfg["wan"]["local_fqdn"].strip()}:{cfg["https"]["web_port"]}/acme/{name}/directory'
|
||||
return f'https://{linuxmanager.https_names(cfg)[0]}:{cfg["https"]["web_port"]}/acme/{name}/directory'
|
||||
|
||||
|
||||
def status(cfg):
|
||||
@@ -1691,7 +1707,7 @@ def status(cfg):
|
||||
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 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')
|
||||
|
||||
@@ -11,7 +11,7 @@ import linuxmanager_pki
|
||||
from .common import PKI_STATUS, section_change
|
||||
|
||||
#: The settings of the https section PUT /https/settings changes.
|
||||
CHANGEABLE = ('acme_staging', 'certificate', 'self_signed_days', 'acme_provider', 'acme_url', 'acme_eab_key_id',
|
||||
CHANGEABLE = ('acme_staging', 'certificate', 'self_signed_days', 'ip_sans', '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.
|
||||
@@ -34,7 +34,7 @@ def https(method, path, body):
|
||||
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"}
|
||||
POST /https/csr make a key and a CSR for the HTTPS names: {"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"}
|
||||
|
||||
|
||||
@@ -80,9 +80,15 @@ 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.
|
||||
#: The certificate and key of the HTTPS names Caddy serves when they come from no ACME CA.
|
||||
CADDY_HTTPS_DIR = pathlib.Path('/etc/caddy/linux-manager-https')
|
||||
|
||||
#: The units of Avahi, which announces <host name>.local with mDNS while wan.local_fqdn is not set.
|
||||
AVAHI_UNITS = ('avahi-daemon.socket', 'avahi-daemon.service')
|
||||
|
||||
#: The UDP port of mDNS.
|
||||
MDNS_PORT = 5353
|
||||
|
||||
#: The unit of dnsmasq, the resolver of the remote access clients.
|
||||
RESOLVER_UNIT = 'linux-manager-resolver.service'
|
||||
|
||||
@@ -122,6 +128,7 @@ BLOCKS = (
|
||||
('# BOOTSTRAP RULES START', '# BOOTSTRAP RULES END'),
|
||||
('# MANAGER RULES START', '# MANAGER RULES END'),
|
||||
('# HTTPS RULES START', '# HTTPS RULES END'),
|
||||
('# MDNS RULES START', '# MDNS RULES END'),
|
||||
('# METRICS RULES START', '# METRICS RULES END'),
|
||||
('# SITES RULES START', '# SITES RULES END'),
|
||||
('# DNS RULES START', '# DNS RULES END'),
|
||||
@@ -200,19 +207,6 @@ def strip_blocks(text):
|
||||
return ''.join(out)
|
||||
|
||||
|
||||
def is_configured(ctx):
|
||||
"""True once any feature is actually configured: routing, a VPN system, or a listener of the core.
|
||||
|
||||
While nothing is configured the package leaves the firewall alone: an
|
||||
install that has not been filled in yet must not start blocking traffic on
|
||||
a host that was working before.
|
||||
"""
|
||||
return any((linuxmanager.s2s_ready(ctx), linuxmanager.routing_ready(ctx),
|
||||
linuxmanager.p2s_ready(ctx), linuxmanager.wg_ready(ctx),
|
||||
linuxmanager.openvpn_ready(ctx), ctx['web_enabled'], linuxmanager.https_ready(ctx),
|
||||
linuxmanager.metrics_ready(ctx), linuxmanager.dns_ready(ctx), bool(ctx['sites'])))
|
||||
|
||||
|
||||
def filter_block(ctx):
|
||||
lines = []
|
||||
|
||||
@@ -277,6 +271,11 @@ def filter_block(ctx):
|
||||
if ctx['web_enabled']:
|
||||
lines += ['', '# WEB RULES START', *opened(ctx['web_listen'], ctx['web_port']), '# WEB RULES END']
|
||||
|
||||
# Without wan.local_fqdn, Avahi answers mDNS queries for <host name>.local on the internal side.
|
||||
if ctx['mdns'] and internal:
|
||||
lines += ['', '# MDNS RULES START', f'-A ufw-before-input -i {internal} -p udp --dport {MDNS_PORT} -j ACCEPT',
|
||||
'# MDNS RULES END']
|
||||
|
||||
if not SETUP_DONE.exists() and ctx['int_iface']:
|
||||
lines += [
|
||||
'',
|
||||
@@ -295,7 +294,7 @@ def filter_block(ctx):
|
||||
|
||||
# The ACME CA reaches the HTTP challenge on the external interface while it issues the server's certificate; the
|
||||
# HTTPS ports are open on both.
|
||||
if linuxmanager.https_ready(ctx) and interfaces:
|
||||
if interfaces:
|
||||
ports = [port for wanted, port in ((ctx['web_enabled'] or ctx['pki_acme'], ctx['https_web_port']),
|
||||
(True, ctx['https_manager_port']),
|
||||
(linuxmanager.metrics_ready(ctx), ctx['metrics_https_port']),
|
||||
@@ -431,17 +430,6 @@ def setup_ufw(ctx):
|
||||
if not BEFORE_RULES.is_file():
|
||||
fail(f'{BEFORE_RULES} does not exist')
|
||||
|
||||
# Nothing configured: remove anything left from an earlier configuration
|
||||
# and touch nothing else.
|
||||
if not is_configured(ctx):
|
||||
original = BEFORE_RULES.read_text(encoding='utf-8')
|
||||
text = strip_blocks(original)
|
||||
if text == original:
|
||||
return False
|
||||
BEFORE_RULES.write_text(text, encoding='utf-8')
|
||||
remove_stale_nat(original, text)
|
||||
return True
|
||||
|
||||
if UFW_DEFAULTS.is_file():
|
||||
text = UFW_DEFAULTS.read_text(encoding='utf-8')
|
||||
updated = ''.join(
|
||||
@@ -728,6 +716,16 @@ def caddy_address(host, port, tls):
|
||||
return f'{"http://" if tls == "none" else ""}{host}:{port}'
|
||||
|
||||
|
||||
def manage_mdns(ctx):
|
||||
"""Run Avahi, which announces <host name>.local, one of the HTTPS names, with mDNS, while wan.local_fqdn is not set,
|
||||
and stop it while it is."""
|
||||
active = unit_is_active(AVAHI_UNITS[1])
|
||||
if ctx['mdns'] and not active:
|
||||
run(['systemctl', 'enable', '--now', *AVAHI_UNITS], check=False)
|
||||
elif not ctx['mdns'] and active:
|
||||
run(['systemctl', 'disable', '--now', *AVAHI_UNITS], check=False)
|
||||
|
||||
|
||||
def manage_resolver(changed):
|
||||
"""Run dnsmasq, the resolver of the remote access clients, while configure wrote its configuration, restarting it when
|
||||
that changed, and stop it when not. It starts after systemd-resolved has left the addresses it takes."""
|
||||
@@ -745,11 +743,14 @@ def manage_caddy(cfg, ctx):
|
||||
"""Run Caddy, a dependency of the package, which serves every HTTP and HTTPS port of the server's services and the
|
||||
web sites; the services listen on loopback only.
|
||||
|
||||
CADDYFILE serves over plain HTTP the web service on web.port while it is enabled, 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
|
||||
CADDYFILE serves over plain HTTP the web service on web.port while it is enabled and the manager on its port, and
|
||||
while metrics are enabled the metrics service on metrics.port. While https.disable_auto_redirect is off, a request
|
||||
of the web service for an HTTPS host is redirected (308) to https.web_port, and every request of the manager to
|
||||
https.manager_port, on the host it named when that is an HTTPS host, else on the first HTTPS name. It serves the
|
||||
web service on https.web_port, the manager on https.manager_port, while metrics are enabled the metrics service on
|
||||
metrics.https_port, and while WebDAV is ready WebDAV on sites.webdav_port, all for the HTTPS hosts: the HTTPS names
|
||||
(linuxmanager.https_names) and, with https.ip_sans and a certificate of its own, the addresses its certificate
|
||||
names; a client without SNI gets the certificate of the first HTTPS name. Every site calls
|
||||
its service on its loopback port. The certificate comes from the ACME CA of https.acme_provider, the global issuer,
|
||||
with https.certificate acme, and otherwise is the one linuxmanager_pki.https_files gives, written to
|
||||
CADDY_HTTPS_DIR; while that cannot be read, the HTTPS sites are left out, so that no ACME CA is asked for it. It
|
||||
@@ -774,7 +775,7 @@ def manage_caddy(cfg, ctx):
|
||||
group = grp.getgrnam(CADDY_GROUP).gr_gid
|
||||
except KeyError:
|
||||
fail(f'the group {CADDY_GROUP} does not exist; is the caddy package installed?')
|
||||
https = linuxmanager.https_ready(ctx)
|
||||
https = True
|
||||
own = None
|
||||
if https and cfg['https']['certificate'] != 'acme':
|
||||
try:
|
||||
@@ -832,8 +833,12 @@ def manage_caddy(cfg, ctx):
|
||||
os.chown(folder / file, 0, group)
|
||||
linuxmanager_sites.ensure_folders(site['name'] for site in sites)
|
||||
names = linuxmanager.issuing_cas(cfg)
|
||||
hosts = [*ctx['https_names'], *(ctx['https_ips'] if own is not None else [])]
|
||||
caddy_ctx = dict(ctx, https=https, manager_port=linuxmanager.manager_port(),
|
||||
redirect=https and not cfg['https']['disable_auto_redirect'],
|
||||
https_name=ctx['https_names'][0],
|
||||
https_hosts=[f'[{host}]' if ':' in host else host for host in hosts],
|
||||
redirect_hosts=[host for host in hosts if ':' not in host],
|
||||
web_loopback_port=linuxmanager.WEB_LOOPBACK_PORT,
|
||||
manager_loopback_port=linuxmanager.MANAGER_LOOPBACK_PORT,
|
||||
metrics_loopback_port=linuxmanager.METRICS_LOOPBACK_PORT,
|
||||
@@ -1043,6 +1048,8 @@ def refresh_web(cfg, ctx):
|
||||
'external_addresses': ctx['local_addr_list'],
|
||||
'internal_address': ctx['int_addr'],
|
||||
'internal_gateway': ctx['int_gateway_ip'],
|
||||
'https_names': ctx['https_names'],
|
||||
'https_addresses': ctx['https_ips'],
|
||||
'local_cidrs': ctx['local_cidr_list'],
|
||||
'client_dns': ctx['p2s_resolver_addrs'] if linuxmanager.RESOLVER_CONF.exists() else [],
|
||||
'site_to_site': [{
|
||||
@@ -1136,16 +1143,13 @@ def main():
|
||||
|
||||
progress('running', 'firewall')
|
||||
rules_changed = setup_ufw(ctx)
|
||||
if is_configured(ctx):
|
||||
status = run(['ufw', 'status'], check=False)
|
||||
if not status.stdout.startswith('Status: active'):
|
||||
# Only ever enable the firewall after making sure SSH survives it.
|
||||
run(['ufw', 'allow', '22/tcp'], check=False)
|
||||
run(['ufw', '--force', 'enable'])
|
||||
elif rules_changed:
|
||||
run(['ufw', 'reload'])
|
||||
status = run(['ufw', 'status'], check=False)
|
||||
if not status.stdout.startswith('Status: active'):
|
||||
# Only ever enable the firewall after making sure SSH survives it.
|
||||
run(['ufw', 'allow', '22/tcp'], check=False)
|
||||
run(['ufw', '--force', 'enable'])
|
||||
elif rules_changed:
|
||||
run(['ufw', 'reload'], check=False)
|
||||
run(['ufw', 'reload'])
|
||||
|
||||
progress('running', 'strongSwan')
|
||||
manage_strongswan(ctx, changed)
|
||||
@@ -1168,6 +1172,8 @@ def main():
|
||||
manage_openvpn(ctx, changed)
|
||||
progress('running', 'HTTPS proxy')
|
||||
manage_caddy(cfg, ctx)
|
||||
progress('running', 'mDNS')
|
||||
manage_mdns(ctx)
|
||||
progress('running', 'WebDAV')
|
||||
manage_webdav(ctx)
|
||||
progress('running', 'name server')
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# Written by linux-manager-setup from /etc/linux-manager/linux-manager.json and the web sites; edits are overwritten.
|
||||
{
|
||||
auto_https disable_redirects
|
||||
{%- if https_tls %}
|
||||
default_sni {{ https_name }}
|
||||
{%- endif %}
|
||||
{%- if https_email %}
|
||||
email {{ https_email }}
|
||||
{%- endif %}
|
||||
@@ -44,10 +47,18 @@
|
||||
file_server
|
||||
}
|
||||
{%- endmacro %}
|
||||
{#- The addresses of an HTTPS site on port: the HTTPS hosts. #}
|
||||
{%- macro https_site(port) %}{% for host in https_hosts %}{{ host }}:{{ port }}{{ ', ' if not loop.last else '' }}{% endfor %}{% endmacro %}
|
||||
{% if web_enabled %}
|
||||
http://:{{ web_port }} {
|
||||
header -Server
|
||||
{{- pki_files(pki_publish_dir) }}
|
||||
{%- if redirect %}
|
||||
@https host {{ redirect_hosts | join(' ') }}
|
||||
handle @https {
|
||||
redir https://{host}:{{ https_web_port }}{uri} 308
|
||||
}
|
||||
{%- endif %}
|
||||
handle {
|
||||
reverse_proxy {{ loopback }}:{{ web_loopback_port }} {
|
||||
header_down -Server
|
||||
@@ -58,9 +69,15 @@ http://:{{ web_port }} {
|
||||
http://:{{ manager_port }} {
|
||||
header -Server
|
||||
{{- pki_files(pki_publish_dir) }}
|
||||
{%- if redirect %}
|
||||
@https host {{ redirect_hosts | join(' ') }}
|
||||
handle @https {
|
||||
redir https://{host}:{{ https_manager_port }}{uri} 308
|
||||
}
|
||||
{%- endif %}
|
||||
handle {
|
||||
{%- if redirect %}
|
||||
redir https://{{ local_fqdn }}:{{ https_manager_port }}{uri} 308
|
||||
redir https://{{ https_name }}:{{ https_manager_port }}{uri} 308
|
||||
{%- else %}
|
||||
reverse_proxy {{ loopback }}:{{ manager_loopback_port }} {
|
||||
header_down -Server
|
||||
@@ -77,7 +94,7 @@ http://:{{ metrics_port }} {
|
||||
}
|
||||
{% endif %}
|
||||
{%- if https and (web_enabled or acme_cas) %}
|
||||
{{ local_fqdn }}:{{ https_web_port }} {
|
||||
{{ https_site(https_web_port) }} {
|
||||
header -Server
|
||||
{%- if https_tls %}
|
||||
tls {{ https_tls.cert }} {{ https_tls.key }}
|
||||
@@ -102,7 +119,7 @@ http://:{{ metrics_port }} {
|
||||
}
|
||||
{% endif %}
|
||||
{%- if https %}
|
||||
{{ local_fqdn }}:{{ https_manager_port }} {
|
||||
{{ https_site(https_manager_port) }} {
|
||||
header -Server
|
||||
{%- if https_tls %}
|
||||
tls {{ https_tls.cert }} {{ https_tls.key }}
|
||||
@@ -116,7 +133,7 @@ http://:{{ metrics_port }} {
|
||||
}
|
||||
{% endif %}
|
||||
{%- if https and metrics_enabled %}
|
||||
{{ local_fqdn }}:{{ metrics_https_port }} {
|
||||
{{ https_site(metrics_https_port) }} {
|
||||
header -Server
|
||||
{%- if https_tls %}
|
||||
tls {{ https_tls.cert }} {{ https_tls.key }}
|
||||
@@ -127,7 +144,7 @@ http://:{{ metrics_port }} {
|
||||
}
|
||||
{% endif %}
|
||||
{%- if webdav %}
|
||||
{{ local_fqdn }}:{{ webdav_port }} {
|
||||
{{ https_site(webdav_port) }} {
|
||||
header -Server
|
||||
{%- if https_tls %}
|
||||
tls {{ https_tls.cert }} {{ https_tls.key }}
|
||||
|
||||
Reference in new issue
Block a user