Files
linux-cloud-router/debian-package/src/usr/lib/linux-manager/linuxmanager_pki.py
T

1701 lines
88 KiB
Python

"""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, 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,
with its kind, template, names, expiry and revocation; the server's own certificates and the users' keep their keys
there, as the server and the OpenVPN profile need them, and a certificate issued for anything else is kept without its
key. A user's certificate is also the userCertificate of the user's entry. A retired CA keeps its entry, renamed
cn=<name>-<time> and marked with linuxManagerRetired.
The root comes from one of ROOT_SOURCES, pki.root, fixed once the root exists:
- local: the server creates the root and keeps its key;
- offline: the root is an offline CA; each issuing CA has its key and a CSR and is pending until import_ca takes its
certificate, signed offline, after the root's own certificate;
- simple-ca: a Simple CA service signs the issuing CAs. A setup code is exchanged for a sign-ca token of one of its
issuing CAs, the upstream CA, kept on cn=root; the upstream CA's certificate and CRL are the entry cn=upstream, and
it stands between the root and the issuing CAs in every chain.
The certificates carry the URLs of pki.publish for their issuer's certificate (AIA) and CRL (CRL distribution point);
PUBLISH_DIR holds the DER copies served there. distribute writes the files strongSwan, OpenVPN and the system's trust
store read.
Callers hold locked() around every operation that writes, which is the lock of the user module's sessions too. A request
that cannot be done raises Failure, whose status says why: 2 the request is invalid, 3 something it names does not
exist, 4 the state does not allow it, 1 anything else.
"""
import base64
import contextlib
import datetime
import fcntl
import ipaddress
import json
import os
import pathlib
import re
import shutil
import socket
import ssl
import subprocess
import tempfile
import urllib.error
import urllib.request
import ldap
import ldap.dn
import ldap.filter
import ldap.modlist
from cryptography import x509
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
from cryptography.hazmat.primitives.serialization import pkcs12
from cryptography.x509.oid import AuthorityInformationAccessOID, NameOID
import linuxmanager
import linuxmanager_ldap
#: The setup code of a Simple CA token, which postinst writes and provision exchanges and removes.
SETUP_CODE_FILE = pathlib.Path('/etc/linux-manager/pki-setup-code')
#: The entry of the Simple CA issuing CA that signs the server's issuing CAs, between them and the root.
UPSTREAM = 'upstream'
#: The CAs above the issuing CAs, which are no issuing CAs themselves.
UPPER_CAS = ('root', UPSTREAM)
#: Seconds an HTTP request to Simple CA may take.
HTTP_TIMEOUT = 30
#: The signature algorithms of a Simple CA token: JWT alg -> the hash.
JWT_HASHES = {'RS256': hashes.SHA256, 'ES256': hashes.SHA256, 'ES384': hashes.SHA384}
#: The DER copies of the CA certificates and CRLs, <name>.crt and <name>.crl, which the web service and Caddy serve.
PUBLISH_DIR = pathlib.Path('/var/lib/linux-manager/pki-publish')
#: The lock of the PKI and of the user module's sessions.
LOCK_FILE = pathlib.Path('/run/linux-manager/users.lock')
#: The copies strongSwan reads: one CA certificate per file, as strongSwan reads only the first of a file.
X509CA_DIR = pathlib.Path('/etc/swanctl/x509ca')
X509_DIR = pathlib.Path('/etc/swanctl/x509')
PRIVATE_DIR = pathlib.Path('/etc/swanctl/private')
X509CRL_DIR = pathlib.Path('/etc/swanctl/x509crl')
SWANCTL_CA_FILES = {'root': 'root.pem', UPSTREAM: 'upstream.pem', 'p2s': 'p2s.pem', 's2s': 's2s.pem'}
VPN_SERVER_CERT = X509_DIR / 'vpn-server.pem'
VPN_SERVER_KEY = PRIVATE_DIR / 'vpn-server.key'
S2S_CERT = X509_DIR / 'site-to-site.pem'
S2S_KEY = PRIVATE_DIR / 'site-to-site.key'
#: What OpenVPN reads: the root, the upstream CA and the P2S CA, and their CRLs, which it needs for every CA of a
#: client's chain.
OPENVPN_CA = pathlib.Path('/etc/openvpn/server/linux-manager-ca.pem')
OPENVPN_CRL = pathlib.Path('/etc/openvpn/server/linux-manager-crl.pem')
#: The root CA in the system's trust store.
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', '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.
BUILTIN_COMPONENTS = {'p2s': 'vpn', 's2s': 'router'}
ROUTER_FILES = {'vpn-server': (VPN_SERVER_CERT, VPN_SERVER_KEY), 'site-to-site': (S2S_CERT, S2S_KEY)}
#: The attributes of a CA's entry and of a certificate's entry.
AUTHORITY_ATTRIBUTES = ['cACertificate;binary', 'certificateRevocationList;binary', 'linuxManagerPrivateKey',
'linuxManagerCertificateRequest', 'linuxManagerCRLNumber', 'linuxManagerCRLSource', 'linuxManagerRetired',
'linuxManagerToken', 'linuxManagerUpstreamName']
CERTIFICATE_ATTRIBUTES = ['serialNumber', 'cn', 'linuxManagerKind', 'linuxManagerTemplate', 'linuxManagerSubjectAltName',
'linuxManagerNotAfter', 'linuxManagerRevoked', 'linuxManagerRevocationReason', 'createTimestamp']
#: The suffix of a retired CA's name: -<time of the retirement>.
RETIRED_SUFFIX = re.compile(r'-\d{14}$')
#: The revocation reasons revoke takes.
REASONS = ('unspecified', 'key_compromise', 'affiliation_changed', 'superseded', 'cessation_of_operation',
'privilege_withdrawn')
#: Days before an expiry or a CRL's next update that status warns.
WARN_DAYS = 30
#: The longest PFX password, in characters.
PASSWORD_MAX = 128
DNS_NAME = re.compile(r'^(\*\.)?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$')
EMAIL = re.compile(r'^[^@\s]+@[^@\s]+\.[^@\s]+$')
SERIAL = re.compile(r'^[0-9A-Fa-f]{1,40}$')
CA_USAGE = x509.KeyUsage(digital_signature=False, content_commitment=False, key_encipherment=False,
data_encipherment=False, key_agreement=False, key_cert_sign=True, crl_sign=True,
encipher_only=False, decipher_only=False)
class Failure(Exception):
"""A request that cannot be done; status is 2 invalid, 3 not found, 4 not allowed in this state, 1 other."""
def __init__(self, message, status=1):
super().__init__(message)
self.status = status
@contextlib.contextmanager
def locked():
"""Hold the lock of the PKI, which the user module's sessions share."""
LOCK_FILE.parent.mkdir(parents=True, exist_ok=True)
with open(LOCK_FILE, 'w') as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
yield
@contextlib.contextmanager
def directory():
"""A connection to the server's directory as root, closed at the end."""
connection = linuxmanager_ldap.root()
try:
yield connection
finally:
connection.unbind_s()
def now():
return datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0)
def iso(moment):
return moment.astimezone(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
def generalized(moment):
"""A time as LDAP's GeneralizedTime, in UTC."""
return moment.astimezone(datetime.timezone.utc).strftime('%Y%m%d%H%M%SZ').encode()
def from_generalized(value):
"""A GeneralizedTime value as an ISO 8601 UTC string, None for none."""
if not value:
return None
return iso(datetime.datetime.strptime(value[:14].decode(), '%Y%m%d%H%M%S').replace(tzinfo=datetime.timezone.utc))
def utc(item, name):
"""A time of a certificate or CRL in UTC: the *_utc attribute of newer cryptography, or the naive one of older."""
if hasattr(item, f'{name}_utc'):
return getattr(item, f'{name}_utc')
value = getattr(item, name)
return value.replace(tzinfo=datetime.timezone.utc) if value is not None else None
def cert_pem(cert):
return cert.public_bytes(serialization.Encoding.PEM)
def cert_der(cert):
return cert.public_bytes(serialization.Encoding.DER)
def key_pem(key, password=None):
encryption = serialization.BestAvailableEncryption(password) if password else serialization.NoEncryption()
return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, encryption)
def write(path, data, mode):
"""Write the bytes to the file with the mode, replacing it in one step; True when its content changed."""
if path.is_file() and path.read_bytes() == data:
os.chmod(path, mode)
return False
path.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
descriptor, name = tempfile.mkstemp(dir=path.parent, prefix=f'.{path.name}.')
try:
with os.fdopen(descriptor, 'wb') as handle:
handle.write(data)
os.chmod(name, mode)
os.replace(name, path)
except OSError:
os.unlink(name)
raise
return True
def remove(path):
"""Remove the file; True when it existed."""
if path.is_file():
path.unlink()
return True
return False
def first(attributes, name):
values = attributes.get(name)
return values[0] if values else None
def authority_dn(name):
return f'cn={ldap.dn.escape_dn_chars(name)},{linuxmanager_ldap.PKI}'
def authority(connection, name):
"""The entry of a CA: {name, cert, key, csr (PEM), crl, crl_number, crl_source, retired, token, upstream_name}, None
when there is none; token and upstream_name are those of the root's Simple CA token."""
try:
attributes = connection.search_s(authority_dn(name), ldap.SCOPE_BASE, attrlist=AUTHORITY_ATTRIBUTES)[0][1]
except ldap.NO_SUCH_OBJECT:
return None
cert, crl, key = (first(attributes, item) for item in AUTHORITY_ATTRIBUTES[:3])
return {
'name': name,
'cert': x509.load_der_x509_certificate(cert) if cert else None,
'key': serialization.load_pem_private_key(key, None) if key else None,
'csr': first(attributes, 'linuxManagerCertificateRequest'),
'crl': x509.load_der_x509_crl(crl) if crl else None,
'crl_number': int(first(attributes, 'linuxManagerCRLNumber') or 0),
'crl_source': (first(attributes, 'linuxManagerCRLSource') or b'').decode() or None,
'retired': from_generalized(first(attributes, 'linuxManagerRetired')),
'token': (first(attributes, 'linuxManagerToken') or b'').decode() or None,
'upstream_name': (first(attributes, 'linuxManagerUpstreamName') or b'').decode() or None,
}
def update(connection, name, values):
"""Set attributes of a CA's entry, adding the entry when it is missing; a value None removes its attribute."""
dn = authority_dn(name)
try:
connection.search_s(dn, ldap.SCOPE_BASE, attrlist=['1.1'])
except ldap.NO_SUCH_OBJECT:
connection.add_s(dn, ldap.modlist.addModlist({
'objectClass': [b'linuxManagerAuthority'], 'cn': [name.encode()],
**{attribute: [value] for attribute, value in values.items() if value is not None}}))
return
connection.modify_s(dn, [(ldap.MOD_REPLACE, attribute, [value] if value is not None else [])
for attribute, value in values.items()])
def issuing(connection):
"""The names of the issuing CAs in the directory that are not retired, sorted."""
found = connection.search_s(linuxmanager_ldap.PKI, ldap.SCOPE_ONELEVEL,
'(&(objectClass=linuxManagerAuthority)(!(linuxManagerRetired=*))'
f'(!(cn=root))(!(cn={UPSTREAM})))', ['cn'])
return sorted(attributes['cn'][0].decode() for _, attributes in found)
def certificate_entry(dn, attributes):
"""A certificate's entry as the answers show it: serial, ca, kind, template, subject, sans, created, expires,
revoked and reason."""
def value(name):
return (first(attributes, name) or b'').decode() or None
return {
'serial': value('serialNumber'), 'ca': ldap.dn.str2dn(dn)[1][0][1], 'kind': value('linuxManagerKind'),
'template': value('linuxManagerTemplate'), 'subject': value('cn') or '',
'sans': [item.decode() for item in attributes.get('linuxManagerSubjectAltName', [])],
'created': from_generalized(first(attributes, 'createTimestamp')),
'expires': from_generalized(first(attributes, 'linuxManagerNotAfter')),
'revoked': from_generalized(first(attributes, 'linuxManagerRevoked')), 'reason': value('linuxManagerRevocationReason'),
'dn': dn,
}
def certificate_entries(connection, base, condition=''):
"""The certificates' entries under base that match the LDAP condition, newest first; none when base does not exist,
as for a built-in CA whose component was never on."""
try:
found = connection.search_s(base, ldap.SCOPE_SUBTREE, f'(&(objectClass=linuxManagerCertificate){condition})',
CERTIFICATE_ATTRIBUTES)
except ldap.NO_SUCH_OBJECT:
return []
return sorted((certificate_entry(dn, attributes) for dn, attributes in found),
key=lambda entry: entry['created'] or '', reverse=True)
def record(connection, cert, ca, kind, template=None, key=None):
"""Add a certificate the CA issued: kind is ca, router, user or external; key is kept for router and user."""
serial = f'{cert.serial_number:X}'
attributes = {
'objectClass': [b'linuxManagerCertificate'], 'serialNumber': [serial.encode()], 'cn': [common_name(cert).encode()],
'userCertificate;binary': [cert_der(cert)], 'linuxManagerKind': [kind.encode()],
'linuxManagerNotAfter': [generalized(utc(cert, 'not_valid_after'))],
}
if template:
attributes['linuxManagerTemplate'] = [template.encode()]
if san_values(cert):
attributes['linuxManagerSubjectAltName'] = [value.encode() for value in san_values(cert)]
if key is not None:
attributes['linuxManagerPrivateKey'] = [key_pem(key)]
connection.add_s(f'serialNumber={serial},{authority_dn(ca)}', ldap.modlist.addModlist(attributes))
def holders(connection, ca, condition):
"""The certificates of the CA that match the LDAP condition and have their key, not revoked, newest first: [(dn,
cert, key)]; none when the CA does not exist."""
try:
found = connection.search_s(
authority_dn(ca), ldap.SCOPE_ONELEVEL,
f'(&(objectClass=linuxManagerCertificate)(linuxManagerPrivateKey=*)(!(linuxManagerRevoked=*)){condition})',
['userCertificate;binary', 'linuxManagerPrivateKey'])
except ldap.NO_SUCH_OBJECT:
return []
pairs = [(dn, x509.load_der_x509_certificate(attributes['userCertificate;binary'][0]),
serialization.load_pem_private_key(attributes['linuxManagerPrivateKey'][0], None)) for dn, attributes in found]
return sorted(pairs, key=lambda pair: utc(pair[1], 'not_valid_after'), reverse=True)
def router_condition(name):
return f'(linuxManagerKind=router)(linuxManagerTemplate={ROUTER_CERTS[name][1]})'
def user_condition(name):
return f'(linuxManagerKind=user)(cn={ldap.filter.escape_filter_chars(name)})'
def drop_key(connection, dn):
connection.modify_s(dn, [(ldap.MOD_REPLACE, 'linuxManagerPrivateKey', [])])
def new_key(kind):
"""A new private key of one of linuxmanager.PKI_KEYS."""
if kind.startswith('rsa-'):
return rsa.generate_private_key(public_exponent=65537, key_size=int(kind[4:]))
return ec.generate_private_key(ec.SECP384R1() if kind == 'ec-p384' else ec.SECP256R1())
def digest(key):
"""The hash a key signs with: SHA-384 for a P-384 key, SHA-256 otherwise."""
return hashes.SHA384() if isinstance(key, ec.EllipticCurvePrivateKey) and key.curve.name == 'secp384r1' \
else hashes.SHA256()
def common_name(item):
"""The common name of a certificate's or a CSR's subject, or the whole subject without one."""
names = item.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
return names[0].value if names else item.subject.rfc4514_string()
def san_values(item):
"""The subject alternative names of a certificate or a CSR as strings: DNS:, IP: and email: values."""
try:
names = item.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
except x509.ExtensionNotFound:
return []
return ([f'DNS:{value}' for value in names.get_values_for_type(x509.DNSName)] +
[f'IP:{value}' for value in names.get_values_for_type(x509.IPAddress)] +
[f'email:{value}' for value in names.get_values_for_type(x509.RFC822Name)])
def same_key(one, other):
der = serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo
return one.public_bytes(*der) == other.public_bytes(*der)
def issued_by(cert, issuer):
"""Whether the issuer's key signed the certificate."""
try:
cert.verify_directly_issued_by(issuer)
except (ValueError, TypeError, InvalidSignature):
return False
return True
def is_ca(cert):
try:
return cert.extensions.get_extension_for_class(x509.BasicConstraints).value.ca
except x509.ExtensionNotFound:
return False
def is_ca_certificate(text):
"""Whether the text is the PEM certificate of a CA."""
try:
return is_ca(x509.load_pem_x509_certificate(text.strip().encode()))
except ValueError:
return False
def authority_key_id(issuer):
try:
return x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(
issuer.extensions.get_extension_for_class(x509.SubjectKeyIdentifier).value)
except x509.ExtensionNotFound:
return x509.AuthorityKeyIdentifier.from_issuer_public_key(issuer.public_key())
def sign(subject, public_key, issuer, issuer_key, days, extensions, urls=(), issuer_name=None):
"""A certificate with the common name subject for public_key, signed by issuer_key, valid for days but not past the
issuer, with the extensions [(extension, critical)].
issuer is the issuer's certificate, None for a self-signed one. The certificate points at the issuer's certificate
and CRL, issuer_name.crt and issuer_name.crl, under each of the base urls.
"""
moment = now()
end = moment + datetime.timedelta(days=days)
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, subject)])
builder = (x509.CertificateBuilder()
.subject_name(name)
.issuer_name(issuer.subject if issuer is not None else name)
.public_key(public_key)
.serial_number(x509.random_serial_number())
.not_valid_before(moment - datetime.timedelta(minutes=5))
.not_valid_after(min(end, utc(issuer, 'not_valid_after')) if issuer is not None else end)
.add_extension(x509.SubjectKeyIdentifier.from_public_key(public_key), False))
if issuer is not None:
builder = builder.add_extension(authority_key_id(issuer), False)
if issuer is not None and urls:
builder = builder.add_extension(x509.AuthorityInformationAccess([
x509.AccessDescription(AuthorityInformationAccessOID.CA_ISSUERS,
x509.UniformResourceIdentifier(f'{url}{issuer_name}.crt')) for url in urls]), False)
builder = builder.add_extension(x509.CRLDistributionPoints([x509.DistributionPoint(
[x509.UniformResourceIdentifier(f'{url}{issuer_name}.crl') for url in urls], None, None, None)]), False)
for extension, critical in extensions:
builder = builder.add_extension(extension, critical)
return builder.sign(issuer_key, digest(issuer_key))
def ca_extensions(path_length):
return [(x509.BasicConstraints(ca=True, path_length=path_length), True), (CA_USAGE, True)]
def general_names(values, allowed):
"""The subject alternative names of values, each a DNS name, an IP address or an e-mail address of the allowed
types (linuxmanager.SAN_TYPES)."""
names = []
for value in values:
if not isinstance(value, str) or not value.strip():
raise Failure('a subject alternative name must be a non-empty string', 2)
value = value.strip()
try:
kind, name = 'ip', x509.IPAddress(ipaddress.ip_address(value))
except ValueError:
if '@' in value:
if not EMAIL.match(value):
raise Failure(f'{value!r} is not an e-mail address', 2)
kind, name = 'email', x509.RFC822Name(value)
else:
if not DNS_NAME.match(value.lower()):
raise Failure(f'{value!r} is not a DNS name, an IP address or an e-mail address', 2)
kind, name = 'dns', x509.DNSName(value.lower())
if kind not in allowed:
raise Failure(f'{value}: the template allows no {kind} names', 2)
if name not in names:
names.append(name)
return names
def leaf_extensions(cfg, template, names):
"""The extensions of a certificate of the template with the subject alternative names: the extended key usages by
their OIDs (linuxmanager.extended_key_usages), and the template's policies as certificate policies."""
usage = x509.KeyUsage(**{option: option in template['key_usage'] for option in linuxmanager.KEY_USAGES},
key_cert_sign=False, crl_sign=False, encipher_only=False, decipher_only=False)
extensions = [(x509.BasicConstraints(ca=False, path_length=None), True), (usage, True)]
if template['extended_key_usage']:
oids = linuxmanager.extended_key_usages(cfg)
extensions.append((x509.ExtendedKeyUsage([x509.ObjectIdentifier(oids[item])
for item in template['extended_key_usage']]), False))
if template['policies']:
extensions.append((x509.CertificatePolicies([x509.PolicyInformation(x509.ObjectIdentifier(oid), None)
for oid in template['policies']]), False))
if names:
extensions.append((x509.SubjectAlternativeName(names), False))
return extensions
def check_subject(kind, subject):
"""Check a common name against the subject of a template (linuxmanager.TEMPLATE_SUBJECTS)."""
if not isinstance(subject, str) or not subject.strip():
raise Failure('the subject is required', 2)
subject = subject.strip()
if kind == 'dns' and not DNS_NAME.match(subject.lower()):
raise Failure(f'{subject!r} is not a DNS name, which the template needs as the subject', 2)
if kind == 'email' and not EMAIL.match(subject):
raise Failure(f'{subject!r} is not an e-mail address, which the template needs as the subject', 2)
if len(subject) > 64 or not subject.isprintable():
raise Failure('the subject must have 1 to 64 printable characters', 2)
return subject.lower() if kind == 'dns' else subject
def sign_crl(connection, cfg, name):
"""Sign a new CRL of the CA with the certificates it revoked that have not expired, valid for pki.root_crl_days for
the root and pki.crl_days for an issuing CA."""
entry = authority(connection, name)
cert, key = entry['cert'], entry['key']
number = entry['crl_number'] + 1
moment = now()
days = cfg['pki']['root_crl_days'] if name == 'root' else cfg['pki']['crl_days']
builder = (x509.CertificateRevocationListBuilder()
.issuer_name(cert.subject)
.last_update(moment)
.next_update(moment + datetime.timedelta(days=days))
.add_extension(x509.CRLNumber(number), False)
.add_extension(authority_key_id(cert), False))
for revoked_entry in certificate_entries(connection, authority_dn(name), '(linuxManagerRevoked=*)'):
if revoked_entry['expires'] and revoked_entry['expires'] <= iso(moment):
continue
revoked = (x509.RevokedCertificateBuilder()
.serial_number(int(revoked_entry['serial'], 16))
.revocation_date(datetime.datetime.strptime(revoked_entry['revoked'], '%Y-%m-%dT%H:%M:%SZ')
.replace(tzinfo=datetime.timezone.utc)))
if revoked_entry['reason'] and revoked_entry['reason'] != 'unspecified':
revoked = revoked.add_extension(x509.CRLReason(x509.ReasonFlags[revoked_entry['reason']]), False)
builder = builder.add_revoked_certificate(revoked.build())
crl = builder.sign(key, digest(key))
update(connection, name, {'certificateRevocationList;binary': crl.public_bytes(serialization.Encoding.DER),
'linuxManagerCRLNumber': str(number).encode(),
**({'linuxManagerCRLSource': b'signed'} if name == 'root' else {})})
def crl_stale(crl):
"""Whether the CRL is missing or past half of its validity."""
if crl is None:
return True
last, following = utc(crl, 'last_update'), utc(crl, 'next_update')
return following is None or now() >= last + (following - last) / 2
def ready(name):
"""Whether the issuing CA has its certificate and key, and so issues certificates."""
with directory() as connection:
entry = authority(connection, name)
return bool(entry and entry['cert'] and entry['key'] and not entry['retired'])
def refresh_crls(connection, cfg, force=()):
"""Sign a new CRL for each CA with its key on the server whose CRL is stale, or that force names."""
for name in ['root', *issuing(connection)]:
entry = authority(connection, name)
if entry and entry['key'] and entry['cert'] and (name in force or crl_stale(entry['crl'])):
sign_crl(connection, cfg, name)
def renewal_due(cert):
"""Whether less than a third of the certificate's lifetime is left."""
start, end = utc(cert, 'not_valid_before'), utc(cert, 'not_valid_after')
return now() >= end - (end - start) / 3
def is_address(value):
try:
ipaddress.ip_address(value)
except ValueError:
return False
return True
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."""
fqdn = ctx['local_fqdn']
if name in ('vpn-server', 'https'):
return fqdn, [fqdn]
names = [fqdn]
for connection in ctx['connections']:
if connection['auth'] != 'certificate' or connection['local_id_mode'] == 'fqdn':
continue
if not connection['local_id']:
return None
if connection['local_id'] not in names:
names.append(connection['local_id'])
return fqdn, names
def ensure_router_cert(connection, cfg, ctx, name, urls):
"""Issue one of the server's certificates when it has none, or its current one is due for renewal, not issued by
its CA's current key, or named otherwise than router_identities says; the older ones lose their keys. Nothing is
issued while an identity it needs is not known yet."""
ca, template_name = ROUTER_CERTS[name]
issuer = authority(connection, ca)
identities = router_identities(name, ctx)
if not issuer or issuer['cert'] is None or issuer['key'] is None or identities is None or not identities[0]:
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}
if current:
_, cert, _ = current[0]
if not renewal_due(cert) and issued_by(cert, issuer['cert']) and common_name(cert) == subject and \
wanted == set(san_values(cert)):
return
template = linuxmanager.pki_templates(cfg)[template_name]
key = new_key(template['key'])
cert = sign(subject, key.public_key(), issuer['cert'], issuer['key'], template['days'],
leaf_extensions(cfg, template, general_names(sans, linuxmanager.SAN_TYPES)), urls, ca)
record(connection, cert, ca, 'router', template_name, key)
for dn, _, _ in current:
drop_key(connection, dn)
def path_length(cert):
"""The path length constraint of a CA certificate, None for none."""
return cert.extensions.get_extension_for_class(x509.BasicConstraints).value.path_length
def check_root_cert(cert, below):
"""Check that the certificate is a self-signed CA whose path length allows below CAs under it."""
if not issued_by(cert, cert):
raise Failure('the root certificate is not self-signed', 2)
if not is_ca(cert):
raise Failure('the root certificate is not a CA certificate', 2)
if path_length(cert) is not None and path_length(cert) < below:
raise Failure(f'the path length of the root certificate allows fewer than {below} CAs below it', 2)
def root_source(entry):
"""The source of the root the directory holds, one of ROOT_SOURCES; None while it holds none."""
if entry is None:
return None
if entry['key'] is not None:
return 'local'
if entry['token'] is not None:
return 'simple-ca'
return 'offline' if entry['cert'] is not None else None
def check_source(cfg, entry):
"""Refuse a root of another source than pki.root."""
source = root_source(entry)
if source is not None and source != cfg['pki']['root']:
raise Failure(f'pki.root is {cfg["pki"]["root"]}, but the root in the directory is {source}; the source of the '
'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))
def token_expires(token):
"""The expiry of a Simple CA token, as an ISO 8601 UTC string; None for a token without one."""
try:
claims = json.loads(jwt_part(token.split('.')[1]))
except (IndexError, ValueError):
return None
return iso(datetime.datetime.fromtimestamp(claims['exp'], datetime.timezone.utc)) if 'exp' in claims else None
def verify_token(token, cert):
"""Whether the Simple CA token is signed by the key of the certificate."""
try:
header, payload, signature = token.split('.')
algorithm = JWT_HASHES[json.loads(jwt_part(header))['alg']]()
signed, signature = f'{header}.{payload}'.encode(), jwt_part(signature)
public_key = cert.public_key()
if isinstance(public_key, rsa.RSAPublicKey):
public_key.verify(signature, signed, padding.PKCS1v15(), algorithm)
else:
half = len(signature) // 2
public_key.verify(encode_dss_signature(int.from_bytes(signature[:half], 'big'),
int.from_bytes(signature[half:], 'big')),
signed, ec.ECDSA(algorithm))
except (ValueError, KeyError, TypeError, InvalidSignature):
return False
return True
def simple_ca_call(cfg, path, body, token=None):
"""POST the JSON body to the path of pki.simple_ca_url, with the token as the bearer; the JSON answer."""
headers = {'Content-Type': 'application/json'}
if token:
headers['Authorization'] = f'Bearer {token}'
url = cfg['pki']['simple_ca_url'].strip().rstrip('/') + path
request = urllib.request.Request(url, json.dumps(body).encode(), headers, method='POST')
try:
with urllib.request.urlopen(request, timeout=HTTP_TIMEOUT) as response:
return json.loads(response.read())
except urllib.error.HTTPError as error:
try:
message = json.loads(error.read()).get('error') or error.reason
except ValueError:
message = error.reason
raise Failure(f'Simple CA refused {path}: {error.code} {message}', 4)
except urllib.error.URLError as error:
if isinstance(error.reason, ssl.SSLCertVerificationError):
reason = getattr(error.reason, 'verify_message', None) or error.reason
raise Failure(f'the HTTPS certificate of Simple CA at {url} is not trusted: {reason}; install the CA that '
'issued it in the system\'s trust store', 1)
raise Failure(f'Simple CA at {url} cannot be reached: {error}', 1)
except (OSError, ValueError) as error:
raise Failure(f'Simple CA at {url} cannot be reached: {error}', 1)
def exchange_code(cfg, code):
"""Exchange a setup code of a Simple CA token for the token and keep it on the root: {upstream, expires}."""
if cfg['pki']['root'] != 'simple-ca':
raise Failure('pki.root is not simple-ca', 4)
if not isinstance(code, str) or not code.strip():
raise Failure('the setup code is required', 2)
with directory() as connection:
check_source(cfg, authority(connection, 'root'))
answer = simple_ca_call(cfg, '/api/token-setup', {'code': code.strip()})
token, upstream = answer.get('token'), answer.get('ca')
if not isinstance(token, str) or not token:
raise Failure('Simple CA answered without a token', 1)
if not upstream or 'sign-ca' not in (answer.get('scopes') or []):
raise Failure('the setup code is not one of a sign-ca token of an issuing CA of Simple CA', 2)
with directory() as connection:
root = authority(connection, 'root')
if root is not None and root['upstream_name'] not in (None, upstream):
raise Failure(f'the token is of Simple CA issuing CA {upstream}, but the server\'s issuing CAs are signed by '
f'{root["upstream_name"]}', 2)
update(connection, 'root', {'linuxManagerToken': token.encode(), 'linuxManagerUpstreamName': upstream.encode()})
return {'upstream': upstream, 'expires': token_expires(token)}
def take_setup_code(cfg):
"""Exchange the setup code of SETUP_CODE_FILE, which is removed either way; the notice of a failure, or None."""
if cfg['pki']['root'] != 'simple-ca' or not SETUP_CODE_FILE.is_file():
return None
code = SETUP_CODE_FILE.read_text(encoding='utf-8')
SETUP_CODE_FILE.unlink()
try:
exchange_code(cfg, code)
except Failure as failure:
return (f'the setup code of {SETUP_CODE_FILE} was not exchanged: {failure}; give a new one with '
'linux-manager-ca root setup-code')
return None
def upstream_sign(cfg, connection, name, request):
"""Have the Simple CA upstream CA sign the CSR of the issuing CA, and keep the root and the upstream CA of the
chain, checked against the token and the certificates kept before; the certificate."""
root = authority(connection, 'root')
upstream = authority(connection, UPSTREAM)
host = cfg['wan']['local_fqdn'].strip() or socket.gethostname()
# The validity ends with the upstream CA's, whose published certificate gives it before the first chain does.
known = upstream['cert'] if upstream is not None and upstream['cert'] is not None else None
if known is None:
url = f'{cfg["pki"]["simple_ca_url"].strip().rstrip("/")}/{root["upstream_name"]}/ca_cert.crt'
try:
with urllib.request.urlopen(url, timeout=HTTP_TIMEOUT) as response:
known = x509.load_der_x509_certificate(response.read())
except (urllib.error.URLError, OSError, ValueError) as error:
raise Failure(f'the certificate of Simple CA issuing CA {root["upstream_name"]} cannot be read from {url}: '
f'{error}', 1)
days = min(cfg['pki']['ca_days'], max((utc(known, 'not_valid_after') - now()).days, 1))
answer = simple_ca_call(cfg, f'/{root["upstream_name"]}/api/sign-ca',
{'csr': request.public_bytes(serialization.Encoding.PEM).decode(), 'name': f'{host}-{name}',
'days': days}, root['token'])
try:
chain = x509.load_pem_x509_certificates(answer['chain'].encode())
except (KeyError, AttributeError, ValueError):
raise Failure('Simple CA answered without a PEM chain', 1)
if len(chain) != 3:
raise Failure('the chain of Simple CA is not the certificate, the issuing CA and the root', 1)
cert, upstream_cert, root_cert = chain
check_root_cert(root_cert, 2)
if not issued_by(upstream_cert, root_cert) or not is_ca(upstream_cert) or \
(path_length(upstream_cert) is not None and path_length(upstream_cert) < 1):
raise Failure('the Simple CA issuing CA is not a CA signed by the root that may sign CAs', 1)
if not verify_token(root['token'], upstream_cert):
raise Failure('the token is not signed by the Simple CA issuing CA of the chain', 1)
if not issued_by(cert, upstream_cert) or not is_ca(cert) or not same_key(cert.public_key(), request.public_key()):
raise Failure(f'the certificate Simple CA signed is not a CA certificate for the key of the CSR of {name}', 1)
if root['cert'] is not None and root['cert'] != root_cert:
raise Failure('the root of the Simple CA chain is not the server\'s root', 1)
if upstream is not None and upstream['cert'] is not None and upstream['cert'] != upstream_cert:
raise Failure('the Simple CA issuing CA of the chain is not the one that signed the server\'s issuing CAs', 1)
if root['cert'] is None:
update(connection, 'root', {'cACertificate;binary': cert_der(root_cert)})
if upstream is None or upstream['cert'] is None:
update(connection, UPSTREAM, {'cACertificate;binary': cert_der(upstream_cert)})
return cert
def crl_url(cert):
"""The first HTTP URL of the CRL distribution points of the certificate, None for none."""
try:
points = cert.extensions.get_extension_for_class(x509.CRLDistributionPoints).value
except x509.ExtensionNotFound:
return None
for point in points:
for name in point.full_name or []:
if isinstance(name, x509.UniformResourceIdentifier) and name.value.startswith(('http://', 'https://')):
return name.value
return None
def fetch_crls(connection):
"""Fetch the stale CRLs of the root and the upstream CA from the distribution points of the certificates they
signed, checked as an uploaded CRL is; the problems, as notices."""
notices = []
upstream = authority(connection, UPSTREAM)
signed = {'root': upstream['cert'] if upstream else None, UPSTREAM: None}
for name in issuing(connection):
entry = authority(connection, name)
if entry['cert'] is not None and signed[UPSTREAM] is None:
signed[UPSTREAM] = entry['cert']
for name, below in signed.items():
entry = authority(connection, name)
url = crl_url(below) if below is not None else None
if entry is None or entry['cert'] is None or url is None or not crl_stale(entry['crl']):
continue
try:
with urllib.request.urlopen(url, timeout=HTTP_TIMEOUT) as response:
data = response.read()
store_crl(connection, name, data, 'fetched')
except (urllib.error.URLError, OSError) as error:
notices.append(f'the CRL of {name} cannot be fetched from {url}: {error}')
except Failure as failure:
notices.append(f'the CRL of {name} from {url} is refused: {failure}')
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.
The root comes from pki.root (ROOT_SOURCES): local creates it with its key when there is none; offline waits for
its certificate (import_ca); simple-ca exchanges the setup code of SETUP_CODE_FILE for the token. Each issuing CA
without a certificate gets its key and a CSR, and is signed by the root key (local), by the Simple CA upstream CA
(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. 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.
"""
pki = cfg['pki']
urls = linuxmanager.pki_base_urls(cfg)
notices = []
def component_on(ca):
return ca not in BUILTIN_COMPONENTS or bool(cfg[BUILTIN_COMPONENTS[ca]]['enabled'])
with directory() as connection:
check_source(cfg, authority(connection, 'root'))
check_names(cfg, connection)
notice = take_setup_code(cfg)
if notice:
notices.append(notice)
with directory() as connection:
root = authority(connection, 'root')
if pki['root'] == 'local' and (root is None or root['cert'] is None):
root_key = new_key(pki['key'])
root_cert = sign(pki['root_name'], root_key.public_key(), None, root_key, pki['root_days'], ca_extensions(1))
update(connection, 'root', {'cACertificate;binary': cert_der(root_cert), 'linuxManagerPrivateKey': key_pem(root_key)})
root = authority(connection, 'root')
if pki['root'] == 'offline' and (root is None or root['cert'] is None):
notices.append('the root waits for its certificate: import it with linux-manager-ca ca import root FILE')
if pki['root'] == 'simple-ca' and (root is None or root['token'] is None):
notices.append('the server has no Simple CA token: give a setup code with linux-manager-ca root setup-code')
root_cert = root['cert'] if root else None
root_key = root['key'] if root else None
token = root['token'] if root else None
authorities = linuxmanager.issuing_cas(cfg)
force = set()
for name, settings in authorities.items():
entry = authority(connection, name)
if (entry is not None and entry['cert'] is not None) or not component_on(name):
continue
key = entry['key'] if entry is not None and entry['key'] is not None else None
if key is None:
key = new_key(pki['key'])
update(connection, name, {'linuxManagerPrivateKey': key_pem(key)})
if root_key is not None:
cert = sign(settings['name'].strip(), key.public_key(), root_cert, root_key, pki['ca_days'],
ca_extensions(0), urls, 'root')
update(connection, name, {'cACertificate;binary': cert_der(cert), 'linuxManagerCertificateRequest': None})
record(connection, cert, 'root', 'ca')
force.add(name)
continue
if entry is None or entry['csr'] is None:
request = (x509.CertificateSigningRequestBuilder()
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, settings['name'].strip())]))
.add_extension(x509.BasicConstraints(ca=True, path_length=0), True)
.add_extension(CA_USAGE, True)
.sign(key, digest(key)))
update(connection, name, {'linuxManagerCertificateRequest': request.public_bytes(serialization.Encoding.PEM)})
else:
request = x509.load_pem_x509_csr(entry['csr'])
if pki['root'] == 'simple-ca' and token is not None:
try:
cert = upstream_sign(cfg, connection, name, request)
except Failure as failure:
notices.append(f'issuing CA {name} waits for its certificate: {failure}')
continue
update(connection, name, {'cACertificate;binary': cert_der(cert), 'linuxManagerCertificateRequest': None})
record(connection, cert, UPSTREAM, 'ca')
force.add(name)
continue
if pki['root'] == 'offline':
notices.append(f'issuing CA {name} waits for its certificate: sign its CSR (linux-manager-ca ca csr {name}) '
f'with the root CA and import it with linux-manager-ca ca import {name}')
for name in issuing(connection):
if name in authorities:
continue
entry = authority(connection, name)
moment = now()
if entry['cert'] is not None:
serial = f'{entry["cert"].serial_number:X}'
for revoked in certificate_entries(connection, authority_dn('root'),
f'(serialNumber={serial})(!(linuxManagerRevoked=*))'):
connection.modify_s(revoked['dn'], [(ldap.MOD_REPLACE, 'linuxManagerRevoked', [generalized(moment)]),
(ldap.MOD_REPLACE, 'linuxManagerRevocationReason', [b'cessation_of_operation'])])
force.add('root')
if pki['root'] == 'offline':
notices.append(f'issuing CA {name} was retired: revoke its certificate on the root CRL offline and '
'upload the CRL with linux-manager-ca root import-crl')
if pki['root'] == 'simple-ca':
upstream_name = root['upstream_name'] if root else UPSTREAM
notices.append(f'issuing CA {name} was retired: revoke its certificate, serial {serial}, in Simple CA '
f'issuing CA {upstream_name}')
retired = f'{name}-{moment.strftime("%Y%m%d%H%M%S")}'
connection.rename_s(authority_dn(name), f'cn={retired}')
update(connection, retired, {'linuxManagerRetired': generalized(moment), 'linuxManagerPrivateKey': None})
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]) 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,
'(&(objectClass=inetOrgPerson)(mail=*)(!(userCertificate=*)))', ['uid', 'mail']) \
if component_on('p2s') and p2s and p2s['cert'] and p2s['key'] and not p2s['retired'] else []
for _, attributes in missing:
issue_user(cfg, attributes['uid'][0].decode(), attributes['mail'][0].decode())
return notices
def publish(connection):
"""Write the DER copies of the certificates and CRLs of the root, the upstream CA and the issuing CAs with a
certificate to PUBLISH_DIR, and remove any other file there; True when anything changed."""
PUBLISH_DIR.mkdir(parents=True, exist_ok=True)
os.chmod(PUBLISH_DIR, 0o755)
wanted = {}
for name in [*UPPER_CAS, *issuing(connection)]:
entry = authority(connection, name)
if entry is not None and entry['cert'] is not None:
wanted[f'{name}.crt'] = cert_der(entry['cert'])
if entry is not None and entry['crl'] is not None:
wanted[f'{name}.crl'] = entry['crl'].public_bytes(serialization.Encoding.DER)
changed = False
for path in PUBLISH_DIR.iterdir():
if path.name not in wanted:
path.unlink()
changed = True
for name, data in wanted.items():
changed |= write(PUBLISH_DIR / name, data, 0o644)
return changed
def remote_ca_file(connection):
"""The name in X509CA_DIR of the remote CA certificate of a site_to_site connection."""
return f's2s-{connection}.pem'
def openvpn_chain(connection):
"""The CAs of a VPN user's chain above the user, which OpenVPN reads: the root, the upstream CA when there is one,
and p2s."""
upstream = authority(connection, UPSTREAM)
return ['root', *([UPSTREAM] if upstream and upstream['cert'] is not None else []), 'p2s']
def install_crls(connection):
"""Write the CRLs of the root, the upstream CA, p2s and s2s for strongSwan, and those of openvpn_chain for
OpenVPN once each of them has one; True on change."""
changed = False
crls = {}
for name, file in SWANCTL_CA_FILES.items():
entry = authority(connection, name)
crls[name] = entry['crl'].public_bytes(serialization.Encoding.PEM) if entry and entry['crl'] is not None else None
changed |= write(X509CRL_DIR / file, crls[name], 0o644) if crls[name] else remove(X509CRL_DIR / file)
chain = openvpn_chain(connection)
if all(crls[name] for name in chain):
changed |= write(OPENVPN_CRL, b''.join(crls[name] for name in chain), 0o644)
return changed
def reload_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)
def distribute(cfg):
"""Write the certificates, keys and CRLs strongSwan, OpenVPN and the system's trust store read; True on change.
strongSwan gets the root, the upstream CA, p2s and s2s, the remote CA of each site_to_site connection that has
one, the server's certificates and keys, and the CRLs; OpenVPN the CAs of openvpn_chain in one file, and their
CRLs (install_crls). The trust store gets the root alone.
"""
changed = False
with directory() as connection:
certs = {}
for name, file in SWANCTL_CA_FILES.items():
entry = authority(connection, name)
certs[name] = cert_pem(entry['cert']) if entry and entry['cert'] else None
changed |= write(X509CA_DIR / file, certs[name], 0o644) if certs[name] else remove(X509CA_DIR / file)
remote = {remote_ca_file(name): connection_settings['remote_ca'].strip().encode() + b'\n'
for name, connection_settings in cfg['site_to_site'].items() if connection_settings['remote_ca'].strip()}
for path in X509CA_DIR.glob(remote_ca_file('*')):
if path.name not in remote:
changed |= remove(path)
for file, data in remote.items():
changed |= write(X509CA_DIR / file, data, 0o644)
for name, (cert_file, key_file) in ROUTER_FILES.items():
current = holders(connection, ROUTER_CERTS[name][0], router_condition(name))
if current:
_, cert, key = current[0]
changed |= write(cert_file, cert_pem(cert), 0o644)
changed |= write(key_file, key_pem(key), 0o600)
else:
changed |= remove(cert_file) | remove(key_file)
chain = openvpn_chain(connection)
if all(certs[name] for name in chain):
changed |= write(OPENVPN_CA, b''.join(certs[name] for name in chain), 0o644)
changed |= install_crls(connection)
if certs['root'] and write(TRUST_ANCHOR, certs['root'], 0o644):
changed = True
if shutil.which('update-ca-certificates'):
subprocess.run(['update-ca-certificates'], capture_output=True, text=True)
return changed
def bundle(name):
"""The PEM certificates a client trusts a CA with: {name, pem}; for root the root alone, for an issuing CA the
issuing CA, the upstream CA when there is one, and the root."""
with directory() as connection:
root = authority(connection, 'root')
entry = root if name == 'root' else authority(connection, name) if isinstance(name, str) else None
above = upper_chain(connection)
if root is None or root['cert'] is None:
raise Failure('there is no root CA', 3)
if entry is None or entry['retired']:
raise Failure(f'no CA {name}', 3)
if entry['cert'] is None:
raise Failure(f'issuing CA {name} has no certificate yet', 4)
pem = cert_pem(root['cert']) if name == 'root' else cert_pem(entry['cert']) + above
return {'name': name, 'pem': pem.decode()}
def upper_chain(connection):
"""The PEM certificates above an issuing CA in its chain: the upstream CA when there is one, then the root."""
upstream = authority(connection, UPSTREAM)
root = authority(connection, 'root')
return (cert_pem(upstream['cert']) if upstream and upstream['cert'] is not None else b'') + cert_pem(root['cert'])
def authority_files(name):
"""The PEM certificate and key of an issuing CA, for Caddy's ACME server; None when it has not both."""
with directory() as connection:
entry = authority(connection, name)
if not entry or entry['cert'] is None or entry['key'] is None:
return None
return cert_pem(entry['cert']), key_pem(entry['key'])
def issuer_of(connection, cfg, ca, template):
"""The entry of the issuing CA and the template, checked to be one the CA issues."""
authorities = linuxmanager.issuing_cas(cfg)
if ca not in authorities:
raise Failure(f'no issuing CA {ca}', 3)
if template not in authorities[ca]['templates']:
raise Failure(f'issuing CA {ca} does not issue {template} certificates', 2)
entry = authority(connection, ca)
if not entry or entry['cert'] is None or entry['key'] is None:
raise Failure(f'issuing CA {ca} has no certificate yet', 4)
return entry, linuxmanager.pki_templates(cfg)[template]
def issue(cfg, ca, template, csr=None, subject=None, sans=None, password=None):
"""Issue a certificate of the template from the issuing CA for something other than the server.
With a CSR, the certificate is for the CSR's key, common name and subject alternative names, and the answer is
{serial, certificate, chain} in PEM. Without one, the server makes a key of the template for the subject and sans,
and the answer is {serial, pfx}: a PKCS#12 file in base64 with the key, the certificate and the chain, protected
by the password; the key is not kept. The templates of linuxmanager.ROUTER_TEMPLATES are not issued here.
"""
if template in linuxmanager.ROUTER_TEMPLATES:
raise Failure(f'{template} certificates are issued by the server only', 2)
with directory() as connection:
issuer, values = issuer_of(connection, cfg, ca, template)
key = None
if csr is not None:
try:
request = x509.load_pem_x509_csr(csr.strip().encode() if isinstance(csr, str) else b'')
except ValueError:
raise Failure('the CSR is not a PEM certificate signing request', 2)
if not request.is_signature_valid:
raise Failure('the signature of the CSR is not valid', 2)
subject = common_name(request)
sans = [value.split(':', 1)[1] for value in san_values(request)]
public_key = request.public_key()
else:
if not isinstance(password, str) or not 1 <= len(password) <= PASSWORD_MAX:
raise Failure(f'the password of the PFX file must have 1 to {PASSWORD_MAX} characters', 2)
if sans is None:
sans = []
if not isinstance(sans, list):
raise Failure('sans must be a list of names', 2)
key = new_key(values['key'])
public_key = key.public_key()
subject = check_subject(values['subject'], subject)
names = general_names(([subject] if values['subject'] == 'dns' else []) + list(sans),
set(values['sans']) | ({'dns'} if values['subject'] == 'dns' else set()))
cert = sign(subject, public_key, issuer['cert'], issuer['key'], values['days'], leaf_extensions(cfg, values, names),
linuxmanager.pki_base_urls(cfg), ca)
record(connection, cert, ca, 'external', template)
above = upper_chain(connection)
serial = f'{cert.serial_number:X}'
if key is None:
return {'serial': serial, 'certificate': cert_pem(cert).decode(),
'chain': (cert_pem(issuer['cert']) + above).decode()}
encryption = (serialization.PrivateFormat.PKCS12.encryption_builder()
.kdf_rounds(50000)
.key_cert_algorithm(pkcs12.PBES.PBESv1SHA1And3KeyTripleDESCBC)
.hmac_hash(hashes.SHA1())
.build(password.encode()))
pfx = pkcs12.serialize_key_and_certificates(subject.encode(), key, cert,
[issuer['cert'], *x509.load_pem_x509_certificates(above)], encryption)
return {'serial': serial, 'pfx': base64.b64encode(pfx).decode()}
def user_dn(name):
return f'uid={ldap.dn.escape_dn_chars(name)},{linuxmanager_ldap.USERS}'
def issue_user(cfg, name, email):
"""Issue the user's certificate from the P2S CA with the template vpn-user: the user name as the common name and a
DNS name, and the e-mail address; it is kept with its key, and is the userCertificate of the user's entry."""
with directory() as connection:
issuer, values = issuer_of(connection, cfg, 'p2s', 'vpn-user')
key = new_key(values['key'])
cert = sign(name, key.public_key(), issuer['cert'], issuer['key'], values['days'],
leaf_extensions(cfg, values, general_names([name, email], linuxmanager.SAN_TYPES)),
linuxmanager.pki_base_urls(cfg), 'p2s')
for dn, _, _ in holders(connection, 'p2s', user_condition(name)):
drop_key(connection, dn)
record(connection, cert, 'p2s', 'user', 'vpn-user', key)
connection.modify_s(user_dn(name), [(ldap.MOD_REPLACE, 'userCertificate;binary', [cert_der(cert)])])
def user_credentials(name):
"""The PEM certificate and key of the user's current certificate, None when the user has none."""
with directory() as connection:
current = holders(connection, 'p2s', user_condition(name))
if not current:
return None
_, cert, key = current[0]
return cert_pem(cert), key_pem(key)
def revoke_entries(connection, cfg, entries, reason):
"""Mark the certificates revoked, sign new CRLs of their CAs, and publish and install them."""
names = {entry['ca'] for entry in entries}
for name in names:
current = authority(connection, name)
if not current or current['key'] is None:
raise Failure(f'the key of {name} is not on the server, so it cannot sign its CRL', 4)
moment = generalized(now())
for entry in entries:
connection.modify_s(entry['dn'], [(ldap.MOD_REPLACE, 'linuxManagerRevoked', [moment]),
(ldap.MOD_REPLACE, 'linuxManagerRevocationReason', [reason.encode()]),
(ldap.MOD_REPLACE, 'linuxManagerPrivateKey', [])])
for name in names:
sign_crl(connection, cfg, name)
publish(connection)
reload_crls(connection)
def revoke_user(cfg, name):
"""Revoke the user's certificates, and remove the userCertificate of the user's entry."""
with directory() as connection:
entries = certificate_entries(connection, authority_dn('p2s'), f'{user_condition(name)}(!(linuxManagerRevoked=*))')
if entries:
revoke_entries(connection, cfg, entries, 'cessation_of_operation')
with contextlib.suppress(ldap.NO_SUCH_OBJECT):
connection.modify_s(user_dn(name), [(ldap.MOD_REPLACE, 'userCertificate;binary', [])])
def revoke(cfg, serial, reason=None):
"""Revoke a certificate the server issued, by its serial number, for one of REASONS.
A user's certificate is revoked by removing the user, and an issuing CA by removing it from pki.issuing_cas. A
revoked router certificate loses its key, so that linux-manager-setup issues a new one; the answer says so with
reissue.
"""
reason = reason or 'unspecified'
if reason not in REASONS:
raise Failure(f'the reason must be one of {", ".join(REASONS)}', 2)
if not isinstance(serial, str) or not SERIAL.match(serial):
raise Failure('the serial number must be hexadecimal', 2)
with directory() as connection:
found = certificate_entries(connection, linuxmanager_ldap.PKI, f'(serialNumber={serial.upper().lstrip("0")})')
if not found:
raise Failure(f'no certificate with the serial number {serial}', 3)
entry = found[0]
if entry['revoked']:
raise Failure(f'certificate {serial} is revoked', 4)
if entry['kind'] == 'user':
raise Failure(f'certificate {serial} is the certificate of user {entry["subject"]}; remove the user', 2)
if entry['kind'] == 'ca':
raise Failure(f'certificate {serial} is an issuing CA; remove it from pki.issuing_cas', 2)
revoke_entries(connection, cfg, [entry], reason)
return {**{key: value for key, value in entry.items() if key != 'dn'}, 'revoked': iso(now()), 'reason': reason,
'reissue': entry['kind'] == 'router'}
def certificates():
"""The certificates the server issued, newest first, each with state: valid, expired or revoked."""
moment = iso(now())
with directory() as connection:
entries = certificate_entries(connection, linuxmanager_ldap.PKI)
return [{**{key: value for key, value in entry.items() if key != 'dn'},
'ca': RETIRED_SUFFIX.sub('', entry['ca']),
'state': 'revoked' if entry['revoked'] else 'expired' if (entry['expires'] or '') <= moment else 'valid'}
for entry in entries]
def csr(cfg, name):
"""The CSR of a pending issuing CA and the openssl extension section to sign it with: {name, csr, extensions}."""
if name not in linuxmanager.issuing_cas(cfg):
raise Failure(f'no issuing CA {name}', 3)
with directory() as connection:
entry = authority(connection, name)
if not entry or entry['cert'] is not None or entry['csr'] is None:
raise Failure(f'issuing CA {name} is not waiting for a certificate', 4)
urls = linuxmanager.pki_base_urls(cfg)
lines = ['[ issuing_ca ]', 'basicConstraints = critical, CA:TRUE, pathlen:0', 'keyUsage = critical, keyCertSign, cRLSign',
'subjectKeyIdentifier = hash', 'authorityKeyIdentifier = keyid:always']
if urls:
lines.append('authorityInfoAccess = ' + ', '.join(f'caIssuers;URI:{url}root.crt' for url in urls))
lines.append('crlDistributionPoints = ' + ', '.join(f'URI:{url}root.crl' for url in urls))
return {'name': name, 'csr': entry['csr'].decode(), 'extensions': '\n'.join(lines) + '\n'}
def import_ca(cfg, name, text):
"""Take the certificate of the offline root, or of a pending issuing CA signed by the root offline.
The root's must be a self-signed CA certificate that allows a CA below it, while pki.root is offline and the root
has none. An issuing CA's must be a CA certificate the root signed for the key of the CA's CSR, once the root has
its certificate.
"""
if name != 'root' and name not in linuxmanager.issuing_cas(cfg):
raise Failure(f'no issuing CA {name}', 3)
try:
cert = x509.load_pem_x509_certificate(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:
root = authority(connection, 'root')
if name == 'root':
if cfg['pki']['root'] != 'offline':
raise Failure(f'the root is not offline: pki.root is {cfg["pki"]["root"]}', 4)
check_source(cfg, root)
if root is not None and root['cert'] is not None:
raise Failure('the root has its certificate', 4)
check_root_cert(cert, 1)
update(connection, 'root', {'cACertificate;binary': cert_der(cert)})
publish(connection)
return {'name': name, 'subject': common_name(cert), 'expires': iso(utc(cert, 'not_valid_after'))}
entry = authority(connection, name)
if entry is not None and entry['cert'] is not None:
raise Failure(f'issuing CA {name} has its certificate', 4)
if entry is None or entry['key'] is None:
raise Failure(f'issuing CA {name} has no key; linux-manager-setup makes it with the CSR', 3)
if root is None or root['cert'] is None:
raise Failure('the root has no certificate yet: import the root first', 4)
if not issued_by(cert, root['cert']):
raise Failure('the certificate is not signed by the root CA', 2)
if not same_key(cert.public_key(), entry['key'].public_key()):
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)
publish(connection)
return {'name': name, 'subject': common_name(cert), 'expires': iso(utc(cert, 'not_valid_after'))}
def store_crl(connection, name, data, source):
"""Keep a CRL of the root or the upstream CA, in PEM or DER, from source, uploaded or fetched: it must be signed by
the CA and not older than the current one; the CRL."""
if isinstance(data, str):
data = data.strip().encode()
try:
crl = x509.load_pem_x509_crl(data) if data.lstrip().startswith(b'-----') else x509.load_der_x509_crl(data)
except ValueError:
raise Failure('the CRL is not a PEM or DER certificate revocation list', 2)
entry = authority(connection, name)
if entry is None or entry['cert'] is None:
raise Failure(f'there is no {name} CA', 3)
if crl.issuer != entry['cert'].subject or not crl.is_signature_valid(entry['cert'].public_key()):
raise Failure(f'the CRL is not signed by the {name} CA', 2)
if entry['crl'] is not None and utc(crl, 'last_update') < utc(entry['crl'], 'last_update'):
raise Failure('the CRL is older than the current one', 2)
update(connection, name, {'certificateRevocationList;binary': crl.public_bytes(serialization.Encoding.DER),
'linuxManagerCRLSource': source.encode()})
return crl
def import_root_crl(cfg, data):
"""Take a CRL of the offline root, in PEM or DER; it must be signed by the root and not older than the current
one."""
if cfg['pki']['root'] != 'offline':
raise Failure(f'the root CRL is uploaded for an offline root only: pki.root is {cfg["pki"]["root"]}', 4)
with directory() as connection:
crl = store_crl(connection, 'root', data, 'uploaded')
publish(connection)
reload_crls(connection)
following = utc(crl, 'next_update')
return {'next_update': iso(following) if following else None}
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, 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 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
for entry in (authority(connection, name) for name in linuxmanager.issuing_cas(cfg)))
return notices, waiting or any(renewal_due(cert) for cert in due)
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'
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. 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 = []
def crl_of(entry):
"""The next update of the CA's CRL; a CRL the server signs or fetches warns once past half of its validity,
which the timer renews before, and one uploaded WARN_DAYS before it expires."""
crl = entry['crl']
following = utc(crl, 'next_update') if crl is not None else None
if crl is None:
warnings.append(f'{entry["name"]} has no CRL')
elif following is not None and (crl_stale(crl) if entry['key'] is not None or entry['crl_source'] == 'fetched'
else following <= soon):
warnings.append(f'the CRL of {entry["name"]} {"expired" if following <= moment else "expires"} on {iso(following)}')
return iso(following) if following else None
with directory() as connection:
root_entry = authority(connection, 'root')
upstream_entry = authority(connection, UPSTREAM)
entries = {name: authority(connection, name) for name in linuxmanager.issuing_cas(cfg)}
retired_found = connection.search_s(linuxmanager_ldap.PKI, ldap.SCOPE_ONELEVEL,
'(&(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 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
root = {'source': source, 'state': 'pending', 'subject': None, 'expires': None, 'crl_next_update': None,
'crl_source': None, 'simple_ca_url': cfg['pki']['simple_ca_url'].strip() if source == 'simple-ca' else None,
'upstream': None, 'token_expires': token_expires(token) if token else None}
if root_entry is not None and root_entry['cert'] is not None:
cert = root_entry['cert']
root.update({'state': 'active', 'subject': common_name(cert), 'expires': iso(utc(cert, 'not_valid_after')),
'crl_next_update': crl_of(root_entry) if source == 'local' or root_entry['crl'] is not None else None,
'crl_source': root_entry['crl_source']})
if source == 'offline' and root_entry['crl'] is None:
warnings.append('the root has no CRL; sign one offline and upload it with linux-manager-ca root import-crl')
if source == 'simple-ca' and root_entry['crl'] is None:
warnings.append('the root has no CRL yet; the server fetches it from Simple CA')
if utc(cert, 'not_valid_after') <= soon:
warnings.append(f'the root certificate expires on {root["expires"]}')
elif source == 'offline':
warnings.append('the root waits for its certificate: import it with linux-manager-ca ca import root FILE')
if source == 'simple-ca' and token is None:
warnings.append('the server has no Simple CA token: give a setup code with linux-manager-ca root setup-code')
if upstream_entry is not None and upstream_entry['cert'] is not None:
cert = upstream_entry['cert']
root['upstream'] = {'name': root_entry['upstream_name'], 'subject': common_name(cert),
'expires': iso(utc(cert, 'not_valid_after')),
'crl_next_update': crl_of(upstream_entry) if upstream_entry['crl'] is not None else None}
if upstream_entry['crl'] is None:
warnings.append('the Simple CA issuing CA has no CRL yet; the server fetches it from Simple CA')
if utc(cert, 'not_valid_after') <= soon:
warnings.append(f'the certificate of the Simple CA issuing CA expires on {root["upstream"]["expires"]}')
authorities = []
for name, settings in linuxmanager.issuing_cas(cfg).items():
entry = entries[name]
cert = entry['cert'] if entry else None
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,
'key': bool(entry and entry['key'] is not None), 'crl_next_update': crl_of(entry) if cert is not None else None,
'acme_url': acme_url(cfg, name) if settings['acme'] and cert is not None else None,
})
if kind == 'pending':
warnings.append(f'issuing CA {name} waits for its certificate signed by '
f'{"Simple CA" if source == "simple-ca" else "the root CA"}')
if cert is not None and utc(cert, 'not_valid_after') <= soon:
warnings.append(f'the certificate of issuing CA {name} expires on {authorities[-1]["expires"]}')
retired = []
for _, attributes in retired_found:
der = first(attributes, 'cACertificate;binary')
serial = f'{x509.load_der_x509_certificate(der).serial_number:X}' if der else None
name = RETIRED_SUFFIX.sub('', attributes['cn'][0].decode())
retired.append({'name': name, 'retired': from_generalized(first(attributes, 'linuxManagerRetired')), 'serial': serial})
signer = upstream_entry if source == 'simple-ca' else root_entry
signer_crl = signer['crl'] if signer else None
if serial and signer_crl is not None and signer_crl.get_revoked_certificate_by_serial_number(int(serial, 16)) is None:
warnings.append(f'the {"Simple CA issuing CA" if source == "simple-ca" else "root"} CRL does not revoke '
f'retired issuing CA {name}')
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}