fix: the directory holds up to 1 GiB, a revocation missing from its CRL is signed into it, and a setup without the directory keeps the certificates Caddy serves.
Release / release (push) Successful in 1m41s
Release / release (push) Successful in 1m41s
This commit is contained in:
1 parent
240255b2ff
commit
d59172c403
6 files changed
+79
-31
No files matched your search
@@ -86,6 +86,9 @@ TOTP_WINDOW = 1
|
||||
#: The value of pwdAccountLockedTime that disables a user until it is enabled again.
|
||||
DISABLED = '000001010000Z'
|
||||
|
||||
#: The largest size of the database, in bytes: slapd-mdb's olcDbMaxSize.
|
||||
DB_MAX_SIZE = 1024 ** 3
|
||||
|
||||
#: The indexes of the database.
|
||||
INDEXES = ('objectClass eq', 'uid eq', 'uidNumber eq', 'linuxManagerConsoleLogin eq', 'linuxManagerCertificateName eq')
|
||||
|
||||
@@ -190,9 +193,10 @@ def _ensure_password_hash(connection):
|
||||
|
||||
|
||||
def _ensure_database(connection):
|
||||
"""The DN of the package's database in cn=config, created when missing; its ACLs are kept as ACCESS, and the
|
||||
indexes of INDEXES it lacks are added, which slapd builds online."""
|
||||
found = connection.search_s('cn=config', ldap.SCOPE_ONELEVEL, f'(olcSuffix={BASE})', ['olcAccess', 'olcDbIndex'])
|
||||
"""The DN of the package's database in cn=config, created when missing; its ACLs are kept as ACCESS, a largest size
|
||||
below DB_MAX_SIZE is raised to it, and the indexes of INDEXES it lacks are added, which slapd builds online."""
|
||||
wanted = ['olcAccess', 'olcDbIndex', 'olcDbMaxSize']
|
||||
found = connection.search_s('cn=config', ldap.SCOPE_ONELEVEL, f'(olcSuffix={BASE})', wanted)
|
||||
if not found:
|
||||
DB_DIRECTORY.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
openldap = pwd.getpwnam('openldap')
|
||||
@@ -203,11 +207,14 @@ def _ensure_database(connection):
|
||||
'olcSuffix': [BASE.encode()],
|
||||
'olcDbDirectory': [str(DB_DIRECTORY).encode()],
|
||||
'olcRootDN': [ROOT.encode()],
|
||||
'olcDbMaxSize': [str(DB_MAX_SIZE).encode()],
|
||||
'olcDbIndex': [index.encode() for index in INDEXES],
|
||||
'olcAccess': [f'{{{index}}}{rule}'.encode() for index, rule in enumerate(ACCESS)],
|
||||
}))
|
||||
found = connection.search_s('cn=config', ldap.SCOPE_ONELEVEL, f'(olcSuffix={BASE})', ['olcAccess', 'olcDbIndex'])
|
||||
found = connection.search_s('cn=config', ldap.SCOPE_ONELEVEL, f'(olcSuffix={BASE})', wanted)
|
||||
dn, attributes = found[0]
|
||||
if int(attributes.get('olcDbMaxSize', [b'0'])[0]) < DB_MAX_SIZE:
|
||||
connection.modify_s(dn, [(ldap.MOD_REPLACE, 'olcDbMaxSize', [str(DB_MAX_SIZE).encode()])])
|
||||
if unordered(attributes.get('olcAccess', [])) != list(ACCESS):
|
||||
connection.modify_s(dn, [(ldap.MOD_REPLACE, 'olcAccess', [f'{{{index}}}{rule}'.encode() for index, rule in enumerate(ACCESS)])])
|
||||
present = [value.decode() for value in attributes.get('olcDbIndex', [])]
|
||||
|
||||
@@ -523,6 +523,12 @@ def check_subject(kind, subject):
|
||||
return subject.lower() if kind == 'dns' else subject
|
||||
|
||||
|
||||
def revoked_unexpired(connection, name, moment):
|
||||
"""The entries of the certificates the CA revoked that have not expired at moment, which its CRL lists."""
|
||||
return [entry for entry in certificate_entries(connection, authority_dn(name), '(linuxManagerRevoked=*)')
|
||||
if not entry['expires'] or entry['expires'] > iso(moment)]
|
||||
|
||||
|
||||
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."""
|
||||
@@ -537,9 +543,7 @@ def sign_crl(connection, cfg, name):
|
||||
.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
|
||||
for revoked_entry in revoked_unexpired(connection, name, moment):
|
||||
revoked = (x509.RevokedCertificateBuilder()
|
||||
.serial_number(int(revoked_entry['serial'], 16))
|
||||
.revocation_date(datetime.datetime.strptime(revoked_entry['revoked'], '%Y-%m-%dT%H:%M:%SZ')
|
||||
@@ -569,10 +573,13 @@ def ready(name):
|
||||
|
||||
|
||||
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."""
|
||||
"""Sign a new CRL for each CA with its key on the server whose CRL is stale or lacks a revoked certificate that
|
||||
has not expired, 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'])):
|
||||
if entry and entry['key'] and entry['cert'] and (name in force or crl_stale(entry['crl']) or any(
|
||||
entry['crl'].get_revoked_certificate_by_serial_number(int(revoked['serial'], 16)) is None
|
||||
for revoked in revoked_unexpired(connection, name, now()))):
|
||||
sign_crl(connection, cfg, name)
|
||||
|
||||
|
||||
@@ -1582,9 +1589,9 @@ def import_root_crl(cfg, data):
|
||||
|
||||
|
||||
def maintain(cfg):
|
||||
"""Sign the stale CRLs again or, with simple-ca, fetch them, publish and install them; the notices, and True when
|
||||
one of the server's certificates is due for renewal, 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."""
|
||||
"""Sign the CRLs of refresh_crls again and, with simple-ca, fetch the stale ones, 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 []
|
||||
|
||||
@@ -739,6 +739,12 @@ def manage_resolver(changed):
|
||||
run(['systemctl', 'restart', RESOLVER_UNIT], check=False)
|
||||
|
||||
|
||||
def caddy_copies(folder):
|
||||
"""The certificate and key copied to folder for Caddy, cert.pem and key.pem; None when it has not both."""
|
||||
files = (folder / 'cert.pem', folder / 'key.pem')
|
||||
return tuple(file.read_bytes() for file in files) if all(file.is_file() for file in files) else None
|
||||
|
||||
|
||||
def manage_caddy(cfg, ctx):
|
||||
"""Run Caddy, a dependency of the package, which serves every HTTP and HTTPS port of the server's services and the
|
||||
web sites; the services listen on loopback only.
|
||||
@@ -753,15 +759,16 @@ def manage_caddy(cfg, ctx):
|
||||
names; a client without SNI gets the certificate of the first HTTPS name. Every site calls
|
||||
its service on its loopback port. The certificate comes from the ACME CA of https.acme_provider, the global issuer,
|
||||
with https.certificate acme, and otherwise is the one linuxmanager_pki.https_files gives, written to
|
||||
CADDY_HTTPS_DIR; while that cannot be read, the HTTPS sites are left out, so that no ACME CA is asked for it. It
|
||||
CADDY_HTTPS_DIR; while there is none, the HTTPS sites are left out, so that no ACME CA is asked for it. It
|
||||
also serves the CA files of linuxmanager_pki.PUBLISH_DIR at /pki/ on web.port, the Manager's port, https.web_port
|
||||
and https.manager_port, ahead of the redirect to HTTPS, and an ACME server at /acme/<name>/ on https.web_port for
|
||||
each issuing CA with acme and a certificate.
|
||||
|
||||
It serves each site of ctx's sites from its folder, with the TLS of the site: an issuing CA of tls ca issues its
|
||||
certificates, and the certificate and key of tls file are written to CADDY_SITES_DIR/<name>. The certificates and
|
||||
keys of the issuing CAs of both are copied to CADDY_PKI_DIR. While the sites cannot be read (ctx's sites is None),
|
||||
the Caddyfile is left as it is.
|
||||
keys of the issuing CAs of both are copied to CADDY_PKI_DIR. While the directory cannot be read, the copies in
|
||||
CADDY_HTTPS_DIR and CADDY_PKI_DIR are served and kept, and what has none is left out. While the sites cannot be
|
||||
read (ctx's sites is None), the Caddyfile is left as it is.
|
||||
"""
|
||||
sites = ctx['sites']
|
||||
if shutil.which('caddy') is None:
|
||||
@@ -777,15 +784,19 @@ def manage_caddy(cfg, ctx):
|
||||
fail(f'the group {CADDY_GROUP} does not exist; is the caddy package installed?')
|
||||
https = True
|
||||
own = None
|
||||
if https and cfg['https']['certificate'] != 'acme':
|
||||
unread = False
|
||||
if cfg['https']['certificate'] != 'acme':
|
||||
try:
|
||||
own = linuxmanager_pki.https_files(cfg)
|
||||
except ldap.LDAPError as exc:
|
||||
warn(f'the HTTPS sites are left out: the HTTPS certificate cannot be read: {exc}')
|
||||
https = False
|
||||
if https and own is None:
|
||||
warn('the HTTPS sites are left out: the server has no HTTPS certificate yet')
|
||||
https = False
|
||||
unread = True
|
||||
own = caddy_copies(CADDY_HTTPS_DIR)
|
||||
outcome = 'the HTTPS sites are left out' if own is None else 'the HTTPS sites keep its copy'
|
||||
warn(f'the HTTPS certificate cannot be read, so {outcome}: {exc}')
|
||||
else:
|
||||
if own is None:
|
||||
warn('the HTTPS sites are left out: the server has no HTTPS certificate yet')
|
||||
https = own is not None
|
||||
copied = False
|
||||
if own is None:
|
||||
if CADDY_HTTPS_DIR.is_dir():
|
||||
@@ -801,14 +812,16 @@ def manage_caddy(cfg, ctx):
|
||||
try:
|
||||
credentials = {name: linuxmanager_pki.authority_files(name) for name in wanted}
|
||||
except ldap.LDAPError as exc:
|
||||
warn(f'the ACME servers and the sites of issuing CAs are left out: the PKI cannot be read: {exc}')
|
||||
credentials = {}
|
||||
unread = True
|
||||
warn(f'the PKI cannot be read, so the ACME servers and the sites of issuing CAs keep its copies, and those '
|
||||
f'without one are left out: {exc}')
|
||||
credentials = {name: caddy_copies(CADDY_PKI_DIR / name) for name in wanted}
|
||||
authorities = [name for name, files in credentials.items() if files is not None]
|
||||
for site in sites:
|
||||
if site['tls'] == 'ca' and site['ca'] not in authorities:
|
||||
warn(f'site {site["name"]} is left out: issuing CA {site["ca"]} has no certificate')
|
||||
sites = [site for site in sites if site['tls'] != 'ca' or site['ca'] in authorities]
|
||||
for folder in (CADDY_PKI_DIR.iterdir() if CADDY_PKI_DIR.is_dir() else []):
|
||||
for folder in (CADDY_PKI_DIR.iterdir() if CADDY_PKI_DIR.is_dir() and not unread else []):
|
||||
if folder.name not in authorities:
|
||||
shutil.rmtree(folder)
|
||||
for name in authorities:
|
||||
|
||||
Reference in new issue
Block a user