fix: the root CA is created by the server, an offline CA or a Simple CA service, chosen at setup; the shell can stay open in a tab of its own, the Docker page is offered only with Docker, and the test scripts are in bin/.
Release / release (push) Failing after 14m20s
Release / release (push) Failing after 14m20s
This commit is contained in:
1 parent
ff0c93ed73
commit
a649331aa2
49 files changed
+1597
-637
No files matched your search
@@ -4,15 +4,20 @@ The root CA signs the issuing CAs, and only them: p2s, which signs the server's
|
||||
certificates, s2s, which signs the server's site-to-site certificate and those of its peers, 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; while the root key is not on the server, a new issuing CA has its key and a CSR and is pending until import_ca
|
||||
takes its certificate, signed offline. 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.
|
||||
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.
|
||||
|
||||
An existing root CA is supplied by placing its certificate, and its key if the server may use it, in SEED_DIR before
|
||||
linux-manager-setup runs; provision imports them into the directory and removes the files.
|
||||
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
|
||||
@@ -28,12 +33,17 @@ 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
|
||||
@@ -42,15 +52,28 @@ 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, rsa
|
||||
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 certificate (cert.pem) and the key (key.pem) of an existing root CA, which provision imports and removes.
|
||||
SEED_DIR = pathlib.Path('/etc/linux-manager/pki/root')
|
||||
#: 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')
|
||||
@@ -63,13 +86,14 @@ 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', 'p2s': 'p2s.pem', 's2s': 's2s.pem'}
|
||||
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 and the P2S CA, and their CRLs, which it needs for every CA of a client's chain.
|
||||
#: 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')
|
||||
|
||||
@@ -86,7 +110,8 @@ ROUTER_FILES = {'vpn-server': (VPN_SERVER_CERT, VPN_SERVER_KEY), 'site-to-site':
|
||||
|
||||
#: The attributes of a CA's entry and of a certificate's entry.
|
||||
AUTHORITY_ATTRIBUTES = ['cACertificate;binary', 'certificateRevocationList;binary', 'linuxManagerPrivateKey',
|
||||
'linuxManagerCertificateRequest', 'linuxManagerCRLNumber', 'linuxManagerCRLSource', 'linuxManagerRetired']
|
||||
'linuxManagerCertificateRequest', 'linuxManagerCRLNumber', 'linuxManagerCRLSource', 'linuxManagerRetired',
|
||||
'linuxManagerToken', 'linuxManagerUpstreamName']
|
||||
CERTIFICATE_ATTRIBUTES = ['serialNumber', 'cn', 'linuxManagerKind', 'linuxManagerTemplate', 'linuxManagerSubjectAltName',
|
||||
'linuxManagerNotAfter', 'linuxManagerRevoked', 'linuxManagerRevocationReason', 'createTimestamp']
|
||||
|
||||
@@ -216,7 +241,8 @@ def authority_dn(name):
|
||||
|
||||
|
||||
def authority(connection, name):
|
||||
"""The entry of a CA: {name, cert, key, csr (PEM), crl, crl_number, crl_source, retired}, None when there is none."""
|
||||
"""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:
|
||||
@@ -231,6 +257,8 @@ def authority(connection, name):
|
||||
'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,
|
||||
}
|
||||
|
||||
|
||||
@@ -251,7 +279,8 @@ def update(connection, name, values):
|
||||
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=*))(!(cn=root)))', ['cn'])
|
||||
'(&(objectClass=linuxManagerAuthority)(!(linuxManagerRetired=*))'
|
||||
f'(!(cn=root))(!(cn={UPSTREAM})))', ['cn'])
|
||||
return sorted(attributes['cn'][0].decode() for _, attributes in found)
|
||||
|
||||
|
||||
@@ -600,38 +629,232 @@ def ensure_router_cert(connection, cfg, ctx, name, urls):
|
||||
drop_key(connection, dn)
|
||||
|
||||
|
||||
def import_seed(connection):
|
||||
"""Import the root CA of SEED_DIR into the directory, and remove the files; False when there is none."""
|
||||
cert_file, key_file = SEED_DIR / 'cert.pem', SEED_DIR / 'key.pem'
|
||||
if not cert_file.is_file():
|
||||
if key_file.is_file():
|
||||
raise Failure(f'{key_file} has no certificate; place cert.pem beside it')
|
||||
return False
|
||||
cert = x509.load_pem_x509_certificate(cert_file.read_bytes())
|
||||
key = serialization.load_pem_private_key(key_file.read_bytes(), None) if key_file.is_file() else None
|
||||
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(f'{cert_file} is not a CA certificate')
|
||||
if key is not None and not same_key(key.public_key(), cert.public_key()):
|
||||
raise Failure(f'{key_file} is not the key of {cert_file}')
|
||||
update(connection, 'root', {'cACertificate;binary': cert_der(cert), 'linuxManagerPrivateKey': key_pem(key) if key else None})
|
||||
for path in (key_file, cert_file):
|
||||
remove(path)
|
||||
for folder in (SEED_DIR, SEED_DIR.parent):
|
||||
with contextlib.suppress(OSError):
|
||||
folder.rmdir()
|
||||
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 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 provision(cfg, ctx):
|
||||
"""Create what the configuration needs and is missing, and keep it current; the notices to report.
|
||||
|
||||
The root is imported from SEED_DIR, or created when it has neither certificate nor seed. Each issuing CA without a
|
||||
certificate is signed by the root key, or, while the root key is not on the server, gets its key and a CSR and is
|
||||
pending. An issuing CA that pki.issuing_cas no longer names is retired, and its certificate revoked on the root CRL.
|
||||
Stale CRLs are signed again, the server's certificates 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.
|
||||
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, the server's certificates 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)
|
||||
@@ -640,17 +863,26 @@ def provision(cfg, ctx):
|
||||
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'))
|
||||
notice = take_setup_code(cfg)
|
||||
if notice:
|
||||
notices.append(notice)
|
||||
|
||||
with directory() as connection:
|
||||
root = authority(connection, 'root')
|
||||
if root is None or root['cert'] is None:
|
||||
if root is not None and root['key'] is not None:
|
||||
raise Failure('the root has a key but no certificate')
|
||||
if not import_seed(connection):
|
||||
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)})
|
||||
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')
|
||||
root_cert, root_key = root['cert'], root['key']
|
||||
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()
|
||||
@@ -676,8 +908,21 @@ def provision(cfg, ctx):
|
||||
.add_extension(CA_USAGE, True)
|
||||
.sign(key, digest(key)))
|
||||
update(connection, name, {'linuxManagerCertificateRequest': request.public_bytes(serialization.Encoding.PEM)})
|
||||
notices.append(f'issuing CA {name} waits for its certificate: sign its CSR (linux-manager-ca ca csr {name}) with '
|
||||
f'the root CA and import it with linux-manager-ca ca import {name}')
|
||||
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:
|
||||
@@ -691,14 +936,20 @@ def provision(cfg, ctx):
|
||||
connection.modify_s(revoked['dn'], [(ldap.MOD_REPLACE, 'linuxManagerRevoked', [generalized(moment)]),
|
||||
(ldap.MOD_REPLACE, 'linuxManagerRevocationReason', [b'cessation_of_operation'])])
|
||||
force.add('root')
|
||||
if root_key is None:
|
||||
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))
|
||||
for name in ROUTER_CERTS:
|
||||
if component_on(ROUTER_CERTS[name][0]):
|
||||
ensure_router_cert(connection, cfg, ctx, name, urls)
|
||||
@@ -713,12 +964,12 @@ def provision(cfg, ctx):
|
||||
|
||||
|
||||
def publish(connection):
|
||||
"""Write the DER copies of the certificates and CRLs of the root and the issuing CAs with a certificate to
|
||||
PUBLISH_DIR, and remove any other file there; True when anything changed."""
|
||||
"""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 ['root', *issuing(connection)]:
|
||||
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'])
|
||||
@@ -739,17 +990,25 @@ def remote_ca_file(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, p2s and s2s for strongSwan, and those of the root and p2s for OpenVPN; True on
|
||||
change."""
|
||||
"""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)
|
||||
if crls['root'] and crls['p2s']:
|
||||
changed |= write(OPENVPN_CRL, crls['root'] + crls['p2s'], 0o644)
|
||||
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
|
||||
|
||||
|
||||
@@ -762,8 +1021,9 @@ def reload_crls(connection):
|
||||
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, 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 root and p2s in one file, and their CRLs (install_crls).
|
||||
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:
|
||||
@@ -787,8 +1047,9 @@ def distribute(cfg):
|
||||
changed |= write(key_file, key_pem(key), 0o600)
|
||||
else:
|
||||
changed |= remove(cert_file) | remove(key_file)
|
||||
if certs['root'] and certs['p2s']:
|
||||
changed |= write(OPENVPN_CA, certs['root'] + certs['p2s'], 0o644)
|
||||
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
|
||||
@@ -799,20 +1060,28 @@ def distribute(cfg):
|
||||
|
||||
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 followed by the root."""
|
||||
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']) + cert_pem(root['cert'])
|
||||
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:
|
||||
@@ -873,17 +1142,18 @@ def issue(cfg, ca, template, csr=None, subject=None, sans=None, password=None):
|
||||
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)
|
||||
root = authority(connection, 'root')['cert']
|
||||
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']) + cert_pem(root)).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'], root], encryption)
|
||||
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()}
|
||||
|
||||
|
||||
@@ -1001,21 +1271,38 @@ def csr(cfg, name):
|
||||
|
||||
|
||||
def import_ca(cfg, name, text):
|
||||
"""Take the certificate of a pending issuing CA, signed by the root offline: it must be a CA certificate the root
|
||||
signed for the key of the CA's CSR."""
|
||||
if name not in linuxmanager.issuing_cas(cfg):
|
||||
"""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)
|
||||
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)
|
||||
if not issued_by(cert, authority(connection, 'root')['cert']):
|
||||
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)
|
||||
@@ -1028,75 +1315,56 @@ def import_ca(cfg, name, text):
|
||||
return {'name': name, 'subject': common_name(cert), 'expires': iso(utc(cert, 'not_valid_after'))}
|
||||
|
||||
|
||||
def import_root_crl(data):
|
||||
"""Take a CRL of the root signed offline, in PEM or DER; it must be signed by the root and not older than the
|
||||
current one."""
|
||||
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.startswith(b'-----') else x509.load_der_x509_crl(data)
|
||||
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:
|
||||
root = authority(connection, 'root')
|
||||
if root is None or root['cert'] is None:
|
||||
raise Failure('there is no root CA', 3)
|
||||
if crl.issuer != root['cert'].subject or not crl.is_signature_valid(root['cert'].public_key()):
|
||||
raise Failure('the CRL is not signed by the root CA', 2)
|
||||
if root['crl'] is not None and utc(crl, 'last_update') < utc(root['crl'], 'last_update'):
|
||||
raise Failure('the CRL is older than the current one', 2)
|
||||
update(connection, 'root', {'certificateRevocationList;binary': crl.public_bytes(serialization.Encoding.DER),
|
||||
'linuxManagerCRLSource': b'uploaded'})
|
||||
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 export_root_key(passphrase):
|
||||
"""The root key in PEM, encrypted with the passphrase."""
|
||||
if not passphrase:
|
||||
raise Failure('the passphrase is required', 2)
|
||||
with directory() as connection:
|
||||
root = authority(connection, 'root')
|
||||
if root is None or root['key'] is None:
|
||||
raise Failure('the root key is not on the server', 3)
|
||||
return key_pem(root['key'], passphrase.encode())
|
||||
|
||||
|
||||
def remove_root_key():
|
||||
with directory() as connection:
|
||||
root = authority(connection, 'root')
|
||||
if root is None or root['key'] is None:
|
||||
raise Failure('the root key is not on the server', 3)
|
||||
update(connection, 'root', {'linuxManagerPrivateKey': None})
|
||||
|
||||
|
||||
def import_root_key(data, passphrase=None):
|
||||
"""Put the root key back, PEM, encrypted with the passphrase or not; it must be the key of the root certificate."""
|
||||
try:
|
||||
key = serialization.load_pem_private_key(data, passphrase.encode() if passphrase else None)
|
||||
except (ValueError, TypeError):
|
||||
raise Failure('the file is not a PEM private key, or the passphrase is wrong', 2)
|
||||
with directory() as connection:
|
||||
root = authority(connection, 'root')
|
||||
if root is None or root['cert'] is None:
|
||||
raise Failure('there is no root CA', 3)
|
||||
if not same_key(key.public_key(), root['cert'].public_key()):
|
||||
raise Failure('the key is not the key of the root CA', 2)
|
||||
update(connection, 'root', {'linuxManagerPrivateKey': key_pem(key)})
|
||||
|
||||
|
||||
def maintain(cfg):
|
||||
"""Sign the stale CRLs again, publish and install them; True when one of the server's certificates is due for
|
||||
renewal, which linux-manager-setup does."""
|
||||
"""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."""
|
||||
with directory() as connection:
|
||||
refresh_crls(connection, cfg)
|
||||
notices = fetch_crls(connection) if cfg['pki']['root'] == 'simple-ca' else []
|
||||
publish(connection)
|
||||
reload_crls(connection)
|
||||
due = [current[0][1] for current in (holders(connection, ROUTER_CERTS[name][0], router_condition(name))
|
||||
for name in ROUTER_CERTS) if current]
|
||||
return any(renewal_due(cert) for cert in due)
|
||||
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):
|
||||
@@ -1105,25 +1373,27 @@ def acme_url(cfg, name):
|
||||
|
||||
|
||||
def status(cfg):
|
||||
"""The root, the issuing CAs, the retired CAs and the warnings, as /ca and linux-manager-ca status show them; the root
|
||||
key on the server is a warning while pki.root_key_warning is true."""
|
||||
"""The root, the upstream CA, the issuing CAs, the retired CAs and the warnings, as /ca and linux-manager-ca status
|
||||
show them."""
|
||||
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 warns once past half of its validity, which the timer
|
||||
renews before, and one signed offline WARN_DAYS before it expires."""
|
||||
"""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 else following <= soon):
|
||||
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=*))',
|
||||
@@ -1131,19 +1401,35 @@ def status(cfg):
|
||||
router_certs = [current[0][1] for current in (holders(connection, ROUTER_CERTS[name][0], router_condition(name))
|
||||
for name in ROUTER_CERTS) if current]
|
||||
|
||||
root = None
|
||||
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, key = root_entry['cert'], root_entry['key'] is not None
|
||||
root = {'subject': common_name(cert), 'expires': iso(utc(cert, 'not_valid_after')), 'key': key,
|
||||
'crl_next_update': crl_of(root_entry) if key or root_entry['crl'] is not None else None,
|
||||
'crl_source': root_entry['crl_source']}
|
||||
if key and cfg['pki']['root_key_warning']:
|
||||
warnings.append('the root key is on the server; export it with linux-manager-ca root export-key and remove it '
|
||||
'with linux-manager-ca root remove-key to keep the root offline')
|
||||
elif not key and root_entry['crl'] is 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():
|
||||
@@ -1159,7 +1445,8 @@ def status(cfg):
|
||||
'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 the root CA')
|
||||
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"]}')
|
||||
|
||||
@@ -1169,9 +1456,11 @@ def status(cfg):
|
||||
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})
|
||||
root_crl = root_entry['crl'] if root_entry else None
|
||||
if serial and root_crl is not None and root_crl.get_revoked_certificate_by_serial_number(int(serial, 16)) is None:
|
||||
warnings.append(f'the root CRL does not revoke retired issuing CA {name}')
|
||||
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"))}')
|
||||
|
||||
Reference in new issue
Block a user