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

This commit is contained in:
slawek committed 2026-11-23 06:45:23 +01:00
1 parent ff0c93ed73
commit a649331aa2
49 files changed
+1597 -637

No files matched your search

+1
View File
@@ -0,0 +1 @@
dotenv_if_exists
+2
View File
@@ -16,3 +16,5 @@ node_modules
web/dist
.venv
dev.json
/.dev-build.serial
**/.env
+60 -23
View File
@@ -259,9 +259,9 @@ P2S CA; with the VPN off a VPN user is created without a certificate, which it g
is switched on (ADR-57). Only the OpenVPN client profile needs OpenVPN to be enabled.
Consequences: slapd always holds the directory and the CAs exist on a configured router, even
when no P2S system uses them; with an offline root the P2S CA, and so the users' certificates,
wait for its certificate. An operator who wants a root CA of their own must place it before
choosing the platform.
when no P2S system uses them; with an offline or a Simple CA root the P2S CA, and so the users'
certificates, wait for its certificate. The source of the root, `pki.root`, is chosen with the
platform, before the root exists (ADR-27).
## ADR-11: Groups are groupOfNames entries that never become empty
@@ -752,19 +752,25 @@ timer's schedules are systemd's shorthands, so all backups of one schedule start
moment. A change of the users between the end of the copy and the next backup is in no backup
until then.
## ADR-27: A two-level CA with dedicated issuing CAs, whose root may be offline
## ADR-27: Dedicated issuing CAs under a root the server creates, an offline root, or a Simple CA root
Status: Accepted
Context: One self-signed CA signed every certificate of the server with the same server and
client purposes, so a certificate for any use was also a VPN client certificate, and the key
that signed everything had to stay on the server. The server needs CAs for the VPN clients, for
site-to-site certificates and for the administrator's own uses, and a root whose key can be kept
elsewhere. The `simple-ca` script handled one level and ran as a separate process with its own
state file.
site-to-site certificates and for the administrator's own uses. Its root is its own, a CA the
organisation keeps offline, or the root of the organisation's Simple CA service. Moving the key of a
root the server created off the server later protects nothing that was not exposed while it was
there. The `simple-ca` script handled one level and ran as a separate process with its own state
file.
Decision: The root signs only issuing CAs, path length 1; the issuing CAs, path length 0, sign
the certificates. `p2s` signs the server's VPN server certificate and the users' certificates,
Decision: `pki.root` chooses the root at setup, fixed once the root exists, as the directory
shows it: `local`, a root the server creates and keeps the key of, which signs only issuing CAs,
path length 1; `offline`, whose certificate and the certificates of the issuing CAs, signed
offline from the CSRs the server makes, are imported with `linux-manager-ca` or `/ca`, the root
first; `simple-ca`, a Simple CA service (ADR-59). The issuing CAs, path length 0, sign the
certificates. `p2s` signs the server's VPN server certificate and the users' certificates,
`s2s` the site-to-site certificates, and the CAs of `pki.issuing_cas` what their templates
allow. A template fixes the key, the lifetime, the key usages, the extended key usages, the kind
of common name and the subject alternative names a certificate may have; `vpn-server` and
@@ -772,10 +778,9 @@ of common name and the subject alternative names a certificate may have; `vpn-se
CA. The module `linuxmanager_pki.py`, with `python3-cryptography` from the Ubuntu archive, builds
the keys, certificates, CSRs and CRLs in the processes that need them, as the user module does
(ADR-6); the settings are the `pki` section of `linux-manager.json`, and the CAs and the
certificates are kept in the server's directory (ADR-32). Keeping the root key off the server is recommended, not required: while it is
on the server a new issuing CA is signed at once, and while it is not the CA gets its key and a
CSR, signed offline and imported with `linux-manager-ca` or `/ca`. The root key itself crosses
neither the API nor the Manager. For a certificate of something other than the server, the server
certificates are kept in the server's directory (ADR-32). A root the server creates keeps its key
there, with no command that exports or removes it; the key crosses neither the API nor the
Manager. For a certificate of something other than the server, the server
signs the requester's CSR, or makes the key and returns it once in a PKCS#12 file, keeping only
the certificate, so a key it gave away cannot leak from it later. The PKCS#12 file uses 3DES and
SHA-1 MACs, the encryption the key stores of Windows and macOS import. strongSwan reads only the
@@ -783,8 +788,10 @@ first certificate of a PEM file, so each CA has a file of its own in `/etc/swanc
IKEv2 access and site-to-site name their CA in `cacerts`, which restricts the trust chain to it.
Consequences: The P2S CA's certificates are accepted by IKEv2 and OpenVPN only, the site-to-site CA's by
site-to-site only. With an offline root, new issuing CAs and the root CRL need the offline step,
and a router whose P2S CA waits has no VPN server certificate and so no P2S access. The server
site-to-site only. With an offline root, the root certificate, new issuing CAs and the root CRL
need the offline step, and a router whose P2S CA waits has no VPN server certificate and so no
P2S access. A server whose root should be elsewhere is set up with that source from the start;
the source of an existing root is not changed. The server
keeps the users' keys, as the OpenVPN profile embeds them.
## ADR-28: CA certificates and CRLs are published at configurable endpoints, and CRLs are short-lived
@@ -850,7 +857,7 @@ Decision: An issuing CA of `pki.issuing_cas` with `acme` makes Caddy serve an AC
at `/acme/<name>/` of the HTTPS status port, each in a `handle` block of its own. The issuing CA's
certificate and key are given to Caddy as both the root and the intermediate of a `pki` CA, copied
to `/etc/caddy/linux-manager-pki/<name>/` for Caddy's group, so that the server's root key never
reaches Caddy and may be offline.
reaches Caddy.
Consequences: The certificates Caddy issues chain to the server's root through the issuing CA, are
not in the server's inventory, follow no template and are not revoked; their short lifetime takes
@@ -1582,17 +1589,47 @@ checks for and installs its updates through apt (ADR-24, ADR-53). A package copi
server and installed from a file tests none of that, and a rebuild of an unreleased changelog
entry keeps the same version, so apt sees no update.
Decision: `tests/remote/lxd-project.py` makes an LXD project for manual tests with networks of its
Decision: `bin/lm-dev-lxd-project.py` makes an LXD project for manual tests with networks of its
own (`features.networks`), a WAN and two LANs, and a container `repo` that serves a signed apt
repository, `resolute main`, built with `apt-ftparchive` and signed by its own key. The networks
are OVN networks on an uplink bridge of the remote, as OVN is the only network type LXD creates
inside a project; they belong to the project and go with it. `tests/remote/dev-build.py` builds the newest
changelog entry as `<upstream>~dev<N>-<revision>`, `N` counted in `tmp/test-number`, by passing
`DEB_VERSION` to the build, which rewrites the version in the image only, and publishes the build
in that repository. `tests/remote/vm.py` gives a VM of the project that repository as its apt
source. The automated tests (`run.py`) keep their own project for one run and install from a
file.
inside a project; they belong to the project and go with it. `bin/lm-dev-build.py` builds the newest
changelog entry as `<upstream>~dev<N>-<revision>`, `N` counted in `.dev-build.serial`, which a
release sets to 0, by passing `DEB_VERSION` to the build, which rewrites the version in the image
only, and publishes the build in that repository. `bin/lm-dev-vm.py` gives a VM of the project
that repository as its apt source. The automated tests (`lm-dev-run.py`) keep their own project
for one run and install from a file.
Consequences: Every dev build is an apt update of the one before, and the release of the entry,
which sorts above all of its `~dev` builds, is an update of them all. The changelog is not
changed by a dev build. Dev builds go to `out/dev/`, so `out/` holds only release builds.
## ADR-59: A Simple CA root signs the issuing CAs through a sign-ca token of its issuing CA
Status: Accepted
Context: An organisation with a Simple CA service wants its servers' issuing CAs under that root,
signed without a person carrying CSRs and certificates. Simple CA's tokens are JWTs signed by the
key of their CA; a one-time setup code is exchanged once for a token, so the token itself is never
handed over. A Simple CA root that signs the issuing CAs of every server directly would give each
server's token the power of the root.
Decision: Simple CA keeps a three-level hierarchy: its root, path length 2, signs an issuing CA,
path length 1, the upstream CA, which signs the server's issuing CAs, path length 0. The server
gets the setup code of a `sign-ca` token of the upstream CA at setup (debconf, written to
`/etc/linux-manager/pki-setup-code` and removed once used) or with `linux-manager-ca root
setup-code`, exchanges it at `/api/token-setup` over `https://` only, checked against the system's
trust store, where the administrator installs the CA of the service's certificate before setup,
and keeps the token and the
upstream CA's name on `cn=root` of the directory, unreadable to every account but root's socket,
as the keys are. Each issuing CA's CSR is signed at `/<upstream>/api/sign-ca`. The root and the
upstream CA are taken from the first chain Simple CA answers with, once the token's signature
verifies with the upstream CA's key, which ties the chain to the service that issued the token;
every later chain must match them. The upstream CA is `cn=upstream`, in every chain the server
gives; the root alone is the trust anchor. Their CRLs are fetched from the distribution points
of the certificates they signed, as Simple CA publishes them.
Consequences: A stolen token signs CAs under the upstream CA only, until it expires or is revoked
in Simple CA. An issuing CA waits while Simple CA cannot be reached or the token has expired, and
a new setup code renews the token. The server cannot revoke a retired issuing CA in Simple CA;
its notice says to. Clients see a chain one CA longer than with the other sources.
+117 -66
View File
@@ -157,7 +157,9 @@ must have the type shown below; an unknown section or setting is an error.
| `dns` | `enabled` | boolean | `false` | The primary name server of the server's domains, `wan.local_fqdn`, which must then be a DNS name (see Name server) |
| `dns` | `secondary` | string | | The secondary name server of every domain, a host name other than `wan.local_fqdn`; it may transfer the domains |
| `dns` | `listen` | string | `external` | The interfaces the name server answers on: `internal`, `external` or `both` |
| `dns` | `ttl` | integer | `300` | TTL of the records, 60 to 86400 seconds |
| `dns` | `ttl` | integer | `300` | The default TTL of the records, 60 to 86400 seconds: used where neither the record nor its domain has one |
| `pki` | `root` | string | `local` | Where the root CA comes from: `local`, `offline` or `simple-ca`; fixed once the root exists (see Certificates) |
| `pki` | `simple_ca_url` | string | | The `https://` URL of the Simple CA service, with `root` `simple-ca` |
| `pki` | `root_name` | string | `Linux Manager Root CA` | Common name of the root CA, when the server creates it |
| `pki` | `root_days` | integer | `7300` | Days the root CA's certificate is valid |
| `pki` | `ca_days` | integer | `3650` | Days an issuing CA's certificate is valid |
@@ -170,7 +172,6 @@ must have the type shown below; an unknown section or setting is an error.
| `pki` | `issuing_cas` | object | | The general-purpose issuing CAs, each a name and `{name, templates, acme}` (see Certificates) |
| `pki` | `templates` | object | | Certificate templates, each a name and the options it changes or defines (see Certificates) |
| `pki` | `extended_key_usages` | object | | Custom extended key usages templates may give, each a name and its OID in dotted form (see Certificates) |
| `pki` | `root_key_warning` | boolean | `true` | `linux-manager-ca status` and `/ca` warn while the root key is on the server; `false` silences that warning |
| `metrics` | `enabled` | boolean | `true` | The metrics service: collection, history and `/metrics` |
| `metrics` | `listen` | string | `internal` | The interfaces `/metrics` is served on: `internal`, `external` or `both` |
| `metrics` | `port` | integer | `9464` | TCP port of `/metrics` |
@@ -431,8 +432,9 @@ The server has a two-level certificate authority, kept by `linux-manager-setup`
uses. It is held in `ou=pki,dc=linux-manager,dc=local` of the server's directory, next to the users:
```
cn=root the root CA; without linuxManagerPrivateKey while the root is offline
cn=<name> an issuing CA; with linuxManagerCertificateRequest while it waits for the offline root
cn=root the root CA; its key with pki.root local, the Simple CA token with simple-ca
cn=upstream the Simple CA issuing CA that signs the issuing CAs, with simple-ca
cn=<name> an issuing CA; with linuxManagerCertificateRequest while it waits for its certificate
cn=<name>-<time> an issuing CA taken out of use, with linuxManagerRetired
serialNumber=<serial>,cn=<CA> a certificate the CA issued
```
@@ -464,21 +466,21 @@ The root signs the issuing CAs only (path length 1), and the issuing CAs sign th
lowercase letters, digits and hyphens, and is not `root`, `p2s` or `s2s`; `templates` are the
templates the CA issues.
Once a platform is chosen, `linux-manager-setup` creates what is missing: the root when it has
neither certificate nor key, each issuing CA, the server's certificates once `wan.local_fqdn` is
set, and the CRLs. The names, lifetimes and key type of `pki` apply when something is created. An
issuing CA removed from `pki.issuing_cas` is retired: its entry is renamed `cn=<name>-<time>`,
loses its key, and its certificate is revoked on the root CRL. The server renews its own certificates when less than a
Once a platform is chosen, `linux-manager-setup` creates what is missing: the root, as `pki.root`
says (see The root), each issuing CA, the server's certificates once `wan.local_fqdn` is set, and
the CRLs. The names, lifetimes and key type of `pki` apply when something is created. An issuing
CA removed from `pki.issuing_cas` is retired: its entry is renamed `cn=<name>-<time>`, loses its
key, and its certificate is revoked on the root CRL, or, with an external root, there. The server renews its own certificates when less than a
third of their lifetime is left, when the names they need change, or when their CA changes; a
user's certificate is renewed by removing and adding the user.
The package copies what each consumer needs: the root, `p2s` and `s2s` into
`/etc/swanctl/x509ca/` as `root.pem`, `p2s.pem` and `s2s.pem` (strongSwan reads one certificate
per file), the remote CA of each site-to-site connection that has one as `s2s-<name>.pem`, the
server's certificates into `/etc/swanctl/x509/` and their keys into `/etc/swanctl/private/`, the
CRLs into `/etc/swanctl/x509crl/`, the root and `p2s` with their CRLs into
`/etc/openvpn/server/linux-manager-ca.pem` and `linux-manager-crl.pem`, and the root into the system
trust store.
The package copies what each consumer needs: the root, the Simple CA upstream CA when there is
one, `p2s` and `s2s` into `/etc/swanctl/x509ca/` as `root.pem`, `upstream.pem`, `p2s.pem` and
`s2s.pem` (strongSwan reads one certificate per file), the remote CA of each site-to-site
connection that has one as `s2s-<name>.pem`, the server's certificates into `/etc/swanctl/x509/`
and their keys into `/etc/swanctl/private/`, the CRLs into `/etc/swanctl/x509crl/`, the root, the
upstream CA and `p2s` with their CRLs into `/etc/openvpn/server/linux-manager-ca.pem` and
`linux-manager-crl.pem`, and the root into the system trust store.
`linux-manager-ca status` shows the root, the issuing CAs and what needs attention:
@@ -580,45 +582,90 @@ has `linux-manager-setup` renew the server's certificates when they are due. Ope
of every CA of a client's chain, the root's included, and refuses every client while one has
expired.
### Offline root
### The root
Keeping the root key off the server is recommended, not required; while it is on the server,
`linux-manager-ca status` says so, unless `pki.root_key_warning` is `false`. Export it, encrypted with a
passphrase read from the first line of standard input, keep the file in a safe place, and remove
the key from the server:
`pki.root`, chosen at setup and fixed once the root exists, says where the root comes from:
| Source | The root | The issuing CAs | The root CRL |
|---|---|---|---|
| `local` (the default) | created by the server, named `pki.root_name`, with its key on the server | signed by the server | signed by the server |
| `offline` | a CA kept elsewhere, whose certificate is imported | signed offline from their CSRs, then imported | signed offline, then uploaded |
| `simple-ca` | the root of a Simple CA service | signed by an issuing CA of that Simple CA | fetched from Simple CA |
Setup refuses a `pki.root` other than the source of the root the directory holds, and so does
`PUT /ca`.
#### Offline root
Setup makes the key and the CSR of each issuing CA and waits; `linux-manager-ca status` lists
what waits. Import the root's certificate first, self-signed and allowing a CA below it, then sign
each CSR with the root and import the certificate:
```sh
linux-manager-ca root export-key --out /root/linux-manager-root-key.pem
linux-manager-ca root remove-key
linux-manager-ca ca import root root-cert.pem
linux-manager-ca ca csr p2s # the CSR, then the [ issuing_ca ] extensions
# on the offline machine, with the CSR in p2s.csr and the extensions in issuing_ca.cnf:
openssl x509 -req -in p2s.csr -CA root-cert.pem -CAkey root-key.pem -CAcreateserial \
-days 3650 -sha256 -extfile issuing_ca.cnf -extensions issuing_ca -out p2s.pem
linux-manager-ca ca import p2s p2s.pem
```
While the root key is not on the server, a new issuing CA gets its key and a CSR and waits;
`linux-manager-ca status` says so. Print the CSR and the extensions to sign it with, sign it with the
root on the offline machine, and import the certificate:
The server cannot sign the root CRL. Sign it offline and upload it before the current one
expires, as OpenVPN refuses every client while a CRL of a client's chain has expired:
```sh
linux-manager-ca ca csr servers # the CSR, then the [ issuing_ca ] extensions
# on the offline machine, with the CSR in servers.csr and the extensions in issuing_ca.cnf:
openssl x509 -req -in servers.csr -CA root-cert.pem -CAkey linux-manager-root-key.pem -CAcreateserial \
-days 3650 -sha256 -extfile issuing_ca.cnf -extensions issuing_ca -out servers.pem
linux-manager-ca ca import servers servers.pem
```
The server cannot sign the root CRL without the key. Sign it where the key is, or put the key back
for a moment, and take the CRL before the current one expires:
```sh
linux-manager-ca root import-key /root/linux-manager-root-key.pem # the passphrase on standard input
linux-manager-ca maintain
linux-manager-ca root remove-key
# or, with a CRL signed elsewhere:
linux-manager-ca root import-crl root.crl
```
An existing root CA of your own is used by placing its certificate, and its key if the server may
use it, as `/etc/linux-manager/pki/root/cert.pem` and `key.pem` before `linux-manager-setup` first runs
with a platform, as cloud-init can. Setup imports them into the directory and removes the files.
Without the key, the issuing CAs wait for their certificates as above.
A retired issuing CA is revoked on the root CRL signed offline.
#### Simple CA root
A Simple CA service signs the issuing CAs. Its root allows two levels of CAs below it, and one of
its issuing CAs, the upstream CA, may sign CAs:
```text
Simple CA root (pathlen 2)
Simple CA issuing CA, the upstream CA (pathlen 1)
the server's issuing CAs (pathlen 0)
the certificates
```
In Simple CA, a `sign-ca` token of the upstream CA is created with a one-time setup code:
```sh
simple-ca ca create --ca-dir /srv/ca --path-length 2 "Example Root CA"
simple-ca ca create --ca-dir /srv/ca --issuing-ca servers --path-length 1 "Example Servers CA"
simple-ca token create --ca-dir /srv/ca/servers --scope sign-ca --otc --valid 8760h router
```
`pki.simple_ca_url` is the `https://` URL of the Simple CA service. The server checks its HTTPS
certificate against the system's trust store, so the CA that issued it, any CA, is installed
there before setup runs, by the administrator or by cloud-init's `ca_certs`:
```sh
install -m 0644 https-ca.pem /usr/local/share/ca-certificates/simple-ca-https-ca.crt
update-ca-certificates
```
The setup code is given at setup (debconf `linux-manager/pki_setup_code`, written to
`/etc/linux-manager/pki-setup-code`) or later:
```sh
linux-manager-ca root setup-code # the setup code on standard input
```
The server exchanges the code at `/api/token-setup` for the token, which it keeps in the
directory, and has each issuing CA signed at `/<upstream>/api/sign-ca`. It takes the root and the
upstream CA from the first chain Simple CA answers with, once the token's signature verifies with
the upstream CA's key, and checks every later chain against them. The upstream CA is in every
chain the server gives: the CA bundles, the chains of issued certificates, OpenVPN's CA file and
the Apple VPN profile. The root and the upstream CRLs are fetched daily from the CRL distribution
points of the certificates they signed.
An issuing CA waits while Simple CA cannot sign it, and `linux-manager-ca maintain` has setup try
again. A token that expired, or a setup code that expired before setup ran, is replaced with a new
setup code. A retired issuing CA is revoked in Simple CA, where the server cannot do it.
### ACME server
@@ -789,7 +836,8 @@ While `p2s.enabled` is `true` and `wan.local_fqdn` is set, `/users/<name>/apple-
user's own `/account/apple-profile` give an unsigned Apple configuration profile (`.mobileconfig`)
that sets up IKEv2 access in the built-in VPN client of macOS, iOS and iPadOS. It holds:
- the P2S CA and the root CA, the root installed as a trusted root;
- the P2S CA, the Simple CA issuing CA above it when there is one, and the root CA, the root
installed as a trusted root;
- the user's certificate and key as a PKCS#12 encrypted with the password of the request, with
3DES and SHA-1, the only encryption Apple's clients read; the device asks for the password when
the profile is installed, and the server does not keep it;
@@ -1162,7 +1210,7 @@ lme /etc/linux-manager/linux-manager.json ~/notes.txt
| `network` | The external and internal interface, their addresses, the internal gateway, `local.cidrs`, `site_to_site`: each connection with `name`, `local_identity`, `remote_identity`, `local_cidrs` and `remote_cidrs`, `interfaces`: each interface but loopback with `name`, `state`, `mac`, `ipv4`, its IPv4 addresses, and `ipv6`, its global IPv6 addresses, as `address/prefix`, `null` when `ip` fails, and the IPv4 routes as `ip -j -4 route` prints them |
| `ipsec` | `connections` and `sas`: one object per connection and per IKE SA, read from `swanctl --list-conns --pretty` and `swanctl --list-sas --pretty`, with the connection's name under `name` and swanctl's keys and string values |
| `wireguard` | The public key and port of `wg0`, and each peer's public key, endpoint, allowed IPs, handshake age and traffic; no private or preshared key |
| `docker` | `docker.exposed_ports` and the rules of the `LINUX-MANAGER-DOCKER` chain |
| `docker` | `installed`, whether `docker.service` is installed, `docker.exposed_ports` and the rules of the `LINUX-MANAGER-DOCKER` chain |
| `postgresql` | `clusters`: each PostgreSQL cluster of `pg_lsclusters` with its version, name, port, status and data directory, and for one that is online its `settings`: `server_version`, `listen_addresses`, `port`, `max_connections`, `shared_buffers`, `effective_cache_size`, `work_mem`, `password_encryption`, `ssl` and `timezone`; `null` when `pg_lsclusters` fails |
| `caddy` | The installed Caddy: `version`, `source`, `upstream` once Caddy's repository is configured and `ubuntu` otherwise, and `service`, the state of `caddy.service`; `null` when Caddy is not installed |
| `oidc` | The OpenID Provider: `enabled`, and `issuer`, its issuer URL, `null` while it is disabled |
@@ -1444,29 +1492,30 @@ group, must allow the OpenVPN and WireGuard ports itself.
| Request | Body | Answer |
| --- | --- | --- |
| `GET /ca` | | `{"settings", "templates", "extended_key_usages", "status", "certificates"}` |
| `PUT /ca` | any of the settings of the `pki` section | `{"settings", "templates"}` |
| `PUT /ca` | any of the settings of the `pki` section; `root` only as the source of an existing root | `{"settings", "templates"}` |
| `POST /ca/certificates` | `{"ca", "template", "csr"}` | 201 and `{"serial", "certificate", "chain"}`, PEM |
| `POST /ca/certificates` | `{"ca", "template", "subject", "sans", "password"}` | 201 and `{"serial", "pfx"}`, a PKCS#12 file in base64 |
| `POST /ca/certificates/<serial>/revoke` | `{"reason"}`, optional | the certificate, with `reissue` for a router certificate |
| `GET /ca/bundle/<name>` | | `{"name", "pem"}`: the certificates a client trusts the CA with, the root alone for `root`, the issuing CA followed by the root for an issuing CA |
| `GET /ca/bundle/<name>` | | `{"name", "pem"}`: the certificates a client trusts the CA with, the root alone for `root`, the issuing CA followed by the Simple CA upstream CA, when there is one, and the root for an issuing CA |
| `GET /ca/issuing/<name>/csr` | | `{"name", "csr", "extensions"}` of an issuing CA waiting for the offline root |
| `PUT /ca/issuing/<name>/certificate` | `{"certificate"}`, PEM, signed by the root | `{"name", "subject", "expires"}` |
| `PUT /ca/root/crl` | `{"crl"}`, PEM, signed by the root | `{"next_update"}` |
| `PUT /ca/root/certificate` | `{"certificate"}`, PEM, of the offline root | `{"name", "subject", "expires"}` |
| `PUT /ca/root/crl` | `{"crl"}`, PEM, signed by the offline root | `{"next_update"}` |
| `PUT /ca/root/setup-code` | `{"code"}`, a Simple CA setup code | `{"upstream", "expires"}`: the Simple CA issuing CA and the expiry of the token |
The answer of `GET /ca` holds:
- **`settings`:** the `pki` section.
- **`templates`:** every template, the built-in ones included, with all its options.
- **`extended_key_usages`:** every extended key usage templates may give, name -> `{"oid", "builtin"}`.
- **`status`:** `root` (`subject`, `expires`, `key`, whether the root key is on the server, `crl_next_update` and `crl_source`, `signed` or `uploaded`), `authorities`, one per issuing CA (`name`, `common_name`, `state`: `active`, `pending` or `missing`, `builtin`, `templates`, `acme`, `subject`, `expires`, `key`, `crl_next_update`, `acme_url`), `retired` and `warnings`.
- **`status`:** `root` (`source`, `pki.root`, `state`, `active` or `pending`, `subject`, `expires`, `crl_next_update`, `crl_source`, `signed`, `uploaded` or `fetched`, `simple_ca_url`, `upstream`, the Simple CA issuing CA `{"name", "subject", "expires", "crl_next_update"}` or null, and `token_expires`), `authorities`, one per issuing CA (`name`, `common_name`, `state`: `active`, `pending` or `missing`, `builtin`, `templates`, `acme`, `subject`, `expires`, `key`, `crl_next_update`, `acme_url`), `retired` and `warnings`.
- **`certificates`:** the certificates issued, newest first, each `{"serial", "ca", "kind", "template", "subject", "sans", "created", "expires", "revoked", "reason", "state"}`; `kind` is `ca`, `router`, `user` or `external`, and `state` `valid`, `expired` or `revoked`.
A change of the settings is made, checked and applied as for `/site-to-site`; an imported issuing
CA certificate and a revoked router certificate restart `linux-manager-setup` too. A failure is
`{"error": ...}` with 400 for an invalid request, 404 for something that does not exist, 409 when
the state does not allow it, as for a revoked certificate or an issuing CA that has its
certificate, and 500 otherwise. The root key never crosses the API; `linux-manager-ca` exports,
removes and imports it.
A change of the settings is made, checked and applied as for `/site-to-site`; an imported root or
issuing CA certificate, a new Simple CA token and a revoked router certificate restart
`linux-manager-setup` too. A failure is `{"error": ...}` with 400 for an invalid request, 404 for
something that does not exist, 409 when the state does not allow it, as for a revoked certificate
or an issuing CA that has its certificate, and 500 otherwise. The root key never crosses the API.
The service starts on its own, without waiting for `linux-manager-setup`, and keeps running. Every
30 seconds it reads `web.listen`, `web.port` and `web.enabled` from `linux-manager.json` and works
@@ -1975,7 +2024,7 @@ A backup holds the state that `linux-manager-setup` cannot make again:
| `/etc/wireguard` | The WireGuard keys and the peers |
| `/etc/ufw`, `/etc/default/ufw` | The firewall rules |
| `files/<path>` | Each `psk_file` outside `/etc/linux-manager` |
| `ldap/linux-manager.ldif` | The user directory, written by `slapcat`: users, groups, service accounts, password hashes and TOTP secrets, and the PKI: the CAs and their keys, the root key while it is on the server, and the certificates issued, with the keys of the server's and the users' certificates |
| `ldap/linux-manager.ldif` | The user directory, written by `slapcat`: users, groups, service accounts, password hashes and TOTP secrets, and the PKI: the CAs and their keys, the Simple CA token, and the certificates issued, with the keys of the server's and the users' certificates |
| `postgresql/linux-manager.dump` | With `backup.metrics`, the database of the metrics and the refresh tokens, written by `pg_dump -Fc` |
| `/var/lib/linux-manager/sites` | The folders of the web sites |
| `postgresql/linux-manager-sites.dump`, `postgresql/linux-manager-dns.dump` | The databases of the web sites and of the name server, once they exist |
@@ -2081,7 +2130,10 @@ name, left of Sign out, opens the account page, and the terminal icon left of it
- **Settings** (the gear in the header, hidden on the sign-in and the account page): how often the Overview and the Metrics tab read the server
on their own, kept in the browser's localStorage, so each browser has its own. Each tab reads
manually, or every 5, 10 or 30 seconds, 1, 5 or 15 minutes; the Overview tab every 10 seconds and
the Metrics tab every minute by default. Manual reads when the tab opens and on Refresh. A change applies at once, also in the browser's other tabs; Defaults sets both back.
the Metrics tab every minute by default. Manual reads when the tab opens and on Refresh. **Open
the shell in a new tab**, off by default, makes the shell button open the shell in a tab of its
own, which stays open while the first tab opens other pages. A change applies at once, also in
the browser's other tabs; Defaults sets them back.
- **Account** (`/user`): the Account and the Passkeys panel side by side, with One-time passwords
and VPN profiles below. The user's name, kind, names, e-mail address, whether they are an
@@ -2102,17 +2154,15 @@ name, left of Sign out, opens the account page, and the terminal icon left of it
and code.
- **Certificates** (`/ca-manager`, in the page menu of administrators): the server's two-level CA, from its `/ca`, in tabs:
- **Root:** the root CA's subject, expiry, whether its key is on the server, marked with a warning sign, or offline, and its CRL, with Download root CA, the root's certificate alone, and Upload CRL for a root CRL signed offline; the general information: where certificates and CRLs are published, the CA key type, the lifetimes, and the CRL validity; the certificates of the issuing CAs, each active one with a download icon for its CA bundle, and the retired ones.
- **Root:** the root CA's source, state, subject, expiry and CRL, with Simple CA its issuing CA that signs the server's and the expiry of the token, with Download root CA, the root's certificate alone; Import root certificate while an offline root waits for it, Upload CRL for a CRL of the offline root, and Enter setup code for a new Simple CA token; the general information: where certificates and CRLs are published, the CA key type, the lifetimes, and the CRL validity; the certificates of the issuing CAs, each active one with a download icon for its CA bundle, and the retired ones.
- **Templates:** the certificate templates with their key, lifetime, subject, usages, alternative names, certificate policies and the CAs that issue them; Add template, Edit on each, Remove on one of the server's own and Reset on a changed built-in one, which brings back its defaults. A template's extended key usages are chosen from those of the next tab, and its certificate policies are OIDs typed in.
- **Extended key usages:** the usages templates may give, with their OIDs and the templates that give them; the built-in ones are shown and not changed, and custom ones are added with a name and an OID, and changed or removed.
- **P2S Issuing CA** and **S2S Issuing CA:** the CA's common name, state (active, or pending while it waits for the offline root), expiry, CRL and templates, and the certificates it issued. An active CA gives its CA bundle, the issuing CA followed by the root, with Download CA bundle; a pending CA gives its CSR with the openssl extensions to sign it with, and takes the certificate signed by the root.
- **Issuing CAs:** the general-purpose CAs with their state, expiry, CRL, templates and ACME directory URL; Add issuing CA, and Edit and Remove on each: its name, fixed once it exists, its common name, the templates it issues and its ACME server; an active CA's download icon gives its CA bundle. A removed CA is retired by the server, which revokes its certificate on the root CRL. Below, their certificates, filtered by CA. - **Certificates:** each with its kind, template, names, expiry and state; a certificate of another system or of the server is revoked after a confirmation with a reason.
- **Issue** (above the tabs): from a CSR, saving the certificate with its chain, or with a key the server makes, saving a PFX file protected by a password; the server keeps no copy of the key.
- **Settings** (above the tabs): the names, lifetimes, key type, CRL validity and publishing endpoints.
- **Settings** (above the tabs): the source of the root, shown, the Simple CA URL, the names, lifetimes, key type, CRL validity and publishing endpoints.
- **Warnings** (above the tabs): what the server says needs attention, such as a CRL about to expire.
The root key is exported, removed and imported on the server with `linux-manager-ca`, never through the Manager.
- **Overview**: the server's overall status, ok or degraded, on the title bar of the Status panel;
at the top of that panel, a table of `linux-manager`
with the installed version and, when the repository has a newer one, that version; Check update
@@ -2256,9 +2306,10 @@ name, left of Sign out, opens the account page, and the terminal icon left of it
domain (domain, TTL), edited and removed with their icons; and for the selected domain the
records it serves, and its manual records, added with Add record (name, type, content and
TTL) and removed with their icon.
- **Docker** (`/docker-manager`): whether Docker is installed, the state of `docker.service` and of
the server's Docker rules, the ports exposed on the external interface and the rules of the
`LINUX-MANAGER-DOCKER` chain, from the server's `/status/full` and `/config`.
- **Docker** (`/docker-manager`): the state of `docker.service` and of the server's Docker rules,
the ports exposed on the external interface and the rules of the `LINUX-MANAGER-DOCKER` chain,
from the server's `/status/full` and `/config`. The page menu leaves the page out while
`/config` says Docker is not installed, and the page itself then says so.
- **Shell** (`/shell`, the terminal icon in the header): a login shell on the server in xterm.js, the terminal of VS Code, as the
signed-in user's console account, the user's own LDAP POSIX account or a local account. Opening
it asks for the password and the code again, or Open with a passkey takes one of the user's
@@ -1,36 +1,38 @@
#!/usr/bin/env python3
"""Build the next numbered dev build and publish it to a test project's repository: dev-build.py.
"""Build the next numbered dev build and publish it to a test project's repository: lm-dev-build.py.
The test number in tmp/test-number goes up by one for each build that succeeds. The build's version
The serial N in .dev-build.serial of the repository is that of the last dev build; each build that
succeeds writes its own, one higher, and release.py writes 0 when it releases. The build's version
is the newest changelog entry's with ~devN before its Debian revision, 0.41.0-1 becoming
0.41.0~dev7-1, so the release of that entry is newer than all its dev builds. ./build.sh builds it
with CONTAINER_RUNTIME and DOCKER_CONTEXT from the environment; the build is moved to out/dev/,
copied into the repository container of the project (--project or LXD_PROJECT, lm-dev by default)
made by lxd-project.py, and published there.
copied into the repository container of the project --project (LXD_PROJECT, lm-dev by default)
made by lm-dev-lxd-project.py, and published there. The remote is the project's, read from
tmp/lxd-project-PROJECT.json, so the script takes no --remote.
"""
import argparse
import json
import os
import pathlib
import re
import subprocess
import sys
HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent.parent
NUMBER = ROOT / 'tmp' / 'test-number'
from lm_dev import PROJECT, ROOT, lxc_exec
SERIAL = ROOT / '.dev-build.serial'
CHANGELOG = ROOT / 'debian-package' / 'debian' / 'changelog'
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', 'lm-dev'),
help='the test project made by lxd-project.py (LXD_PROJECT, default lm-dev)')
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT),
help=f'the test project made by lm-dev-lxd-project.py, whose remote is used (LXD_PROJECT, '
f'default {PROJECT})')
args = parser.parse_args()
state_file = ROOT / 'tmp' / f'lxd-project-{args.project}.json'
if not state_file.is_file():
sys.exit(f'no {state_file}; create the project with lxd-project.py create')
sys.exit(f'no {state_file}; create the project with lm-dev-lxd-project.py create')
state = json.loads(state_file.read_text(encoding='utf-8'))
# The newest entry's first line is "package (version) distribution; urgency=...".
@@ -38,14 +40,14 @@ def main():
if not match:
sys.exit(f'no version in the first line of {CHANGELOG}')
package, version = match.groups()
number = int(NUMBER.read_text(encoding='utf-8').strip()) + 1 if NUMBER.is_file() else 1
number = int(SERIAL.read_text(encoding='utf-8').strip()) + 1 if SERIAL.is_file() else 1
upstream, dash, revision = version.rpartition('-')
dev = f'{upstream}~dev{number}-{revision}' if dash else f'{version}~dev{number}'
print(f'building {package} {dev}')
if subprocess.run(['./build.sh', '--build-arg', f'DEB_VERSION={dev}'], cwd=ROOT).returncode != 0:
sys.exit(f'the build of {dev} failed; the test number stays {number - 1}')
NUMBER.write_text(f'{number}\n', encoding='utf-8')
sys.exit(f'the build of {dev} failed; the serial stays {number - 1}')
SERIAL.write_text(f'{number}\n', encoding='utf-8')
# The dev build leaves out/ to out/dev/, so out/ keeps the release builds.
target = ROOT / 'out' / 'dev'
@@ -56,13 +58,12 @@ def main():
if not deb.is_file():
sys.exit(f'the build made no {deb.name}')
where = ['--project', state['project']]
pushed = subprocess.run(['lxc', 'file', 'push', str(deb), f'{state["remote"]}:repo/var/www/html/pool/main/{deb.name}',
'--mode', '0644', *where], capture_output=True, text=True)
pool = f'{state["remote"]}:repo/var/www/html/pool/main/{deb.name}'
pushed = subprocess.run(['lxc', 'file', 'push', str(deb), pool, '--mode', '0644', '--project', state['project']],
capture_output=True, text=True)
if pushed.returncode != 0:
sys.exit(f'could not copy {deb.name} into the repository: {pushed.stderr.strip()}')
published = subprocess.run(['lxc', 'exec', f'{state["remote"]}:repo', *where, '-T', '--',
'linux-manager-repo-publish'], capture_output=True, text=True)
published = lxc_exec(state['remote'], state['project'], 'repo', 'linux-manager-repo-publish')
if published.returncode != 0:
sys.exit(f'the repository was not published: {published.stderr.strip()}')
print(f'{package} {dev} is published at {state["repository"]} (resolute main)')
@@ -1,29 +1,29 @@
#!/usr/bin/env python3
"""Create or remove an LXD project for manual tests: lxd-project.py create|remove|uplink setup|remove.
"""Create or remove an LXD project for manual tests, or its uplink: lm-dev-lxd-project.py create|remove|uplink.
uplink setup creates the physical uplink network once per remote, uplink remove deletes it (see
uplink).
uplink setup creates the physical uplink network once per remote, and uplink remove deletes it
(see uplink).
create makes, on the remote (--remote or LXD_REMOTE), the project (--project or LXD_PROJECT,
lm-dev by default) with its root disks on --pool (LXD_POOL) and networks of its own, OVN networks
on the uplink --uplink (LXD_UPLINK, uplink by default): wan, with NAT and DHCP on a subnet LXD
picks, and lana and lanb, on subnets LXD picks without DHCP. The project's default profile puts
eth0 on wan. The container repo serves a signed apt repository of the dev builds over HTTP; dev-build.py publishes into it and vm.py installs from it. What they need is
written to tmp/lxd-project-PROJECT.json, with the repository's key in tmp/lxd-project-PROJECT.gpg.
remove deletes the project's instances, its networks, the project and those files.
eth0 on wan. The container repo serves a signed apt repository of the dev builds over HTTP;
lm-dev-build.py publishes into it and lm-dev-vm.py installs from it. What they need is written to
tmp/lxd-project-PROJECT.json, with the repository's key in tmp/lxd-project-PROJECT.gpg. remove
deletes the project's instances, its networks, the project and those files.
"""
import argparse
import json
import os
import pathlib
import re
import subprocess
import sys
import time
HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent.parent
from lm_dev import PROJECT, ROOT, TESTS, lxc_exec
NETWORKS = ('wan', 'lana', 'lanb')
@@ -51,12 +51,11 @@ def create(args, state, key):
print(f'launching the repository container {args.remote}:repo (project {args.project})')
lxc('launch', args.image, f'{args.remote}:repo',
'-c', 'cloud-init.user-data=' + (HERE / 'cloud-init' / 'repo.yaml').read_text(encoding='utf-8'),
'-c', 'cloud-init.user-data=' + (TESTS / 'cloud-init' / 'repo.yaml').read_text(encoding='utf-8'),
project=args.project)
def inside(*command):
return subprocess.run(['lxc', 'exec', f'{args.remote}:repo', '--project', args.project, '-T', '--', *command],
capture_output=True, text=True)
return lxc_exec(args.remote, args.project, 'repo', *command)
# Wait for cloud-init (status 2 is done with recoverable errors), then for the address of eth0.
for _ in range(120):
@@ -66,7 +65,8 @@ def create(args, state, key):
else:
raise RuntimeError('the repository container did not boot')
for _ in range(24):
match = re.search(r' inet (\d+\.\d+\.\d+\.\d+)/', inside('ip', '-4', '-o', 'addr', 'show', 'dev', 'eth0').stdout)
match = re.search(r' inet (\d+\.\d+\.\d+\.\d+)/',
inside('ip', '-4', '-o', 'addr', 'show', 'dev', 'eth0').stdout)
if match:
break
time.sleep(5)
@@ -77,15 +77,15 @@ def create(args, state, key):
project=args.project)
# The signing key, the publishing script and the empty indexes.
for step, command in (('key generation', ('gpg', '--batch', '--pinentry-mode', 'loopback', '--passphrase', '',
'--quick-generate-key', 'Linux Manager test repository', 'default',
'default', 'never')),
('key export', ('gpg', '--batch', '--yes', '--export', '-o', '/root/linux-manager-test.gpg'))):
generate = ('gpg', '--batch', '--pinentry-mode', 'loopback', '--passphrase', '', '--quick-generate-key',
'Linux Manager test repository', 'default', 'default', 'never')
export = ('gpg', '--batch', '--yes', '--export', '-o', '/root/linux-manager-test.gpg')
for step, command in (('key generation', generate), ('key export', export)):
result = inside(*command)
if result.returncode != 0:
raise RuntimeError(f'the {step} failed in repo: {result.stderr.strip()}')
lxc('file', 'push', str(HERE / 'repo' / 'publish.sh'), f'{args.remote}:repo/usr/local/sbin/linux-manager-repo-publish',
'--mode', '0755', project=args.project)
lxc('file', 'push', str(TESTS / 'repo' / 'publish.sh'),
f'{args.remote}:repo/usr/local/sbin/linux-manager-repo-publish', '--mode', '0755', project=args.project)
result = inside('linux-manager-repo-publish')
if result.returncode != 0:
raise RuntimeError(f'the repository was not published: {result.stderr.strip()}')
@@ -164,12 +164,12 @@ def uplink(args):
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('action', choices=('create', 'remove', 'uplink'))
parser.add_argument('operation', nargs='?', choices=('setup', 'remove'), help='with uplink: setup or remove')
parser.add_argument('operation', nargs='?', choices=('setup', 'remove'), help='after uplink: setup or remove')
parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--pool', default=os.environ.get('LXD_POOL'),
help='the storage pool of the project, for create (LXD_POOL)')
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', 'lm-dev'),
help='the project (LXD_PROJECT, default lm-dev)')
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT),
help=f'the project (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'),
help='the image of the repository container (LXD_IMAGE, default ubuntu:26.04)')
parser.add_argument('--uplink', default=os.environ.get('LXD_UPLINK', 'uplink'),
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Register a TOTP token for a user of a Linux Manager VM on an LXD remote: lm-dev-otp-register.py.
The token is enrolled for --user (admin by default) of the VM --vm (lm-dev) in the project --project
(LXD_PROJECT, lm-dev by default) on the remote --remote (LXD_REMOTE), through lxc exec: inside the
VM, as root, linuxmanager_users makes a new secret, and stores it once a code computed here from it
verifies, replacing a token the user had. The secret, base32, is then written to the file
--secret-file or OTP_FILE names, readable by its owner only, so otp.py code prints the user's codes.
"""
import argparse
import json
import os
import pathlib
import sys
from lm_dev import PROJECT, lxc_exec
from otp import code_of
# Run in the VM as python3 -c CODE ARGUMENTS..., with the package's modules on the path.
NEW = ("import json, sys; sys.path.insert(0, '/usr/lib/linux-manager'); import linuxmanager_users as users\n"
"with users.session() as connection: print(json.dumps(users.otp_new(connection, sys.argv[1])))")
ENROL = ("import sys; sys.path.insert(0, '/usr/lib/linux-manager'); import linuxmanager_users as users\n"
"with users.session() as connection: users.otp_enrol(connection, sys.argv[1], sys.argv[2], sys.argv[3])")
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT),
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)')
parser.add_argument('--user', default='admin', help='the user to enrol (default admin)')
parser.add_argument('--secret-file', default=os.environ.get('OTP_FILE'),
help='the file the base32 secret is written to (OTP_FILE)')
args = parser.parse_args()
if not args.remote:
parser.error('--remote or LXD_REMOTE is required')
if not args.secret_file:
parser.error('--secret-file or OTP_FILE is required')
secret_file = pathlib.Path(args.secret_file)
def failure(result):
return (result.stderr.strip().splitlines() or ['lxc exec failed'])[-1]
created = lxc_exec(args.remote, args.project, args.vm, 'python3', '-c', NEW, args.user)
if created.returncode != 0:
sys.exit(f'no new secret for {args.user}: {failure(created)}')
secret = json.loads(created.stdout)['secret']
enrolled = lxc_exec(args.remote, args.project, args.vm, 'python3', '-c', ENROL, args.user, secret, code_of(secret))
if enrolled.returncode != 0:
sys.exit(f'{args.user} was not enrolled: {failure(enrolled)}')
secret_file.parent.mkdir(parents=True, exist_ok=True)
secret_file.touch(mode=0o600)
secret_file.chmod(0o600)
secret_file.write_text(f'{secret}\n', encoding='utf-8')
print(f'{args.user} of {args.remote}:{args.vm} has a new TOTP token; its secret is in {secret_file}')
if __name__ == '__main__':
main()
+19 -19
View File
@@ -1,10 +1,12 @@
#!/usr/bin/env python3
"""Run the Linux Manager test scenarios on an LXD remote: run.py core|nat|s2s... or run.py all.
"""Run the Linux Manager test scenarios on an LXD remote: lm-dev-run.py core|nat|s2s...|all.
The remote and its storage pool are required, as --remote and --pool or LXD_REMOTE and
LXD_POOL. The instances live in a project of their own, which must not exist and is removed
with its networks after each scenario unless --keep is given. The package is the newest
out/linux-manager_*_all.deb. Each check prints PASS, FAIL or SKIP; the run exits 1 when a
LXD_POOL. The instances live in a project of their own, --project (LXD_TEST_PROJECT, lm-test by
default), which must not exist and is removed with its networks after each scenario unless --keep
is given. The package is the newest out/linux-manager_*_all.deb. The administrator's name and
password are set as ADMIN_USERNAME and ADMIN_PASSWORD in the repository's .env, and the pre-shared
key is written to tmp/remote-test.env. Each check prints PASS, FAIL or SKIP; the run exits 1 when a
check failed.
"""
@@ -13,17 +15,16 @@ import importlib
import ipaddress
import json
import os
import pathlib
import re
import secrets
import subprocess
import sys
import time
HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent.parent
from lm_dev import ROOT, TESTS, lxc_exec, set_dotenv
TMP = ROOT / 'tmp' / 'remote-test'
SCENARIOS = sorted(path.stem for path in (HERE / 'scenarios').glob('*.py') if path.stem != '__init__')
SCENARIOS = sorted(path.stem for path in (TESTS / 'scenarios').glob('*.py') if path.stem != '__init__')
class Lab:
@@ -53,9 +54,7 @@ class Lab:
def on(self, name, *command, input=None):
"""Run the command in the instance with the input, and return its CompletedProcess."""
return subprocess.run(
['lxc', 'exec', f'{self.remote}:{name}', '--project', self.project, '-T', '--', *command],
input=input, capture_output=True, text=True)
return lxc_exec(self.remote, self.project, name, *command, input=input)
def push(self, source, name, path, mode='0644'):
"""Copy the local file into the instance; True when it was copied."""
@@ -143,7 +142,7 @@ class Lab:
limits = ['-c', 'limits.cpu=2', '-c', 'limits.memory=4GiB'] if kind == 'vm' else \
['-c', 'limits.cpu=1', '-c', 'limits.memory=1GiB']
self.lxc('init', self.image, f'{self.remote}:{name}', *(['--vm'] if kind == 'vm' else []), *limits,
'-c', 'cloud-init.user-data=' + (HERE / 'cloud-init' / user_data).read_text(encoding='utf-8'),
'-c', 'cloud-init.user-data=' + (TESTS / 'cloud-init' / user_data).read_text(encoding='utf-8'),
'-c', 'cloud-init.network-config=' + netcfg)
if kind != 'vm':
self.lxc('config', 'device', 'add', f'{self.remote}:{name}', 'tun', 'unix-char', 'path=/dev/net/tun')
@@ -227,7 +226,7 @@ class Lab:
@PSK@ is the pre-shared key, @ETH0@ and @ETH1@ the names of the server's NICs and @CIDR0@ the
network of its first address.
"""
text = (HERE / 'configs' / config).read_text(encoding='utf-8').replace('@PSK@', self.psk)
text = (TESTS / 'configs' / config).read_text(encoding='utf-8').replace('@PSK@', self.psk)
for index in (0, 1):
placeholder = f'@ETH{index}@'
if placeholder in text:
@@ -245,7 +244,7 @@ class Lab:
def echo_server(self, name):
"""Answer HTTP on port 8080 of the instance with the address of the client."""
return (self.push(HERE / 'echo.py', name, '/root/echo.py') and
return (self.push(TESTS / 'echo.py', name, '/root/echo.py') and
self.on(name, 'systemd-run', '--unit=lm-test-echo', 'python3', '/root/echo.py').returncode == 0)
def vpn_user(self, name):
@@ -265,7 +264,7 @@ class Lab:
public_key = self.on(client, 'wg', 'pubkey', input=private_key + '\n').stdout.strip()
if not private_key or not public_key:
return False
if not self.push(HERE / 'wireguard_peer.py', server, '/root/wireguard_peer.py'):
if not self.push(TESTS / 'wireguard_peer.py', server, '/root/wireguard_peer.py'):
return False
if self.on(server, 'python3', '/root/wireguard_peer.py', public_key, address).returncode != 0:
return False
@@ -304,8 +303,8 @@ def main():
parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--pool', default=os.environ.get('LXD_POOL'),
help='the storage pool of the project (LXD_POOL)')
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', 'lm-test'),
help='the project the instances live in (LXD_PROJECT, default lm-test)')
parser.add_argument('--project', default=os.environ.get('LXD_TEST_PROJECT', 'lm-test'),
help='the project the instances live in (LXD_TEST_PROJECT, default lm-test)')
parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'),
help='the image of every instance (LXD_IMAGE, default ubuntu:26.04)')
parser.add_argument('--keep', action='store_true', help='leave the project and the networks in place')
@@ -331,10 +330,11 @@ def main():
env = ROOT / 'tmp' / 'remote-test.env'
env.touch(mode=0o600)
env.chmod(0o600)
env.write_text(f'ADMIN_USERNAME=admin\nADMIN_PASSWORD={lab.admin_password}\nPSK={lab.psk}\n', encoding='utf-8')
env.write_text(f'PSK={lab.psk}\n', encoding='utf-8')
set_dotenv({'ADMIN_USERNAME': 'admin', 'ADMIN_PASSWORD': lab.admin_password})
print(f'package: {debs[-1].name}; remote: {args.remote}; project: {args.project}; image: {args.image}')
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(TESTS))
try:
for name in scenarios:
subprocess.run(['lxc', 'project', 'create', f'{args.remote}:{args.project}', '-s', args.pool,
+84 -85
View File
@@ -1,25 +1,27 @@
#!/usr/bin/env python3
"""Launch one Linux Manager server VM on an LXD remote to work with, or remove it: vm.py [--remove].
"""Launch one Linux Manager server VM on an LXD remote to work with, or remove it: lm-dev-vm.py create|remove.
The VM is launched on the remote (--remote or LXD_REMOTE) in --project with that project's
default profile. It gets the newest out/linux-manager_*_all.deb with the administrator admin and
a generated password; in a test project made by lxd-project.py, which tmp/lxd-project-PROJECT.json
describes, it gets the package instead from that project's repository, as its apt source, so later
dev builds reach it as updates. It also gets a configuration from configs/ (core.json by
default), whose @ETH0@ is the interface of the VM's default route, @CIDR0@ its network and @PSK@
a generated key. The password and the key are written to tmp/vm-NAME.env. The VM's leased
address is pinned on its NIC, and ports 7080 and 7081 of a listen address lead to the same ports
of the VM, and port 2222 to its SSH port. In a test project the listen address is a network
forward's on the project's WAN, allocated from its uplink's routes; elsewhere NAT proxy devices
listen on the host address --listen (or LXD_LISTEN, by default the IPv4 address of the host of the
remote's URL). --remove deletes the VM, its forward and that file.
create launches the VM --vm (lm-dev by default) on the remote --remote (LXD_REMOTE) in the project
--project (LXD_PROJECT, lm-dev by default) with that project's default profile. In a test project
made by lm-dev-lxd-project.py, which tmp/lxd-project-PROJECT.json describes, the VM gets the package
from that project's repository, as its apt source, so later dev builds reach it as updates;
elsewhere it gets the newest out/linux-manager_*_all.deb. The administrator is admin with a
generated password, set as ADMIN_USERNAME and ADMIN_PASSWORD in the repository's .env. The VM
gets a configuration from tests/remote/configs/ (--config, core.json by default), whose @ETH0@ is
the interface of its default route, @CIDR0@ its network and @PSK@ a generated key, written to
tmp/vm-VM.env.
The VM's leased address is pinned on its NIC, and ports 7080 and 7081 of a listen address lead to
the same ports of the VM, and port 2222 to its SSH port. In a test project the listen address is a
network forward's on the project's WAN, allocated from its uplink's routes; elsewhere NAT proxy
devices listen on the host address --listen (LXD_LISTEN, by default the IPv4 address of the host of
the remote's URL). remove deletes the VM, its forward and tmp/vm-VM.env; .env is left as it is.
"""
import argparse
import ipaddress
import json
import os
import pathlib
import re
import secrets
import socket
@@ -28,36 +30,26 @@ import sys
import time
import urllib.parse
HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent.parent
# The host port and the VM port of each proxy: the Manager, the status web service and SSH.
PROXIES = ((7080, 7080), (7081, 7081), (2222, 22))
from lm_dev import PROJECT, ROOT, TESTS, lxc_exec, set_dotenv
def inside(args, *command, input=None):
"""Run the command in the VM with the input, and return its CompletedProcess."""
return subprocess.run(['lxc', 'exec', f'{args.remote}:{args.name}', '--project', args.project, '-T', '--',
*command], input=input, capture_output=True, text=True)
def push(args, source, path, mode):
"""Copy the local file into the VM at the path with the mode; True when it was copied."""
return subprocess.run(['lxc', 'file', 'push', str(source), f'{args.remote}:{args.name}{path}',
'--project', args.project, '--mode', mode], capture_output=True).returncode == 0
# The listen port and the VM port of each forward or proxy: the Manager, the status web service and SSH.
PORTS = ((7080, 7080), (7081, 7081), (2222, 22))
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('action', choices=('create', 'remove'))
parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--project', default='default', help='the project of the VM (default default)')
parser.add_argument('--name', default='lm-dev', help='the name of the VM (default lm-dev)')
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT),
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)')
parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'),
help='the image of the VM (LXD_IMAGE, default ubuntu:26.04)')
parser.add_argument('--config', default='core.json', help='the configuration from configs/ (default core.json)')
parser.add_argument('--config', default='core.json',
help='the configuration from tests/remote/configs/ (default core.json)')
parser.add_argument('--listen', default=os.environ.get('LXD_LISTEN'),
help='outside a test project, the LXD host address the proxies listen on (LXD_LISTEN, '
'default the IPv4 address of the remote URL\'s host)')
parser.add_argument('--remove', action='store_true', help='delete the VM and its env file')
help="outside a test project, the LXD host address the proxies listen on (LXD_LISTEN, "
"default the IPv4 address of the remote URL's host)")
args = parser.parse_args()
if not args.remote:
parser.error('--remote or LXD_REMOTE is required')
@@ -65,7 +57,7 @@ def main():
project = json.loads(project_file.read_text(encoding='utf-8')) if project_file.is_file() else None
if project and project['remote'] != args.remote:
sys.exit(f'{project_file} is of remote {project["remote"]}, not {args.remote}')
if not project and not args.remove and not args.listen:
if not project and args.action == 'create' and not args.listen:
# The default listen address is the IPv4 address of the remote's host in its lxc URL.
remotes = json.loads(subprocess.run(['lxc', 'remote', 'list', '--format', 'json'], capture_output=True,
text=True, check=True).stdout)
@@ -76,10 +68,17 @@ def main():
pass
if not args.listen:
parser.error(f'no IPv4 address of the host of remote {args.remote}; give --listen or LXD_LISTEN')
where = f'{args.remote}:{args.name} (project {args.project})'
exists = subprocess.run(['lxc', 'info', f'{args.remote}:{args.name}', '--project', args.project],
where = f'{args.remote}:{args.vm} (project {args.project})'
exists = subprocess.run(['lxc', 'info', f'{args.remote}:{args.vm}', '--project', args.project],
capture_output=True).returncode == 0
env = ROOT / 'tmp' / f'vm-{args.name}.env'
env = ROOT / 'tmp' / f'vm-{args.vm}.env'
def inside(*command, input=None):
return lxc_exec(args.remote, args.project, args.vm, *command, input=input)
def push(source, path, mode):
return subprocess.run(['lxc', 'file', 'push', str(source), f'{args.remote}:{args.vm}{path}',
'--project', args.project, '--mode', mode], capture_output=True).returncode == 0
# In a test project the VM is reached through a network forward on the project's WAN, tagged with user.vm.
wan = f'{args.remote}:{project["networks"][0]}' if project else None
@@ -88,24 +87,23 @@ def main():
listing = subprocess.run(['lxc', 'network', 'forward', 'list', wan, '-f', 'json', '--project', args.project],
capture_output=True, text=True, check=True).stdout
return next((forward['listen_address'] for forward in json.loads(listing) or []
if forward.get('config', {}).get('user.vm') == args.name), None)
if forward.get('config', {}).get('user.vm') == args.vm), None)
if args.remove:
if args.action == 'remove':
if not exists:
sys.exit(f'no VM {where}')
if project and (listen := forward_of_vm()):
subprocess.run(['lxc', 'network', 'forward', 'delete', wan, listen, '--project', args.project], check=True)
subprocess.run(['lxc', 'delete', '--force', f'{args.remote}:{args.name}', '--project', args.project],
check=True)
subprocess.run(['lxc', 'delete', '--force', f'{args.remote}:{args.vm}', '--project', args.project], check=True)
env.unlink(missing_ok=True)
print(f'removed {where}')
return
if exists:
sys.exit(f'{where} exists; remove it with --remove or choose another --name')
config = HERE / 'configs' / args.config
sys.exit(f'{where} exists; remove it with remove or choose another --vm')
config = TESTS / 'configs' / args.config
if not config.is_file():
parser.error(f'no configs/{args.config}')
parser.error(f'no tests/remote/configs/{args.config}')
debs = sorted((ROOT / 'out').glob('linux-manager_*_all.deb'))
if not project and not debs:
sys.exit('no out/linux-manager_*_all.deb; run ./build.sh first')
@@ -115,81 +113,82 @@ def main():
env.parent.mkdir(parents=True, exist_ok=True)
env.touch(mode=0o600)
env.chmod(0o600)
env.write_text(f'ADMIN_USERNAME=admin\nADMIN_PASSWORD={password}\nPSK={psk}\n', encoding='utf-8')
env.write_text(f'PSK={psk}\n', encoding='utf-8')
set_dotenv({'ADMIN_USERNAME': 'admin', 'ADMIN_PASSWORD': password})
reached = f'a forward on {project["networks"][0]}' if project else f'proxies on {args.listen}'
print(f'launching {where} from {args.image} with {source}; reached through {reached}')
subprocess.run(['lxc', 'launch', args.image, f'{args.remote}:{args.name}', '--vm', '-c', 'limits.cpu=2',
subprocess.run(['lxc', 'launch', args.image, f'{args.remote}:{args.vm}', '--vm', '-c', 'limits.cpu=2',
'-c', 'limits.memory=4GiB',
'-c', 'cloud-init.user-data=' + (HERE / 'cloud-init' / 'server.yaml').read_text(encoding='utf-8'),
'-c', 'cloud-init.user-data=' + (TESTS / 'cloud-init' / 'server.yaml').read_text(encoding='utf-8'),
'--project', args.project], check=True)
# Wait for the agent and cloud-init (status 2 is done with recoverable errors), then for the default route.
for _ in range(120):
if inside(args, 'cloud-init', 'status', '--wait').returncode in (0, 2):
if inside('cloud-init', 'status', '--wait').returncode in (0, 2):
break
time.sleep(5)
else:
sys.exit(f'{args.name} did not boot; remove it with --remove')
sys.exit(f'{args.vm} did not boot; remove it with remove')
for _ in range(24):
route = re.search(r'\bdev (\S+)', inside(args, 'ip', '-4', '-o', 'route', 'show', 'default').stdout)
route = re.search(r'\bdev (\S+)', inside('ip', '-4', '-o', 'route', 'show', 'default').stdout)
address = route and re.search(r' inet (\S+) ',
inside(args, 'ip', '-4', '-o', 'addr', 'show', 'dev', route.group(1)).stdout)
inside('ip', '-4', '-o', 'addr', 'show', 'dev', route.group(1)).stdout)
if address:
break
time.sleep(5)
else:
sys.exit(f'{args.name} has no default route or address; remove it with --remove')
sys.exit(f'{args.vm} has no default route or address; remove it with remove')
nic, interface = route.group(1), ipaddress.IPv4Interface(address.group(1))
# Pin the leased address on the profile's NIC, then forward or proxy the ports to the VM.
mac = inside(args, 'cat', f'/sys/class/net/{nic}/address').stdout.strip()
expanded = subprocess.run(['lxc', 'config', 'show', '--expanded', f'{args.remote}:{args.name}',
mac = inside('cat', f'/sys/class/net/{nic}/address').stdout.strip()
expanded = subprocess.run(['lxc', 'config', 'show', '--expanded', f'{args.remote}:{args.vm}',
'--project', args.project], capture_output=True, text=True, check=True).stdout
device = next((m.group(1) for m in re.finditer(r'^\s*volatile\.(\S+)\.hwaddr: "?([0-9a-f:]+)"?$', expanded, re.M)
if m.group(2) == mac), None)
if not device:
sys.exit(f'no LXD device of {args.name} has the MAC address {mac} of {nic}')
subprocess.run(['lxc', 'config', 'device', 'override', f'{args.remote}:{args.name}', device,
sys.exit(f'no LXD device of {args.vm} has the MAC address {mac} of {nic}')
subprocess.run(['lxc', 'config', 'device', 'override', f'{args.remote}:{args.vm}', device,
f'ipv4.address={interface.ip}', '--project', args.project], check=True)
if project:
# An OVN network refuses NAT proxies; the forward's listen address is allocated from the uplink's routes.
subprocess.run(['lxc', 'network', 'forward', 'create', wan, '--allocate=ipv4', f'user.vm={args.name}',
subprocess.run(['lxc', 'network', 'forward', 'create', wan, '--allocate=ipv4', f'user.vm={args.vm}',
'--project', args.project], check=True)
args.listen = forward_of_vm()
if not args.listen:
sys.exit(f'no forward of {args.name} on {wan}; remove the VM with --remove')
for host_port, vm_port in PROXIES:
subprocess.run(['lxc', 'network', 'forward', 'port', 'add', wan, args.listen, 'tcp', str(host_port),
sys.exit(f'no forward of {args.vm} on {wan}; remove the VM with remove')
for listen_port, vm_port in PORTS:
subprocess.run(['lxc', 'network', 'forward', 'port', 'add', wan, args.listen, 'tcp', str(listen_port),
str(interface.ip), str(vm_port), '--project', args.project], check=True)
else:
for host_port, vm_port in PROXIES:
subprocess.run(['lxc', 'config', 'device', 'add', f'{args.remote}:{args.name}', f'proxy-{vm_port}',
'proxy', f'listen=tcp:{args.listen}:{host_port}', f'connect=tcp:{interface.ip}:{vm_port}',
for listen_port, vm_port in PORTS:
subprocess.run(['lxc', 'config', 'device', 'add', f'{args.remote}:{args.vm}', f'proxy-{vm_port}', 'proxy',
f'listen=tcp:{args.listen}:{listen_port}', f'connect=tcp:{interface.ip}:{vm_port}',
'nat=true', '--project', args.project], check=True)
# Install the package with the test administrator, from the test project's repository when there is one.
if project:
sources = (f'Types: deb\nURIs: {project["repository"]}\nSuites: resolute\nComponents: main\n'
f'Signed-By: /etc/apt/keyrings/linux-manager-test.gpg\n')
if (inside(args, 'mkdir', '-p', '/etc/apt/keyrings').returncode != 0 or
not push(args, project['key'], '/etc/apt/keyrings/linux-manager-test.gpg', '0644') or
inside(args, 'tee', '/etc/apt/sources.list.d/linux-manager-test.sources', input=sources).returncode != 0):
sys.exit(f'could not add the repository of project {args.project} to {args.name}')
updated = inside(args, 'apt-get', 'update')
if (inside('mkdir', '-p', '/etc/apt/keyrings').returncode != 0 or
not push(project['key'], '/etc/apt/keyrings/linux-manager-test.gpg', '0644') or
inside('tee', '/etc/apt/sources.list.d/linux-manager-test.sources', input=sources).returncode != 0):
sys.exit(f'could not add the repository of project {args.project} to {args.vm}')
updated = inside('apt-get', 'update')
if updated.returncode != 0:
sys.exit(f'apt-get update failed in {args.name}: {updated.stderr.strip()}')
sys.exit(f'apt-get update failed in {args.vm}: {updated.stderr.strip()}')
package = 'linux-manager'
else:
if not push(args, debs[-1], '/tmp/linux-manager.deb', '0644'):
sys.exit(f'could not copy {debs[-1].name} into {args.name}')
if not push(debs[-1], '/tmp/linux-manager.deb', '0644'):
sys.exit(f'could not copy {debs[-1].name} into {args.vm}')
package = '/tmp/linux-manager.deb'
preseed = (f'linux-manager linux-manager/admin_username string admin\n'
f'linux-manager linux-manager/admin_password password {password}\n')
if inside(args, 'debconf-set-selections', input=preseed).returncode != 0:
sys.exit('debconf-set-selections failed')
result = inside(args, 'env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y', package)
log = ROOT / 'tmp' / f'vm-{args.name}-install.log'
if inside('debconf-set-selections', input=preseed).returncode != 0:
sys.exit(f'debconf-set-selections failed in {args.vm}')
result = inside('env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y', package)
log = ROOT / 'tmp' / f'vm-{args.vm}-install.log'
log.write_text(result.stdout + result.stderr, encoding='utf-8')
if result.returncode != 0:
sys.exit(f'the package did not install; see {log}')
@@ -197,23 +196,23 @@ def main():
# Apply the configuration twice, as the server's certificates follow the first run.
text = (config.read_text(encoding='utf-8').replace('@ETH0@', nic).replace('@CIDR0@', str(interface.network))
.replace('@PSK@', psk))
rendered = ROOT / 'tmp' / f'vm-{args.name}.json'
rendered = ROOT / 'tmp' / f'vm-{args.vm}.json'
rendered.touch(mode=0o600)
rendered.chmod(0o600)
rendered.write_text(text, encoding='utf-8')
pushed = push(args, rendered, '/etc/linux-manager/linux-manager.json', '0600')
pushed = push(rendered, '/etc/linux-manager/linux-manager.json', '0600')
rendered.unlink()
if not pushed:
sys.exit(f'could not copy {args.config} into {args.name}')
sys.exit(f'could not copy {args.config} into {args.vm}')
for _ in range(2):
if inside(args, 'systemctl', 'restart', 'linux-manager-setup').returncode != 0:
if inside('systemctl', 'restart', 'linux-manager-setup').returncode != 0:
sys.exit(f'linux-manager-setup failed with {args.config}; see journalctl -u linux-manager-setup in the VM')
print(f'{args.name} is up at {interface.ip} with {args.config}')
print(f'administrator: admin password: {password} (also in {env})')
print(f'{args.vm} is up at {interface.ip} with {args.config}')
print(f'administrator: admin password: {password} (also in {ROOT / ".env"})')
print(f'manager: http://{args.listen}:7080/ status: http://{args.listen}:7081/ ssh: {args.listen} port 2222')
print(f'shell: lxc exec {args.remote}:{args.name} --project {args.project} -- su -l')
print(f'remove: {sys.argv[0]} --remote {args.remote} --project {args.project} --name {args.name} --remove')
print(f'shell: lxc exec {args.remote}:{args.vm} --project {args.project} -- su -l')
print(f'remove: {sys.argv[0]} remove --remote {args.remote} --project {args.project} --vm {args.vm}')
if __name__ == '__main__':
+27
View File
@@ -0,0 +1,27 @@
"""What the lm-dev scripts share: the repository's paths, lxc exec in an instance, and the .env of the repository."""
import pathlib
import subprocess
ROOT = pathlib.Path(__file__).resolve().parent.parent
# The test data: scenarios, configurations, cloud-init files, the repository's script and the files copied in.
TESTS = ROOT / 'tests' / 'remote'
# The project of the manual tests, which lm-dev-lxd-project.py makes.
PROJECT = 'lm-dev'
def lxc_exec(remote, project, instance, *command, input=None):
"""Run the command in the instance as root with the input, and return its CompletedProcess."""
return subprocess.run(['lxc', 'exec', f'{remote}:{instance}', '--project', project, '-T', '--', *command],
input=input, capture_output=True, text=True)
def set_dotenv(values):
"""Set the variables in the repository's .env, readable by its owner only, keeping its other lines."""
dotenv = ROOT / '.env'
lines = dotenv.read_text(encoding='utf-8').splitlines() if dotenv.is_file() else []
kept = [line for line in lines if line.split('=', 1)[0] not in values]
dotenv.touch(mode=0o600)
dotenv.chmod(0o600)
dotenv.write_text(''.join(f'{line}\n' for line in kept + [f'{key}={value}' for key, value in values.items()]),
encoding='utf-8')
Executable
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""An authenticator app on the command line: make a TOTP secret or print its current code: otp.py new|code.
The secret, base32, is kept in the file --secret-file or OTP_FILE names, readable by its owner
only. new makes a new secret of 20 random bytes in that file, refusing to replace one without
--force, and prints its otpauth URI, labelled with --account and --issuer when given. code prints
the code of the secret now, or at the Unix time --at. The codes are RFC 6238's, with --algorithm
(sha1 by default), --digits (6) and --period (30 seconds).
"""
import argparse
import base64
import hashlib
import hmac
import os
import pathlib
import secrets
import struct
import sys
import time
import urllib.parse
ALGORITHMS = ('sha1', 'sha256', 'sha512')
def code_of(secret, now=None, digits=6, period=30, algorithm='sha1'):
"""The TOTP code of the base32 secret at the Unix time now, the current time by default."""
counter = int((time.time() if now is None else now) // period)
key = base64.b32decode(secret.upper() + '=' * (-len(secret) % 8))
digest = hmac.new(key, struct.pack('>Q', counter), getattr(hashlib, algorithm)).digest()
offset = digest[-1] & 0x0F
value = struct.unpack('>I', digest[offset:offset + 4])[0] & 0x7FFFFFFF
return f'{value % 10 ** digits:0{digits}d}'
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('action', choices=('new', 'code'))
parser.add_argument('--secret-file', default=os.environ.get('OTP_FILE'),
help='the file of the base32 secret (OTP_FILE)')
parser.add_argument('--algorithm', choices=ALGORITHMS, default='sha1', help='the HMAC hash (default sha1)')
parser.add_argument('--digits', type=int, default=6, help='the digits of a code (default 6)')
parser.add_argument('--period', type=int, default=30, help='the seconds a code is valid (default 30)')
parser.add_argument('--at', type=float, help='code: the Unix time of the code instead of now')
parser.add_argument('--account', help='new: the account name in the otpauth URI')
parser.add_argument('--issuer', help='new: the issuer in the otpauth URI')
parser.add_argument('--force', action='store_true', help='new: replace an existing secret')
args = parser.parse_args()
if not args.secret_file:
parser.error('--secret-file or OTP_FILE is required')
if not 6 <= args.digits <= 10 or args.period < 1:
parser.error('--digits must be 6 to 10 and --period at least 1')
secret_file = pathlib.Path(args.secret_file)
if args.action == 'code':
if not secret_file.is_file():
sys.exit(f'no {secret_file}; make a secret with new')
print(code_of(secret_file.read_text(encoding='utf-8').strip(), args.at, args.digits, args.period, args.algorithm))
return
if secret_file.exists() and not args.force:
sys.exit(f'{secret_file} exists; give --force to replace its secret')
secret = base64.b32encode(secrets.token_bytes(20)).decode()
secret_file.parent.mkdir(parents=True, exist_ok=True)
secret_file.touch(mode=0o600)
secret_file.chmod(0o600)
secret_file.write_text(f'{secret}\n', encoding='utf-8')
label = urllib.parse.quote(':'.join(part for part in (args.issuer, args.account) if part) or 'otp')
query = {'secret': secret, 'algorithm': args.algorithm.upper(), 'digits': args.digits, 'period': args.period}
if args.issuer:
query['issuer'] = args.issuer
print(f'otpauth://totp/{label}?{urllib.parse.urlencode(query)}')
if __name__ == '__main__':
main()
+46
View File
@@ -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
+10 -1
View File
@@ -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
+12 -1
View File
@@ -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.
+1
View File
@@ -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 \
+36 -2
View File
@@ -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'),
},
+35 -43
View File
@@ -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,
+12 -8
View File
@@ -1,19 +1,24 @@
# Certificates
The server's two-level CA: a root CA and issuing CAs that sign the certificates.
The server's CA: a root CA and issuing CAs that sign the certificates. The root is created by the
server, an offline CA, or the root of a Simple CA service whose issuing CA signs the server's
issuing CAs; that is chosen at setup and fixed once the root exists.
## Above the tabs
- **Issue:** a certificate from a CSR, saved with its chain, or with a key the server makes, saved
as a PFX file protected by a password; the server keeps no copy of the key.
- **Settings:** the names, lifetimes, key type, CRL validity and publishing endpoints.
- **Settings:** the names, lifetimes, key type, CRL validity, publishing endpoints and, with a
Simple CA root, the URL of the service.
- **Warnings:** what needs attention, such as a CRL about to expire.
## Tabs
- **Root:** the root CA's subject and expiry, whether its key is on the server (marked with a
warning sign) or offline, and its CRL. **Download root CA** gives its certificate; **Upload CRL**
takes a root CRL signed offline. Below, the certificates of the issuing CAs.
- **Root:** the root CA's source, state, subject, expiry and CRL, and with Simple CA its issuing
CA that signs the server's and the expiry of the token. **Download root CA** gives its
certificate. An offline root takes its certificate with **Import root certificate**, before the
issuing CAs, and a CRL signed offline with **Upload CRL**; a Simple CA root takes the setup code
of a new token with **Enter setup code**. Below, the certificates of the issuing CAs.
- **Templates:** key, lifetime, subject, usages, alternative names, certificate policies and the
CAs that issue each template. **Add template**, **Edit**, **Remove** for the server's own and
**Reset** for a changed built-in one.
@@ -21,10 +26,9 @@ The server's two-level CA: a root CA and issuing CAs that sign the certificates.
with a name and an OID.
- **P2S Issuing CA** and **S2S Issuing CA:** the CAs of the VPN users and of site-to-site
connections. An active CA gives its CA bundle; a pending CA, waiting for the offline root, gives
its CSR and takes the certificate the root signed.
its CSR and takes the certificate the root signed, and one waiting for Simple CA is signed once
the server reaches it.
- **Issuing CAs:** general-purpose CAs, each with its templates and an optional ACME server.
**Add issuing CA**, **Edit** and **Remove**; a removed CA is retired and its certificate revoked.
- **Certificates:** each with its kind, template, names, expiry and state; one of another system
or of the server is revoked after a confirmation with a reason.
The root key is exported, removed and imported on the server with `linux-manager-ca`, never here.
+2 -1
View File
@@ -18,7 +18,8 @@ whose DNS is Router managed get their records in the domain they are in.
take; empty when the server has none or no site uses it.
- **Listen:** the interfaces port 53 is open on. While IKEv2 or OpenVPN remote access is enabled,
it must not share an interface with the clients' resolver, by default on the internal one.
- **TTL:** how long resolvers keep the answers of a domain without its own TTL.
- **TTL:** the default TTL of the records, how long resolvers keep their answers; used where
neither the record nor its domain has a TTL of its own.
**Settings** edits them.
+3 -3
View File
@@ -1,8 +1,8 @@
# Docker
Whether Docker is installed on the server, the state of `docker.service` and of the server's
Docker rules, the ports exposed on the external interface, and the rules of the
`LINUX-MANAGER-DOCKER` chain.
The state of `docker.service` and of the server's Docker rules, the ports exposed on the external
interface, and the rules of the `LINUX-MANAGER-DOCKER` chain. The page menu offers this page only
while Docker is installed on the server.
Exposed ports are set on the server as root, for example:
+8 -3
View File
@@ -6,7 +6,8 @@ pages; any other user sees only their own account.
The router and the VPN are components switched on in the server's configuration (`router.enabled`
and `vpn.enabled`). While the VPN is off the page menu has no Remote Access page; while the router
is off the Connectivity page shows only its Network tab.
is off the Connectivity page shows only its Network tab. Without Docker on the server the page menu
has no Docker page.
The help opens at the topic of the page you are on. Links between topics open in this panel;
Back returns to the previous topic and the house icon to this one.
@@ -30,11 +31,15 @@ Back returns to the previous topic and the house icon to this one.
- **Help** (question mark, left of the page menu): opens and closes this panel; the page moves left
while it is open.
- **Shell** (terminal icon, administrators): a shell on the server; pressed on the Shell page, it
returns to the page it was opened from.
returns to the page it was opened from. With **Open the shell in a new tab** in the settings,
it opens the shell in a tab of its own.
- **Your name**: opens your account; pressed there, it returns to the page it was opened from.
- **Sign out**, **Settings** (gear, but not on the account page) and **Theme** (light, dark or the system's).
## Settings
The gear, hidden on the sign-in and the account page, sets how often the Overview and the Metrics tab read the server on their own: manually, or
every 5, 10 or 30 seconds, 1, 5 or 15 minutes. The browser keeps the choice; Defaults sets it back.
every 5, 10 or 30 seconds, 1, 5 or 15 minutes. **Open the shell in a new tab** makes the shell
button open the shell in a tab of its own, so it stays open while other pages are opened in the
first tab; a shell ends when its page is left. The browser keeps the choices; Defaults sets them
back.
+3 -1
View File
@@ -8,7 +8,9 @@ a local account root chose.
unlocked with your device's PIN or biometrics; it shows when you have a passkey (see
[Account](account.md)).
- **Closing:** the server ends the shell after `web.shell_idle_minutes` without a keystroke; the
page shows the reason and keeps the terminal readable.
page shows the reason and keeps the terminal readable. Leaving the page ends the shell too;
with **Open the shell in a new tab** in the [settings](index.md#settings), the shell button opens
it in a tab of its own, which other pages leave alone.
## Editor
+4 -3
View File
@@ -3,7 +3,7 @@ data "http" "repo_gpg_key" {
}
locals {
supply_pki = var.root_cert_file != ""
supply_pki = var.simple_ca_url != ""
cloud_init_vars = {
hostname = var.name
@@ -11,6 +11,7 @@ locals {
repo_url = var.repo_url
repo_gpg_key = data.http.repo_gpg_key.response_body
ubuntu_codename = var.ubuntu_codename
trusted_cas = [for path in var.trusted_ca_files : file(path)]
# Contents of /etc/linux-manager/linux-manager.json.
config = {
@@ -104,8 +105,8 @@ resource "azurerm_linux_virtual_machine" "router" {
custom_data = base64encode(
local.supply_pki
? templatefile("${path.module}/../cloud-init-with-pki.yaml.tpl", merge(local.cloud_init_vars, {
root_cert = file(var.root_cert_file)
root_key = var.root_key_file != "" ? file(var.root_key_file) : ""
config = merge(local.cloud_init_vars.config, { pki = { root = "simple-ca", simple_ca_url = var.simple_ca_url } })
setup_code = var.simple_ca_setup_code
}))
: templatefile("${path.module}/../cloud-init.yaml.tpl", local.cloud_init_vars)
)
+15 -9
View File
@@ -32,7 +32,7 @@ variable "admin_username" {
}
variable "admin_password" {
description = "Admin password for the server VM. SSH key auth is always configured; leaving this empty additionally disables password authentication, setting it enables password auth alongside the key."
description = "Admin password for the server VM, accepted alongside the SSH key; empty disables password authentication."
type = string
default = ""
sensitive = true
@@ -50,7 +50,7 @@ variable "local_fqdn" {
}
variable "dns_zone_id" {
description = "Resource ID of an existing Azure DNS zone to create local_fqdn's A record in, pointing at the server's public IP. local_fqdn must be a name within that zone. Leave null to skip - local_fqdn is then just a label with nothing making it resolve."
description = "Resource ID of an existing Azure DNS zone, holding local_fqdn, to create local_fqdn's A record in, pointing at the server's public IP; null for no record."
type = string
nullable = true
default = null
@@ -63,7 +63,7 @@ variable "local_id_mode" {
}
variable "local_cidrs" {
description = "Local subnet CIDR(s) advertised into the site-to-site tunnel. Should include the workload subnet CIDR."
description = "Local subnet CIDR(s) advertised into the site-to-site tunnel, the workload subnet CIDR among them."
type = string
}
@@ -100,14 +100,20 @@ variable "p2s_address_pool" {
default = ""
}
variable "root_cert_file" {
description = "Path to an existing root CA certificate PEM to supply instead of letting the package create one. Leave empty to create one."
variable "simple_ca_url" {
description = "The https:// URL of the Simple CA service that signs the router's issuing CAs; empty for a root the package creates."
type = string
default = ""
}
variable "root_key_file" {
description = "Path to the private key PEM of root_cert_file. Leave empty to keep the root offline: the issuing CAs then wait for certificates signed elsewhere."
variable "trusted_ca_files" {
description = "Paths to PEM certificates of CAs added to the server's system trust store."
type = list(string)
default = []
}
variable "simple_ca_setup_code" {
description = "The one-time setup code of a sign-ca token of the Simple CA issuing CA, valid until the router's first boot."
type = string
default = ""
sensitive = true
@@ -132,7 +138,7 @@ variable "wireguard_listen_port" {
}
variable "deploy_workload_vm" {
description = "Deploy a bare VM on the workload subnet, for manually verifying routing through the server."
description = "Deploy a bare VM on the workload subnet."
type = bool
default = false
}
@@ -144,7 +150,7 @@ variable "repo_url" {
}
variable "ubuntu_codename" {
description = "Ubuntu release codename of the server VM's image, used to select the apt repo component."
description = "Ubuntu release codename of the server VM's image, the apt repository's distribution."
type = string
default = "resolute"
}
+17 -22
View File
@@ -1,13 +1,11 @@
#cloud-config
#
# Example: install and configure linux-manager during first boot, supplying an
# existing root CA instead of letting the package create one. See
# cloud-init.yaml.tpl for the variant that creates its own.
#
# Template variables are Terraform templatefile() placeholders. Adapt or drop
# them for whatever renders this file. With root_key empty the root stays
# offline: the server's issuing CAs wait for their certificates, signed with
# the root elsewhere and imported with linux-manager-ca ca import.
# Example: install and configure linux-manager during first boot, with its
# issuing CAs signed by a Simple CA service. The template variables are
# Terraform templatefile() placeholders: config holds pki.root simple-ca and
# pki.simple_ca_url, setup_code is the one-time setup code of a sign-ca token,
# and trusted_cas the PEM certificates of CAs added to the trust store, among
# them the CA of the service's HTTPS certificate.
hostname: ${hostname}
fqdn: ${fqdn}
@@ -21,31 +19,28 @@ apt:
${indent(8, trimspace(repo_gpg_key))}
write_files:
# The configuration file. Created here before the package is installed, so
# postinst leaves it alone.
- path: /etc/linux-manager/linux-manager.json
permissions: '0600'
owner: root:root
content: |
${jsonencode(config)}
- path: /etc/linux-manager/pki/root/cert.pem
permissions: '0644'
owner: root:root
content: |
${indent(6, trimspace(root_cert))}
%{ if root_key != "" ~}
- path: /etc/linux-manager/pki/root/key.pem
- path: /etc/linux-manager/pki-setup-code
permissions: '0600'
owner: root:root
content: |
${indent(6, trimspace(root_key))}
%{ endif ~}
${setup_code}
%{ if length(trusted_cas) > 0 ~}
ca_certs:
trusted:
%{ for ca in trusted_cas ~}
- |
${indent(6, trimspace(ca))}
%{ endfor ~}
%{ endif ~}
package_update: true
packages:
- linux-manager
# Nothing further is required: installing the package starts
# linux-manager-setup, which applies the configuration written above.
+13 -18
View File
@@ -1,18 +1,9 @@
#cloud-config
#
# Example: install and configure linux-manager during first boot.
#
# This is one way to reach the state described in README.md, not an interface
# the package depends on. It writes the configuration file directly, which
# keeps everything in one place and works the same whether or not debconf is
# involved.
#
# Template variables are Terraform templatefile() placeholders. Adapt or drop
# them for whatever renders this file.
#
# This variant lets the package create its own CAs on first boot. See
# cloud-init-with-pki.yaml.tpl for the variant that supplies an existing root
# CA instead.
# Example: install and configure linux-manager during first boot, with a root
# CA the package creates. The template variables are Terraform templatefile()
# placeholders; trusted_cas holds the PEM certificates of CAs added to the
# trust store.
hostname: ${hostname}
fqdn: ${fqdn}
@@ -26,18 +17,22 @@ apt:
${indent(8, trimspace(repo_gpg_key))}
write_files:
# The configuration file. Created here before the package is installed, so
# postinst leaves it alone.
- path: /etc/linux-manager/linux-manager.json
permissions: '0600'
owner: root:root
content: |
${jsonencode(config)}
%{ if length(trusted_cas) > 0 ~}
ca_certs:
trusted:
%{ for ca in trusted_cas ~}
- |
${indent(6, trimspace(ca))}
%{ endfor ~}
%{ endif ~}
package_update: true
packages:
- linux-manager
# Nothing further is required: installing the package starts
# linux-manager-setup, which applies the configuration written above.
+4 -3
View File
@@ -3,7 +3,7 @@ data "http" "repo_gpg_key" {
}
locals {
supply_pki = var.root_cert_file != ""
supply_pki = var.simple_ca_url != ""
cloud_init_vars = {
hostname = var.name
@@ -11,6 +11,7 @@ locals {
repo_url = var.repo_url
repo_gpg_key = data.http.repo_gpg_key.response_body
ubuntu_codename = var.ubuntu_codename
trusted_cas = [for path in var.trusted_ca_files : file(path)]
# Contents of /etc/linux-manager/linux-manager.json.
config = {
@@ -35,8 +36,8 @@ locals {
}
cloud_init_rendered = local.supply_pki ? templatefile("${path.module}/../cloud-init-with-pki.yaml.tpl", merge(local.cloud_init_vars, {
root_cert = file(var.root_cert_file)
root_key = var.root_key_file != "" ? file(var.root_key_file) : ""
config = merge(local.cloud_init_vars.config, { pki = { root = "simple-ca", simple_ca_url = var.simple_ca_url } })
setup_code = var.simple_ca_setup_code
})) : templatefile("${path.module}/../cloud-init.yaml.tpl", local.cloud_init_vars)
}
+14 -8
View File
@@ -42,7 +42,7 @@ variable "local_fqdn" {
}
variable "dns_managed_zone" {
description = "Name of an existing Cloud DNS managed zone to create local_fqdn's A record in, pointing at the server's public IP. local_fqdn must be a name within that zone's DNS name. Leave empty to skip - local_fqdn is then just a label with nothing making it resolve."
description = "Name of an existing Cloud DNS managed zone, holding local_fqdn, to create local_fqdn's A record in, pointing at the server's public IP; empty for no record."
type = string
default = ""
}
@@ -60,7 +60,7 @@ variable "local_id_mode" {
}
variable "local_cidrs" {
description = "Local subnet CIDR(s) advertised into the site-to-site tunnel. Should include the workload subnet CIDR."
description = "Local subnet CIDR(s) advertised into the site-to-site tunnel, the workload subnet CIDR among them."
type = string
}
@@ -97,14 +97,20 @@ variable "p2s_address_pool" {
default = ""
}
variable "root_cert_file" {
description = "Path to an existing root CA certificate PEM to supply instead of letting the package create one. Leave empty to create one."
variable "simple_ca_url" {
description = "The https:// URL of the Simple CA service that signs the router's issuing CAs; empty for a root the package creates."
type = string
default = ""
}
variable "root_key_file" {
description = "Path to the private key PEM of root_cert_file. Leave empty to keep the root offline: the issuing CAs then wait for certificates signed elsewhere."
variable "trusted_ca_files" {
description = "Paths to PEM certificates of CAs added to the server's system trust store."
type = list(string)
default = []
}
variable "simple_ca_setup_code" {
description = "The one-time setup code of a sign-ca token of the Simple CA issuing CA, valid until the router's first boot."
type = string
default = ""
sensitive = true
@@ -129,7 +135,7 @@ variable "wireguard_listen_port" {
}
variable "deploy_workload_vm" {
description = "Deploy a bare VM on the workload subnet, for manually verifying routing through the server."
description = "Deploy a bare VM on the workload subnet."
type = bool
default = false
}
@@ -141,7 +147,7 @@ variable "repo_url" {
}
variable "ubuntu_codename" {
description = "Ubuntu release codename of the server VM's image, used to select the apt repo component."
description = "Ubuntu release codename of the server VM's image, the apt repository's distribution."
type = string
default = "resolute"
}
+8 -1
View File
@@ -3,7 +3,9 @@
The tag is the version of the first entry of debian-package/debian/changelog, without the
Debian revision 1: linux-manager (0.5.1-1) is tagged 0.5.1 and (0.5.1-2) 0.5.1-2. The tag
starts the release workflow.
starts the release workflow. Once the release succeeds, .dev-build.serial, the serial of the last
dev build (bin/lm-dev-build.py), is written as 0, so the dev builds of the next entry start at
~dev1.
"""
import argparse
@@ -14,6 +16,7 @@ import sys
ROOT = pathlib.Path(__file__).resolve().parent
CHANGELOG = ROOT / 'debian-package' / 'debian' / 'changelog'
DEV_SERIAL = ROOT / '.dev-build.serial'
#: Print the git commands instead of running them; set by -n/--dry-run.
@@ -88,6 +91,10 @@ def main():
git('tag', tag)
if not args.no_push:
git('push', 'origin', 'main', '--tags')
if DRY_RUN:
print(f'echo 0 > {shlex.quote(str(DEV_SERIAL))}')
else:
DEV_SERIAL.write_text('0\n', encoding='utf-8')
return 0
+114 -45
View File
@@ -1,7 +1,10 @@
# Remote tests
`run.py` installs the newest `out/linux-manager_*_all.deb` into instances of an LXD remote and
checks the router and VPN components in three scenarios:
The scripts are in `bin/` of the repository; this directory holds their data: `scenarios/`,
`configs/`, `cloud-init/`, `repo/` and the files copied into instances.
`bin/lm-dev-run.py` installs the newest `out/linux-manager_*_all.deb` into instances of an LXD
remote and checks the router and VPN components in three scenarios:
- `core`: one interface, router and VPN off;
- `nat`: VPN on, router off, one interface; WireGuard and OpenVPN clients reach a target through
@@ -11,7 +14,7 @@ checks the router and VPN components in three scenarios:
`site_to_site` is set, which setup refuses.
Servers are virtual machines, clients and LAN hosts containers, all from `ubuntu:26.04`. Each
scenario is a module in `scenarios/` whose `run(lab)` uses the `Lab` class of `run.py`.
scenario is a module in `scenarios/` whose `run(lab)` uses the `Lab` class of `lm-dev-run.py`.
`wireguard_peer.py` and `echo.py` are copied into the instances: the first gives the test user a
WireGuard peer on the server, the second answers HTTP with the client's address.
@@ -22,11 +25,11 @@ export LXD_POOL=...
```sh
./build.sh
tests/remote/run.py core nat s2s
bin/lm-dev-run.py core nat s2s
```
```sh
tests/remote/run.py all
bin/lm-dev-run.py all
```
Options:
@@ -35,14 +38,16 @@ Options:
|---|---|---|---|
| `--remote` | `LXD_REMOTE` | required | The `lxc` remote |
| `--pool` | `LXD_POOL` | required | The storage pool of the project's root disks |
| `--project` | `LXD_PROJECT` | `lm-test` | The project the instances live in; it must not exist |
| `--project` | `LXD_TEST_PROJECT` | `lm-test` | The project the instances live in; it must not exist |
| `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of every instance |
| `--keep` | | off | Leaves the project and the networks in place; run one scenario then |
Each scenario creates the project and its networks (`lmt-<scenario>-<net>`) and removes them at
its end. The administrator password and the pre-shared key are generated per run and written to
`tmp/remote-test.env`. The run prints PASS, FAIL or SKIP per check and exits non-zero on a
failure; WireGuard is skipped when the host kernel has no WireGuard module.
its end. The administrator password and the pre-shared key are generated per run. The
administrator's name and password are set as `ADMIN_USERNAME` and `ADMIN_PASSWORD` in the
repository's `.env`, keeping its other lines, and the key is written to `tmp/remote-test.env`.
The run prints PASS, FAIL or SKIP per check and exits non-zero on a failure; WireGuard is skipped
when the host kernel has no WireGuard module.
The configurations in `configs/` have placeholders that are filled in for each server:
@@ -52,53 +57,56 @@ The configurations in `configs/` have placeholders that are filled in for each s
## A VM to work with
`vm.py` launches one server VM, `lm-dev` by default, on the LXD remote and leaves it
running. The VM is created in a project, `default` by default, with that project's default
profile, and takes its address from DHCP. It gets the newest package with the administrator
`admin` and a generated password, written to `tmp/vm-<name>.env`, and a configuration from
`configs/`, `core.json` by default; `@ETH0@` is the interface of the VM's default route.
`lm-dev-vm.py create` launches one server VM, `lm-dev` by default, on the LXD remote and leaves
it running. The VM is created in a project, the test project `lm-dev` by default, with that
project's default profile, and takes its address from DHCP. It gets the package with the
administrator `admin` and a generated password, set as `ADMIN_USERNAME` and `ADMIN_PASSWORD` in the
repository's `.env`, and a configuration from `configs/`, `core.json` by default; `@ETH0@` is the
interface of the VM's default route.
The leased address is pinned on the VM's NIC, as NAT proxy devices require a static address.
Proxy devices then forward ports of the LXD host address `--listen` to the VM; by default that is
the IPv4 address of the host in the remote's URL (`lxc remote list`), which must be an address of
the LXD host itself:
In a test project made by `lm-dev-lxd-project.py`, the VM installs the package from the project's
repository, so later dev builds reach it as updates; in another project it installs the newest
`out/linux-manager_*_all.deb`. The leased address is pinned on the VM's NIC, and these ports lead
to the VM:
- `7080` to the Manager;
- `7081` to the status web service;
- `2222` to SSH, port `22`.
The script prints the VM's address, the administrator's password, the proxied URLs, the command
of a shell in it and the command that removes it.
In a test project they lead through a network forward on the project's `wan`, whose listen address
LXD allocates from the uplink's `--routes`, as LXD refuses NAT proxy devices in a project with
networks of its own. In another project NAT proxy devices listen on the LXD host address
`--listen`, by default the IPv4 address of the host in the remote's URL (`lxc remote list`), which
must be an address of the LXD host itself.
The script prints the VM's address, the administrator's password, the URLs, the command of a
shell in it and the command that removes it.
```sh
tests/remote/vm.py
bin/lm-dev-vm.py create
```
```sh
tests/remote/vm.py --remove
bin/lm-dev-vm.py remove
```
`--remove` deletes the VM and its env file. Options:
`remove` deletes the VM, its forward and `tmp/vm-<vm>.env`, its pre-shared key; `.env` is left as
it is. Options:
| Option | Variable | Default | Meaning |
|---|---|---|---|
| `--remote` | `LXD_REMOTE` | required | The `lxc` remote |
| `--project` | | `default` | The project of the VM |
| `--name` | | `lm-dev` | The name of the VM; it must not exist |
| `--project` | `LXD_PROJECT` | `lm-dev` | The project of the VM |
| `--vm` | | `lm-dev` | The name of the VM; it must not exist for `create` |
| `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of the VM |
| `--config` | | `core.json` | The configuration from `configs/` |
| `--listen` | `LXD_LISTEN` | the remote URL's host | An address of the LXD host the proxies listen on |
In a test project made by `lxd-project.py`, `vm.py` installs the package from the project's
repository instead of `out/`, so later dev builds reach the VM as updates. LXD refuses NAT proxy
devices in a project with networks of its own, so there the ports lead through a network forward
on the project's `wan`, whose listen address LXD allocates from the uplink's `--routes`;
`--listen` does not apply, and `--remove` deletes the forward with the VM.
| `--listen` | `LXD_LISTEN` | the remote URL's host | Outside a test project, the address the proxies listen on |
## A test project with dev builds
`lxd-project.py create` makes a project for manual tests that stays until
`lxd-project.py remove`; `run.py` keeps making and removing its own projects. The project has:
`lm-dev-lxd-project.py create` makes a project for manual tests that stays until
`lm-dev-lxd-project.py remove`; `lm-dev-run.py` keeps making and removing its own projects. The
project has:
- networks of its own (`features.networks`), OVN networks on the physical uplink `--uplink`:
`wan`, with NAT and DHCP on a subnet LXD picks, and `lana` and `lanb`, on subnets LXD picks
@@ -127,19 +135,19 @@ OVN answers ARP for its routers' and forwards' addresses on the LAN (`ovn.ingres
of that name as it is; `uplink remove` deletes it.
```sh
tests/remote/lxd-project.py uplink setup
bin/lm-dev-lxd-project.py uplink setup
```
```sh
tests/remote/lxd-project.py uplink remove
bin/lm-dev-lxd-project.py uplink remove
```
```sh
tests/remote/lxd-project.py create
bin/lm-dev-lxd-project.py create
```
```sh
tests/remote/lxd-project.py remove
bin/lm-dev-lxd-project.py remove
```
| Option | Variable | Default | Meaning |
@@ -155,21 +163,82 @@ tests/remote/lxd-project.py remove
| `--ovn-ranges` | `LXD_UPLINK_OVN_RANGES` | required by `uplink setup` | LAN addresses for OVN routers |
| `--routes` | `LXD_UPLINK_ROUTES` | required by `uplink setup` | A LAN subnet for network forwards |
`dev-build.py` builds and publishes the next dev build. Its version is the newest changelog
`lm-dev-build.py` builds and publishes the next dev build. Its version is the newest changelog
entry's with `~dev<N>` before the Debian revision, `0.41.0~dev7-1` for `0.41.0-1`, so the release
of that entry is newer than its dev builds. `N` is kept in `tmp/test-number` and goes up with each
build that succeeds. `./build.sh` builds it, with `CONTAINER_RUNTIME` and `DOCKER_CONTEXT` from the
of that entry is newer than its dev builds. `N` is that of the last dev build, kept in
`.dev-build.serial` of the repository; each build that succeeds writes its own, one higher, and
`release.py` writes 0 when it releases, so the next entry's builds start at `~dev1`. `./build.sh` builds it, with `CONTAINER_RUNTIME` and `DOCKER_CONTEXT` from the
environment; the build is moved to `out/dev/`, copied into the repository and published there. A
VM of the project then gets it with Check update and Upgrade in the Manager, or `apt-get update`
and `apt-get upgrade`.
```sh
tests/remote/dev-build.py
bin/lm-dev-build.py
```
`--project` (`LXD_PROJECT`, `lm-dev` by default) names the project.
`--project` (`LXD_PROJECT`, `lm-dev` by default) names the project; the remote is the project's,
read from its state file, so the script takes no `--remote`.
## A TOTP token for a user of a test VM
`bin/lm-dev-otp-register.py` enrols a new TOTP token for a user of a VM, `admin` of `lm-dev` by
default, through `lxc exec`: in the VM, as root, the package's `linuxmanager_users` makes a new
secret and stores it once a code the script computes from it verifies, replacing a token the user
had. The secret, base32, is then written to the file `--secret-file` or `OTP_FILE` names,
readable by its owner only; `otp.py code` prints its codes (see below).
```sh
export OTP_FILE=tmp/admin.otp
bin/lm-dev-otp-register.py
```
| Option | Variable | Default | Meaning |
|---|---|---|---|
| `--secret-file` | `OTP_FILE` | required | The file the secret is written to |
| `--remote` | `LXD_REMOTE` | required | The `lxc` remote |
| `--project` | `LXD_PROJECT` | `lm-dev` | The project of the VM |
| `--vm` | | `lm-dev` | The name of the VM |
| `--user` | | `admin` | The user to enrol |
## A command-line authenticator app
`bin/otp.py` is an authenticator app on the command line, in place of one on a phone, not tied to
Linux Manager or LXD. It keeps a base32 secret in the file `--secret-file` or `OTP_FILE` names,
readable by its owner only. The codes are
RFC 6238's, SHA-1, 6 digits and 30 seconds by default.
Options of both actions:
| Option | Variable | Default | Meaning |
|---|---|---|---|
| `--secret-file` | `OTP_FILE` | required | The file of the base32 secret |
| `--algorithm` | | `sha1` | `sha1`, `sha256` or `sha512` |
| `--digits` | | `6` | The digits of a code, 6 to 10 |
| `--period` | | `30` | The seconds a code is valid |
`new` makes a new secret of 20 random bytes in the file and prints its `otpauth://` URI, with the
algorithm, digits and period, for a server or an app that enrols a given secret:
```sh
bin/otp.py new --account admin --issuer lm-dev
```
| Option | Default | Meaning |
|---|---|---|
| `--account`, `--issuer` | none | The label of the URI |
| `--force` | off | Replace an existing secret |
`code` prints the current code of the secret, for the Manager's sign-in, SSH or `sudo`:
```sh
bin/otp.py code
```
| Option | Default | Meaning |
|---|---|---|
| `--at` | now | The Unix time of the code |
## Scope of the tests
Not covered by `run.py`: IKEv2 client access, HTTPS with Let's Encrypt, the OpenID Provider and
passkeys, PowerDNS answering from outside, and the Azure and GCP platform modules.
Not covered by `lm-dev-run.py`: IKEv2 client access, HTTPS with Let's Encrypt, the OpenID
Provider and passkeys, PowerDNS answering from outside, and the Azure and GCP platform modules.
+11
View File
@@ -0,0 +1,11 @@
{
"general": {"platform": "generic", "mode": "manual"},
"router": {"enabled": false},
"vpn": {"enabled": true},
"interfaces": {"external": "@ETH0@"},
"wan": {"local_fqdn": "lm-offline.test"},
"local": {"cidrs": ["@CIDR0@"]},
"openvpn": {"enabled": true, "address_pool": "10.67.0.0/24", "port": 1194, "protocol": "udp"},
"pki": {"root": "offline"},
"https": {"enabled": false}
}
+11
View File
@@ -0,0 +1,11 @@
{
"general": {"platform": "generic", "mode": "manual"},
"router": {"enabled": false},
"vpn": {"enabled": true},
"interfaces": {"external": "@ETH0@"},
"wan": {"local_fqdn": "lm-simple-ca.test"},
"local": {"cidrs": ["@CIDR0@"]},
"openvpn": {"enabled": true, "address_pool": "10.67.0.0/24", "port": 1194, "protocol": "udp"},
"pki": {"root": "simple-ca", "simple_ca_url": "https://10.188.96.4:8443"},
"https": {"enabled": false}
}
+17 -6
View File
@@ -20,6 +20,7 @@ import RemoteAccessPanel from './RemoteAccessPanel.tsx'
import ServerPanel from './ServerPanel.tsx'
import ServiceAccountsPanel from './ServiceAccountsPanel.tsx'
import SettingsButton from './SettingsButton.tsx'
import { useBrowserSettings } from './settings.ts'
import ShellPanel from './ShellPanel.tsx'
import SignIn from './SignIn.tsx'
import SystemPanel from './SystemPanel.tsx'
@@ -71,7 +72,8 @@ const HELP_KEY = 'linux-manager-ui.help'
* the Status panel, its metrics, its logs, its backups or the updates of its system's packages. A page shows one tab at a time, each read only while shown. An
* administrator switches pages with the page menu at the right end of the header; the button with the user's name,
* left of Sign out, opens the user's own account, and an administrator's shell button, left of it, the shell; pressed
* on their page, each returns to the page it was opened from. While files are open in the shell's editor, the editor
* on their page, each returns to the page it was opened from; with the browser setting shellNewTab the shell button opens
* the shell in a new tab instead. While files are open in the shell's editor, the editor
* button left of the shell button switches the Shell page between the terminal and the editor. The help button, between the theme switcher and the page menu, opens or closes the help on
* the right (HelpPanel) at the topic of the page and tab shown (HELP_TOPICS), the page moving left; the browser keeps
* whether it is open. A call answered 401 ends the session and asks for a sign-in again.
@@ -85,16 +87,19 @@ export default function App(props: { info: Info }) {
const [filesSite, setFilesSite] = useState<string | null>(null)
const [session, setSession] = useState<Session | null | undefined>(undefined)
const [role, setRole] = useState<{ name: string; admin: boolean } | null>(null)
// The router and the VPN components as router.enabled and vpn.enabled of /config; null while not known, when every page shows.
const [components, setComponents] = useState<{ router: boolean; vpn: boolean } | null>(null)
// The router and the VPN components as router.enabled and vpn.enabled of /config, and whether Docker is installed;
// null while not known, when every page shows.
const [components, setComponents] = useState<{ router: boolean; vpn: boolean; docker: boolean } | null>(null)
const routerOff = components?.router === false
const vpnOff = components?.vpn === false
const dockerMissing = components?.docker === false
const page = PAGE_PATHS.find((path) => path === window.location.pathname) ?? '/'
const userPage = page === USER_PATH
const admin = session && role?.name === session.name ? role.admin : undefined
// The account page is the page of every user who is not an administrator, and of an administrator at USER_PATH.
const accountShown = Boolean(session) && admin !== undefined && (userPage || !admin)
const [helpOpen, setHelpOpen] = useState(() => window.localStorage.getItem(HELP_KEY) === 'open')
const { shellNewTab } = useBrowserSettings()
// The files open in the Shell page's editor, and whether the editor is shown in place of the terminal.
const [editorFiles, setEditorFiles] = useState(0)
const [editorShown, setEditorShown] = useState(false)
@@ -142,6 +147,7 @@ export default function App(props: { info: Info }) {
.then((details) => setComponents({
router: details.configuration.router?.enabled === true,
vpn: details.configuration.vpn?.enabled === true,
docker: details.docker.installed,
}))
.catch(() => setComponents(null))
}, [admin])
@@ -208,7 +214,7 @@ export default function App(props: { info: Info }) {
<IconButton
aria-label="shell"
color={page === SHELL_PATH ? 'primary' : 'default'}
onClick={() => toggle(SHELL_PATH)}
onClick={() => (shellNewTab && page !== SHELL_PATH ? window.open(SHELL_PATH, '_blank') : toggle(SHELL_PATH))}
sx={page === SHELL_PATH ? { bgcolor: 'action.selected' } : undefined}
>
<Terminal />
@@ -237,7 +243,9 @@ export default function App(props: { info: Info }) {
</IconButton>
</Tooltip>
)}
{session && admin && <PageMenu path={page} hidden={vpnOff ? [REMOTE_ACCESS_PATH] : []} />}
{session && admin && (
<PageMenu path={page} hidden={[...(vpnOff ? [REMOTE_ACCESS_PATH] : []), ...(dockerMissing ? [DOCKER_PATH] : [])]} />
)}
</Stack>
</Stack>
{session === undefined && <CircularProgress />}
@@ -269,7 +277,10 @@ export default function App(props: { info: Info }) {
{sitesView === 'dns' && <DnsPanel />}
</>
)}
{session && admin && page === DOCKER_PATH && (
{session && admin && page === DOCKER_PATH && dockerMissing && (
<Typography color="text.secondary">Docker is not installed on this server.</Typography>
)}
{session && admin && page === DOCKER_PATH && !dockerMissing && (
<>
<Typography variant="h6" component="h2" sx={{ mb: 2 }}>Docker</Typography>
<DockerPanel />
+77 -34
View File
@@ -5,8 +5,8 @@ import Download from '@mui/icons-material/Download'
import Edit from '@mui/icons-material/Edit'
import Refresh from '@mui/icons-material/Refresh'
import Settings from '@mui/icons-material/Settings'
import Key from '@mui/icons-material/Key'
import UploadFile from '@mui/icons-material/UploadFile'
import WarningAmber from '@mui/icons-material/WarningAmber'
import {
Alert, Box, Button, Chip, IconButton, MenuItem, Stack, Tab, Table, TableBody, TableCell, TableHead, TableRow, Tabs, TextField,
Tooltip, Typography,
@@ -20,10 +20,12 @@ import IssuingCaDialog from './IssuingCaDialog.tsx'
import TemplateDialog from './TemplateDialog.tsx'
import Toolbar from './Toolbar.tsx'
import EkuDialog from './EkuDialog.tsx'
import PkiSettingsDialog, { PUBLISH_LABELS } from './PkiSettingsDialog.tsx'
import PkiSettingsDialog, { PUBLISH_LABELS, ROOT_SOURCE_LABELS } from './PkiSettingsDialog.tsx'
import { Pairs, Section } from './ServerPanel.tsx'
import SetupCodeDialog from './SetupCodeDialog.tsx'
import {
ApiError, BUNDLE_SHAPE, CA_IMPORTED_SHAPE, CRL_IMPORTED_SHAPE, CSR_SHAPE, ISSUED_SHAPE, PFX_SHAPE, PKI_SETTINGS_SHAPE, PKI_SHAPE, REVOKED_SHAPE,
TOKEN_SHAPE,
BUILTIN_TEMPLATES, REVOKE_REASONS, request, type Pki, type PkiCertificate, type PkiIssuingCa, type PkiTemplate,
} from './api.ts'
import { saveFile } from './saveFile.ts'
@@ -32,8 +34,11 @@ import { saveFile } from './saveFile.ts'
* built-in issuing CAs, the general-purpose ones. */
type View = 'root' | 'templates' | 'usages' | 'p2s' | 's2s' | 'issuing'
/** The built-in CAs, whose certificates the Issuing CAs tab leaves out. */
const BUILTIN_CAS = ['root', 'p2s', 's2s']
/** The built-in CAs and the Simple CA issuing CA above them, whose certificates the Issuing CAs tab leaves out. */
const BUILTIN_CAS = ['root', 'upstream', 'p2s', 's2s']
/** Where the root CRL came from. */
const CRL_SOURCE_LABELS: Record<string, string> = { signed: 'signed by the server', uploaded: 'uploaded', fetched: 'fetched from Simple CA' }
/** The note shown after a change, which the server applies when linux-manager-setup has run again. */
const APPLIED = 'The server applies the change in the background.'
@@ -67,8 +72,8 @@ const REASON_LABELS: Record<string, string> = {
* changed and removed there, with their certificates, filtered by CA. The warnings, Issue and Settings
* are above the tabs. Settings edits the pki section, Issue issues a certificate from a CSR or into a PFX file, a
* certificate of another system or of the server is revoked, an issuing CA waiting for the offline root gives its CSR
* and takes its signed certificate, and the root takes a CRL signed offline. The root key is managed on the server
* with linux-manager-ca only.
* and takes its signed certificate, the offline root takes its certificate and a CRL signed offline, and a Simple CA
* root takes a setup code for a new token.
*/
export default function CertificatesPanel() {
const [pki, setPki] = useState<Pki | null>(null)
@@ -83,6 +88,7 @@ export default function CertificatesPanel() {
const [issuing, setIssuing] = useState(false)
const [importing, setImporting] = useState<string | null>(null)
const [uploading, setUploading] = useState(false)
const [entering, setEntering] = useState(false)
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
const [filter, setFilter] = useState('')
const [view, setView] = useState<View>('root')
@@ -195,7 +201,11 @@ export default function CertificatesPanel() {
function removeAuthority(name: string) {
setConfirm({
title: 'Remove issuing CA',
message: `Remove issuing CA ${name}? The server retires it and revokes its certificate on the root CRL; with the root offline, the root CRL is signed offline. Its certificates stay valid until they expire or are revoked.`,
message: `Remove issuing CA ${name}? The server retires it. ${{
local: 'It revokes its certificate on the root CRL.',
offline: 'Its certificate is revoked on the root CRL signed offline.',
'simple-ca': 'Its certificate is revoked in Simple CA.',
}[pki?.settings.root ?? 'local']} Its certificates stay valid until they expire or are revoked.`,
confirmLabel: 'Remove',
destructive: true,
onCancel: () => setConfirm(null),
@@ -314,7 +324,7 @@ export default function CertificatesPanel() {
</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
{authorityOf(certificate) && (
<Tooltip title="Download the CA bundle: the issuing CA and the root">
<Tooltip title="Download the CA bundle: the issuing CA and the CAs above it">
<span>
<IconButton size="small" disabled={busy} onClick={() => void downloadBundle(authorityOf(certificate)!.name)}>
<Download fontSize="small" />
@@ -356,8 +366,10 @@ export default function CertificatesPanel() {
/>
{authority.state === 'pending' && (
<Stack direction="row" sx={{ mt: 1, alignItems: 'center', justifyContent: 'flex-end', gap: 1 }}>
<Typography variant="body2" color="text.secondary">Waits for its certificate signed by the root:</Typography>
{pendingActions(name)}
<Typography variant="body2" color="text.secondary">
{pki?.settings.root === 'offline' ? 'Waits for its certificate signed by the root:' : 'Waits for its certificate signed by Simple CA.'}
</Typography>
{pki?.settings.root === 'offline' && pendingActions(name)}
</Stack>
)}
{authority.state === 'active' && (
@@ -407,34 +419,51 @@ export default function CertificatesPanel() {
{pki && view === 'root' && (
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' } }}>
<Section title="Root CA">
{root ? (
{root && (
<>
<Pairs
rows={[
['Subject', root.subject],
['Source', root.source === 'simple-ca' ? `Simple CA, ${root.simple_ca_url}` : ROOT_SOURCE_LABELS[root.source]],
['State', <Chip size="small" label={root.state} color={STATE_COLORS[root.state] ?? 'default'} />],
['Subject', root.subject ?? '-'],
['Expires', when(root.expires)],
['Key', root.key ? (
<Box component="span" sx={{ display: 'inline-flex', alignItems: 'center', gap: 0.5 }}>
on the server
<Tooltip title="Keeping the root key off the server is recommended: linux-manager-ca root export-key, then linux-manager-ca root remove-key.">
<WarningAmber fontSize="small" color="warning" aria-label="The root key is on the server" />
</Tooltip>
</Box>
) : 'offline'],
['CRL valid until', when(root.crl_next_update)],
['CRL', root.crl_source === 'uploaded' ? 'uploaded' : root.crl_source === 'signed' ? 'signed by the server' : '-'],
['CRL', CRL_SOURCE_LABELS[root.crl_source ?? ''] ?? '-'],
...(root.upstream ? [
['Simple CA issuing CA', `${root.upstream.name}: ${root.upstream.subject}`],
['Its expiry', when(root.upstream.expires)],
['Its CRL valid until', when(root.upstream.crl_next_update)],
] as [string, string][] : []),
...(root.source === 'simple-ca' ? [['Token valid until', root.token_expires ? when(root.token_expires) : 'no token']] as [string, string][] : []),
]}
/>
{root.state === 'pending' && root.source === 'local' && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>The server creates it once a platform is chosen.</Typography>
)}
<Stack direction="row" sx={{ mt: 1, justifyContent: 'flex-end', gap: 1 }}>
<Button size="small" variant="outlined" startIcon={<Download />} disabled={busy} onClick={() => void downloadBundle('root')}>
Download root CA
</Button>
<Button size="small" variant="outlined" startIcon={<UploadFile />} disabled={busy} onClick={() => setUploading(true)}>
Upload CRL
</Button>
{root.state === 'active' && (
<Button size="small" variant="outlined" startIcon={<Download />} disabled={busy} onClick={() => void downloadBundle('root')}>
Download root CA
</Button>
)}
{root.source === 'offline' && root.state === 'pending' && (
<Button size="small" variant="outlined" startIcon={<UploadFile />} disabled={busy} onClick={() => setImporting('root')}>
Import root certificate
</Button>
)}
{root.source === 'offline' && root.state === 'active' && (
<Button size="small" variant="outlined" startIcon={<UploadFile />} disabled={busy} onClick={() => setUploading(true)}>
Upload CRL
</Button>
)}
{root.source === 'simple-ca' && (
<Button size="small" variant="outlined" startIcon={<Key />} disabled={busy} onClick={() => setEntering(true)}>
Enter setup code
</Button>
)}
</Stack>
</>
) : <Typography variant="body2" color="text.secondary">None yet; the server creates it once a platform is chosen.</Typography>}
)}
</Section>
<Section title="General">
<Pairs
@@ -447,7 +476,7 @@ export default function CertificatesPanel() {
/>
</Section>
<Section title="Issuing CA certificates" wide>
{certificateTable(pki.certificates.filter((certificate) => certificate.ca === 'root'))}
{certificateTable(pki.certificates.filter((certificate) => certificate.ca === 'root' || certificate.ca === 'upstream'))}
{pki.status.retired.length > 0 && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
{`Retired: ${pki.status.retired.map((retired) => `${retired.name} (${when(retired.retired)})`).join(', ')}`}
@@ -622,9 +651,9 @@ export default function CertificatesPanel() {
<TableCell>{authority.templates.join(', ')}</TableCell>
<TableCell sx={{ wordBreak: 'break-all' }}>{authority.acme_url ?? (authority.acme ? 'waits for the certificate' : '-')}</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
{authority.state === 'pending' && pendingActions(authority.name)}
{authority.state === 'pending' && pki.settings.root === 'offline' && pendingActions(authority.name)}
{authority.state === 'active' && (
<Tooltip title="Download the CA bundle: the issuing CA and the root">
<Tooltip title="Download the CA bundle: the issuing CA and the CAs above it">
<span>
<IconButton size="small" disabled={busy} onClick={() => void downloadBundle(authority.name)}><Download fontSize="small" /></IconButton>
</span>
@@ -721,13 +750,15 @@ export default function CertificatesPanel() {
)}
{importing && (
<ImportDialog
title={`Import the certificate of ${importing}`}
message="The certificate of the issuing CA, signed by the root CA for the key of its CSR."
title={importing === 'root' ? 'Import the root certificate' : `Import the certificate of ${importing}`}
message={importing === 'root'
? 'The self-signed certificate of the offline root CA; the certificates of the issuing CAs are imported after it.'
: 'The certificate of the issuing CA, signed by the root CA for the key of its CSR.'}
label="Certificate"
begin="-----BEGIN CERTIFICATE-----"
onCancel={() => setImporting(null)}
onSave={async (certificate) => {
await request('PUT', `/ca/issuing/${importing}/certificate`, CA_IMPORTED_SHAPE, { certificate })
await request('PUT', importing === 'root' ? '/ca/root/certificate' : `/ca/issuing/${importing}/certificate`, CA_IMPORTED_SHAPE, { certificate })
setImporting(null)
setNote(APPLIED)
await refresh()
@@ -748,6 +779,18 @@ export default function CertificatesPanel() {
}}
/>
)}
{entering && root && (
<SetupCodeDialog
url={root.simple_ca_url ?? ''}
onCancel={() => setEntering(false)}
onSave={async (code) => {
await request('PUT', '/ca/root/setup-code', TOKEN_SHAPE, { code })
setEntering(false)
setNote(APPLIED)
await refresh()
}}
/>
)}
{confirm && <ConfirmDialog {...confirm} />}
</Box>
)
+1 -1
View File
@@ -85,7 +85,7 @@ export default function DnsSettingsDialog(props: {
value={ttl}
autoComplete="off"
error={ttlProblem !== ''}
helperText={ttlProblem || 'The TTL of the domains without their own.'}
helperText={ttlProblem || 'The default TTL of the records: used where neither the record nor its domain has one.'}
slotProps={{ htmlInput: { inputMode: 'numeric' } }}
onChange={(event) => setTtl(event.target.value.trim())}
sx={{ flex: 1 }}
+1 -1
View File
@@ -47,7 +47,7 @@ const PAGES: { path: string; label: string; icon: ReactNode }[] = [
/**
* A button naming the page shown, or Pages on the account and the shell page, whose menu opens the pages of an
* administrator but those of hidden, the pages of a component switched off.
* administrator but those of hidden, the pages of a component switched off or of software the server does not have.
*/
export default function PageMenu(props: { path: string; hidden: string[] }) {
const [anchor, setAnchor] = useState<HTMLElement | null>(null)
+37 -7
View File
@@ -3,7 +3,7 @@ import {
Typography,
} from '@mui/material'
import { useState, type FormEvent } from 'react'
import { PKI_KEYS, PKI_PUBLISH, type Pki, type PkiSettings, type PkiTemplate } from './api.ts'
import { PKI_KEYS, PKI_PUBLISH, type Pki, type PkiRootSource, type PkiSettings, type PkiTemplate } from './api.ts'
/** The labels of the publishing endpoints. */
export const PUBLISH_LABELS: Record<string, string> = {
@@ -13,11 +13,18 @@ export const PUBLISH_LABELS: Record<string, string> = {
'https-default': 'HTTPS on port 443, served by Caddy',
}
/** The labels of the sources of the root CA. */
export const ROOT_SOURCE_LABELS: Record<PkiRootSource, string> = {
local: 'Created by the server',
offline: 'Offline',
'simple-ca': 'Simple CA',
}
/** The name of an issuing CA or a template, as the server accepts it. */
export const NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}$/
/** The names the issuing CAs of pki.issuing_cas cannot have. */
export const RESERVED = ['root', 'p2s', 's2s']
export const RESERVED = ['root', 'upstream', 'p2s', 's2s']
/** The longest common name of a CA, in characters. */
const CA_NAME_MAX = 64
@@ -35,6 +42,16 @@ export function nameProblem(value: string) {
return value.trim() === '' || value.trim().length > CA_NAME_MAX ? `1 to ${CA_NAME_MAX} characters.` : ''
}
/** The problem of the URL of a Simple CA service, or ''. */
export function urlProblem(value: string) {
try {
const url = new URL(value.trim())
return url.protocol === 'https:' && url.hostname !== '' && url.search === '' && url.hash === '' ? '' : 'An https:// URL.'
} catch {
return 'An https:// URL.'
}
}
/** A lifetime's problem, or ''. */
export function daysProblem(value: number) {
return !Number.isInteger(value) || value < 1 || value > DAYS_MAX ? `1 to ${DAYS_MAX} days.` : ''
@@ -43,9 +60,10 @@ export function daysProblem(value: number) {
/**
* A dialog that edits the server's pki section but the general-purpose issuing CAs, the templates and the custom
* extended key usages, which IssuingCaDialog, TemplateDialog and EkuDialog edit: the names, lifetimes and key type of
* the CAs, the validity of the CRLs and
* where certificates and CRLs are published. The server applies the names, lifetimes and key type when it creates a
* CA. onSave sends the settings; the dialog closes when it succeeds and shows the server's message when it fails.
* the CAs, the validity of the CRLs, where certificates and CRLs are published and, with a Simple CA root, the URL of
* the service. The source of the root is shown and not edited, as it is fixed once the root exists. The server applies
* the names, lifetimes and key type when it creates a CA. onSave sends the settings; the dialog closes when it
* succeeds and shows the server's message when it fails.
*/
export default function PkiSettingsDialog(props: {
pki: Pki
@@ -60,6 +78,7 @@ export default function PkiSettingsDialog(props: {
const blocked = [
nameProblem(settings.root_name), nameProblem(settings.p2s_name), nameProblem(settings.s2s_name),
daysProblem(settings.root_days), daysProblem(settings.ca_days), daysProblem(settings.crl_days), daysProblem(settings.root_crl_days),
settings.root === 'simple-ca' ? urlProblem(settings.simple_ca_url) : '',
].some((problem) => problem !== '')
async function submit(event: FormEvent) {
@@ -90,7 +109,18 @@ export default function PkiSettingsDialog(props: {
Names, lifetimes and the key type apply when the server creates a CA; URLs apply to the certificates signed afterwards.
</Typography>
<Typography variant="subtitle2">CAs</Typography>
{(['root', 'p2s', 's2s'] as const).map((name) => {
<TextField label="Root CA source" value={ROOT_SOURCE_LABELS[settings.root]} disabled helperText="Fixed once the root exists." />
{settings.root === 'simple-ca' && (
<TextField
label="Simple CA URL"
value={settings.simple_ca_url}
autoComplete="off"
error={urlProblem(settings.simple_ca_url) !== ''}
helperText={urlProblem(settings.simple_ca_url) || 'The service the server exchanges setup codes with and has its issuing CAs signed by.'}
onChange={(event) => change({ simple_ca_url: event.target.value.trim() })}
/>
)}
{(['root', 'p2s', 's2s'] as const).filter((name) => name !== 'root' || settings.root === 'local').map((name) => {
const option = `${name}_name` as 'root_name' | 'p2s_name' | 's2s_name'
return (
<TextField
@@ -144,7 +174,7 @@ export default function PkiSettingsDialog(props: {
type="number"
value={settings.root_crl_days}
error={daysProblem(settings.root_crl_days) !== ''}
helperText={daysProblem(settings.root_crl_days) || 'When the server signs it, with the root key on the server.'}
helperText={daysProblem(settings.root_crl_days) || 'When the server signs it, for a root the server created.'}
onChange={(event) => change({ root_crl_days: number(event.target.value) })}
/>
</Stack>
+9 -4
View File
@@ -1,12 +1,12 @@
import SettingsIcon from '@mui/icons-material/Settings'
import { Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, IconButton, MenuItem, Stack, TextField, Tooltip } from '@mui/material'
import { Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, FormControlLabel, FormHelperText, IconButton, MenuItem, Stack, Switch, TextField, Tooltip } from '@mui/material'
import { useState } from 'react'
import { DEFAULT_SETTINGS, REFRESH_CHOICES, refreshLabel, saveBrowserSettings, useBrowserSettings } from './settings.ts'
/**
* An icon button that opens the settings of this browser: how often the Overview and the Metrics tab read the server on
* their own, or manual, when they read only when opened and on Refresh. A change applies at once and is kept in the
* browser; Defaults sets every setting back.
* their own, or manual, when they read only when opened and on Refresh, and whether the shell button opens the shell in
* a new tab. A change applies at once and is kept in the browser; Defaults sets every setting back.
*/
export default function SettingsButton() {
const [open, setOpen] = useState(false)
@@ -44,11 +44,16 @@ export default function SettingsButton() {
>
{REFRESH_CHOICES.map((seconds) => <MenuItem key={seconds} value={seconds}>{refreshLabel(seconds)}</MenuItem>)}
</TextField>
<FormControlLabel
control={<Switch checked={settings.shellNewTab} onChange={(event) => saveBrowserSettings({ ...settings, shellNewTab: event.target.checked })} />}
label="Open the shell in a new tab"
/>
<FormHelperText sx={{ mt: -2 }}>The shell then stays open while other pages are opened in this tab.</FormHelperText>
</Stack>
</DialogContent>
<DialogActions>
<Button
onClick={() => saveBrowserSettings({ ...settings, routerRefresh: DEFAULT_SETTINGS.routerRefresh, metricsRefresh: DEFAULT_SETTINGS.metricsRefresh })}
onClick={() => saveBrowserSettings({ ...settings, routerRefresh: DEFAULT_SETTINGS.routerRefresh, metricsRefresh: DEFAULT_SETTINGS.metricsRefresh, shellNewTab: DEFAULT_SETTINGS.shellNewTab })}
>
Defaults
</Button>
+55
View File
@@ -0,0 +1,55 @@
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Stack, TextField } from '@mui/material'
import { useState, type FormEvent } from 'react'
/**
* A dialog that takes the one-time setup code of a sign-ca token of a Simple CA issuing CA, which the server exchanges
* for the token it has its issuing CAs signed with. onSave sends the code; the dialog closes when it succeeds and
* shows the server's message when it fails.
*/
export default function SetupCodeDialog(props: { url: string; onSave: (code: string) => Promise<void>; onCancel: () => void }) {
const [code, setCode] = useState('')
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
async function submit(event: FormEvent) {
event.preventDefault()
if (code.trim() === '') {
return
}
setSaving(true)
setError(null)
try {
await props.onSave(code.trim())
} catch (caught) {
setError((caught as Error).message)
setSaving(false)
}
}
return (
<Dialog open onClose={(_event, reason) => reason !== 'backdropClick' && props.onCancel()} maxWidth="sm" fullWidth slotProps={{ paper: { component: 'form', onSubmit: submit } }}>
<DialogTitle>Enter a Simple CA setup code</DialogTitle>
<DialogContent>
<Stack sx={{ gap: 2, pt: 1 }}>
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
<DialogContentText>
{`The one-time setup code of a sign-ca token of an issuing CA of ${props.url}. The server exchanges it for the token, which replaces the one it has.`}
</DialogContentText>
<TextField
label="Setup code"
value={code}
autoFocus
autoComplete="off"
helperText="Such as K7QF-M2XA-JP4D-W5ZR; it works once."
slotProps={{ htmlInput: { sx: { fontFamily: 'monospace' } } }}
onChange={(event) => setCode(event.target.value)}
/>
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={props.onCancel}>Cancel</Button>
<Button type="submit" variant="contained" disabled={saving || code.trim() === ''}>Exchange</Button>
</DialogActions>
</Dialog>
)
}
+36 -9
View File
@@ -100,7 +100,8 @@ export type RouterDetails = {
listen_port: number | null
peers: { public_key: string; endpoint: string | null; allowed_ips: string[]; handshake_seconds_ago: number | null; received_bytes: number; sent_bytes: number }[]
} | null
docker: { exposed_ports: string[]; rules: string[] | null }
/** installed is whether docker.service is installed on the server. */
docker: { installed: boolean; exposed_ports: string[]; rules: string[] | null }
/** The PostgreSQL clusters of pg_lsclusters, with the main settings of each online one; null when pg_lsclusters fails. */
postgresql: {
clusters: { version: string; name: string; port: number | null; status: string; data_directory: string; settings: Record<string, string> | null }[]
@@ -375,15 +376,28 @@ export type PkiSettings = {
issuing_cas: Record<string, Partial<PkiIssuingCa>>
templates: Record<string, Partial<PkiTemplate>>
extended_key_usages: Record<string, string>
root: PkiRootSource
simple_ca_url: string
}
/** The root CA: whether its key is on the server, and where its CRL came from, signed by the server or uploaded. */
/** Where the root CA comes from, pki.root: the server creates it, an offline CA, or a Simple CA service. */
export type PkiRootSource = 'local' | 'offline' | 'simple-ca'
/**
* The root CA: its source, active or pending (waiting for its certificate), where its CRL came from (signed by the
* server, uploaded or fetched), and, with Simple CA, the service, the Simple CA issuing CA that signs the issuing CAs,
* and the expiry of the token.
*/
export type PkiRoot = {
subject: string
expires: string
key: boolean
source: PkiRootSource
state: string
subject: string | null
expires: string | null
crl_next_update: string | null
crl_source: string | null
simple_ca_url: string | null
upstream: { name: string; subject: string; expires: string; crl_next_update: string | null } | null
token_expires: string | null
}
/** An issuing CA: state is active, pending (waiting for the offline root) or missing. */
@@ -418,7 +432,7 @@ export type PkiCertificate = {
/**
* GET /ca: the pki section, every template with all its options, every extended key usage with its OID and whether it
* is built in, the root (null before it exists), the issuing CAs, the retired CAs and the warnings, and the
* is built in, the root, the issuing CAs, the retired CAs and the warnings, and the
* certificates issued, newest first.
*/
export type Pki = {
@@ -426,7 +440,7 @@ export type Pki = {
templates: Record<string, PkiTemplate>
extended_key_usages: Record<string, { oid: string; builtin: boolean }>
status: {
root: PkiRoot | null
root: PkiRoot
authorities: PkiAuthority[]
retired: { name: string; retired: string; serial: string | null }[]
warnings: string[]
@@ -701,7 +715,7 @@ export const DETAILS_SHAPE = object({
sent_bytes: number,
})),
})),
docker: object({ exposed_ports: list(string), rules: nullable(list(string)) }),
docker: object({ installed: boolean, exposed_ports: list(string), rules: nullable(list(string)) }),
postgresql: nullable(object({
clusters: list(object({
version: string,
@@ -908,6 +922,8 @@ const PKI_SETTINGS: Check = object({
issuing_cas: record(object({ name: optional(string), templates: optional(list(string)), acme: optional(boolean) })),
templates: record(isObject),
extended_key_usages: record(string),
root: string,
simple_ca_url: string,
})
const PKI_CERTIFICATE: Check = object({
serial: string,
@@ -926,7 +942,17 @@ export const PKI_SHAPE = object({
templates: record(PKI_TEMPLATE),
extended_key_usages: record(object({ oid: string, builtin: boolean })),
status: object({
root: nullable(object({ subject: string, expires: string, key: boolean, crl_next_update: nullable(string), crl_source: nullable(string) })),
root: object({
source: string,
state: string,
subject: nullable(string),
expires: nullable(string),
crl_next_update: nullable(string),
crl_source: nullable(string),
simple_ca_url: nullable(string),
upstream: nullable(object({ name: string, subject: string, expires: string, crl_next_update: nullable(string) })),
token_expires: nullable(string),
}),
authorities: list(object({
name: string,
common_name: string,
@@ -953,6 +979,7 @@ export const BUNDLE_SHAPE = object({ name: string, pem: string })
export const REVOKED_SHAPE: Check = (value) => PKI_CERTIFICATE(value) && object({ reissue: boolean })(value)
export const CA_IMPORTED_SHAPE = object({ name: string, subject: string, expires: string })
export const CRL_IMPORTED_SHAPE = object({ next_update: nullable(string) })
export const TOKEN_SHAPE = object({ upstream: string, expires: nullable(string) })
/** The remote access systems of the server: IKEv2 (p2s), OpenVPN and WireGuard. */
export const REMOTE_ACCESS_SYSTEMS = ['p2s', 'openvpn', 'wireguard'] as const
+5 -3
View File
@@ -2,9 +2,10 @@ import { useSyncExternalStore } from 'react'
/**
* The settings of this browser: the seconds between the automatic reads of the Overview and the Metrics tab, 0 for
* manual, and whether the WireGuard configuration dialog leaves out the lines a client fills in (wireguardPrefilled).
* manual, whether the WireGuard configuration dialog leaves out the lines a client fills in (wireguardPrefilled), and
* whether the shell button opens the shell in a new tab (shellNewTab).
*/
export type BrowserSettings = { routerRefresh: number; metricsRefresh: number; wireguardPrefilled: boolean }
export type BrowserSettings = { routerRefresh: number; metricsRefresh: number; wireguardPrefilled: boolean; shellNewTab: boolean }
/** The localStorage key of the settings. */
const KEY = 'linux-manager-ui.settings'
@@ -12,7 +13,7 @@ const KEY = 'linux-manager-ui.settings'
/** The event raised on window when the settings change in this tab. */
const CHANGED = 'linux-manager-ui-settings'
export const DEFAULT_SETTINGS: BrowserSettings = { routerRefresh: 10, metricsRefresh: 60, wireguardPrefilled: false }
export const DEFAULT_SETTINGS: BrowserSettings = { routerRefresh: 10, metricsRefresh: 60, wireguardPrefilled: false, shellNewTab: false }
/** The refresh choices of both tabs, in seconds; 0 is manual. */
export const REFRESH_CHOICES = [0, 5, 10, 30, 60, 300, 900]
@@ -45,6 +46,7 @@ function snapshot(): BrowserSettings {
routerRefresh: choice(stored.routerRefresh, REFRESH_CHOICES, DEFAULT_SETTINGS.routerRefresh),
metricsRefresh: choice(stored.metricsRefresh, REFRESH_CHOICES, DEFAULT_SETTINGS.metricsRefresh),
wireguardPrefilled: typeof stored.wireguardPrefilled === 'boolean' ? stored.wireguardPrefilled : DEFAULT_SETTINGS.wireguardPrefilled,
shellNewTab: typeof stored.shellNewTab === 'boolean' ? stored.shellNewTab : DEFAULT_SETTINGS.shellNewTab,
}
cached = { text, settings }
return settings