Compare commits

...
9 Commits
Author SHA1 Message Date
slawek 5c6fd90f37 update: the development VM of lm-dev-vm.py keeps plain HTTP by name.
Release / release (push) Successful in 21s
2026-11-24 19:57:53 +01:00
slawek 64c3ae4c36 feature: HTTPS is always on, for wan.local_fqdn or, without it, the host name and its mDNS name, optionally also for the server's addresses, and the redirect to HTTPS covers the status page by name.
Release / release (push) Successful in 23s
2026-11-24 19:26:51 +01:00
slawek 7efacfa3bb fix: a configuration that names no HTTPS certificate source gets the first setup's choice, and the development VM of lm-dev-vm.py is named by --fqdn, so its HTTPS sites answer a name that resolves to it.
Release / release (push) Successful in 19s
2026-11-24 18:23:42 +01:00
slawek 0cec95c19b feature: the CA certificates and CRLs are always published over HTTP and HTTPS on the status and Manager ports, the Shell page is an entry of the page menu, and the web interface passes its lint.
Release / release (push) Successful in 26s
2026-11-24 18:06:34 +01:00
slawek 4b5318c676 fix: build.py and publish.py print their usage for --help instead of building or publishing.
Release / release (push) Successful in 19s
2026-11-24 14:37:02 +01:00
slawek b61d1593b7 feature: the PKI's schema is a file of its own that another slapd loads, a certificate can carry the name an application files it under, and the members of pki-managers manage the PKI with its keys.
Release / release (push) Successful in 24s
2026-11-24 14:30:50 +01:00
slawek 6911d16fa3 update: the history of the package is CHANGELOG.md, from which the build writes debian/changelog, the build, publish and development scripts are in Python, and the development tools keep their settings and credentials in .lm-dev-config.
Release / release (push) Failing after 14m43s
2026-11-24 06:51:04 +01:00
slawek a7bfabcb89 feature: the VPN, the router, the name server and WebDAV are components switched on the System tab and installed on demand, Caddy from the Ubuntu archive is a dependency and serves every HTTP and HTTPS port, HTTPS is chosen at install, its certificate is of the Servers Issuing CA or self-signed by default, of ACME or of another CA, the issuing CAs are in one tab, a locked account is unlocked again, the name of a CA is fixed once the CA exists, and a run of setup is no longer cut short by a change.
Release / release (push) Failing after 8s
2026-11-24 05:51:27 +01:00
slawek a649331aa2 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
2026-11-23 06:45:23 +01:00
158 changed files with 9240 additions and 5311 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
dotenv_if_exists
+2 -4
View File
@@ -15,13 +15,11 @@ jobs:
uses: actions/checkout@v6
- name: Build package
working-directory: debian-package
run: ./build.sh
run: ./build.py
- name: Publish package
working-directory: debian-package
env:
SERVER_URL: ${{ secrets.CI_URL }}
OWNER: ${{ secrets.CI_OWNER }}
PACKAGES_TOKEN: ${{ secrets.CI_TOKEN }}
run: ./publish.sh
run: ./publish.py
+3 -1
View File
@@ -15,4 +15,6 @@ tmp
node_modules
web/dist
.venv
dev.json
**/.env
/.lm-dev-config/
/debian-package/debian/changelog
+427 -169
View File
@@ -27,7 +27,7 @@ port is reachable from the external interface only when it is in `exposed_ports`
in `DOCKER-USER` are not touched, because the package owns only its own chain. Restarting Docker
restores the rules. The rules cover IPv4 only.
## ADR-2: A small status web service, on the interfaces web.listen chooses
## ADR-2: A small status web service, reached on the interfaces web.listen chooses
Status: Accepted
@@ -38,11 +38,12 @@ host, so what the service shows and where it listens matter.
Decision: The `linux-manager-web` unit runs one Python script on the standard library's
`http.server`, with the package's own modules and the Python packages of the Ubuntu archive that
the package depends on, and no web framework. It listens on `web.port`, 7081 by default, on the
address of the internal interface, of the external interface or of both, as `web.listen` sets
(`internal`, `external` or `both`, the default), with a server for each address, and is on
unless `web.enabled` is `false` (ADR-7). `/` is for people, in plain text for `curl` and `wget`
and as a Tailwind CSS page for a browser, and `/status` is the same status as JSON. Both show as
the package depends on, and no web framework. It listens on the loopback address behind Caddy
(ADR-21), which serves it on `web.port`, 7081 by default, and is on unless `web.enabled` is
`false` (ADR-7). The firewall opens `web.port` on the internal interface, the external interface
or both, as `web.listen` sets (`internal`, `external` or `both`, the default). `/` is for people,
in plain text for `curl` and `wget` and as a Tailwind CSS page for a browser, and `/status` is
the same status as JSON. Both show as
much as `web.status_content` says, since the server is reachable from the internet and the
operator decides how much it tells strangers: `basic`, the default because it tells the least,
the overall status and the Client IP, `standard` also the package versions and the number of
@@ -50,16 +51,14 @@ active and other services, and `full` also each service and the state of the sit
WireGuard features. The Client IP is the address the request came from, through the trusted
proxies, so a person can see the address the server sees. Nothing comes from the configuration.
`/status` names its content, so clients such as Cloud Manager and the Manager show what it
has. `linux-manager-setup` opens the
port on both interfaces in UFW, so the choice of `web.listen` is made by the service alone, and
writes the features and the facts it resolves to `/run/linux-manager/web.json`.
has. `linux-manager-setup` writes the firewall rules of `web.listen`, and the features and the
facts it resolves to `/run/linux-manager/web.json`.
Consequences: By default the service is reachable from the internet on the external address;
`web.listen` set to `internal` keeps it to the internal network. It serves plain HTTP itself;
HTTPS is Caddy's (ADR-21), so on the plain HTTP port the passwords of `/auth` and the tokens
cross the internet unencrypted. A change of `web.listen`
needs no run of setup, since the firewall does not depend on it; the package's upgrade runs
setup, which writes the rules. `/` and `/status` have no authentication, which is acceptable because they are
`web.listen` set to `internal` keeps it to the internal network. Caddy serves it over plain HTTP
as well as HTTPS (ADR-21), so on the plain HTTP port the passwords of `/auth` and the tokens
cross the internet unencrypted. A change of `web.listen` takes effect with the next run of setup,
which writes the firewall rules. `/` and `/status` have no authentication, which is acceptable because they are
read only and show no configuration. It runs as root, because `swanctl` and `wg` need it, with `NoNewPrivileges`,
`ProtectSystem=strict`, `ProtectHome` and `PrivateTmp`. The Tailwind style comes from a CDN, so a
browser on a network without internet shows the unstyled page, and `curl` is unaffected.
@@ -259,9 +258,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
@@ -347,7 +346,10 @@ lockout. A Ubuntu Linux Manager signs all its users in from one address.
Decision: The default password policy locks an account for 15 minutes after 5 failed binds
within 15 minutes; a successful bind clears the count; `linux-manager-user unlock` and
`POST /users/<name>/unlock` end a lockout and clear the count, and leave a disabled user disabled.
`/auth` answers the same 401 for a wrong name, password or code and for a locked or disabled
The count, `pwdFailureTime`, is NO-USER-MODIFICATION in the ppolicy schema, so the unlock is sent
with the Relax Rules control (`1.3.6.1.4.1.4203.666.5.12`), which slapd honours for the user
manager account; deleting `pwdAccountLockedTime` alone would leave the failures counted, and the
next wrong password would lock the account again. `/auth` answers the same 401 for a wrong name, password or code and for a locked or disabled
user. `/auth` and `/auth/refresh` allow 10 calls a minute per client address, counted in memory,
and answer 429 with `Retry-After` beyond that. The client address is the peer, or the last
`X-Forwarded-For` entry for a peer in `web.trusted_proxies`, by default the address the call came
@@ -518,41 +520,56 @@ needs the next code. Changing the password revokes the user's refresh tokens, so
Manager session ends with its access token. An enrolled user who has lost the authenticator
needs an administrator.
## ADR-21: Caddy from the Ubuntu archive serves HTTPS with a certificate from Let's Encrypt
## ADR-21: Caddy from the Ubuntu archive serves every HTTP and HTTPS port, the services listen on loopback
Status: Accepted
Context: The status web service and the Manager are reachable from the internet (ADR-2),
and `/auth` and the Manager's sign-in carry passwords. Both are small servers on the standard
library's `http.server`, which would need certificates, their renewal and a TLS setup of their
own. Browsers trust a public CA, not the server's.
own. Browsers trust a public CA, not the server's; a server off the internet, or of an
organisation with a PKI of its own, cannot use a public CA. Caddy is needed for HTTPS anyway, and
one front for plain HTTP and HTTPS keeps one place where the server's ports, the redirect to HTTPS
and the client's address are decided.
Decision: Caddy, the `caddy` package of the Ubuntu archive, is the HTTPS proxy. While
`https.enabled` is `true` (the default) and `wan.local_fqdn` is set, `linux-manager-setup` writes
`/etc/caddy/linux-manager.Caddyfile`: a site for `wan.local_fqdn` on `https.web_port` (7444) for the
web service and, while the Manager is installed, one on `https.manager_port` (7443) for
the manager, each passing calls to the service on `127.0.0.1`. Caddy obtains and renews the
certificate from Let's Encrypt with the HTTP challenge on port 80, which the firewall opens on
the external interface; `auto_https disable_redirects` keeps port 80 to the challenge. The
package's drop-in for `caddy.service` points it at that file and keeps it from starting before
the file exists, so `/etc/caddy/Caddyfile`, a configuration file of the `caddy` package, is left
unchanged. Both services always listen on `127.0.0.1` as well as on the interfaces their
`listen` settings name, and trust `X-Forwarded-For` from it, which Caddy sets from the peer and
never takes from the client. Let's Encrypt issues at most 5 certificates a week for the same
names, which routers rebuilt for tests reach; `https.acme_staging` sets Caddy's global `acme_ca`
to Let's Encrypt's staging directory, which replaces Caddy's default CAs for every site, so no
test certificate comes from a production CA. `PUT /https/settings` changes `acme_staging` alone:
Decision: Caddy, the `caddy` package of the Ubuntu archive and a dependency of the package
(ADR-31), serves every HTTP and HTTPS port of the server's services. The web service listens on
`127.0.0.1:7091`, the Manager on the server on `127.0.0.1:7090`, the metrics service on
`127.0.0.1:9474` and rclone's WebDAV on `127.0.0.1:7446`, and Caddy calls them there. Once the
server is configured, `linux-manager-setup` writes `/etc/caddy/linux-manager.Caddyfile`: plain
HTTP sites on `web.port` (7081), the Manager's `port` (7080) and, while metrics are on,
`metrics.port` (9464), on every address; and always sites for the HTTPS names (ADR-65) on
`https.web_port` (7444), `https.manager_port` (7443), `metrics.https_port` (9465) and
`sites.webdav_port` (7445). Unless `https.disable_auto_redirect` is set, both plain HTTP sites
redirect (308) a request for an HTTPS name to the same host on HTTPS, and the Manager's redirects
every other request to the first HTTPS name; the status page stays on plain HTTP by address, so
monitors and clients that do not trust the server's certificate keep reaching it, and `/pki/`
stays on plain HTTP on both, where the certificates name it. The `listen` settings choose the interfaces the firewall opens each plain HTTP
port on, as Caddy listens on every address. The certificate comes from `https.certificate`
(ADR-60); with `acme`, Caddy obtains and renews it with the HTTP challenge on port 80, which the
firewall opens on the external interface then; `auto_https disable_redirects` keeps port 80 to the
challenge. The ACME CA is `https.acme_provider`, written as Caddy's global `cert_issuer`, so it is
also the CA of the web sites with `tls` `acme`: Let's Encrypt, ZeroSSL, whose issuer gets its EAB
credentials itself, or a custom directory with optional EAB. The package's drop-in for
`caddy.service` points it at that file and keeps it from starting before the file exists, so
`/etc/caddy/Caddyfile`, a configuration file of the `caddy` package, is left unchanged. The
services trust `X-Forwarded-For` from `127.0.0.1`, which Caddy sets from the peer and never takes
from the client, and the OpenID Provider answers only calls with `X-Forwarded-Proto: https`,
which Caddy sets on its HTTPS sites. Let's Encrypt issues at most 5 certificates a week for the
same names, which routers rebuilt for tests reach; with `letsencrypt`, `https.acme_staging` makes
the issuer's directory Let's Encrypt's staging one, so no test certificate comes from a
production CA. `PUT /https/settings` changes the certificate source and the ACME settings only:
the other settings of the section switch HTTPS off or move its ports, which would end the
connection the Manager makes the change on.
Consequences: HTTPS needs `wan.local_fqdn` in public DNS pointing at the server and port 80
reachable from the internet; until then Caddy retries and the HTTPS ports do not answer. The
certificate and the ACME account are in `/var/lib/caddy`. A router on the staging CA has a
certificate no client trusts. Plain HTTP stays as the `listen`
settings set it, so `internal` keeps passwords off the internet. Caddy's admin endpoint listens
on `localhost:2019`, which `caddy reload` uses. Port 80 and the HTTPS ports are not available
to Docker containers while HTTPS is on. The Manager's HTTPS port is a setting of the server, not
of the manager.
Consequences: HTTPS with a public ACME CA needs `wan.local_fqdn` in public DNS pointing at the
server and port 80 reachable from the internet; until then Caddy retries and the HTTPS ports do
not answer. The certificate and the ACME account are in `/var/lib/caddy`. A router on the staging
CA has a certificate no client trusts. A service that is not behind Caddy cannot be reached from
another host, so while Caddy is stopped, or before the first setup, only the bootstrap page
answers. The loopback ports are fixed, and no site or Docker container may take them or Caddy's
ports. Caddy's admin endpoint listens on `localhost:2019`, which `caddy reload` uses. The
Manager's HTTPS port is a setting of the server, not of the manager.
## ADR-22: Metrics are kept in PostgreSQL and served in the Prometheus format, pushed with OTLP
@@ -752,30 +769,37 @@ 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,
`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
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. Three are built in: `p2s` signs the server's VPN server certificate and the
users' certificates, `s2s` the site-to-site certificates, and `servers`, the Servers Issuing CA, mTLS
certificates with both the server and the client purposes, the server's HTTPS certificate among
them (ADR-60); the custom CAs of `pki.issuing_cas` sign what their templates allow, such as code
signing. The Manager shows all of them in one Issuing CAs tab. 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
`vpn-user` are issued by the server only, so no certificate for another use comes from the P2S
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,34 +807,40 @@ 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
## ADR-28: CA certificates and CRLs are always published over plain HTTP, and CRLs are short-lived
Status: Accepted
Context: Clients outside the server, such as Windows and servers using the general-purpose CAs,
find the issuer's certificate and the CRL through the AIA and CRL distribution point extensions,
and cache a CRL until its next update. The server's CRLs were valid for ten years and published
nowhere. Caddy serves files itself, and the web service already answers on the status port.
nowhere. Caddy fronts every web port of the server: the status web service's and the Manager's, over
plain HTTP and HTTPS. A client fetching an AIA certificate or a CRL may not follow a redirect, and
checking the revocation of an HTTPS server's certificate over HTTPS depends on itself.
Decision: `pki.publish` lists the endpoints, in the order the URLs appear in the certificates:
plain HTTP on the status port, served by the web service; plain HTTP on port 80, HTTPS on the
status HTTPS port and HTTPS on port 443, served by Caddy's `file_server`. The files are DER, as
RFC 5280 asks of these URLs, copied to `/var/lib/linux-manager/pki-publish`, outside the 0700 PKI
directory, so that Caddy's user reads them. Ports 80 and 443 serve only the CA files and are opened
on both interfaces when chosen. The CRLs of the issuing CAs are valid for `pki.crl_days`, a week
by default, signed again at every revocation and by a daily timer once half their validity has
passed; the root CRL has its own `pki.root_crl_days`, half a year by default, so an offline root
needs its CRL signed twice a year, not weekly.
Decision: the files are always published; there is no setting. Caddy's `file_server` serves them
at `/pki/` on `web.port` and on the Manager's port, ahead of the Manager's redirect to HTTPS, and
on `https.web_port` and `https.manager_port`, with the content types RFC 5280 gives. The
certificates name only the plain HTTP URLs: the status port while the status web service is
enabled, then the Manager's port, which always exists. The files are DER, copied to
`/var/lib/linux-manager/pki-publish`, outside the 0700 PKI directory, so that Caddy's user reads
them. The CRLs of the issuing CAs are valid for `pki.crl_days`, a week by default, signed again at
every revocation and by a daily timer once half their validity has passed; the root CRL has its own
`pki.root_crl_days`, half a year by default, so an offline root needs its CRL signed twice a year,
not weekly.
Consequences: A client that caches a CRL sees a revocation within a week. The URLs are fixed in a
certificate when it is signed, so a change of the endpoints or of `wan.local_fqdn` applies to
certificates signed afterwards. HTTPS URLs are offered for clients that cannot use plain HTTP,
although a client checking the revocation of the HTTPS server's own certificate cannot use them;
Caddy's certificate is Let's Encrypt's, so the server's endpoints do not depend on themselves.
Consequences: A client that caches a CRL sees a revocation within a week. A client tries the URLs
in order, so one that cannot reach the status port falls back to the Manager's. The files are
reachable where the firewall opens those ports: `web.listen` and the Manager's `listen` decide.
The URLs are fixed in a certificate when it is signed, so a change of the ports or of
`wan.local_fqdn` applies to certificates signed afterwards. A `pki.publish` of an earlier version
is left out when the settings are read.
## ADR-29: Site-to-site connections authenticate with a pre-shared key or certificates
@@ -850,34 +880,29 @@ 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
the place of revocation. An issuing CA waiting for the offline root has no ACME server.
## ADR-31: linux-manager-setup installs Caddy from the Ubuntu archive or from Caddy's repository
## ADR-31: Caddy is a dependency of the package, from the Ubuntu archive
Status: Accepted
Context: Caddy 2.6.2 of the Ubuntu archive lacks later features, such as a pki root without its key
and the settings of the ACME server. Caddy's own repository has current versions of the package of
the same name. A dependency on `caddy` installs the archive's package with `linux-manager`. apt cannot
run inside `linux-manager-setup` when the package's installation runs setup, as dpkg holds its lock.
Context: Caddy fronts every HTTP and HTTPS port of the server (ADR-21), so the server's services
cannot be reached without it. Caddy 2.6.2 of the Ubuntu archive lacks later features, such as a
pki root without its key and the settings of the ACME server; Caddy's own repository has current
versions, but a third-party repository, its key and a version that sorts above the archive's are
one more thing to keep and to trust.
Decision: `linux-manager` only suggests `caddy`. While HTTPS is on, setup has
`linux-manager-caddy.service` install it from `https.caddy_source`: `ubuntu`, or `upstream`, for
which the unit writes the deb822 source and the key it downloads over HTTPS from Caddy's
repository. The unit waits for dpkg's lock and runs setup again when Caddy is in place.
`linux-manager-caddy use-upstream` switches an installed router. Upstream's versions sort above the
archive's, so once the repository is configured apt keeps upstream's Caddy without a pin, and
`ubuntu` has no effect; nothing downgrades Caddy on its own, as a downgrade may break the
configuration and is the administrator's decision. Only the CLI switches the source; the
Manager shows which one is in effect.
Decision: `linux-manager` depends on `caddy`, which apt installs from the Ubuntu archive with the
package and upgrades with the system's packages. The package writes no repository of its own and
installs nothing at setup time, and the configuration uses only what Caddy 2.6.2 supports.
Consequences: The first setup run with HTTPS starts the installation and serves HTTPS on the run
that follows it. The key of Caddy's repository is trusted as downloaded over HTTPS, the way Caddy's
installation instructions do it. Going back to the archive's Caddy is a manual downgrade.
Consequences: Features of later Caddy versions are not available until the archive has them. An
administrator who adds another repository with a `caddy` package gets that version, which the
package does not check.
## ADR-32: The PKI is kept in the server's directory
@@ -1203,8 +1228,8 @@ and removal, every path resolved inside the site's folder. While `sites.webdav`
`linux-manager-webdav.service` runs `rclone serve webdav` on `127.0.0.1:7446` behind Caddy at
`https://<wan.local_fqdn>:<sites.webdav_port>`; its auth proxy, `webdav-auth`, binds as the user
and gives an admin all sites and any other user the sites of its editors groups, one folder each.
rclone and PowerDNS are installed on demand from the archive by `linux-manager-install@<feature>`,
like Caddy.
rclone and PowerDNS are installed on demand from the archive by `linux-manager-install@<component>`
(ADR-57).
Consequences: Uploads and WebDAV use the directory's passwords, a TOTP code appended for an
enrolled user. rclone writes a WebDAV upload to its cache first and to the folder a few seconds
@@ -1214,45 +1239,46 @@ later. S3 and Azure Blob clients are not served.
Status: Accepted
Context: The server hosts authoritative domains as their primary, with a secondary name server, and
a domain can give the sites their records without a registrar change per site. The server's own
name, `wan.local_fqdn`, belongs to a domain of its own, wherever that is hosted. Ubuntu
has BIND, Knot and PowerDNS; only PowerDNS's gpgsql backend reads records
from PostgreSQL, so changes are rows, without zone files or reloads. systemd-resolved's stub holds
127.0.0.53 and 127.0.0.54, and the remote access clients' resolver answered on the external
addresses, the addresses an authoritative server needs. The clients reach the internal address
just as well, through the tunnel when it is in `local.cidrs` (ADR-43).
Context: The server hosts authoritative domains as their primary, with an optional secondary name
server, and a domain can give the sites their records without a registrar change per site. The
server's own name, `wan.local_fqdn`, belongs to a domain of its own, wherever that is hosted. Ubuntu
has BIND, Knot and PowerDNS; only PowerDNS's gpgsql backend reads records from PostgreSQL, so
changes are rows, without zone files or reloads. systemd-resolved's stub holds 127.0.0.53 and
127.0.0.54, and the remote access clients' resolver answered on the external addresses, the
addresses an authoritative server needs. The clients reach the internal address just as well,
through the tunnel when it is in `local.cidrs` (ADR-43).
Decision: While `dns.enabled` is true, setup runs `pdns.service` with
`/etc/powerdns/pdns.d/linux-manager.conf`, written before the packages are installed, on the
addresses of `dns.listen`, with the gpgsql backend on the database `linux-manager-dns` and PowerDNS's
own schema, and `primary=yes`. The domains and their manual records are rows of the server's tables
in that database, like the sites in `linux-manager-sites`, not settings of `linux-manager.json`: they are
many and change through the web service. The name servers are settings, the same for every domain:
`wan.local_fqdn`, the server's one name, is the primary, and `dns.secondary` the secondary. Setup
writes each domain as a MASTER zone through the procedure `dns_apply` of
`/usr/share/linux-manager/sql/dns.sql`: SOA with `wan.local_fqdn`, NS of `wan.local_fqdn` and
`dns.secondary`, an A or AAAA record of every host name of a site with `dns` `router` whose closest
domain it is, with the server's address the site chooses (`wan.public_address`, the internal or the
external interface's), and the manual records; the serial grows only when the records change, which
makes PowerDNS notify. `wan.local_fqdn` gets no record in the domains: its A record is in the DNS of
its own domain, which the server does not manage. A site of `dns` `user` gets no records, as its
names are served elsewhere. The addresses `dns.secondary` resolves to at each run go to every
domain's `ALSO-NOTIFY` and `ALLOW-AXFR-FROM` metadata, so the global `allow-axfr-ips` stays the
loopback default. The public address is a setting, since the server sees only private addresses on
its interfaces behind a cloud's NAT and resolving `wan.local_fqdn` would answer from its own DNS
when it hosts that name. `dns.nameserver` and `dns.addresses` of an earlier configuration are left
out when it is read, so that it loads; a missing `dns.secondary` makes setup warn, not fail, so that
a router keeps running until it is set. A host name belongs to its closest domain only, and a
domain inside another is delegated from it with NS records, so a name is never answered by two
zones. The remote access clients' resolver answers on the addresses of the setting
`p2s.dns_listen`, by default the internal one; a `dns.listen` that shares an interface with it is
refused while P2S or OpenVPN is enabled.
addresses of `dns.listen`, with the gpgsql backend on the database `linux-manager-dns` and
PowerDNS's own schema, and `primary=yes`. The domains and their manual records are rows of the
server's tables in that database, like the sites in `linux-manager-sites`, not settings of
`linux-manager.json`: they are many and change through the web service. The name servers are
settings, the same for every domain: `wan.local_fqdn`, the server's one name, is the primary, and
`dns.secondary` the secondary, which is optional: without it the domains have the primary as their
only name server, as a small or internal deployment has no second server to name. Setup writes each
domain as a MASTER zone through the procedure `dns_apply` of `/usr/share/linux-manager/sql/dns.sql`:
SOA with `wan.local_fqdn`, NS of `wan.local_fqdn` and `dns.secondary` while it is set, an A or AAAA
record of every host name of a site with `dns` `router` whose closest domain it is, with the
server's address the site chooses (`wan.public_address`, the internal or the external interface's),
and the manual records; the serial grows only when the records change, which makes PowerDNS notify.
`wan.local_fqdn` gets no record in the domains: its A record is in the DNS of its own domain, which
the server does not manage. A site of `dns` `user` gets no records, as its names are served
elsewhere. The addresses `dns.secondary` resolves to at each run go to every domain's `ALSO-NOTIFY`
and `ALLOW-AXFR-FROM` metadata, so the global `allow-axfr-ips` stays the loopback default. The
public address is a setting, since the server sees only private addresses on its interfaces behind a
cloud's NAT and resolving `wan.local_fqdn` would answer from its own DNS when it hosts that name.
`dns.nameserver` and `dns.addresses` of an earlier configuration are left out when it is read, so
that it loads. A host name belongs to its closest domain only, and a domain inside another is
delegated from it with NS records, so a name is never answered by two zones. The remote access
clients' resolver answers on the addresses of the setting `p2s.dns_listen`, by default the internal
one; a `dns.listen` that shares an interface with it is refused while P2S or OpenVPN is enabled.
Consequences: The domains follow the sites at each setup run. Transfers are authorized by the
address the secondary's name resolves to, without TSIG, and there is no DNSSEC; the delegation of
each domain, with glue for the name servers inside it, is made at its parent zone by hand. Every
domain has the same two name servers.
domain has the same name servers, the primary alone without a secondary, which is not the redundancy
the DNS asks of public zones.
## ADR-43: The remote access clients' resolver is dnsmasq, not systemd-resolved
@@ -1387,19 +1413,30 @@ one line with its type and message.
Consequences: The logs hold one line per failure, without its stack. A failure that reaches the
last line of defence is found by its message and fixed where it occurs, with its own handling.
## ADR-49: A changelog summary is a paragraph wrapped at 80 columns
## ADR-49: CHANGELOG.md is the history, and debian/changelog is written from it by the build
Status: Accepted
Context: The summary of an entry of `debian/changelog` is the commit message of its release,
which `release.py` reads from the changelog. Summaries are often longer than the 80 columns
Debian's tools expect of a changelog line.
Context: The history of the package is also the source of each release's commit message and tag:
`release.py` commits with the summary of the newest entry and tags its version. A Debian changelog
needs a package name, a maintainer, an RFC 2822 date and lines of at most 80 columns in every entry,
which a history written by hand gets wrong and which repeat in every entry. Summaries are often
longer than one line.
Decision: The summary is the entry's first paragraph, indented by two spaces and wrapped at 80
columns. `release.py` joins its lines with single spaces into the commit message.
Decision: `CHANGELOG.md` at the repository's root is the only history kept by hand. An entry is a
`## x.y.z` heading, a summary paragraph wrapped at 100 columns and `-` items; `release.py` writes
the release time into the heading, `## x.y.z - YYYY-MM-DD HH:MM:SS +ZZZZ`, when it commits the
entry, joining the summary's lines with single spaces into the commit message. `bin/changelog.py`
writes `debian/changelog` from it in the build image, with the package name and the maintainer of
`debian/control`, the time of the build for an entry without a date, and `DEB_VERSION` as the
newest entry's version for a dev build. `x.y.z` is the Debian version `x.y.z-1`, and `x.y.z-n` is
itself. `debian/changelog` is not kept in the repository.
Consequences: The commit message is one line however the summary is wrapped, so a summary
rewrapped later still matches the commit of its release.
Consequences: The commit message is one line however the summary is wrapped, so a summary rewrapped
later still matches the commit of its release, and an entry with a date in its heading is
released. Every entry of the generated `debian/changelog` has the current package name and
maintainer, also the entries made under the package's earlier name. The builder image has Python
for the script.
## ADR-50: The help is Markdown rendered in the browser, in a panel that pushes the page
@@ -1452,7 +1489,7 @@ Status: Accepted
Context: With `terraform_dir`, the manager built `http://<router_private_ip_addresses.int>:7081`.
The port of the server's web service is `web.port` and the interfaces it listens on are `web.listen`,
which the platform sets from its variables; the manager that `dev.sh` runs on a workstation cannot read them.
which the platform sets from its variables; the manager that `dev.py` runs on a workstation cannot read them.
Decision: `router_url` is the output `router_web_url` of the platform, which derives the URL from
the same variables that configure the server.
@@ -1518,7 +1555,7 @@ system against a stored light or dark choice.
Consequences: A page in the dark theme is dark from its first paint. The script depends on the
storage key and class names of MUI's defaults, which `colorSchemeSelector: 'class'` uses.
## ADR-56: One package, linux-manager, installs every component
## ADR-56: One package, linux-manager, with the software of its components installed on demand
Status: Accepted
@@ -1529,49 +1566,62 @@ creates its first administrator, Caddy proxies it and the status reports it. Pac
own would pin each other's versions, and a change of the server's API would need several
repositories and changelogs.
Decision: One package, `linux-manager`, installs every component, the Manager included. The
router and the VPN are switched on in the configuration (ADR-57), not by installing packages. The
Decision: One package, `linux-manager`, holds every component, the Manager included. The software
the installable components need, the VPN, the router, the name server and WebDAV, is installed from
the Ubuntu archive when the component is switched on (ADR-57), and the package only suggests it. The
programs are in `/usr/lib/linux-manager`, the Manager's application and help in
`/usr/share/linux-manager/manager`, the settings and secrets in `/etc/linux-manager`
(`linux-manager.json`, `manager.json`, `manager-database.secret`, `manager-admin.json`) and the
state of the upgrades in `/var/lib/linux-manager`. The Manager's unit is
`linux-manager-ui.service`. The debconf questions of its first administrator are
`linux-manager/admin_username` and `admin_password`. The server's bootstrap page shows the
Manager, which has no bootstrap service of its own. `dev.sh` runs the Manager on a workstation,
Manager, which has no bootstrap service of its own. `dev.py` runs the Manager on a workstation,
with `terraform_dir` and `bind`.
Consequences: The repository holds the Manager's `web/` and `docs/`, and its build runs from the
root. A server that runs neither the router nor the VPN still has their programs and
dependencies installed.
root. A server has the programs of the components it has switched on, and keeps them when a
component is switched off.
## ADR-57: The router and the VPN are components switched in the configuration
## ADR-57: The installable components are switched on the System tab and installed on demand
Status: Accepted
Context: The server is used without its routing and VPN features, as a directory, PKI and web
server on one network interface. Routing between two interfaces and site-to-site IPsec need two
interfaces; remote access needs only one, if its clients reach the server's networks from the
server's own address.
interfaces; remote access works with one or two, its clients reaching the server's networks from
the server's own address with one. A component needs its software installed and its setup run, so
switching one only in the configuration file left the Manager unable to reach it.
Decision: `router.enabled` and `vpn.enabled`, both false by default, switch the two components.
With the router off, `site_to_site` must be empty, only `interfaces.external` is used, and it is
also the internal side of the services' `listen` choices; no route, forward rule or `rp_filter`
setting is written. With the VPN off, `p2s.enabled`, `openvpn.enabled` and `wireguard.enabled`
must be false, users get no VPN certificate, WireGuard peers and VPN profiles are refused, and the
Manager hides the Remote Access page. With the router off and the VPN on, setup masquerades each
ready VPN pool out of the external interface, so the clients reach `local.cidrs` from the
server's address. `linux-manager-setup` writes `/etc/sysctl.d/99-linux-manager.conf` while
either component is on: forwarding for both, a loose `rp_filter` for the router; it removes the
file while both are off and leaves the running values alone, as Docker also needs forwarding. The
built-in issuing CAs follow their component: `p2s` the VPN and `s2s` the router; they are created
when their component is first switched on and kept when it is switched off. Switching the VPN on
issues a certificate to each VPN user that has none. The firewall is written once any core
listener (web, HTTPS, metrics, DNS, sites) or component is configured; the IPsec rules only while
site-to-site or IKEv2 is ready.
Decision: The installable components are the VPN (`vpn.enabled`), the router (`router.enabled`),
the name server (`dns.enabled`) and WebDAV (`sites.webdav`), listed with their packages in
`linuxmanager.COMPONENTS`; all are off by default. The Manager's System tab switches them through
`PUT /components/<name>`, and shows whether their packages are installed, being installed or failed
(`GET /components`). While a component is on and any of its packages is missing, or marked as
installed automatically, which `apt autoremove` would remove, setup starts
`linux-manager-install@<component>`, whose `apt-get install` marks them as installed by hand and
runs setup again; until then the component's readiness checks are false. Switching a component off
removes no package. The router is offered only while the server has a network interface besides
the external one, and switching it on takes the internal interface and, in `manual` mode, its
address and gateway, as the installer asks them. With the router off, `site_to_site` must be empty,
only `interfaces.external` is used, and it is also the internal side of the services' `listen`
choices; no route, forward rule or `rp_filter` setting is written. With the VPN off,
`p2s.enabled`, `openvpn.enabled` and `wireguard.enabled` must be false, users get no VPN
certificate, WireGuard peers and VPN profiles are refused, and the Manager hides the Remote Access
page. With the router off and the VPN on, setup masquerades each ready VPN pool out of the external
interface, so the clients reach `local.cidrs` from the server's address. `linux-manager-setup`
writes `/etc/sysctl.d/99-linux-manager.conf` while the router or the VPN is on: forwarding for
both, a loose `rp_filter` for the router; it removes the file while both are off and leaves the
running values alone, as Docker also needs forwarding. The built-in issuing CAs follow their
component: `p2s` the VPN and `s2s` the router; they are created when their component is first
switched on and kept when it is switched off. Switching the VPN on issues a certificate to each VPN
user that has none. The firewall is written once any core listener (web, HTTPS, metrics, DNS,
sites) or component is configured; the IPsec rules only while site-to-site or IKEv2 is ready.
Consequences: A core-only server needs one interface and gets its firewall at its first setup
run. The readiness checks (`routing_ready`, `s2s_ready`, `p2s_ready`, `wg_ready`,
`openvpn_ready`) carry the switches, so every consumer of them follows the components.
Consequences: A core-only server needs one interface, has none of the components' software, and
gets its firewall at its first setup run. A component switched on is served once its packages are
installed, a minute or so later. The readiness checks (`routing_ready`, `s2s_ready`, `p2s_ready`,
`wg_ready`, `openvpn_ready`) carry the switches and the installation, so every consumer of them
follows the components.
## ADR-58: Manual tests get numbered dev builds from a signed apt repository in a test project
@@ -1582,17 +1632,225 @@ 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 `LXD_DEV_BUILD_SERIAL` of
`.lm-dev-config/settings.json`, 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 project also
has a Vault, through which secrets reach its instances (ADR-61). The scripts keep their state in
`.lm-dev-config/`, which outlives clean-ups of `tmp/`. 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
which sorts above all of its `~dev` builds, is an update of them all. `CHANGELOG.md` 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.
## ADR-60: A certificate of the server other than ACME's is kept in the directory, with a self-signed fallback
Status: Accepted
Context: A server whose certificate comes from no ACME CA needs one made by the server, one of its
own PKI, or one of another CA, given as a certificate signed for a CSR or as a PFX file with its
key. Caddy takes a certificate file and its key per site. The server's other certificates and
keys are in its directory (ADR-32), which every backup holds.
Decision: `https.certificate` is `acme`, `self-signed`, `ca` or `external`. With `ca` the
certificate is a router certificate of the built-in Servers Issuing CA, `servers`, with the template
`mtls`, issued and renewed as the VPN server's is. A self-signed or imported certificate, with its
chain and key, a pending CSR and that CSR's key, are the entry `cn=https,ou=pki`, of the class
`linuxManagerHostCertificate`; the keys are unreadable to every account but root's socket. An
import must be for the CSR's key, or the PFX's own, be valid and name `wan.local_fqdn`, directly or
with a wildcard. While the chosen certificate is not available, such as before an import or while
`servers` waits for an offline root, the server makes a self-signed certificate and serves it, with a
warning, so that no ACME CA is asked unasked. Setup writes the served certificate and key to
`/etc/caddy/linux-manager-https/`, group `caddy`, and the server's site blocks name them; when
they cannot be read, the Caddyfile is left as it is.
`https.certificate` is `self-signed` when the configuration does not set it, as in most
appliances, and ACME is used only when it is set to `acme`: a public name that resolves to the
server and port 80 reachable from the internet are rarely ready when a server is installed. The
file a new installation writes has it empty, and that installation's first setup chooses it and
writes it into the file: `ca` when the Servers Issuing CA has its certificate after the PKI is
provisioned, as with a root the server creates, else `self-signed`. Until a setup run has
succeeded, a file that does not set it is taken as empty, so a configuration written by hand or by
a tool in place of the installer's file gets the same choice. An upgrade makes no choice: a
configuration that names a source keeps it, and once a run has succeeded, one that names none is
self-signed. `https.disable_auto_redirect`, an installer question, is always respected; it keeps
Caddy's plain HTTP sites from redirecting to HTTPS (ADR-21).
Consequences: A browser trusts a self-signed certificate, or one of the server's PKI, only once
its user trusts it or the root. An imported certificate is not renewed by the server, which warns
before it expires. The certificate follows the server in a backup with the PKI.
## ADR-61: Test instances read secrets from the project's Vault with an AppRole of their own
Status: Accepted
Context: The test scripts give the instances they make secrets: the admin password, pre-shared
keys, passwords of test users, OpenVPN profiles and TOTP secrets. A secret passed as a command-line
argument of `lxc exec` is visible in `ps` and `/proc/<pid>/cmdline` on both ends and can reach
logs; standard input and files assembled on the Mac are better, but the tooling is to show a
correctly designed mechanism, not a shortcut, even for a lab. A wrapping token per secret, with a
template and the helper pushed each time, made every hand-over several uploads.
Decision: Every project the scripts use has a HashiCorp Vault, a container with file storage and a
plain HTTP listener, initialised with one key share and unsealed by the scripts over its API; its
unseal key and root token stay on the Mac in `.lm-dev-config/` (0700, files 0600). Every instance
that can reach it gets, once, an AppRole named after it: a policy that reads `kv/data/<name>/*` and
creates the TOTP keys `totp/keys/<name>-*`, batch tokens of 5 minutes, and a secret ID that lives
as long as the instance. The role ID and a response-wrapped secret ID go to `/etc/vault` with the
helper `lm-dev-vault`, which refuses a token that does not wrap the role's `secret-id` request and
unwraps it once. A file that holds a secret is stored whole in KV by the Mac and written by the
instance with its own login, so a hand-over is one KV write and one `lxc exec`, and no argument of
any process is a secret. A TOTP key is generated by the Vault for the instance's own token, so its
secret is held by the Vault and the VM only, and the scripts read the codes from the Vault. A
secret an instance makes for itself, such as a WireGuard client key, does not leave it. The
manual-test project's Vault is reached by the Mac through a network forward, the automated run's
through a proxy on the LXD host's address; plain HTTP is accepted on the lab's LAN.
Consequences: Creating an instance needs the project's Vault, made before any other instance, and
a restarted Vault container is unsealed with `lm-dev-lxd-project.py vault unseal`. An instance's
root can read that instance's secrets for its whole life; removing a VM deletes its role, policy,
secrets and TOTP keys. A wrapping token that is intercepted and used first is noticed, as the
instance's `init` then fails. Hosts of the lab's isolated LANs have no route to the Vault and get no
AppRole. The secrets of a project stay readable with the root token until the project's Vault is
removed.
## ADR-62: The name of a CA is fixed once the CA has its certificate or CSR
Status: Accepted
Context: A CA gets its common name from the configuration when the server makes its certificate or
its CSR, and never again; a name changed afterwards changed the configuration only, so the
configuration and the CA disagreed without a word. A certificate's issuer must be its CA's subject,
so a renamed CA is a new CA, and every certificate it issued would have to be issued again: the
server can do that for its own certificates and its VPN users, but not for certificates issued from
a CSR, such as those of site-to-site peers and mTLS clients, and with an external root the new CA
waits for a signature made elsewhere. The first setup, run at installation before the web UI can be
reached, makes the root and the Servers CA; the P2S and S2S CAs wait until the VPN and the router
are switched on, and a custom CA is made when it is added.
Decision: Setup refuses `pki.root_name`, for a root the server created, and the name of each issuing
CA when it differs from the common name of the CA's certificate, or of its CSR while it waits for
one. `linux-manager-ca ca import` refuses an issuing CA certificate whose common name differs from
its CSR's. The PKI settings dialog shows the P2S and S2S names only, editable until their CA has a
certificate or a CSR; the root and Servers CA names are not shown, and the issuing CA dialog shows
the common name of an existing CA without editing it. A CA under another name is added as a new
custom CA, which retires nothing until the old one is removed.
Consequences: A name changed by hand in the configuration of a server whose CA exists makes setup
fail until the name is put back. The built-in CAs cannot be renamed; replacing one, with its
certificates issued again, would be a feature of its own.
## ADR-63: A run of setup in progress runs once more instead of being restarted
Status: Accepted
Context: `linux-manager-setup` is a oneshot unit that applies the configuration in many steps, such
as writing and reloading the firewall rules, the VPN and the routes. The Manager, the package's
commands, a restore and the installation of a component all apply their change by having setup run.
`systemctl restart` of a oneshot unit that is still activating kills the run, which leaves the steps
it had not reached to the next run, and until that run the server is half configured. Components
installed on demand made such overlaps common: the installation asks for a run while the run that
started it, or one asked for by the Manager, is still going.
Decision: Every caller asks for a run with `linuxmanager.request_setup`. A run holds the lock
`/run/linux-manager/setup.running` while it works. A request creates
`/run/linux-manager/setup.request` and restarts the unit only when no run holds that lock; otherwise
the run in progress runs once more when it ends, however many requests came during it. The request,
and a run's check of the file before it ends, are both made under `/run/linux-manager/setup.lock`,
and a run keeps that lock until its process ends, so a request either comes before the check or
finds no run. A caller that waits, `linux-manager-config-edit apply` or a restore, waits for
the unit's job to end and reads its result. The package's postinst still restarts the unit, as a run
of the previous version is to be replaced by one of the new.
Consequences: A change made during a run is applied by the extra run that follows it, not at once.
A plain `systemctl restart linux-manager-setup` still kills a run in progress; the documentation
names `linux-manager-config-edit apply` instead. A run that fails runs once more when a request came
during it, and the unit's result is that of the last run.
## ADR-64: The schema is two LDIF files, and the PKI part is a schema of its own
Status: Accepted
Context: An application other than Linux Manager, such as Simple CA, is to keep its CAs in OpenLDAP
in Linux Manager's PKI classes, either on the server's own slapd or on a slapd without Linux
Manager. The second needs the PKI's definitions as a file its administrator can load, without the
account, OpenID Provider and role classes. The first needs an account other than root that may
read and write the keys, which no account could.
Decision: The schema is defined only in two LDIF files of `/usr/share/linux-manager/schema/`, in the
form `ldapadd` loads into `cn=config`: `linux-manager-pki.ldif` (`cn=linux-manager-pki`), the CAs,
the certificates and the host certificates, which needs only the core schema, and
`linux-manager.ldif` (`cn=linux-manager`), the rest. Setup loads each into its own schema entry, the
same way a slapd without Linux Manager loads the PKI file. A certificate may name what it is filed
under with `linuxManagerCertificateName`, which Linux Manager does not set. The members of the group
`pki-managers` may manage `ou=pki` with its keys; an application binds as a service account in that
group. On a slapd without Linux Manager, access is that slapd's administrator's business.
Consequences: One file serves both kinds of slapd, so the definitions cannot drift apart. The group
is an ordinary one, made with its first member; until it exists, only root reads the keys, and
renaming it takes the access away. A server whose slapd holds the PKI definitions inside
`cn=linux-manager` is installed anew, as slapd refuses the same OIDs in a second entry.
## ADR-65: HTTPS is always on, for wan.local_fqdn or the host name, with IP addresses on request
Status: Accepted
Context: The status page and the Manager carry passwords, so they are to be served over HTTPS on
every server; only the redirect from plain HTTP is a choice, for labs and development, where the
name of a server behind a forward is the only way to reach it. A server without `wan.local_fqdn`,
such as the first device of a network without DNS, still needs a name for its certificate, and an
appliance that is set up by address needs a certificate that names its address.
Decision: HTTPS has no switch: `https.enabled` and the installer's question are gone, and a file
that still has the setting loads without it. The HTTPS names are `wan.local_fqdn` alone when it is
set, else the host name and `<host name>.local`, which Avahi announces with mDNS on the internal
side while there is no FQDN. `https.ip_sans`, off by default, adds the server's addresses to the
self-signed certificate and the Servers Issuing CA's, and Caddy then serves HTTPS on them too; an
ACME certificate names `wan.local_fqdn` only, which `acme` requires. Unless
`https.disable_auto_redirect` is set, a plain HTTP request for an HTTPS host is redirected to the
same host on HTTPS, on the status page's port and the Manager's; the status page stays on plain
HTTP by any other address, and `/pki/` stays on plain HTTP. A certificate whose names or addresses
differ from the current ones is made or issued again at the next setup, so a changed DHCP address
is followed. As Caddy always listens, the firewall is always set up.
Consequences: A browser warns about a self-signed certificate, or one of the server's PKI, until
its user trusts it or the root; one reached by address warns unless `https.ip_sans` is on. A server
whose addresses change gets a new certificate at each change while `https.ip_sans` is on. Avahi is
a dependency, running only while there is no FQDN; it sends its announcements on every interface,
and the firewall lets queries in on the internal side only.
+1433
View File
File diff suppressed because it is too large. Load diff
+6 -4
View File
@@ -12,21 +12,23 @@ FROM ubuntu:${UBUNTU_VERSION}
ARG HOST_UID
ARG HOST_GID
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
RUN apt-get -o Acquire::Retries=5 update \
&& DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 install -y --no-install-recommends \
build-essential \
dpkg-dev \
debhelper \
lintian \
python3 \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /build
COPY debian-package/ src/
COPY docs/ src/docs/
COPY --from=web /web/dist src/web/dist/
# DEB_VERSION, when set, replaces the version of the newest changelog entry in the image only.
# debian/changelog is written from CHANGELOG.md; DEB_VERSION, when set, is the version of its newest entry.
COPY CHANGELOG.md bin/changelog.py ./
ARG DEB_VERSION
RUN if [ -n "$DEB_VERSION" ]; then sed -i "1s/([^)]*)/($DEB_VERSION)/" src/debian/changelog; fi
RUN python3 changelog.py CHANGELOG.md src/debian/control src/debian/changelog ${DEB_VERSION:+--version "$DEB_VERSION"}
RUN cd src && dpkg-buildpackage -us -uc -b
RUN lintian --no-tag-display-limit /build/*.changes || true
+33 -2
View File
@@ -162,7 +162,10 @@ Table of Contents
6.2. LDAP Attribute Types
Every attribute type below has the status active, was allocated on
2026-11-21, and is defined in "linuxmanager_ldap.py" of this
2026-11-21 unless its entry gives another date, and is defined in
"linux-manager-pki.ldif" (the PKI: .2.1.2 to .2.1.12 and .2.1.24 to
.2.1.28) or "linux-manager.ldif" (the others) in
"debian-package/src/usr/share/linux-manager/schema/" of this
repository.
.2.1.1 linuxManagerScope
@@ -236,10 +239,34 @@ Table of Contents
.2.1.23 linuxManagerResourceScope
A scope of a resource of the OpenID Provider
.2.1.24 linuxManagerToken
The Simple CA token that signs the issuing CAs
Allocated: 2026-11-23
.2.1.25 linuxManagerUpstreamName
The Simple CA issuing CA of the token
Allocated: 2026-11-23
.2.1.26 linuxManagerCertificateChain
A certificate and its chain, PEM
Allocated: 2026-11-24
.2.1.27 linuxManagerRequestKey
The private key of a CSR, PEM
Allocated: 2026-11-24
.2.1.28 linuxManagerCertificateName
The name a certificate is filed under by the application
that keeps it
Allocated: 2026-11-24
6.3. LDAP Object Classes
Every object class below has the status active, was allocated on
2026-11-21, and is defined in "linuxmanager_ldap.py" of this
2026-11-21 unless its entry gives another date, and is defined in
"linux-manager-pki.ldif" (.2.2.2, .2.2.3 and .2.2.5) or
"linux-manager.ldif" (.2.2.1 and .2.2.4) in
"debian-package/src/usr/share/linux-manager/schema/" of this
repository.
.2.2.1 linuxManagerAccount
@@ -254,6 +281,10 @@ Table of Contents
.2.2.4 linuxManagerRole
Structural: a role of a resource of the OpenID Provider
.2.2.5 linuxManagerHostCertificate
Structural: a certificate of the server kept with its key
Allocated: 2026-11-24
7. Requesting an OID
An allocation is a change to this document. The change adds an
+472 -253
View File
File diff suppressed because it is too large. Load diff
+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""Read CHANGELOG.md and write debian/changelog from it: changelog.py CHANGELOG CONTROL OUTPUT [--version V].
CHANGELOG.md is the history of the package. Its entries, newest first, are "## VERSION" headings,
"## VERSION - YYYY-MM-DD HH:MM:SS +ZZZZ" once released, each followed by a summary paragraph and
"- " items whose continuation lines are indented by two spaces; an older entry may have items only.
VERSION x.y.z is the Debian version x.y.z-1, and x.y.z-n, n from 2, is x.y.z-n.
The command writes OUTPUT in Debian's format: the package name (Source) and the maintainer
(Maintainer) of the debian/control CONTROL, the summary and the items wrapped at 80 columns, and the
entry's date, the current time for an entry without one. --version replaces the Debian version of
the newest entry, as the dev builds do. A malformed CHANGELOG.md is a message on standard error and
the exit status 1.
"""
import argparse
import datetime
import email.utils
import pathlib
import re
import sys
import textwrap
#: The format of the date in a heading.
DATE_FORMAT = '%Y-%m-%d %H:%M:%S %z'
#: A heading: its version, and its date once the entry is released.
HEADING = re.compile(r'## (\d+\.\d+\.\d+(?:-\d+)?)(?: - (\d{4}-\d\d-\d\d \d\d:\d\d:\d\d [+-]\d{4}))?$')
def entries(text):
"""The entries of the CHANGELOG.md text, newest first: dicts of version, date (a datetime or None), summary (a
string or None), items (strings) and line, the index of the heading's line; ValueError when it is malformed."""
found = []
# Where the entry is: right after its heading, in its summary, after the summary, or in its items.
state = None
for index, line in enumerate(text.splitlines()):
if line.startswith('## '):
match = HEADING.match(line)
if not match:
raise ValueError(f'line {index + 1}: a heading is "## x.y.z" or "## x.y.z - {DATE_FORMAT}": {line}')
date = datetime.datetime.strptime(match.group(2), DATE_FORMAT) if match.group(2) else None
found.append({'version': match.group(1), 'date': date, 'summary': None, 'items': [], 'line': index})
state = 'heading'
elif state is None:
continue
elif not line.strip():
state = 'after' if state == 'summary' else state
elif line.startswith('- '):
found[-1]['items'].append(line[2:].strip())
state = 'items'
elif line.startswith(' ') and state == 'items':
found[-1]['items'][-1] += ' ' + line.strip()
elif state in ('heading', 'summary'):
found[-1]['summary'] = f'{found[-1]["summary"]} {line.strip()}' if state == 'summary' else line.strip()
state = 'summary'
else:
raise ValueError(f'line {index + 1}: neither a summary line, an item nor its continuation: {line}')
return found
def debian_version(version):
"""The Debian version of a CHANGELOG.md version: x.y.z-1 for x.y.z, x.y.z-n as it is."""
return version if '-' in version else f'{version}-1'
def wrapped(text, first, rest):
"""The text wrapped at 80 columns, its first line indented by first and the others by rest."""
return textwrap.fill(text, width=80, initial_indent=first, subsequent_indent=rest, break_long_words=False,
break_on_hyphens=False)
def debian(found, package, maintainer, version=None):
"""The debian/changelog of the entries, with the version as the newest entry's Debian version when given."""
blocks = []
for index, entry in enumerate(found):
number = version if index == 0 and version else debian_version(entry['version'])
date = entry['date'] or datetime.datetime.now().astimezone()
lines = [f'{package} ({number}) unstable; urgency=medium', '']
if entry['summary']:
lines += [wrapped(entry['summary'], ' ', ' '), '']
lines += [wrapped(item, ' * ', ' ') for item in entry['items']]
if entry['items']:
lines.append('')
lines.append(f' -- {maintainer} {email.utils.format_datetime(date)}')
blocks.append('\n'.join(lines) + '\n')
return '\n'.join(blocks)
def control_field(text, name):
"""The value of the field name of the source paragraph of the debian/control text."""
match = re.search(rf'^{name}:\s*(.+)$', text.split('\n\n', 1)[0], re.MULTILINE)
if not match:
raise ValueError(f'debian/control has no {name}')
return match.group(1).strip()
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('changelog', type=pathlib.Path, help='CHANGELOG.md')
parser.add_argument('control', type=pathlib.Path, help='debian/control')
parser.add_argument('output', type=pathlib.Path, help='the debian/changelog to write')
parser.add_argument('--version', help='the Debian version of the newest entry instead of its own')
args = parser.parse_args()
try:
found = entries(args.changelog.read_text(encoding='utf-8'))
control = args.control.read_text(encoding='utf-8')
if not found:
raise ValueError('no entry')
text = debian(found, control_field(control, 'Source'), control_field(control, 'Maintainer'), args.version)
except (OSError, ValueError) as error:
print(f'changelog.py: {args.changelog}: {error}', file=sys.stderr)
return 1
args.output.write_text(text, encoding='utf-8')
return 0
if __name__ == '__main__':
sys.exit(main())
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""Build the next numbered dev build and publish it to a test project's repository: lm-dev-build.py.
The serial N, the setting LXD_DEV_BUILD_SERIAL (lm_dev.setting, 0 by default), is that of the last
dev build; each build that succeeds writes its own, one higher, into .lm-dev-config/settings.json,
and release.py writes 0 there when it releases. The build's version is the Debian version of the
newest entry of CHANGELOG.md (bin/changelog.py) with ~devN before its revision, 0.41.0 (0.41.0-1)
becoming 0.41.0~dev7-1, so the release of that entry is newer than all its dev builds. ./build.py 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 (LXD_PROJECT, lm-dev by default)
made by lm-dev-lxd-project.py, and published there. The remote is the project's, read from
.lm-dev-config/lxd-project-PROJECT.json, so the script takes no --remote.
"""
import argparse
import json
import subprocess
import sys
import changelog
from lm_dev import PROJECT, ROOT, config_path, lxc_exec, save_setting, setting
CHANGELOG = ROOT / 'CHANGELOG.md'
CONTROL = ROOT / 'debian-package' / 'debian' / 'control'
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--project', default=setting('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 = config_path(f'lxd-project-{args.project}.json')
if not state_file.is_file():
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'))
try:
found = changelog.entries(CHANGELOG.read_text(encoding='utf-8'))
package = changelog.control_field(CONTROL.read_text(encoding='utf-8'), 'Source')
except ValueError as error:
sys.exit(f'{CHANGELOG}: {error}')
if not found:
sys.exit(f'{CHANGELOG} has no entry')
number = int(setting('LXD_DEV_BUILD_SERIAL', 0)) + 1
upstream, _, revision = changelog.debian_version(found[0]['version']).rpartition('-')
dev = f'{upstream}~dev{number}-{revision}'
print(f'building {package} {dev}')
if subprocess.run(['./build.py', '--build-arg', f'DEB_VERSION={dev}'], cwd=ROOT).returncode != 0:
sys.exit(f'the build of {dev} failed; the serial stays {number - 1}')
save_setting('LXD_DEV_BUILD_SERIAL', number)
# The dev build leaves out/ to out/dev/, so out/ keeps the release builds.
target = ROOT / 'out' / 'dev'
target.mkdir(exist_ok=True)
for artifact in (ROOT / 'out').glob(f'{package}_{dev}_*'):
artifact.replace(target / artifact.name)
deb = target / f'{package}_{dev}_all.deb'
if not deb.is_file():
sys.exit(f'the build made no {deb.name}')
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 = 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)')
if __name__ == '__main__':
main()
+319
View File
@@ -0,0 +1,319 @@
#!/usr/bin/env python3
"""Create or remove an LXD project for manual tests, its Vault, or its uplink: lm-dev-lxd-project.py
create|remove|vault|uplink.
uplink setup creates the physical uplink network once per remote, and uplink remove deletes it
(see uplink). vault create makes the project's Vault, vault unseal unseals it after a restart, and
vault remove deletes it (see vault_create).
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;
lm-dev-build.py publishes into it and lm-dev-vm.py installs from it. The container vault is the
project's Vault, made first, which the scripts hand secrets to the instances through; every other
instance gets an AppRole of its own in it and /etc/vault (lm_dev.enrol_instance). What they need is written
to .lm-dev-config/lxd-project-PROJECT.json, with the repository's key in
.lm-dev-config/lxd-project-PROJECT.gpg. remove deletes the project's instances, its networks, the
project and those files.
"""
import argparse
import json
import re
import subprocess
import sys
import time
from lm_dev import PROJECT, TESTS, VAULT_PORT, MissingSetting, VaultError, config_path, enrol_instance, lxc_exec, \
setting, vault_initialise, vault_state, vault_unseal
NETWORKS = ('wan', 'lana', 'lanb')
# The settings of the options of uplink setup, which have no defaults.
UPLINK_SETTINGS = {'parent': 'LXD_UPLINK_PARENT', 'gateway': 'LXD_UPLINK_GATEWAY', 'dns': 'LXD_UPLINK_DNS',
'ovn_ranges': 'LXD_UPLINK_OVN_RANGES', 'routes': 'LXD_UPLINK_ROUTES'}
def lxc(*args, project, check=True, input=None):
"""Run lxc with the arguments in the project; raise CalledProcessError when it fails, unless check is false."""
return subprocess.run(['lxc', *args, '--project', project], input=input, capture_output=True, text=True,
check=check)
def launch(args, name, user_data):
"""Launch the container with the cloud-init user data on the project's default profile, wait until it has booted
and has an address on eth0, and pin that address; the address."""
lxc('launch', args.image, f'{args.remote}:{name}',
'-c', 'cloud-init.user-data=' + (TESTS / 'cloud-init' / user_data).read_text(encoding='utf-8'),
project=args.project)
# cloud-init's status 2 is done with recoverable errors.
for _ in range(120):
if lxc_exec(args.remote, args.project, name, 'cloud-init', 'status', '--wait').returncode in (0, 2):
break
time.sleep(5)
else:
raise RuntimeError(f'the container {name} did not boot')
for _ in range(24):
match = re.search(r' inet (\d+\.\d+\.\d+\.\d+)/',
lxc_exec(args.remote, args.project, name, 'ip', '-4', '-o', 'addr', 'show', 'dev',
'eth0').stdout)
if match:
break
time.sleep(5)
else:
raise RuntimeError(f'the container {name} has no address on eth0')
lxc('config', 'device', 'override', f'{args.remote}:{name}', 'eth0', f'ipv4.address={match.group(1)}',
project=args.project)
return match.group(1)
def vault_forward(args):
"""The listen address of the forward of the project's Vault on wan, or None."""
listing = lxc('network', 'forward', 'list', f'{args.remote}:wan', '-f', 'json', project=args.project,
check=False)
if listing.returncode != 0:
return None
return next((forward['listen_address'] for forward in json.loads(listing.stdout) or []
if forward.get('config', {}).get('user.service') == 'vault'), None)
def vault_create(args):
"""Make the project's Vault: the container vault (cloud-init vault.yaml), a forward of its port on wan at
--vault-address or an allocated one, which the scripts reach it on, and its initialisation with one key share,
unsealed, with KV v2, TOTP and AppRole; its key and root token are kept in .lm-dev-config/vault-PROJECT.json;
the state."""
if vault_state(args.project) is not None:
raise RuntimeError(f'project {args.project} has a Vault; remove it with vault remove first')
print(f'launching the Vault container {args.remote}:vault (project {args.project})')
address = launch(args, 'vault', 'vault.yaml')
listen = [args.vault_address] if args.vault_address else ['--allocate=ipv4']
lxc('network', 'forward', 'create', f'{args.remote}:wan', *listen, 'user.service=vault', project=args.project)
forward = vault_forward(args)
if not forward:
raise RuntimeError('the forward of the Vault was not made')
lxc('network', 'forward', 'port', 'add', f'{args.remote}:wan', forward, 'tcp', str(VAULT_PORT), address,
str(VAULT_PORT), project=args.project)
state = vault_initialise(args.project, f'http://{forward}:{VAULT_PORT}', f'http://{address}:{VAULT_PORT}')
print(f'the Vault of {args.project} is at {state["url"]}, for the instances {state["internal_url"]}; '
f'state: {config_path(f"vault-{args.project}.json")}')
return state
def vault_remove(args):
"""Delete the project's Vault, its forward and its state; True when all went."""
ok = True
if lxc('info', f'{args.remote}:vault', project=args.project, check=False).returncode == 0:
result = lxc('delete', '--force', f'{args.remote}:vault', project=args.project, check=False)
if result.returncode != 0:
ok = False
print(f'could not delete vault: {result.stderr.strip()}', file=sys.stderr)
forward = vault_forward(args)
if forward:
lxc('network', 'forward', 'delete', f'{args.remote}:wan', forward, project=args.project, check=False)
if ok:
config_path(f'vault-{args.project}.json').unlink(missing_ok=True)
print(f'project {args.project} has no Vault')
return ok
def create(args, state, key):
"""Create the project with its networks and default profile, the Vault and the repository container."""
subprocess.run(['lxc', 'project', 'create', f'{args.remote}:{args.project}', '-s', args.pool,
'-c', 'features.images=false', '-c', 'features.networks=true'],
capture_output=True, text=True, check=True)
print(f'project {args.project} created; creating its OVN networks on {args.uplink}')
lxc('network', 'create', f'{args.remote}:wan', '--type=ovn', f'network={args.uplink}', 'ipv4.address=auto',
'ipv4.nat=true', 'ipv4.dhcp=true', 'ipv6.address=none', project=args.project)
# OVN gives every network's router an address; without DHCP the LAN hosts keep their own gateways.
for name in ('lana', 'lanb'):
lxc('network', 'create', f'{args.remote}:{name}', '--type=ovn', f'network={args.uplink}',
'ipv4.address=auto', 'ipv4.nat=true', 'ipv4.dhcp=false', 'ipv6.address=none', project=args.project)
# The project's default profile has the root disk on the pool of project create's -s.
lxc('profile', 'device', 'add', f'{args.remote}:default', 'eth0', 'nic', 'network=wan', 'name=eth0',
project=args.project)
vault = vault_create(args)
print(f'launching the repository container {args.remote}:repo (project {args.project})')
address = launch(args, 'repo', 'repo.yaml')
problem = enrol_instance(args.remote, args.project, 'repo', vault)
if problem:
raise RuntimeError(problem)
def inside(*command):
return lxc_exec(args.remote, args.project, 'repo', *command)
# The signing key, the publishing script and the empty indexes.
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(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()}')
lxc('file', 'pull', f'{args.remote}:repo/root/linux-manager-test.gpg', str(key), project=args.project)
state.write_text(json.dumps({'remote': args.remote, 'project': args.project, 'networks': list(NETWORKS),
'repository': f'http://{address}/', 'key': str(key)}, indent=2) + '\n',
encoding='utf-8')
state.chmod(0o600)
print(f'project {args.project} is ready on {args.remote}: networks {", ".join(NETWORKS)}, '
f'repository http://{address}/')
print(f'state: {state}')
def remove(args, state, key):
"""Delete the project's instances, the networks, the project and the local files; True when all went."""
ok = True
listing = lxc('list', f'{args.remote}:', '-c', 'n', '-f', 'csv', project=args.project, check=False)
for name in listing.stdout.split():
result = lxc('delete', '--force', f'{args.remote}:{name}', project=args.project, check=False)
if result.returncode != 0:
ok = False
print(f'could not delete {name}: {result.stderr.strip()}', file=sys.stderr)
# The default profile's eth0 keeps wan in use.
lxc('profile', 'device', 'remove', f'{args.remote}:default', 'eth0', project=args.project, check=False)
for name in NETWORKS:
if lxc('network', 'show', f'{args.remote}:{name}', project=args.project, check=False).returncode != 0:
continue
result = lxc('network', 'delete', f'{args.remote}:{name}', project=args.project, check=False)
if result.returncode != 0:
ok = False
print(f'could not delete network {name}: {result.stderr.strip()}', file=sys.stderr)
result = subprocess.run(['lxc', 'project', 'delete', f'{args.remote}:{args.project}'], capture_output=True,
text=True)
if result.returncode != 0:
ok = False
print(f'could not delete project {args.project}: {result.stderr.strip()}', file=sys.stderr)
if ok:
state.unlink(missing_ok=True)
key.unlink(missing_ok=True)
config_path(f'vault-{args.project}.json').unlink(missing_ok=True)
print(f'removed project {args.project} and its networks from {args.remote}')
return ok
def uplink(args):
"""Create the physical uplink network of the OVN networks on a host bridge of the LAN, or delete it.
setup creates --uplink in the default project with parent --parent, the LAN's gateway
--gateway (address/prefix), its name servers --dns, the LAN addresses OVN routers take
(--ovn-ranges, FIRST-LAST) and the LAN subnets for network forwards (--routes, CIDR); OVN
answers ARP for those on the LAN (ovn.ingress_mode l2proxy, the default). It leaves an
existing network of that name as it is. remove deletes the network.
"""
network = f'{args.remote}:{args.uplink}'
exists = lxc('network', 'show', network, project='default', check=False).returncode == 0
if args.operation == 'remove':
if exists:
lxc('network', 'delete', network, project='default')
print(f'{args.remote} has no network {args.uplink}')
return
if exists:
print(f'{args.remote} has the network {args.uplink} already')
return
for option, name in UPLINK_SETTINGS.items():
try:
setattr(args, option, getattr(args, option) or setting(name))
except MissingSetting as missing:
sys.exit(f'uplink setup: --{option.replace("_", "-")} or {missing}')
lxc('network', 'create', network, '--type=physical', f'parent={args.parent}', f'ipv4.gateway={args.gateway}',
f'dns.nameservers={args.dns}', f'ipv4.ovn.ranges={args.ovn_ranges}', f'ipv4.routes={args.routes}',
project='default')
print(f'{args.uplink} on {args.remote}: physical on {args.parent}, gateway {args.gateway}, OVN routers '
f'{args.ovn_ranges}, forwards {args.routes}')
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('action', choices=('create', 'remove', 'vault', 'uplink'))
parser.add_argument('operation', nargs='?', choices=('setup', 'create', 'unseal', 'remove'),
help='after vault: create, unseal or remove; after uplink: setup or remove')
parser.add_argument('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--pool',
help='the storage pool of the project, for create (LXD_POOL)')
parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--image', default=setting('LXD_IMAGE', 'ubuntu:26.04'),
help='the image of the repository container (LXD_IMAGE, default ubuntu:26.04)')
parser.add_argument('--vault-address', default=setting('LXD_VAULT_ADDRESS', None),
help="the listen address of the Vault's forward, one of the uplink's routes "
'(LXD_VAULT_ADDRESS); without it one is allocated')
parser.add_argument('--uplink', default=setting('LXD_UPLINK', 'uplink'),
help='the physical uplink network of the OVN networks (LXD_UPLINK, default uplink)')
parser.add_argument('--parent',
help='uplink setup: the host bridge on the LAN (LXD_UPLINK_PARENT)')
parser.add_argument('--gateway',
help='uplink setup: the LAN gateway as address/prefix (LXD_UPLINK_GATEWAY)')
parser.add_argument('--dns',
help='uplink setup: the LAN name servers, comma-separated (LXD_UPLINK_DNS)')
parser.add_argument('--ovn-ranges',
help='uplink setup: LAN addresses for OVN routers, FIRST-LAST (LXD_UPLINK_OVN_RANGES)')
parser.add_argument('--routes',
help='uplink setup: LAN subnets for network forwards, CIDR (LXD_UPLINK_ROUTES)')
args = parser.parse_args()
try:
args.remote = args.remote or setting('LXD_REMOTE')
except MissingSetting as missing:
parser.error(f'--remote or {missing}')
operations = {'uplink': ('setup', 'remove'), 'vault': ('create', 'unseal', 'remove')}
if args.operation not in operations.get(args.action, (None,)):
parser.error('setup or remove follows uplink, create, unseal or remove follows vault, and nothing else')
if args.action == 'uplink':
try:
uplink(args)
except subprocess.CalledProcessError as error:
sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}')
return
state = config_path(f'lxd-project-{args.project}.json')
key = config_path(f'lxd-project-{args.project}.gpg')
if args.action == 'vault':
try:
if args.operation == 'create':
vault_create(args)
elif args.operation == 'unseal':
current = vault_state(args.project)
if current is None:
sys.exit(f'project {args.project} has no Vault')
vault_unseal(current)
print(f'the Vault of {args.project} is unsealed')
elif not vault_remove(args):
sys.exit(1)
except subprocess.CalledProcessError as error:
sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}')
except (RuntimeError, VaultError) as error:
sys.exit(str(error))
return
if args.action == 'remove':
sys.exit(0 if remove(args, state, key) else 1)
try:
args.pool = args.pool or setting('LXD_POOL')
except MissingSetting as missing:
parser.error(f'--pool or {missing}')
if subprocess.run(['lxc', 'project', 'show', f'{args.remote}:{args.project}'], capture_output=True).returncode == 0:
sys.exit(f'project {args.project} exists on {args.remote}; remove it first or choose another --project')
state.parent.mkdir(parents=True, exist_ok=True)
try:
create(args, state, key)
except subprocess.CalledProcessError as error:
sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}\n'
f'remove what was made with: {sys.argv[0]} remove --remote {args.remote} --project {args.project}')
except (RuntimeError, VaultError) as error:
sys.exit(f'{error}\nremove what was made with: {sys.argv[0]} remove --remote {args.remote} '
f'--project {args.project}')
if __name__ == '__main__':
main()
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env python3
"""Print the current TOTP code of a user of a Linux Manager VM: lm-dev-otp-code.py.
The code is the one of the key <vm>-<user> in the TOTP engine of the Vault of the project --project
(LXD_PROJECT, lm-dev by default), for --user (admin by default) of the VM --vm (router), which
lm-dev-otp-register.py or lm-dev-vm.py create enrolled.
"""
import argparse
import sys
from lm_dev import PROJECT, VM, VaultError, otp_code, setting
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--vm', default=VM, help=f'the name of the VM (default {VM})')
parser.add_argument('--user', default='admin', help='the user (default admin)')
args = parser.parse_args()
try:
print(otp_code(args.project, args.vm, args.user))
except VaultError as error:
sys.exit(f'no code: {error}')
if __name__ == '__main__':
main()
+38
View File
@@ -0,0 +1,38 @@
#!/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 (router) in the project --project
(LXD_PROJECT, lm-dev by default) on the remote --remote (LXD_REMOTE): the project's Vault generates
the key in its TOTP engine as <vm>-<user> and hands it to the VM, where linuxmanager_users stores
it with its current code, replacing a token the user had. For the administrator of
.lm-dev-config/vm-PROJECT-VM.json, the key is made from the file's otp_url when it has one, and a generated key's
otpauth URI is kept there as otp_url. lm-dev-otp-code.py prints the user's codes.
"""
import argparse
import sys
from lm_dev import PROJECT, VM, MissingSetting, enrol_otp, setting, totp_key
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--vm', default=VM, help=f'the name of the VM (default {VM})')
parser.add_argument('--user', default='admin', help='the user to enrol (default admin)')
args = parser.parse_args()
try:
args.remote = args.remote or setting('LXD_REMOTE')
except MissingSetting as missing:
parser.error(f'--remote or {missing}')
problem = enrol_otp(args.remote, args.project, args.vm, args.user)
if problem:
sys.exit(problem)
print(f'{args.user} of {args.remote}:{args.vm} has a new TOTP token, the key {totp_key(args.vm, args.user)} '
f'of the Vault of {args.project}')
if __name__ == '__main__':
main()
+142 -57
View File
@@ -1,18 +1,21 @@
#!/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
check failed.
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 --deb, or else the one built last, in out/ or out/dev/. The administrator, admin, has a
password generated per run, kept in the scenario's Vault as <server>/admin. Each scenario's
project gets a Vault, the container lm-vault reached on the LXD host's address; every other instance
with a default route, the hosts of isolated LANs apart, gets an AppRole of its own in it and
/etc/vault once it is ready, and reads the files that hold a secret from it (Lab.hand_over), never as an argument or on standard input. Each check prints PASS, FAIL or SKIP; the run exits 1 when a check
failed.
"""
import argparse
import importlib
import ipaddress
import json
import os
import pathlib
import re
import secrets
@@ -20,10 +23,17 @@ import subprocess
import sys
import time
HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent.parent
from lm_dev import HANDOVER_DIR, ROOT, TESTS, VAULT_PORT, MissingSetting, VaultError, config_path, enrol_instance, hand_over, \
host_address, lxc_exec, newest_deb, setting, store_secret, vault_initialise
TMP = ROOT / 'tmp' / 'remote-test'
SCENARIOS = sorted(path.stem for path in (HERE / 'scenarios').glob('*.py') if path.stem != '__init__')
#: Seconds a server's component installations may take before a configuration fails.
INSTALL_WAIT = 900
SCENARIOS = sorted(path.stem for path in (TESTS / 'scenarios').glob('*.py') if path.stem != '__init__')
# The Vault of a scenario: its bridge with outbound NAT, and the container's MAC address and address on it.
VAULT_NETWORK = ('lmt-vault', '10.99.99.1/24', '00:16:3e:4c:99:10', '10.99.99.10/24')
class Lab:
@@ -46,6 +56,9 @@ class Lab:
self.networks = []
self.macs = {}
self.addresses = {}
self.vault = None
self.enrolled = set()
self.routed = set()
def lxc(self, *args, check=True):
"""Run lxc with the arguments and the project; raise CalledProcessError when it fails, unless check is false."""
@@ -53,9 +66,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."""
@@ -109,6 +120,33 @@ class Lab:
result = self.on(name, *command)
self.result(description, re.search(pattern, result.stdout + result.stderr, re.M) is None)
def start_vault(self):
"""Launch the scenario's Vault, the container lm-vault, reached by the Mac and the instances on the LXD host's
address through a proxy device, and initialise it."""
host = host_address(self.remote)
if not host:
raise RuntimeError(f'no IPv4 address of the host of remote {self.remote} for the Vault')
network, gateway, mac, address = VAULT_NETWORK
self.network(network, gateway)
self.instance('lm-vault', 'container', 'vault.yaml', (network, mac, address, gateway.split('/')[0]))
if not self.ready('lm-vault'):
raise RuntimeError('the Vault container did not boot')
self.lxc('config', 'device', 'add', f'{self.remote}:lm-vault', 'vault', 'proxy',
f'listen=tcp:{host}:{VAULT_PORT}', f'connect=tcp:127.0.0.1:{VAULT_PORT}')
url = f'http://{host}:{VAULT_PORT}'
try:
self.vault = vault_initialise(self.project, url, url)
except VaultError as error:
raise RuntimeError(f'the Vault was not initialised: {error}')
def hand_over(self, name, secret, content, destination, mode='0600'):
"""Give the instance the content, a file that holds a secret, through the Vault as <name>/<secret>, written
to destination; True when it was handed over."""
problem = hand_over(self.remote, self.project, name, self.vault, secret, content, destination, mode)
if problem:
print(problem, file=sys.stderr)
return problem is None
def network(self, name, address):
"""Create a bridge with outbound NAT at the gateway address GATEWAY/PREFIX, or without a host address when None.
@@ -130,6 +168,8 @@ class Lab:
"""
self.macs[name] = [nic[1] for nic in nics]
self.addresses[name] = nics[0][2]
if any(len(nic) > 3 for nic in nics):
self.routed.add(name)
netcfg = 'version: 2\nethernets:\n'
for index, (_, mac, address, *gateway) in enumerate(nics):
if kind == 'vm':
@@ -143,7 +183,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')
@@ -153,7 +193,8 @@ class Lab:
self.lxc('start', f'{self.remote}:{name}')
def ready(self, *names):
"""Wait for each instance's agent and cloud-init, then for its first address; False when one is not ready.
"""Wait for each instance's agent and cloud-init, then for its first address, and give an instance with a
default route, other than the Vault, its AppRole the first time; False when one is not ready.
cloud-init's status 2, done with recoverable errors, counts as booted. An instance whose first
NIC takes its address from DHCP waits for any IPv4 address outside lo.
@@ -175,6 +216,15 @@ class Lab:
else:
print(f'{name} has no address {address or "from DHCP"}', file=sys.stderr)
return False
if name != 'lm-vault' and name in self.routed and name not in self.enrolled:
problem = enrol_instance(self.remote, self.project, name, self.vault)
if problem:
print(problem, file=sys.stderr)
return False
if self.on(name, 'install', '-d', '-m', '0700', HANDOVER_DIR).returncode != 0:
print(f'{HANDOVER_DIR} cannot be made in {name}', file=sys.stderr)
return False
self.enrolled.add(name)
return True
def nic_of(self, name, index):
@@ -205,16 +255,24 @@ class Lab:
'wireguard-tools', 'openvpn', 'curl').returncode == 0)
def setup_run(self, name):
"""Run linux-manager-setup and wait for it; True when it succeeded."""
return self.on(name, 'systemctl', 'restart', 'linux-manager-setup').returncode == 0
"""Have linux-manager-setup run, after a run in progress, and wait for it; True when it succeeded."""
return self.on(name, 'linux-manager-config-edit', 'apply').returncode == 0
def server(self, name, config):
"""Install the package with the test administrator, then apply the configuration; True when both succeeded."""
if not self.push(self.deb, name, '/tmp/linux-manager.deb'):
return False
preseed = (f'linux-manager linux-manager/admin_username string admin\n'
preseed = ('linux-manager linux-manager/admin_username string admin\n'
f'linux-manager linux-manager/admin_password password {self.admin_password}\n')
if self.on(name, 'debconf-set-selections', input=preseed).returncode != 0:
try:
store_secret(self.vault, f'{name}/admin', {'password': self.admin_password})
except VaultError as error:
print(f'the admin password cannot be kept in the Vault: {error}', file=sys.stderr)
return False
if not self.hand_over(name, 'preseed', preseed, f'{HANDOVER_DIR}/preseed'):
return False
if self.on(name, 'sh', '-c', f'debconf-set-selections {HANDOVER_DIR}/preseed; status=$?; '
f'rm -f {HANDOVER_DIR}/preseed; exit $status').returncode != 0:
return False
result = self.on(name, 'env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y',
'/tmp/linux-manager.deb')
@@ -224,10 +282,10 @@ class Lab:
def render(self, name, config):
"""Replace the server's configuration, with its placeholders filled in.
@PSK@ is the pre-shared key, @ETH0@ and @ETH1@ the names of the server's NICs and @CIDR0@ the
network of its first address.
@PSK@ is the pre-shared key, @ETH0@ and @ETH1@ the names of the server's NICs and @CIDR0@ the network of its
first address; the configuration reaches the server through the Vault.
"""
text = (HERE / 'configs' / config).read_text(encoding='utf-8').replace('@PSK@', self.psk)
text = (TESTS / 'configs' / config).read_text(encoding='utf-8')
for index in (0, 1):
placeholder = f'@ETH{index}@'
if placeholder in text:
@@ -237,22 +295,40 @@ class Lab:
text = text.replace(placeholder, nic)
if '@CIDR0@' in text:
text = text.replace('@CIDR0@', str(self.address(name).network))
return self.push_text(text, name, '/etc/linux-manager/linux-manager.json', '0600')
return self.hand_over(name, 'config', text.replace('@PSK@', self.psk), '/etc/linux-manager/linux-manager.json')
def installed(self, name):
"""Wait for the installations of the server's components (linux-manager-install@*) to end, up to INSTALL_WAIT
seconds; True when none failed."""
deadline = time.monotonic() + INSTALL_WAIT
while time.monotonic() < deadline:
running = self.on(name, 'systemctl', 'list-units', '--no-legend', '--state=activating,active',
'linux-manager-install@*').stdout.strip()
if not running:
return not self.on(name, 'systemctl', 'list-units', '--no-legend', '--state=failed',
'linux-manager-install@*').stdout.strip()
time.sleep(5)
return False
def configure(self, name, config):
"""Render the configuration and apply it twice, as the server's certificates follow the first run."""
return self.render(name, config) and self.setup_run(name) and self.setup_run(name)
"""Render the configuration and apply it, wait for the packages of its components, and apply it again, as the
components and the server's certificates follow the first run."""
return self.render(name, config) and self.setup_run(name) and self.installed(name) and self.setup_run(name)
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):
"""Add the VPN user alice, whose password is the administrator's; True when it was added."""
return self.on(name, 'linux-manager-user', '--json', 'add', 'alice', '--first-name', 'Alice',
'--last-name', 'Test', '--email', 'alice@example.org',
input=self.admin_password + '\n').returncode == 0
"""Add the VPN user alice, whose password is the administrator's, read from a file the Vault gives the
server; True when it was added."""
secret = f'{HANDOVER_DIR}/alice.password'
if not self.hand_over(name, 'alice', f'{self.admin_password}\n', secret):
return False
return self.on(name, 'sh', '-c', 'linux-manager-user --json add alice --first-name Alice --last-name Test '
f'--email alice@example.org < {secret}; status=$?; rm -f {secret}; '
'exit $status').returncode == 0
def alice(self, name):
"""User alice from the server's user list, or None."""
@@ -260,21 +336,29 @@ class Lab:
return next((user for user in listing.get('users', []) if user.get('name') == 'alice'), None)
def wireguard_client(self, client, server, endpoint, address, allowed):
"""Give alice a peer of a new client key and bring wg0 up on the client towards the server, for allowed only."""
private_key = self.on(client, 'wg', 'genkey').stdout.strip()
public_key = self.on(client, 'wg', 'pubkey', input=private_key + '\n').stdout.strip()
if not private_key or not public_key:
"""Give alice a peer of a new client key and bring wg0 up on the client towards the server, for allowed only.
The client's private key is made in the client and never leaves it; wg0.conf is completed there.
"""
public_key = self.on(client, 'sh', '-c', 'umask 077; wg genkey > /etc/wireguard/private.key && '
'wg pubkey < /etc/wireguard/private.key').stdout.strip()
if 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
if not self.setup_run(server):
return False
server_key = self.on(server, 'cat', '/etc/wireguard/wg0.pub').stdout.strip()
conf = (f'[Interface]\nPrivateKey = {private_key}\nAddress = {address}/32\n\n'
conf = (f'[Interface]\nPrivateKey = @KEY@\nAddress = {address}/32\n\n'
f'[Peer]\nPublicKey = {server_key}\nEndpoint = {endpoint}:51820\nAllowedIPs = {allowed}\n')
return (self.push_text(conf, client, '/etc/wireguard/wg0.conf', '0600') and
# awk reads the key from its file, so it is no argument of any process.
complete = ("umask 077; awk 'NR == FNR { key = $0; next } { gsub(\"@KEY@\", key) } 1' "
'/etc/wireguard/private.key /etc/wireguard/wg0.template > /etc/wireguard/wg0.conf && '
'rm -f /etc/wireguard/wg0.template')
return (self.push_text(conf, client, '/etc/wireguard/wg0.template', '0600') and
self.on(client, 'sh', '-c', complete).returncode == 0 and
self.on(client, 'bash', '/usr/bin/wg-quick', 'up', 'wg0').returncode == 0)
def wireguard_module(self, name):
@@ -292,6 +376,8 @@ class Lab:
listing = self.lxc('list', f'{self.remote}:', '-c', 'n', '-f', 'csv', check=False)
for name in listing.stdout.split():
self.lxc('delete', '--force', f'{self.remote}:{name}', check=False)
config_path(f'vault-{self.project}.json').unlink(missing_ok=True)
self.vault = None
for name in self.networks:
subprocess.run(['lxc', 'network', 'delete', f'{self.remote}:{name}'], capture_output=True)
self.networks = []
@@ -301,46 +387,45 @@ class Lab:
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('scenarios', nargs='+', metavar='scenario', help=f'{", ".join(SCENARIOS)} or all')
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'),
parser.add_argument('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--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('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'),
parser.add_argument('--project', default=setting('LXD_TEST_PROJECT', 'lm-test'),
help='the project the instances live in (LXD_TEST_PROJECT, default lm-test)')
parser.add_argument('--image', default=setting('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')
parser.add_argument('--deb', help='the package to test (default the one built last, in out/ or out/dev/)')
args = parser.parse_args()
if not args.remote:
parser.error('--remote or LXD_REMOTE is required')
if not args.pool:
parser.error('--pool or LXD_POOL is required')
try:
args.remote = args.remote or setting('LXD_REMOTE')
args.pool = args.pool or setting('LXD_POOL')
except MissingSetting as missing:
parser.error(f'--{missing.name.removeprefix("LXD_").lower()} or {missing}')
scenarios = SCENARIOS if args.scenarios == ['all'] else args.scenarios
unknown = [name for name in scenarios if name not in SCENARIOS]
if unknown:
parser.error(f'no scenario {", ".join(unknown)}')
debs = sorted((ROOT / 'out').glob('linux-manager_*_all.deb'))
if not debs:
sys.exit('no out/linux-manager_*_all.deb; run ./build.sh first')
deb = pathlib.Path(args.deb) if args.deb else newest_deb()
if deb is None or not deb.is_file():
sys.exit(f'no package {args.deb}' if args.deb else 'no out/linux-manager_*_all.deb; run ./build.py first')
if subprocess.run(['lxc', 'project', 'show', f'{args.remote}:{args.project}'], capture_output=True).returncode == 0:
sys.exit(f'project {args.project} exists on {args.remote}; remove it or choose another with --project')
TMP.mkdir(parents=True, exist_ok=True)
lab = Lab(args.remote, args.project, args.pool, args.image, args.keep, debs[-1],
lab = Lab(args.remote, args.project, args.pool, args.image, args.keep, deb,
secrets.token_hex(16), secrets.token_hex(24))
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')
print(f'package: {debs[-1].name}; remote: {args.remote}; project: {args.project}; image: {args.image}')
print(f'package: {deb}; 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,
'-c', 'features.images=false'], capture_output=True, check=True)
print(f'== {name}')
try:
lab.start_vault()
importlib.import_module(f'scenarios.{name}').run(lab)
except (subprocess.CalledProcessError, RuntimeError) as error:
detail = error.stderr.strip() if isinstance(error, subprocess.CalledProcessError) else str(error)
@@ -351,8 +436,8 @@ def main():
sys.exit(130)
print(f'== passed {lab.passed}, failed {lab.failed}, skipped {lab.skipped}')
print("Not covered: IKEv2 client access, HTTPS with Let's Encrypt, the OpenID Provider and passkeys,")
print('PowerDNS answering from outside, the Azure and GCP platform modules.')
print("Not covered: IKEv2 client access, HTTPS with Let's Encrypt, passkeys, PowerDNS answering from")
print('outside, the Azure and GCP platform modules.')
sys.exit(1 if lab.failed else 0)
+263
View File
@@ -0,0 +1,263 @@
#!/usr/bin/env python3
"""Launch one Linux Manager server VM on an LXD remote to work with, or remove it: lm-dev-vm.py create|remove.
create launches the VM --vm (router 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 .lm-dev-config/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 --deb, or else the package built last, in out/ or out/dev/. The administrator is admin with the
password of .lm-dev-config/vm-PROJECT-VM.json, and a TOTP token, the key VM-admin of the project's Vault's TOTP
engine made from the file's otp_url, unless --no-otp is given; lm-dev-otp-code.py prints its codes. A password or
otp_url the file lacks, or all of them when there is no file, is generated and kept in the file, so a VM made again
has the same password and token until they are deleted from the file.
The VM gets a configuration from tests/remote/configs/ (--config, dev.json by default), whose @ETH0@ is the
interface of its default route, @CIDR0@ its network, @FQDN@ --fqdn (LXD_DEV_FQDN, lm-dev.test by default), and @PSK@ a
generated key; the Manager and the status web service answer HTTPS for that name, which has to resolve to the
listen address. The VM gets an AppRole of its own in the project's Vault
(lm_dev.enrol_instance), with which it reads the debconf preseed with the admin's password and the
configuration with its key, kept there as VM/preseed and VM/config, and its TOTP key, generated or from otp_url; no
secret is an argument or on standard input, so create needs a project with a Vault
(lm-dev-lxd-project.py vault create). The admin's password is also kept there as VM/admin.
The VM's leased address is pinned on its NIC, and ports 7080, 7081, 7443 and 7444 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, --forward-address (LXD_FORWARD_ADDRESS) or else one 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 what the Vault keeps
for it, and keeps .lm-dev-config/vm-PROJECT-VM.json. The defaults of the options come from the environment, else from
.lm-dev-config/settings.json (lm_dev.setting).
"""
import argparse
import ipaddress
import json
import pathlib
import re
import secrets
import subprocess
import sys
import time
from lm_dev import HANDOVER_DIR, PROJECT, VM, ROOT, TESTS, VAULT_MOUNT, MissingSetting, VaultError, config_path, \
credentials_path, enrol_instance, enrol_otp, forget_instance, hand_over, host_address, lxc_exec, newest_deb, \
setting, store_secret, vault_state, write_private
# The listen port and the VM port of each forward or proxy: the Manager and the status web service over HTTP and
# HTTPS, and SSH.
PORTS = ((7080, 7080), (7081, 7081), (7443, 7443), (7444, 7444), (2222, 22))
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('action', choices=('create', 'remove'))
parser.add_argument('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--vm', default=VM, help=f'the name of the VM (default {VM})')
parser.add_argument('--image', default=setting('LXD_IMAGE', 'ubuntu:26.04'),
help='the image of the VM (LXD_IMAGE, default ubuntu:26.04)')
parser.add_argument('--config', default='dev.json',
help='the configuration from tests/remote/configs/ (default dev.json)')
parser.add_argument('--listen', default=setting('LXD_LISTEN', None),
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('--fqdn', default=setting('LXD_DEV_FQDN', 'lm-dev.test'),
help='the name of the VM in its configuration, @FQDN@ (LXD_DEV_FQDN, default lm-dev.test)')
parser.add_argument('--forward-address', default=setting('LXD_FORWARD_ADDRESS', None),
help="with create in a test project, the forward's listen address, one of the uplink's routes "
"(LXD_FORWARD_ADDRESS); without it one is allocated")
parser.add_argument('--no-otp', action='store_true', help='with create, enrol no TOTP token for admin')
parser.add_argument('--deb', help='outside a test project, the package to install (default the one built last, '
'in out/ or out/dev/)')
args = parser.parse_args()
try:
args.remote = args.remote or setting('LXD_REMOTE')
except MissingSetting as missing:
parser.error(f'--remote or {missing}')
project_file = config_path(f'lxd-project-{args.project}.json')
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 args.action == 'create' and not args.listen:
# The default listen address is the IPv4 address of the remote's host in its lxc URL.
args.listen = host_address(args.remote)
if not args.listen:
parser.error(f'no IPv4 address of the host of remote {args.remote}; give --listen or LXD_LISTEN, in the '
'environment or .lm-dev-config/settings.json')
where = f'{args.remote}:{args.vm} (project {args.project})'
credentials = credentials_path(args.project, args.vm)
exists = subprocess.run(['lxc', 'info', f'{args.remote}:{args.vm}', '--project', args.project],
capture_output=True).returncode == 0
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
def forward_of_vm():
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.vm), None)
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.vm}', '--project', args.project], check=True)
if (vault := vault_state(args.project)) is not None:
try:
forget_instance(vault, args.vm)
except VaultError as error:
print(f'the Vault keeps what it had for {args.vm}: {error}', file=sys.stderr)
print(f'removed {where}; {credentials} is kept for the next create')
return
if exists:
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 tests/remote/configs/{args.config}')
deb = pathlib.Path(args.deb) if args.deb else newest_deb()
if not project and (deb is None or not deb.is_file()):
sys.exit(f'no package {args.deb}' if args.deb else 'no out/linux-manager_*_all.deb; run ./build.py first')
source = f'the repository {project["repository"]}' if project else str(deb)
vault = vault_state(args.project)
if vault is None:
sys.exit(f'project {args.project} has no Vault, which the secrets reach the VM through; make it with '
'lm-dev-lxd-project.py vault create')
# The password and otp_url of the credentials file are reused; a missing one is generated.
known = json.loads(credentials.read_text(encoding='utf-8')) if credentials.is_file() else {}
password, psk = known.get('password') or secrets.token_hex(16), secrets.token_hex(24)
known.update(username='admin', password=password)
write_private(credentials, json.dumps(known, indent=2) + '\n')
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.vm}', '--vm', '-c', 'limits.cpu=2',
'-c', 'limits.memory=4GiB',
'-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('cloud-init', 'status', '--wait').returncode in (0, 2):
break
time.sleep(5)
else:
sys.exit(f'{args.vm} did not boot; remove it with remove')
problem = enrol_instance(args.remote, args.project, args.vm, vault)
if problem:
sys.exit(f'{problem}; remove the VM with remove')
for _ in range(24):
route = re.search(r'\bdev (\S+)', inside('ip', '-4', '-o', 'route', 'show', 'default').stdout)
address = route and re.search(r' inet (\S+) ',
inside('ip', '-4', '-o', 'addr', 'show', 'dev', route.group(1)).stdout)
if address:
break
time.sleep(5)
else:
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('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.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 --forward-address, or one allocated
# from the uplink's routes.
address = [args.forward_address] if args.forward_address else ['--allocate=ipv4']
subprocess.run(['lxc', 'network', 'forward', 'create', wan, *address, 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.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 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('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.vm}: {updated.stderr.strip()}')
package = 'linux-manager'
else:
if not push(deb, '/tmp/linux-manager.deb', '0644'):
sys.exit(f'could not copy {deb} into {args.vm}')
package = '/tmp/linux-manager.deb'
preseed = ('linux-manager linux-manager/admin_username string admin\n'
f'linux-manager linux-manager/admin_password password {password}\n')
try:
store_secret(vault, f'{args.vm}/admin', {'password': password})
except VaultError as error:
sys.exit(f'the admin password cannot be kept in the Vault: {error}')
if inside('install', '-d', '-m', '0700', HANDOVER_DIR).returncode != 0:
sys.exit(f'{HANDOVER_DIR} cannot be made in {args.vm}')
problem = hand_over(args.remote, args.project, args.vm, vault, 'preseed', preseed, f'{HANDOVER_DIR}/preseed', '0600')
if problem:
sys.exit(problem)
if inside('sh', '-c', f'debconf-set-selections {HANDOVER_DIR}/preseed; status=$?; rm -f {HANDOVER_DIR}/preseed; '
'exit $status').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}')
# 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('@FQDN@', args.fqdn)
problem = hand_over(args.remote, args.project, args.vm, vault, 'config', text.replace('@PSK@', psk),
'/etc/linux-manager/linux-manager.json', '0600')
if problem:
sys.exit(f'could not give {args.vm} {args.config}: {problem}')
for _ in range(2):
if inside('linux-manager-config-edit', 'apply').returncode != 0:
sys.exit(f'linux-manager-setup failed with {args.config}; see journalctl -u linux-manager-setup in the VM')
if not args.no_otp:
problem = enrol_otp(args.remote, args.project, args.vm, 'admin')
if problem:
sys.exit(f'{args.vm} is up, but {problem}')
print(f'{args.vm} is up at {interface.ip} with {args.config}')
print(f'administrator: admin, password in {credentials} and the Vault ({VAULT_MOUNT}/{args.vm}/admin)')
if not args.no_otp:
print(f'administrator TOTP: otp_url in {credentials}; codes: bin/lm-dev-otp-code.py --project {args.project} '
f'--vm {args.vm}')
print(f'manager: https://{args.fqdn}:7443/ status: https://{args.fqdn}:7444/ and http://{args.listen}:7081/ '
f'ssh: {args.listen} port 2222')
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__':
main()
+348
View File
@@ -0,0 +1,348 @@
"""What the lm-dev scripts share: the repository's paths, lxc in an instance, the persistent state and settings in
.lm-dev-config, the Vault of a test project, the AppRole of each instance in it, the hand-over of
secrets to an instance through it, and the TOTP tokens of the users of a VM, kept in the Vault's TOTP engine.
A secret never reaches an instance as a command-line argument or on standard input. Each instance has an AppRole of
its own (enrol_instance): its role ID and the helper lm-dev-vault (tests/remote/lm-dev-vault) are pushed into it, and
its secret ID with a response-wrapping token, which the helper unwraps once into /etc/vault. The instance then logs in
and reads what the Mac stored for it under kv/<instance>/, whole files that hold a secret (hand_over), and creates its
own TOTP keys (enrol_otp).
"""
import json
import os
import pathlib
import socket
import subprocess
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
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'
# The default VM of the manual tests, which lm-dev-vm.py makes.
VM = 'router'
# The state of the scripts that outlives a clean-up of tmp/: settings, project and Vault states, keys and secrets; 0700.
CONFIG = ROOT / '.lm-dev-config'
# The settings of the scripts, the defaults of their options: a JSON object of LXD_* names and their values.
SETTINGS = CONFIG / 'settings.json'
# The Vault: its port, the KV v2 and TOTP mounts, the lifetimes of a wrapping token and of an instance's token.
VAULT_PORT = 8200
VAULT_MOUNT = 'kv'
TOTP_MOUNT = 'totp'
WRAP_TTL = '120s'
TOKEN_TTL = '5m'
# In an instance: the helper, its directory of the Vault's URL and the AppRole's IDs, and the directory of files a
# secret passes through.
HELPER = '/usr/local/sbin/lm-dev-vault'
ETC_VAULT = '/etc/vault'
HANDOVER_DIR = '/run/lm-dev'
# Run in the VM as python3 -c CODE USER FILE: enrol the secret of the otpauth URI in FILE for USER with its current
# code, then remove the file.
OTP_ENROL = ("import os, sys, urllib.parse; sys.path.insert(0, '/usr/lib/linux-manager')\n"
"import linuxmanager_users as users\n"
"user, path = sys.argv[1:3]\n"
"try:\n"
" with open(path, encoding='utf-8') as handle: url = handle.read().strip()\n"
"finally:\n"
" os.unlink(path)\n"
"secret = urllib.parse.parse_qs(urllib.parse.urlsplit(url).query)['secret'][0]\n"
"with users.session() as connection:\n"
" users.otp_enrol(connection, user, secret, users.totp(secret).now())")
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 lxc_push(remote, project, instance, source, path, mode):
"""Copy the local file to the path in the instance with the mode; True when it was copied."""
return subprocess.run(['lxc', 'file', 'push', str(source), f'{remote}:{instance}{path}', '--mode', mode,
'--project', project], capture_output=True, text=True).returncode == 0
class MissingSetting(Exception):
"""A setting without a default that neither the environment nor SETTINGS has; name is the setting."""
def __init__(self, name):
super().__init__(f'{name}, in the environment or {SETTINGS.relative_to(ROOT)}, is required')
self.name = name
# The default of a setting that has none.
REQUIRED = object()
def setting(name, default=REQUIRED):
"""The value of the setting name, such as LXD_REMOTE: the environment's, else that of SETTINGS, else default;
MissingSetting without a default."""
if name in os.environ:
return os.environ[name]
try:
values = json.loads(SETTINGS.read_text(encoding='utf-8'))
except FileNotFoundError:
values = {}
except ValueError as error:
raise SystemExit(f'{SETTINGS} is not JSON: {error}')
if name in values:
return values[name]
if default is REQUIRED:
raise MissingSetting(name)
return default
def save_setting(name, value):
"""Set the setting name to the value in SETTINGS, keeping its other settings."""
path = config_path(SETTINGS.name)
values = json.loads(path.read_text(encoding='utf-8')) if path.is_file() else {}
values[name] = value
write_private(path, json.dumps(values, indent=2) + '\n')
def newest_deb():
"""The package built last, release or dev build, by modification time among out/ and out/dev/; None without
one."""
debs = [*(ROOT / 'out').glob('linux-manager_*_all.deb'), *(ROOT / 'out' / 'dev').glob('linux-manager_*_all.deb')]
return max(debs, key=lambda path: path.stat().st_mtime, default=None)
def config_path(name):
"""The path of a file in CONFIG, which is made with mode 0700 when it is missing."""
CONFIG.mkdir(mode=0o700, exist_ok=True)
CONFIG.chmod(0o700)
return CONFIG / name
def write_private(path, text):
"""Write the text to the file, readable by its owner only."""
path = pathlib.Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.touch(mode=0o600)
path.chmod(0o600)
path.write_text(text, encoding='utf-8')
def host_address(remote):
"""The IPv4 address of the host of the remote's lxc URL, or None."""
remotes = json.loads(subprocess.run(['lxc', 'remote', 'list', '--format', 'json'], capture_output=True,
text=True, check=True).stdout)
host = urllib.parse.urlsplit(remotes.get(remote, {}).get('Addr', '')).hostname
try:
return socket.getaddrinfo(host, None, socket.AF_INET)[0][4][0] if host else None
except socket.gaierror:
return None
class VaultError(Exception):
"""A Vault request that failed."""
def vault_call(url, method, path, body=None, token=None, wrap=None):
"""Send the request to the Vault at url; the JSON answer, {} for none. wrap asks for a wrapped answer."""
headers = {'Content-Type': 'application/json'}
if token:
headers['X-Vault-Token'] = token
if wrap:
headers['X-Vault-Wrap-TTL'] = wrap
request = urllib.request.Request(url.rstrip('/') + path, json.dumps(body).encode() if body is not None else None,
headers, method=method)
try:
with urllib.request.urlopen(request, timeout=30) as response:
data = response.read()
except urllib.error.HTTPError as error:
raise VaultError(f'{method} {path}: {error.code} {error.read().decode(errors="replace").strip()}')
except (urllib.error.URLError, OSError) as error:
raise VaultError(f'{method} {path}: {url} cannot be reached: {error}')
return json.loads(data) if data else {}
def vault_state(project):
"""The Vault state of the project: {url, internal_url, key, root_token}, None when it has no Vault."""
path = config_path(f'vault-{project}.json')
return json.loads(path.read_text(encoding='utf-8')) if path.is_file() else None
def vault_initialise(project, url, internal_url):
"""Initialise the Vault at url with one key share, unseal it, mount KV v2 and TOTP, enable AppRole and keep its
state; the state."""
for _ in range(60):
try:
if 'initialized' in vault_call(url, 'GET', '/v1/sys/init'):
break
except VaultError:
pass
time.sleep(2)
else:
raise VaultError(f'{url} does not answer')
answer = vault_call(url, 'POST', '/v1/sys/init', {'secret_shares': 1, 'secret_threshold': 1})
state = {'url': url, 'internal_url': internal_url, 'key': answer['keys_base64'][0],
'root_token': answer['root_token']}
write_private(config_path(f'vault-{project}.json'), json.dumps(state, indent=2) + '\n')
vault_unseal(state)
vault_call(url, 'POST', f'/v1/sys/mounts/{VAULT_MOUNT}', {'type': 'kv', 'options': {'version': '2'}},
token=state['root_token'])
vault_call(url, 'POST', f'/v1/sys/mounts/{TOTP_MOUNT}', {'type': 'totp'}, token=state['root_token'])
vault_call(url, 'POST', '/v1/sys/auth/approle', {'type': 'approle'}, token=state['root_token'])
return state
def vault_unseal(state):
"""Unseal the Vault of the state with its key; it is left as it is when it is unsealed."""
answer = vault_call(state['url'], 'POST', '/v1/sys/unseal', {'key': state['key']})
if answer.get('sealed'):
raise VaultError(f'{state["url"]} is still sealed')
def store_secret(state, path, values):
"""Write the values, a dict of strings, as the KV v2 secret at path."""
vault_call(state['url'], 'POST', f'/v1/{VAULT_MOUNT}/data/{path}', {'data': values}, token=state['root_token'])
def enrol_instance(remote, project, instance, state):
"""Give the instance an AppRole of its own, named after it, whose policy reads kv/<instance>/ and creates the TOTP
keys <instance>-*, and set up /etc/vault in it; the problem, or None.
The instance receives the helper, the Vault's URL, the role ID and a wrapping token of a new secret ID, each as a
file; the helper unwraps the token once, after checking that it wraps the role's secret-id request.
"""
policy = (f'path "{VAULT_MOUNT}/data/{instance}/*" {{ capabilities = ["read"] }}\n'
f'path "{TOTP_MOUNT}/keys/{instance}-*" {{ capabilities = ["create", "update"] }}\n')
role = f'/v1/auth/approle/role/{instance}'
try:
vault_call(state['url'], 'POST', f'/v1/sys/policies/acl/instance-{instance}', {'policy': policy},
token=state['root_token'])
vault_call(state['url'], 'POST', role, {'token_policies': [f'instance-{instance}'], 'token_type': 'batch',
'token_ttl': TOKEN_TTL, 'secret_id_ttl': 0, 'secret_id_num_uses': 0},
token=state['root_token'])
role_id = vault_call(state['url'], 'GET', f'{role}/role-id', token=state['root_token'])['data']['role_id']
token = vault_call(state['url'], 'POST', f'{role}/secret-id', {}, token=state['root_token'],
wrap=WRAP_TTL)['wrap_info']['token']
except (VaultError, KeyError) as error:
return f'the AppRole of {instance} cannot be made: {error}'
prepared = lxc_exec(remote, project, instance, 'install', '-d', '-m', '0700', ETC_VAULT)
if prepared.returncode != 0:
return f'{ETC_VAULT} cannot be made in {instance}: {prepared.stderr.strip()}'
with tempfile.TemporaryDirectory(dir=ROOT / 'tmp' if (ROOT / 'tmp').is_dir() else None) as folder:
local = pathlib.Path(folder)
os.chmod(local, 0o700)
write_private(local / 'url', state['internal_url'] + '\n')
write_private(local / 'role-id', role_id + '\n')
write_private(local / 'wrapped', token + '\n')
files = ((TESTS / 'lm-dev-vault', HELPER, '0755'), (local / 'url', f'{ETC_VAULT}/url', '0644'),
(local / 'role-id', f'{ETC_VAULT}/role-id', '0600'),
(local / 'wrapped', f'{ETC_VAULT}/secret-id.wrapped', '0600'))
for source, target, mode in files:
if not lxc_push(remote, project, instance, source, target, mode):
return f'{target} cannot be copied into {instance}'
result = lxc_exec(remote, project, instance, HELPER, 'init', instance)
if result.returncode != 0:
return f'{instance} did not take its secret ID: {result.stderr.strip()}'
return None
def forget_instance(state, instance):
"""Delete the instance's AppRole, its policy, its secrets under kv/<instance>/ and its TOTP keys."""
url, token = state['url'], state['root_token']
def listed(path):
try:
return vault_call(url, 'LIST', path, token=token)['data']['keys']
except VaultError:
return []
vault_call(url, 'DELETE', f'/v1/auth/approle/role/{instance}', token=token)
vault_call(url, 'DELETE', f'/v1/sys/policies/acl/instance-{instance}', token=token)
for name in listed(f'/v1/{VAULT_MOUNT}/metadata/{instance}'):
vault_call(url, 'DELETE', f'/v1/{VAULT_MOUNT}/metadata/{instance}/{name}', token=token)
for key in listed(f'/v1/{TOTP_MOUNT}/keys'):
if key.startswith(f'{instance}-'):
vault_call(url, 'DELETE', f'/v1/{TOTP_MOUNT}/keys/{key}', token=token)
def hand_over(remote, project, instance, state, name, content, destination, mode):
"""Store the content, a file that holds a secret, as kv/<instance>/<name>, and have the instance write it to
destination with the mode, reading it with its AppRole; the problem, or None."""
try:
store_secret(state, f'{instance}/{name}', {'content': content})
except VaultError as error:
return f'the secret {instance}/{name} cannot be stored: {error}'
result = lxc_exec(remote, project, instance, HELPER, 'get', f'{instance}/{name}', 'content', destination, mode)
if result.returncode != 0:
return f'{instance}/{name} was not handed over to {instance}: {result.stderr.strip()}'
return None
def credentials_path(project, instance):
"""The file of the administrator of the VM lm-dev-vm.py made, JSON of username, password and otp_url; 0600."""
return config_path(f'vm-{project}-{instance}.json')
def totp_key(instance, user):
"""The name of the TOTP key of the user of the instance in the Vault's TOTP engine."""
return f'{instance}-{user}'
def enrol_otp(remote, project, instance, user):
"""Enrol a TOTP token for the user of the VM, replacing one the user had; the problem, or None.
When the user is the administrator of the VM's credentials_path and the file has otp_url, the Vault's key is made
from that otpauth URI and the VM receives it through the Vault (hand_over), so the token stays the same. Otherwise
the VM has the Vault generate a new key with its AppRole, and for the administrator the key's otpauth URI, read
from the VM's file before it is removed, is kept in the file as otp_url, to add the token to an authenticator. The
VM enrols the key's secret with its current code; the codes are read from the Vault (otp_code).
"""
state = vault_state(project)
if state is None:
return f'project {project} has no Vault; make it with lm-dev-lxd-project.py vault create'
key = totp_key(instance, user)
try:
vault_call(state['url'], 'DELETE', f'/v1/{TOTP_MOUNT}/keys/{key}', token=state['root_token'])
except VaultError as error:
return f'the TOTP key {key} cannot be replaced: {error}'
target = f'{HANDOVER_DIR}/otp-url'
credentials = credentials_path(project, instance)
known = json.loads(credentials.read_text(encoding='utf-8')) if credentials.is_file() else {}
keep = known.get('username') == user
reuse = known.get('otp_url') if keep else None
prepared = lxc_exec(remote, project, instance, 'install', '-d', '-m', '0700', HANDOVER_DIR)
if prepared.returncode != 0:
return f'{HANDOVER_DIR} cannot be made in {instance}: {prepared.stderr.strip()}'
if reuse:
try:
vault_call(state['url'], 'POST', f'/v1/{TOTP_MOUNT}/keys/{key}', {'url': reuse},
token=state['root_token'])
except VaultError as error:
return f'the TOTP key {key} cannot be made from otp_url: {error}'
problem = hand_over(remote, project, instance, state, 'otp-url', reuse + '\n', target, '0600')
if problem:
return problem
steps = ()
else:
steps = ((HELPER, 'totp', key, instance, user, target, '0600'), *((('cat', target),) if keep else ()))
for command in (*steps, ('python3', '-c', OTP_ENROL, user, target)):
result = lxc_exec(remote, project, instance, *command)
if result.returncode != 0:
return f'{user} was not enrolled: {(result.stderr.strip().splitlines() or ["lxc exec failed"])[-1]}'
if command[0] == 'cat':
known['otp_url'] = result.stdout.strip()
if keep:
write_private(credentials, json.dumps(known, indent=2) + '\n')
return None
def otp_code(project, instance, user):
"""The current TOTP code of the user of the instance, from the project's Vault."""
state = vault_state(project)
if state is None:
raise VaultError(f'project {project} has no Vault')
return vault_call(state['url'], 'GET', f'/v1/{TOTP_MOUNT}/code/{totp_key(instance, user)}',
token=state['root_token'])['data']['code']
Executable
+95
View File
@@ -0,0 +1,95 @@
#!/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 is kept in the file --secret-file or OTP_FILE names, readable by its owner only, as
nothing but its base32 secret, or with --url as its otpauth URI, each without a line end, so the
file is a value Vault's TOTP engine imports as it is (key=@FILE or url=@FILE). 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, from either form of the file. The codes are RFC 6238's, with
--algorithm (sha1 by default), --digits (6) and --period (30 seconds); a file holding an otpauth
URI gives those of the URI instead.
"""
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 stored(text, digits, period, algorithm):
"""The secret, digits, period and algorithm of the file's text: a base32 secret with the given settings, or an
otpauth URI with its own, the given ones where it has none."""
if not text.startswith('otpauth://'):
return text, digits, period, algorithm
query = {name: values[0] for name, values in urllib.parse.parse_qs(urllib.parse.urlsplit(text).query).items()}
found = query.get('algorithm', algorithm).lower()
if found not in ALGORITHMS:
sys.exit(f'the otpauth URI has the unknown algorithm {found}')
return query.get('secret', ''), int(query.get('digits', digits)), int(query.get('period', period)), found
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 or its otpauth URI (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('--url', action='store_true', help='new: store the otpauth URI instead of the secret alone')
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')
secret, digits, period, algorithm = stored(secret_file.read_text(encoding='utf-8').strip(), args.digits,
args.period, args.algorithm)
print(code_of(secret, args.at, digits, period, 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()
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
uri = f'otpauth://totp/{label}?{urllib.parse.urlencode(query)}'
secret_file.parent.mkdir(parents=True, exist_ok=True)
secret_file.touch(mode=0o600)
secret_file.chmod(0o600)
secret_file.write_text(uri if args.url else secret, encoding='utf-8')
print(uri)
if __name__ == '__main__':
main()
Executable
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Build the package in a container and write it to out/: build.py [CONTAINER BUILD OPTIONS].
The Dockerfile builds the Manager's application and the package, whose debian/changelog it writes
from CHANGELOG.md; the build's files are then streamed out of the image as a tar archive into out/,
so no bind mount is needed. The container runtime is CONTAINER_RUNTIME from the environment, for
example docker with DOCKER_CONTEXT naming a remote engine, else Apple's container CLI on macOS and
Docker on Linux. Options are passed to the runtime's build, such as --build-arg DEB_VERSION=V. A
failure is a message on standard error and a non-zero exit status.
"""
import argparse
import os
import pathlib
import platform
import subprocess
import sys
import tarfile
ROOT = pathlib.Path(__file__).resolve().parent
OUT = ROOT / 'out'
IMAGE = 'linux-manager-builder'
#: The container runtime of each platform when CONTAINER_RUNTIME is not set.
RUNTIMES = {'Darwin': 'container', 'Linux': 'docker'}
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0], allow_abbrev=False,
usage='%(prog)s [-h] [CONTAINER BUILD OPTIONS]',
epilog="the other options are passed to the container runtime's build")
_, options = parser.parse_known_args()
runtime = os.environ.get('CONTAINER_RUNTIME') or RUNTIMES.get(platform.system())
if not runtime:
sys.exit(f'build.py: unsupported platform {platform.system()}; set CONTAINER_RUNTIME')
OUT.mkdir(exist_ok=True)
build = [runtime, 'build', '--build-arg', f'HOST_UID={os.getuid()}', '--build-arg', f'HOST_GID={os.getgid()}',
'-t', IMAGE, *options, '.']
if subprocess.run(build, cwd=ROOT).returncode != 0:
sys.exit('build.py: the image build failed')
with subprocess.Popen([runtime, 'run', '--rm', IMAGE, 'tar', '-cf', '-', '-C', '/out', '.'], cwd=ROOT,
stdout=subprocess.PIPE) as stream:
with tarfile.open(fileobj=stream.stdout, mode='r|') as archive:
archive.extractall(OUT, filter='data')
if stream.returncode != 0:
sys.exit('build.py: the build files could not be copied out of the image')
print(f'Build artifacts written to {OUT.relative_to(ROOT)}/')
return 0
if __name__ == '__main__':
sys.exit(main())
-20
View File
@@ -1,20 +0,0 @@
#!/bin/sh
set -e
# CONTAINER_RUNTIME from the environment, for example docker with DOCKER_CONTEXT naming a remote engine;
# otherwise Apple container CLI on macOS and Docker CE on Linux.
if [ -z "${CONTAINER_RUNTIME:-}" ]; then
case "$(uname -s)" in
Darwin) CONTAINER_RUNTIME=container ;;
Linux) CONTAINER_RUNTIME=docker ;;
*) printf 'ERROR: unsupported platform %s\n' "$(uname -s)" >&2; exit 1 ;;
esac
fi
mkdir -p out
$CONTAINER_RUNTIME build --build-arg HOST_UID=$(id -u) --build-arg HOST_GID=$(id -g) -t linux-manager-builder "$@" .
# Artifacts are streamed out as a tar archive, so no bind mount is needed.
$CONTAINER_RUNTIME run --rm linux-manager-builder tar -cf - -C /out . | tar -xf - -C out
echo "Build artifacts written to out/"
File diff suppressed because it is too large. Load diff
+13 -1
View File
@@ -77,13 +77,25 @@ 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_input high linux-manager/https_disable_auto_redirect || true
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 -11
View File
@@ -9,11 +9,6 @@ Rules-Requires-Root: no
Package: linux-manager
Architecture: all
Depends: ${misc:Depends},
strongswan-swanctl (>= 5.0),
charon-systemd (>= 5.0),
libstrongswan-extra-plugins,
libcharon-extra-plugins,
wireguard-tools,
ufw,
debconf,
ucf,
@@ -29,20 +24,26 @@ Depends: ${misc:Depends},
python3-psutil,
python3-prometheus-client,
python3-requests,
caddy,
avahi-daemon,
postgresql,
slapd,
nslcd,
libnss-ldapd,
libpam-ldapd,
sudo,
openvpn,
openvpn-auth-ldap,
iproute2,
systemd-resolved,
dnsmasq-base,
zstd
Recommends: bash-completion
Suggests: caddy,
Suggests: strongswan-swanctl (>= 5.0),
charon-systemd (>= 5.0),
libstrongswan-extra-plugins,
libcharon-extra-plugins,
wireguard-tools,
openvpn,
openvpn-auth-ldap,
dnsmasq-base,
rclone,
pdns-server,
pdns-backend-pgsql,
@@ -57,8 +58,8 @@ Description: Ubuntu Linux Manager: directory, PKI, web, optional router and VPN
user, and WireGuard; without the router its clients reach the server's
networks through NAT on one interface. Its two-level CA, whose root may be
kept offline, has issuing CAs for the VPN clients, for site-to-site and for
general use, and publishes their certificates and CRLs. Caddy, installed by
the package from the Ubuntu archive or from Caddy's repository, serves HTTPS
general use, and publishes their certificates and CRLs. Caddy, from the
Ubuntu archive, serves every HTTP and HTTPS port of the server's services
and static web sites, whose files are uploaded through the web service or
WebDAV, an optional PowerDNS name server answers for a zone of the sites,
and an optional OpenID Provider signs the directory's users in to other
+1 -1
View File
@@ -25,7 +25,6 @@ src/usr/sbin/linux-manager-token usr/sbin/
src/usr/sbin/linux-manager-config-edit usr/sbin/
src/usr/sbin/linux-manager-backup usr/sbin/
src/usr/sbin/linux-manager-ca usr/sbin/
src/usr/sbin/linux-manager-caddy usr/sbin/
src/usr/sbin/linux-manager-site usr/sbin/
src/usr/lib/linux-manager/configure usr/lib/linux-manager/
src/usr/lib/linux-manager/docker-rules usr/lib/linux-manager/
@@ -42,6 +41,7 @@ src/usr/lib/linux-manager/upgrade usr/lib/linux-manager/
src/usr/lib/linux-manager/linuxmanager_platforms/*.py usr/lib/linux-manager/linuxmanager_platforms/
src/usr/share/linux-manager/templates/* usr/share/linux-manager/templates/
src/usr/share/linux-manager/sql/* usr/share/linux-manager/sql/
src/usr/share/linux-manager/schema/* usr/share/linux-manager/schema/
src/usr/share/bash-completion/completions/*.bash usr/share/bash-completion/completions/
src/usr/lib/systemd/system/caddy.service.d/linux-manager.conf usr/lib/systemd/system/caddy.service.d/
src/usr/share/doc/linux-manager/linux-manager.json.example usr/share/doc/linux-manager/
@@ -1,10 +0,0 @@
[Unit]
Description=Linux Manager Caddy installation
Documentation=file:/usr/share/doc/linux-manager/README.md
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/sbin/linux-manager-caddy apply
TimeoutStartSec=20min
+14 -1
View File
@@ -24,6 +24,7 @@ case "$1" in
answer linux-manager/external_interface; LINUX_MANAGER_EXTERNAL_INTERFACE="$ANSWER"
answer linux-manager/internal_interface; LINUX_MANAGER_INTERNAL_INTERFACE="$ANSWER"
answer linux-manager/local_fqdn; LINUX_MANAGER_LOCAL_FQDN="$ANSWER"
answer linux-manager/https_disable_auto_redirect; LINUX_MANAGER_HTTPS_DISABLE_AUTO_REDIRECT="$ANSWER"
answer linux-manager/local_id_mode; LINUX_MANAGER_LOCAL_ID_MODE="$ANSWER"
answer linux-manager/local_cidrs; LINUX_MANAGER_LOCAL_CIDRS="$ANSWER"
answer linux-manager/int_gateway_ip; LINUX_MANAGER_INT_GATEWAY_IP="$ANSWER"
@@ -33,7 +34,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"
@@ -42,12 +45,14 @@ case "$1" in
LINUX_MANAGER_ROUTER_ENABLED LINUX_MANAGER_VPN_ENABLED \
LINUX_MANAGER_EXTERNAL_INTERFACE \
LINUX_MANAGER_INTERNAL_INTERFACE LINUX_MANAGER_LOCAL_FQDN \
LINUX_MANAGER_HTTPS_DISABLE_AUTO_REDIRECT \
LINUX_MANAGER_LOCAL_ID_MODE LINUX_MANAGER_LOCAL_CIDRS \
LINUX_MANAGER_INT_GATEWAY_IP \
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 +87,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.
+3 -3
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 \
@@ -72,7 +73,7 @@ case "$1" in
# The name service no longer looks up the console accounts of the server's directory.
sed -i '/^passwd:/s/ ldap\b//' /etc/nsswitch.conf
rm -rf /var/lib/linux-manager/backup/staging /var/lib/linux-manager/backup/restore \
/var/lib/linux-manager/pki-publish /etc/caddy/linux-manager-pki /etc/caddy/linux-manager-sites \
/var/lib/linux-manager/pki-publish /etc/caddy/linux-manager-pki /etc/caddy/linux-manager-https /etc/caddy/linux-manager-sites \
/etc/openvpn/server/linux-manager-ca.pem /etc/openvpn/server/linux-manager-crl.pem
rmdir --ignore-fail-on-non-empty /var/lib/linux-manager/backup /var/lib/linux-manager 2>/dev/null || true
@@ -99,8 +100,7 @@ case "$1" in
# in slapd, the WireGuard key pair, everything under /etc/swanctl, the
# files of the web sites in /var/lib/linux-manager/sites, the backups and
# what a restore replaced are left in place. Caddy, rclone and PowerDNS
# stay installed, so Caddy's repository, which linux-manager-caddy
# configures, stays too.
# stay installed.
rmdir --ignore-fail-on-non-empty /etc/linux-manager 2>/dev/null || true
;;
esac
-1
View File
@@ -14,7 +14,6 @@ override_dh_installsystemd:
dh_installsystemd --name=linux-manager-bootstrap --no-enable --no-start
dh_installsystemd --name=linux-manager-backup --no-enable --no-start
dh_installsystemd --name=linux-manager-pki --no-enable --no-start
dh_installsystemd --name=linux-manager-caddy --no-enable --no-start
dh_installsystemd --name=linux-manager-webdav --no-enable --no-start
dh_installsystemd --name=linux-manager-resolver --no-enable --no-start
dh_installsystemd --name=linux-manager-install@ --no-enable --no-start
+46 -2
View File
@@ -95,6 +95,16 @@ Description: Local router FQDN:
router.example.com). Used as the IKEv2 server identity and
certificate common name.
Template: linux-manager/https_disable_auto_redirect
Type: boolean
Default: false
Description: Keep the status page and the Manager available over plain HTTP?
Caddy always serves the status page and the Manager over HTTPS, for the
router FQDN or, without one, for the host name and <host name>.local. If
enabled, both also answer on their plain HTTP ports by name. Otherwise a
request by name on those ports is redirected to HTTPS; the status page stays
available over plain HTTP by address.
Template: linux-manager/local_id_mode
Type: select
Choices: fqdn, public_ip, internal_ip
@@ -166,12 +176,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
@@ -7,8 +7,8 @@ this script never writes to /etc and never has to worry about destroying an
administrator's edits.
The candidate is the current /etc/linux-manager/linux-manager.json as it is, or the
shipped defaults when there is none, with every debconf answer that was given
written over it. Without an answer that changes it, the candidate is the current
shipped defaults when there is none, with https.certificate empty for the first
setup to choose, with every debconf answer that was given written over it. Without an answer that changes it, the candidate is the current
file byte for byte, so
an upgrade or a reconfiguration that changes nothing gives ucf nothing to ask;
defaults the file leaves out are applied by linuxmanager.load_config() when the
@@ -43,6 +43,7 @@ ANSWERS = {
'LINUX_MANAGER_EXTERNAL_INTERFACE': (('interfaces', 'external'),),
'LINUX_MANAGER_INTERNAL_INTERFACE': (('interfaces', 'internal'),),
'LINUX_MANAGER_LOCAL_FQDN': (('wan', 'local_fqdn'),),
'LINUX_MANAGER_HTTPS_DISABLE_AUTO_REDIRECT': (('https', 'disable_auto_redirect'),),
'LINUX_MANAGER_LOCAL_ID_MODE': ((*FIRST, 'local_id_mode'),),
'LINUX_MANAGER_LOCAL_CIDRS': (('local', 'cidrs'), (*FIRST, 'local_cidrs')),
'LINUX_MANAGER_INT_GATEWAY_IP': (('local', 'int_gateway_ip'),),
@@ -52,7 +53,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'),),
@@ -71,6 +74,8 @@ def main():
current = None
if current is None:
cfg = linuxmanager.load_config()
# A new installation leaves the source of the HTTPS certificate to its first setup.
cfg['https']['certificate'] = ''
else:
try:
cfg = json.loads(current)
@@ -1,19 +1,31 @@
#!/usr/bin/python3
"""Install the packages of a feature from the Ubuntu archive, then restart linux-manager-setup without waiting.
"""Install the packages of a component from the Ubuntu archive, then have linux-manager-setup run without waiting.
Run by linux-manager-install@<feature>.service, which linux-manager-setup starts when the feature is on and its packages are
missing: webdav (rclone) and dns (PowerDNS with its gpgsql backend). Recommended packages are left out, so PowerDNS
comes without its bind backend. A failure is a message on standard error and the exit status 1.
Run by linux-manager-install@<component>.service, which linux-manager-setup starts when the component is on and its
packages are missing or marked as installed automatically: the components and their packages are
linuxmanager.COMPONENTS, the VPN, the router, the name server (PowerDNS with its gpgsql backend) and WebDAV (rclone).
Recommended packages are left out, so PowerDNS comes without its bind backend. apt-get marks the packages as installed
by hand. Installations of several components run one after another (INSTALL_LOCK), as apt locks its package lists.
A run of setup in progress, the one that started the installation, runs again when it ends (request_setup). A failure
is a message on standard error and the exit status 1.
install-packages FEATURE
install-packages COMPONENT
"""
import fcntl
import os
import subprocess
import sys
#: The packages of each feature.
FEATURES = {'webdav': ['rclone'], 'dns': ['pdns-server', 'pdns-backend-pgsql']}
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
import linuxmanager # noqa: E402
#: The packages of each component.
FEATURES = {name: packages for name, (_, packages) in linuxmanager.COMPONENTS.items()}
#: The lock that has the installations of several components run one after another.
INSTALL_LOCK = '/run/linux-manager-install.lock'
#: apt-get, waiting up to ten minutes for dpkg's lock, which a package installation that runs setup holds.
APT = ['apt-get', '-o', 'DPkg::Lock::Timeout=600']
@@ -23,12 +35,15 @@ def main():
if len(sys.argv) != 2 or sys.argv[1] not in FEATURES:
sys.exit(f'usage: install-packages {"|".join(FEATURES)}')
environment = dict(os.environ, DEBIAN_FRONTEND='noninteractive')
lock = open(INSTALL_LOCK, 'w', encoding='utf-8')
fcntl.flock(lock, fcntl.LOCK_EX)
for args in ([*APT, 'update'], [*APT, '-y', '--no-install-recommends', '-o', 'Dpkg::Options::=--force-confdef',
'-o', 'Dpkg::Options::=--force-confold', 'install', *FEATURES[sys.argv[1]]]):
print(f'$ {" ".join(args)}', flush=True)
if subprocess.run(args, env=environment).returncode != 0:
sys.exit(f'install-packages: {args[0]} failed')
subprocess.run(['systemctl', 'restart', '--no-block', 'linux-manager-setup.service'])
lock.close()
linuxmanager.request_setup()
return 0
@@ -12,8 +12,11 @@ import os
import pathlib
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import urllib.parse
import jinja2
@@ -27,12 +30,21 @@ import linuxmanager_ldap
import linuxmanager_pki
import linuxmanager_platforms
import linuxmanager_status
from linuxmanager_net import DEFAULT_LISTEN, LISTEN_CHOICES, LOOPBACK, ConfigError, detect_interfaces, interface_addresses, ip_output
from linuxmanager_net import DEFAULT_LISTEN, LISTEN_CHOICES, LOOPBACK, MANAGER_LOOPBACK_PORT, METRICS_LOOPBACK_PORT, \
WEB_LOOPBACK_PORT, ConfigError, detect_interfaces, interface_addresses, ip_output
CONFIG_FILE = pathlib.Path('/etc/linux-manager/linux-manager.json')
CONFIG_LOCK = pathlib.Path('/run/linux-manager/config.lock')
#: What setup resolved and runs, for the web service (setup's refresh_web).
WEB_STATE = pathlib.Path('/run/linux-manager/web.json')
#: The unit of linux-manager-setup, which request_setup runs.
SETUP_UNIT = 'linux-manager-setup.service'
#: The lock under which a run of setup is requested and a run of setup decides whether to run again.
SETUP_LOCK = pathlib.Path('/run/linux-manager/setup.lock')
#: The lock a run of setup holds while it applies the configuration.
SETUP_RUNNING = pathlib.Path('/run/linux-manager/setup.running')
#: The file that asks a run of setup in progress to run once more when it ends.
SETUP_REQUEST = pathlib.Path('/run/linux-manager/setup.request')
TEMPLATE_DIR = pathlib.Path('/usr/share/linux-manager/templates')
SWANCTL_CONF_D = pathlib.Path('/etc/swanctl/conf.d')
@@ -68,15 +80,18 @@ SCHEMA = {
'status_content': 'basic', 'shell': False, 'shell_idle_minutes': 15, 'shell_auth_timeout': 15,
'log_files': []},
'ssh': {'ldap_login': False},
'https': {'enabled': True, 'email': '', 'web_port': 7444, 'manager_port': 7443, 'caddy_source': 'ubuntu',
'acme_staging': False},
'https': {'email': '', 'web_port': 7444, 'manager_port': 7443, 'ip_sans': False,
'disable_auto_redirect': False, 'acme_staging': False, 'certificate': 'self-signed', 'self_signed_days': 365,
'acme_provider': 'letsencrypt', 'acme_url': '', 'acme_eab_key_id': '', 'acme_eab_mac_key': '',
'zerossl_api_key': ''},
'oidc': {'enabled': False},
'sites': {'enabled': False, 'upload_max_mb': 512, 'webdav': False, 'webdav_port': 7445},
'dns': {'enabled': False, 'secondary': '', 'listen': 'external', 'ttl': 300},
'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},
'crl_days': 7, 'root_crl_days': 180, 'p2s_name': 'Linux Manager VPN CA',
's2s_name': 'Linux Manager Site-to-Site CA', 'servers_name': 'Linux Manager Servers CA',
'issuing_cas': {}, 'templates': {},
'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',
@@ -134,7 +149,7 @@ PBS_NAMESPACE = re.compile(r'^[A-Za-z0-9_][A-Za-z0-9._-]*(/[A-Za-z0-9_][A-Za-z0-
#: The port of Let's Encrypt's HTTP challenge, which Caddy answers while HTTPS is on.
ACME_HTTP_PORT = 80
#: The default port of HTTPS, where Caddy publishes the CA files when pki.publish has https-default.
#: The default port of HTTPS.
HTTPS_DEFAULT_PORT = 443
#: The most files web.log_files lists.
@@ -143,12 +158,23 @@ LOG_FILES_MAX = 32
#: The port rclone serves WebDAV on, on the loopback address, behind Caddy.
WEBDAV_LOOPBACK_PORT = 7446
#: The installable components, managed on the Manager's System tab: name -> (section, setting) of their switch and the
#: packages linux-manager-install@<name> installs from the Ubuntu archive while the switch is on.
STRONGSWAN_PACKAGES = ('strongswan-swanctl', 'charon-systemd', 'libstrongswan-extra-plugins', 'libcharon-extra-plugins')
COMPONENTS = {
'vpn': (('vpn', 'enabled'), (*STRONGSWAN_PACKAGES, 'openvpn', 'openvpn-auth-ldap', 'wireguard-tools', 'dnsmasq-base')),
'router': (('router', 'enabled'), STRONGSWAN_PACKAGES),
'dns': (('dns', 'enabled'), ('pdns-server', 'pdns-backend-pgsql')),
'webdav': (('sites', 'webdav'), ('rclone',)),
}
#: The largest sites.upload_max_mb, 10 GiB.
UPLOAD_MAX_MB = 10240
#: Settings that no longer exist, section -> options, left out when the file is read so that a file of an earlier
#: version loads: the name server is wan.local_fqdn and a site chooses the address of its records.
RETIRED = {'dns': ('nameserver', 'addresses')}
#: version loads: the name server is wan.local_fqdn, a site chooses the address of its records, and the CA certificates
#: and CRLs are always published, and HTTPS is always on.
RETIRED = {'dns': ('nameserver', 'addresses'), 'pki': ('publish',), 'https': ('enabled',)}
#: The shortest and the longest dns.ttl, in seconds.
DNS_TTL_RANGE = (60, 86400)
@@ -167,23 +193,26 @@ BOOTSTRAP_PORTS = (17081,)
MANAGER_CONFIG = pathlib.Path('/etc/linux-manager/manager.json')
MANAGER_PORT = 7080
#: Where linux-manager-setup installs Caddy from, https.caddy_source: the Ubuntu archive or Caddy's own repository.
CADDY_SOURCES = ('ubuntu', 'upstream')
#: The ACME directory of Let's Encrypt's staging environment, Caddy's only CA while https.acme_staging is true.
ACME_STAGING_CA = 'https://acme-staging-v02.api.letsencrypt.org/directory'
#: Caddy's own repository, which https.caddy_source upstream configures: the source, its signing key and their URLs.
CADDY_APT_SOURCE = pathlib.Path('/etc/apt/sources.list.d/caddy-stable.sources')
CADDY_KEYRING = pathlib.Path('/etc/apt/keyrings/caddy-stable.asc')
CADDY_KEY_URL = 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key'
CADDY_REPOSITORY = 'https://dl.cloudsmith.io/public/caddy/stable/deb/debian'
#: The ACME directory of Let's Encrypt's production CA.
ACME_PRODUCTION_CA = 'https://acme-v02.api.letsencrypt.org/directory'
#: Where the certificate of wan.local_fqdn comes from, https.certificate: ACME, a self-signed certificate, the
#: Servers Issuing CA (servers), or a certificate of another CA, imported; self-signed when not set. A new installation's
#: configuration file has it empty (generate-config) until the first setup chooses ca or self-signed
#: (linuxmanager_pki.provision).
HTTPS_CERTIFICATES = ('acme', 'self-signed', 'ca', 'external')
#: The ACME CA of the server and of the web sites with TLS acme, https.acme_provider.
ACME_PROVIDERS = ('letsencrypt', 'zerossl', 'custom')
#: 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 CA certificates and CRLs are published, pki.publish, as the URLs in the certificates list them.
PKI_PUBLISH = ('http', 'http-80', 'https', 'https-default')
#: 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')
#: The key usages a template may give, as the arguments of cryptography's KeyUsage.
KEY_USAGES = ('digital_signature', 'content_commitment', 'key_encipherment', 'data_encipherment', 'key_agreement')
@@ -221,7 +250,7 @@ PKI_TEMPLATES = {
'vpn-server': {'key_usage': ['digital_signature', 'key_encipherment'],
'extended_key_usage': ['server_auth', 'ike_intermediate'], 'subject': 'dns', 'sans': ['dns', 'ip']},
'vpn-user': {'extended_key_usage': ['client_auth'], 'subject': 'name', 'sans': ['dns', 'email']},
'site-to-site': {'key_usage': ['digital_signature', 'key_encipherment'],
'mtls': {'key_usage': ['digital_signature', 'key_encipherment'],
'extended_key_usage': ['server_auth', 'client_auth'], 'subject': 'dns', 'sans': ['dns', 'ip']},
'server': {'key_usage': ['digital_signature', 'key_encipherment'], 'extended_key_usage': ['server_auth'],
'subject': 'dns', 'sans': ['dns', 'ip']},
@@ -231,8 +260,11 @@ PKI_TEMPLATES = {
#: The templates only the server issues: its VPN server certificate and the users' certificates.
ROUTER_TEMPLATES = ('vpn-server', 'vpn-user')
#: The built-in issuing CAs: name -> the pki option of the common name and the templates the CA issues.
BUILTIN_CAS = {'p2s': ('p2s_name', ['vpn-server', 'vpn-user']), 's2s': ('s2s_name', ['site-to-site'])}
#: The built-in issuing CAs: name -> the pki option of the common name and the templates the CA issues: the VPN, the
#: site-to-site connections, and the Servers Issuing CA of mTLS certificates, which also signs the server's HTTPS
#: certificate.
BUILTIN_CAS = {'p2s': ('p2s_name', ['vpn-server', 'vpn-user']), 's2s': ('s2s_name', ['mtls']),
'servers': ('servers_name', ['mtls'])}
#: A general-purpose issuing CA of pki.issuing_cas: option -> default, the type of the default being the required type.
ISSUING_CA = {'name': '', 'templates': [], 'acme': False}
@@ -347,6 +379,45 @@ def config_lock():
yield
def setup_lock():
"""The open SETUP_LOCK, held; closing it releases the lock."""
SETUP_LOCK.parent.mkdir(parents=True, exist_ok=True)
handle = open(SETUP_LOCK, 'a', encoding='utf-8')
fcntl.flock(handle, fcntl.LOCK_EX)
return handle
def request_setup(wait=False):
"""Have linux-manager-setup apply the configuration; with wait, True when it has applied it and its last run
succeeded, without wait, True when the run was requested.
A run in progress is not cut short: it holds SETUP_RUNNING, and the request, SETUP_REQUEST, has it run once more
when it ends, however many requests it got. Without a run in progress the unit is restarted. The request is made
under SETUP_LOCK, under which a run of setup also decides whether to end, so no request is missed.
"""
with setup_lock():
SETUP_REQUEST.touch()
with open(SETUP_RUNNING, 'a', encoding='utf-8') as running:
try:
fcntl.flock(running, fcntl.LOCK_EX | fcntl.LOCK_NB)
idle = True
except BlockingIOError:
idle = False
if idle:
restart = subprocess.run(['systemctl', 'restart', '--no-block', SETUP_UNIT], capture_output=True)
if restart.returncode != 0:
return False
# The unit's start job, the restarted run or the run in progress with its further runs, is waited for.
while wait:
state = subprocess.run(['systemctl', 'show', '-p', 'Job,ActiveState,Result', SETUP_UNIT],
capture_output=True, text=True).stdout
values = dict(line.partition('=')[::2] for line in state.splitlines())
if not values.get('Job') and values.get('ActiveState') != 'activating':
return values.get('ActiveState') == 'active' and values.get('Result') == 'success'
time.sleep(1)
return True
def save_config(data):
"""Write the settings to the configuration file, indented, with mode 0600, replacing it in one step.
@@ -363,6 +434,19 @@ def save_config(data):
raise
def choose_https_certificate(cfg, ctx, source):
"""Write https.certificate, empty until then, as source into the configuration file, and into cfg and ctx for the
rest of the run: the first setup's choice of the server's HTTPS certificate."""
with config_lock():
data = read_settings()
section = data.get('https')
data['https'] = {**(section if isinstance(section, dict) else {}), 'certificate': source}
save_config(data)
cfg['https']['certificate'] = source
ctx['https_certificate'] = source
warn(f'https.certificate is set to {source}, chosen by the first setup')
def _split_list(value):
return [item.strip() for item in value.split(',') if item.strip()]
@@ -583,22 +667,34 @@ def validate(cfg):
if not item.startswith('/') or '/../' in f'{item}/':
raise ConfigError(f'web.log_files: {item!r} is not an absolute path')
caddy_source = _get(cfg, 'https', 'caddy_source')
if caddy_source not in CADDY_SOURCES:
raise ConfigError(f'https.caddy_source: {caddy_source!r} is not one of {", ".join(CADDY_SOURCES)}')
if _get(cfg, 'https', 'certificate') not in ('', *HTTPS_CERTIFICATES):
raise ConfigError(f'https.certificate: {_get(cfg, "https", "certificate")!r} is not one of '
f'{", ".join(HTTPS_CERTIFICATES)}, or empty for the next setup to choose')
if not 1 <= _get(cfg, 'https', 'self_signed_days') <= 3650:
raise ConfigError('https.self_signed_days must be 1 to 3650 days')
provider = _get(cfg, 'https', 'acme_provider')
if provider not in ACME_PROVIDERS:
raise ConfigError(f'https.acme_provider: {provider!r} is not one of {", ".join(ACME_PROVIDERS)}')
acme_url = _get(cfg, 'https', 'acme_url')
if provider == 'custom' and not acme_url:
raise ConfigError('https.acme_url is required while https.acme_provider is custom')
if acme_url:
parts = urllib.parse.urlsplit(acme_url)
if parts.scheme != 'https' or not parts.hostname or parts.fragment:
raise ConfigError('https.acme_url must be an https:// URL without a fragment')
for option in ('email', 'acme_url', 'acme_eab_key_id', 'acme_eab_mac_key', 'zerossl_api_key'):
if any(character.isspace() or character in '{}"' for character in _get(cfg, 'https', option)):
raise ConfigError(f'https.{option} must not hold spaces, braces or quotes')
if _get(cfg, 'https', 'certificate') == 'acme' and not _get(cfg, 'wan', 'local_fqdn'):
raise ConfigError('https.certificate: an ACME CA issues the certificate of wan.local_fqdn, which is not set')
if _get(cfg, 'oidc', 'enabled') and not (_get(cfg, 'web', 'enabled') and _get(cfg, 'https', 'enabled')
and _get(cfg, 'wan', 'local_fqdn')):
if _get(cfg, 'oidc', 'enabled') and not _get(cfg, 'web', 'enabled'):
raise ConfigError('oidc.enabled: the OpenID Provider is the web service served by Caddy at '
'https://<wan.local_fqdn>:<https.web_port>, which needs web.enabled, https.enabled and '
'wan.local_fqdn')
'https://<HTTPS name>:<https.web_port>, which needs web.enabled')
upload_max = _get(cfg, 'sites', 'upload_max_mb')
if not 1 <= upload_max <= UPLOAD_MAX_MB:
raise ConfigError(f'sites.upload_max_mb: {upload_max} is not between 1 and {UPLOAD_MAX_MB}')
if _get(cfg, 'sites', 'webdav') and not (_get(cfg, 'https', 'enabled') and _get(cfg, 'wan', 'local_fqdn')):
raise ConfigError('sites.webdav: WebDAV is served by Caddy at https://<wan.local_fqdn>:<sites.webdav_port>, '
'which needs https.enabled and wan.local_fqdn')
_check_address(_get(cfg, 'wan', 'public_address'), 'wan.public_address')
dns = cfg['dns']
@@ -631,27 +727,24 @@ def validate(cfg):
f'addresses is the resolver of the remote access clients (p2s.dns_listen {resolver_listen}) '
'while p2s.enabled, openvpn.enabled or wireguard.enabled is true')
for option in ('root_name', 'p2s_name', 's2s_name'):
for option in ('root_name', 'p2s_name', 's2s_name', 'servers_name'):
value = _get(cfg, 'pki', option)
if not value or len(value) > CA_NAME_MAX or not value.isprintable():
raise ConfigError(f'pki.{option} must have 1 to {CA_NAME_MAX} printable characters')
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')
for item in publish:
if item not in PKI_PUBLISH:
raise ConfigError(f'pki.publish: {item!r} is not one of {", ".join(PKI_PUBLISH)}')
if len(set(publish)) != len(publish):
raise ConfigError('pki.publish names an endpoint twice')
if publish and not _get(cfg, 'wan', 'local_fqdn'):
raise ConfigError('pki.publish needs wan.local_fqdn, the name in the published URLs')
if 'http' in publish and not _get(cfg, 'web', 'enabled'):
raise ConfigError('pki.publish: http is served by the web service, which needs web.enabled')
if set(publish) - {'http'} and not _get(cfg, 'https', 'enabled'):
raise ConfigError('pki.publish: http-80, https and https-default are served by Caddy, which needs https.enabled')
for name, oid in cfg['pki']['extended_key_usages'].items():
prefix = f'pki.extended_key_usages.{name}'
if not EKU_NAME.match(name) or name in EXTENDED_KEY_USAGES:
@@ -689,9 +782,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 or '
f'{", ".join(BUILTIN_CAS)}')
if not isinstance(authority, dict):
raise ConfigError(f'{prefix} must be {TYPE_NAMES[dict]}')
_check_options(authority, ISSUING_CA, prefix)
@@ -709,18 +803,18 @@ def validate(cfg):
raise ConfigError(f'{prefix}.templates: {template!r} is not a template')
if template in ROUTER_TEMPLATES:
raise ConfigError(f'{prefix}.templates: {template} is issued by the P2S CA only')
if authority['acme'] and not _get(cfg, 'https', 'enabled'):
raise ConfigError(f'{prefix}.acme: the ACME server is Caddy\'s, which needs https.enabled')
taken = {web_port: 'web.port', ACME_HTTP_PORT: 'the HTTP challenge',
https_ports[0]: 'https.web_port', https_ports[1]: 'https.manager_port'}
if 'https-default' in publish:
if HTTPS_DEFAULT_PORT in taken:
raise ConfigError(f'pki.publish: https-default takes port {HTTPS_DEFAULT_PORT}, the port of '
f'{taken[HTTPS_DEFAULT_PORT]}')
if _get(cfg, 'openvpn', 'protocol') == 'tcp' and _get(cfg, 'openvpn', 'port') == HTTPS_DEFAULT_PORT:
raise ConfigError(f'pki.publish: https-default takes port {HTTPS_DEFAULT_PORT}, the port of openvpn.port')
taken[HTTPS_DEFAULT_PORT] = 'pki.publish https-default'
# Caddy serves the Manager's plain HTTP port and calls the services on their loopback ports.
for port, owner in ((manager_port(), f"the Manager's port in {MANAGER_CONFIG}"),
(WEB_LOOPBACK_PORT, 'the web service behind Caddy'),
(MANAGER_LOOPBACK_PORT, 'the Manager behind Caddy'),
(METRICS_LOOPBACK_PORT, 'the metrics service behind Caddy'),
(WEBDAV_LOOPBACK_PORT, 'WebDAV behind Caddy')):
if port in taken:
raise ConfigError(f'{taken[port]}: {port} is the port of {owner}')
taken[port] = owner
for section_name, option in (('metrics', 'port'), ('metrics', 'https_port'), ('sites', 'webdav_port')):
port = _get(cfg, section_name, option)
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
@@ -800,13 +894,10 @@ def validate(cfg):
f'docker.exposed_ports: {item!r} is not a port or a port range')
weight += 2 if ':' in item else 1
first, _, last = item.partition(':')
if _get(cfg, 'https', 'enabled'):
caddy_ports = (ACME_HTTP_PORT, *https_ports, *([HTTPS_DEFAULT_PORT] if 'https-default' in publish else []))
for port in caddy_ports:
if int(first) <= port <= int(last or first):
raise ConfigError(
f'docker.exposed_ports: {item!r} takes port {port}, which Caddy serves while '
'https.enabled is true')
caddy_ports = (web_port, manager_port(), _get(cfg, 'metrics', 'port'), ACME_HTTP_PORT, *https_ports)
for port in caddy_ports:
if int(first) <= port <= int(last or first):
raise ConfigError(f'docker.exposed_ports: {item!r} takes port {port}, which Caddy serves')
if weight > DOCKER_PORT_LIMIT:
raise ConfigError(
f'docker.exposed_ports: at most {DOCKER_PORT_LIMIT} ports are allowed, '
@@ -834,8 +925,8 @@ def extended_key_usages(cfg):
def issuing_cas(cfg):
"""The issuing CAs, name -> {name, templates, acme, builtin}: p2s and s2s (BUILTIN_CAS) with their common names from
the pki section, then those of pki.issuing_cas, each filled from ISSUING_CA."""
"""The issuing CAs, name -> {name, templates, acme, builtin}: p2s, s2s and servers (BUILTIN_CAS) with their common names
from the pki section, then those of pki.issuing_cas, each filled from ISSUING_CA."""
found = {name: {'name': _get(cfg, 'pki', option), 'templates': list(templates), 'acme': False, 'builtin': True}
for name, (option, templates) in BUILTIN_CAS.items()}
for name, options in cfg['pki']['issuing_cas'].items():
@@ -845,19 +936,19 @@ def issuing_cas(cfg):
def pki_base_urls(cfg):
"""The base URLs, ending in /, under which the CA certificates and CRLs are published, in the order of pki.publish."""
"""The plain HTTP base URLs, ending in /, under which Caddy publishes the CA certificates and CRLs and the
certificates name them: the status web service's web.port while it is enabled, then the Manager's port; none without
wan.local_fqdn."""
fqdn = _get(cfg, 'wan', 'local_fqdn')
bases = {
'http': f'http://{fqdn}:{_get(cfg, "web", "port")}/pki/',
'http-80': f'http://{fqdn}/pki/',
'https': f'https://{fqdn}:{_get(cfg, "https", "web_port")}/pki/',
'https-default': f'https://{fqdn}/pki/',
}
return [bases[item] for item in _get_list(cfg, 'pki', 'publish') if item in bases] if fqdn else []
if not fqdn:
return []
ports = [*([_get(cfg, 'web', 'port')] if _get(cfg, 'web', 'enabled') else []), manager_port()]
return [f'http://{fqdn}:{port}/pki/' for port in ports]
def manager_port():
"""The port of the Manager: port in its settings, or MANAGER_PORT when it is not set or not a port."""
"""The port of the Manager, Caddy's plain HTTP site of it: port in its settings, or MANAGER_PORT when it is not set
or not a port."""
try:
port = json.loads(MANAGER_CONFIG.read_text(encoding='utf-8')).get('port')
except (OSError, ValueError, AttributeError):
@@ -865,10 +956,21 @@ def manager_port():
return port if isinstance(port, int) and not isinstance(port, bool) and 1 <= port <= 65535 else MANAGER_PORT
def manager_listen():
"""The interfaces the firewall opens the Manager's port on: listen in its settings, one of LISTEN_CHOICES, or
DEFAULT_LISTEN when it is not set or not one."""
try:
choice = json.loads(MANAGER_CONFIG.read_text(encoding='utf-8')).get('listen')
except (OSError, ValueError, AttributeError):
return DEFAULT_LISTEN
return choice if choice in LISTEN_CHOICES else DEFAULT_LISTEN
def oidc_issuer(cfg):
"""The issuer of the OpenID Provider: the web service's HTTPS site, without the port when it is HTTPS_DEFAULT_PORT."""
"""The issuer of the OpenID Provider: the web service's HTTPS site on the first HTTPS name, without the port when it
is HTTPS_DEFAULT_PORT."""
port = _get(cfg, 'https', 'web_port')
return f'https://{_get(cfg, "wan", "local_fqdn")}' + ('' if port == HTTPS_DEFAULT_PORT else f':{port}')
return f'https://{https_names(cfg)[0]}' + ('' if port == HTTPS_DEFAULT_PORT else f':{port}')
def resolve_psk(connection, name):
@@ -1021,6 +1123,8 @@ def build_context(cfg, public_ip=None):
'mode': _get(cfg, 'general', 'mode') or 'manual',
'router_enabled': _get(cfg, 'router', 'enabled'),
'vpn_enabled': _get(cfg, 'vpn', 'enabled'),
'router_installed': packages_installed(COMPONENTS['router'][1]),
'vpn_installed': packages_installed(COMPONENTS['vpn'][1]),
'wan_iface': ext_iface,
'int_iface': int_iface,
'local_addrs': ', '.join(local_addrs),
@@ -1067,15 +1171,25 @@ def build_context(cfg, public_ip=None):
'ldap_users': linuxmanager_ldap.USERS,
'web_enabled': _get(cfg, 'web', 'enabled'),
'web_port': _get(cfg, 'web', 'port'),
'https_enabled': _get(cfg, 'https', 'enabled'),
'web_listen': _get(cfg, 'web', 'listen'),
'https_names': https_names(cfg),
'https_ips': https_addresses(cfg, local_addrs, int_addr),
'mdns': not local_fqdn,
'https_email': _get(cfg, 'https', 'email'),
'https_acme_ca': ACME_STAGING_CA if _get(cfg, 'https', 'acme_staging') else '',
'https_certificate': _get(cfg, 'https', 'certificate'),
'https_acme_provider': _get(cfg, 'https', 'acme_provider'),
'https_acme_url': (_get(cfg, 'https', 'acme_url') if _get(cfg, 'https', 'acme_provider') == 'custom'
else ACME_STAGING_CA if _get(cfg, 'https', 'acme_staging') else ACME_PRODUCTION_CA),
'https_acme_eab': ((_get(cfg, 'https', 'acme_eab_key_id'), _get(cfg, 'https', 'acme_eab_mac_key'))
if _get(cfg, 'https', 'acme_eab_key_id') and _get(cfg, 'https', 'acme_eab_mac_key')
else None),
'https_zerossl_api_key': _get(cfg, 'https', 'zerossl_api_key'),
'https_web_port': _get(cfg, 'https', 'web_port'),
'https_manager_port': _get(cfg, 'https', 'manager_port'),
'pki_publish': _get_list(cfg, 'pki', 'publish'),
'pki_acme': [name for name, authority in issuing_cas(cfg).items() if authority['acme']],
'metrics_enabled': _get(cfg, 'metrics', 'enabled'),
'metrics_port': _get(cfg, 'metrics', 'port'),
'metrics_listen': _get(cfg, 'metrics', 'listen'),
'metrics_https_port': _get(cfg, 'metrics', 'https_port'),
'metrics_service_account': _get(cfg, 'metrics', 'service_account'),
'sites_enabled': _get(cfg, 'sites', 'enabled'),
@@ -1088,8 +1202,8 @@ def build_context(cfg, public_ip=None):
def s2s_ready(ctx):
"""True when the router is on and any site_to_site connection is ready."""
return bool(ctx['router_enabled'] and any(connection['ready'] for connection in ctx['connections']))
"""True when the router is on and installed and any site_to_site connection is ready."""
return bool(ctx['router_enabled'] and ctx['router_installed'] and any(connection['ready'] for connection in ctx['connections']))
def routing_ready(ctx):
@@ -1099,19 +1213,21 @@ def routing_ready(ctx):
def p2s_ready(ctx):
"""IKEv2 access needs the VPN on, its settings and the server's VPN server certificate, which the P2S CA issues."""
return bool(ctx['vpn_enabled'] and ctx['p2s_enabled'] and ctx['p2s_address_pool'] and ctx['local_fqdn']
"""IKEv2 access needs the VPN on and installed, its settings and the server's VPN server certificate, which the P2S
CA issues."""
return bool(ctx['vpn_enabled'] and ctx['vpn_installed'] and ctx['p2s_enabled'] and ctx['p2s_address_pool'] and ctx['local_fqdn']
and ctx['server_certificate'])
def wg_ready(ctx):
"""WireGuard needs the VPN on and its settings."""
return bool(ctx['vpn_enabled'] and ctx['wg_enabled'] and ctx['wg_address'])
"""WireGuard needs the VPN on and installed and its settings."""
return bool(ctx['vpn_enabled'] and ctx['vpn_installed'] and ctx['wg_enabled'] and ctx['wg_address'])
def openvpn_ready(ctx):
"""OpenVPN needs the VPN on, its settings and the server's VPN server certificate, which the P2S CA issues."""
return bool(ctx['vpn_enabled'] and ctx['openvpn_enabled'] and ctx['openvpn_pool'] and ctx['local_fqdn']
"""OpenVPN needs the VPN on and installed, its settings and the server's VPN server certificate, which the P2S CA
issues."""
return bool(ctx['vpn_enabled'] and ctx['vpn_installed'] and ctx['openvpn_enabled'] and ctx['openvpn_pool'] and ctx['local_fqdn']
and ctx['server_certificate'])
@@ -1122,9 +1238,30 @@ def vpn_pools(ctx):
(wg_ready(ctx), ctx['wg_network'])) if ready]
def https_ready(ctx):
"""Caddy serves HTTPS once it is enabled and wan.local_fqdn names the certificate."""
return bool(ctx['https_enabled'] and ctx['local_fqdn'])
def https_names(cfg):
"""The names of the server's HTTPS certificate and sites: wan.local_fqdn alone when it is set, else the host name
and <host name>.local, which Avahi announces with mDNS."""
fqdn = _get(cfg, 'wan', 'local_fqdn').lower()
if fqdn:
return [fqdn]
host = socket.gethostname().split('.')[0].lower()
return [host, f'{host}.local']
def https_addresses(cfg, local_addrs, int_addr):
"""The IP addresses of the server's HTTPS certificate and sites while https.ip_sans is on: those of its interfaces
and wan.public_address, without link-local ones; [] while it is off."""
if not _get(cfg, 'https', 'ip_sans'):
return []
found = []
for value in (*local_addrs, int_addr, _get(cfg, 'wan', 'public_address')):
try:
address = ipaddress.ip_address(str(value).split('/')[0])
except ValueError:
continue
if not address.is_link_local and str(address) not in found:
found.append(str(address))
return found
def metrics_ready(ctx):
@@ -1133,8 +1270,27 @@ def metrics_ready(ctx):
def webdav_ready(ctx):
"""WebDAV of the sites' folders is served by Caddy, on the server's own name, while it is on and HTTPS is ready."""
return bool(ctx['webdav_enabled'] and https_ready(ctx))
"""WebDAV of the sites' folders is served by Caddy, on the server's HTTPS names, while it is on."""
return bool(ctx['webdav_enabled'])
def packages_installed(packages):
"""Whether every one of the packages is installed, as dpkg knows them."""
result = subprocess.run(['dpkg-query', '-W', '-f=${db:Status-Status}\n', *packages], capture_output=True, text=True)
states = result.stdout.split()
return len(states) == len(packages) and all(state == 'installed' for state in states)
def packages_automatic(packages):
"""The packages apt marks as installed automatically, which apt autoremove removes once nothing depends on them."""
result = subprocess.run(['apt-mark', 'showauto', *packages], capture_output=True, text=True)
return result.stdout.split() if result.returncode == 0 else []
def component_on(cfg, name):
"""Whether the switch of the component of COMPONENTS is on in the configuration."""
section, setting = COMPONENTS[name][0]
return bool(cfg[section][setting])
def dns_ready(ctx):
@@ -1263,6 +1419,9 @@ def configure(cfg=None, public_ip=None):
fail(str(failure))
except ldap.LDAPError as exc:
notices = [f'the PKI is left as it is: the directory cannot be reached: {exc}']
# Without the directory the first setup has no Servers Issuing CA to choose.
if not cfg['https']['certificate']:
choose_https_certificate(cfg, ctx, 'self-signed')
for notice in notices:
warn(notice)
# The WireGuard peers of the users; None keeps those of wg0.conf while the directory cannot be reached.
@@ -416,7 +416,8 @@ def restore(source, pbs, confirm):
if result.returncode != 0:
raise Failure(f'pg_restore of {item} failed: {result.stderr.decode(errors="replace").strip()}')
subprocess.run(['systemctl', 'start', 'linux-manager-web.service'], capture_output=True)
command(['systemctl', 'restart', 'linux-manager-setup.service'])
if not linuxmanager.request_setup(wait=True):
raise Failure('linux-manager-setup failed; see journalctl -u linux-manager-setup')
for unit in RESTORE_RESTARTS:
subprocess.run(['systemctl', 'try-restart', unit], capture_output=True)
subprocess.run(['ufw', 'reload'], capture_output=True)
@@ -255,11 +255,11 @@ def domain_remove(name):
def secondary_addresses(cfg):
"""The addresses dns.secondary resolves to, which are notified of the zones' changes and may transfer them; none,
with a warning, while it is not set or does not resolve."""
"""The addresses dns.secondary resolves to, which are notified of the zones' changes and may transfer them; none while
it is not set, the domains then having the primary as their only name server, and none, with a warning, while it
does not resolve."""
secondary = cfg['dns']['secondary'].strip()
if not secondary:
linuxmanager.warn('dns.secondary is not set: the domains have no secondary name server')
return []
try:
found = socket.getaddrinfo(secondary, 53, proto=socket.IPPROTO_UDP)
@@ -17,7 +17,9 @@ CONSOLE_UID_MIN and the gidNumber of the local group CONSOLE_GROUP; nslcd serves
linuxManagerConsoleLogin TRUE to the system over the local socket.
ou=pki holds the server's PKI (linuxmanager_pki): an entry per CA, and under it an entry per
certificate the CA issued. Private keys are readable by root alone, the database's root DN.
certificate the CA issued. Private keys are readable by root, the database's root DN, and by the
members of the group PKI_GROUP, which also write ou=pki: an application that keeps its CAs there,
such as Simple CA, binds as a service account in that group.
ou=roles holds the roles of the resources of the OpenID Provider: an entry per role,
cn=<resource>:<role>, whose members are the groups, users and service accounts it is assigned to.
@@ -32,6 +34,7 @@ import secrets
import ldap
import ldap.modlist
import ldap.sasl
import ldif
URI = 'ldapi:///'
#: The local socket ldapi:/// names, which slapd listens on.
@@ -64,87 +67,15 @@ LOCKOUT_SECONDS = 900
#: The overlays of the database, in the order they are configured.
OVERLAYS = ('ppolicy', 'otp')
#: The package's own schema, under the LDAP arc of the Linux Manager OID arc (OID-REGISTRY.txt):
#: attribute types under .1 and object classes under .2. linuxManagerAccount, auxiliary, adds properties of the
#: package to a user of either kind: mail, for a Manager-only account, linuxManagerScope,
#: authorization scopes, of which service marks a service account, displayName and
#: description, the labels of a service account, and linuxManagerConsoleLogin and
#: linuxManagerConsoleAccount, whether the user may use a console and the local account it runs as,
#: without which it runs as the user's own posixAccount, and linuxManagerWireGuardPeer, each a
#: WireGuard peer of the user as "<public key> <IP>[,<IP>...]", and linuxManagerPasskey, each a
#: passkey of the user as JSON (linuxmanager_passkeys). A service account with linuxManagerRedirectUri
#: is a client of the OpenID Provider (linuxmanager_oidc): the URIs it is sent back to after a sign-in
#: and, linuxManagerPostLogoutRedirectUri, after a sign-out, and linuxManagerAllowedGroup, the DNs of the
#: groups whose members may sign in to it; linuxManagerGrantType, the further grants it may use,
#: linuxManagerPublicClient, whether it has no secret, and linuxManagerClientScope, the scopes of
#: resources it may ask for, as <resource>:<scope>. A service account with linuxManagerResourceScope
#: is a resource of the OpenID Provider with those scopes. linuxManagerRole is a role of a resource,
#: 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
#: 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'
SCHEMA_NAME = 'linux-manager'
_STRING = 'EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} SINGLE-VALUE'
_TIME = 'EQUALITY generalizedTimeMatch ORDERING generalizedTimeOrderingMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE'
_OCTETS = 'EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 SINGLE-VALUE'
SCHEMA_ATTRIBUTE_TYPES = (
f"( {SCHEMA_OID}.1.1 NAME 'linuxManagerScope' DESC 'Linux Manager: an authorization scope of the account' "
"EQUALITY caseIgnoreMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} )",
f"( {SCHEMA_OID}.1.2 NAME 'linuxManagerPrivateKey' DESC 'Linux Manager: a private key, PEM' {_OCTETS} )",
f"( {SCHEMA_OID}.1.3 NAME 'linuxManagerCertificateRequest' DESC 'Linux Manager: the CSR of a CA, PEM' {_OCTETS} )",
f"( {SCHEMA_OID}.1.4 NAME 'linuxManagerCRLNumber' DESC 'Linux Manager: the number of the last CRL of a CA' "
"EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )",
f"( {SCHEMA_OID}.1.5 NAME 'linuxManagerCRLSource' DESC 'Linux Manager: signed or uploaded, where the CRL of a CA came from' {_STRING} )",
f"( {SCHEMA_OID}.1.6 NAME 'linuxManagerRetired' DESC 'Linux Manager: when a CA was retired' {_TIME} )",
f"( {SCHEMA_OID}.1.7 NAME 'linuxManagerKind' DESC 'Linux Manager: ca, router, user or external, the kind of a certificate' {_STRING} )",
f"( {SCHEMA_OID}.1.8 NAME 'linuxManagerTemplate' DESC 'Linux Manager: the template of a certificate' {_STRING} )",
f"( {SCHEMA_OID}.1.9 NAME 'linuxManagerSubjectAltName' DESC 'Linux Manager: a subject alternative name of a certificate' "
"EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} )",
f"( {SCHEMA_OID}.1.10 NAME 'linuxManagerNotAfter' DESC 'Linux Manager: when a certificate expires' {_TIME} )",
f"( {SCHEMA_OID}.1.11 NAME 'linuxManagerRevoked' DESC 'Linux Manager: when a certificate was revoked' {_TIME} )",
f"( {SCHEMA_OID}.1.12 NAME 'linuxManagerRevocationReason' DESC 'Linux Manager: why a certificate was revoked' {_STRING} )",
f"( {SCHEMA_OID}.1.13 NAME 'linuxManagerConsoleLogin' DESC 'Linux Manager: whether the user may use a console' "
"EQUALITY booleanMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.7 SINGLE-VALUE )",
f"( {SCHEMA_OID}.1.14 NAME 'linuxManagerConsoleAccount' DESC 'Linux Manager: the local account the console of the user runs as' "
f"{_STRING} )",
f"( {SCHEMA_OID}.1.15 NAME 'linuxManagerWireGuardPeer' DESC 'Linux Manager: a WireGuard peer of the user, its public key and IPs' "
"EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )",
f"( {SCHEMA_OID}.1.16 NAME 'linuxManagerPasskey' DESC 'Linux Manager: a passkey of the user, its credential as JSON' "
"EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{4096} )",
f"( {SCHEMA_OID}.1.17 NAME 'linuxManagerRedirectUri' DESC 'Linux Manager: a redirect URI of an OpenID Connect client' "
"EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )",
f"( {SCHEMA_OID}.1.18 NAME 'linuxManagerPostLogoutRedirectUri' DESC 'Linux Manager: a post-logout redirect URI of an "
"OpenID Connect client' EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )",
f"( {SCHEMA_OID}.1.19 NAME 'linuxManagerAllowedGroup' DESC 'Linux Manager: a group whose members may sign in to an "
"OpenID Connect client' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 )",
f"( {SCHEMA_OID}.1.20 NAME 'linuxManagerGrantType' DESC 'Linux Manager: a grant an OpenID Connect client may use besides "
"the authorization code' EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{64} )",
f"( {SCHEMA_OID}.1.21 NAME 'linuxManagerPublicClient' DESC 'Linux Manager: whether an OpenID Connect client has no secret' "
"EQUALITY booleanMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.7 SINGLE-VALUE )",
f"( {SCHEMA_OID}.1.22 NAME 'linuxManagerClientScope' DESC 'Linux Manager: a scope of a resource an OpenID Connect client "
"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} )",
)
SCHEMA_OBJECT_CLASSES = (
f"( {SCHEMA_OID}.2.1 NAME 'linuxManagerAccount' DESC 'Linux Manager: properties of a user or a Manager-only account' "
"SUP top AUXILIARY MAY ( mail $ linuxManagerScope $ displayName $ description $ linuxManagerConsoleLogin $ "
"linuxManagerConsoleAccount $ linuxManagerWireGuardPeer $ linuxManagerPasskey $ linuxManagerRedirectUri $ "
"linuxManagerPostLogoutRedirectUri $ linuxManagerAllowedGroup $ linuxManagerGrantType $ linuxManagerPublicClient $ "
"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 ) )",
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 ) )",
f"( {SCHEMA_OID}.2.4 NAME 'linuxManagerRole' DESC 'Linux Manager: a role of a resource of the OpenID Provider' SUP top "
"STRUCTURAL MUST cn MAY ( description $ member ) )",
)
#: The package's schema, two schema entries of cn=config, each loaded from its LDIF file (ldapadd's form): the PKI,
#: linux-manager-pki, which a slapd without the package loads alike, and the accounts, the clients and resources of
#: the OpenID Provider and their roles, linux-manager. The files describe their attribute types and object classes.
SCHEMA_DIR = pathlib.Path('/usr/share/linux-manager/schema')
SCHEMA_FILES = (SCHEMA_DIR / 'linux-manager-pki.ldif', SCHEMA_DIR / 'linux-manager.ldif')
#: The group whose members manage the PKI, ou=pki with the keys; it is made when its first member is added.
PKI_GROUP = 'pki-managers'
PKI_MANAGERS = f'cn={PKI_GROUP},{GROUPS}'
#: The TOTP parameters: digits, the OID of HMAC-SHA1, seconds per time step, and the time steps accepted before and after now.
TOTP_DIGITS = 6
@@ -156,7 +87,7 @@ TOTP_WINDOW = 1
DISABLED = '000001010000Z'
#: The indexes of the database.
INDEXES = ('objectClass eq', 'uid eq', 'uidNumber eq', 'linuxManagerConsoleLogin eq')
INDEXES = ('objectClass eq', 'uid eq', 'uidNumber eq', 'linuxManagerConsoleLogin eq', 'linuxManagerCertificateName eq')
#: The POSIX accounts of console login (linuxmanager_users.console): the lowest uidNumber, which nslcd's nss_min_uid
#: matches, the local group that is their primary group and grants sudo, the shell and the parent of their homes.
@@ -167,12 +98,14 @@ CONSOLE_HOMES = '/home'
#: The ACLs of the database, in order.
ACCESS = (
'to attrs=linuxManagerPrivateKey by * none',
f'to attrs=linuxManagerPrivateKey,linuxManagerToken,linuxManagerRequestKey by group.exact="{PKI_MANAGERS}" manage '
'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',
f'to dn.subtree="{GROUPS}" by dn.exact="{MANAGER}" manage by * read',
f'to dn.subtree="{ROLES}" by dn.exact="{MANAGER}" manage by * read',
f'to dn.subtree="{PKI}" by group.exact="{PKI_MANAGERS}" manage by * read',
'to * by * read',
)
@@ -221,27 +154,32 @@ def _ensure_modules(connection):
def _ensure_schema(connection):
"""Add the package's schema to cn=config when missing, else add the definitions it lacks; a definition that differs
from the one of the same OID replaces the whole list of its kind."""
found = connection.search_s('cn=schema,cn=config', ldap.SCOPE_ONELEVEL, f'(cn=*{SCHEMA_NAME})',
['olcAttributeTypes', 'olcObjectClasses'])
attributes = {'olcAttributeTypes': list(SCHEMA_ATTRIBUTE_TYPES), 'olcObjectClasses': list(SCHEMA_OBJECT_CLASSES)}
if not found:
connection.add_s(f'cn={SCHEMA_NAME},cn=schema,cn=config', ldap.modlist.addModlist(
dict({name: [value.encode() for value in values] for name, values in attributes.items()},
objectClass=[b'olcSchemaConfig'], cn=[SCHEMA_NAME.encode()])))
return
dn, current = found[0]
for name, wanted in attributes.items():
present = unordered(current.get(name, []))
oids = {value.split()[1] for value in present}
missing = [value for value in wanted if value not in present]
if not missing:
"""Add each schema of SCHEMA_FILES to cn=config when missing, else add the definitions it lacks; a definition that
differs from the one of the same OID replaces the whole list of its kind."""
for path in SCHEMA_FILES:
with open(path, encoding='utf-8') as handle:
records = ldif.LDIFRecordList(handle)
records.parse()
dn, wanted = records.all_records[0]
name = wanted['cn'][0]
found = [(found_dn, current) for found_dn, current in connection.search_s(
'cn=schema,cn=config', ldap.SCOPE_ONELEVEL, f'(cn=*{name.decode()})', ['cn', 'olcAttributeTypes', 'olcObjectClasses'])
if ORDER.sub(b'', current['cn'][0]) == name]
if not found:
connection.add_s(dn, ldap.modlist.addModlist(wanted))
continue
if any(value.split()[1] in oids for value in missing):
connection.modify_s(dn, [(ldap.MOD_REPLACE, name, [value.encode() for value in wanted])])
else:
connection.modify_s(dn, [(ldap.MOD_ADD, name, [value.encode() for value in missing])])
found_dn, current = found[0]
for kind in ('olcAttributeTypes', 'olcObjectClasses'):
values = [value.decode() for value in wanted.get(kind, [])]
present = unordered(current.get(kind, []))
oids = {value.split()[1] for value in present}
missing = [value for value in values if value not in present]
if not missing:
continue
if any(value.split()[1] in oids for value in missing):
connection.modify_s(found_dn, [(ldap.MOD_REPLACE, kind, [value.encode() for value in values])])
else:
connection.modify_s(found_dn, [(ldap.MOD_ADD, kind, [value.encode() for value in missing])])
def _ensure_password_hash(connection):
@@ -7,15 +7,22 @@ this module too.
import pathlib
import subprocess
#: The values of web.listen and of the Manager's listen: the interfaces a service listens on.
#: The values of web.listen, metrics.listen and of the Manager's listen: the interfaces the firewall opens a service's
#: port on.
LISTEN_CHOICES = ('internal', 'external', 'both')
#: The interfaces a service listens on when it is not set.
#: The interfaces a service's port is open on when it is not set.
DEFAULT_LISTEN = 'both'
#: The address every service also listens on, where the HTTPS proxy calls it.
#: The address the services listen on, where Caddy calls them.
LOOPBACK = '127.0.0.1'
#: The ports the web service, the manager on the server and the metrics service listen on, on LOOPBACK only; Caddy
#: serves web.port, the manager's port and metrics.port and calls them.
WEB_LOOPBACK_PORT = 7091
MANAGER_LOOPBACK_PORT = 7090
METRICS_LOOPBACK_PORT = 9474
class ConfigError(Exception):
"""A setting is present but malformed."""
@@ -68,6 +75,12 @@ def _is_virtual(name):
return '/devices/virtual/' in str(link.resolve())
def nics():
"""The names of the network interfaces with a device behind them; loopback and virtual interfaces are left out."""
directory = pathlib.Path('/sys/class/net')
return sorted(path.name for path in directory.iterdir() if not _is_virtual(path.name)) if directory.is_dir() else []
def _addressed_interfaces():
"""Names of the NICs holding at least one IPv4 address; virtual interfaces are left out."""
names = []
@@ -147,7 +160,7 @@ def listen_addresses(configuration, choice):
"""The addresses a service listens on for choice of LISTEN_CHOICES, from linux-manager.json read as configuration.
The internal address comes first; an address not known yet is left out. A choice that is not
one of LISTEN_CHOICES is DEFAULT_LISTEN. LOOPBACK is not among them; web_listen adds it.
one of LISTEN_CHOICES is DEFAULT_LISTEN. LOOPBACK is not among them.
Without the router (router.enabled false) the external interface is also the internal side.
"""
if choice not in LISTEN_CHOICES:
@@ -165,20 +178,9 @@ def listen_addresses(configuration, choice):
return list(dict.fromkeys(address for address in addresses if address))
def web_listen(configuration, default_port):
"""Where the web service listens, from linux-manager.json read as configuration, as ([(address, port), ...], '').
The addresses are those of the interfaces web.listen names (listen_addresses), then
LOOPBACK, the port web.port, else default_port. While web.enabled is false or no address of
an interface is known, the answer is ([], the reason).
"""
web = _section(configuration, 'web')
if web.get('enabled', True) is False:
def web_listen(configuration):
"""Where the web service listens, from linux-manager.json read as configuration: ([(LOOPBACK, WEB_LOOPBACK_PORT)], ''),
Caddy serving web.port, or ([], the reason) while web.enabled is false."""
if _section(configuration, 'web').get('enabled', True) is False:
return [], 'the web service is disabled in the configuration'
port = web.get('port', default_port)
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
port = default_port
addresses = listen_addresses(configuration, web.get('listen', DEFAULT_LISTEN))
if not addresses:
return [], 'the addresses to listen on are not known yet'
return [(address, port) for address in [*addresses, LOOPBACK]], ''
return [(LOOPBACK, WEB_LOOPBACK_PORT)], ''
File diff suppressed because it is too large. Load diff
@@ -14,7 +14,7 @@ public (wan.public_address), internal or external. A site may use wan.local_fqdn
stays where the domain of wan.local_fqdn is.
The sites are served while sites.enabled is true; linux-manager-setup writes Caddy's configuration and opens the ports. A
site is changed only through this module, which checks it (check), and its callers then restart linux-manager-setup.
site is changed only through this module, which checks it (check), and its callers then request a run of linux-manager-setup.
The files of a site are read and written by path relative to its folder; resolve() refuses a path that leaves it.
receive() writes a file from a stream, extract() a zip archive into a folder; both stop at sites.upload_max_mb.
@@ -177,7 +177,9 @@ def taken_ports(cfg):
cfg['https']['manager_port']: 'https.manager_port', cfg['metrics']['port']: 'metrics.port',
cfg['metrics']['https_port']: 'metrics.https_port', linuxmanager.manager_port(): 'the Manager',
cfg['sites']['webdav_port']: 'sites.webdav_port', linuxmanager.WEBDAV_LOOPBACK_PORT: 'rclone\'s WebDAV',
53: 'DNS'}
linuxmanager.WEB_LOOPBACK_PORT: 'the web service behind Caddy',
linuxmanager.MANAGER_LOOPBACK_PORT: 'the Manager behind Caddy',
linuxmanager.METRICS_LOOPBACK_PORT: 'the metrics service behind Caddy', 53: 'DNS'}
for port in linuxmanager.BOOTSTRAP_PORTS:
taken[port] = 'the bootstrap service'
if cfg['openvpn']['protocol'] == 'tcp':
@@ -3,13 +3,14 @@
The settings file (CONFIG_FILE unless another is given) sets, all optional: router_url, database,
listen, bind, port, terraform_dir and iac_tool. bind is the one address to listen on. Without
router_url, terraform_dir names the Terraform root module whose output router_web_url gives the
URL of the server's web service, read with iac_tool, terraform (the default) or tofu; dev.sh uses
it to run the manager on a workstation. A setting that is not given comes from the server's
configuration, ROUTER_CONFIG_FILE: without bind the manager listens on the addresses of the
interfaces listen names, internal, external or both (the default), and on the loopback address,
where the server's HTTPS proxy calls it, router_url is the first address and web.port of the
server's web service, and database is the DATABASE database on this host, with the password in
DATABASE_SECRET.
URL of the server's web service, read with iac_tool, terraform (the default) or tofu; dev.py uses
it to run the manager on a workstation. On the server, where ROUTER_CONFIG_FILE is, the manager
listens without bind on linuxmanager_net.MANAGER_LOOPBACK_PORT of the loopback address, where
Caddy calls it: Caddy serves port over plain HTTP and https.manager_port over HTTPS, and the
firewall opens port on the interfaces listen names, internal, external or both (the default).
A setting that is not given comes from the server's configuration: router_url is the web
service on its loopback port, and database is the DATABASE database on this host, with the
password in DATABASE_SECRET.
"""
import json
@@ -30,7 +31,7 @@ DATABASE_SECRET = '/etc/linux-manager/manager-database.secret'
#: The role and the database the manager creates on the server.
DATABASE = 'linux-manager-ui'
#: The port when port is not set.
#: The port when port is not set: the port of bind, or on the server Caddy's plain HTTP port of the manager.
DEFAULT_PORT = 7080
#: The port of the server's web service when web.port is not set.
@@ -94,16 +95,16 @@ def output_value(outputs, name):
def listen(config_file):
"""Where the manager listens, read now: ([(address, port), ...], ''), or ([], the reason) while no address is known."""
"""Where the manager listens, read now: [(bind, port)] with bind, else on the server
[(LOOPBACK, MANAGER_LOOPBACK_PORT)], as ([(address, port), ...], ''), or ([], the reason) off the server without
bind."""
configuration = read_json(config_file)
bind = text_setting(configuration, 'bind')
port = port_setting(configuration.get('port'), DEFAULT_PORT)
if bind:
return [(bind, port)], ''
addresses = linuxmanager_net.listen_addresses(read_json(ROUTER_CONFIG_FILE), text_setting(configuration, 'listen'))
if not addresses:
return [], "the server's addresses to listen on are not known yet"
return [(address, port) for address in [*addresses, linuxmanager_net.LOOPBACK]], ''
return [(bind, port_setting(configuration.get('port'), DEFAULT_PORT))], ''
if os.path.exists(ROUTER_CONFIG_FILE):
return [(linuxmanager_net.LOOPBACK, linuxmanager_net.MANAGER_LOOPBACK_PORT)], ''
return [], f'bind is not set, and {ROUTER_CONFIG_FILE} is not here'
def settings(config_file):
@@ -128,20 +129,20 @@ def settings(config_file):
if password:
result['database'] = f'host=localhost dbname={DATABASE} user={DATABASE} password={password}'
if not result['router_url']:
targets, _ = linuxmanager_net.web_listen(router, ROUTER_PORT)
targets, _ = linuxmanager_net.web_listen(router)
if targets:
result['router_url'] = f'http://{targets[0][0]}:{targets[0][1]}'
result['router_url'] = result['router_url'].rstrip('/')
return result
def status_url(config_file, host, address, https):
"""The URL of the server's status page for a browser that reached the manager as host on its address.
def status_url(config_file, host, https):
"""The URL of the server's status page for a browser that reached the manager as host.
On the server, while neither router_url nor terraform_dir is set, it has host, without its
port, so the link works by whatever name or address the browser used: with https, a call
through the server's HTTPS proxy, https and https.web_port; else, while the server's web
service listens on address, http and web.port. Otherwise it is router_url, or '' without one.
through Caddy's HTTPS site, https and https.web_port; else, while the web service is enabled,
http and web.port, Caddy's plain HTTP site. Otherwise it is router_url, or '' without one.
"""
configuration = read_json(config_file)
try:
@@ -155,13 +156,21 @@ def status_url(config_file, host, address, https):
if https:
options = router.get('https') if isinstance(router.get('https'), dict) else {}
return f'https://{name}:{port_setting(options.get("web_port"), ROUTER_HTTPS_PORT)}'
targets, _ = linuxmanager_net.web_listen(router, ROUTER_PORT)
ports = [port for listened, port in targets if listened == address]
if ports:
return f'http://{name}:{ports[0]}'
web = router.get('web') if isinstance(router.get('web'), dict) else {}
if web.get('enabled', True) is not False:
return f'http://{name}:{port_setting(web.get("port"), ROUTER_PORT)}'
return settings(config_file)['router_url']
def plain_site(config_file):
"""The manager's plain HTTP site on the server, served by Caddy: {port, listen}, its port and the interfaces the
firewall opens it on, from the settings, with DEFAULT_PORT and linuxmanager_net.DEFAULT_LISTEN when not set."""
configuration = read_json(config_file)
listen = text_setting(configuration, 'listen')
return {'port': port_setting(configuration.get('port'), DEFAULT_PORT),
'listen': listen if listen in linuxmanager_net.LISTEN_CHOICES else linuxmanager_net.DEFAULT_LISTEN}
def serve(wanted, handler, log, interval):
"""Work out where to listen every interval seconds with wanted, and run an HTTP server of handler at each place.
@@ -33,7 +33,9 @@ optional description and at least one member; a group cannot be empty, so the la
cannot leave it and a user who is the last member of a group cannot be removed. ADMIN_GROUP grants the management of
the server, the allowed groups of the OpenID Provider's clients who may sign in to them, and the editors group of a web
site who may change its files (linuxmanager_sites); renaming a group renames it in those, and a group a client allows or a
site has cannot be removed.
site has cannot be removed. The members of linuxmanager_ldap.PKI_GROUP manage the PKI in ou=pki with its keys,
which an application that keeps its CAs there binds for as a service account; the group is made with its first member,
and renaming it takes that access away.
A VPN user may have WireGuard peers, each a device with its public key and its IPs, in
linuxManagerWireGuardPeer; linux-manager-setup writes a [Peer] of wg0.conf for each peer of a user who
@@ -84,6 +86,7 @@ import uuid
import ldap
import ldap.filter
import ldap.modlist
from ldap.controls import RequestControl
import pyotp
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
@@ -150,6 +153,8 @@ GROUP_ATTRIBUTES = ['cn', 'description', 'member']
DESCRIPTION_MAX = 256
#: The value of pwdAccountLockedTime that disables an account until it is enabled.
LOCKED = linuxmanager_ldap.DISABLED.encode()
#: The OID of the Relax Rules control.
RELAX_RULES = '1.3.6.1.4.1.4203.666.5.12'
#: The group whose members manage the server through the web service.
ADMIN_GROUP = 'admins'
#: The digits of a TOTP code given to login().
@@ -720,7 +725,7 @@ def update(connection, name, values):
def apply_wireguard():
"""Have linux-manager-setup write the WireGuard peers of the users into wg0.conf, without waiting for it."""
subprocess.run(['systemctl', 'restart', '--no-block', 'linux-manager-setup.service'], capture_output=True)
linuxmanager.request_setup()
def update_service(connection, name, values):
@@ -793,14 +798,15 @@ def enable(connection, name):
def unlock(connection, name):
"""End a lockout after failed binds and clear the failure count; a disabled user stays disabled."""
"""End a lockout after failed binds and clear the failure count, with the Relax Rules control; a disabled user
stays disabled."""
entry(connection, name)
current = connection.search_s(dn_of(name), ldap.SCOPE_BASE, attrlist=['pwdAccountLockedTime', 'pwdFailureTime'])[0][1]
changes = [(ldap.MOD_DELETE, 'pwdFailureTime', None)] if 'pwdFailureTime' in current else []
if 'pwdAccountLockedTime' in current and current['pwdAccountLockedTime'] != [LOCKED]:
changes.append((ldap.MOD_DELETE, 'pwdAccountLockedTime', None))
if changes:
connection.modify_s(dn_of(name), changes)
connection.modify_ext_s(dn_of(name), changes, serverctrls=[RequestControl(RELAX_RULES, True)])
return summary(entry(connection, name))
@@ -30,9 +30,6 @@ Pages:
/ca the PKI: its settings, the root and issuing CAs, the certificates issued; change the
settings, issue and revoke certificates, and take the certificate of an issuing CA
and a root CRL signed offline (see ca())
/pki/<name>.crt, /pki/<name>.crl
the DER certificate and CRL of the root (root) and of each issuing CA, which the
certificates name in their AIA and CRL distribution points; no authentication
/shell while web.shell is true, a login shell of the user's console account on a terminal, for
a member of admins whose console login is on and who has a TOTP token: POST signs the user in again,
with the password and the TOTP code or with a passkey whose proof POST /shell/passkey begins,
@@ -54,17 +51,20 @@ Pages:
/sites the web sites Caddy serves: the settings of sites, list, add, change and remove (see sites()),
and the files of each: list, download, upload, extract a zip archive, create a folder, rename and
remove (see Handler.site_files()); a member of a site's editors group may use the site's files
/components
the installable components, the VPN, the router, the name server and WebDAV: their switches and
whether their packages are installed (see components())
/dns the primary name server of the server's domains: its settings, and the domains: add, change and
remove, each with the records it serves and its manual records (see dns())
/postgresql
the databases of each PostgreSQL cluster on the server with their sizes, as JSON (see
postgresql_databases()); /config has the clusters' settings
/.well-known/openid-configuration, /oidc/...
while oidc.enabled is true, the OpenID Provider (linuxmanager_oidc), answered only on the
loopback address, where Caddy passes the requests of the HTTPS site; POST /oidc/login counts
towards the limit of /auth calls
while oidc.enabled is true, the OpenID Provider (linuxmanager_oidc), answered only for Caddy's
calls of the HTTPS site, from the loopback address with X-Forwarded-Proto https; POST
/oidc/login counts towards the limit of /auth calls
/status/full, /config, /metrics/history, /metrics/settings, /postgresql, /users, /service-accounts, /groups, /site-to-site, /backup, /remote-access, /ca, /logs, /sites, /dns, /shell and /account need an HS256 JWT in an Authorization: Bearer header signed
/status/full, /config, /metrics/history, /metrics/settings, /postgresql, /users, /service-accounts, /groups, /site-to-site, /backup, /remote-access, /ca, /logs, /sites, /dns, /components, /shell and /account need an HS256 JWT in an Authorization: Bearer header signed
with linuxmanager_auth.WEB_KEY (see linuxmanager_auth.verify). A token of /auth names a user in sub;
/account serves that user, and the other paths need a member of linuxmanager_users.ADMIN_GROUP. A
token of linux-manager-token has the admin claim and names no user; it may call every path but
@@ -36,7 +36,7 @@ def backup(method, path, body):
current secret
POST /backup/run start a backup now, without waiting for it; 409 while one runs
A change is made as /site-to-site makes one, and applied by restarting linux-manager-setup without waiting for it.
A change is made as /site-to-site makes one, and applied by a run of 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'}
@@ -80,5 +80,5 @@ def backup(method, path, body):
return 500, {'error': f'the configuration cannot be written: {exc}'}
except SystemExit as exc:
return 500, {'error': str(exc.code)}
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
linuxmanager.request_setup()
return 200, {'settings': backup_settings(cfg['backup'])}
@@ -1,6 +1,6 @@
"""What the modules of the web service share: the paths of the configuration and of the state linux-manager-setup writes,
the limit of request bodies, the HTTP statuses of the failures of the server's modules, reading the configuration and
the state, changing a section of the configuration, the state of a unit, and the log."""
the state, changing settings of the configuration, the state of a unit, and the log."""
import json
import sys
@@ -59,15 +59,17 @@ def unit_state(unit):
return result.stdout.strip() if result and result.stdout.strip() else 'unknown'
def section_change(name, body):
"""Change any of the settings of the configuration's section as /backup changes its own; the section, or the HTTP
status and the error document as a tuple."""
settings = {option: body[option] for option in linuxmanager.SCHEMA[name] if option in body}
def settings_change(changes):
"""Change settings of sections of the configuration in one step, section -> {setting: value}, keeping only the
settings of SCHEMA, validated as a whole, and run setup; the configuration, or the HTTP status and the error document
as a tuple."""
try:
with linuxmanager.config_lock():
data = linuxmanager.read_settings()
current = data.get(name)
data[name] = {**(current if isinstance(current, dict) else {}), **settings}
for name, body in changes.items():
current = data.get(name)
data[name] = {**(current if isinstance(current, dict) else {}),
**{option: body[option] for option in linuxmanager.SCHEMA[name] if option in body}}
cfg = linuxmanager.with_defaults(data)
linuxmanager.validate(cfg)
linuxmanager.save_config(data)
@@ -77,8 +79,15 @@ def section_change(name, body):
return 500, {'error': f'the configuration cannot be written: {exc}'}
except SystemExit as exc:
return 500, {'error': str(exc.code)}
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
return cfg[name]
linuxmanager.request_setup()
return cfg
def section_change(name, body):
"""Change any of the settings of the configuration's section as /backup changes its own; the section, or the HTTP
status and the error document as a tuple."""
changed = settings_change({name: body})
return changed if isinstance(changed, tuple) else changed[name]
def log(message):
@@ -0,0 +1,83 @@
"""/components: the installable components of the server, which the Manager's System tab switches."""
import linuxmanager
import linuxmanager_net
from .common import settings_change, unit_state
def router_choices(cfg):
"""The interfaces the router may take as its internal one: the NICs but the external interface."""
external = cfg['interfaces']['external'].strip()
if not external and (cfg['general']['mode'] or 'manual') == 'auto':
try:
external, _ = linuxmanager_net.detect_interfaces(internal=False)
except linuxmanager_net.ConfigError:
external = ''
return [name for name in linuxmanager_net.nics() if name != external]
def listing(cfg):
"""Each component of linuxmanager.COMPONENTS: {name, enabled, state}, state being installing or failed while its
installation unit is, else installed or not installed; the router also has available, whether the server has an
interface for its internal side or the router is on, the interfaces to choose from, general.mode and its current
internal_interface, int_addr and int_gateway_ip."""
found = []
for name, (_, packages) in linuxmanager.COMPONENTS.items():
unit = unit_state(f'linux-manager-install@{name}.service')
state = {'activating': 'installing', 'active': 'installing', 'failed': 'failed'}.get(unit) or \
('installed' if linuxmanager.packages_installed(packages) else 'not installed')
entry = {'name': name, 'enabled': linuxmanager.component_on(cfg, name), 'state': state}
if name == 'router':
choices = router_choices(cfg)
entry.update({'available': entry['enabled'] or bool(choices), 'interfaces': choices,
'mode': cfg['general']['mode'] or 'manual',
'internal_interface': cfg['interfaces']['internal'].strip(),
'int_addr': cfg['local']['int_addr'].strip(),
'int_gateway_ip': cfg['local']['int_gateway_ip'].strip()})
found.append(entry)
return found
def components(method, path, body):
"""Answer a /components request: the HTTP status and the JSON document.
GET /components {"components": [...]} (listing)
PUT /components/<name> switch a component: {"enabled"}, for the router switched on also "internal_interface",
"int_addr" and "int_gateway_ip" as general.mode needs them; {"components": [...]}
A switched-on component's packages are installed by linux-manager-setup (linux-manager-install@<name>), which a
change starts without waiting for it; switching a component off removes no package. The configuration's validation
refuses a change it does not allow, such as the VPN off while IKEv2, OpenVPN or WireGuard is on.
"""
if body == 'invalid' or (body is not None and not isinstance(body, dict)):
return 400, {'error': 'the body must be a JSON object'}
body = body or {}
parts = path.strip('/').split('/')
cfg = linuxmanager.load_config()
if method in ('GET', 'HEAD') and parts == ['components']:
return 200, {'components': listing(cfg)}
if method != 'PUT' or len(parts) != 2 or parts[1] not in linuxmanager.COMPONENTS:
return 404, {'error': f'no route {method} {path}'}
name, enabled = parts[1], body.get('enabled')
if not isinstance(enabled, bool):
return 400, {'error': 'enabled must be true or false'}
(section, setting), _ = linuxmanager.COMPONENTS[name]
changes = {section: {setting: enabled}}
if name == 'router' and enabled and not cfg['router']['enabled']:
choices = router_choices(cfg)
if not choices:
return 409, {'error': 'the router needs a second network interface; the server has only one'}
values = {key: body.get(key, '') for key in ('internal_interface', 'int_addr', 'int_gateway_ip')}
if any(not isinstance(value, str) for value in values.values()):
return 400, {'error': 'internal_interface, int_addr and int_gateway_ip must be strings'}
if values['internal_interface'] and values['internal_interface'] not in choices:
return 400, {'error': f'internal_interface must be one of {", ".join(choices)}'}
if values['internal_interface']:
changes['interfaces'] = {'internal': values['internal_interface']}
if values['int_addr'] or values['int_gateway_ip']:
changes['local'] = {'int_addr': values['int_addr'].strip(), 'int_gateway_ip': values['int_gateway_ip'].strip()}
changed = settings_change(changes)
if isinstance(changed, tuple):
return changed
return 200, {'components': listing(changed)}
@@ -3,7 +3,7 @@
import ipaddress
import linuxmanager
from linuxmanager_status import established_each, run
from linuxmanager_status import established_each
from .common import section
@@ -37,7 +37,7 @@ def site_to_site(method, path, body):
DELETE /site-to-site/<name> remove the connection
A change is made holding linuxmanager.config_lock, checked as linux-manager-setup checks the configuration (400 with
the reason), written with linuxmanager.save_config, and applied by restarting linux-manager-setup without waiting for it.
the reason), written with linuxmanager.save_config, and applied by a run of 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'}
@@ -84,7 +84,7 @@ def site_to_site(method, path, body):
return 500, {'error': f'the configuration cannot be written: {exc}'}
except SystemExit as exc:
return 500, {'error': str(exc.code)}
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
linuxmanager.request_setup()
if method == 'DELETE':
return 200, {'name': name, 'removed': True}
return (201 if method == 'POST' else 200), connection_of(name, cfg['site_to_site'][name], None)
@@ -121,7 +121,7 @@ def remote_access(state, method, path, body):
configuration needs of the server (wireguard_server)
PUT /remote-access/<system> change any of the settings of the system's section; answers the section
A change is made as /site-to-site makes one, and applied by restarting linux-manager-setup without waiting for it.
A change is made as /site-to-site makes one, and applied by a run of 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'}
@@ -151,5 +151,5 @@ def remote_access(state, method, path, body):
return 500, {'error': f'the configuration cannot be written: {exc}'}
except SystemExit as exc:
return 500, {'error': str(exc.code)}
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
linuxmanager.request_setup()
return 200, cfg[system]
@@ -2,7 +2,6 @@
import linuxmanager
import linuxmanager_dns
from linuxmanager_status import run
from .common import section_change, unit_state
@@ -30,7 +29,7 @@ def dns(method, path, query, body):
DELETE /dns/domains/<domain>/records
remove the manual records of name= and type=, with content= only that one
A change is applied by restarting linux-manager-setup without waiting for it.
A change is applied by a run of 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'}
@@ -80,5 +79,5 @@ def dns(method, path, query, body):
return 500, {'error': str(exc)}
except SystemExit as exc:
return 500, {'error': str(exc.code)}
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
linuxmanager.request_setup()
return code, document
@@ -8,23 +8,22 @@ from http.server import BaseHTTPRequestHandler
import ldap
import linuxmanager
import linuxmanager_auth
import linuxmanager_net
import linuxmanager_oidc
import linuxmanager_pki
import linuxmanager_sites
from .auth import auth, auth_wait, refusal
from .backup import backup
from .common import BODY_LIMIT, CONFIG_FILE, current, log, read_json, section
from .components import components
from .connectivity import remote_access, site_to_site
from .dns import dns
from .identities import account, groups, service_accounts, users
from .logs import logs
from .https import https_settings
from .https import PATHS as HTTPS_PATHS, https
from .metrics import metrics_history, metrics_settings
from .pki import PUBLISHED, ca
from .pki import ca
from .shell import EDITOR_BODY_LIMIT, shell, shell_editor, shell_passkey, shell_ticket
from .sites import SITE_FILES, site_files, sites
from .status import cached, details, html_of, postgresql_databases, shown, text_of
@@ -65,14 +64,14 @@ class Handler(BaseHTTPRequestHandler):
if self.command not in ('GET', 'HEAD'):
self.close_connection = True
directory = next((name for name in ('users', 'service-accounts', 'groups', 'account', 'site-to-site', 'backup',
'ca', 'shell', 'remote-access', 'logs', 'sites', 'dns')
'ca', 'shell', 'remote-access', 'logs', 'sites', 'dns', 'components')
if path == f'/{name}' or path.startswith(f'/{name}/')), None)
protected = path in ('/status/full', '/config', '/metrics/history', '/metrics/settings', '/https/settings',
protected = path in ('/status/full', '/config', '/metrics/history', '/metrics/settings', *HTTPS_PATHS,
'/postgresql') or \
directory is not None
signing = path in ('/auth', '/auth/passkey', '/auth/passkey/complete', '/auth/refresh', '/auth/logout')
oidc = (path == '/.well-known/openid-configuration' or path.startswith('/oidc/')) and \
self.server.server_address[0] == linuxmanager_net.LOOPBACK
self.client_address[0] == linuxmanager_net.LOOPBACK and self.headers.get('X-Forwarded-Proto') == 'https'
files = SITE_FILES.match(path) if directory == 'sites' else None
query = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query)
state = current() if protected or signing else {}
@@ -115,8 +114,8 @@ class Handler(BaseHTTPRequestHandler):
elif path == '/metrics/settings':
code, document = metrics_settings(self.command, payload)
body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json'
elif path == '/https/settings':
code, document = https_settings(self.command, payload)
elif path in HTTPS_PATHS:
code, document = https(self.command, path, payload)
body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json'
elif directory == 'shell' and (path, self.command) == ('/shell', 'GET'):
return shell(self, claims.get('sub'))
@@ -160,6 +159,9 @@ class Handler(BaseHTTPRequestHandler):
elif directory == 'dns':
code, document = dns(self.command, path, query, payload)
body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json'
elif directory == 'components':
code, document = components(self.command, path, payload)
body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json'
elif directory == 'service-accounts':
code, document = service_accounts(self.command, path, payload)
body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json'
@@ -178,9 +180,6 @@ class Handler(BaseHTTPRequestHandler):
extra += headers
elif self.command not in ('GET', 'HEAD'):
body, kind, code = b'Method not allowed\n', 'text/plain; charset=utf-8', 405
elif path.startswith('/pki/') and linuxmanager.PKI_NAME.match(path[5:-4]) and path[-4:] in PUBLISHED and \
(linuxmanager_pki.PUBLISH_DIR / path[5:]).is_file():
body, kind, code = (linuxmanager_pki.PUBLISH_DIR / path[5:]).read_bytes(), PUBLISHED[path[-4:]], 200
elif path in ('/status', '/'):
document = shown(cached(), section(read_json(CONFIG_FILE), 'web').get('status_content'), self.client())
agent = self.headers.get('User-Agent', '').lower()
@@ -1,33 +1,82 @@
"""/https/settings: the settings of HTTPS, of which the API changes the CA of Caddy's certificates."""
"""/https: the settings of HTTPS and the server's own HTTPS certificate."""
import base64
import binascii
import ldap
import linuxmanager
import linuxmanager_pki
from .common import section_change
from .common import PKI_STATUS, section_change
#: The settings of the https section PUT /https/settings changes.
CHANGEABLE = ('acme_staging',)
CHANGEABLE = ('acme_staging', 'certificate', 'self_signed_days', 'ip_sans', 'acme_provider', 'acme_url', 'acme_eab_key_id',
'acme_eab_mac_key', 'zerossl_api_key')
#: The secrets of the https section, which the answers give as <name>_set instead.
SECRETS = ('acme_eab_mac_key', 'zerossl_api_key')
#: The paths of /https.
PATHS = ('/https/settings', '/https/csr', '/https/certificate', '/https/pfx')
def https_settings(method, body):
"""Answer a /https/settings request: the HTTP status and the JSON document.
def shown(settings):
"""The https section without its secrets, each replaced by whether it is set."""
return {**{key: value for key, value in settings.items() if key not in SECRETS},
**{f'{key}_set': bool(settings[key]) for key in SECRETS}}
GET /https/settings {"settings"}: the https section
PUT /https/settings change acme_staging; the other settings of the section are changed on the server with
linux-manager-config-edit, and a body naming one is 400
A change is applied by restarting linux-manager-setup without waiting for it.
def https(method, path, body):
"""Answer a /https request: the HTTP status and the JSON document.
GET /https/settings {"settings", "certificate"}: the https section, its secrets as <name>_set, and the
server's HTTPS certificate (linuxmanager_pki.https_status)
PUT /https/settings change any of CHANGEABLE; the other settings of the section are changed on the server
with linux-manager-config-edit, and a body naming one is 400
POST /https/csr make a key and a CSR for the HTTPS names: {"csr"}
PUT /https/certificate take the certificate another CA signed for the CSR, PEM with its chain: {"certificate"}
PUT /https/pfx take a PKCS#12 file of another CA's certificate: {"pfx" in base64, "password"}
A change is applied by a run of 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'}
if method in ('GET', 'HEAD'):
try:
return 200, {'settings': linuxmanager.load_config()['https']}
except SystemExit as exc:
return 500, {'error': str(exc.code)}
if method != 'PUT':
return 404, {'error': f'no route {method} /https/settings'}
others = sorted(set(body or {}) - set(CHANGEABLE))
if others:
return 400, {'error': f'https.{", https.".join(others)}: changed on the server with linux-manager-config-edit only'}
changed = section_change('https', body or {})
return changed if isinstance(changed, tuple) else (200, {'settings': changed})
body = body or {}
try:
cfg = linuxmanager.load_config()
if path == '/https/settings' and method in ('GET', 'HEAD'):
return 200, {'settings': shown(cfg['https']), 'certificate': linuxmanager_pki.https_status(cfg)}
if path == '/https/settings' and method == 'PUT':
others = sorted(set(body) - set(CHANGEABLE))
if others:
return 400, {'error': f'https.{", https.".join(others)}: changed on the server with '
'linux-manager-config-edit only'}
if 'certificate' in body and body['certificate'] not in linuxmanager.HTTPS_CERTIFICATES:
return 400, {'error': f'https.certificate must be one of {", ".join(linuxmanager.HTTPS_CERTIFICATES)}'}
changed = section_change('https', body)
return changed if isinstance(changed, tuple) else (200, {'settings': shown(changed)})
with linuxmanager_pki.locked():
if (path, method) == ('/https/csr', 'POST'):
return 200, linuxmanager_pki.https_csr(cfg)
if (path, method) == ('/https/certificate', 'PUT'):
document = linuxmanager_pki.import_https_certificate(cfg, body.get('certificate'))
elif (path, method) == ('/https/pfx', 'PUT'):
try:
data = base64.b64decode(body.get('pfx') or '', validate=True)
except (binascii.Error, TypeError):
return 400, {'error': 'pfx must be a PKCS#12 file in base64'}
password = body.get('password')
if password is not None and not isinstance(password, str):
return 400, {'error': 'password must be a string'}
document = linuxmanager_pki.import_https_pfx(cfg, data, password)
else:
return 404, {'error': f'no route {method} {path}'}
except linuxmanager_pki.Failure as failure:
return PKI_STATUS.get(failure.status, 500), {'error': str(failure)}
except ldap.LDAPError as exc:
return 500, {'error': f'the directory, which holds the certificate, failed: {exc}'}
except SystemExit as exc:
return 500, {'error': str(exc.code)}
linuxmanager.request_setup()
return 200, document
@@ -7,7 +7,7 @@ import linuxmanager
#: The units whose journal /logs/journal shows, besides the whole journal: the package's own and the services it runs.
JOURNAL_UNITS = ('linux-manager-setup', 'linux-manager-web', 'linux-manager-metrics', 'linux-manager-pki', 'linux-manager-backup',
'linux-manager-caddy', 'linux-manager-ui', 'caddy', 'slapd', 'nslcd', 'postgresql', 'strongswan',
'linux-manager-ui', 'caddy', 'slapd', 'nslcd', 'postgresql', 'strongswan',
'wg-quick@wg0', 'openvpn-server@linux-manager', 'ssh', 'linux-manager-resolver', 'linux-manager-webdav', 'pdns')
#: The most lines /logs answers, the number it answers without lines, and the most bytes it reads from the end of a file.
@@ -35,7 +35,7 @@ def metrics_settings(method, body):
PUT /metrics/settings change any of the settings of the metrics section; an empty or absent otlp_password keeps
the current secret, and an empty otlp_username removes it
A change is applied by restarting linux-manager-setup without waiting for it.
A change is applied by a run of 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'}
@@ -1,16 +1,12 @@
"""The PKI: /ca, and the certificates and CRLs /pki/ serves without authentication."""
"""The PKI: /ca."""
import ldap
import linuxmanager
import linuxmanager_pki
from linuxmanager_status import run
from .common import PKI_STATUS
#: A file /pki/ serves: the certificate or the CRL of a CA, and its content type.
PUBLISHED = {'.crt': 'application/pkix-cert', '.crl': 'application/pkix-crl'}
def ca(method, path, body):
"""Answer a /ca request with linuxmanager_pki: the HTTP status and the JSON document.
@@ -20,20 +16,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 a run of 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,8 +59,10 @@ 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')
linuxmanager.request_setup()
return 200, {'settings': cfg['pki'], 'templates': linuxmanager.pki_templates(cfg)}
with linuxmanager_pki.locked():
if route == ('POST', 'certificates'):
@@ -71,8 +75,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 +93,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'):
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
if route[1] in ('issuing', 'root') or document.get('reissue'):
linuxmanager.request_setup()
return 200, document
@@ -10,7 +10,6 @@ import ldap
import linuxmanager
import linuxmanager_sites
from linuxmanager_status import run
from .common import MIB, SITE_STATUS, section_change
@@ -31,7 +30,7 @@ def sites(method, path, query, body):
PUT /sites/<name> change any of the settings of POST but name; an empty or absent private_key keeps the key
DELETE /sites/<name> remove the site, with content=true also its folder
A change is applied by restarting linux-manager-setup without waiting for it.
A change is applied by a run of 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'}
@@ -68,7 +67,7 @@ def sites(method, path, query, body):
return 500, {'error': f'the site cannot be changed: {exc}'}
except SystemExit as exc:
return 500, {'error': str(exc.code)}
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service')
linuxmanager.request_setup()
return code, document
@@ -232,8 +232,9 @@ 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."""
installed Caddy, {version, 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; 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,13 +247,12 @@ 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'),
},
'postgresql': postgresql_configuration(),
# Caddy is upstream's once its repository is configured (linux-manager-caddy).
'caddy': {'version': caddy, 'source': 'upstream' if linuxmanager.CADDY_APT_SOURCE.is_file() else 'ubuntu',
'service': unit_state('caddy.service')} if caddy else None,
'caddy': {'version': caddy, 'service': unit_state('caddy.service')} if caddy else None,
'oidc': {'enabled': oidc, 'issuer': linuxmanager.oidc_issuer(configuration) if oidc else None},
}
@@ -6,7 +6,8 @@ python3-psycopg to keep the sessions; its settings and its listening loop are in
linuxmanager_ui.
Pages:
/api/info the version of this package and the server it manages, as JSON
/api/info the URL of the status page of the server it manages, the port and listen of the
manager's plain HTTP site, and with a session the version of this package, as JSON
/api/session POST signs in through the server's /auth with {"name", "password", "code"?},
GET answers the signed-in user, DELETE signs out
/api/session/passkey
@@ -47,9 +48,9 @@ and logging each failure. Then it listens. Its unit starts it only once wait-for
libpq in the linker cache, where psycopg looks it up.
The service needs nothing else to start and does not end on its own. Every DISCOVERY_SECONDS it
works out where to listen, bind or the interfaces listen names, and runs a server at each address
(linuxmanager_ui.serve). Every request
reads the settings when it is made.
works out where to listen, bind, or on the server the loopback port Caddy calls
(linuxmanager_ui.listen), and runs a server at each address (linuxmanager_ui.serve). Every
request reads the settings when it is made.
"""
import argparse
@@ -77,11 +78,9 @@ import requests
import urllib3
import linuxmanager_ui
from linuxmanager_net import LOOPBACK
from linuxmanager_ui import DATABASE, DATABASE_SECRET, ROUTER_CONFIG_FILE
#: The address a proxy on this host calls from.
LOOPBACK = '127.0.0.1'
CONFIG_FILE = linuxmanager_ui.CONFIG_FILE
WEB_DIR = '/usr/share/linux-manager/manager/web'
DOCS_DIR = '/usr/share/linux-manager/manager/docs'
@@ -792,8 +791,14 @@ class Handler(BaseHTTPRequestHandler):
self.close_connection = True
if route == '/api/info':
https = self.proxied() and self.headers.get('X-Forwarded-Proto') == 'https'
status = linuxmanager_ui.status_url(CONFIG_FILE, self.headers.get('Host', ''), self.server.server_address[0], https)
body = json.dumps({'version': package_version(), 'status_url': status or None}).encode()
status = linuxmanager_ui.status_url(CONFIG_FILE, self.headers.get('Host', ''), https)
# The version is not told to a browser that has not signed in.
try:
signed_in = session(settings(), self.session_id(), self.client()) is not None
except (Unavailable, psycopg.Error):
signed_in = False
body = json.dumps({'version': package_version() if signed_in else None, 'status_url': status or None,
'manager': linuxmanager_ui.plain_site(CONFIG_FILE)}).encode()
code, kind = 200, 'application/json'
elif route == '/api/shell' and self.command == 'GET' and self.headers.get('Upgrade', '').lower() == 'websocket':
try:
@@ -23,9 +23,10 @@ prometheus_client, with OpenTelemetry semantic convention names in their Prometh
OpenTelemetry Collector's prometheus receiver. It needs HTTP Basic authentication as the service
account metrics.service_account names, which linux-manager-setup keeps with the password in
/etc/linux-manager/metrics.secret, checked with a bind to the server's directory, so failed attempts
lock the account as for any user. The service listens on the interfaces metrics.listen
names and on the loopback address, where Caddy serves it over HTTPS at metrics.https_port; the
address of a call through Caddy is the last entry of its X-Forwarded-For header.
lock the account as for any user. The service listens on the loopback address only, behind
Caddy, which serves it over plain HTTP at metrics.port, on the interfaces metrics.listen names
in the firewall, and over HTTPS at metrics.https_port; the address of a call through Caddy is
the last entry of its X-Forwarded-For header.
When metrics.otlp_endpoint is set, every sample is also pushed there as an OTLP/HTTP JSON
ExportMetricsServiceRequest, with HTTP Basic authentication when metrics.otlp_username is set.
@@ -431,19 +432,11 @@ class Handler(BaseHTTPRequestHandler):
def wanted():
"""Where the service listens: the addresses of the interfaces metrics.listen names and LOOPBACK, at metrics.port."""
configuration = read_json(CONFIG_FILE)
metrics = section(configuration, 'metrics')
defaults = linuxmanager.SCHEMA['metrics']
if metrics.get('enabled', defaults['enabled']) is False:
"""Where the service listens: METRICS_LOOPBACK_PORT of LOOPBACK, where Caddy calls it, while metrics are enabled."""
metrics = section(read_json(CONFIG_FILE), 'metrics')
if metrics.get('enabled', linuxmanager.SCHEMA['metrics']['enabled']) is False:
return [], 'metrics are disabled in the configuration'
port = metrics.get('port', defaults['port'])
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
port = defaults['port']
addresses = linuxmanager_net.listen_addresses(configuration, metrics.get('listen', defaults['listen']))
if not addresses:
return [], 'the addresses to listen on are not known yet'
return [(address, port) for address in [*addresses, linuxmanager_net.LOOPBACK]], ''
return [(linuxmanager_net.LOOPBACK, linuxmanager_net.METRICS_LOOPBACK_PORT)], ''
def main():
+154 -118
View File
@@ -16,6 +16,7 @@ firewall and NAT rules are written against them, so choosing the wrong one
would be a silent and security-relevant mistake.
"""
import fcntl
import grp
import json
import os
@@ -27,6 +28,7 @@ import socket
import subprocess
import sys
import time
import traceback
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
@@ -71,9 +73,6 @@ CADDYFILE = pathlib.Path('/etc/caddy/linux-manager.Caddyfile')
CADDY_UNIT = 'caddy.service'
CADDY_GROUP = 'caddy'
#: The unit that installs Caddy from https.caddy_source with linux-manager-caddy, outside setup.
CADDY_INSTALL_UNIT = 'linux-manager-caddy.service'
#: The certificates and keys of the issuing CAs behind Caddy's ACME server and the sites of tls ca, <name>/cert.pem and
#: key.pem.
CADDY_PKI_DIR = pathlib.Path('/etc/caddy/linux-manager-pki')
@@ -81,6 +80,15 @@ CADDY_PKI_DIR = pathlib.Path('/etc/caddy/linux-manager-pki')
#: The certificates and keys of the sites of tls file, <site>/cert.pem and key.pem.
CADDY_SITES_DIR = pathlib.Path('/etc/caddy/linux-manager-sites')
#: The certificate and key of the HTTPS names Caddy serves when they come from no ACME CA.
CADDY_HTTPS_DIR = pathlib.Path('/etc/caddy/linux-manager-https')
#: The units of Avahi, which announces <host name>.local with mDNS while wan.local_fqdn is not set.
AVAHI_UNITS = ('avahi-daemon.socket', 'avahi-daemon.service')
#: The UDP port of mDNS.
MDNS_PORT = 5353
#: The unit of dnsmasq, the resolver of the remote access clients.
RESOLVER_UNIT = 'linux-manager-resolver.service'
@@ -120,6 +128,7 @@ BLOCKS = (
('# BOOTSTRAP RULES START', '# BOOTSTRAP RULES END'),
('# MANAGER RULES START', '# MANAGER RULES END'),
('# HTTPS RULES START', '# HTTPS RULES END'),
('# MDNS RULES START', '# MDNS RULES END'),
('# METRICS RULES START', '# METRICS RULES END'),
('# SITES RULES START', '# SITES RULES END'),
('# DNS RULES START', '# DNS RULES END'),
@@ -155,8 +164,8 @@ def resolve_public_ip(fqdn):
def setup_wireguard(ctx):
"""Generate the WireGuard key pair when it does not exist."""
if not ctx['wg_enabled']:
"""Generate the WireGuard key pair when it does not exist, once the VPN's packages are installed."""
if not ctx['wg_enabled'] or not ctx['vpn_installed']:
return
WG_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
key_file = WG_DIR / 'wg0.key'
@@ -198,19 +207,6 @@ def strip_blocks(text):
return ''.join(out)
def is_configured(ctx):
"""True once any feature is actually configured: routing, a VPN system, or a listener of the core.
While nothing is configured the package leaves the firewall alone: an
install that has not been filled in yet must not start blocking traffic on
a host that was working before.
"""
return any((linuxmanager.s2s_ready(ctx), linuxmanager.routing_ready(ctx),
linuxmanager.p2s_ready(ctx), linuxmanager.wg_ready(ctx),
linuxmanager.openvpn_ready(ctx), ctx['web_enabled'], linuxmanager.https_ready(ctx),
linuxmanager.metrics_ready(ctx), linuxmanager.dns_ready(ctx), bool(ctx['sites'])))
def filter_block(ctx):
lines = []
@@ -262,16 +258,23 @@ def filter_block(ctx):
]
lines += ['# P2S DNS RULES END']
# The web service, the Manager and the metrics service choose their interfaces themselves, so their ports are open on
# both; without the router both are the one interface.
# Caddy serves the plain HTTP ports of the web service, the Manager and the metrics service on every address; each is
# open on the interfaces its listen names, where internal is the external interface without the router.
internal = ctx['int_iface'] if ctx['router_enabled'] else ctx['wan_iface']
listened = {'internal': [internal], 'external': [ctx['wan_iface']], 'both': [internal, ctx['wan_iface']]}
interfaces = list(dict.fromkeys(name for name in (ctx['int_iface'], ctx['wan_iface']) if name))
if ctx['web_enabled'] and interfaces:
lines += [
'',
'# WEB RULES START',
*(f'-A ufw-before-input -i {name} -p tcp --dport {ctx["web_port"]} -j ACCEPT' for name in interfaces),
'# WEB RULES END',
]
def opened(choice, port):
return [f'-A ufw-before-input -i {name} -p tcp --dport {port} -j ACCEPT'
for name in dict.fromkeys(listened[choice]) if name]
if ctx['web_enabled']:
lines += ['', '# WEB RULES START', *opened(ctx['web_listen'], ctx['web_port']), '# WEB RULES END']
# Without wan.local_fqdn, Avahi answers mDNS queries for <host name>.local on the internal side.
if ctx['mdns'] and internal:
lines += ['', '# MDNS RULES START', f'-A ufw-before-input -i {internal} -p udp --dport {MDNS_PORT} -j ACCEPT',
'# MDNS RULES END']
if not SETUP_DONE.exists() and ctx['int_iface']:
lines += [
@@ -282,39 +285,25 @@ def filter_block(ctx):
'# BOOTSTRAP RULES END',
]
lines += ['', '# MANAGER RULES START', *opened(linuxmanager.manager_listen(), linuxmanager.manager_port()),
'# MANAGER RULES END']
if linuxmanager.metrics_ready(ctx):
lines += ['', '# METRICS RULES START', *opened(ctx['metrics_listen'], ctx['metrics_port']),
'# METRICS RULES END']
# The ACME CA reaches the HTTP challenge on the external interface while it issues the server's certificate; the
# HTTPS ports are open on both.
if interfaces:
port = linuxmanager.manager_port()
lines += [
'',
'# MANAGER RULES START',
*(f'-A ufw-before-input -i {name} -p tcp --dport {port} -j ACCEPT' for name in interfaces),
'# MANAGER RULES END',
]
if linuxmanager.metrics_ready(ctx) and interfaces:
lines += [
'',
'# METRICS RULES START',
*(f'-A ufw-before-input -i {name} -p tcp --dport {ctx["metrics_port"]} -j ACCEPT' for name in interfaces),
'# METRICS RULES END',
]
# Let's Encrypt reaches the HTTP challenge on the external interface, and the CA files published on port 80 are
# read on both; the HTTPS ports are open on both.
if linuxmanager.https_ready(ctx) and interfaces:
publish = ctx['pki_publish']
ports = [port for wanted, port in ((ctx['web_enabled'] or 'https' in publish or ctx['pki_acme'],
ctx['https_web_port']),
ports = [port for wanted, port in ((ctx['web_enabled'] or ctx['pki_acme'], ctx['https_web_port']),
(True, ctx['https_manager_port']),
(linuxmanager.metrics_ready(ctx), ctx['metrics_https_port']),
(linuxmanager.webdav_ready(ctx), ctx['webdav_port']),
('http-80' in publish, linuxmanager.ACME_HTTP_PORT),
('https-default' in publish, linuxmanager.HTTPS_DEFAULT_PORT)) if wanted]
(linuxmanager.webdav_ready(ctx), ctx['webdav_port'])) if wanted]
lines += [
'',
'# HTTPS RULES START',
*([f'-A ufw-before-input -i {ctx["wan_iface"]} -p tcp --dport {linuxmanager.ACME_HTTP_PORT} -j ACCEPT']
if ctx['wan_iface'] and 'http-80' not in publish else []),
if ctx['wan_iface'] and ctx['https_certificate'] == 'acme' else []),
*(f'-A ufw-before-input -i {name} -p tcp --dport {port} -j ACCEPT' for name in interfaces for port in ports),
'# HTTPS RULES END',
]
@@ -441,17 +430,6 @@ def setup_ufw(ctx):
if not BEFORE_RULES.is_file():
fail(f'{BEFORE_RULES} does not exist')
# Nothing configured: remove anything left from an earlier configuration
# and touch nothing else.
if not is_configured(ctx):
original = BEFORE_RULES.read_text(encoding='utf-8')
text = strip_blocks(original)
if text == original:
return False
BEFORE_RULES.write_text(text, encoding='utf-8')
remove_stale_nat(original, text)
return True
if UFW_DEFAULTS.is_file():
text = UFW_DEFAULTS.read_text(encoding='utf-8')
updated = ''.join(
@@ -738,6 +716,16 @@ def caddy_address(host, port, tls):
return f'{"http://" if tls == "none" else ""}{host}:{port}'
def manage_mdns(ctx):
"""Run Avahi, which announces <host name>.local, one of the HTTPS names, with mDNS, while wan.local_fqdn is not set,
and stop it while it is."""
active = unit_is_active(AVAHI_UNITS[1])
if ctx['mdns'] and not active:
run(['systemctl', 'enable', '--now', *AVAHI_UNITS], check=False)
elif not ctx['mdns'] and active:
run(['systemctl', 'disable', '--now', *AVAHI_UNITS], check=False)
def manage_resolver(changed):
"""Run dnsmasq, the resolver of the remote access clients, while configure wrote its configuration, restarting it when
that changed, and stop it when not. It starts after systemd-resolved has left the addresses it takes."""
@@ -752,42 +740,32 @@ def manage_resolver(changed):
def manage_caddy(cfg, ctx):
"""Run Caddy, the HTTPS proxy of the server's services and the server of the web sites, while either is wanted, and
stop it when not.
"""Run Caddy, a dependency of the package, which serves every HTTP and HTTPS port of the server's services and the
web sites; the services listen on loopback only.
While HTTPS is ready, CADDYFILE serves the web service on https.web_port, the manager on
https.manager_port, while metrics are enabled the metrics service on metrics.https_port, and while
WebDAV is ready WebDAV on sites.webdav_port, all for wan.local_fqdn with a certificate from Let's Encrypt, and all
calling the service on its loopback address. It also serves the CA files of linuxmanager_pki.PUBLISH_DIR at /pki/ on
the endpoints of pki.publish that are Caddy's, and an ACME server at /acme/<name>/ on https.web_port for each
issuing CA with acme and a certificate.
CADDYFILE serves over plain HTTP the web service on web.port while it is enabled and the manager on its port, and
while metrics are enabled the metrics service on metrics.port. While https.disable_auto_redirect is off, a request
of the web service for an HTTPS host is redirected (308) to https.web_port, and every request of the manager to
https.manager_port, on the host it named when that is an HTTPS host, else on the first HTTPS name. It serves the
web service on https.web_port, the manager on https.manager_port, while metrics are enabled the metrics service on
metrics.https_port, and while WebDAV is ready WebDAV on sites.webdav_port, all for the HTTPS hosts: the HTTPS names
(linuxmanager.https_names) and, with https.ip_sans and a certificate of its own, the addresses its certificate
names; a client without SNI gets the certificate of the first HTTPS name. Every site calls
its service on its loopback port. The certificate comes from the ACME CA of https.acme_provider, the global issuer,
with https.certificate acme, and otherwise is the one linuxmanager_pki.https_files gives, written to
CADDY_HTTPS_DIR; while that cannot be read, the HTTPS sites are left out, so that no ACME CA is asked for it. It
also serves the CA files of linuxmanager_pki.PUBLISH_DIR at /pki/ on web.port, the Manager's port, https.web_port
and https.manager_port, ahead of the redirect to HTTPS, and an ACME server at /acme/<name>/ on https.web_port for
each issuing CA with acme and a certificate.
It serves each site of ctx's sites from its folder, with the TLS of the site: an issuing CA of tls ca issues its
certificates, and the certificate and key of tls file are written to CADDY_SITES_DIR/<name>. The certificates and
keys of the issuing CAs of both are copied to CADDY_PKI_DIR. While the sites cannot be read (ctx's sites is None),
the Caddyfile is left as it is.
Caddy is installed by CADDY_INSTALL_UNIT, outside setup, when it is missing or when
https.caddy_source is upstream and Caddy's repository is not configured; the unit restarts
setup, whose next run serves with it.
"""
sites = ctx['sites']
if not linuxmanager.https_ready(ctx) and not sites:
if sites is None:
return
linuxmanager.remove(CADDYFILE)
if unit_is_active(CADDY_UNIT):
run(['systemctl', 'disable', '--now', CADDY_UNIT], check=False)
return
source = cfg['https']['caddy_source']
if shutil.which('caddy') is None or (source == 'upstream' and not linuxmanager.CADDY_APT_SOURCE.is_file()):
run(['systemctl', 'start', '--no-block', CADDY_INSTALL_UNIT], check=False)
warn(f'Caddy is installed from the {source} source by {CADDY_INSTALL_UNIT}, which runs setup again')
return
if source == 'ubuntu' and linuxmanager.CADDY_APT_SOURCE.is_file():
warn("https.caddy_source ubuntu is ignored: Caddy's repository is configured, and Caddy stays upstream's")
if shutil.which('caddy') is None:
fail('caddy is not installed; it is a dependency of the package')
if sites is None:
warn('the web sites cannot be read; the Caddyfile is left as it is')
if not unit_is_active(CADDY_UNIT) and CADDYFILE.exists():
@@ -797,7 +775,27 @@ def manage_caddy(cfg, ctx):
group = grp.getgrnam(CADDY_GROUP).gr_gid
except KeyError:
fail(f'the group {CADDY_GROUP} does not exist; is the caddy package installed?')
https = linuxmanager.https_ready(ctx)
https = True
own = None
if https and cfg['https']['certificate'] != 'acme':
try:
own = linuxmanager_pki.https_files(cfg)
except ldap.LDAPError as exc:
warn(f'the HTTPS sites are left out: the HTTPS certificate cannot be read: {exc}')
https = False
if https and own is None:
warn('the HTTPS sites are left out: the server has no HTTPS certificate yet')
https = False
copied = False
if own is None:
if CADDY_HTTPS_DIR.is_dir():
shutil.rmtree(CADDY_HTTPS_DIR)
else:
CADDY_HTTPS_DIR.mkdir(mode=0o750, exist_ok=True)
os.chown(CADDY_HTTPS_DIR, 0, group)
for file, data in zip(('cert.pem', 'key.pem'), own):
copied |= linuxmanager_pki.write(CADDY_HTTPS_DIR / file, data, 0o640)
os.chown(CADDY_HTTPS_DIR / file, 0, group)
wanted = list(dict.fromkeys([*(ctx['pki_acme'] if https else []),
*(site['ca'] for site in sites if site['tls'] == 'ca')]))
try:
@@ -810,7 +808,6 @@ def manage_caddy(cfg, ctx):
if site['tls'] == 'ca' and site['ca'] not in authorities:
warn(f'site {site["name"]} is left out: issuing CA {site["ca"]} has no certificate')
sites = [site for site in sites if site['tls'] != 'ca' or site['ca'] in authorities]
copied = False
for folder in (CADDY_PKI_DIR.iterdir() if CADDY_PKI_DIR.is_dir() else []):
if folder.name not in authorities:
shutil.rmtree(folder)
@@ -836,13 +833,23 @@ def manage_caddy(cfg, ctx):
os.chown(folder / file, 0, group)
linuxmanager_sites.ensure_folders(site['name'] for site in sites)
names = linuxmanager.issuing_cas(cfg)
hosts = [*ctx['https_names'], *(ctx['https_ips'] if own is not None else [])]
caddy_ctx = dict(ctx, https=https, manager_port=linuxmanager.manager_port(),
redirect=https and not cfg['https']['disable_auto_redirect'],
https_name=ctx['https_names'][0],
https_hosts=[f'[{host}]' if ':' in host else host for host in hosts],
redirect_hosts=[host for host in hosts if ':' not in host],
web_loopback_port=linuxmanager.WEB_LOOPBACK_PORT,
manager_loopback_port=linuxmanager.MANAGER_LOOPBACK_PORT,
metrics_loopback_port=linuxmanager.METRICS_LOOPBACK_PORT,
https_tls={'cert': str(CADDY_HTTPS_DIR / 'cert.pem'), 'key': str(CADDY_HTTPS_DIR / 'key.pem')}
if own is not None else None,
pki_publish_dir=str(linuxmanager_pki.PUBLISH_DIR),
pki_cas=[{'id': name, 'name': names[name]['name'].strip(),
'cert': str(CADDY_PKI_DIR / name / 'cert.pem'),
'key': str(CADDY_PKI_DIR / name / 'key.pem')} for name in authorities],
acme_cas=[name for name in authorities if https and name in ctx['pki_acme']],
webdav=linuxmanager.webdav_ready(ctx), webdav_loopback_port=linuxmanager.WEBDAV_LOOPBACK_PORT,
webdav=https and linuxmanager.webdav_ready(ctx), webdav_loopback_port=linuxmanager.WEBDAV_LOOPBACK_PORT,
sites=[{'name': site['name'], 'tls': site['tls'], 'ca': site['ca'], 'spa': site['spa'],
'index': site['index_file'], 'root': str(linuxmanager_sites.SITES_DIR / site['name']),
'addresses': [caddy_address(host, site['port'], site['tls']) for host in site['hosts']]
@@ -864,15 +871,24 @@ def install_packages(feature):
warn(f'the packages of {feature} are installed by {unit}, which runs setup again')
def manage_components(cfg):
"""Install the packages of each component of linuxmanager.COMPONENTS whose switch is on, when any is missing or
marked as installed automatically, which apt autoremove would remove: an installation by apt-get marks them as
installed by hand. A component's steps wait for its packages; nothing is removed while a component is off."""
for name, (_, packages) in linuxmanager.COMPONENTS.items():
if linuxmanager.component_on(cfg, name) and (not linuxmanager.packages_installed(packages)
or linuxmanager.packages_automatic(packages)):
install_packages(name)
def manage_webdav(ctx):
"""Run rclone's WebDAV server of the sites' folders while WebDAV is ready, and stop it when not; rclone is installed
when it is missing."""
"""Run rclone's WebDAV server of the sites' folders while WebDAV is ready and rclone is installed
(manage_components), and stop it when not."""
if not linuxmanager.webdav_ready(ctx):
if unit_is_active(WEBDAV_UNIT):
run(['systemctl', 'disable', '--now', WEBDAV_UNIT], check=False)
return
if shutil.which('rclone') is None:
install_packages('webdav')
return
linuxmanager_sites.ensure_folders([])
run(['systemctl', 'enable', '--now', WEBDAV_UNIT], check=False)
@@ -899,7 +915,7 @@ def site_addresses(cfg, ctx):
def manage_dns(cfg, ctx):
"""Run PowerDNS, the primary name server of the domains of linuxmanager_dns, on the addresses of dns.listen while DNS
is enabled, and stop it when not; its packages are installed when they are missing.
is enabled and its packages are installed (manage_components), and stop it when not.
The settings, linuxmanager_dns.PDNS_CONF, are written before the packages are installed, so the server their
installation starts answers on those addresses only, beside systemd-resolved's stub on 127.0.0.53. The host names
@@ -927,7 +943,6 @@ def manage_dns(cfg, ctx):
linuxmanager_dns.PDNS_CONF.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
changed = write_if_changed(linuxmanager_dns.PDNS_CONF, linuxmanager_dns.config_text(addresses), 0o640)
if not linuxmanager_dns.PDNS_SERVER.exists() or not linuxmanager_dns.PDNS_SCHEMA.exists():
install_packages('dns')
return
os.chown(linuxmanager_dns.PDNS_CONF, 0, grp.getgrnam(linuxmanager_dns.GROUP).gr_gid)
linuxmanager_dns.provision()
@@ -1033,6 +1048,8 @@ def refresh_web(cfg, ctx):
'external_addresses': ctx['local_addr_list'],
'internal_address': ctx['int_addr'],
'internal_gateway': ctx['int_gateway_ip'],
'https_names': ctx['https_names'],
'https_addresses': ctx['https_ips'],
'local_cidrs': ctx['local_cidr_list'],
'client_dns': ctx['p2s_resolver_addrs'] if linuxmanager.RESOLVER_CONF.exists() else [],
'site_to_site': [{
@@ -1085,11 +1102,16 @@ def main():
f'set general.platform in {linuxmanager.CONFIG_FILE}')
progress('deferred', 'configuration', f'general.platform is none; set it in {linuxmanager.CONFIG_FILE}')
return 0
# Until a run has succeeded, a file that names no HTTPS certificate source leaves the choice to this run.
if not SETUP_DONE.exists() and not linuxmanager.read_settings().get('https', {}).get('certificate'):
cfg['https']['certificate'] = ''
# The directory holds the PKI, which the configuration needs; its problem ends setup only after every other step.
failed_step = 'user directory'
progress('running', failed_step)
problem = manage_directory()
progress('running', 'components')
manage_components(cfg)
progress('running', 'configuration')
ctx, changed = linuxmanager.configure(cfg)
@@ -1121,16 +1143,13 @@ def main():
progress('running', 'firewall')
rules_changed = setup_ufw(ctx)
if is_configured(ctx):
status = run(['ufw', 'status'], check=False)
if not status.stdout.startswith('Status: active'):
# Only ever enable the firewall after making sure SSH survives it.
run(['ufw', 'allow', '22/tcp'], check=False)
run(['ufw', '--force', 'enable'])
elif rules_changed:
run(['ufw', 'reload'])
status = run(['ufw', 'status'], check=False)
if not status.stdout.startswith('Status: active'):
# Only ever enable the firewall after making sure SSH survives it.
run(['ufw', 'allow', '22/tcp'], check=False)
run(['ufw', '--force', 'enable'])
elif rules_changed:
run(['ufw', 'reload'], check=False)
run(['ufw', 'reload'])
progress('running', 'strongSwan')
manage_strongswan(ctx, changed)
@@ -1153,6 +1172,8 @@ def main():
manage_openvpn(ctx, changed)
progress('running', 'HTTPS proxy')
manage_caddy(cfg, ctx)
progress('running', 'mDNS')
manage_mdns(ctx)
progress('running', 'WebDAV')
manage_webdav(ctx)
progress('running', 'name server')
@@ -1195,13 +1216,28 @@ def record_failure(error):
if __name__ == '__main__':
# A failing step ends with SystemExit carrying its message (linuxmanager.fail).
try:
code = main()
except SystemExit as exc:
record_failure(str(exc.code))
raise
except Exception as exc:
record_failure(repr(exc))
raise
# The run holds SETUP_RUNNING while it works, and runs again while a request came during it (request_setup).
linuxmanager.SETUP_RUNNING.parent.mkdir(parents=True, exist_ok=True)
running = open(linuxmanager.SETUP_RUNNING, 'a', encoding='utf-8')
fcntl.flock(running, fcntl.LOCK_EX)
while True:
with linuxmanager.setup_lock():
linuxmanager.SETUP_REQUEST.unlink(missing_ok=True)
# A failing step ends with SystemExit carrying its message (linuxmanager.fail).
try:
code = main()
except SystemExit as exc:
record_failure(str(exc.code))
code = exc.code
except Exception as exc:
record_failure(repr(exc))
traceback.print_exc()
code = 1
# The lock is kept to the end of the process, so that a request either comes before this check or finds no run.
lock = linuxmanager.setup_lock()
if not linuxmanager.SETUP_REQUEST.exists():
break
lock.close()
print('linux-manager: another run was requested during this one; running again', flush=True)
fcntl.flock(running, fcntl.LOCK_UN)
sys.exit(code)
+7 -11
View File
@@ -1,5 +1,6 @@
#!/usr/bin/python3
"""Serve the status of the server on its internal address, its external address or both, as web.listen sets.
"""Serve the status of the server on the loopback address, behind Caddy, which serves web.port over plain HTTP and
https.web_port over HTTPS.
Run by linux-manager-web.service. Users are managed with linuxmanager_users, the module that
linux-manager-user uses too.
@@ -12,11 +13,9 @@ logging each failure. Then it listens. Its unit starts it only once wait-for-lib
in the linker cache, where psycopg looks it up.
The service needs nothing else to start and does not end on its own. Every DISCOVERY_SECONDS it
works out from /etc/linux-manager/linux-manager.json the addresses of the interfaces web.listen names,
internal, external or both, as general.mode directs, with web.port and web.enabled
(linuxmanager_net.web_listen), and runs a server on each (linuxmanager_serve.serve): it starts them,
moves them when an address or the port changes, and stops them while the service is disabled or
no address is known. Every request reads what it needs when it is made: the signing
reads web.enabled from /etc/linux-manager/linux-manager.json and listens on
linuxmanager_net.WEB_LOOPBACK_PORT of the loopback address while it is on (linuxmanager_net.web_listen,
linuxmanager_serve.serve). Every request reads what it needs when it is made: the signing
key, the configuration, and the features of the server and the facts shown by /config from
/run/linux-manager/web.json, which linux-manager-setup writes. Before setup has written that file
the server has no features, and /config shows no configuration or interfaces.
@@ -43,9 +42,6 @@ from linuxmanager_web.shell import editor_listen
#: Seconds between two attempts of the initialization.
INIT_RETRY_SECONDS = 15
#: The port when web.port is not set.
DEFAULT_PORT = 7081
#: Seconds between two discoveries of where the service should listen.
DISCOVERY_SECONDS = 30
@@ -88,8 +84,8 @@ def main():
initialize()
threading.Thread(target=editor_listen, name='editor socket', daemon=True).start()
try:
linuxmanager_serve.serve(lambda: linuxmanager_net.web_listen(read_json(CONFIG_FILE), DEFAULT_PORT), Handler, log,
DISCOVERY_SECONDS)
linuxmanager_serve.serve(lambda: linuxmanager_net.web_listen(read_json(CONFIG_FILE)), Handler, log,
DISCOVERY_SECONDS)
except KeyboardInterrupt:
pass
return 0
+69 -52
View File
@@ -4,10 +4,12 @@
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. https status shows the server's HTTPS certificate, https csr prints a new CSR for
wan.local_fqdn, to be signed by another CA, https import takes the certificate signed for it, and https import-pfx a
PKCS#12 file whose password is read from the first line of standard input. 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 requests a run of 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 +23,12 @@ 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)
linux-manager-ca [--json] https status|csr
linux-manager-ca [--json] https import FILE
linux-manager-ca [--json] https import-pfx FILE (password on stdin)
"""
import argparse
@@ -33,7 +36,6 @@ import base64
import json
import os
import pathlib
import subprocess
import sys
sys.path.insert(0, '/usr/lib/linux-manager')
@@ -58,17 +60,21 @@ def secret():
return sys.stdin.readline().rstrip('\r\n')
def restart_setup():
subprocess.run(['systemctl', 'restart', '--no-block', 'linux-manager-setup.service'], capture_output=True, text=True)
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']:
@@ -89,6 +95,13 @@ def run(options):
if options.command == 'status':
document = linuxmanager_pki.status(cfg)
return document, None
if options.command == 'https' and options.action == 'status':
document = linuxmanager_pki.https_status(cfg)
return document, (f'Source: {document["source"]}, served: {document["served"] or "none"}\n'
f'Subject: {document["subject"] or "-"}, issuer: {document["issuer"] or "-"}, '
f'expires {document["expires"] or "-"}\n'
f'Names: {", ".join(document["sans"]) or "-"}' + ('\nA CSR waits for its certificate.'
if document['pending'] else ''))
if options.command == 'list':
found = [entry for entry in linuxmanager_pki.certificates() if options.ca in (None, entry['ca'])]
text = '\n'.join(f'{entry["serial"]} {entry["ca"]} {entry["kind"]} {entry["subject"]} {entry["state"]} '
@@ -111,40 +124,42 @@ def run(options):
if options.command == 'revoke':
document = linuxmanager_pki.revoke(cfg, options.serial, options.reason)
if document['reissue']:
restart_setup()
linuxmanager.request_setup()
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 '.')
linuxmanager.request_setup()
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)
restart_setup()
return {'imported': True}, 'Root key back on the server.'
document = linuxmanager_pki.import_root_crl(pathlib.Path(options.file).read_bytes())
linuxmanager.request_setup()
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.command == 'https' and options.action == 'csr':
document = linuxmanager_pki.https_csr(cfg)
return document, document['csr']
if options.command == 'https':
if options.action == 'import':
document = linuxmanager_pki.import_https_certificate(
cfg, pathlib.Path(options.file).read_text(encoding='ascii'))
else:
document = linuxmanager_pki.import_https_pfx(cfg, pathlib.Path(options.file).read_bytes(), secret())
linuxmanager.request_setup()
return document, f'The HTTPS certificate of {document["subject"]}, issued by {document["issuer"]}, ' \
f'expires {document["expires"]}.'
if options.action == 'setup-code':
document = linuxmanager_pki.exchange_code(cfg, secret())
linuxmanager.request_setup()
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 +180,23 @@ 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')
host = commands.add_parser('https', help="the server's HTTPS certificate")
host_actions = host.add_subparsers(dest='action', required=True, parser_class=Parser)
host_actions.add_parser('status', help='show the certificate Caddy serves')
host_actions.add_parser('csr', help='print a new CSR for wan.local_fqdn, to be signed by another CA')
host_actions.add_parser('import', help='take the certificate signed for the CSR, PEM with its chain').add_argument('file')
host_actions.add_parser('import-pfx', help='take a PKCS#12 file; the password is read from stdin').add_argument('file')
options = parser.parse_args(argv)
os.umask(0o077)
@@ -1,151 +0,0 @@
#!/usr/bin/python3
"""Install Caddy, the server's HTTPS proxy, from the source https.caddy_source names.
status shows the configured source, the source in effect and the installed and candidate versions of Caddy. apply
installs Caddy when it is missing: from the Ubuntu archive, or with upstream from Caddy's own repository, which it
configures first (linuxmanager.CADDY_APT_SOURCE, with the key in linuxmanager.CADDY_KEYRING). When upstream is configured
and the repository is not, it configures the repository and replaces the installed Caddy with upstream's. It then
restarts linux-manager-setup without waiting, which serves with the new Caddy; linux-manager-caddy.service runs it for
linux-manager-setup. use-upstream sets https.caddy_source to upstream and applies it, printing each step.
Once the repository is configured Caddy stays upstream's: apt keeps the higher upstream version, and ubuntu has no
effect. A failure is a message on standard error and the exit status 1. -h or --help shows the commands.
linux-manager-caddy [--json] status
linux-manager-caddy apply
linux-manager-caddy use-upstream
"""
import argparse
import json
import os
import subprocess
import sys
import urllib.request
sys.path.insert(0, '/usr/lib/linux-manager')
import linuxmanager
#: apt-get, waiting up to ten minutes for dpkg's lock, which a package installation that runs setup holds.
APT = ['apt-get', '-o', 'DPkg::Lock::Timeout=600']
#: The options of apt-get install: no questions, and the configuration files of the installed Caddy kept.
INSTALL = ['-y', '-o', 'Dpkg::Options::=--force-confdef', '-o', 'Dpkg::Options::=--force-confold', 'install']
#: Seconds the key of Caddy's repository may take to download.
KEY_TIMEOUT = 60
class Parser(argparse.ArgumentParser):
"""An argument parser whose errors end with status 2."""
def error(self, message):
print(f'{self.prog}: {message}; see {self.prog} --help', file=sys.stderr)
sys.exit(2)
def step(message):
print(message, flush=True)
def installed():
"""The installed version of caddy, or None when it is not installed."""
result = subprocess.run(['dpkg-query', '-W', '-f=${Status}\t${Version}', 'caddy'], capture_output=True, text=True)
status, _, version = result.stdout.partition('\t')
return version if result.returncode == 0 and status == 'install ok installed' else None
def candidate():
"""The version of caddy apt would install, or None when it knows none."""
result = subprocess.run(['apt-cache', 'policy', 'caddy'], capture_output=True, text=True)
for line in result.stdout.splitlines():
if line.strip().startswith('Candidate:'):
value = line.split(':', 1)[1].strip()
return None if value == '(none)' else value
return None
def effective():
"""The source Caddy comes from: upstream once its repository is configured, ubuntu otherwise."""
return 'upstream' if linuxmanager.CADDY_APT_SOURCE.is_file() else 'ubuntu'
def command(args):
"""Run a command with its output shown; SystemExit when it fails."""
step(f'$ {" ".join(args)}')
result = subprocess.run(args, env=dict(os.environ, DEBIAN_FRONTEND='noninteractive'))
if result.returncode != 0:
sys.exit(f'linux-manager-caddy: {args[0]} failed with status {result.returncode}')
def apply():
"""Install Caddy, or replace it with upstream's, as https.caddy_source asks (see the module)."""
source = linuxmanager.load_config()['https']['caddy_source']
repository = source == 'upstream' and not linuxmanager.CADDY_APT_SOURCE.is_file()
if installed() and not repository:
if source == 'ubuntu' and effective() == 'upstream':
step("https.caddy_source is ubuntu, but Caddy's repository is configured, so Caddy stays upstream's.")
else:
step(f'Caddy {installed()} is installed from the {source} source.')
return
if repository:
step(f"Downloading the key of Caddy's repository from {linuxmanager.CADDY_KEY_URL}")
with urllib.request.urlopen(linuxmanager.CADDY_KEY_URL, timeout=KEY_TIMEOUT) as response:
key = response.read()
if not key.lstrip().startswith(b'-----BEGIN PGP PUBLIC KEY BLOCK-----'):
sys.exit(f'linux-manager-caddy: {linuxmanager.CADDY_KEY_URL} did not answer with an OpenPGP public key')
linuxmanager.CADDY_KEYRING.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
linuxmanager.CADDY_KEYRING.write_bytes(key)
os.chmod(linuxmanager.CADDY_KEYRING, 0o644)
linuxmanager.CADDY_APT_SOURCE.write_text(
f'Types: deb\nURIs: {linuxmanager.CADDY_REPOSITORY}\nSuites: any-version\nComponents: main\n'
f'Signed-By: {linuxmanager.CADDY_KEYRING}\n', encoding='utf-8')
os.chmod(linuxmanager.CADDY_APT_SOURCE, 0o644)
step(f"Caddy's repository is configured in {linuxmanager.CADDY_APT_SOURCE}.")
command([*APT, 'update'])
command([*APT, *INSTALL, 'caddy'])
step(f'Caddy {installed()} is installed from the {effective()} source.')
subprocess.run(['systemctl', 'restart', '--no-block', 'linux-manager-setup.service'], capture_output=True, text=True)
step('linux-manager-setup restarted.')
def main(argv):
parser = Parser(prog='linux-manager-caddy', description='Install Caddy from the source https.caddy_source names.')
parser.add_argument('--json', action='store_true', help='answer status in JSON')
commands = parser.add_subparsers(dest='command', required=True, parser_class=Parser)
commands.add_parser('status', help='show the sources and the versions of Caddy')
commands.add_parser('apply', help='install Caddy, or replace it with upstream\'s, as https.caddy_source asks')
commands.add_parser('use-upstream', help="switch to Caddy's own repository and replace Caddy with upstream's")
options = parser.parse_args(argv)
try:
if options.command == 'status':
document = {'configured': linuxmanager.load_config()['https']['caddy_source'], 'source': effective(),
'installed': installed(), 'candidate': candidate()}
if options.json:
print(json.dumps(document, indent=2))
else:
print(f'Configured source: {document["configured"]}\nSource in effect: {document["source"]}\n'
f'Installed: {document["installed"] or "no"}\nCandidate: {document["candidate"] or "none"}')
return 0
if options.command == 'use-upstream':
with linuxmanager.config_lock():
data = linuxmanager.read_settings()
current = data.get('https')
data['https'] = {**(current if isinstance(current, dict) else {}), 'caddy_source': 'upstream'}
linuxmanager.validate(linuxmanager.with_defaults(data))
linuxmanager.save_config(data)
step('https.caddy_source is upstream.')
apply()
except linuxmanager.ConfigError as exc:
print(f'linux-manager-caddy: {exc}', file=sys.stderr)
return 1
except OSError as exc:
print(f'linux-manager-caddy: {exc}', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
@@ -9,21 +9,22 @@ number, true or false, a list of strings separated by commas (an empty value is
or a string. remove takes site_to_site.NAME and removes that connection. The configuration with
the change is checked as linux-manager-setup checks it, and only then written with
linuxmanager.save_config, holding linuxmanager.config_lock; linux-manager-setup applies it at its next
run, which set and remove remind of. With --restart they restart linux-manager-setup and wait until
it has applied the change. A failure is a message on standard error; the exit status is 2 for an
invalid request and 1 for any other failure, a failed run of linux-manager-setup included. -h or
--help shows the options.
run, which set and remove remind of. With --restart they have linux-manager-setup run and wait until
it has applied the change, as apply does without a change: a run in progress is not cut short but
runs once more (linuxmanager.request_setup). A failure is a message on standard error; the exit
status is 2 for an invalid request and 1 for any other failure, a failed run of linux-manager-setup
included. -h or --help shows the options.
linux-manager-config-edit show
linux-manager-config-edit set [--restart] SECTION.OPTION VALUE
linux-manager-config-edit set [--restart] site_to_site.NAME.OPTION VALUE
linux-manager-config-edit remove [--restart] site_to_site.NAME
linux-manager-config-edit apply
"""
import argparse
import copy
import json
import subprocess
import sys
sys.path.insert(0, '/usr/lib/linux-manager')
@@ -83,6 +84,7 @@ def main(argv):
parser = Parser(prog='linux-manager-config-edit', description='Show and change the server configuration.')
commands = parser.add_subparsers(dest='command', required=True, parser_class=Parser)
commands.add_parser('show', help='print the configuration as indented JSON')
commands.add_parser('apply', help='have linux-manager-setup apply the configuration and wait for it')
setter = commands.add_parser('set', help='set a setting and write the configuration')
setter.add_argument('key', metavar='SECTION.OPTION',
help='the setting, such as web.port or site_to_site.NAME.option')
@@ -91,12 +93,14 @@ def main(argv):
remover.add_argument('key', metavar='site_to_site.NAME', help='the connection')
for changer in (setter, remover):
changer.add_argument('--restart', action='store_true',
help='restart linux-manager-setup and wait until it has applied the change')
help='have linux-manager-setup apply the change and wait for it')
options = parser.parse_args(argv)
if options.command == 'show':
print(json.dumps(read(), indent=2))
return 0
if options.command == 'apply':
return applied()
with linuxmanager.config_lock():
data = read()
@@ -131,10 +135,15 @@ def main(argv):
else:
print(f'{options.key} removed from {linuxmanager.CONFIG_FILE}.')
if not options.restart:
print('Apply it with: systemctl restart linux-manager-setup, or --restart')
print('Apply it with: linux-manager-config-edit apply, or --restart')
return 0
print('Restarting linux-manager-setup...', flush=True)
if subprocess.run(['systemctl', 'restart', 'linux-manager-setup.service']).returncode != 0:
return applied()
def applied():
"""Have linux-manager-setup apply the configuration and wait for it; the exit status."""
print('Running linux-manager-setup...', flush=True)
if not linuxmanager.request_setup(wait=True):
print('linux-manager-config-edit: linux-manager-setup failed; see journalctl -u linux-manager-setup', file=sys.stderr)
return 1
print('linux-manager-setup applied it.')
@@ -6,7 +6,7 @@ firewall opens it, TLS (none, acme, ca with --ca, or file with --certificate and
whether any path without a file is served that file of the site (--spa), the group whose members change its files, and
who serves the records of its host names (--dns user, elsewhere, or router, the server's name server, with the server's
address of --dns-address).
A change is applied by restarting linux-manager-setup without waiting for it. The answer is text for people on standard
A change is applied by a run of linux-manager-setup, without waiting for it. 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 is invalid, 3 the site does not exist, 4
the site exists, 1 anything else. -h or --help shows the commands and their options.
@@ -25,7 +25,6 @@ the site exists, 1 anything else. -h or --help shows the commands and their opti
import argparse
import json
import subprocess
import sys
sys.path.insert(0, '/usr/lib/linux-manager')
@@ -151,7 +150,7 @@ def main(argv):
message, status = f'the user directory failed: {exc}', 1
else:
if changed:
subprocess.run(['systemctl', 'restart', '--no-block', 'linux-manager-setup.service'])
linuxmanager.request_setup()
print(json.dumps(answer) if as_json else text_of(answer))
return 0
if as_json:
@@ -22,17 +22,17 @@ _linux_manager_ca()
local cur prev words cword split
_init_completion -s || return
# The command and, for ca and root, the action are the first words that are not options; the arguments are the
# The command and, for ca, root and https, the action are the first words that are not options; the arguments are the
# words after them but option values.
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
command=${words[i]}
elif [[ $command == @(ca|root) && -z $action ]]; then
elif [[ $command == @(ca|root|https) && -z $action ]]; then
action=${words[i]}
else
((args++))
@@ -54,7 +54,7 @@ _linux_manager_ca()
COMPREPLY=($(compgen -W "$(_linux_manager_ca_python reasons)" -- "$cur"))
return
;;
--csr | --pfx | --out)
--csr | --pfx)
_filedir
return
;;
@@ -68,7 +68,7 @@ _linux_manager_ca()
if [[ $cur == -* ]]; then
COMPREPLY=($(compgen -W '--json --help' -- "$cur"))
else
COMPREPLY=($(compgen -W 'status list issue revoke maintain ca root' -- "$cur"))
COMPREPLY=($(compgen -W 'status list issue revoke maintain ca root https' -- "$cur"))
fi
return
fi
@@ -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,11 @@ _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")) ;;
https,,*) COMPREPLY=($(compgen -W 'status csr import import-pfx' -- "$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 | https,import,0 | https,import-pfx,0) _filedir ;;
esac
} &&
complete -F _linux_manager_ca linux-manager-ca
@@ -1,24 +0,0 @@
# bash completion for linux-manager-caddy -*- shell-script -*-
_linux_manager_caddy()
{
local cur prev words cword
_init_completion || return
# After the command only --help is left.
local word
for word in "${words[@]:1:cword-1}"; do
if [[ $word != -* ]]; then
[[ $cur == -* ]] && COMPREPLY=($(compgen -W '--help' -- "$cur"))
return
fi
done
if [[ $cur == -* ]]; then
COMPREPLY=($(compgen -W '--json --help' -- "$cur"))
else
COMPREPLY=($(compgen -W 'status apply use-upstream' -- "$cur"))
fi
} &&
complete -F _linux_manager_caddy linux-manager-caddy
# ex: filetype=sh
@@ -48,7 +48,7 @@ _vpn_config_edit()
fi
case $command,${#args[@]} in
,*) COMPREPLY=($(compgen -W 'show set remove' -- "$cur")) ;;
,*) COMPREPLY=($(compgen -W 'show set remove apply' -- "$cur")) ;;
set,0) COMPREPLY=($(compgen -W "$(_vpn_config_edit_python settings)" -- "$cur")) ;;
set,1) COMPREPLY=($(compgen -W "$(_vpn_config_edit_python values "${args[0]}")" -- "$cur")) ;;
remove,0) COMPREPLY=($(compgen -W "$(_vpn_config_edit_python connections)" -- "$cur")) ;;
@@ -82,8 +82,7 @@
"enabled": true,
"email": "",
"web_port": 7444,
"manager_port": 7443,
"caddy_source": "ubuntu"
"manager_port": 7443
},
"oidc": {
"enabled": false
@@ -107,7 +106,6 @@
"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": {
@@ -125,7 +123,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,
@@ -0,0 +1,90 @@
# Linux Manager's PKI schema: CAs, the certificates they issued and the server's host certificates,
# with their keys. It needs only the core schema. A slapd without Linux Manager loads it with:
#
# ldapadd -Y EXTERNAL -H ldapi:/// -f linux-manager-pki.ldif
#
# OIDs: the LDAP arc 1.3.6.1.4.1.67380.10.1.2 of OID-REGISTRY.txt, attribute types under .1 and
# object classes under .2.
dn: cn=linux-manager-pki,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: linux-manager-pki
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.2 NAME
'linuxManagerPrivateKey' DESC 'Linux Manager: a private key, PEM' EQUALITY
octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.3 NAME
'linuxManagerCertificateRequest' DESC 'Linux Manager: the CSR of a CA, PEM'
EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 SINGLE-VALUE
)
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.4 NAME 'linuxManagerCRLNumber'
DESC 'Linux Manager: the number of the last CRL of a CA' EQUALITY
integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.5 NAME 'linuxManagerCRLSource'
DESC 'Linux Manager: signed or uploaded, where the CRL of a CA came from'
EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256}
SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.6 NAME 'linuxManagerRetired'
DESC 'Linux Manager: when a CA was retired' EQUALITY generalizedTimeMatch
ORDERING generalizedTimeOrderingMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.24
SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.7 NAME 'linuxManagerKind' DESC
'Linux Manager: ca, router, user or external, the kind of a certificate'
EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256}
SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.8 NAME 'linuxManagerTemplate'
DESC 'Linux Manager: the template of a certificate' EQUALITY caseIgnoreMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.9 NAME
'linuxManagerSubjectAltName' DESC 'Linux Manager: a subject alternative name
of a certificate' EQUALITY caseIgnoreMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{256} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.10 NAME 'linuxManagerNotAfter'
DESC 'Linux Manager: when a certificate expires' EQUALITY
generalizedTimeMatch ORDERING generalizedTimeOrderingMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.11 NAME 'linuxManagerRevoked'
DESC 'Linux Manager: when a certificate was revoked' EQUALITY
generalizedTimeMatch ORDERING generalizedTimeOrderingMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.12 NAME
'linuxManagerRevocationReason' DESC 'Linux Manager: why a certificate was
revoked' EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256}
SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.24 NAME 'linuxManagerToken'
DESC 'Linux Manager: the Simple CA token that signs the issuing CAs'
EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 SINGLE-VALUE
)
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.25 NAME
'linuxManagerUpstreamName' DESC 'Linux Manager: the Simple CA issuing CA of
the token' EQUALITY caseIgnoreMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{256} SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.26 NAME
'linuxManagerCertificateChain' DESC 'Linux Manager: a certificate and its
chain, PEM' EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40
SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.27 NAME
'linuxManagerRequestKey' DESC 'Linux Manager: the private key of a CSR, PEM'
EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 SINGLE-VALUE
)
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.28 NAME
'linuxManagerCertificateName' DESC 'Linux Manager: the name a certificate is
filed under by the application that keeps it' EQUALITY caseExactMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{256} SINGLE-VALUE )
olcObjectClasses: ( 1.3.6.1.4.1.67380.10.1.2.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 $ linuxManagerToken $
linuxManagerUpstreamName ) )
olcObjectClasses: ( 1.3.6.1.4.1.67380.10.1.2.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 $ linuxManagerCertificateName ) )
olcObjectClasses: ( 1.3.6.1.4.1.67380.10.1.2.2.5 NAME
'linuxManagerHostCertificate' DESC 'Linux Manager: a certificate of the
server kept with its key' SUP top STRUCTURAL MUST cn MAY (
linuxManagerCertificateChain $ linuxManagerPrivateKey $
linuxManagerCertificateRequest $ linuxManagerRequestKey $ linuxManagerKind )
)
@@ -0,0 +1,67 @@
# Linux Manager's schema of its accounts, of the clients and resources of its OpenID Provider, and
# of the roles of those resources; the PKI is in linux-manager-pki.ldif.
#
# OIDs: the LDAP arc 1.3.6.1.4.1.67380.10.1.2 of OID-REGISTRY.txt, attribute types under .1 and
# object classes under .2.
dn: cn=linux-manager,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: linux-manager
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.1 NAME 'linuxManagerScope'
DESC 'Linux Manager: an authorization scope of the account' EQUALITY
caseIgnoreMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{256} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.13 NAME
'linuxManagerConsoleLogin' DESC 'Linux Manager: whether the user may use a
console' EQUALITY booleanMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.7
SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.14 NAME
'linuxManagerConsoleAccount' DESC 'Linux Manager: the local account the
console of the user runs as' EQUALITY caseIgnoreMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{256} SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.15 NAME
'linuxManagerWireGuardPeer' DESC 'Linux Manager: a WireGuard peer of the
user, its public key and IPs' EQUALITY caseExactMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{1024} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.16 NAME 'linuxManagerPasskey'
DESC 'Linux Manager: a passkey of the user, its credential as JSON' EQUALITY
caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{4096} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.17 NAME
'linuxManagerRedirectUri' DESC 'Linux Manager: a redirect URI of an OpenID
Connect client' EQUALITY caseExactMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{1024} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.18 NAME
'linuxManagerPostLogoutRedirectUri' DESC 'Linux Manager: a post-logout
redirect URI of an OpenID Connect client' EQUALITY caseExactMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{1024} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.19 NAME
'linuxManagerAllowedGroup' DESC 'Linux Manager: a group whose members may
sign in to an OpenID Connect client' EQUALITY distinguishedNameMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.12 )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.20 NAME
'linuxManagerGrantType' DESC 'Linux Manager: a grant an OpenID Connect
client may use besides the authorization code' EQUALITY caseExactMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{64} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.21 NAME
'linuxManagerPublicClient' DESC 'Linux Manager: whether an OpenID Connect
client has no secret' EQUALITY booleanMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.7 SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.22 NAME
'linuxManagerClientScope' DESC 'Linux Manager: a scope of a resource an
OpenID Connect client may ask for' EQUALITY caseExactMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{128} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.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} )
olcObjectClasses: ( 1.3.6.1.4.1.67380.10.1.2.2.1 NAME 'linuxManagerAccount'
DESC 'Linux Manager: properties of a user or a Manager-only account' SUP top
AUXILIARY MAY ( mail $ linuxManagerScope $ displayName $ description $
linuxManagerConsoleLogin $ linuxManagerConsoleAccount $
linuxManagerWireGuardPeer $ linuxManagerPasskey $ linuxManagerRedirectUri $
linuxManagerPostLogoutRedirectUri $ linuxManagerAllowedGroup $
linuxManagerGrantType $ linuxManagerPublicClient $ linuxManagerClientScope $
linuxManagerResourceScope ) )
olcObjectClasses: ( 1.3.6.1.4.1.67380.10.1.2.2.4 NAME 'linuxManagerRole' DESC
'Linux Manager: a role of a resource of the OpenID Provider' SUP top
STRUCTURAL MUST cn MAY ( description $ member ) )
@@ -1,11 +1,21 @@
# Written by linux-manager-setup from /etc/linux-manager/linux-manager.json and the web sites; edits are overwritten.
{
auto_https disable_redirects
{%- if https_tls %}
default_sni {{ https_name }}
{%- endif %}
{%- if https_email %}
email {{ https_email }}
{%- endif %}
{%- if https_acme_ca %}
acme_ca {{ https_acme_ca }}
{%- if https_acme_provider == 'zerossl' %}
cert_issuer zerossl{% if https_zerossl_api_key %} {{ https_zerossl_api_key }}{% endif %}
{%- else %}
cert_issuer acme {
dir {{ https_acme_url }}
{%- if https_acme_eab %}
eab {{ https_acme_eab[0] }} {{ https_acme_eab[1] }}
{%- endif %}
}
{%- endif %}
{%- if pki_cas %}
skip_install_trust
@@ -26,14 +36,70 @@
}
{%- endif %}
}
{% if https and (web_enabled or 'https' in pki_publish or acme_cas) %}
{{ local_fqdn }}:{{ https_web_port }} {
{%- if 'https' in pki_publish %}
{#- The CA certificates and CRLs of directory at /pki/, as DER with the content types of RFC 5280. #}
{%- macro pki_files(directory) %}
handle_path /pki/* {
root * {{ pki_publish_dir }}
@crt path *.crt
@crl path *.crl
header @crt Content-Type application/pkix-cert
header @crl Content-Type application/pkix-crl
root * {{ directory }}
file_server
}
{%- endmacro %}
{#- The addresses of an HTTPS site on port: the HTTPS hosts. #}
{%- macro https_site(port) %}{% for host in https_hosts %}{{ host }}:{{ port }}{{ ', ' if not loop.last else '' }}{% endfor %}{% endmacro %}
{% if web_enabled %}
http://:{{ web_port }} {
header -Server
{{- pki_files(pki_publish_dir) }}
{%- if redirect %}
@https host {{ redirect_hosts | join(' ') }}
handle @https {
redir https://{host}:{{ https_web_port }}{uri} 308
}
{%- endif %}
handle {
reverse_proxy {{ loopback }}:{{ web_loopback_port }} {
header_down -Server
}
}
}
{% endif %}
http://:{{ manager_port }} {
header -Server
{{- pki_files(pki_publish_dir) }}
{%- if redirect %}
@https host {{ redirect_hosts | join(' ') }}
handle @https {
redir https://{host}:{{ https_manager_port }}{uri} 308
}
{%- endif %}
handle {
{%- if redirect %}
redir https://{{ https_name }}:{{ https_manager_port }}{uri} 308
{%- else %}
reverse_proxy {{ loopback }}:{{ manager_loopback_port }} {
header_down -Server
}
{%- endif %}
}
}
{% if metrics_enabled %}
http://:{{ metrics_port }} {
header -Server
reverse_proxy {{ loopback }}:{{ metrics_loopback_port }} {
header_down -Server
}
}
{% endif %}
{%- if https and (web_enabled or acme_cas) %}
{{ https_site(https_web_port) }} {
header -Server
{%- if https_tls %}
tls {{ https_tls.cert }} {{ https_tls.key }}
{%- endif %}
{{- pki_files(pki_publish_dir) }}
{%- for ca in acme_cas %}
handle /acme/{{ ca }}/* {
acme_server {
@@ -43,53 +109,55 @@
{%- endfor %}
handle {
{%- if web_enabled %}
reverse_proxy {{ loopback }}:{{ web_port }}
reverse_proxy {{ loopback }}:{{ web_loopback_port }} {
header_down -Server
}
{%- else %}
respond 404
{%- endif %}
}
}
{% endif %}
{%- if https and 'http-80' in pki_publish %}
http://{{ local_fqdn }} {
handle_path /pki/* {
root * {{ pki_publish_dir }}
file_server
}
handle {
respond 404
}
}
{% endif %}
{%- if https and 'https-default' in pki_publish %}
{{ local_fqdn }}:443 {
handle_path /pki/* {
root * {{ pki_publish_dir }}
file_server
}
handle {
respond 404
}
}
{% endif %}
{%- if https %}
{{ local_fqdn }}:{{ https_manager_port }} {
reverse_proxy {{ loopback }}:{{ manager_port }}
{{ https_site(https_manager_port) }} {
header -Server
{%- if https_tls %}
tls {{ https_tls.cert }} {{ https_tls.key }}
{%- endif %}
{{- pki_files(pki_publish_dir) }}
handle {
reverse_proxy {{ loopback }}:{{ manager_loopback_port }} {
header_down -Server
}
}
}
{% endif %}
{%- if https and metrics_enabled %}
{{ local_fqdn }}:{{ metrics_https_port }} {
reverse_proxy {{ loopback }}:{{ metrics_port }}
{{ https_site(metrics_https_port) }} {
header -Server
{%- if https_tls %}
tls {{ https_tls.cert }} {{ https_tls.key }}
{%- endif %}
reverse_proxy {{ loopback }}:{{ metrics_loopback_port }} {
header_down -Server
}
}
{% endif %}
{%- if webdav %}
{{ local_fqdn }}:{{ webdav_port }} {
reverse_proxy {{ loopback }}:{{ webdav_loopback_port }}
{{ https_site(webdav_port) }} {
header -Server
{%- if https_tls %}
tls {{ https_tls.cert }} {{ https_tls.key }}
{%- endif %}
reverse_proxy {{ loopback }}:{{ webdav_loopback_port }} {
header_down -Server
}
}
{% endif %}
{%- for site in sites %}
# Site {{ site.name }}
{{ site.addresses | join(', ') }} {
header -Server
root * {{ site.root }}
{%- if site.tls == 'ca' %}
tls {
Executable
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Run the manager and the Vite development server on this workstation: dev.py CONFIG [CONNECTION].
CONFIG is the config.json of a platform. The server's address comes from the outputs of the
platform's root module, module_root of CONFIG, relative to its directory, read with its iac_tool
(terraform by default, or tofu). The sessions are kept in the database of the PostgreSQL connection
string CONNECTION, or without one in PGDATABASE (else the login name), with libpq's PG* variables
for the rest. The manager reads the generated dev.json, whose bind is 127.0.0.1, and listens on
127.0.0.1:7080; its Python packages are installed in .venv. The application is served at
http://localhost:5180 and passes /api to the manager. A wrong argument is a message on standard
error and the exit status 2.
"""
import getpass
import json
import os
import pathlib
import subprocess
import sys
ROOT = pathlib.Path(__file__).resolve().parent
SETTINGS = ROOT / 'dev.json'
VENV = ROOT / '.venv'
WEB = ROOT / 'web'
MANAGER = ROOT / 'debian-package' / 'src' / 'usr' / 'lib' / 'linux-manager' / 'manager'
def main():
if not 2 <= len(sys.argv) <= 3:
print(f'usage: {sys.argv[0]} <platform config.json> [PostgreSQL connection string]', file=sys.stderr)
return 2
config = pathlib.Path(sys.argv[1]).resolve()
if not config.is_file():
print(f'dev.py: {sys.argv[1]} does not exist', file=sys.stderr)
return 2
database = sys.argv[2] if len(sys.argv) == 3 else f'dbname={os.environ.get("PGDATABASE") or getpass.getuser()}'
platform = json.loads(config.read_text(encoding='utf-8'))
root = platform.get('module_root')
if not isinstance(root, str) or not root.strip() or os.path.isabs(root):
print(f'dev.py: module_root in {config} must be a directory relative to {config.parent}', file=sys.stderr)
return 2
module_root = pathlib.Path(os.path.normpath(config.parent / root))
if not module_root.is_dir():
print(f'dev.py: module_root {module_root} is not a directory', file=sys.stderr)
return 2
SETTINGS.write_text(json.dumps({'terraform_dir': str(module_root), 'database': database,
'iac_tool': platform.get('iac_tool') or 'terraform', 'bind': '127.0.0.1'}) + '\n',
encoding='utf-8')
# The manager's packages in .venv, and the application's in node_modules, installed when missing or older.
python = VENV / 'bin' / 'python'
if not os.access(python, os.X_OK):
subprocess.run([sys.executable, '-m', 'venv', str(VENV)], check=True)
if subprocess.run([str(python), '-c', 'import psycopg, requests'], stderr=subprocess.DEVNULL).returncode != 0:
subprocess.run([str(VENV / 'bin' / 'pip'), 'install', '--quiet', 'psycopg[binary]', 'requests'], check=True)
modules, lock = WEB / 'node_modules', WEB / 'package-lock.json'
if not modules.is_dir() or lock.stat().st_mtime > modules.stat().st_mtime:
subprocess.run(['npm', 'install'], cwd=WEB, check=True)
manager = subprocess.Popen([str(python), str(MANAGER), '--config', str(SETTINGS)])
try:
print(f'Platform module: {module_root}', flush=True)
return subprocess.run(['npm', 'run', 'dev'], cwd=WEB,
env={**os.environ, 'VITE_MANAGER': 'http://127.0.0.1:7080'}).returncode
except KeyboardInterrupt:
return 130
finally:
manager.terminate()
manager.wait()
if __name__ == '__main__':
sys.exit(main())
-65
View File
@@ -1,65 +0,0 @@
#!/bin/sh
# Run the manager and the Vite development server on this workstation.
# Usage: ./dev.sh <platform config.json> [PostgreSQL connection string]
# The server's address comes from the outputs of the platform's root module, module_root of that
# config.json, relative to its directory, read with its iac_tool; the sessions are kept in the database of the connection
# string, or without one in PGDATABASE (else the login name) with libpq's PG* variables for the
# rest. The manager reads the generated dev.json, whose bind is 127.0.0.1, and listens on 127.0.0.1:7080; its Python packages
# are installed in .venv. The application is served at http://localhost:5180 and passes /api to the
# manager.
set -e
if [ $# -lt 1 ] || [ $# -gt 2 ]; then
printf 'Usage: %s <platform config.json> [PostgreSQL connection string]\n' "$0" >&2
exit 2
fi
DATABASE="${2:-dbname=${PGDATABASE:-$(id -un)}}"
if [ ! -f "$1" ]; then
printf 'ERROR: %s does not exist.\n' "$1" >&2
exit 2
fi
ROOT="$(cd "$(dirname "$0")" && pwd)"
SETTINGS="$ROOT/dev.json"
PLATFORM_CONFIG="$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"
MODULE_ROOT="$(python3 - "$PLATFORM_CONFIG" <<'EOF'
import json, os, sys
path = sys.argv[1]
root = json.load(open(path, encoding='utf-8')).get('module_root')
if not isinstance(root, str) or not root.strip() or os.path.isabs(root):
sys.exit(f'module_root in {path} must be a directory relative to {os.path.dirname(path)}')
print(os.path.normpath(os.path.join(os.path.dirname(path), root)))
EOF
)"
# The tool that reads the outputs is the platform's, iac_tool of its config.json: tofu or terraform.
IAC_TOOL="$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1], encoding="utf-8")).get("iac_tool") or "terraform")' "$PLATFORM_CONFIG")"
if [ ! -d "$MODULE_ROOT" ]; then
printf 'ERROR: module_root %s is not a directory.\n' "$MODULE_ROOT" >&2
exit 2
fi
python3 - "$SETTINGS" "$MODULE_ROOT" "$DATABASE" "$IAC_TOOL" <<'EOF'
import json, sys
with open(sys.argv[1], 'w', encoding='utf-8') as handle:
json.dump({'terraform_dir': sys.argv[2], 'database': sys.argv[3], 'iac_tool': sys.argv[4], 'bind': '127.0.0.1'}, handle)
handle.write('\n')
EOF
if [ ! -x "$ROOT/.venv/bin/python" ]; then
python3 -m venv "$ROOT/.venv"
fi
if ! "$ROOT/.venv/bin/python" -c 'import psycopg, requests' 2>/dev/null; then
"$ROOT/.venv/bin/pip" install --quiet 'psycopg[binary]' requests
fi
cd "$ROOT/web"
if [ ! -d node_modules ] || [ package-lock.json -nt node_modules ]; then
npm install
fi
"$ROOT/.venv/bin/python" "$ROOT/debian-package/src/usr/lib/linux-manager/manager" --config "$SETTINGS" &
MANAGER=$!
trap 'kill $MANAGER 2>/dev/null' EXIT INT TERM
echo "Platform module: $MODULE_ROOT"
VITE_MANAGER=http://127.0.0.1:7080 npm run dev
+57 -13
View File
@@ -1,30 +1,74 @@
# Certificates
The server's two-level CA: a root CA and issuing CAs that sign the certificates.
The server's HTTPS certificate and its 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 and Settings are on every tab but Server.
- **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 of the P2S and S2S CAs while they do not exist yet, the lifetimes, key
type, CRL validity 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.
- **Server:** the first tab, shown also while the PKI cannot be read: HTTPS and the names and
addresses it is for, with a chip while the server's certificate has a source other than ACME, and a settings
button; the server's certificate, when it is not ACME's, with its issuer and expiry; the ACME
CA, with a chip while it is Let's Encrypt's staging environment, and a settings button (see
Server HTTPS below); and Caddy, which serves every HTTP and HTTPS port of the server, with its
version and the state of `caddy.service`.
- **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.
- **Extended key usages:** the usages templates may give, with their OIDs; custom ones are added
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.
- **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.
- **Issuing CAs:** the built-in CAs, P2S for the VPN users, S2S for site-to-site connections and
the Servers Issuing CA `servers` for mTLS certificates and the server's HTTPS certificate, and the
custom CAs, each with its templates and an optional ACME server. P2S is off while the VPN is,
and S2S while the router is, until they are switched on. 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, and one waiting for Simple CA is signed once the server reaches it. **Add issuing
CA**, **Edit** and **Remove** are for the custom CAs; a removed CA is retired and its
certificate revoked. The common name of a CA is fixed once the CA has its certificate or CSR:
a CA with another name is a new CA, added under a new name. Below, the certificates of all of
them, filtered by CA, 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.
## Server HTTPS
The settings button of the HTTPS row sets the **certificate of the server**: ACME; self-signed,
with its validity in days; the Servers Issuing CA of the server's PKI; or another CA. Without
ACME, a checkbox also names the server's IP addresses in the certificate, to reach it over HTTPS
by address. Until the chosen certificate is available, the server serves a self-signed one and warns.
The source is self-signed unless the configuration names another; ACME is used only when it is
chosen. The first setup of a new installation chooses the Servers Issuing CA when the root CA and
that CA are available, as with a root the server creates, else self-signed; it does so also when
the configuration it is given names no source.
HTTPS is always on, for `wan.local_fqdn` or, without it, the host name and `<host name>.local`;
with `https.ip_sans` the certificate also names the server's addresses. A plain HTTP request for
those names is redirected to HTTPS, on the status page's port and the Manager's, unless the
installer's `https_disable_auto_redirect` or `https.disable_auto_redirect` says otherwise; the
status page stays on plain HTTP by address, and `/pki/` on plain HTTP always.
The settings button of the ACME CA row sets the ACME CA of the server's certificate with ACME, and
of the web sites with TLS ACME: Let's Encrypt, with **Staging environment** for routers rebuilt
often, whose certificates no browser trusts; ZeroSSL, with an optional API key; or a custom ACME
directory URL, such as HashiCorp Vault, Caddy or Simple CA, with optional EAB credentials. The CA
of a custom directory's HTTPS certificate is in the server's trust store.
With another CA, the HTTPS certificate row has **Generate CSR**, which saves a CSR for the
server's name, **Import certificate**, which takes the certificate signed for it followed by its
chain, and **Import PFX**, which takes a PFX file and its password. Saving and importing run the
server's setup again, which applies the change. The other HTTPS settings are changed on the
server with `linux-manager-config-edit`.
+11 -9
View File
@@ -1,24 +1,26 @@
# DNS
The server's name server (PowerDNS), the primary of the server's domains. Every domain has the
same two name servers: the server's FQDN and a secondary name server. The [web sites](sites.md)
whose DNS is Router managed get their records in the domain they are in.
The server's name server (PowerDNS), the primary of the server's domains, on a page of its own,
in the page menu while the name server is on. Every domain has the same name servers: the server's
FQDN and, when one is set, a secondary name server. The [web sites](sites.md) whose DNS is Router
managed get their records in the domain they are in.
## Settings
- **State:** disabled, running, or not running yet; the server installs PowerDNS when it is
enabled.
- **State:** disabled, running, or not running yet. The name server is switched on the
[System](system.md) tab, which installs PowerDNS.
- **Primary name server:** the server's FQDN, the SOA and the first NS of every domain. It is the
server's name and is not edited here; its own A record is kept by the DNS of its domain,
wherever that is, not by the server's domains.
- **Secondary name server:** the second NS of every domain, required while the name server is
enabled. The server notifies the addresses it resolves to of every change and allows them to
transfer the domains.
- **Secondary name server:** the second NS of every domain, optional; without it the server's FQDN
is the domains' only name server. The server notifies the addresses it resolves to of every
change and allows them to transfer the domains.
- **Public IP address:** the server's public IP, which the records of the sites with Public IP
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:
+10 -7
View File
@@ -4,9 +4,10 @@ The Ubuntu Linux Manager shows the state of a server running the `linux-manager`
its users, connections, certificates and services. Members of the server's group `admins` see all
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.
The VPN, the router, the name server and WebDAV are components switched on the
[System](system.md) tab, which installs their software. 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. 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.
@@ -22,19 +23,21 @@ Back returns to the previous topic and the house icon to this one.
| Certificates | [Certificates](certificates.md) |
| Web Sites | [Sites](sites.md), [Files](site-files.md), [DNS](dns.md) |
| Docker | [Docker](docker.md) |
| Header | [Shell](shell.md), [Account](account.md) |
| Shell | [Shell](shell.md) |
| Header | [Account](account.md) |
## Header
- **Page menu** (right end): switches between the pages; its button names the page shown.
- **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.
- **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 -3
View File
@@ -3,9 +3,9 @@
A tab each for IKEv2, OpenVPN and WireGuard access: the settings, whether the server
runs the system, why an enabled one does not run yet, and the connected clients.
The page is there while the VPN component is on (`vpn.enabled`). While the router component is
off, the clients reach the networks of `local.cidrs` through NAT from the server's address, on
its one interface; while it is on, they are routed with their own addresses.
The page is there while the VPN component is on, switched on the [System](system.md) tab. While
the router component is off, the clients reach the networks of `local.cidrs` through NAT from the
server's address, on its one interface; while it is on, they are routed with their own addresses.
## Edit
+1 -17
View File
@@ -8,10 +8,7 @@ The Overview tab shows the state of the server, read every 10 seconds by default
- **Status:** the overall status, ok or degraded, on its title bar; the installed version of
`linux-manager` and, when the repository has a newer one, that version;
IKEv2, OpenVPN and WireGuard; the status web service and its port; HTTPS and the name it is for,
with a chip while the certificates come from Let's Encrypt's staging CA and a settings button
(see HTTPS settings below); and Caddy, its HTTPS proxy, with its version, where it comes from (Ubuntu or upstream) and the
state of `caddy.service`.
IKEv2, OpenVPN and WireGuard; and the status web service and its port.
- **Services:** the state of each of the server's systemd services and of Caddy; the chip on the
title bar tells whether the server's services are active.
- **Addresses:** links to the status page over HTTPS and over plain HTTP, and to the
@@ -23,19 +20,6 @@ The Overview tab shows the state of the server, read every 10 seconds by default
- **Configuration:** the sections of the server's configuration the other pages do not show,
among them the status web service (`web`) and HTTPS (`https`).
Caddy is switched to upstream's packages on the server as root with
`linux-manager-caddy use-upstream`.
## HTTPS settings
The settings button of the HTTPS row switches **Let's Encrypt staging CA**. While it is on, Caddy
takes every certificate, the web sites' included, from Let's Encrypt's staging environment, whose
rate limits are far higher but whose certificates no browser trusts: it is for routers that are
rebuilt often, for tests only. While it is off, Caddy takes its certificates from Let's Encrypt,
and from ZeroSSL when Let's Encrypt refuses, such as for its limit of 5 certificates a week for the
same name. Saving runs the server's setup again, which applies the change. The other HTTPS
settings are changed on the server with `linux-manager-config-edit`.
## Updates
- **Check update** asks the server's package repository for newer versions.
+5 -3
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 page menu opens
the Shell page in a tab of its own, which other pages leave alone.
## Editor
@@ -21,8 +23,8 @@ lme /etc/hosts ~/notes.txt
- **Tabs:** each file has a tab with its name, and its path as the tooltip. A dot marks unsaved
changes, and the cross closes the tab, asking first when there are unsaved changes.
- **Editor icon** (left of the shell icon): shown while a file is open. It switches between the
terminal and the editor; the shell keeps running.
- **Editor icon** (left of your name in the header): shown while a file is open. It switches
between the terminal and the editor; the shell keeps running.
- **Minimap button** (left of Save): shows or hides the minimap at the right edge of the editor.
This browser remembers the choice.
- **Save** (or Ctrl+S): writes the file on the server, as your console account. When the file
+12 -9
View File
@@ -1,16 +1,17 @@
# Web sites
Static web sites that Caddy serves on the server, each from its own folder,
`/var/lib/linux-manager/sites/<name>`. The files of a site are on the [Files](site-files.md) tab, and
the name server of their domain on the [DNS](dns.md) tab.
`/var/lib/linux-manager/sites/<name>`. The files of a site are on the [Files](site-files.md) tab,
and the name server of their domain on the [DNS](dns.md) page.
## Settings
- **State:** whether the sites are served.
- **Largest upload:** the largest file or zip archive the Files tab and the server's API take.
- **WebDAV:** whether the folders are served over WebDAV, and its URL with a copy icon.
- **WebDAV:** whether the folders are served over WebDAV, and its URL with a copy icon. WebDAV is
switched on the [System](system.md) tab, which installs rclone.
**Settings** edits them.
**Settings** edits the state, the largest upload and the WebDAV port.
## Columns
@@ -18,12 +19,12 @@ the name server of their domain on the [DNS](dns.md) tab.
name on its port.
- **Port** and **Listen:** the TCP port, and the interfaces its firewall opens: internal,
external or both.
- **TLS:** None (plain HTTP), Let's Encrypt, an issuing CA of the Certificates page, or a
certificate and key given with the site.
- **TLS:** None (plain HTTP), ACME, from the CA set on the Server tab of the Certificates page,
an issuing CA of the same page, or a certificate and key given with the site.
- **Editors:** the group whose members may change the files besides the admins.
- **DNS:** who serves the records of the host names. **User managed:** a DNS provider outside the
router. **Router managed:** the server's name server gives each host name an A or AAAA record in
its domain on the [DNS](dns.md) tab, with the server's **Public IP** (the Public IP address of
its domain on the [DNS](dns.md) page, with the server's **Public IP** (the Public IP address of
the DNS settings), **Internal interface IP** or **External interface IP**. A host name in none of
the server's domains gets no record.
@@ -39,9 +40,11 @@ the DNS of its domain.
## Rules
- The server's own ports, such as 22, 7081, 7443, 7444 and 7445, cannot be taken by a site.
- The server's own ports, such as 22, 7080, 7081, 7443, 7444 and 7445, and the loopback ports of
its services, 7090, 7091 and 9474, cannot be taken by a site.
- Sites sharing a port need host names of their own, the same Listen and the same kind of TLS.
- Let's Encrypt needs host names that resolve to the server from the internet, and port 80.
- ACME with a public CA needs host names that resolve to the server from the internet, and port
80.
- A certificate and key must belong together and name the host names.
- An issuing CA's certificates are trusted by browsers that trust the server's root CA.
+17 -1
View File
@@ -1,6 +1,6 @@
# System
The System tab manages the server's operating system.
The System tab manages the server's operating system and its installable components.
## System updates
@@ -15,3 +15,19 @@ The System tab manages the server's operating system.
- A reboot is offered when a package asks for one, as after a new kernel.
- Only one upgrade runs at a time: this one or the upgrade of `linux-manager` on the
[Overview](router.md) tab.
## Components
- The panel lists the **VPN** (IKEv2, OpenVPN and WireGuard), the **Router** (routing between two
interfaces and site-to-site IPsec), the **Name server** (PowerDNS) and **WebDAV** (the sites'
folders), each on or off, with its packages not installed, installing, installed or failed.
- **Enable** switches a component on. The server installs its packages from the Ubuntu archive,
which takes a minute or so, and then runs it; the panel follows the installation.
- **Disable** switches a component off after a confirmation. Its settings and its packages are
kept. The VPN cannot be switched off while IKEv2, OpenVPN or WireGuard is enabled, nor the
router while site-to-site connections exist.
- The router needs a second network interface: without one it is shown unavailable. Its
**Enable** asks for the internal interface and, in `manual` mode, its address with the prefix
length and the gateway of the internal network.
- A failed installation shows **Enable** again, which tries once more; the
[Logs](logs.md) tab has the output of `linux-manager-install@<component>`.
+3 -3
View File
@@ -11,11 +11,11 @@ for what the package itself does.
up).
- An SSH key pair for `admin_ssh_public_key`.
- A build of the `linux-manager` package published to the repository at `repo_url` (default: the
project's Gitea Debian registry). See [../../debian-package](../../debian-package) for
`build.sh`/`publish.sh`.
project's Gitea Debian registry). See [Building](../../README.md#building) for
`build.py`/`publish.py`.
- That repository must allow anonymous reads, since the server pulls the package with no
credentials configured. On Gitea this means the `debian` package registry under the
`slawek` account is set to public/anonymous-read; `publish.sh` still authenticates to
`slawek` account is set to public/anonymous-read; `publish.py` still authenticates to
upload, only reads are anonymous. This is a one-time change made on the Gitea side, outside
this repository.
+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.
+2 -2
View File
@@ -12,8 +12,8 @@ repository's top-level [README](../../README.md) for what the package itself doe
or a service account).
- An SSH key pair for `admin_ssh_public_key`.
- A build of the `linux-manager` package published to the repository at `repo_url` (default: the
project's Gitea Debian registry). See [../../debian-package](../../debian-package) for
`build.sh`/`publish.sh`. That repository must allow anonymous reads, since the server pulls
project's Gitea Debian registry). See [Building](../../README.md#building) for
`build.py`/`publish.py`. That repository must allow anonymous reads, since the server pulls
the package with no credentials configured.
## Usage
+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"
}
Executable
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
"""Upload the package built for the newest CHANGELOG.md entry to the Gitea Debian repository: publish.py.
The package is out/PACKAGE_VERSION_all.deb, its name the Source of debian/control and its version
the Debian version of the newest entry of CHANGELOG.md (bin/changelog.py), which build.py builds.
It is uploaded to the component main of each distribution of DISTRIBUTIONS (resolute by default,
separated by spaces) of the owner OWNER (koszewscy by default) at SERVER_URL
(https://gitea.koszewscy.waw.pl by default), signed in as OWNER with the token PACKAGES_TOKEN, else
the content of ~/.gitea-packages-token. A distribution that has the version already (Gitea's 409)
is skipped. A failure is a message on standard error and the exit status 1.
"""
import argparse
import base64
import os
import pathlib
import sys
import urllib.error
import urllib.request
ROOT = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT / 'bin'))
import changelog # noqa: E402
CHANGELOG = ROOT / 'CHANGELOG.md'
CONTROL = ROOT / 'debian-package' / 'debian' / 'control'
TOKEN_FILE = pathlib.Path.home() / '.gitea-packages-token'
def main():
argparse.ArgumentParser(description=__doc__.splitlines()[0]).parse_args()
owner = os.environ.get('OWNER') or 'koszewscy'
server = (os.environ.get('SERVER_URL') or 'https://gitea.koszewscy.waw.pl').rstrip('/')
distributions = (os.environ.get('DISTRIBUTIONS') or 'resolute').split()
try:
found = changelog.entries(CHANGELOG.read_text(encoding='utf-8'))
package = changelog.control_field(CONTROL.read_text(encoding='utf-8'), 'Source')
if not found:
raise ValueError('no entry')
token = os.environ.get('PACKAGES_TOKEN') or TOKEN_FILE.read_text(encoding='utf-8').strip()
except (OSError, ValueError) as error:
sys.exit(f'publish.py: {error}')
version = changelog.debian_version(found[0]['version'])
deb = ROOT / 'out' / f'{package}_{version}_all.deb'
if not deb.is_file():
sys.exit(f'publish.py: {deb.relative_to(ROOT)} does not exist; run ./build.py first')
content = deb.read_bytes()
credentials = base64.b64encode(f'{owner}:{token}'.encode()).decode()
for distribution in distributions:
request = urllib.request.Request(f'{server}/api/packages/{owner}/debian/pool/{distribution}/main/upload',
data=content, method='PUT',
headers={'Authorization': f'Basic {credentials}',
'Content-Type': 'application/octet-stream'})
try:
with urllib.request.urlopen(request, timeout=300):
print(f'{package} {version} is published in {distribution}/main.')
except urllib.error.HTTPError as error:
if error.code != 409:
sys.exit(f'publish.py: the upload to {distribution}/main returned HTTP {error.code}: '
f'{error.read().decode(errors="replace").strip()}')
print(f'{package} {version} is already in {distribution}/main, skipping.')
except urllib.error.URLError as error:
sys.exit(f'publish.py: {server} cannot be reached: {error.reason}')
return 0
if __name__ == '__main__':
sys.exit(main())
-48
View File
@@ -1,48 +0,0 @@
#!/bin/sh
set -e
# CONTAINER_RUNTIME from the environment, for example docker with DOCKER_CONTEXT naming a remote engine;
# otherwise Apple container CLI on macOS and Docker CE on Linux.
if [ -z "${CONTAINER_RUNTIME:-}" ]; then
case "$(uname -s)" in
Darwin) CONTAINER_RUNTIME=container ;;
Linux) CONTAINER_RUNTIME=docker ;;
*) printf 'ERROR: unsupported platform %s\n' "$(uname -s)" >&2; exit 1 ;;
esac
fi
OWNER="${OWNER:-koszewscy}"
SERVER_URL="${SERVER_URL:-https://gitea.koszewscy.waw.pl}"
PACKAGES_TOKEN="${PACKAGES_TOKEN:-$(cat ~/.gitea-packages-token)}"
# The Ubuntu releases whose distribution of the repository gets the package, in its component main.
DISTRIBUTIONS="${DISTRIBUTIONS:-resolute}"
# Reads the changelog copied into the builder image, so no bind mount is needed.
changelog_field() {
$CONTAINER_RUNTIME run --rm linux-manager-builder \
dpkg-parsechangelog --show-field "$1" -l /build/src/debian/changelog
}
VERSION="$(changelog_field Version)"
PACKAGE="$(changelog_field Source)"
DEB="out/${PACKAGE}_${VERSION}_all.deb"
if [ ! -f "$DEB" ]; then
printf 'ERROR: %s does not exist. Run ./build.sh first.\n' "$DEB" >&2
exit 1
fi
BODY="$(mktemp)"
trap 'rm -f "$BODY"' EXIT
# Gitea answers 409 for a version that is in the distribution already.
for DISTRIBUTION in $DISTRIBUTIONS; do
STATUS="$(curl -s -o "$BODY" -w '%{http_code}' --user "$OWNER:$PACKAGES_TOKEN" \
--upload-file "$DEB" \
"$SERVER_URL/api/packages/$OWNER/debian/pool/$DISTRIBUTION/main/upload")"
case "$STATUS" in
2??) printf '%s %s is published in %s/main.\n' "$PACKAGE" "$VERSION" "$DISTRIBUTION" ;;
409) printf '%s %s is already in %s/main, skipping.\n' "$PACKAGE" "$VERSION" "$DISTRIBUTION" ;;
*) printf 'ERROR: the upload to %s/main returned HTTP %s: %s\n' "$DISTRIBUTION" "$STATUS" "$(cat "$BODY")" >&2; exit 1 ;;
esac
done
+70 -53
View File
@@ -1,22 +1,39 @@
#!/usr/bin/env python3
"""Commit everything, tag the version of the newest changelog entry and push main with the tags.
"""Commit everything with the summary of the newest CHANGELOG.md entry; with --push, tag its version and push main and the tag.
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.
The newest entry of CHANGELOG.md (bin/changelog.py reads it) is released: its heading gets the
current time, "## 0.5.1 - 2026-11-24 10:00:00 +0100", and everything is committed with its summary
paragraph, its lines joined, as the message. The commit marks the entry as released: a second run
for the same entry is refused, and the next change needs a new entry. With --push, the version of
the heading is tagged, 0.5.1 or 0.5.1-2, and main and the tag are pushed in one atomic push; the tag
starts the release workflow. With --no-tag, the entry is an internal release: it is committed as
without --push, and --push pushes main without a tag. debian/changelog is not kept in the
repository; the build writes it from CHANGELOG.md.
Once a release is committed, LXD_DEV_BUILD_SERIAL of .lm-dev-config/settings.json, the serial of
the last dev build (bin/lm-dev-build.py), is written as 0 when the file exists, so the dev builds
of the next entry start at ~dev1. -n prints what would change and the git commands instead.
"""
import argparse
import datetime
import json
import pathlib
import shlex
import subprocess
import sys
ROOT = pathlib.Path(__file__).resolve().parent
CHANGELOG = ROOT / 'debian-package' / 'debian' / 'changelog'
sys.path.insert(0, str(ROOT / 'bin'))
import changelog # noqa: E402
CHANGELOG = ROOT / 'CHANGELOG.md'
#: The settings of the lm-dev scripts, which hold LXD_DEV_BUILD_SERIAL.
DEV_SETTINGS = ROOT / '.lm-dev-config' / 'settings.json'
#: Print the git commands instead of running them; set by -n/--dry-run.
#: Print the changes and the git commands instead of making them; set by -n/--dry-run.
DRY_RUN = False
@@ -31,63 +48,63 @@ def git(*args):
sys.exit(result.returncode)
def summary():
"""The summary of the first changelog entry joined into one line, or None when it has none.
The summary is the entry's first paragraph: lines indented by exactly two spaces, the
first not a "*" item, with a blank line between it and the header and a blank line after it.
"""
lines = CHANGELOG.read_text(encoding='utf-8').splitlines()
if len(lines) < 4 or lines[1].strip():
return None
paragraph = []
for line in lines[2:]:
if not line.strip():
break
if not line.startswith(' ') or line.startswith(' ') or line.startswith(' -- '):
return None
paragraph.append(line.strip())
else:
return None
if not paragraph or paragraph[0].startswith('*'):
return None
return ' '.join(paragraph)
def version():
"""The tag of the first changelog entry: its version, without the Debian revision when that is 1."""
first = CHANGELOG.read_text(encoding='utf-8').splitlines()[0]
start, end = first.find('('), first.find(')')
if start == -1 or end < start:
sys.exit(f'{CHANGELOG}: the first line has no version: {first}')
full = first[start + 1:end]
upstream, _, revision = full.rpartition('-')
return upstream if upstream and revision == '1' else full
def main():
global DRY_RUN
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('-m', '--message', help='commit message; default: the summary of the newest changelog entry, a paragraph not starting with "*" between blank lines right after its header')
parser.add_argument('-n', '--dry-run', action='store_true', help='print the git commands instead of running them')
parser.add_argument('--no-push', action='store_true', help='commit and tag, but do not push')
parser.add_argument('-n', '--dry-run', action='store_true',
help='print the changes and the git commands instead of making them')
parser.add_argument('--push', action='store_true', help='also tag the release and push main and the tag')
parser.add_argument('--no-tag', action='store_true',
help='make an internal release: with --push, push main alone, without a tag')
args = parser.parse_args()
DRY_RUN = args.dry_run
message = args.message or summary()
if not message:
sys.exit(f'no commit message: pass -m, or start the newest entry of {CHANGELOG} with a summary paragraph '
'not starting with "*", indented by two spaces, with a blank line above and below it')
tag = version()
text = CHANGELOG.read_text(encoding='utf-8')
try:
found = changelog.entries(text)
except ValueError as error:
sys.exit(f'{CHANGELOG}: {error}')
if not found or not found[0]['summary']:
sys.exit(f'start the newest entry of {CHANGELOG} with a summary paragraph between blank lines right after '
'its heading')
newest = found[0]
message, tag = newest['summary'], newest['version']
if subprocess.run(['git', 'rev-parse', '-q', '--verify', f'refs/tags/{tag}'], cwd=ROOT,
capture_output=True).returncode == 0:
sys.exit(f'tag {tag} exists; add a new changelog entry first')
git('add', '-A')
git('commit', '-m', message)
git('tag', tag)
if not args.no_push:
git('push', 'origin', 'main', '--tags')
log = subprocess.run(['git', 'log', '--format=%s'], cwd=ROOT, capture_output=True, text=True)
committed = log.returncode == 0 and message in log.stdout.splitlines()
dirty = subprocess.run(['git', 'status', '--porcelain'], cwd=ROOT, capture_output=True,
text=True).stdout.strip() != ''
if committed and dirty:
sys.exit(f'{tag} is released; add a new changelog entry for the changes')
if committed and not args.push:
sys.exit(f'{tag} is released; add a new changelog entry, or publish it with --push')
if not committed and not dirty:
sys.exit(f'nothing to commit for {tag}')
if not committed:
if newest['date'] is None:
heading = f'## {tag} - {datetime.datetime.now().astimezone().strftime(changelog.DATE_FORMAT)}'
if DRY_RUN:
print(f'# {CHANGELOG.name}: {heading}')
else:
lines = text.splitlines(keepends=True)
lines[newest['line']] = heading + '\n'
CHANGELOG.write_text(''.join(lines), encoding='utf-8')
git('add', '-A')
git('commit', '-m', message)
if DRY_RUN:
print(f'# LXD_DEV_BUILD_SERIAL of {DEV_SETTINGS} set to 0')
elif DEV_SETTINGS.is_file():
settings = json.loads(DEV_SETTINGS.read_text(encoding='utf-8'))
settings['LXD_DEV_BUILD_SERIAL'] = 0
DEV_SETTINGS.write_text(json.dumps(settings, indent=2) + '\n', encoding='utf-8')
if args.push and args.no_tag:
git('push', 'origin', 'main')
elif args.push:
git('tag', tag)
git('push', '--atomic', 'origin', 'main', tag)
return 0
+229 -59
View File
@@ -1,19 +1,28 @@
# 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 package built last, a release in `out/` or a dev build in
`out/dev/`, or the one `--deb` names, into instances of an LXD remote and checks the server in four
scenarios:
- `core`: one interface, router and VPN off;
- `nat`: VPN on, router off, one interface; WireGuard and OpenVPN clients reach a target through
NAT, then the VPN is switched off;
- `s2s`: router and VPN on, two sites with two interfaces each, a site-to-site connection with a
pre-shared key, and a routed WireGuard client; the router is then switched off while
`site_to_site` is set, which setup refuses.
`site_to_site` is set, which setup refuses;
- `oidc`: HTTPS with a certificate of the Servers CA and the OpenID Provider on; the scenario's
Vault, a relying party with its `auth/oidc` method, signs the user alice in with the
authorization code flow and PKCE, her password and a TOTP code of the Vault, driven in a client
by `oidc_login.py` as a browser would, and a wrong code is refused.
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`.
`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.
scenario is a module in `scenarios/` whose `run(lab)` uses the `Lab` class of `lm-dev-run.py`.
`wireguard_peer.py`, `echo.py` and `oidc_login.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,
and the third signs a user in at the server's OpenID Provider.
```sh
export LXD_REMOTE=...
@@ -21,12 +30,12 @@ export LXD_POOL=...
```
```sh
./build.sh
tests/remote/run.py core nat s2s
./build.py
bin/lm-dev-run.py core nat s2s
```
```sh
tests/remote/run.py all
bin/lm-dev-run.py all
```
Options:
@@ -35,70 +44,145 @@ 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 |
| `--deb` | | the package built last | The package to test |
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. Its first instance is its Vault, `lm-vault` on the bridge `lmt-vault` (`10.99.99.0/24`),
reached by the Mac and the instances on the LXD host's address, port 8200, through a proxy
device; every secret reaches an instance through it (see Secrets). The administrator password and
the pre-shared key are generated per run and kept in the scenario's Vault, as `<server>/admin` and
`<server>/config`; with `--keep` they stay there.
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:
- `@PSK@`: the pre-shared key;
- `@PSK@`: the pre-shared key, filled in on the Mac; the file reaches the server through the Vault;
- `@ETH0@` and `@ETH1@`: the names of its interfaces;
- `@CIDR0@`: the network of its first address.
- `@CIDR0@`: the network of its first address;
- `@FQDN@`: in `dev.json`, the name of the dev VM, `--fqdn` of `lm-dev-vm.py`.
## Secrets
A secret never reaches an instance as a command-line argument or on standard input, where `ps`,
`/proc/<pid>/cmdline` or a log would show it. The scripts keep it in the project's Vault, HashiCorp
Vault with file storage and a plain HTTP listener, which `lm_dev.py` initialises with one key share
and unseals over its API, with KV v2 at `kv`, the TOTP engine at `totp` and AppRole enabled.
Every instance the scripts launch, apart from the Vault and the hosts of the lab's isolated LANs,
which have no route to it, gets an AppRole of its own, named after it, once it has booted:
1. The Mac makes the policy `instance-<name>`, which reads `kv/data/<name>/*` and creates the TOTP
keys `totp/keys/<name>-*`, and the role `<name>`, which gives batch tokens of 5 minutes and secret
IDs that do not expire.
2. The helper `lm-dev-vault` goes to `/usr/local/sbin`, and the Vault's URL, the role ID and a
wrapping token of a new secret ID, single-use and living 120 seconds, to `/etc/vault` (0700), the
IDs readable by root only.
3. `lm-dev-vault init` removes the token, refuses it unless it wraps the role's `secret-id`
request, unwraps it and keeps the secret ID in `/etc/vault/secret-id`.
From then on the instance logs in with its AppRole. A file that holds a secret is stored whole by
the Mac as `kv/<name>/<file>`, and `lm-dev-vault get` writes it in the instance with the mode asked
for; a program that reads the secret on standard input reads that file, which is removed right
after. The debconf preseed with the admin password, `linux-manager.json` with the pre-shared key,
and alice's password and OpenVPN profile take this way; the admin password is also kept as
`<name>/admin`. A WireGuard client's private key is made in the client and never leaves it.
A user's TOTP token is the key `<vm>-<user>` of the TOTP engine. The VM has the Vault generate it
with `lm-dev-vault totp` and enrols its secret with its current code; the secret cannot be read
back from the Vault, which gives the codes (`totp/code/<vm>-<user>`). For the administrator of a VM
made by `lm-dev-vm.py`, the Mac also reads the key's otpauth URL from the VM before the VM removes
its copy, and keeps it as `otp_url` with the password, to add the token to an authenticator app.
`lm-dev-vm.py remove` deletes the VM's role, policy, secrets and TOTP keys.
The Vault's web UI is at `/ui` of its address, `http://<vault-address>:8200/ui`; it signs in with
the root token of `vault-<project>.json`.
The state the scripts keep across clean-ups of `tmp/` is in `.lm-dev-config/` at the repository's
root, mode 0700, its files 0600, ignored by git: the scripts' settings (`settings.json`), the
project's state and repository key, the Vault's address, unseal key and root token
(`vault-<project>.json`) and the administrator of each VM `lm-dev-vm.py` made, its `username`,
`password` and the otpauth URL of its TOTP token, `otp_url` (`vm-<project>-<vm>.json`). `tmp/` holds only what can go: logs and files removed right after use.
Each variable of the option tables below, and `LXD_DEV_BUILD_SERIAL`, the serial of the last dev
build (see `lm-dev-build.py` below), is read from the environment, else from `settings.json`, a
JSON object of the variables and their values, else it takes its default. A variable without a
default, such as `LXD_REMOTE`, is required: without its option, the script stops and names it.
```json
{
"LXD_REMOTE": "my-remote",
"LXD_POOL": "default",
"LXD_FORWARD_ADDRESS": "192.0.2.10",
"LXD_DEV_FQDN": "lm-dev.example.org"
}
```
## 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, `router` 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`, whose password and TOTP token, unless `--no-otp` is given, are `password` and
`otp_url` of `.lm-dev-config/vm-<project>-<vm>.json`, and a configuration from `configs/`,
`dev.json` by default, which keeps the status page and the Manager on plain HTTP by name too
(`https.disable_auto_redirect`); `@ETH0@` is the interface of the VM's default route. A password or
`otp_url` the file lacks, or both when there is no file, is generated and kept in the file, so a VM
made again has the same password and token; delete one from the file to have a new one made.
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 `--deb`, or
else the package built last, in `out/` or `out/dev/`. 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;
- `7080` and `7443` to the Manager, over HTTP and HTTPS;
- `7081` and `7444` to the status web service, over HTTP and HTTPS;
- `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
is `--forward-address`, or else one 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, where the administrator's password is kept, the URLs, the
command of a shell in it and the command that removes it; it never prints the password.
```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:
`create` needs the project's Vault (`lm-dev-lxd-project.py vault create`): the VM gets its
AppRole there, and reads the preseed and the configuration, kept as `<vm>/preseed` and
`<vm>/config`; the TOTP key `<vm>-admin` is made from `otp_url`, or else the VM has the Vault
generate it. `remove` deletes the VM, its forward and what the Vault keeps for it, and keeps
`vm-<project>-<vm>.json`. 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` | | `router` | 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.
| `--config` | | `dev.json` | The configuration from `configs/` |
| `--listen` | `LXD_LISTEN` | the remote URL's host | Outside a test project, the address the proxies listen on |
| `--forward-address` | `LXD_FORWARD_ADDRESS` | allocated | In a test project, the forward's listen address, one of the uplink's routes, so a recreated VM keeps it |
| `--fqdn` | `LXD_DEV_FQDN` | `lm-dev.test` | The name of the VM, `@FQDN@` of `dev.json`: the Manager and the status web service answer HTTPS for it, so it has to resolve to the forward or proxy address |
| `--no-otp` | | off | With `create`, enrol no TOTP token for `admin` |
| `--deb` | | the package built last | Outside a test project, the package to install |
## 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
@@ -106,11 +190,21 @@ on the project's `wan`, whose listen address LXD allocates from the uplink's `--
gateway;
- a default profile with a root disk on the pool and `eth0` on `wan`;
- the container `repo`, whose nginx serves a signed apt repository of the dev builds,
`resolute main` for amd64 and arm64, at its pinned address.
`resolute main` for amd64 and arm64, at its pinned address;
- the container `vault`, the project's Vault (see Secrets), reached by the Mac through a forward
of port 8200 on `wan` at `--vault-address` (`LXD_VAULT_ADDRESS`), or an allocated address, and
by the instances on its pinned address.
What the other scripts need, the repository's URL among it, is written to
`tmp/lxd-project-<project>.json`, and the repository's key to `tmp/lxd-project-<project>.gpg`.
`remove` deletes the project's instances, its networks, the project and those files.
`.lm-dev-config/lxd-project-<project>.json`, and the repository's key to
`.lm-dev-config/lxd-project-<project>.gpg`. `remove` deletes the project's instances, its networks,
the project and those files.
```sh
bin/lm-dev-lxd-project.py vault create # the Vault of an existing project
bin/lm-dev-lxd-project.py vault unseal # after a restart of the vault container
bin/lm-dev-lxd-project.py vault remove
```
The remote needs OVN, set up as LXD's standalone OVN guide describes, and a host bridge on the
LAN, whose host address stays on the bridge. `uplink setup` creates on it, once per remote, the
@@ -127,19 +221,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 |
@@ -148,6 +242,7 @@ tests/remote/lxd-project.py remove
| `--pool` | `LXD_POOL` | required by `create` | The storage pool of the project's root disks |
| `--project` | `LXD_PROJECT` | `lm-dev` | The project |
| `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of the repository container |
| `--vault-address` | `LXD_VAULT_ADDRESS` | allocated | The listen address of the Vault's forward, one of the uplink's routes |
| `--uplink` | `LXD_UPLINK` | `uplink` | The physical uplink network of the OVN networks |
| `--parent` | `LXD_UPLINK_PARENT` | required by `uplink setup` | The host bridge on the LAN |
| `--gateway` | `LXD_UPLINK_GATEWAY` | required by `uplink setup` | The LAN's gateway, address/prefix |
@@ -155,21 +250,96 @@ 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
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
environment; the build is moved to `out/dev/`, copied into the repository and published there. A
`lm-dev-build.py` builds and publishes the next dev build. Its version is the Debian version of
the newest entry of `CHANGELOG.md` with `~dev<N>` before the Debian revision, `0.41.0~dev7-1` for
`0.41.0`, so the release of that entry is newer than its dev builds. `N` is that of the last dev build,
`LXD_DEV_BUILD_SERIAL`, 0 by default; each build that succeeds writes its own, one higher, into
`.lm-dev-config/settings.json`, and `release.py` writes 0 there when it releases, so the next
entry's builds start at `~dev1`. `./build.py` 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 TOTP token for a user of a VM, `admin` of `router` by
default, replacing a token the user had. The project's Vault generates the key `<vm>-<user>` in its
TOTP engine and hands it to the VM (see Secrets), where the package's `linuxmanager_users` stores
it. For the VM's administrator, the key is made from `otp_url` in `vm-<project>-<vm>.json` when the
file has it, and a generated key's URL is kept there as `otp_url`.
`bin/lm-dev-otp-code.py` prints the user's current code, read from the Vault, for the Manager's
sign-in, SSH or `sudo`.
```sh
bin/lm-dev-otp-register.py
```
```sh
bin/lm-dev-otp-code.py
```
| Option | Variable | Default | Meaning |
|---|---|---|---|
| `--remote` | `LXD_REMOTE` | required by `lm-dev-otp-register.py` | The `lxc` remote |
| `--project` | `LXD_PROJECT` | `lm-dev` | The project of the VM |
| `--vm` | | `router` | The name of the VM |
| `--user` | | `admin` | The user |
## 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 secret in the file `--secret-file` or `OTP_FILE` names, readable
by its owner only: the base32 secret alone, or with `--url` its `otpauth://` URI, without a line
end, so Vault's TOTP engine imports the file as it is. The codes are RFC 6238's, SHA-1, 6 digits
and 30 seconds by default; a file holding a URI gives the URI's.
Options of both actions:
| Option | Variable | Default | Meaning |
|---|---|---|---|
| `--secret-file` | `OTP_FILE` | required | The file of the base32 secret or its `otpauth://` URI |
| `--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
```
Either file is a key of Vault's TOTP engine, the secret with its settings, or the URI with all of
them:
```sh
vault write totp/keys/admin key=@secret-file issuer=lm-dev account_name=admin
vault write totp/keys/admin url=@otpauth-file
```
| Option | Default | Meaning |
|---|---|---|
| `--account`, `--issuer` | none | The label of the URI |
| `--url` | off | Store the `otpauth://` URI instead of the secret alone |
| `--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, passkeys,
PowerDNS answering from outside, and the Azure and GCP platform modules.
+24
View File
@@ -0,0 +1,24 @@
#cloud-config
# The Vault of a test project: HashiCorp's vault package from its apt repository, file storage and a plain HTTP
# listener; lm_dev.vault_initialise initialises and unseals it over its API.
write_files:
- path: /root/vault.hcl
permissions: '0644'
content: |
storage "file" {
path = "/opt/vault/data"
}
listener "tcp" {
address = "0.0.0.0:8200"
tls_disable = "true"
}
disable_mlock = true
ui = true
runcmd:
- wget -O - https://apt.releases.hashicorp.com/gpg | gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
- echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?<=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" > /etc/apt/sources.list.d/hashicorp.list
- apt-get update
- DEBIAN_FRONTEND=noninteractive apt-get install -y vault
- install -d -o vault -g vault -m 0700 /opt/vault/data
- install -m 0644 /root/vault.hcl /etc/vault.d/vault.hcl
- systemctl enable --now vault
+2 -5
View File
@@ -1,8 +1,5 @@
{
"general": {"platform": "generic", "mode": "manual"},
"router": {"enabled": false},
"vpn": {"enabled": false},
"general": {"platform": "generic"},
"interfaces": {"external": "@ETH0@"},
"wan": {"local_fqdn": "lm-core.test"},
"https": {"enabled": false}
"wan": {"local_fqdn": "lm-core.test"}
}
+6
View File
@@ -0,0 +1,6 @@
{
"general": {"platform": "generic"},
"interfaces": {"external": "@ETH0@"},
"wan": {"local_fqdn": "@FQDN@"},
"https": {"disable_auto_redirect": true}
}
+2 -7
View File
@@ -1,11 +1,6 @@
{
"general": {"platform": "generic", "mode": "manual"},
"router": {"enabled": false},
"vpn": {"enabled": false},
"general": {"platform": "generic"},
"interfaces": {"external": "@ETH0@"},
"wan": {"local_fqdn": "lm-nat.test"},
"local": {"cidrs": ["@CIDR0@"]},
"wireguard": {"enabled": false, "address": "10.66.0.1/24", "listen_port": 51820},
"openvpn": {"enabled": false, "address_pool": "10.67.0.0/24", "port": 1194, "protocol": "udp"},
"https": {"enabled": false}
"local": {"cidrs": ["@CIDR0@"]}
}
+3 -5
View File
@@ -1,11 +1,9 @@
{
"general": {"platform": "generic", "mode": "manual"},
"router": {"enabled": false},
"general": {"platform": "generic"},
"vpn": {"enabled": true},
"interfaces": {"external": "@ETH0@"},
"wan": {"local_fqdn": "lm-nat.test"},
"local": {"cidrs": ["@CIDR0@"]},
"wireguard": {"enabled": true, "address": "10.66.0.1/24", "listen_port": 51820},
"openvpn": {"enabled": true, "address_pool": "10.67.0.0/24", "port": 1194, "protocol": "udp"},
"https": {"enabled": false}
"wireguard": {"enabled": true, "address": "10.66.0.1/24"},
"openvpn": {"enabled": true, "address_pool": "10.67.0.0/24"}
}
+6
View File
@@ -0,0 +1,6 @@
{
"general": {"platform": "generic"},
"interfaces": {"external": "@ETH0@"},
"wan": {"local_fqdn": "lm-oidc.test"},
"oidc": {"enabled": true}
}
+3 -5
View File
@@ -1,14 +1,12 @@
{
"general": {"platform": "generic", "mode": "manual"},
"router": {"enabled": false},
"general": {"platform": "generic"},
"vpn": {"enabled": true},
"interfaces": {"external": "@ETH0@"},
"wan": {"local_fqdn": "lm-s2s-a.test"},
"local": {"cidrs": ["172.31.31.0/24"]},
"site_to_site": {
"to-b": {"addrs": ["172.31.20.20"], "id": "lm-s2s-b.test", "cidrs": ["172.31.32.0/24"],
"local_cidrs": ["172.31.31.0/24"], "local_id_mode": "fqdn", "auth": "psk", "psk": "@PSK@"}
"local_cidrs": ["172.31.31.0/24"], "psk": "@PSK@"}
},
"wireguard": {"enabled": true, "address": "10.66.0.1/24", "listen_port": 51820},
"https": {"enabled": false}
"wireguard": {"enabled": true, "address": "10.66.0.1/24"}
}
+3 -4
View File
@@ -1,5 +1,5 @@
{
"general": {"platform": "generic", "mode": "manual"},
"general": {"platform": "generic"},
"router": {"enabled": true},
"vpn": {"enabled": true},
"interfaces": {"external": "@ETH0@", "internal": "@ETH1@"},
@@ -7,8 +7,7 @@
"local": {"cidrs": ["172.31.31.0/24"], "int_addr": "172.31.21.10", "int_gateway_ip": "172.31.21.20"},
"site_to_site": {
"to-b": {"addrs": ["172.31.20.20"], "id": "lm-s2s-b.test", "cidrs": ["172.31.32.0/24"],
"local_cidrs": ["172.31.31.0/24"], "local_id_mode": "fqdn", "auth": "psk", "psk": "@PSK@"}
"local_cidrs": ["172.31.31.0/24"], "psk": "@PSK@"}
},
"wireguard": {"enabled": true, "address": "10.66.0.1/24", "listen_port": 51820},
"https": {"enabled": false}
"wireguard": {"enabled": true, "address": "10.66.0.1/24"}
}
+3 -5
View File
@@ -1,13 +1,11 @@
{
"general": {"platform": "generic", "mode": "manual"},
"general": {"platform": "generic"},
"router": {"enabled": true},
"vpn": {"enabled": false},
"interfaces": {"external": "@ETH0@", "internal": "@ETH1@"},
"wan": {"local_fqdn": "lm-s2s-b.test"},
"local": {"cidrs": ["172.31.32.0/24"], "int_addr": "172.31.22.10", "int_gateway_ip": "172.31.22.20"},
"site_to_site": {
"to-a": {"addrs": ["172.31.20.10"], "id": "lm-s2s-a.test", "cidrs": ["172.31.31.0/24"],
"local_cidrs": ["172.31.32.0/24"], "local_id_mode": "fqdn", "auth": "psk", "psk": "@PSK@"}
},
"https": {"enabled": false}
"local_cidrs": ["172.31.32.0/24"], "psk": "@PSK@"}
}
}
-72
View File
@@ -1,72 +0,0 @@
#!/usr/bin/env python3
"""Build the next numbered dev build and publish it to a test project's repository: dev-build.py.
The test number in tmp/test-number goes up by one for each build that succeeds. 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.
"""
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'
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)')
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')
state = json.loads(state_file.read_text(encoding='utf-8'))
# The newest entry's first line is "package (version) distribution; urgency=...".
match = re.match(r'(\S+) \(([^)]+)\)', CHANGELOG.read_text(encoding='utf-8'))
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
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')
# The dev build leaves out/ to out/dev/, so out/ keeps the release builds.
target = ROOT / 'out' / 'dev'
target.mkdir(exist_ok=True)
for artifact in (ROOT / 'out').glob(f'{package}_{dev}_*'):
artifact.replace(target / artifact.name)
deb = target / f'{package}_{dev}_all.deb'
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)
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)
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)')
if __name__ == '__main__':
main()
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more