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

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

No files matched your search

@@ -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}