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
@@ -1,3 +1,49 @@
|
||||
linux-manager (0.41.1-1) unstable; urgency=medium
|
||||
|
||||
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/.
|
||||
|
||||
* The Manager's browser settings have Open the shell in a new tab, off by
|
||||
default; with it the shell button opens the shell in a tab of its own.
|
||||
* The page menu leaves the Docker page out while Docker is not installed;
|
||||
/config has docker.installed.
|
||||
* The test scripts are bin/lm-dev-run.py, lm-dev-vm.py,
|
||||
lm-dev-lxd-project.py and lm-dev-build.py, their data stays in
|
||||
tests/remote; bin/otp.py is a command-line authenticator app, and
|
||||
bin/lm-dev-otp-register.py enrols a token for a user of a test VM.
|
||||
* The lm-dev scripts default to the project lm-dev, read from LXD_PROJECT,
|
||||
and name the VM with --vm; lm-dev-run.py reads its project from
|
||||
LXD_TEST_PROJECT; lm-dev-vm.py takes create and remove.
|
||||
* lm-dev-build.py keeps the serial of the last dev build in
|
||||
.dev-build.serial, which release.py writes as 0 when it releases.
|
||||
* pki.root, local by default, offline or simple-ca, says where the root CA
|
||||
comes from, and is fixed once the root exists; the debconf question
|
||||
linux-manager/pki_root sets it.
|
||||
* With pki.root offline, setup makes the CSRs of the issuing CAs and waits;
|
||||
linux-manager-ca ca import root, and Import root certificate on the Root
|
||||
tab, take the root certificate before the issuing CAs.
|
||||
* With pki.root simple-ca, setup exchanges a setup code, debconf
|
||||
linux-manager/pki_setup_code or linux-manager-ca root setup-code, for a
|
||||
sign-ca token of a Simple CA issuing CA at pki.simple_ca_url, has the
|
||||
issuing CAs signed by it, and fetches the CRLs of the root and that CA,
|
||||
which joins every chain the server gives; the CA of the service's HTTPS
|
||||
certificate is installed in the system's trust store before setup.
|
||||
* The root key is no longer exported, removed or imported:
|
||||
linux-manager-ca root export-key, remove-key and import-key,
|
||||
pki.root_key_warning, and a root placed in /etc/linux-manager/pki/root
|
||||
are gone.
|
||||
* The Root tab shows the source of the root, and with Simple CA its
|
||||
issuing CA and the expiry of the token, with Enter setup code.
|
||||
* examples/cloud-init-with-pki.yaml.tpl and the Azure and GCP examples
|
||||
give the router a Simple CA root with simple_ca_url and
|
||||
simple_ca_setup_code, and both cloud-init examples add the CAs of
|
||||
trusted_ca_files to the trust store.
|
||||
* The name server settings describe TTL as the default TTL of the records,
|
||||
used where neither the record nor its domain has one.
|
||||
|
||||
-- Slawomir Koszewski <slawek@koszewscy.waw.pl> Sun, 22 Nov 2026 20:13:38 +0100
|
||||
|
||||
linux-manager (0.41.0-1) unstable; urgency=medium
|
||||
|
||||
feature: the package is linux-manager, the Ubuntu Linux Manager, whose
|
||||
|
||||
@@ -77,13 +77,22 @@ if [ "$ROUTER" = "true" ]; then
|
||||
db_input high linux-manager/remote_cidrs || true
|
||||
db_input high linux-manager/psk || true
|
||||
fi
|
||||
db_input high linux-manager/pki_root_name || true
|
||||
db_input high linux-manager/pki_root || true
|
||||
if [ "$VPN" = "true" ]; then
|
||||
db_input high linux-manager/p2s_enabled || true
|
||||
db_input high linux-manager/wg_enabled || true
|
||||
fi
|
||||
db_go || true
|
||||
|
||||
db_get linux-manager/pki_root
|
||||
if [ "$RET" = "local" ]; then
|
||||
db_input high linux-manager/pki_root_name || true
|
||||
elif [ "$RET" = "simple-ca" ]; then
|
||||
db_input high linux-manager/pki_simple_ca_url || true
|
||||
db_input high linux-manager/pki_setup_code || true
|
||||
fi
|
||||
db_go || true
|
||||
|
||||
if [ "$VPN" = "true" ]; then
|
||||
db_get linux-manager/p2s_enabled
|
||||
if [ "$RET" = "true" ]; then
|
||||
|
||||
@@ -33,7 +33,9 @@ case "$1" in
|
||||
answer linux-manager/psk; LINUX_MANAGER_PSK="$ANSWER"
|
||||
answer linux-manager/p2s_enabled; LINUX_MANAGER_P2S_ENABLED="$ANSWER"
|
||||
answer linux-manager/p2s_address_pool; LINUX_MANAGER_P2S_ADDRESS_POOL="$ANSWER"
|
||||
answer linux-manager/pki_root; LINUX_MANAGER_PKI_ROOT="$ANSWER"
|
||||
answer linux-manager/pki_root_name; LINUX_MANAGER_PKI_ROOT_NAME="$ANSWER"
|
||||
answer linux-manager/pki_simple_ca_url; LINUX_MANAGER_PKI_SIMPLE_CA_URL="$ANSWER"
|
||||
answer linux-manager/wg_enabled; LINUX_MANAGER_WG_ENABLED="$ANSWER"
|
||||
answer linux-manager/wg_address; LINUX_MANAGER_WG_ADDRESS="$ANSWER"
|
||||
answer linux-manager/wg_listen_port; LINUX_MANAGER_WG_LISTEN_PORT="$ANSWER"
|
||||
@@ -47,7 +49,8 @@ case "$1" in
|
||||
LINUX_MANAGER_REMOTE_ADDRS LINUX_MANAGER_REMOTE_ID \
|
||||
LINUX_MANAGER_REMOTE_CIDRS LINUX_MANAGER_PSK \
|
||||
LINUX_MANAGER_P2S_ENABLED LINUX_MANAGER_P2S_ADDRESS_POOL \
|
||||
LINUX_MANAGER_PKI_ROOT_NAME LINUX_MANAGER_WG_ENABLED \
|
||||
LINUX_MANAGER_PKI_ROOT LINUX_MANAGER_PKI_ROOT_NAME \
|
||||
LINUX_MANAGER_PKI_SIMPLE_CA_URL LINUX_MANAGER_WG_ENABLED \
|
||||
LINUX_MANAGER_WG_ADDRESS LINUX_MANAGER_WG_LISTEN_PORT
|
||||
|
||||
# --- Hand a candidate configuration to ucf ---
|
||||
@@ -82,6 +85,14 @@ case "$1" in
|
||||
db_set linux-manager/admin_username ""
|
||||
db_set linux-manager/admin_password ""
|
||||
|
||||
# The Simple CA setup code for linux-manager-setup to exchange for the token; the answer is cleared, as
|
||||
# the code works once.
|
||||
db_get linux-manager/pki_setup_code
|
||||
if [ -n "$RET" ]; then
|
||||
(umask 077; printf '%s\n' "$RET" > /etc/linux-manager/pki-setup-code)
|
||||
fi
|
||||
db_set linux-manager/pki_setup_code ""
|
||||
|
||||
# The firewall is not touched here. Enabling it, allowing SSH and
|
||||
# setting the forward policy all belong to linux-manager-setup, which does
|
||||
# them only once the configuration says this host is a router.
|
||||
|
||||
@@ -59,6 +59,7 @@ case "$1" in
|
||||
/etc/linux-manager/metrics.secret \
|
||||
/etc/linux-manager/manager.json \
|
||||
/etc/linux-manager/manager-admin.json \
|
||||
/etc/linux-manager/pki-setup-code \
|
||||
/var/lib/linux-manager/upgrade.json \
|
||||
/var/lib/linux-manager/upgrade.log \
|
||||
/var/lib/linux-manager/system-upgrade.json \
|
||||
|
||||
@@ -166,12 +166,46 @@ Default:
|
||||
Description: IKEv2 address pool:
|
||||
CIDR block assigned to IKEv2 clients (for example 172.16.0.0/24).
|
||||
|
||||
Template: linux-manager/pki_root
|
||||
Type: select
|
||||
Choices: local, offline, simple-ca
|
||||
Default: local
|
||||
Description: Root CA:
|
||||
Where the root certificate authority of the server's PKI comes from. It is
|
||||
fixed once the root exists.
|
||||
.
|
||||
local - the server creates the root and keeps its key.
|
||||
.
|
||||
offline - the root is a CA kept elsewhere. The server makes the CSRs of its
|
||||
issuing CAs and waits; the root certificate and the signed issuing CA
|
||||
certificates are imported with linux-manager-ca ca import.
|
||||
.
|
||||
simple-ca - an issuing CA of a Simple CA service signs the server's issuing
|
||||
CAs, with a token the server gets for a one-time setup code.
|
||||
|
||||
Template: linux-manager/pki_root_name
|
||||
Type: string
|
||||
Default: Linux Manager Root CA
|
||||
Description: Root CA name:
|
||||
Common name of the root certificate authority the server creates in
|
||||
/etc/linux-manager/pki/root. Ignored when a root certificate is placed there.
|
||||
Common name of the root certificate authority the server creates.
|
||||
|
||||
Template: linux-manager/pki_simple_ca_url
|
||||
Type: string
|
||||
Default:
|
||||
Description: Simple CA URL:
|
||||
The https:// URL of the Simple CA service, for example
|
||||
https://pki.example.com. The CA that issued its HTTPS certificate must be in
|
||||
the system's trust store (/usr/local/share/ca-certificates, then
|
||||
update-ca-certificates) before setup runs.
|
||||
|
||||
Template: linux-manager/pki_setup_code
|
||||
Type: password
|
||||
Description: Simple CA setup code:
|
||||
The one-time setup code of a sign-ca token of a Simple CA issuing CA, such as
|
||||
K7QF-M2XA-JP4D-W5ZR. It is passed to linux-manager-setup in a file readable by
|
||||
root only, which is removed once the code is exchanged, and not kept by
|
||||
debconf. Leave it empty to give it later with linux-manager-ca root
|
||||
setup-code.
|
||||
|
||||
Template: linux-manager/wg_enabled
|
||||
Type: boolean
|
||||
|
||||
@@ -52,7 +52,9 @@ ANSWERS = {
|
||||
'LINUX_MANAGER_PSK': ((*FIRST, 'psk'),),
|
||||
'LINUX_MANAGER_P2S_ENABLED': (('p2s', 'enabled'),),
|
||||
'LINUX_MANAGER_P2S_ADDRESS_POOL': (('p2s', 'address_pool'),),
|
||||
'LINUX_MANAGER_PKI_ROOT': (('pki', 'root'),),
|
||||
'LINUX_MANAGER_PKI_ROOT_NAME': (('pki', 'root_name'),),
|
||||
'LINUX_MANAGER_PKI_SIMPLE_CA_URL': (('pki', 'simple_ca_url'),),
|
||||
'LINUX_MANAGER_WG_ENABLED': (('wireguard', 'enabled'),),
|
||||
'LINUX_MANAGER_WG_ADDRESS': (('wireguard', 'address'),),
|
||||
'LINUX_MANAGER_WG_LISTEN_PORT': (('wireguard', 'listen_port'),),
|
||||
|
||||
@@ -76,7 +76,7 @@ SCHEMA = {
|
||||
'pki': {'root_name': 'Linux Manager Root CA', 'root_days': 7300, 'ca_days': 3650, 'key': 'rsa-4096',
|
||||
'crl_days': 7, 'root_crl_days': 180, 'publish': ['http'], 'p2s_name': 'Linux Manager VPN CA',
|
||||
's2s_name': 'Linux Manager Site-to-Site CA', 'issuing_cas': {}, 'templates': {},
|
||||
'extended_key_usages': {}, 'root_key_warning': True},
|
||||
'extended_key_usages': {}, 'root': 'local', 'simple_ca_url': ''},
|
||||
'metrics': {'enabled': True, 'listen': 'internal', 'port': 9464, 'https_port': 9465, 'service_account': 'metrics',
|
||||
'otlp_endpoint': '', 'otlp_username': '', 'otlp_password': '',
|
||||
'keep_details': '24 hours', 'keep_hourly': '1 month', 'keep_daily': '3 months',
|
||||
@@ -182,6 +182,9 @@ CADDY_REPOSITORY = 'https://dl.cloudsmith.io/public/caddy/stable/deb/debian'
|
||||
#: The key types of the CAs, pki.key, and of the templates.
|
||||
PKI_KEYS = ('rsa-2048', 'rsa-3072', 'rsa-4096', 'ec-p256', 'ec-p384')
|
||||
|
||||
#: Where the root CA comes from, pki.root: the server creates it, an offline CA, or a Simple CA service.
|
||||
PKI_ROOTS = ('local', 'offline', 'simple-ca')
|
||||
|
||||
#: Where the CA certificates and CRLs are published, pki.publish, as the URLs in the certificates list them.
|
||||
PKI_PUBLISH = ('http', 'http-80', 'https', 'https-default')
|
||||
|
||||
@@ -638,6 +641,15 @@ def validate(cfg):
|
||||
for option in ('root_days', 'ca_days', 'crl_days', 'root_crl_days'):
|
||||
if not 1 <= _get(cfg, 'pki', option) <= 36500:
|
||||
raise ConfigError(f'pki.{option} must be 1 to 36500 days')
|
||||
if _get(cfg, 'pki', 'root') not in PKI_ROOTS:
|
||||
raise ConfigError(f'pki.root: {_get(cfg, "pki", "root")!r} is not one of {", ".join(PKI_ROOTS)}')
|
||||
simple_ca_url = _get(cfg, 'pki', 'simple_ca_url')
|
||||
if _get(cfg, 'pki', 'root') == 'simple-ca' and not simple_ca_url:
|
||||
raise ConfigError('pki.simple_ca_url is required while pki.root is simple-ca')
|
||||
if simple_ca_url:
|
||||
parts = urllib.parse.urlsplit(simple_ca_url)
|
||||
if parts.scheme != 'https' or not parts.hostname or parts.query or parts.fragment:
|
||||
raise ConfigError('pki.simple_ca_url must be an https:// URL without a query or a fragment')
|
||||
if _get(cfg, 'pki', 'key') not in PKI_KEYS:
|
||||
raise ConfigError(f'pki.key: {_get(cfg, "pki", "key")!r} is not one of {", ".join(PKI_KEYS)}')
|
||||
publish = _get_list(cfg, 'pki', 'publish')
|
||||
@@ -689,9 +701,10 @@ def validate(cfg):
|
||||
raise ConfigError(f'{prefix}.subject: {template["subject"]!r} is not one of {", ".join(TEMPLATE_SUBJECTS)}')
|
||||
for name, authority in cfg['pki']['issuing_cas'].items():
|
||||
prefix = f'pki.issuing_cas.{name}'
|
||||
if not PKI_NAME.match(name) or name in BUILTIN_CAS or name == 'root':
|
||||
if not PKI_NAME.match(name) or name in BUILTIN_CAS or name in ('root', 'upstream'):
|
||||
raise ConfigError(f'{prefix}: an issuing CA name starts with a lowercase letter and has at most 31 '
|
||||
f'lowercase letters, digits and hyphens, and is not root, {" or ".join(BUILTIN_CAS)}')
|
||||
f'lowercase letters, digits and hyphens, and is not root, upstream, '
|
||||
f'{" or ".join(BUILTIN_CAS)}')
|
||||
if not isinstance(authority, dict):
|
||||
raise ConfigError(f'{prefix} must be {TYPE_NAMES[dict]}')
|
||||
_check_options(authority, ISSUING_CA, prefix)
|
||||
|
||||
@@ -82,8 +82,9 @@ OVERLAYS = ('ppolicy', 'otp')
|
||||
#: named cn=<resource>:<role>, with the DNs of the groups and accounts it is assigned to in
|
||||
#: member. linuxManagerAuthority is a CA of the PKI: its
|
||||
#: certificate and CRL (cACertificate and certificateRevocationList of RFC 4523), its key, the
|
||||
#: CSR it waits with for the offline root, the number of its last CRL, where the CRL came from,
|
||||
#: and when it was retired. linuxManagerCertificate is a certificate a CA issued, named by its
|
||||
#: CSR it waits with for its certificate, the number of its last CRL, where the CRL came from,
|
||||
#: and when it was retired; the root also holds the Simple CA token, linuxManagerToken, and the
|
||||
#: name of the Simple CA issuing CA that signs with it, linuxManagerUpstreamName. linuxManagerCertificate is a certificate a CA issued, named by its
|
||||
#: serial number: the certificate, the key the server keeps for its own and the users'
|
||||
#: certificates, its kind, template, names and expiry, and its revocation.
|
||||
SCHEMA_OID = '1.3.6.1.4.1.67380.10.1.2'
|
||||
@@ -129,6 +130,10 @@ SCHEMA_ATTRIBUTE_TYPES = (
|
||||
"may ask for' EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} )",
|
||||
f"( {SCHEMA_OID}.1.23 NAME 'linuxManagerResourceScope' DESC 'Linux Manager: a scope of a resource of the OpenID Provider' "
|
||||
"EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{64} )",
|
||||
f"( {SCHEMA_OID}.1.24 NAME 'linuxManagerToken' DESC 'Linux Manager: the Simple CA token that signs the issuing CAs' "
|
||||
f"{_OCTETS} )",
|
||||
f"( {SCHEMA_OID}.1.25 NAME 'linuxManagerUpstreamName' DESC 'Linux Manager: the Simple CA issuing CA of the token' "
|
||||
f"{_STRING} )",
|
||||
)
|
||||
SCHEMA_OBJECT_CLASSES = (
|
||||
f"( {SCHEMA_OID}.2.1 NAME 'linuxManagerAccount' DESC 'Linux Manager: properties of a user or a Manager-only account' "
|
||||
@@ -138,7 +143,8 @@ SCHEMA_OBJECT_CLASSES = (
|
||||
"linuxManagerClientScope $ linuxManagerResourceScope ) )",
|
||||
f"( {SCHEMA_OID}.2.2 NAME 'linuxManagerAuthority' DESC 'Linux Manager: a CA of the PKI' SUP top STRUCTURAL MUST cn "
|
||||
"MAY ( cACertificate $ certificateRevocationList $ linuxManagerPrivateKey $ linuxManagerCertificateRequest $ "
|
||||
"linuxManagerCRLNumber $ linuxManagerCRLSource $ linuxManagerRetired ) )",
|
||||
"linuxManagerCRLNumber $ linuxManagerCRLSource $ linuxManagerRetired $ linuxManagerToken $ "
|
||||
"linuxManagerUpstreamName ) )",
|
||||
f"( {SCHEMA_OID}.2.3 NAME 'linuxManagerCertificate' DESC 'Linux Manager: a certificate a CA of the PKI issued' SUP top "
|
||||
"STRUCTURAL MUST serialNumber MAY ( cn $ userCertificate $ linuxManagerPrivateKey $ linuxManagerKind $ linuxManagerTemplate $ "
|
||||
"linuxManagerSubjectAltName $ linuxManagerNotAfter $ linuxManagerRevoked $ linuxManagerRevocationReason ) )",
|
||||
@@ -167,7 +173,7 @@ CONSOLE_HOMES = '/home'
|
||||
|
||||
#: The ACLs of the database, in order.
|
||||
ACCESS = (
|
||||
'to attrs=linuxManagerPrivateKey by * none',
|
||||
'to attrs=linuxManagerPrivateKey,linuxManagerToken by * none',
|
||||
f'to attrs=userPassword by dn.exact="{MANAGER}" =wx by self =wx by anonymous auth by * none',
|
||||
f'to attrs=oathSecret by dn.exact="{MANAGER}" =w by * none',
|
||||
f'to dn.subtree="{USERS}" by dn.exact="{MANAGER}" manage by * read',
|
||||
|
||||
@@ -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"))}')
|
||||
|
||||
@@ -20,20 +20,26 @@ def ca(method, path, body):
|
||||
ones, the extended key usages, each {oid, builtin}, the root, the
|
||||
issuing CAs, the retired CAs and the warnings (linuxmanager_pki.status),
|
||||
and the certificates issued, newest first
|
||||
PUT /ca change any of the settings of the pki section
|
||||
PUT /ca change any of the settings of the pki section; pki.root, once the
|
||||
root exists, only to the source it has
|
||||
POST /ca/certificates issue a certificate: {"ca", "template", "csr"} answers {"serial",
|
||||
"certificate", "chain"}; {"ca", "template", "subject", "sans",
|
||||
"password"} answers {"serial", "pfx"}, a PKCS#12 file in base64
|
||||
POST /ca/certificates/<serial>/revoke revoke a certificate: {"reason"?}
|
||||
GET /ca/bundle/<name> the PEM certificates a client trusts the CA with: {"name", "pem"}; for
|
||||
root the root alone, for an issuing CA the issuing CA and the root
|
||||
root the root alone, for an issuing CA the issuing CA, the upstream
|
||||
CA when there is one, and the root
|
||||
GET /ca/issuing/<name>/csr the CSR of an issuing CA that waits for the offline root, with the
|
||||
openssl extensions to sign it with: {"name", "csr", "extensions"}
|
||||
PUT /ca/issuing/<name>/certificate take its certificate signed by the root: {"certificate"}
|
||||
PUT /ca/root/certificate take the certificate of the offline root: {"certificate"}
|
||||
PUT /ca/root/crl take a root CRL signed offline: {"crl"}
|
||||
PUT /ca/root/setup-code exchange a setup code of a Simple CA token for the token: {"code"}
|
||||
answers {"upstream", "expires"}
|
||||
|
||||
A change of the settings is made as /site-to-site makes one; it, a revoked router certificate and an imported
|
||||
issuing CA certificate are applied by restarting linux-manager-setup without waiting for it.
|
||||
A change of the settings is made as /site-to-site makes one; it, a revoked router certificate, an imported root
|
||||
or issuing CA certificate and a new Simple CA token are applied by restarting linux-manager-setup without waiting
|
||||
for it.
|
||||
"""
|
||||
if body == 'invalid' or (body is not None and not isinstance(body, dict)):
|
||||
return 400, {'error': 'the body must be a JSON object'}
|
||||
@@ -57,6 +63,8 @@ def ca(method, path, body):
|
||||
data['pki'] = {**(current if isinstance(current, dict) else {}), **settings}
|
||||
cfg = linuxmanager.with_defaults(data)
|
||||
linuxmanager.validate(cfg)
|
||||
with linuxmanager_pki.directory() as connection:
|
||||
linuxmanager_pki.check_source(cfg, linuxmanager_pki.authority(connection, 'root'))
|
||||
linuxmanager.save_config(data)
|
||||
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
|
||||
return 200, {'settings': cfg['pki'], 'templates': linuxmanager.pki_templates(cfg)}
|
||||
@@ -71,8 +79,12 @@ def ca(method, path, body):
|
||||
return 200, linuxmanager_pki.csr(cfg, route[2])
|
||||
elif len(route) == 4 and route[:2] == ('PUT', 'issuing') and route[3] == 'certificate':
|
||||
document = linuxmanager_pki.import_ca(cfg, route[2], body.get('certificate'))
|
||||
elif route == ('PUT', 'root', 'certificate'):
|
||||
document = linuxmanager_pki.import_ca(cfg, 'root', body.get('certificate'))
|
||||
elif route == ('PUT', 'root', 'crl'):
|
||||
return 200, linuxmanager_pki.import_root_crl(body.get('crl'))
|
||||
return 200, linuxmanager_pki.import_root_crl(cfg, body.get('crl'))
|
||||
elif route == ('PUT', 'root', 'setup-code'):
|
||||
document = linuxmanager_pki.exchange_code(cfg, body.get('code'))
|
||||
else:
|
||||
return 404, {'error': f'no route {method} {path}'}
|
||||
except linuxmanager.ConfigError as exc:
|
||||
@@ -85,6 +97,6 @@ def ca(method, path, body):
|
||||
return 500, {'error': f'the PKI cannot be changed: {exc}'}
|
||||
except SystemExit as exc:
|
||||
return 500, {'error': str(exc.code)}
|
||||
if route[1] == 'issuing' or document.get('reissue'):
|
||||
if route[1] in ('issuing', 'root') or document.get('reissue'):
|
||||
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
|
||||
return 200, document
|
||||
@@ -233,7 +233,8 @@ def postgresql_databases():
|
||||
def details(state):
|
||||
"""What /config shows: the configuration without its secrets, and what the server resolved and runs; caddy is the
|
||||
installed Caddy, {version, source, service}, service the state of caddy.service, null when it is not installed; oidc
|
||||
is {enabled, issuer} of the OpenID Provider, issuer null while it is disabled."""
|
||||
is {enabled, issuer} of the OpenID Provider, issuer null while it is disabled; docker.installed is whether
|
||||
docker.service is installed, as docker_status finds it."""
|
||||
configuration = state.get('configuration', {})
|
||||
caddy = package_version('caddy')
|
||||
oidc = configuration.get('oidc', {}).get('enabled') is True
|
||||
@@ -246,6 +247,7 @@ def details(state):
|
||||
},
|
||||
'wireguard': wireguard_details(),
|
||||
'docker': {
|
||||
'installed': docker_status()['installed'],
|
||||
'exposed_ports': configuration.get('docker', {}).get('exposed_ports', []),
|
||||
'rules': lines_of('iptables', '-S', 'LINUX-MANAGER-DOCKER'),
|
||||
},
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
status shows the root, the issuing CAs and the warnings; list the certificates the server issued. issue signs a CSR,
|
||||
or makes a key and writes a PFX file whose password is read from the first line of standard input. ca csr prints the
|
||||
CSR of an issuing CA that waits for the offline root, with the openssl extensions to sign it with, and ca import takes
|
||||
the signed certificate. root export-key writes the root key encrypted with the passphrase read from standard input,
|
||||
root remove-key removes it from the server, root import-key puts it back, and root import-crl takes a root CRL signed
|
||||
offline. maintain signs the stale CRLs again; linux-manager-pki.service runs it daily. A change that needs
|
||||
linux-manager-setup restarts it without waiting.
|
||||
the signed certificate, and, named root, the certificate of the offline root. root import-crl takes a CRL of the
|
||||
offline root, and root setup-code exchanges a setup code of a Simple CA token, read from the first line of standard
|
||||
input, for the token. maintain signs the stale CRLs again, or fetches those of Simple CA; linux-manager-pki.service
|
||||
runs it daily. A change that needs linux-manager-setup restarts it without waiting.
|
||||
|
||||
The answer is text for people on standard output, and a failure is a message on standard error. With --json the answer
|
||||
is JSON on standard output, and a failure is {"error": ...} there too. The exit status says what failed: 2 the request
|
||||
@@ -21,11 +21,9 @@ commands and their options.
|
||||
linux-manager-ca [--json] revoke SERIAL [--reason REASON]
|
||||
linux-manager-ca [--json] maintain
|
||||
linux-manager-ca [--json] ca csr NAME
|
||||
linux-manager-ca [--json] ca import NAME FILE
|
||||
linux-manager-ca [--json] root export-key --out FILE (passphrase on stdin)
|
||||
linux-manager-ca [--json] root remove-key [--yes]
|
||||
linux-manager-ca [--json] root import-key FILE (passphrase on stdin, an empty line for none)
|
||||
linux-manager-ca [--json] ca import NAME|root FILE
|
||||
linux-manager-ca [--json] root import-crl FILE
|
||||
linux-manager-ca [--json] root setup-code (setup code on stdin)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -64,11 +62,19 @@ def restart_setup():
|
||||
|
||||
def show_status(document):
|
||||
root = document['root']
|
||||
if root is None:
|
||||
print('Root CA: none; linux-manager-setup creates it once a platform is chosen')
|
||||
source = {'local': 'created by the server', 'offline': 'offline',
|
||||
'simple-ca': f'Simple CA {root["simple_ca_url"]}'}[root['source']]
|
||||
if root['state'] == 'pending':
|
||||
print(f'Root CA: {source}, waits for its certificate')
|
||||
else:
|
||||
print(f'Root CA: {root["subject"]}, expires {root["expires"]}, key {"on the server" if root["key"] else "offline"}'
|
||||
f', CRL until {root["crl_next_update"] or "none"}')
|
||||
print(f'Root CA: {root["subject"]}, {source}, expires {root["expires"]}, '
|
||||
f'CRL until {root["crl_next_update"] or "none"}')
|
||||
if root['upstream']:
|
||||
upstream = root['upstream']
|
||||
print(f'Simple CA issuing CA {upstream["name"]}: {upstream["subject"]}, expires {upstream["expires"]}, '
|
||||
f'CRL until {upstream["crl_next_update"] or "none"}')
|
||||
if root['source'] == 'simple-ca':
|
||||
print(f'Simple CA token: {"valid until " + root["token_expires"] if root["token_expires"] else "none"}')
|
||||
for authority in document['authorities']:
|
||||
line = f'Issuing CA {authority["name"]}: {authority["common_name"]}, {authority["state"]}'
|
||||
if authority['expires']:
|
||||
@@ -115,36 +121,26 @@ def run(options):
|
||||
return document, f'Certificate {document["serial"]} revoked' + \
|
||||
('; linux-manager-setup issues a new one.' if document['reissue'] else '.')
|
||||
if options.command == 'maintain':
|
||||
due = linuxmanager_pki.maintain(cfg)
|
||||
notices, due = linuxmanager_pki.maintain(cfg)
|
||||
if due:
|
||||
restart_setup()
|
||||
return {'renewal': due}, 'CRLs checked' + ('; linux-manager-setup renews the server certificates.' if due else '.')
|
||||
return {'renewal': due, 'notices': notices}, '\n'.join(
|
||||
['CRLs checked' + ('; linux-manager-setup renews the certificates.' if due else '.'),
|
||||
*(f'Warning: {notice}' for notice in notices)])
|
||||
if options.command == 'ca' and options.action == 'csr':
|
||||
document = linuxmanager_pki.csr(cfg, options.name)
|
||||
return document, document['csr'] + '\n' + document['extensions']
|
||||
if options.command == 'ca':
|
||||
document = linuxmanager_pki.import_ca(cfg, options.name, pathlib.Path(options.file).read_text(encoding='ascii'))
|
||||
restart_setup()
|
||||
return document, f'Issuing CA {options.name} has its certificate, which expires {document["expires"]}.'
|
||||
if options.action == 'export-key':
|
||||
data = linuxmanager_pki.export_root_key(secret())
|
||||
out = pathlib.Path(options.out)
|
||||
with open(out, 'xb') as handle:
|
||||
handle.write(data)
|
||||
return {'exported': str(out)}, f'Root key written to {out}, encrypted.'
|
||||
if options.action == 'remove-key':
|
||||
if not options.yes:
|
||||
print('Remove the root key from the server? Keep an exported copy first. Type yes: ', end='',
|
||||
file=sys.stderr, flush=True)
|
||||
if secret().strip() != 'yes':
|
||||
return {'removed': False}, 'Nothing removed.'
|
||||
linuxmanager_pki.remove_root_key()
|
||||
return {'removed': True}, 'Root key removed; new issuing CAs now wait for an offline signature.'
|
||||
if options.action == 'import-key':
|
||||
linuxmanager_pki.import_root_key(pathlib.Path(options.file).read_bytes(), secret() or None)
|
||||
what = 'The root' if options.name == 'root' else f'Issuing CA {options.name}'
|
||||
return document, f'{what} has its certificate, which expires {document["expires"]}.'
|
||||
if options.action == 'setup-code':
|
||||
document = linuxmanager_pki.exchange_code(cfg, secret())
|
||||
restart_setup()
|
||||
return {'imported': True}, 'Root key back on the server.'
|
||||
document = linuxmanager_pki.import_root_crl(pathlib.Path(options.file).read_bytes())
|
||||
return document, (f'Simple CA token of issuing CA {document["upstream"]} taken'
|
||||
+ (f', valid until {document["expires"]}.' if document['expires'] else '.'))
|
||||
document = linuxmanager_pki.import_root_crl(cfg, pathlib.Path(options.file).read_bytes())
|
||||
return document, f'Root CRL taken, valid until {document["next_update"]}.'
|
||||
|
||||
|
||||
@@ -165,21 +161,17 @@ def main(argv):
|
||||
revoker = commands.add_parser('revoke', help='revoke a certificate the server issued')
|
||||
revoker.add_argument('serial', help='the serial number, hexadecimal')
|
||||
revoker.add_argument('--reason', choices=linuxmanager_pki.REASONS, help='the reason, unspecified by default')
|
||||
commands.add_parser('maintain', help='sign the stale CRLs again')
|
||||
authority = commands.add_parser('ca', help='an issuing CA that waits for the offline root')
|
||||
commands.add_parser('maintain', help='sign the stale CRLs again, or fetch those of Simple CA')
|
||||
authority = commands.add_parser('ca', help='an issuing CA, or the root, that waits for the offline root')
|
||||
actions = authority.add_subparsers(dest='action', required=True, parser_class=Parser)
|
||||
actions.add_parser('csr', help='print its CSR and the openssl extensions').add_argument('name')
|
||||
importer = actions.add_parser('import', help='take its certificate signed by the root')
|
||||
importer.add_argument('name')
|
||||
importer = actions.add_parser('import', help='take its certificate signed by the root, or the root certificate')
|
||||
importer.add_argument('name', help='the issuing CA, or root')
|
||||
importer.add_argument('file')
|
||||
root = commands.add_parser('root', help='the root CA')
|
||||
root_actions = root.add_subparsers(dest='action', required=True, parser_class=Parser)
|
||||
exporter = root_actions.add_parser('export-key', help='write the root key encrypted with the passphrase from stdin')
|
||||
exporter.add_argument('--out', required=True, help='the file to write')
|
||||
remover = root_actions.add_parser('remove-key', help='remove the root key from the server')
|
||||
remover.add_argument('--yes', action='store_true', help='do not ask')
|
||||
root_actions.add_parser('import-key', help='put the root key back').add_argument('file')
|
||||
root_actions.add_parser('import-crl', help='take a root CRL signed offline').add_argument('file')
|
||||
root_actions.add_parser('import-crl', help='take a CRL of the offline root').add_argument('file')
|
||||
root_actions.add_parser('setup-code', help='exchange a Simple CA setup code from stdin for the token')
|
||||
options = parser.parse_args(argv)
|
||||
os.umask(0o077)
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ _linux_manager_ca()
|
||||
local i command='' action='' args=0
|
||||
for ((i = 1; i < cword; i++)); do
|
||||
case ${words[i]} in
|
||||
--ca | --template | --csr | --subject | --san | --pfx | --reason | --out) ((i++)) ;;
|
||||
--ca | --template | --csr | --subject | --san | --pfx | --reason) ((i++)) ;;
|
||||
-*) ;;
|
||||
*)
|
||||
if [[ -z $command ]]; then
|
||||
@@ -54,7 +54,7 @@ _linux_manager_ca()
|
||||
COMPREPLY=($(compgen -W "$(_linux_manager_ca_python reasons)" -- "$cur"))
|
||||
return
|
||||
;;
|
||||
--csr | --pfx | --out)
|
||||
--csr | --pfx)
|
||||
_filedir
|
||||
return
|
||||
;;
|
||||
@@ -79,8 +79,6 @@ _linux_manager_ca()
|
||||
list) options+=' --ca' ;;
|
||||
issue) options+=' --ca --template --csr --subject --san --pfx' ;;
|
||||
revoke) options+=' --reason' ;;
|
||||
rootexport-key) options+=' --out' ;;
|
||||
rootremove-key) options+=' --yes' ;;
|
||||
esac
|
||||
COMPREPLY=($(compgen -W "$options" -- "$cur"))
|
||||
return
|
||||
@@ -88,9 +86,10 @@ _linux_manager_ca()
|
||||
|
||||
case $command,$action,$args in
|
||||
ca,,*) COMPREPLY=($(compgen -W 'csr import' -- "$cur")) ;;
|
||||
root,,*) COMPREPLY=($(compgen -W 'export-key remove-key import-key import-crl' -- "$cur")) ;;
|
||||
ca,*,0) COMPREPLY=($(compgen -W "$(_linux_manager_ca_python cas)" -- "$cur")) ;;
|
||||
ca,import,1 | root,import-key,0 | root,import-crl,0) _filedir ;;
|
||||
root,,*) COMPREPLY=($(compgen -W 'import-crl setup-code' -- "$cur")) ;;
|
||||
ca,csr,0) COMPREPLY=($(compgen -W "$(_linux_manager_ca_python cas)" -- "$cur")) ;;
|
||||
ca,import,0) COMPREPLY=($(compgen -W "root $(_linux_manager_ca_python cas)" -- "$cur")) ;;
|
||||
ca,import,1 | root,import-crl,0) _filedir ;;
|
||||
esac
|
||||
} &&
|
||||
complete -F _linux_manager_ca linux-manager-ca
|
||||
|
||||
@@ -125,7 +125,8 @@
|
||||
"extended_key_usages": {
|
||||
"smartcard_logon": "1.3.6.1.4.1.311.20.2.2"
|
||||
},
|
||||
"root_key_warning": true
|
||||
"root": "local",
|
||||
"simple_ca_url": ""
|
||||
},
|
||||
"metrics": {
|
||||
"enabled": true,
|
||||
|
||||
Reference in new issue
Block a user