Compare commits

...
2 Commits
109 changed files with 6311 additions and 3786 deletions

No files matched your search

+2 -4
View File
@@ -15,13 +15,11 @@ jobs:
uses: actions/checkout@v6 uses: actions/checkout@v6
- name: Build package - name: Build package
working-directory: debian-package run: ./build.py
run: ./build.sh
- name: Publish package - name: Publish package
working-directory: debian-package
env: env:
SERVER_URL: ${{ secrets.CI_URL }} SERVER_URL: ${{ secrets.CI_URL }}
OWNER: ${{ secrets.CI_OWNER }} OWNER: ${{ secrets.CI_OWNER }}
PACKAGES_TOKEN: ${{ secrets.CI_TOKEN }} PACKAGES_TOKEN: ${{ secrets.CI_TOKEN }}
run: ./publish.sh run: ./publish.py
+2 -1
View File
@@ -16,5 +16,6 @@ node_modules
web/dist web/dist
.venv .venv
dev.json dev.json
/.dev-build.serial
**/.env **/.env
/.lm-dev-config/
/debian-package/debian/changelog
+299 -136
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 in `DOCKER-USER` are not touched, because the package owns only its own chain. Restarting Docker
restores the rules. The rules cover IPv4 only. 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 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 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 `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 the package depends on, and no web framework. It listens on the loopback address behind Caddy
address of the internal interface, of the external interface or of both, as `web.listen` sets (ADR-21), which serves it on `web.port`, 7081 by default, and is on unless `web.enabled` is
(`internal`, `external` or `both`, the default), with a server for each address, and is on `false` (ADR-7). The firewall opens `web.port` on the internal interface, the external interface
unless `web.enabled` is `false` (ADR-7). `/` is for people, in plain text for `curl` and `wget` or both, as `web.listen` sets (`internal`, `external` or `both`, the default). `/` is for people,
and as a Tailwind CSS page for a browser, and `/status` is the same status as JSON. Both show as 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 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, 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 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 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. 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 `/status` names its content, so clients such as Cloud Manager and the Manager show what it
has. `linux-manager-setup` opens the has. `linux-manager-setup` writes the firewall rules of `web.listen`, and the features and the
port on both interfaces in UFW, so the choice of `web.listen` is made by the service alone, and facts it resolves to `/run/linux-manager/web.json`.
writes 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; 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; `web.listen` set to `internal` keeps it to the internal network. Caddy serves it over plain HTTP
HTTPS is Caddy's (ADR-21), so on the plain HTTP port the passwords of `/auth` and the tokens 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` cross the internet unencrypted. A change of `web.listen` takes effect with the next run of setup,
needs no run of setup, since the firewall does not depend on it; the package's upgrade runs which writes the firewall rules. `/` and `/status` have no authentication, which is acceptable because they are
setup, which writes the 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`, 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 `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. browser on a network without internet shows the unstyled page, and `curl` is unaffected.
@@ -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 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 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. `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, 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 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 `X-Forwarded-For` entry for a peer in `web.trusted_proxies`, by default the address the call came
@@ -518,41 +520,55 @@ 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 Manager session ends with its access token. An enrolled user who has lost the authenticator
needs an administrator. 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 Status: Accepted
Context: The status web service and the Manager are reachable from the internet (ADR-2), 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 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 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 Decision: Caddy, the `caddy` package of the Ubuntu archive and a dependency of the package
`https.enabled` is `true` (the default) and `wan.local_fqdn` is set, `linux-manager-setup` writes (ADR-31), serves every HTTP and HTTPS port of the server's services. The web service listens on
`/etc/caddy/linux-manager.Caddyfile`: a site for `wan.local_fqdn` on `https.web_port` (7444) for the `127.0.0.1:7091`, the Manager on the server on `127.0.0.1:7090`, the metrics service on
web service and, while the Manager is installed, one on `https.manager_port` (7443) for `127.0.0.1:9474` and rclone's WebDAV on `127.0.0.1:7446`, and Caddy calls them there. Once the
the manager, each passing calls to the service on `127.0.0.1`. Caddy obtains and renews the server is configured, `linux-manager-setup` writes `/etc/caddy/linux-manager.Caddyfile`: plain
certificate from Let's Encrypt with the HTTP challenge on port 80, which the firewall opens on HTTP sites on `web.port` (7081), the Manager's `port` (7080) and, while metrics are on,
the external interface; `auto_https disable_redirects` keeps port 80 to the challenge. The `metrics.port` (9464), on every address; while `https.enabled` is `true` and `wan.local_fqdn` is
package's drop-in for `caddy.service` points it at that file and keeps it from starting before set, sites for `wan.local_fqdn` on `https.web_port` (7444), `https.manager_port` (7443),
the file exists, so `/etc/caddy/Caddyfile`, a configuration file of the `caddy` package, is left `metrics.https_port` (9465) and `sites.webdav_port` (7445). While HTTPS is on, the Manager's plain
unchanged. Both services always listen on `127.0.0.1` as well as on the interfaces their HTTP site redirects (308) to its HTTPS address unless `https.disable_auto_redirect` is set; the
`listen` settings name, and trust `X-Forwarded-For` from it, which Caddy sets from the peer and status page's never does, so monitors and clients that do not trust the server's certificate
never takes from the client. Let's Encrypt issues at most 5 certificates a week for the same keep reaching it. The `listen` settings choose the interfaces the firewall opens each plain HTTP
names, which routers rebuilt for tests reach; `https.acme_staging` sets Caddy's global `acme_ca` port on, as Caddy listens on every address. The certificate comes from `https.certificate`
to Let's Encrypt's staging directory, which replaces Caddy's default CAs for every site, so no (ADR-60); with `acme`, Caddy obtains and renews it with the HTTP challenge on port 80, which the
test certificate comes from a production CA. `PUT /https/settings` changes `acme_staging` alone: 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 the other settings of the section switch HTTPS off or move its ports, which would end the
connection the Manager makes the change on. connection the Manager makes the change on.
Consequences: HTTPS needs `wan.local_fqdn` in public DNS pointing at the server and port 80 Consequences: HTTPS with a public ACME CA needs `wan.local_fqdn` in public DNS pointing at the
reachable from the internet; until then Caddy retries and the HTTPS ports do not answer. The server and port 80 reachable from the internet; until then Caddy retries and the HTTPS ports do
certificate and the ACME account are in `/var/lib/caddy`. A router on the staging CA has a not answer. The certificate and the ACME account are in `/var/lib/caddy`. A router on the staging
certificate no client trusts. Plain HTTP stays as the `listen` CA has a certificate no client trusts. A service that is not behind Caddy cannot be reached from
settings set it, so `internal` keeps passwords off the internet. Caddy's admin endpoint listens another host, so while Caddy is stopped, or before the first setup, only the bootstrap page
on `localhost:2019`, which `caddy reload` uses. Port 80 and the HTTPS ports are not available answers. The loopback ports are fixed, and no site or Docker container may take them or Caddy's
to Docker containers while HTTPS is on. The Manager's HTTPS port is a setting of the server, not ports. Caddy's admin endpoint listens on `localhost:2019`, which `caddy reload` uses. The
of the manager. 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 ## ADR-22: Metrics are kept in PostgreSQL and served in the Prometheus format, pushed with OTLP
@@ -770,9 +786,11 @@ shows it: `local`, a root the server creates and keeps the key of, which signs o
path length 1; `offline`, whose certificate and the certificates of the issuing CAs, signed 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 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 first; `simple-ca`, a Simple CA service (ADR-59). The issuing CAs, path length 0, sign the
certificates. `p2s` signs the server's VPN server certificate and the users' certificates, certificates. Three are built in: `p2s` signs the server's VPN server certificate and the
`s2s` the site-to-site certificates, and the CAs of `pki.issuing_cas` what their templates users' certificates, `s2s` the site-to-site certificates, and `servers`, the Servers Issuing CA, mTLS
allow. A template fixes the key, the lifetime, the key usages, the extended key usages, the kind 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 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 `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 CA. The module `linuxmanager_pki.py`, with `python3-cryptography` from the Ubuntu archive, builds
@@ -863,28 +881,23 @@ Consequences: The certificates Caddy issues chain to the server's root through t
not in the server's inventory, follow no template and are not revoked; their short lifetime takes 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. 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 Status: Accepted
Context: Caddy 2.6.2 of the Ubuntu archive lacks later features, such as a pki root without its key Context: Caddy fronts every HTTP and HTTPS port of the server (ADR-21), so the server's services
and the settings of the ACME server. Caddy's own repository has current versions of the package of cannot be reached without it. Caddy 2.6.2 of the Ubuntu archive lacks later features, such as a
the same name. A dependency on `caddy` installs the archive's package with `linux-manager`. apt cannot pki root without its key and the settings of the ACME server; Caddy's own repository has current
run inside `linux-manager-setup` when the package's installation runs setup, as dpkg holds its lock. 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 Decision: `linux-manager` depends on `caddy`, which apt installs from the Ubuntu archive with the
`linux-manager-caddy.service` install it from `https.caddy_source`: `ubuntu`, or `upstream`, for package and upgrades with the system's packages. The package writes no repository of its own and
which the unit writes the deb822 source and the key it downloads over HTTPS from Caddy's installs nothing at setup time, and the configuration uses only what Caddy 2.6.2 supports.
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.
Consequences: The first setup run with HTTPS starts the installation and serves HTTPS on the run Consequences: Features of later Caddy versions are not available until the archive has them. An
that follows it. The key of Caddy's repository is trusted as downloaded over HTTPS, the way Caddy's administrator who adds another repository with a `caddy` package gets that version, which the
installation instructions do it. Going back to the archive's Caddy is a manual downgrade. package does not check.
## ADR-32: The PKI is kept in the server's directory ## ADR-32: The PKI is kept in the server's directory
@@ -1210,8 +1223,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 `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 `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. 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>`, rclone and PowerDNS are installed on demand from the archive by `linux-manager-install@<component>`
like Caddy. (ADR-57).
Consequences: Uploads and WebDAV use the directory's passwords, a TOTP code appended for an 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 enrolled user. rclone writes a WebDAV upload to its cache first and to the folder a few seconds
@@ -1221,45 +1234,46 @@ later. S3 and Azure Blob clients are not served.
Status: Accepted Status: Accepted
Context: The server hosts authoritative domains as their primary, with a secondary name server, and Context: The server hosts authoritative domains as their primary, with an optional secondary name
a domain can give the sites their records without a registrar change per site. The server's own server, and a domain can give the sites their records without a registrar change per site. The
name, `wan.local_fqdn`, belongs to a domain of its own, wherever that is hosted. Ubuntu 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 has BIND, Knot and PowerDNS; only PowerDNS's gpgsql backend reads records from PostgreSQL, so
from PostgreSQL, so changes are rows, without zone files or reloads. systemd-resolved's stub holds changes are rows, without zone files or reloads. systemd-resolved's stub holds 127.0.0.53 and
127.0.0.53 and 127.0.0.54, and the remote access clients' resolver answered on the external 127.0.0.54, and the remote access clients' resolver answered on the external addresses, the
addresses, the addresses an authoritative server needs. The clients reach the internal address addresses an authoritative server needs. The clients reach the internal address just as well,
just as well, through the tunnel when it is in `local.cidrs` (ADR-43). through the tunnel when it is in `local.cidrs` (ADR-43).
Decision: While `dns.enabled` is true, setup runs `pdns.service` with 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 `/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 addresses of `dns.listen`, with the gpgsql backend on the database `linux-manager-dns` and
own schema, and `primary=yes`. The domains and their manual records are rows of the server's tables PowerDNS's own schema, and `primary=yes`. The domains and their manual records are rows of the
in that database, like the sites in `linux-manager-sites`, not settings of `linux-manager.json`: they are server's tables in that database, like the sites in `linux-manager-sites`, not settings of
many and change through the web service. The name servers are settings, the same for every domain: `linux-manager.json`: they are many and change through the web service. The name servers are
`wan.local_fqdn`, the server's one name, is the primary, and `dns.secondary` the secondary. Setup settings, the same for every domain: `wan.local_fqdn`, the server's one name, is the primary, and
writes each domain as a MASTER zone through the procedure `dns_apply` of `dns.secondary` the secondary, which is optional: without it the domains have the primary as their
`/usr/share/linux-manager/sql/dns.sql`: SOA with `wan.local_fqdn`, NS of `wan.local_fqdn` and only name server, as a small or internal deployment has no second server to name. Setup writes each
`dns.secondary`, an A or AAAA record of every host name of a site with `dns` `router` whose closest domain as a MASTER zone through the procedure `dns_apply` of `/usr/share/linux-manager/sql/dns.sql`:
domain it is, with the server's address the site chooses (`wan.public_address`, the internal or the SOA with `wan.local_fqdn`, NS of `wan.local_fqdn` and `dns.secondary` while it is set, an A or AAAA
external interface's), and the manual records; the serial grows only when the records change, which record of every host name of a site with `dns` `router` whose closest domain it is, with the
makes PowerDNS notify. `wan.local_fqdn` gets no record in the domains: its A record is in the DNS of server's address the site chooses (`wan.public_address`, the internal or the external interface's),
its own domain, which the server does not manage. A site of `dns` `user` gets no records, as its and the manual records; the serial grows only when the records change, which makes PowerDNS notify.
names are served elsewhere. The addresses `dns.secondary` resolves to at each run go to every `wan.local_fqdn` gets no record in the domains: its A record is in the DNS of its own domain, which
domain's `ALSO-NOTIFY` and `ALLOW-AXFR-FROM` metadata, so the global `allow-axfr-ips` stays the the server does not manage. A site of `dns` `user` gets no records, as its names are served
loopback default. The public address is a setting, since the server sees only private addresses on elsewhere. The addresses `dns.secondary` resolves to at each run go to every domain's `ALSO-NOTIFY`
its interfaces behind a cloud's NAT and resolving `wan.local_fqdn` would answer from its own DNS and `ALLOW-AXFR-FROM` metadata, so the global `allow-axfr-ips` stays the loopback default. The
when it hosts that name. `dns.nameserver` and `dns.addresses` of an earlier configuration are left public address is a setting, since the server sees only private addresses on its interfaces behind a
out when it is read, so that it loads; a missing `dns.secondary` makes setup warn, not fail, so that cloud's NAT and resolving `wan.local_fqdn` would answer from its own DNS when it hosts that name.
a router keeps running until it is set. A host name belongs to its closest domain only, and a `dns.nameserver` and `dns.addresses` of an earlier configuration are left out when it is read, so
domain inside another is delegated from it with NS records, so a name is never answered by two that it loads. A host name belongs to its closest domain only, and a domain inside another is
zones. The remote access clients' resolver answers on the addresses of the setting delegated from it with NS records, so a name is never answered by two zones. The remote access
`p2s.dns_listen`, by default the internal one; a `dns.listen` that shares an interface with it is clients' resolver answers on the addresses of the setting `p2s.dns_listen`, by default the internal
refused while P2S or OpenVPN is enabled. 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 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 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 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 ## ADR-43: The remote access clients' resolver is dnsmasq, not systemd-resolved
@@ -1394,19 +1408,30 @@ one line with its type and message.
Consequences: The logs hold one line per failure, without its stack. A failure that reaches the 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. 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 Status: Accepted
Context: The summary of an entry of `debian/changelog` is the commit message of its release, Context: The history of the package is also the source of each release's commit message and tag:
which `release.py` reads from the changelog. Summaries are often longer than the 80 columns `release.py` commits with the summary of the newest entry and tags its version. A Debian changelog
Debian's tools expect of a changelog line. 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 Decision: `CHANGELOG.md` at the repository's root is the only history kept by hand. An entry is a
columns. `release.py` joins its lines with single spaces into the commit message. `## 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 Consequences: The commit message is one line however the summary is wrapped, so a summary rewrapped
rewrapped later still matches the commit of its release. 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 ## ADR-50: The help is Markdown rendered in the browser, in a panel that pushes the page
@@ -1459,7 +1484,7 @@ Status: Accepted
Context: With `terraform_dir`, the manager built `http://<router_private_ip_addresses.int>:7081`. 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`, 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 Decision: `router_url` is the output `router_web_url` of the platform, which derives the URL from
the same variables that configure the server. the same variables that configure the server.
@@ -1525,7 +1550,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 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. 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 Status: Accepted
@@ -1536,49 +1561,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 own would pin each other's versions, and a change of the server's API would need several
repositories and changelogs. repositories and changelogs.
Decision: One package, `linux-manager`, installs every component, the Manager included. The Decision: One package, `linux-manager`, holds every component, the Manager included. The software
router and the VPN are switched on in the configuration (ADR-57), not by installing packages. The 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 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` `/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 (`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 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-ui.service`. The debconf questions of its first administrator are
`linux-manager/admin_username` and `admin_password`. The server's bootstrap page shows the `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`. with `terraform_dir` and `bind`.
Consequences: The repository holds the Manager's `web/` and `docs/`, and its build runs from the 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 root. A server has the programs of the components it has switched on, and keeps them when a
dependencies installed. 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 Status: Accepted
Context: The server is used without its routing and VPN features, as a directory, PKI and web 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 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 interfaces; remote access works with one or two, its clients reaching the server's networks from
server's own address. 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. Decision: The installable components are the VPN (`vpn.enabled`), the router (`router.enabled`),
With the router off, `site_to_site` must be empty, only `interfaces.external` is used, and it is the name server (`dns.enabled`) and WebDAV (`sites.webdav`), listed with their packages in
also the internal side of the services' `listen` choices; no route, forward rule or `rp_filter` `linuxmanager.COMPONENTS`; all are off by default. The Manager's System tab switches them through
setting is written. With the VPN off, `p2s.enabled`, `openvpn.enabled` and `wireguard.enabled` `PUT /components/<name>`, and shows whether their packages are installed, being installed or failed
must be false, users get no VPN certificate, WireGuard peers and VPN profiles are refused, and the (`GET /components`). While a component is on and any of its packages is missing, or marked as
Manager hides the Remote Access page. With the router off and the VPN on, setup masquerades each installed automatically, which `apt autoremove` would remove, setup starts
ready VPN pool out of the external interface, so the clients reach `local.cidrs` from the `linux-manager-install@<component>`, whose `apt-get install` marks them as installed by hand and
server's address. `linux-manager-setup` writes `/etc/sysctl.d/99-linux-manager.conf` while runs setup again; until then the component's readiness checks are false. Switching a component off
either component is on: forwarding for both, a loose `rp_filter` for the router; it removes the removes no package. The router is offered only while the server has a network interface besides
file while both are off and leaves the running values alone, as Docker also needs forwarding. The the external one, and switching it on takes the internal interface and, in `manual` mode, its
built-in issuing CAs follow their component: `p2s` the VPN and `s2s` the router; they are created address and gateway, as the installer asks them. With the router off, `site_to_site` must be empty,
when their component is first switched on and kept when it is switched off. Switching the VPN on only `interfaces.external` is used, and it is also the internal side of the services' `listen`
issues a certificate to each VPN user that has none. The firewall is written once any core choices; no route, forward rule or `rp_filter` setting is written. With the VPN off,
listener (web, HTTPS, metrics, DNS, sites) or component is configured; the IPsec rules only while `p2s.enabled`, `openvpn.enabled` and `wireguard.enabled` must be false, users get no VPN
site-to-site or IKEv2 is ready. 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 Consequences: A core-only server needs one interface, has none of the components' software, and
run. The readiness checks (`routing_ready`, `s2s_ready`, `p2s_ready`, `wg_ready`, gets its firewall at its first setup run. A component switched on is served once its packages are
`openvpn_ready`) carry the switches, so every consumer of them follows the components. 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 ## ADR-58: Manual tests get numbered dev builds from a signed apt repository in a test project
@@ -1594,14 +1632,16 @@ own (`features.networks`), a WAN and two LANs, and a container `repo` that serve
repository, `resolute main`, built with `apt-ftparchive` and signed by its own key. The networks 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 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. `bin/lm-dev-build.py` builds the newest inside a project; they belong to the project and go with it. `bin/lm-dev-build.py` builds the newest
changelog entry as `<upstream>~dev<N>-<revision>`, `N` counted in `.dev-build.serial`, which a changelog entry as `<upstream>~dev<N>-<revision>`, `N` counted in `LXD_DEV_BUILD_SERIAL` of
release sets to 0, by passing `DEB_VERSION` to the build, which rewrites the version in the image `.lm-dev-config/settings.json`, which a release sets to 0, by passing `DEB_VERSION` to the build,
only, and publishes the build in that repository. `bin/lm-dev-vm.py` gives a VM of the project which rewrites the version in the image only, and publishes the build in that repository.
that repository as its apt source. The automated tests (`lm-dev-run.py`) keep their own project `bin/lm-dev-vm.py` gives a VM of the project that repository as its apt source. The project also
for one run and install from a file. 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, 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. 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 ## ADR-59: A Simple CA root signs the issuing CAs through a sign-ca token of its issuing CA
@@ -1633,3 +1673,126 @@ Consequences: A stolen token signs CAs under the upstream CA only, until it expi
in Simple CA. An issuing CA waits while Simple CA cannot be reached or the token has expired, and 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; 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. 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`. An upgrade makes no choice: a
configuration that names a source keeps it, and one that names none is self-signed. Whether
HTTPS is on is an installer question and is always respected, and so is
`https.disable_auto_redirect`, which keeps Caddy's plain HTTP site of the Manager 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.
+1320
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_UID
ARG HOST_GID ARG HOST_GID
RUN apt-get update \ RUN apt-get -o Acquire::Retries=5 update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ && DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 install -y --no-install-recommends \
build-essential \ build-essential \
dpkg-dev \ dpkg-dev \
debhelper \ debhelper \
lintian \ lintian \
python3 \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
WORKDIR /build WORKDIR /build
COPY debian-package/ src/ COPY debian-package/ src/
COPY docs/ src/docs/ COPY docs/ src/docs/
COPY --from=web /web/dist src/web/dist/ 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 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 cd src && dpkg-buildpackage -us -uc -b
RUN lintian --no-tag-display-limit /build/*.changes || true RUN lintian --no-tag-display-limit /build/*.changes || true
+288 -156
View File
@@ -1,9 +1,11 @@
# linux-manager # linux-manager
A Debian package that configures a Linux host or virtual machine as a server managed by the A Debian package that configures a Linux host or virtual machine as a server managed by the
Ubuntu Linux Manager. Every component is installed; the router (`router.enabled`) and the VPN Ubuntu Linux Manager. The core is always installed; the installable components, the VPN
(`vpn.enabled`) are switched on in the configuration, and the rest is the core. Without the (`vpn.enabled`), the router (`router.enabled`), the name server (`dns.enabled`) and WebDAV
router the server needs one network interface, and the VPN clients reach the server's networks (`sites.webdav`), are switched on the Manager's System tab or in the configuration, and their
software is installed from the Ubuntu archive when they are switched on (see Components). Without
the router the server needs one network interface, and the VPN clients reach the server's networks
through NAT from its address. The package provides: through NAT from its address. The package provides:
- site-to-site IKEv2 IPSec, with the router on, with pre-shared key or certificate authentication (strongSwan swanctl) - site-to-site IKEv2 IPSec, with the router on, with pre-shared key or certificate authentication (strongSwan swanctl)
@@ -39,7 +41,7 @@ service that applies it.
``` ```
/etc/linux-manager/linux-manager.json the configuration /etc/linux-manager/linux-manager.json the configuration
systemctl restart linux-manager-setup apply it linux-manager-config-edit apply apply it
``` ```
If the host runs Docker, the recommended order is Docker first and the package second. The If the host runs Docker, the recommended order is Docker first and the package second. The
@@ -51,7 +53,7 @@ host that already runs Docker, and for installing Docker later, are under [Docke
```sh ```sh
apt-get install linux-manager # answer "none" to the platform question apt-get install linux-manager # answer "none" to the platform question
$EDITOR /etc/linux-manager/linux-manager.json $EDITOR /etc/linux-manager/linux-manager.json
systemctl restart linux-manager-setup linux-manager-config-edit apply
``` ```
Answering `none` to the platform question defers everything: no further questions are Answering `none` to the platform question defers everything: no further questions are
@@ -73,6 +75,7 @@ linux-manager linux-manager/internal_interface string eth1
linux-manager linux-manager/int_addr string 10.1.1.4 linux-manager linux-manager/int_addr string 10.1.1.4
linux-manager linux-manager/int_gateway_ip string 10.1.1.1 linux-manager linux-manager/int_gateway_ip string 10.1.1.1
linux-manager linux-manager/local_fqdn string router.example.com linux-manager linux-manager/local_fqdn string router.example.com
linux-manager linux-manager/https_enabled boolean true
linux-manager linux-manager/local_cidrs string 10.0.0.0/24 linux-manager linux-manager/local_cidrs string 10.0.0.0/24
linux-manager linux-manager/remote_addrs string peer.example.net linux-manager linux-manager/remote_addrs string peer.example.net
linux-manager linux-manager/remote_id string peer.example.net linux-manager linux-manager/remote_id string peer.example.net
@@ -109,8 +112,8 @@ must have the type shown below; an unknown section or setting is an error.
|---|---|---|---|---| |---|---|---|---|---|
| `general` | `platform` | string | `none` | `none`, `generic`, `azure` or `gcp`. `none` defers configuration entirely | | `general` | `platform` | string | `none` | `none`, `generic`, `azure` or `gcp`. `none` defers configuration entirely |
| `general` | `mode` | string | `manual` | How much you supply: `manual`, `interfaces` or `auto` | | `general` | `mode` | string | `manual` | How much you supply: `manual`, `interfaces` or `auto` |
| `router` | `enabled` | boolean | `false` | The router component: routing between the two NICs and site-to-site. Off, the server needs only `interfaces.external`, and `site_to_site` must be empty | | `router` | `enabled` | boolean | `false` | The router component: routing between the two NICs and site-to-site, its packages installed when it is switched on (see Components). Off, the server needs only `interfaces.external`, and `site_to_site` must be empty |
| `vpn` | `enabled` | boolean | `false` | The VPN component: IKEv2, OpenVPN and WireGuard. Off, `p2s.enabled`, `openvpn.enabled` and `wireguard.enabled` must be false. With the router off, the VPN clients reach `local.cidrs` through NAT from the server's address | | `vpn` | `enabled` | boolean | `false` | The VPN component: IKEv2, OpenVPN and WireGuard, its packages installed when it is switched on (see Components). Off, `p2s.enabled`, `openvpn.enabled` and `wireguard.enabled` must be false. With the router off, the VPN clients reach `local.cidrs` through NAT from the server's address |
| `interfaces` | `external` | string | | Name of the NIC facing the untrusted network | | `interfaces` | `external` | string | | Name of the NIC facing the untrusted network |
| `interfaces` | `internal` | string | | Name of the NIC facing the protected network | | `interfaces` | `internal` | string | | Name of the NIC facing the protected network |
| `wan` | `local_fqdn` | string | | This server's name or IP address: its IKE identity in `fqdn` mode, the name resolved in `public_ip` mode, the name of HTTPS, IKEv2 and OpenVPN, and the primary name server of its domains | | `wan` | `local_fqdn` | string | | This server's name or IP address: its IKE identity in `fqdn` mode, the name resolved in `public_ip` mode, the name of HTTPS, IKEv2 and OpenVPN, and the primary name server of its domains |
@@ -133,10 +136,10 @@ must have the type shown below; an unknown section or setting is an error.
| `docker` | `mode` | string | `auto` | `auto` secures Docker when its service is installed, `on` requires it, `off` removes the rules | | `docker` | `mode` | string | `auto` | `auto` secures Docker when its service is installed, `on` requires it, `off` removes the rules |
| `docker` | `exposed_ports` | list | | TCP ports and port ranges (`8000:8100`) reachable from the external interface; at most 15, a range counting as two | | `docker` | `exposed_ports` | list | | TCP ports and port ranges (`8000:8100`) reachable from the external interface; at most 15, a range counting as two |
| `web` | `enabled` | boolean | `true` | The status web service | | `web` | `enabled` | boolean | `true` | The status web service |
| `web` | `listen` | string | `both` | The interfaces the status web service listens on: `internal`, `external` or `both` | | `web` | `listen` | string | `both` | The interfaces the firewall opens `web.port` on: `internal`, `external` or `both` |
| `web` | `port` | integer | `7081` | TCP port of the status web service | | `web` | `port` | integer | `7081` | TCP port of the status web service, served by Caddy over plain HTTP |
| `web` | `database` | string | | A PostgreSQL connection string for the refresh tokens; without it, the `linux-manager` database on this host that the web service creates | | `web` | `database` | string | | A PostgreSQL connection string for the refresh tokens; without it, the `linux-manager` database on this host that the web service creates |
| `web` | `trusted_proxies` | list | the address the call came in on | Addresses whose `X-Forwarded-For` header names the client for the `/auth` rate limit and the Client IP of the status | | `web` | `trusted_proxies` | list | `127.0.0.1`, where Caddy and the Manager call from | Addresses whose `X-Forwarded-For` header names the client for the `/auth` rate limit and the Client IP of the status |
| `web` | `status_content` | string | `basic` | What `/` and `/status` show: `basic`, `standard` or `full` (see Status web service) | | `web` | `status_content` | string | `basic` | What `/` and `/status` show: `basic`, `standard` or `full` (see Status web service) |
| `web` | `shell` | boolean | `false` | `/shell` opens a login shell for a member of `admins` with console login (see The shell) | | `web` | `shell` | boolean | `false` | `/shell` opens a login shell for a member of `admins` with console login (see The shell) |
| `web` | `shell_idle_minutes` | integer | `15` | Minutes without a keystroke after which a shell is closed, 1 to 1440 | | `web` | `shell_idle_minutes` | integer | `15` | Minutes without a keystroke after which a shell is closed, 1 to 1440 |
@@ -144,37 +147,45 @@ must have the type shown below; an unknown section or setting is an error.
| `web` | `shell_auth_timeout` | integer | `15` | Minutes after the last use of a shell in which a new shell opens without signing in again, 0 (always sign in) to 1440 | | `web` | `shell_auth_timeout` | integer | `15` | Minutes after the last use of a shell in which a new shell opens without signing in again, 0 (always sign in) to 1440 |
| `ssh` | `ldap_login` | boolean | `false` | sshd accepts the directory password of the console accounts in the directory (see Console login and SSH) | | `ssh` | `ldap_login` | boolean | `false` | sshd accepts the directory password of the console accounts in the directory (see Console login and SSH) |
| `https` | `enabled` | boolean | `true` | Caddy serves the status web service and the Manager over HTTPS for `wan.local_fqdn` | | `https` | `enabled` | boolean | `true` | Caddy serves the status web service and the Manager over HTTPS for `wan.local_fqdn` |
| `https` | `email` | string | | The e-mail address of the Let's Encrypt account | | `https` | `email` | string | | The e-mail address of the ACME account |
| `https` | `web_port` | integer | `7444` | HTTPS port of the status web service | | `https` | `web_port` | integer | `7444` | HTTPS port of the status web service |
| `https` | `manager_port` | integer | `7443` | HTTPS port of the Manager | | `https` | `manager_port` | integer | `7443` | HTTPS port of the Manager |
| `https` | `acme_staging` | boolean | `false` | Caddy takes its certificates from Let's Encrypt's staging environment alone, whose certificates no browser trusts and whose rate limits are higher, for routers rebuilt often (see HTTPS) | | `https` | `disable_auto_redirect` | boolean | `false` | The Manager answers on its plain HTTP port instead of redirecting there to its HTTPS address while `enabled` is `true`; the status page never redirects |
| `https` | `caddy_source` | string | `ubuntu` | Where Caddy is installed from: `ubuntu`, the Ubuntu archive, or `upstream`, Caddy's own repository (see HTTPS) | | `https` | `certificate` | string | `self-signed` | Where the certificate of `wan.local_fqdn` comes from: `self-signed`, `ca`, `acme` or `external`; empty in a new installation's file, for its first setup to choose `ca` or `self-signed` and write it here (see HTTPS) |
| `https` | `self_signed_days` | integer | `365` | Days the self-signed certificate is valid, 1 to 3650 |
| `https` | `acme_provider` | string | `letsencrypt` | The ACME CA of the server and of the web sites with `tls` `acme`: `letsencrypt`, `zerossl` or `custom` (see HTTPS) |
| `https` | `acme_url` | string | | The `https://` ACME directory URL of `custom` |
| `https` | `acme_eab_key_id` | string | | The EAB key ID of `custom`; the EAB credentials are used once both it and `acme_eab_mac_key` are set |
| `https` | `acme_eab_mac_key` | string | | The EAB MAC key of `custom` |
| `https` | `zerossl_api_key` | string | | The ZeroSSL API key; without it the EAB credentials come from `email` |
| `https` | `acme_staging` | boolean | `false` | With `letsencrypt`, Caddy takes its certificates from Let's Encrypt's staging environment, whose certificates no browser trusts and whose rate limits are higher, for routers rebuilt often (see HTTPS) |
| `oidc` | `enabled` | boolean | `false` | The OpenID Provider at the status web service's HTTPS site, which needs `web.enabled`, `https.enabled` and `wan.local_fqdn` (see OpenID Provider) | | `oidc` | `enabled` | boolean | `false` | The OpenID Provider at the status web service's HTTPS site, which needs `web.enabled`, `https.enabled` and `wan.local_fqdn` (see OpenID Provider) |
| `sites` | `enabled` | boolean | `false` | Caddy serves the web sites (see Web sites) | | `sites` | `enabled` | boolean | `false` | Caddy serves the web sites (see Web sites) |
| `sites` | `upload_max_mb` | integer | `512` | The largest upload of a site's file or zip archive, in MiB, 1 to 10240 | | `sites` | `upload_max_mb` | integer | `512` | The largest upload of a site's file or zip archive, in MiB, 1 to 10240 |
| `sites` | `webdav` | boolean | `false` | WebDAV of the sites' folders, which needs `https.enabled` and `wan.local_fqdn` (see WebDAV) | | `sites` | `webdav` | boolean | `false` | WebDAV of the sites' folders, which needs `https.enabled` and `wan.local_fqdn` (see WebDAV) |
| `sites` | `webdav_port` | integer | `7445` | HTTPS port of WebDAV | | `sites` | `webdav_port` | integer | `7445` | HTTPS port of WebDAV |
| `dns` | `enabled` | boolean | `false` | The primary name server of the server's domains, `wan.local_fqdn`, which must then be a DNS name (see Name server) | | `dns` | `enabled` | boolean | `false` | The primary name server of the server's domains, `wan.local_fqdn`, which must then be a DNS name (see Name server) |
| `dns` | `secondary` | string | | The secondary name server of every domain, a host name other than `wan.local_fqdn`; it may transfer the domains | | `dns` | `secondary` | string | | The optional secondary name server of every domain, a host name other than `wan.local_fqdn`; it may transfer the domains; empty, `wan.local_fqdn` is the only name server |
| `dns` | `listen` | string | `external` | The interfaces the name server answers on: `internal`, `external` or `both` | | `dns` | `listen` | string | `external` | The interfaces the name server answers on: `internal`, `external` or `both` |
| `dns` | `ttl` | integer | `300` | The default TTL of the records, 60 to 86400 seconds: used where neither the record nor its domain has one | | `dns` | `ttl` | integer | `300` | The default TTL of the records, 60 to 86400 seconds: used where neither the record nor its domain has one |
| `pki` | `root` | string | `local` | Where the root CA comes from: `local`, `offline` or `simple-ca`; fixed once the root exists (see Certificates) | | `pki` | `root` | string | `local` | Where the root CA comes from: `local`, `offline` or `simple-ca`; fixed once the root exists (see Certificates) |
| `pki` | `simple_ca_url` | string | | The `https://` URL of the Simple CA service, with `root` `simple-ca` | | `pki` | `simple_ca_url` | string | | The `https://` URL of the Simple CA service, with `root` `simple-ca` |
| `pki` | `root_name` | string | `Linux Manager Root CA` | Common name of the root CA, when the server creates it | | `pki` | `root_name` | string | `Linux Manager Root CA` | Common name of the root CA, when the server creates it; fixed once the root exists |
| `pki` | `root_days` | integer | `7300` | Days the root CA's certificate is valid | | `pki` | `root_days` | integer | `7300` | Days the root CA's certificate is valid |
| `pki` | `ca_days` | integer | `3650` | Days an issuing CA's certificate is valid | | `pki` | `ca_days` | integer | `3650` | Days an issuing CA's certificate is valid |
| `pki` | `key` | string | `rsa-4096` | Key of the root and the issuing CAs: `rsa-2048`, `rsa-3072`, `rsa-4096`, `ec-p256` or `ec-p384` | | `pki` | `key` | string | `rsa-4096` | Key of the root and the issuing CAs: `rsa-2048`, `rsa-3072`, `rsa-4096`, `ec-p256` or `ec-p384` |
| `pki` | `crl_days` | integer | `7` | Days the CRLs of the issuing CAs are valid | | `pki` | `crl_days` | integer | `7` | Days the CRLs of the issuing CAs are valid |
| `pki` | `root_crl_days` | integer | `180` | Days the root CRL is valid, when the server signs it | | `pki` | `root_crl_days` | integer | `180` | Days the root CRL is valid, when the server signs it |
| `pki` | `publish` | list | `http` | Where the CA certificates and CRLs are published: `http`, `http-80`, `https`, `https-default` (see Certificates) | | `pki` | `publish` | list | `http` | Where the CA certificates and CRLs are published: `http`, `http-80`, `https`, `https-default` (see Certificates) |
| `pki` | `p2s_name` | string | `Linux Manager VPN CA` | Common name of the P2S issuing CA | | `pki` | `p2s_name` | string | `Linux Manager VPN CA` | Common name of the P2S issuing CA; fixed once the CA exists, from when the VPN is first on |
| `pki` | `s2s_name` | string | `Linux Manager Site-to-Site CA` | Common name of the site-to-site issuing CA | | `pki` | `s2s_name` | string | `Linux Manager Site-to-Site CA` | Common name of the site-to-site issuing CA; fixed once the CA exists, from when the router is first on |
| `pki` | `servers_name` | string | `Linux Manager Servers CA` | Common name of the Servers Issuing CA; fixed by the first setup, which creates the CA |
| `pki` | `issuing_cas` | object | | The general-purpose issuing CAs, each a name and `{name, templates, acme}` (see Certificates) | | `pki` | `issuing_cas` | object | | The general-purpose issuing CAs, each a name and `{name, templates, acme}` (see Certificates) |
| `pki` | `templates` | object | | Certificate templates, each a name and the options it changes or defines (see Certificates) | | `pki` | `templates` | object | | Certificate templates, each a name and the options it changes or defines (see Certificates) |
| `pki` | `extended_key_usages` | object | | Custom extended key usages templates may give, each a name and its OID in dotted form (see Certificates) | | `pki` | `extended_key_usages` | object | | Custom extended key usages templates may give, each a name and its OID in dotted form (see Certificates) |
| `metrics` | `enabled` | boolean | `true` | The metrics service: collection, history and `/metrics` | | `metrics` | `enabled` | boolean | `true` | The metrics service: collection, history and `/metrics` |
| `metrics` | `listen` | string | `internal` | The interfaces `/metrics` is served on: `internal`, `external` or `both` | | `metrics` | `listen` | string | `internal` | The interfaces the firewall opens `metrics.port` on: `internal`, `external` or `both` |
| `metrics` | `port` | integer | `9464` | TCP port of `/metrics` | | `metrics` | `port` | integer | `9464` | TCP port of `/metrics`, served by Caddy over plain HTTP |
| `metrics` | `https_port` | integer | `9465` | HTTPS port of `/metrics`, served by Caddy while `https.enabled` is true | | `metrics` | `https_port` | integer | `9465` | HTTPS port of `/metrics`, served by Caddy while `https.enabled` is true |
| `metrics` | `service_account` | string | `metrics` | The service account `/metrics` takes, which `linux-manager-setup` adds and keeps | | `metrics` | `service_account` | string | `metrics` | The service account `/metrics` takes, which `linux-manager-setup` adds and keeps |
| `metrics` | `otlp_endpoint` | string | | An OTLP/HTTP URL the metrics are pushed to every minute, for example `https://collector.example.com:4318/v1/metrics` | | `metrics` | `otlp_endpoint` | string | | An OTLP/HTTP URL the metrics are pushed to every minute, for example `https://collector.example.com:4318/v1/metrics` |
@@ -318,7 +329,7 @@ Installing Docker first is the recommended order. After installing the package:
`"docker": { "exposed_ports": ["443"] }`. The default is none: once the rules are applied, `"docker": { "exposed_ports": ["443"] }`. The default is none: once the rules are applied,
every published port that is not listed is unreachable from the external interface, and every published port that is not listed is unreachable from the external interface, and
remains reachable through the IPsec tunnel. remains reachable through the IPsec tunnel.
3. Apply the configuration with `systemctl restart linux-manager-setup`. Docker is running, so 3. Apply the configuration with `linux-manager-config-edit apply`. Docker is running, so
this also restarts `linux-manager-docker`, which installs the rules. this also restarts `linux-manager-docker`, which installs the rules.
4. Check the result: 4. Check the result:
@@ -330,7 +341,7 @@ Installing Docker first is the recommended order. After installing the package:
### When Docker is installed after the package ### When Docker is installed after the package
The Docker rules are not applied when Docker starts for the first time, so run The Docker rules are not applied when Docker starts for the first time, so run
`systemctl restart linux-manager-setup` after installing Docker, then check as above. A reboot or a `linux-manager-config-edit apply` after installing Docker, then check as above. A reboot or a
restart of Docker applies them as well. restart of Docker applies them as well.
The rules sit in their own chain, `LINUX-MANAGER-DOCKER`, entered by one jump at the top of The rules sit in their own chain, `LINUX-MANAGER-DOCKER`, entered by one jump at the top of
@@ -365,6 +376,7 @@ linux-manager-config-edit set web.trusted_proxies 127.0.0.1,10.0.0.4
linux-manager-config-edit set site_to_site.branch.addrs branch.example.net linux-manager-config-edit set site_to_site.branch.addrs branch.example.net
linux-manager-config-edit remove site_to_site.branch linux-manager-config-edit remove site_to_site.branch
linux-manager-config-edit set --restart oidc.enabled true linux-manager-config-edit set --restart oidc.enabled true
linux-manager-config-edit apply
``` ```
`show` prints the file as indented JSON and does not change it. `set` takes a setting as `show` prints the file as indented JSON and does not change it. `set` takes a setting as
@@ -374,15 +386,16 @@ a whole number, `true` or `false`, a list separated by commas (an empty value is
or a string; an unknown setting is refused. `remove site_to_site.NAME` removes a connection. It or a string; an unknown setting is refused. `remove site_to_site.NAME` removes a connection. It
checks the whole configuration as `linux-manager-setup` does, and only then writes the file, checks the whole configuration as `linux-manager-setup` does, and only then writes the file,
indented, with mode 0600, and reminds that `linux-manager-setup` applies it; with `--restart`, `set` indented, with mode 0600, and reminds that `linux-manager-setup` applies it; with `--restart`, `set`
and `remove` restart `linux-manager-setup` and wait until it has applied the change, and exit with and `remove` have `linux-manager-setup` run and wait until it has applied the change, and exit with
status 1 when it fails. The status web service status 1 when it fails. `apply` does the same without a change, as described under
[Applying changes](#applying-changes). The status web service
writes the file the same way, and a lock keeps the two from overwriting each other's change. A writes the file the same way, and a lock keeps the two from overwriting each other's change. A
refused request exits with status 2, any other failure with 1. refused request exits with status 2, any other failure with 1.
## Bash completion ## Bash completion
Bash completes the commands, options and arguments of `linux-manager-user`, `linux-manager-group`, Bash completes the commands, options and arguments of `linux-manager-user`, `linux-manager-group`,
`linux-manager-role`, `linux-manager-token`, `linux-manager-config-edit`, `linux-manager-backup`, `linux-manager-ca`, `linux-manager-caddy` `linux-manager-role`, `linux-manager-token`, `linux-manager-config-edit`, `linux-manager-backup`, `linux-manager-ca`
and `linux-manager-site` with the Tab key. The package installs a file per command in and `linux-manager-site` with the Tab key. The package installs a file per command in
`/usr/share/bash-completion/completions`, which the `bash-completion` package, recommended by `/usr/share/bash-completion/completions`, which the `bash-completion` package, recommended by
`linux-manager`, loads on the first Tab after the command. For root, who can read them, the `linux-manager`, loads on the first Tab after the command. For root, who can read them, the
@@ -396,10 +409,45 @@ linux-manager-config-edit set oidc.<Tab>
linux-manager-user passwd <Tab> linux-manager-user passwd <Tab>
``` ```
## Components
The installable components are switched on the Manager's System tab, through the web service's
`/components`, or in the configuration, and their packages come from the Ubuntu archive, which the
package only suggests:
| Component | Setting | Packages |
|---|---|---|
| VPN | `vpn.enabled` | `strongswan-swanctl`, `charon-systemd`, `libstrongswan-extra-plugins`, `libcharon-extra-plugins`, `openvpn`, `openvpn-auth-ldap`, `wireguard-tools`, `dnsmasq-base` |
| Router | `router.enabled` | `strongswan-swanctl`, `charon-systemd`, `libstrongswan-extra-plugins`, `libcharon-extra-plugins` |
| Name server | `dns.enabled` | `pdns-server`, `pdns-backend-pgsql` |
| WebDAV | `sites.webdav` | `rclone` |
While a component is on and any of its packages is missing, or marked as installed automatically,
which `apt autoremove` would remove, `linux-manager-setup` starts
`linux-manager-install@<component>.service`. It installs them with `apt-get install`, which marks
them as installed by hand, waiting for dpkg's lock, and runs setup again, which serves the
component; until then setup skips it. A failed installation leaves its unit failed; switching the
component on again tries once more. Switching a component off stops it and removes no package.
The router needs a second network interface: the System tab offers it only then, and switching it
on sets `interfaces.internal` and, in `manual` mode, `local.int_addr` and `local.int_gateway_ip`.
```sh
curl -H "Authorization: Bearer $TOKEN" http://127.0.0.1:7081/components
curl -X PUT -H "Authorization: Bearer $TOKEN" -d '{"enabled": true}' http://127.0.0.1:7081/components/vpn
```
`GET /components` gives `components`, each with `name`, `enabled` and `state` (`not installed`,
`installing`, `installed` or `failed`); the router's also has `available`, `interfaces` (the
interfaces besides the external one), `mode`, `internal_interface`, `int_addr` and
`int_gateway_ip`. `PUT /components/<name>` takes `enabled` and, for the router switched on,
`internal_interface`, `int_addr` and `int_gateway_ip`; the configuration's validation refuses a
change it does not allow, such as the VPN off while IKEv2, OpenVPN or WireGuard is on (400), and
the router without a second interface is 409. Both need an administrator's token.
## Applying changes ## Applying changes
```sh ```sh
systemctl restart linux-manager-setup linux-manager-config-edit apply
``` ```
The service also runs at boot. With platform `none` it does nothing and says so. The service also runs at boot. With platform `none` it does nothing and says so.
@@ -411,7 +459,13 @@ access is configured. It then starts `strongswan`, `wg-quick@wg0` and
restarting them only when their inputs changed, and restarting them only when their inputs changed, and
restarts the remote access clients' resolver only when its configuration changed. Turning a restarts the remote access clients' resolver only when its configuration changed. Turning a
feature off in the configuration stops its service and removes its files. Every step is feature off in the configuration stops its service and removes its files. Every step is
idempotent, so restarting with no changes does nothing. idempotent, so a run with no changes does nothing.
`apply` waits for the run and exits with status 1 when it fails. The Manager, the commands of the
package and the installation of a component ask for a run the same way: a run in progress is not
cut short, it runs once more when it ends, however many runs were asked for during it. Without a
run in progress, `linux-manager-setup` is restarted. A plain `systemctl restart
linux-manager-setup` stops a run in progress, which then leaves its work to the next run.
To regenerate the configuration files and PKI without starting, stopping or reloading To regenerate the configuration files and PKI without starting, stopping or reloading
anything: anything:
@@ -423,7 +477,7 @@ anything:
This does still write to the system: it renders into `/etc/swanctl/`, This does still write to the system: it renders into `/etc/swanctl/`,
`/etc/systemd/resolved.conf.d/` and `/etc/wireguard/`, creates what the PKI is missing and `/etc/systemd/resolved.conf.d/` and `/etc/wireguard/`, creates what the PKI is missing and
adds the root CA to the host trust store. What it leaves alone is routes, firewall rules and adds the root CA to the host trust store. What it leaves alone is routes, firewall rules and
services - that is what `systemctl restart linux-manager-setup` adds. services - that is what `linux-manager-config-edit apply` adds.
## Certificates ## Certificates
@@ -460,11 +514,14 @@ The root signs the issuing CAs only (path length 1), and the issuing CAs sign th
present, and the users' certificates. IKEv2 and OpenVPN accept client certificates of present, and the users' certificates. IKEv2 and OpenVPN accept client certificates of
this CA only. this CA only.
- `s2s`, named `pki.s2s_name`, signs the server's site-to-site certificate and the certificates - `s2s`, named `pki.s2s_name`, signs the server's site-to-site certificate and the certificates
of its peers. of its peers, with the template `mtls`.
- The general-purpose CAs of `pki.issuing_cas`, each a name and `{"name": common name, - `servers`, the Servers Issuing CA, named `pki.servers_name`, signs mTLS certificates, with both the
"templates": [...], "acme": false}`. The name starts with a lowercase letter, has at most 31 server and the client purposes, and the server's HTTPS certificate while `https.certificate`
lowercase letters, digits and hyphens, and is not `root`, `p2s` or `s2s`; `templates` are the is `ca`.
templates the CA issues. - The custom CAs of `pki.issuing_cas`, each a name and `{"name": common name,
"templates": [...], "acme": false}`, such as one for code signing. The name starts with a
lowercase letter, has at most 31 lowercase letters, digits and hyphens, and is not `root`,
`upstream`, `p2s`, `s2s` or `servers`; `templates` are the templates the CA issues.
Once a platform is chosen, `linux-manager-setup` creates what is missing: the root, as `pki.root` Once a platform is chosen, `linux-manager-setup` creates what is missing: the root, as `pki.root`
says (see The root), each issuing CA, the server's certificates once `wan.local_fqdn` is set, and says (see The root), each issuing CA, the server's certificates once `wan.local_fqdn` is set, and
@@ -509,9 +566,9 @@ The built-in templates:
|---|---|---|---|---|---| |---|---|---|---|---|---|
| `vpn-server` | digital signature, key encipherment | server auth, IKE intermediate | `dns` | `dns`, `ip` | `p2s`, for the server only | | `vpn-server` | digital signature, key encipherment | server auth, IKE intermediate | `dns` | `dns`, `ip` | `p2s`, for the server only |
| `vpn-user` | digital signature | client auth | `name` | `dns`, `email` | `p2s`, for the users only | | `vpn-user` | digital signature | client auth | `name` | `dns`, `email` | `p2s`, for the users only |
| `site-to-site` | digital signature, key encipherment | server auth, client auth | `dns` | `dns`, `ip` | `s2s` | | `mtls` | digital signature, key encipherment | server auth, client auth | `dns` | `dns`, `ip` | `s2s`, `servers` |
| `server` | digital signature, key encipherment | server auth | `dns` | `dns`, `ip` | general-purpose CAs | | `server` | digital signature, key encipherment | server auth | `dns` | `dns`, `ip` | custom CAs |
| `client` | digital signature | client auth | `name` | `dns`, `email` | general-purpose CAs | | `client` | digital signature | client auth | `name` | `dns`, `email` | custom CAs |
`pki.templates` changes options of the built-in templates, which cannot be removed, and adds `pki.templates` changes options of the built-in templates, which cannot be removed, and adds
templates of its own, named like the issuing CAs: templates of its own, named like the issuing CAs:
@@ -610,6 +667,9 @@ openssl x509 -req -in p2s.csr -CA root-cert.pem -CAkey root-key.pem -CAcreateser
linux-manager-ca ca import p2s p2s.pem linux-manager-ca ca import p2s p2s.pem
``` ```
The imported certificate must keep the common name of the CSR, as setup refuses a CA whose name
differs from its configured one.
The server cannot sign the root CRL. Sign it offline and upload it before the current one The server cannot sign the root CRL. Sign it offline and upload it before the current one
expires, as OpenVPN refuses every client while a CRL of a client's chain has expired: expires, as OpenVPN refuses every client while a CRL of a client's chain has expired:
@@ -987,9 +1047,10 @@ modules shipped with the package; the configuration file accepts any module inst
## Status web service ## Status web service
The `linux-manager-web` service shows the state of the server on the addresses of the interfaces The `linux-manager-web` service shows the state of the server. It listens on `127.0.0.1:7091`
`web.listen` names, the internal, the external or both (the default), and on `127.0.0.1`, where only, behind Caddy, which serves it over plain HTTP on `web.port` (7081 by default), open in the
Caddy calls it (see HTTPS), with `web.port` (7081 by default). Its pages `/` and `/status` need no authentication and show no firewall on the interfaces `web.listen` names, the internal, the external or both (the default),
and over HTTPS (see HTTPS). Its pages `/` and `/status` need no authentication and show no
configuration: no key, identity, subnet, or address but the client's. They show as much as configuration: no key, identity, subnet, or address but the client's. They show as much as
`web.status_content` says, read at each request: `web.status_content` says, read at each request:
@@ -1000,8 +1061,8 @@ configuration: no key, identity, subnet, or address but the client's. They show
| `full` | Also each service and its state, Docker, how many site-to-site connections are set up and how many of them are established (`site_to_site`: `connections` and `established`, `null` when swanctl cannot be asked), IKEv2, OpenVPN and WireGuard | | `full` | Also each service and its state, Docker, how many site-to-site connections are set up and how many of them are established (`site_to_site`: `connections` and `established`, `null` when swanctl cannot be asked), IKEv2, OpenVPN and WireGuard |
The Client IP is the address the request came from: the last entry of `X-Forwarded-For` for a The Client IP is the address the request came from: the last entry of `X-Forwarded-For` for a
request from one of `web.trusted_proxies`, by default the address the request came in on, so request from one of `web.trusted_proxies`, by default `127.0.0.1`, where Caddy and the
behind Caddy or a Ubuntu Linux Manager on the server it is the browser's. `/status` names the content in Ubuntu Linux Manager on the server call from, so it is the browser's. `/status` names the content in
`content` and the Client IP in `client_ip`; `/` keeps the time and the link to `/status`. `content` and the Client IP in `client_ip`; `/` keeps the time and the link to `/status`.
The service first makes its signing key, the OpenID Provider's key and the refresh tokens' The service first makes its signing key, the OpenID Provider's key and the refresh tokens'
@@ -1112,8 +1173,8 @@ directory). A passkey that does not sign, is not the user's, or of a disabled, l
account gets 401 too (see Passkeys). `/auth`, `/auth/passkey/complete` and `/auth/refresh` take account gets 401 too (see Passkeys). `/auth`, `/auth/passkey/complete` and `/auth/refresh` take
at most 10 calls a minute from one client address, at most 10 calls a minute from one client address,
and answer 429 with `Retry-After` beyond that; for a call from one of `web.trusted_proxies`, by and answer 429 with `Retry-After` beyond that; for a call from one of `web.trusted_proxies`, by
default the address the call came in on, the client address is the last entry of default `127.0.0.1`, where Caddy and the Manager call from, the client address is the last entry
`X-Forwarded-For`. of `X-Forwarded-For`.
Refresh tokens are kept, as their SHA-256, in PostgreSQL: by default in the database and role Refresh tokens are kept, as their SHA-256, in PostgreSQL: by default in the database and role
`linux-manager` on the server, which the web service creates on its first run with a password in `linux-manager` on the server, which the web service creates on its first run with a password in
@@ -1455,17 +1516,23 @@ A change is made, checked and applied as for `/site-to-site`.
A change is made, checked and applied as for `/site-to-site`. A change is made, checked and applied as for `/site-to-site`.
### The /https/settings API ### The /https API
`/https/settings` shows the settings of HTTPS and changes the CA of Caddy's certificates, with the `/https` shows the settings of HTTPS and the server's certificate, changes where the certificate
same token as `/users`. comes from and the ACME CA, and imports a certificate of another CA, with the same token as
`/users`. The secrets `acme_eab_mac_key` and `zerossl_api_key` are answered as `<name>_set`.
| Request | Body | Answer | | Request | Body | Answer |
| --- | --- | --- | | --- | --- | --- |
| `GET /https/settings` | | `{"settings"}`: the `https` section | | `GET /https/settings` | | `{"settings", "certificate"}`: the `https` section, and `{"source", "served", "subject", "issuer", "sans", "expires", "pending"}`, `served` being the source of the certificate Caddy serves, `self-signed` while the chosen one is not available, and `pending` whether a CSR waits |
| `PUT /https/settings` | `{"acme_staging"}`; any other setting of the `https` section is 400, as it is changed on the server with `linux-manager-config-edit` | `{"settings"}` | | `PUT /https/settings` | any of `certificate`, `self_signed_days`, `acme_provider`, `acme_url`, `acme_eab_key_id`, `acme_eab_mac_key`, `zerossl_api_key`, `acme_staging`; any other setting is 400, as it is changed on the server with `linux-manager-config-edit` | `{"settings"}` |
| `POST /https/csr` | | `{"csr"}`: a new CSR for `wan.local_fqdn`, replacing a pending one |
| `PUT /https/certificate` | `{"certificate"}`, PEM, the certificate signed for the CSR followed by its chain | `{"subject", "issuer", "expires"}` |
| `PUT /https/pfx` | `{"pfx", "password"}`, the PKCS#12 file in base64 | `{"subject", "issuer", "expires"}` |
A change is made, checked and applied as for `/site-to-site`. A change of the settings is made, checked and applied as for `/site-to-site`; an import restarts
`linux-manager-setup` too. An import needs `https.certificate` `external`; a refused one is 400,
and one without a pending CSR 409.
### The /remote-access API ### The /remote-access API
@@ -1508,7 +1575,7 @@ The answer of `GET /ca` holds:
- **`settings`:** the `pki` section. - **`settings`:** the `pki` section.
- **`templates`:** every template, the built-in ones included, with all its options. - **`templates`:** every template, the built-in ones included, with all its options.
- **`extended_key_usages`:** every extended key usage templates may give, name -> `{"oid", "builtin"}`. - **`extended_key_usages`:** every extended key usage templates may give, name -> `{"oid", "builtin"}`.
- **`status`:** `root` (`source`, `pki.root`, `state`, `active` or `pending`, `subject`, `expires`, `crl_next_update`, `crl_source`, `signed`, `uploaded` or `fetched`, `simple_ca_url`, `upstream`, the Simple CA issuing CA `{"name", "subject", "expires", "crl_next_update"}` or null, and `token_expires`), `authorities`, one per issuing CA (`name`, `common_name`, `state`: `active`, `pending` or `missing`, `builtin`, `templates`, `acme`, `subject`, `expires`, `key`, `crl_next_update`, `acme_url`), `retired` and `warnings`. - **`status`:** `root` (`source`, `pki.root`, `state`, `active` or `pending`, `subject`, `expires`, `crl_next_update`, `crl_source`, `signed`, `uploaded` or `fetched`, `simple_ca_url`, `upstream`, the Simple CA issuing CA `{"name", "subject", "expires", "crl_next_update"}` or null, and `token_expires`), `authorities`, one per issuing CA (`name`, `common_name`, `state`: `active`, `pending`, `off`, a built-in CA whose component is off, or `missing`, `builtin`, `component`, the section that switches a built-in CA, `templates`, `acme`, `subject`, `expires`, `key`, `crl_next_update`, `acme_url`), `retired` and `warnings`.
- **`certificates`:** the certificates issued, newest first, each `{"serial", "ca", "kind", "template", "subject", "sans", "created", "expires", "revoked", "reason", "state"}`; `kind` is `ca`, `router`, `user` or `external`, and `state` `valid`, `expired` or `revoked`. - **`certificates`:** the certificates issued, newest first, each `{"serial", "ca", "kind", "template", "subject", "sans", "created", "expires", "revoked", "reason", "state"}`; `kind` is `ca`, `router`, `user` or `external`, and `state` `valid`, `expired` or `revoked`.
A change of the settings is made, checked and applied as for `/site-to-site`; an imported root or A change of the settings is made, checked and applied as for `/site-to-site`; an imported root or
@@ -1529,72 +1596,105 @@ and the facts for `/config` from `/run/linux-manager/web.json` (readable by root
## HTTPS ## HTTPS
Caddy serves the status web service on `https.web_port` (7444 by Caddy, a dependency of the package, serves every HTTP and HTTPS port of the server's services; the
default), the Manager on `https.manager_port` (7443), and services listen on `127.0.0.1` only. Over plain HTTP it serves the status web service on
while metrics are enabled the metrics service on `metrics.https_port` (9465), all for `wan.local_fqdn`, while `https.enabled` is `true` and `wan.local_fqdn` is set. It obtains `web.port` (7081 by default), the Manager on its `port` (7080), and while metrics are enabled the
and renews the certificate from Let's Encrypt with the HTTP challenge, so `wan.local_fqdn` must metrics service on `metrics.port` (9464). While `https.enabled` is `true` and `wan.local_fqdn` is
resolve to the server's public address and port 80 must be reachable from the internet; the set, it also serves the status web service on `https.web_port` (7444), the Manager on
certificate and the ACME account are kept in `/var/lib/caddy`. Port 80 answers the challenge only; `https.manager_port` (7443), and while metrics are enabled the metrics service on
it does not redirect to HTTPS. Caddy's default CAs are Let's Encrypt and ZeroSSL, which it takes `metrics.https_port` (9465), all for `wan.local_fqdn`.
when Let's Encrypt refuses, such as for its rate limit of 5 certificates a week for the same name.
While `https.acme_staging` is `true`, Caddy's only CA is Let's Encrypt's staging environment, for The installer asks whether to serve over HTTPS (`https_enabled`) and, with HTTPS, whether to keep
routers that are rebuilt often. Its rate limits are far higher, but no browser or client trusts the Manager on plain HTTP (`https_disable_auto_redirect`). While HTTPS is on, Caddy answers the
its certificates, so they are for tests only. The setting applies to every certificate Caddy Manager's plain HTTP port with a redirect (308) to the same path at
obtains from an ACME CA, those of the web sites with `tls` `acme` included. `https://<wan.local_fqdn>:<https.manager_port>`, unless `https.disable_auto_redirect` is `true`.
The status page never redirects and stays available over plain HTTP on `web.port` whether HTTPS
is on or not.
### The server's certificate
`https.certificate` says where the certificate of `wan.local_fqdn` comes from; it is `self-signed`
when the file does not set it, and ACME only when it is set to `acme`. 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 root CA and the Servers Issuing CA are available, as with a root the server creates,
else `self-signed`, as with an offline root, a Simple CA root that has not signed yet, or a
directory that cannot be reached. A source chosen later, in the Manager or the file, stays.
| Source | The certificate |
|---|---|
| `acme` | obtained and renewed by Caddy from the ACME CA of `https.acme_provider`, with the HTTP challenge, so `wan.local_fqdn` resolves to the server's public address and port 80 is reachable from the internet; kept in `/var/lib/caddy` |
| `self-signed` (the default) | made by the server, valid for `https.self_signed_days`, and made again when a third of it is left or `wan.local_fqdn` changes |
| `ca` | issued and renewed by the Servers Issuing CA, `servers`, of the server's PKI (see Certificates), with the template `mtls` |
| `external` | another CA's certificate, imported, from a CSR the server makes or as a PFX file |
A certificate other than ACME's is kept in the server's directory, `cn=https,ou=pki` (a router
certificate of `servers` for `ca`), and written for Caddy to `/etc/caddy/linux-manager-https/`.
While the chosen certificate is not available, such as before an import or while `servers` waits for
an offline root, the server serves a self-signed one and warns. Port 80 is opened for the HTTP
challenge only with `acme`.
```sh ```sh
linux-manager-config-edit set --restart https.acme_staging true linux-manager-config-edit set --restart https.certificate external
linux-manager-ca https csr > router.csr # signed by the other CA into router.pem, with its chain
linux-manager-ca https import router.pem
linux-manager-ca https import-pfx router.pfx # or a PFX file; its password on standard input
linux-manager-ca https status
``` ```
The Manager switches it on the Overview, and `PUT /https/settings` changes it (see The An imported certificate must be valid and name `wan.local_fqdn`, directly or with a wildcard, and
/https/settings API). the CSR's key or the PFX's key must be its key. The server warns 30 days before it expires; a new
CSR or PFX replaces it.
### The ACME CA
`https.acme_provider` is the ACME CA of the server's certificate with `acme`, and of the web sites
with `tls` `acme` whatever the source:
| Provider | The CA |
|---|---|
| `letsencrypt` (the default) | Let's Encrypt; with `https.acme_staging` `true`, its staging environment, whose rate limits are far higher but whose certificates no browser trusts, for routers rebuilt often and tests |
| `zerossl` | ZeroSSL; its EAB credentials come from `https.zerossl_api_key` when it is set, else from the e-mail address `https.email` |
| `custom` | the ACME directory `https.acme_url`, such as HashiCorp Vault, a Caddy ACME server or Simple CA, with the EAB credentials `https.acme_eab_key_id` and `https.acme_eab_mac_key` when it needs them |
The CA that issued the HTTPS certificate of a custom ACME directory is installed in the system's
trust store, which Caddy uses. `https.email` is the e-mail address of the ACME account.
The Manager changes the source and the provider on the Server tab of the Certificates page, whose
HTTPS certificate row makes the CSR and imports the certificates, and `/https` changes them
(see The /https API).
### Caddy's configuration
`linux-manager-setup` writes Caddy's configuration to `/etc/caddy/linux-manager.Caddyfile` (root, group `linux-manager-setup` writes Caddy's configuration to `/etc/caddy/linux-manager.Caddyfile` (root, group
`caddy`, the group Caddy runs as, mode 0640), which the `caddy`, the group Caddy runs as, mode 0640), which the package's drop-in
package's drop-in `/usr/lib/systemd/system/caddy.service.d/linux-manager.conf` makes `caddy.service` `/usr/lib/systemd/system/caddy.service.d/linux-manager.conf` makes `caddy.service` read;
read; `caddy.service` does not start before the file exists, and `/etc/caddy/Caddyfile` is not `caddy.service` does not start before the file exists, and `/etc/caddy/Caddyfile` is not used.
used. Setup starts Caddy, reloads it when the file changes, and stops it and removes the file when Setup starts Caddy once the server is configured (`general.platform` other than `none`) and
HTTPS is off and no web site is served (see Web sites). In the firewall it opens port 80 on the external interface and the HTTPS ports on the reloads it when the file changes.
internal and the external interface, and ports 80 and 443 on both when `pki.publish` has `http-80`
and `https-default`, on which Caddy serves only the CA files (see Certificates). Caddy calls both services on `127.0.0.1`, where they listen Caddy listens on every address, and the firewall decides who reaches it: `web.port` is open on the
whatever `web.listen` and the manager's `listen` say, and passes the client's address in interfaces `web.listen` names, the Manager's port on those of its `listen`, and `metrics.port` on
`X-Forwarded-For`, which the manager trusts from `127.0.0.1` and the web service by default, as those of `metrics.listen`, where `internal` is the external interface without the router. Port
the address the call came in on; a `web.trusted_proxies` that is set must list `127.0.0.1`. The plain HTTP ports stay as 80 is open on the external interface while ACME needs it, the HTTPS ports on the internal and the
`web.listen` and the manager's `listen` set them. `docker.exposed_ports` may not take port 80 or external interface, and ports 80 and 443 on both when `pki.publish` has `http-80` and
the HTTPS ports while `https.enabled` is `true`. `https-default`, on which Caddy serves only the CA files (see Certificates).
Caddy calls the services on `127.0.0.1`: the status web service on port 7091, the Manager on
7090, the metrics service on 9474 and WebDAV on 7446, and passes the client's address in
`X-Forwarded-For`, which every service trusts from `127.0.0.1`; a `web.trusted_proxies` that is
set must list `127.0.0.1`. The OpenID Provider answers only calls of Caddy's HTTPS site, which
carry `X-Forwarded-Proto: https`. Caddy removes the `Server` header of its own answers and of the
services', so no answer names the software or its version. `docker.exposed_ports` and the web
sites may not take Caddy's ports or the loopback ports.
```bash ```bash
curl https://router.example.com:7444/status curl https://router.example.com:7444/status
``` ```
### Installing Caddy ### Caddy
The package does not depend on Caddy; `linux-manager-setup` has it installed, while HTTPS is on, Caddy is a dependency of the package, the `caddy` package of the Ubuntu archive, installed with
from the source `https.caddy_source` names: `linux-manager` and kept up to date with the system's packages.
- `ubuntu`, the default: the `caddy` package of the Ubuntu archive.
- `upstream`: Caddy's own repository, `https://dl.cloudsmith.io/public/caddy/stable/deb/debian`,
whose source the package writes to `/etc/apt/sources.list.d/caddy-stable.sources` with its key,
downloaded over HTTPS, in `/etc/apt/keyrings/caddy-stable.asc`.
apt runs in `linux-manager-caddy.service`, which waits for dpkg's lock, so setup run by a package
installation does not wait for itself; the unit runs `linux-manager-caddy apply` and then setup
again, which serves with the new Caddy. `linux-manager-caddy status` shows the configured source, the
source in effect and the versions.
A router installed with `ubuntu` is switched to upstream's Caddy with:
```sh
linux-manager-caddy use-upstream
```
It sets `https.caddy_source` to `upstream`, configures the repository and replaces Caddy, printing
each step. Upstream versions sort above Ubuntu's, so once the repository is configured apt keeps
upstream's Caddy, and `ubuntu` has no effect; setup says so. Going back is a downgrade nothing
does on its own: remove the source and the key, run `apt-get update`, and install Ubuntu's version
with `apt-get install --allow-downgrades caddy=<version>`, the version `apt-cache policy caddy`
lists for the archive.
## OpenID Provider ## OpenID Provider
@@ -1788,7 +1888,7 @@ Ubuntu Linux Manager, each change applied by restarting `linux-manager-setup`. A
| `hosts` | The host names (or IP addresses) Caddy answers on the port, the names TLS clients send as SNI; none answers any name | | `hosts` | The host names (or IP addresses) Caddy answers on the port, the names TLS clients send as SNI; none answers any name |
| `port` | The TCP port, 443 by default | | `port` | The TCP port, 443 by default |
| `listen` | `internal`, `external` (the default) or `both`: the interfaces whose firewall opens the port | | `listen` | `internal`, `external` (the default) or `both`: the interfaces whose firewall opens the port |
| `tls` | `none` (plain HTTP), `acme` (Let's Encrypt, the default), `ca` (certificates of an issuing CA of `pki.issuing_cas`, named by `ca`) or `file` (`certificate` and `private_key`, PEM) | | `tls` | `none` (plain HTTP), `acme` (the ACME CA of `https.acme_provider`, the default), `ca` (certificates of an issuing CA of `pki.issuing_cas`, named by `ca`) or `file` (`certificate` and `private_key`, PEM) |
| `index_file` | The file served for a folder, `index.html` by default | | `index_file` | The file served for a folder, `index.html` by default |
| `spa` | Whether a path without a file is served the site's `index_file`, for single-page applications | | `spa` | Whether a path without a file is served the site's `index_file`, for single-page applications |
| `editors` | The group whose members may change the site's files besides the admins | | `editors` | The group whose members may change the site's files besides the admins |
@@ -1796,7 +1896,8 @@ Ubuntu Linux Manager, each change applied by restarting `linux-manager-setup`. A
| `dns_address` | With `dns` `router`, the server's address in the records: `public` (the default, `wan.public_address`), `internal` or `external` | | `dns_address` | With `dns` `router`, the server's address in the records: `public` (the default, `wan.public_address`), `internal` or `external` |
A site may not take a port of the server's own services (SSH, `web.port`, the HTTPS ports, the A site may not take a port of the server's own services (SSH, `web.port`, the HTTPS ports, the
metrics ports, the Manager's, `sites.webdav_port`, 7446, 53, the bootstrap ports, a TCP metrics ports, the Manager's, `sites.webdav_port`, the loopback ports 7090, 7091, 9474 and 7446, 53,
the bootstrap ports, a TCP
`openvpn.port` and `docker.exposed_ports`). It may use `wan.local_fqdn` as a host name, on a port `openvpn.port` and `docker.exposed_ports`). It may use `wan.local_fqdn` as a host name, on a port
of its own, such as 443, which the server's services leave free; its record is then kept where the of its own, such as 443, which the server's services leave free; its record is then kept where the
domain of `wan.local_fqdn` is, so `dns` `router` takes neither it, nor wildcards or addresses, and domain of `wan.local_fqdn` is, so `dns` `router` takes neither it, nor wildcards or addresses, and
@@ -1806,8 +1907,8 @@ names of their own, the same `listen` and the same kind of TLS (plain HTTP or HT
which setup opens on the external interface. The certificate of `file` must be the key's and name which setup opens on the external interface. The certificate of `file` must be the key's and name
the hosts; it is written to `/etc/caddy/linux-manager-sites/<name>` (root, group `caddy`, 0640). An the hosts; it is written to `/etc/caddy/linux-manager-sites/<name>` (root, group `caddy`, 0640). An
issuing CA of `ca` is given to Caddy as the ACME servers' CAs are, in `/etc/caddy/linux-manager-pki`; issuing CA of `ca` is given to Caddy as the ACME servers' CAs are, in `/etc/caddy/linux-manager-pki`;
its certificates are trusted by clients that trust the server's root. Caddy runs while HTTPS is its certificates are trusted by clients that trust the server's root. While the sites cannot be
ready or a site is served; while the sites cannot be read, setup leaves the Caddyfile as it is. read, setup leaves the Caddyfile as it is.
```sh ```sh
linux-manager-config-edit set --restart sites.enabled true linux-manager-config-edit set --restart sites.enabled true
@@ -1839,8 +1940,8 @@ interfaces. A user signs in with the name and password of the server's directory
TOTP code for an enrolled user; an admin sees a folder for every site, any other user the folders of TOTP code for an enrolled user; an admin sees a folder for every site, any other user the folders of
the sites whose `editors` group the user is a member of, and no folder means no access. rclone writes the sites whose `editors` group the user is a member of, and no folder means no access. rclone writes
an upload to its cache in `/var/cache/linux-manager-webdav` and to the site's folder a few seconds an upload to its cache in `/var/cache/linux-manager-webdav` and to the site's folder a few seconds
later. rclone is installed from the Ubuntu archive by `linux-manager-install@webdav.service` when it is later. WebDAV is a component (see Components): rclone is installed from the Ubuntu archive by
missing. `linux-manager-install@webdav.service` while `sites.webdav` is true and rclone is missing.
```sh ```sh
linux-manager-config-edit set --restart sites.webdav true linux-manager-config-edit set --restart sites.webdav true
@@ -1853,9 +1954,10 @@ primary name server of the server's domains, on port 53 of the addresses of `dns
(`internal`, `external`, the default, or `both`), which the firewall opens for UDP and TCP. The (`internal`, `external`, the default, or `both`), which the firewall opens for UDP and TCP. The
domains and records are in the database `linux-manager-dns` (password in `/etc/linux-manager/dns-database.secret`), domains and records are in the database `linux-manager-dns` (password in `/etc/linux-manager/dns-database.secret`),
read by PowerDNS's gpgsql backend; setup writes the settings read by PowerDNS's gpgsql backend; setup writes the settings
`/etc/powerdns/pdns.d/linux-manager.conf` (root, group `pdns`, 0640) and installs `pdns-server` and `/etc/powerdns/pdns.d/linux-manager.conf` (root, group `pdns`, 0640). The name server is a component
`pdns-backend-pgsql` from the Ubuntu archive with `linux-manager-install@dns.service` when they are (see Components): `pdns-server` and `pdns-backend-pgsql` are installed from the Ubuntu archive with
missing, without the recommended bind backend. `linux-manager-install@dns.service` while `dns.enabled` is true and they are missing, without the
recommended bind backend.
| Setting | Meaning | | Setting | Meaning |
| --- | --- | | --- | --- |
@@ -1890,8 +1992,8 @@ through `/dns`; the SOA's serial grows only when the records change. While IKEv2
WireGuard is enabled, dnsmasq answers their clients on port 53 of the addresses of WireGuard is enabled, dnsmasq answers their clients on port 53 of the addresses of
`p2s.dns_listen`, by default the internal address, so `dns.listen` must not share an interface with `p2s.dns_listen`, by default the internal address, so `dns.listen` must not share an interface with
it. The parent zone of each domain must delegate it to `wan.local_fqdn` and `dns.secondary`, with it. The parent zone of each domain must delegate it to `wan.local_fqdn` and `dns.secondary`, with
glue records for those of them inside the domain. While `dns.secondary` is not set, the domains have glue records for those of them inside the domain. The secondary is optional: while `dns.secondary`
`wan.local_fqdn` as their only name server, and setup warns. is not set, the domains have `wan.local_fqdn` as their only name server.
```sh ```sh
linux-manager-config-edit set dns.secondary ns2.provider.net linux-manager-config-edit set dns.secondary ns2.provider.net
@@ -2052,7 +2154,7 @@ sudo apt-get install rclone
sudo rclone config --config /etc/linux-manager/rclone.conf sudo rclone config --config /etc/linux-manager/rclone.conf
sudo chmod 0600 /etc/linux-manager/rclone.conf sudo chmod 0600 /etc/linux-manager/rclone.conf
sudo linux-manager-config-edit set backup.rclone_remote azure:backups/router sudo linux-manager-config-edit set backup.rclone_remote azure:backups/router
sudo systemctl restart linux-manager-setup sudo linux-manager-config-edit apply
``` ```
The two modes: The two modes:
@@ -2112,8 +2214,8 @@ only page of a user who is not a member of `admins`. Administrators switch betwe
the Overview, Metrics, Logs, Backup and System tabs), Identities (`/user-manager`: the Users, Groups and Service the Overview, Metrics, Logs, Backup and System tabs), Identities (`/user-manager`: the Users, Groups and Service
Accounts tabs), Connectivity (`/site-to-site-manager`: the Status, Network and Connections tabs), Remote Accounts tabs), Connectivity (`/site-to-site-manager`: the Status, Network and Connections tabs), Remote
Access (`/remote-access-manager`: the IKEv2, OpenVPN and WireGuard tabs), Certificates Access (`/remote-access-manager`: the IKEv2, OpenVPN and WireGuard tabs), Certificates
(`/ca-manager`), Web Sites (`/sites-manager`: the Sites, Files and DNS tabs) and (`/ca-manager`), Web Sites (`/sites-manager`: the Sites and Files tabs), DNS (`/dns-manager`, while the name
Docker (`/docker-manager`) with the page menu at the server is on) and Docker (`/docker-manager`) with the page menu at the
right end of the header, a button naming the page shown. The button with the signed-in user's right end of the header, a button naming the page shown. The button with the signed-in user's
name, left of Sign out, opens the account page, and the terminal icon left of it the Shell name, left of Sign out, opens the account page, and the terminal icon left of it the Shell
(`/shell`); pressed on its page, each returns to the page it was opened from. (`/shell`); pressed on its page, each returns to the page it was opened from.
@@ -2153,21 +2255,21 @@ name, left of Sign out, opens the account page, and the terminal icon left of it
Level 3. They sign in to the Manager, and open a shell on the Shell page in place of the password Level 3. They sign in to the Manager, and open a shell on the Shell page in place of the password
and code. and code.
- **Certificates** (`/ca-manager`, in the page menu of administrators): the server's two-level CA, from its `/ca`, in tabs: - **Certificates** (`/ca-manager`, in the page menu of administrators): the server's HTTPS and its two-level CA, from its `/ca`, in tabs:
- **Server:** the first tab, from the server's `/config` and `/https/settings`, shown also while the PKI cannot be read: whether HTTPS is on and for which name, with a chip while the certificate has another source than ACME and a settings button for the certificate's source, the ACME CA with a chip while Caddy takes Let's Encrypt's staging CA and a settings button for it (both through the server's `/https/settings`), the server's certificate when it is not ACME's, with Generate CSR, Import certificate and Import PFX for one of another CA, and Caddy, which serves every HTTP and HTTPS port: its version and the state of `caddy.service`.
- **Root:** the root CA's source, state, subject, expiry and CRL, with Simple CA its issuing CA that signs the server's and the expiry of the token, with Download root CA, the root's certificate alone; Import root certificate while an offline root waits for it, Upload CRL for a CRL of the offline root, and Enter setup code for a new Simple CA token; the general information: where certificates and CRLs are published, the CA key type, the lifetimes, and the CRL validity; the certificates of the issuing CAs, each active one with a download icon for its CA bundle, and the retired ones. - **Root:** the root CA's source, state, subject, expiry and CRL, with Simple CA its issuing CA that signs the server's and the expiry of the token, with Download root CA, the root's certificate alone; Import root certificate while an offline root waits for it, Upload CRL for a CRL of the offline root, and Enter setup code for a new Simple CA token; the general information: where certificates and CRLs are published, the CA key type, the lifetimes, and the CRL validity; the certificates of the issuing CAs, each active one with a download icon for its CA bundle, and the retired ones.
- **Templates:** the certificate templates with their key, lifetime, subject, usages, alternative names, certificate policies and the CAs that issue them; Add template, Edit on each, Remove on one of the server's own and Reset on a changed built-in one, which brings back its defaults. A template's extended key usages are chosen from those of the next tab, and its certificate policies are OIDs typed in. - **Templates:** the certificate templates with their key, lifetime, subject, usages, alternative names, certificate policies and the CAs that issue them; Add template, Edit on each, Remove on one of the server's own and Reset on a changed built-in one, which brings back its defaults. A template's extended key usages are chosen from those of the next tab, and its certificate policies are OIDs typed in.
- **Extended key usages:** the usages templates may give, with their OIDs and the templates that give them; the built-in ones are shown and not changed, and custom ones are added with a name and an OID, and changed or removed. - **Extended key usages:** the usages templates may give, with their OIDs and the templates that give them; the built-in ones are shown and not changed, and custom ones are added with a name and an OID, and changed or removed.
- **P2S Issuing CA** and **S2S Issuing CA:** the CA's common name, state (active, or pending while it waits for the offline root), expiry, CRL and templates, and the certificates it issued. An active CA gives its CA bundle, the issuing CA followed by the root, with Download CA bundle; a pending CA gives its CSR with the openssl extensions to sign it with, and takes the certificate signed by the root. - **Issuing CAs:** the built-in P2S, S2S and Servers (`servers`) CAs and the custom CAs, with their state (active, pending while they wait for the offline root or Simple CA, or off while the VPN or the router a built-in CA belongs to is off), expiry, CRL, templates and ACME directory URL; an active CA's download icon gives its CA bundle, the issuing CA followed by the CAs above it, and a pending CA waiting for the offline root gives its CSR with the openssl extensions to sign it with and takes the certificate signed by the root. Add issuing CA, and Edit and Remove on each custom CA: its name, fixed once it exists, its common name, the templates it issues and its ACME server. A removed CA is retired by the server, which revokes its certificate on the root CRL. Below, the certificates of all of them, filtered by CA, each with its kind, template, names, expiry and state; a certificate of another system or of the server is revoked after a confirmation with a reason.
- **Issuing CAs:** the general-purpose CAs with their state, expiry, CRL, templates and ACME directory URL; Add issuing CA, and Edit and Remove on each: its name, fixed once it exists, its common name, the templates it issues and its ACME server; an active CA's download icon gives its CA bundle. A removed CA is retired by the server, which revokes its certificate on the root CRL. Below, their certificates, filtered by CA. - **Certificates:** each with its kind, template, names, expiry and state; a certificate of another system or of the server is revoked after a confirmation with a reason. - **Issue** (above the tabs but on Server): from a CSR, saving the certificate with its chain, or with a key the server makes, saving a PFX file protected by a password; the server keeps no copy of the key.
- **Issue** (above the tabs): from a CSR, saving the certificate with its chain, or with a key the server makes, saving a PFX file protected by a password; the server keeps no copy of the key. - **Settings** (above the tabs but on Server): the source of the root, shown, the Simple CA URL, the names, lifetimes, key type, CRL validity and publishing endpoints.
- **Settings** (above the tabs): the source of the root, shown, the Simple CA URL, the names, lifetimes, key type, CRL validity and publishing endpoints.
- **Warnings** (above the tabs): what the server says needs attention, such as a CRL about to expire. - **Warnings** (above the tabs): what the server says needs attention, such as a CRL about to expire.
- **Overview**: the server's overall status, ok or degraded, on the title bar of the Status panel; - **Overview**: the server's overall status, ok or degraded, on the title bar of the Status panel;
at the top of that panel, a table of `linux-manager` at the top of that panel, a table of `linux-manager`
with the installed version and, when the repository has a newer one, that version; Check update with the installed version and, when the repository has a newer one, that version; Check update
is always in its top right corner, and Upgrade is added beside it when an update is found. Then is always in its top right corner, and Upgrade is added beside it when an update is found. Then
IKEv2, OpenVPN and WireGuard, read from the server's authenticated `/status/full`, and from its `/config` the status web service and its port, whether HTTPS is on and for which name, with a chip while Caddy takes Let's Encrypt's staging CA and a settings button that switches it (`https.acme_staging`, through the server's `/https/settings`), and Caddy, its HTTPS proxy: its version, whether it comes from Ubuntu or upstream (switched on the server with `linux-manager-caddy use-upstream`) with the configured `https.caddy_source` when that differs, and the state of `caddy.service`. The Services panel shows the state of each of the server's IKEv2, OpenVPN and WireGuard, read from the server's authenticated `/status/full`, and from its `/config` the status web service and its port. The Services panel shows the state of each of the server's
systemd services and of Caddy, with a chip on its title bar telling whether the server's services are active. The Addresses panel links, opening in a new tab, to the status page over HTTPS and over plain HTTP on the addresses `web.listen` names, and to the Manager over HTTPS, and shows the issuer and the discovery URL of the server's OpenID Provider, each with an icon that copies it, or off while the provider is disabled. Further panels systemd services and of Caddy, with a chip on its title bar telling whether the server's services are active. The Addresses panel links, opening in a new tab, to the status page over HTTPS and over plain HTTP on the addresses `web.listen` names, and to the Manager over HTTPS, and shows the issuer and the discovery URL of the server's OpenID Provider, each with an icon that copies it, or off while the provider is disabled. Further panels
show each PostgreSQL cluster of the show each PostgreSQL cluster of the
router with its main settings and its databases with their sizes, and one Configuration panel router with its main settings and its databases with their sizes, and one Configuration panel
@@ -2288,7 +2390,7 @@ name, left of Sign out, opens the account page, and the terminal icon left of it
`/sites` and `/dns`, in tabs: `/sites` and `/dns`, in tabs:
- **Sites:** the Settings panel shows whether the sites are served, the largest upload and - **Sites:** the Settings panel shows whether the sites are served, the largest upload and
WebDAV with its URL and a copy icon, edited with Settings. The list shows each site with its WebDAV with its URL and a copy icon, edited with Settings. The list shows each site with its
URLs, linked, its port, the interfaces whose firewall opens it, its TLS (none, Let's Encrypt, URLs, linked, its port, the interfaces whose firewall opens it, its TLS (none, ACME,
an issuing CA of the server or a certificate and key) and its editors group, searched by name, an issuing CA of the server or a certificate and key) and its editors group, searched by name,
host name and group; Add and Edit take the name, fixed once added, the host names, one per host name and group; Add and Edit take the name, fixed once added, the host names, one per
line, the port, the interfaces, the TLS with the issuing CA or the PEM certificate chain and line, the port, the interfaces, the TLS with the issuing CA or the PEM certificate chain and
@@ -2300,12 +2402,13 @@ name, left of Sign out, opens the account page, and the terminal icon left of it
with a progress bar; while Extract zip archives is on, a `.zip` file is extracted there with a progress bar; while Extract zip archives is on, a `.zip` file is extracted there
instead. New folder, Rename, Remove and Download. A file larger than the server's largest instead. New folder, Rename, Remove and Download. A file larger than the server's largest
upload is not sent. upload is not sent.
- **DNS:** the server's primary name server: its settings with whether PowerDNS is installed - **DNS** (`/dns-manager`, in the page menu while the name server is on): the server's primary
and runs, the server's FQDN as the primary name server, edited with Settings (enabled, name server: its settings with whether PowerDNS is installed and runs, the server's FQDN as the
secondary name server, public IP address, interfaces, TTL); the domains, added with Add primary name server, edited with Settings (optional secondary name server, public IP address,
domain (domain, TTL), edited and removed with their icons; and for the selected domain the interfaces, TTL; the name server is switched on the System tab); the domains, added with Add
records it serves, and its manual records, added with Add record (name, type, content and domain (domain, TTL), edited and removed with their icons; and for the selected domain the
TTL) and removed with their icon. records it serves, and its manual records, added with Add record (name, type, content and TTL)
and removed with their icon.
- **Docker** (`/docker-manager`): the state of `docker.service` and of the server's Docker rules, - **Docker** (`/docker-manager`): the state of `docker.service` and of the server's Docker rules,
the ports exposed on the external interface and the rules of the `LINUX-MANAGER-DOCKER` chain, the ports exposed on the external interface and the rules of the `LINUX-MANAGER-DOCKER` chain,
from the server's `/status/full` and `/config`. The page menu leaves the page out while from the server's `/status/full` and `/config`. The page menu leaves the page out while
@@ -2330,7 +2433,7 @@ name, left of Sign out, opens the account page, and the terminal icon left of it
- **Warnings:** shown when the PBS client or rclone the settings need is not installed on the server. - **Warnings:** shown when the PBS client or rclone the settings need is not installed on the server.
Restoring is done on the server with `linux-manager-backup restore`. The Overview tab has a Backup panel with the result of the last run, the next run and Run now. Restoring is done on the server with `linux-manager-backup restore`. The Overview tab has a Backup panel with the result of the last run, the next run and Run now.
- **System**: the server's operating system. The System updates panel lists the packages `apt-get upgrade` would upgrade, each with its installed and its new version, from `/api/system-updates`; Check update is always in its top right corner, and Upgrade is added beside it when a package can be upgraded. Upgrade runs `apt-get upgrade -y` after a confirmation and shows its output in a dialog, as Upgrade on the Overview tab does, with Reload page and Reboot when they apply. - **System**: the server's operating system. The System updates panel lists the packages `apt-get upgrade` would upgrade, each with its installed and its new version, from `/api/system-updates`; Check update is always in its top right corner, and Upgrade is added beside it when a package can be upgraded. Upgrade runs `apt-get upgrade -y` after a confirmation and shows its output in a dialog, as Upgrade on the Overview tab does, with Reload page and Reboot when they apply. The Components panel lists the VPN, the router, the name server and WebDAV from the server's `/components`, each on or off and with its packages not installed, installing, installed or failed; Enable switches one on and the server installs its packages, Disable switches it off after a confirmation and keeps them. The router is offered only while the server has a second network interface, and its Enable asks for the internal interface and, in `manual` mode, its address and gateway. The name server and WebDAV are switched only there; their settings dialogs keep their other settings.
### How it works ### How it works
@@ -2363,10 +2466,11 @@ It serves the application from `/usr/share/linux-manager/manager/web`.
manager relays the WebSocket's bytes both ways until either side closes. `POST /api/shell`, which manager relays the WebSocket's bytes both ways until either side closes. `POST /api/shell`, which
gives the ticket the handshake needs, and `POST /api/shell/passkey`, which begins the passkey gives the ticket the handshake needs, and `POST /api/shell/passkey`, which begins the passkey
proof it may take, pass as every other call does. proof it may take, pass as every other call does.
- `/api/info` gives the version of the package and the URL of the server's status page, without a - `/api/info` gives the URL of the server's status page and `manager`, the `port` and `listen` of
session. On the server, while `router_url` and `terraform_dir` are not set and the status web the manager's plain HTTP site, without a session, and the version of the package only with one,
service listens on the address the call came in on, the URL has the name or address the browser so the sign-in page shows no version. On the server, while `router_url` and `terraform_dir` are not set and the status web
used and `web.port`, for example `http://router.example.com:7081`, and for a page opened over service is enabled, the URL has the name or address the browser used and `web.port`, Caddy's
plain HTTP site, for example `http://router.example.com:7081`, and for a page opened over
the server's HTTPS proxy `https` and `https.web_port`, for example the server's HTTPS proxy `https` and `https.web_port`, for example
`https://router.example.com:7444`; otherwise it is `router_url`. `https://router.example.com:7444`; otherwise it is `router_url`.
- `/api/updates`, with a session, gives the installed and the candidate version of `linux-manager` - `/api/updates`, with a session, gives the installed and the candidate version of `linux-manager`
@@ -2409,17 +2513,20 @@ It serves the application from `/usr/share/linux-manager/manager/web`.
| 411 | The upload of a site's file has no `Content-Length` | | 411 | The upload of a site's file has no `Content-Length` |
The server's rate limit of sign-ins counts the browser's address when the manager's address is The server's rate limit of sign-ins counts the browser's address when the manager's address is
in the server's `web.trusted_proxies`; by default that is the server's address the call came in in the server's `web.trusted_proxies`; by default that is `127.0.0.1`, which is the address a
on, which is the address a manager on the server calls from, so it needs nothing more. manager on the server calls from, so it needs nothing more.
On the server, the server's Caddy serves the manager over HTTPS on `https.manager_port` of On the server, the manager listens on `127.0.0.1:7090` only. The server's Caddy serves it over
`linux-manager.json` (7443 by default) for `wan.local_fqdn`, with a certificate from Let's Encrypt, plain HTTP on `port` (7080 by default), open in the firewall on the interfaces `listen` names, or
and calls it on `127.0.0.1`, where the manager also listens. For a call from `127.0.0.1` with redirects there to its HTTPS address while HTTPS is on (see HTTPS), and over HTTPS on
`X-Forwarded-For`, the manager takes the browser's address from the last entry of that header. `https.manager_port` of `linux-manager.json` (7443 by default) for `wan.local_fqdn`, with the
certificate of `https.certificate`. For a call from `127.0.0.1` with `X-Forwarded-For`, the
manager takes the browser's address from the last entry of that header.
The service needs nothing else to start and keeps running. Every 30 seconds it works out where to The service needs nothing else to start and keeps running. Every 30 seconds it works out where to
listen and starts, moves or stops a server on each address to match, so a change of `listen`, listen and starts, moves or stops a server on each address to match, so a change of `bind` or
`bind` or `port` takes effect within 30 seconds, or when the service restarts. Each request `port` off the server takes effect within 30 seconds, or when the service restarts; on the
server, `listen` and `port` take effect with the next run of `linux-manager-setup`. Each request
reads the settings again. reads the settings again.
Before it listens, it creates its sessions database on the server when it is missing and connects Before it listens, it creates its sessions database on the server when it is missing and connects
@@ -2433,12 +2540,12 @@ PostgreSQL is not running yet.
| Setting | Meaning | Default | | Setting | Meaning | Default |
|---------|---------|---------| |---------|---------|---------|
| `router_url` | The server's status web service | `http://<first address of the web service>:<web.port>`, the internal address when it listens on both | | `router_url` | The server's status web service | On the server, `http://127.0.0.1:7091`, the web service behind Caddy |
| `database` | A PostgreSQL connection string for the sessions | The `linux-manager-ui` database on the server | | `database` | A PostgreSQL connection string for the sessions | The `linux-manager-ui` database on the server |
| `listen` | The interfaces to listen on when `bind` is not set: `internal`, `external` or `both`, and always `127.0.0.1` | `both` | | `listen` | On the server, the interfaces the firewall opens `port` on: `internal`, `external` or `both` | `both` |
| `bind` | The one address to listen on; the server's HTTPS proxy reaches the manager only when it is `127.0.0.1` | none, `listen` applies | | `bind` | The one address to listen on, with `port`, off the server, as `dev.py` sets it | none; on the server `127.0.0.1:7090` |
| `port` | The port to listen on, HTTP | `7080` | | `port` | The port of `bind`; on the server, Caddy's plain HTTP port of the manager, which redirects to the HTTPS address while HTTPS is on unless `https.disable_auto_redirect` is `true` | `7080` |
| `terraform_dir` | A Terraform root directory whose outputs give `router_url` when it is not set; `dev.sh` sets it | none | | `terraform_dir` | A Terraform root directory whose outputs give `router_url` when it is not set; `dev.py` sets it | none |
| `iac_tool` | The tool that reads the outputs of `terraform_dir`: `terraform` or `tofu` | `terraform` | | `iac_tool` | The tool that reads the outputs of `terraform_dir`: `terraform` or `tofu` | `terraform` |
From the outputs of `<iac_tool> -chdir=<terraform_dir> output -json`, read every 30 seconds at From the outputs of `<iac_tool> -chdir=<terraform_dir> output -json`, read every 30 seconds at
@@ -2470,20 +2577,20 @@ echo 'linux-manager linux-manager/admin_password password s3cr3t-pass' | debconf
### Running the application on a workstation ### Running the application on a workstation
`dev.sh` runs the manager and the Vite development server, which reloads on changes, on the `dev.py` runs the manager and the Vite development server, which reloads on changes, on the
workstation; the application is at http://localhost:5180. Its first argument is the workstation; the application is at http://localhost:5180. Its first argument is the
`config.json` of the platform that deployed the server. Its `module_root`, relative to the `config.json` of the platform that deployed the server. Its `module_root`, relative to the
directory of that file, is the Terraform root module whose outputs give the server's address. directory of that file, is the Terraform root module whose outputs give the server's address.
The second argument, optional, is the connection string of a PostgreSQL database for the The second argument, optional, is the connection string of a PostgreSQL database for the
sessions; without it the sessions are kept in the database `PGDATABASE` names, or the one named sessions; without it the sessions are kept in the database `PGDATABASE` names, or the one named
after the login, and libpq takes the server, port, user, password and SSL mode from the `PG*` after the login, and libpq takes the server, port, user, password and SSL mode from the `PG*`
variables of the environment, such as those of the platform's `pg.env.sh`. `dev.sh` writes them variables of the environment, such as those of the platform's `pg.env.sh`. `dev.py` writes them
as `terraform_dir` and `database`, with the platform's `iac_tool` and `bind` `127.0.0.1`, to `dev.json` in the repository root, which is not in Git, and as `terraform_dir` and `database`, with the platform's `iac_tool` and `bind` `127.0.0.1`, to `dev.json` in the repository root, which is not in Git, and
the manager reads that and listens on `127.0.0.1:7080`: the manager reads that and listens on `127.0.0.1:7080`:
```sh ```sh
./dev.sh /path/to/azure-platform/config.json ./dev.py /path/to/azure-platform/config.json
./dev.sh /path/to/azure-platform/config.json 'host=localhost dbname=manager user=manager password=secret' ./dev.py /path/to/azure-platform/config.json 'host=localhost dbname=manager user=manager password=secret'
``` ```
It creates `.venv` with `psycopg[binary]` and `requests` when they are missing, and installs the npm dependencies It creates `.venv` with `psycopg[binary]` and `requests` when they are missing, and installs the npm dependencies
@@ -2528,7 +2635,7 @@ key pair, everything under `/etc/swanctl`, the folders of the web sites in `/var
## Building ## Building
```sh ```sh
./build.sh ./build.py
``` ```
The build runs in a container from the repository root: a Node.js stage builds the The build runs in a container from the repository root: a Node.js stage builds the
@@ -2538,9 +2645,34 @@ container runtime is Apple's `container` on macOS and Docker on Linux, or `CONTA
when set, for example Docker on a remote engine: when set, for example Docker on a remote engine:
```sh ```sh
CONTAINER_RUNTIME=docker DOCKER_CONTEXT=build-host ./build.sh CONTAINER_RUNTIME=docker DOCKER_CONTEXT=build-host ./build.py
``` ```
`./publish.sh` uploads the package to the component `main` of the distribution `resolute` The build writes `debian/changelog` from `CHANGELOG.md` with `bin/changelog.py`; the file is
(Ubuntu 26.04, the only supported release) of the configured repository, skipping a not kept in the repository.
distribution that has the version already; `DISTRIBUTIONS` names others.
`./publish.py` uploads the package of the newest `CHANGELOG.md` entry from `out/` to the
component `main` of the distribution `resolute` (Ubuntu 26.04, the only supported release) of the
Gitea Debian repository of `OWNER` at `SERVER_URL`, with the token `PACKAGES_TOKEN` or else the
content of `~/.gitea-packages-token`, skipping a distribution that has the version already;
`DISTRIBUTIONS` names others.
## Releasing
`CHANGELOG.md` is the package's history. Its newest entry, a `## x.y.z` heading, a summary
paragraph and `-` items, is the next release; `x.y.z` is the Debian version `x.y.z-1`, and
`x.y.z-n` is a later release of the same code.
```sh
./release.py
./release.py --push
./release.py --no-tag --push
./release.py -n --push
```
`./release.py` writes the current time into the newest entry's heading, `## x.y.z - YYYY-MM-DD
HH:MM:SS +ZZZZ`, and commits everything with the entry's summary as the message; the release stays
on the machine, and the next change needs a new entry. `--push` also tags the version, `x.y.z` or
`x.y.z-n`, and pushes `main` and the tag, which starts the release workflow; a committed entry is
pushed this way later too. `--no-tag` makes an internal release: `--push` then pushes `main` alone.
`-n` prints the heading and the git commands instead of making them.
+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())
+24 -22
View File
@@ -1,53 +1,55 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Build the next numbered dev build and publish it to a test project's repository: lm-dev-build.py. """Build the next numbered dev build and publish it to a test project's repository: lm-dev-build.py.
The serial N in .dev-build.serial of the repository is that of the last dev build; each build that The serial N, the setting LXD_DEV_BUILD_SERIAL (lm_dev.setting, 0 by default), is that of the last
succeeds writes its own, one higher, and release.py writes 0 when it releases. The build's version dev build; each build that succeeds writes its own, one higher, into .lm-dev-config/settings.json,
is the newest changelog entry's with ~devN before its Debian revision, 0.41.0-1 becoming and release.py writes 0 there when it releases. The build's version is the Debian version of the
0.41.0~dev7-1, so the release of that entry is newer than all its dev builds. ./build.sh builds it 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/, 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) 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 made by lm-dev-lxd-project.py, and published there. The remote is the project's, read from
tmp/lxd-project-PROJECT.json, so the script takes no --remote. .lm-dev-config/lxd-project-PROJECT.json, so the script takes no --remote.
""" """
import argparse import argparse
import json import json
import os
import re
import subprocess import subprocess
import sys import sys
from lm_dev import PROJECT, ROOT, lxc_exec import changelog
from lm_dev import PROJECT, ROOT, config_path, lxc_exec, save_setting, setting
SERIAL = ROOT / '.dev-build.serial' CHANGELOG = ROOT / 'CHANGELOG.md'
CHANGELOG = ROOT / 'debian-package' / 'debian' / 'changelog' CONTROL = ROOT / 'debian-package' / 'debian' / 'control'
def main(): def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT), 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, ' help=f'the test project made by lm-dev-lxd-project.py, whose remote is used (LXD_PROJECT, '
f'default {PROJECT})') f'default {PROJECT})')
args = parser.parse_args() args = parser.parse_args()
state_file = ROOT / 'tmp' / f'lxd-project-{args.project}.json' state_file = config_path(f'lxd-project-{args.project}.json')
if not state_file.is_file(): if not state_file.is_file():
sys.exit(f'no {state_file}; create the project with lm-dev-lxd-project.py create') sys.exit(f'no {state_file}; create the project with lm-dev-lxd-project.py create')
state = json.loads(state_file.read_text(encoding='utf-8')) state = json.loads(state_file.read_text(encoding='utf-8'))
# The newest entry's first line is "package (version) distribution; urgency=...". try:
match = re.match(r'(\S+) \(([^)]+)\)', CHANGELOG.read_text(encoding='utf-8')) found = changelog.entries(CHANGELOG.read_text(encoding='utf-8'))
if not match: package = changelog.control_field(CONTROL.read_text(encoding='utf-8'), 'Source')
sys.exit(f'no version in the first line of {CHANGELOG}') except ValueError as error:
package, version = match.groups() sys.exit(f'{CHANGELOG}: {error}')
number = int(SERIAL.read_text(encoding='utf-8').strip()) + 1 if SERIAL.is_file() else 1 if not found:
upstream, dash, revision = version.rpartition('-') sys.exit(f'{CHANGELOG} has no entry')
dev = f'{upstream}~dev{number}-{revision}' if dash else f'{version}~dev{number}' 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}') print(f'building {package} {dev}')
if subprocess.run(['./build.sh', '--build-arg', f'DEB_VERSION={dev}'], cwd=ROOT).returncode != 0: 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}') sys.exit(f'the build of {dev} failed; the serial stays {number - 1}')
SERIAL.write_text(f'{number}\n', encoding='utf-8') save_setting('LXD_DEV_BUILD_SERIAL', number)
# The dev build leaves out/ to out/dev/, so out/ keeps the release builds. # The dev build leaves out/ to out/dev/, so out/ keeps the release builds.
target = ROOT / 'out' / 'dev' target = ROOT / 'out' / 'dev'
+153 -55
View File
@@ -1,31 +1,40 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Create or remove an LXD project for manual tests, or its uplink: lm-dev-lxd-project.py create|remove|uplink. """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 uplink setup creates the physical uplink network once per remote, and uplink remove deletes it
(see uplink). (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, 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 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 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 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; eth0 on wan. The container repo serves a signed apt repository of the dev builds over HTTP;
lm-dev-build.py publishes into it and lm-dev-vm.py installs from it. What they need is written to lm-dev-build.py publishes into it and lm-dev-vm.py installs from it. The container vault is the
tmp/lxd-project-PROJECT.json, with the repository's key in tmp/lxd-project-PROJECT.gpg. remove project's Vault, made first, which the scripts hand secrets to the instances through; every other
deletes the project's instances, its networks, the project and those files. 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 argparse
import json import json
import os
import re import re
import subprocess import subprocess
import sys import sys
import time import time
from lm_dev import PROJECT, ROOT, TESTS, lxc_exec 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') 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): 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.""" """Run lxc with the arguments in the project; raise CalledProcessError when it fails, unless check is false."""
@@ -33,8 +42,84 @@ def lxc(*args, project, check=True, input=None):
check=check) 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): def create(args, state, key):
"""Create the project with its networks and default profile, and the repository container.""" """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, subprocess.run(['lxc', 'project', 'create', f'{args.remote}:{args.project}', '-s', args.pool,
'-c', 'features.images=false', '-c', 'features.networks=true'], '-c', 'features.images=false', '-c', 'features.networks=true'],
capture_output=True, text=True, check=True) capture_output=True, text=True, check=True)
@@ -49,33 +134,16 @@ def create(args, state, key):
lxc('profile', 'device', 'add', f'{args.remote}:default', 'eth0', 'nic', 'network=wan', 'name=eth0', lxc('profile', 'device', 'add', f'{args.remote}:default', 'eth0', 'nic', 'network=wan', 'name=eth0',
project=args.project) project=args.project)
vault = vault_create(args)
print(f'launching the repository container {args.remote}:repo (project {args.project})') print(f'launching the repository container {args.remote}:repo (project {args.project})')
lxc('launch', args.image, f'{args.remote}:repo', address = launch(args, 'repo', 'repo.yaml')
'-c', 'cloud-init.user-data=' + (TESTS / 'cloud-init' / 'repo.yaml').read_text(encoding='utf-8'), problem = enrol_instance(args.remote, args.project, 'repo', vault)
project=args.project) if problem:
raise RuntimeError(problem)
def inside(*command): def inside(*command):
return lxc_exec(args.remote, args.project, 'repo', *command) return lxc_exec(args.remote, args.project, 'repo', *command)
# Wait for cloud-init (status 2 is done with recoverable errors), then for the address of eth0.
for _ in range(120):
if inside('cloud-init', 'status', '--wait').returncode in (0, 2):
break
time.sleep(5)
else:
raise RuntimeError('the repository container did not boot')
for _ in range(24):
match = re.search(r' inet (\d+\.\d+\.\d+\.\d+)/',
inside('ip', '-4', '-o', 'addr', 'show', 'dev', 'eth0').stdout)
if match:
break
time.sleep(5)
else:
raise RuntimeError('the repository container has no address on eth0')
address = match.group(1)
lxc('config', 'device', 'override', f'{args.remote}:repo', 'eth0', f'ipv4.address={address}',
project=args.project)
# The signing key, the publishing script and the empty indexes. # The signing key, the publishing script and the empty indexes.
generate = ('gpg', '--batch', '--pinentry-mode', 'loopback', '--passphrase', '', '--quick-generate-key', generate = ('gpg', '--batch', '--pinentry-mode', 'loopback', '--passphrase', '', '--quick-generate-key',
'Linux Manager test repository', 'default', 'default', 'never') 'Linux Manager test repository', 'default', 'default', 'never')
@@ -94,6 +162,7 @@ def create(args, state, key):
state.write_text(json.dumps({'remote': args.remote, 'project': args.project, 'networks': list(NETWORKS), state.write_text(json.dumps({'remote': args.remote, 'project': args.project, 'networks': list(NETWORKS),
'repository': f'http://{address}/', 'key': str(key)}, indent=2) + '\n', 'repository': f'http://{address}/', 'key': str(key)}, indent=2) + '\n',
encoding='utf-8') encoding='utf-8')
state.chmod(0o600)
print(f'project {args.project} is ready on {args.remote}: networks {", ".join(NETWORKS)}, ' print(f'project {args.project} is ready on {args.remote}: networks {", ".join(NETWORKS)}, '
f'repository http://{address}/') f'repository http://{address}/')
print(f'state: {state}') print(f'state: {state}')
@@ -125,6 +194,7 @@ def remove(args, state, key):
if ok: if ok:
state.unlink(missing_ok=True) state.unlink(missing_ok=True)
key.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}') print(f'removed project {args.project} and its networks from {args.remote}')
return ok return ok
@@ -150,10 +220,11 @@ def uplink(args):
if exists: if exists:
print(f'{args.remote} has the network {args.uplink} already') print(f'{args.remote} has the network {args.uplink} already')
return return
missing = [option for option, value in (('--parent', args.parent), ('--gateway', args.gateway), ('--dns', args.dns), for option, name in UPLINK_SETTINGS.items():
('--ovn-ranges', args.ovn_ranges), ('--routes', args.routes)) if not value] try:
if missing: setattr(args, option, getattr(args, option) or setting(name))
sys.exit(f'uplink setup needs {", ".join(missing)}') 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}', 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}', f'dns.nameservers={args.dns}', f'ipv4.ovn.ranges={args.ovn_ranges}', f'ipv4.routes={args.routes}',
project='default') project='default')
@@ -163,32 +234,39 @@ def uplink(args):
def main(): def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('action', choices=('create', 'remove', 'uplink')) parser.add_argument('action', choices=('create', 'remove', 'vault', 'uplink'))
parser.add_argument('operation', nargs='?', choices=('setup', 'remove'), help='after uplink: setup or remove') parser.add_argument('operation', nargs='?', choices=('setup', 'create', 'unseal', 'remove'),
parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)') help='after vault: create, unseal or remove; after uplink: setup or remove')
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, for create (LXD_POOL)') help='the storage pool of the project, for create (LXD_POOL)')
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT), parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project (LXD_PROJECT, default {PROJECT})') help=f'the project (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'), parser.add_argument('--image', default=setting('LXD_IMAGE', 'ubuntu:26.04'),
help='the image of the repository container (LXD_IMAGE, default ubuntu:26.04)') help='the image of the repository container (LXD_IMAGE, default ubuntu:26.04)')
parser.add_argument('--uplink', default=os.environ.get('LXD_UPLINK', 'uplink'), 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)') help='the physical uplink network of the OVN networks (LXD_UPLINK, default uplink)')
parser.add_argument('--parent', default=os.environ.get('LXD_UPLINK_PARENT'), parser.add_argument('--parent',
help='uplink setup: the host bridge on the LAN (LXD_UPLINK_PARENT)') help='uplink setup: the host bridge on the LAN (LXD_UPLINK_PARENT)')
parser.add_argument('--gateway', default=os.environ.get('LXD_UPLINK_GATEWAY'), parser.add_argument('--gateway',
help='uplink setup: the LAN gateway as address/prefix (LXD_UPLINK_GATEWAY)') help='uplink setup: the LAN gateway as address/prefix (LXD_UPLINK_GATEWAY)')
parser.add_argument('--dns', default=os.environ.get('LXD_UPLINK_DNS'), parser.add_argument('--dns',
help='uplink setup: the LAN name servers, comma-separated (LXD_UPLINK_DNS)') help='uplink setup: the LAN name servers, comma-separated (LXD_UPLINK_DNS)')
parser.add_argument('--ovn-ranges', default=os.environ.get('LXD_UPLINK_OVN_RANGES'), parser.add_argument('--ovn-ranges',
help='uplink setup: LAN addresses for OVN routers, FIRST-LAST (LXD_UPLINK_OVN_RANGES)') help='uplink setup: LAN addresses for OVN routers, FIRST-LAST (LXD_UPLINK_OVN_RANGES)')
parser.add_argument('--routes', default=os.environ.get('LXD_UPLINK_ROUTES'), parser.add_argument('--routes',
help='uplink setup: LAN subnets for network forwards, CIDR (LXD_UPLINK_ROUTES)') help='uplink setup: LAN subnets for network forwards, CIDR (LXD_UPLINK_ROUTES)')
args = parser.parse_args() args = parser.parse_args()
if not args.remote: try:
parser.error('--remote or LXD_REMOTE is required') args.remote = args.remote or setting('LXD_REMOTE')
if (args.action == 'uplink') != (args.operation is not None): except MissingSetting as missing:
parser.error('setup or remove follows uplink, and only uplink') 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': if args.action == 'uplink':
try: try:
@@ -196,14 +274,34 @@ def main():
except subprocess.CalledProcessError as error: except subprocess.CalledProcessError as error:
sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}') sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}')
return return
state = ROOT / 'tmp' / f'lxd-project-{args.project}.json' state = config_path(f'lxd-project-{args.project}.json')
key = ROOT / 'tmp' / f'lxd-project-{args.project}.gpg' 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': if args.action == 'remove':
sys.exit(0 if remove(args, state, key) else 1) sys.exit(0 if remove(args, state, key) else 1)
if not args.pool: try:
parser.error('--pool or LXD_POOL is required') 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: 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') 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) state.parent.mkdir(parents=True, exist_ok=True)
@@ -212,7 +310,7 @@ def main():
except subprocess.CalledProcessError as error: except subprocess.CalledProcessError as error:
sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}\n' 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}') f'remove what was made with: {sys.argv[0]} remove --remote {args.remote} --project {args.project}')
except RuntimeError as error: except (RuntimeError, VaultError) as error:
sys.exit(f'{error}\nremove what was made with: {sys.argv[0]} remove --remote {args.remote} ' sys.exit(f'{error}\nremove what was made with: {sys.argv[0]} remove --remote {args.remote} '
f'--project {args.project}') f'--project {args.project}')
+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 (lm-dev), which
lm-dev-otp-register.py or lm-dev-vm.py create enrolled.
"""
import argparse
import sys
from lm_dev import PROJECT, 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='lm-dev', help='the name of the VM (default lm-dev)')
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()
+16 -41
View File
@@ -2,60 +2,35 @@
"""Register a TOTP token for a user of a Linux Manager VM on an LXD remote: lm-dev-otp-register.py. """Register a TOTP token for a user of a Linux Manager VM on an LXD remote: lm-dev-otp-register.py.
The token is enrolled for --user (admin by default) of the VM --vm (lm-dev) in the project --project The token is enrolled for --user (admin by default) of the VM --vm (lm-dev) in the project --project
(LXD_PROJECT, lm-dev by default) on the remote --remote (LXD_REMOTE), through lxc exec: inside the (LXD_PROJECT, lm-dev by default) on the remote --remote (LXD_REMOTE): the project's Vault generates
VM, as root, linuxmanager_users makes a new secret, and stores it once a code computed here from it the key in its TOTP engine as <vm>-<user> and hands it to the VM, where linuxmanager_users stores
verifies, replacing a token the user had. The secret, base32, is then written to the file it with its current code, replacing a token the user had. The secret stays in the Vault and the
--secret-file or OTP_FILE names, readable by its owner only, so otp.py code prints the user's codes. VM; lm-dev-otp-code.py prints the user's codes.
""" """
import argparse import argparse
import json
import os
import pathlib
import sys import sys
from lm_dev import PROJECT, lxc_exec from lm_dev import PROJECT, MissingSetting, enrol_otp, setting, totp_key
from otp import code_of
# Run in the VM as python3 -c CODE ARGUMENTS..., with the package's modules on the path.
NEW = ("import json, sys; sys.path.insert(0, '/usr/lib/linux-manager'); import linuxmanager_users as users\n"
"with users.session() as connection: print(json.dumps(users.otp_new(connection, sys.argv[1])))")
ENROL = ("import sys; sys.path.insert(0, '/usr/lib/linux-manager'); import linuxmanager_users as users\n"
"with users.session() as connection: users.otp_enrol(connection, sys.argv[1], sys.argv[2], sys.argv[3])")
def main(): def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)') parser.add_argument('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT), parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})') help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)') parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)')
parser.add_argument('--user', default='admin', help='the user to enrol (default admin)') parser.add_argument('--user', default='admin', help='the user to enrol (default admin)')
parser.add_argument('--secret-file', default=os.environ.get('OTP_FILE'),
help='the file the base32 secret is written to (OTP_FILE)')
args = parser.parse_args() args = parser.parse_args()
if not args.remote: try:
parser.error('--remote or LXD_REMOTE is required') args.remote = args.remote or setting('LXD_REMOTE')
if not args.secret_file: except MissingSetting as missing:
parser.error('--secret-file or OTP_FILE is required') parser.error(f'--remote or {missing}')
secret_file = pathlib.Path(args.secret_file) problem = enrol_otp(args.remote, args.project, args.vm, args.user)
if problem:
def failure(result): sys.exit(problem)
return (result.stderr.strip().splitlines() or ['lxc exec failed'])[-1] 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}')
created = lxc_exec(args.remote, args.project, args.vm, 'python3', '-c', NEW, args.user)
if created.returncode != 0:
sys.exit(f'no new secret for {args.user}: {failure(created)}')
secret = json.loads(created.stdout)['secret']
enrolled = lxc_exec(args.remote, args.project, args.vm, 'python3', '-c', ENROL, args.user, secret, code_of(secret))
if enrolled.returncode != 0:
sys.exit(f'{args.user} was not enrolled: {failure(enrolled)}')
secret_file.parent.mkdir(parents=True, exist_ok=True)
secret_file.touch(mode=0o600)
secret_file.chmod(0o600)
secret_file.write_text(f'{secret}\n', encoding='utf-8')
print(f'{args.user} of {args.remote}:{args.vm} has a new TOTP token; its secret is in {secret_file}')
if __name__ == '__main__': if __name__ == '__main__':
+132 -47
View File
@@ -4,28 +4,37 @@
The remote and its storage pool are required, as --remote and --pool or LXD_REMOTE and 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, --project (LXD_TEST_PROJECT, lm-test by 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 default), which must not exist and is removed with its networks after each scenario unless --keep
is given. The package is the newest out/linux-manager_*_all.deb. The administrator's name and is given. The package is --deb, or else the one built last, in out/ or out/dev/. The administrator, admin, has a
password are set as ADMIN_USERNAME and ADMIN_PASSWORD in the repository's .env, and the pre-shared password generated per run, kept in the scenario's Vault as <server>/admin. Each scenario's
key is written to tmp/remote-test.env. Each check prints PASS, FAIL or SKIP; the run exits 1 when a project gets a Vault, the container lm-vault reached on the LXD host's address; every other instance
check failed. 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 argparse
import importlib import importlib
import ipaddress import ipaddress
import json import json
import os import pathlib
import re import re
import secrets import secrets
import subprocess import subprocess
import sys import sys
import time import time
from lm_dev import ROOT, TESTS, lxc_exec, set_dotenv 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' TMP = ROOT / 'tmp' / 'remote-test'
#: 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__') 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: class Lab:
"""The instances and networks of a run on one LXD remote and project, and the results of its checks. """The instances and networks of a run on one LXD remote and project, and the results of its checks.
@@ -47,6 +56,9 @@ class Lab:
self.networks = [] self.networks = []
self.macs = {} self.macs = {}
self.addresses = {} self.addresses = {}
self.vault = None
self.enrolled = set()
self.routed = set()
def lxc(self, *args, check=True): def lxc(self, *args, check=True):
"""Run lxc with the arguments and the project; raise CalledProcessError when it fails, unless check is false.""" """Run lxc with the arguments and the project; raise CalledProcessError when it fails, unless check is false."""
@@ -108,6 +120,33 @@ class Lab:
result = self.on(name, *command) result = self.on(name, *command)
self.result(description, re.search(pattern, result.stdout + result.stderr, re.M) is None) 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): def network(self, name, address):
"""Create a bridge with outbound NAT at the gateway address GATEWAY/PREFIX, or without a host address when None. """Create a bridge with outbound NAT at the gateway address GATEWAY/PREFIX, or without a host address when None.
@@ -129,6 +168,8 @@ class Lab:
""" """
self.macs[name] = [nic[1] for nic in nics] self.macs[name] = [nic[1] for nic in nics]
self.addresses[name] = nics[0][2] self.addresses[name] = nics[0][2]
if any(len(nic) > 3 for nic in nics):
self.routed.add(name)
netcfg = 'version: 2\nethernets:\n' netcfg = 'version: 2\nethernets:\n'
for index, (_, mac, address, *gateway) in enumerate(nics): for index, (_, mac, address, *gateway) in enumerate(nics):
if kind == 'vm': if kind == 'vm':
@@ -152,7 +193,8 @@ class Lab:
self.lxc('start', f'{self.remote}:{name}') self.lxc('start', f'{self.remote}:{name}')
def ready(self, *names): 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 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. NIC takes its address from DHCP waits for any IPv4 address outside lo.
@@ -174,6 +216,15 @@ class Lab:
else: else:
print(f'{name} has no address {address or "from DHCP"}', file=sys.stderr) print(f'{name} has no address {address or "from DHCP"}', file=sys.stderr)
return False 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 return True
def nic_of(self, name, index): def nic_of(self, name, index):
@@ -204,16 +255,24 @@ class Lab:
'wireguard-tools', 'openvpn', 'curl').returncode == 0) 'wireguard-tools', 'openvpn', 'curl').returncode == 0)
def setup_run(self, name): def setup_run(self, name):
"""Run linux-manager-setup and wait for it; True when it succeeded.""" """Have linux-manager-setup run, after a run in progress, and wait for it; True when it succeeded."""
return self.on(name, 'systemctl', 'restart', 'linux-manager-setup').returncode == 0 return self.on(name, 'linux-manager-config-edit', 'apply').returncode == 0
def server(self, name, config): def server(self, name, config):
"""Install the package with the test administrator, then apply the configuration; True when both succeeded.""" """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'): if not self.push(self.deb, name, '/tmp/linux-manager.deb'):
return False 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') 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 return False
result = self.on(name, 'env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y', result = self.on(name, 'env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y',
'/tmp/linux-manager.deb') '/tmp/linux-manager.deb')
@@ -223,10 +282,10 @@ class Lab:
def render(self, name, config): def render(self, name, config):
"""Replace the server's configuration, with its placeholders filled in. """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 @PSK@ is the pre-shared key, @ETH0@ and @ETH1@ the names of the server's NICs and @CIDR0@ the network of its
network of its first address. first address; the configuration reaches the server through the Vault.
""" """
text = (TESTS / '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): for index in (0, 1):
placeholder = f'@ETH{index}@' placeholder = f'@ETH{index}@'
if placeholder in text: if placeholder in text:
@@ -236,11 +295,25 @@ class Lab:
text = text.replace(placeholder, nic) text = text.replace(placeholder, nic)
if '@CIDR0@' in text: if '@CIDR0@' in text:
text = text.replace('@CIDR0@', str(self.address(name).network)) 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): def configure(self, name, config):
"""Render the configuration and apply it twice, as the server's certificates follow the first run.""" """Render the configuration and apply it, wait for the packages of its components, and apply it again, as the
return self.render(name, config) and self.setup_run(name) and self.setup_run(name) 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): def echo_server(self, name):
"""Answer HTTP on port 8080 of the instance with the address of the client.""" """Answer HTTP on port 8080 of the instance with the address of the client."""
@@ -248,10 +321,14 @@ class Lab:
self.on(name, 'systemd-run', '--unit=lm-test-echo', 'python3', '/root/echo.py').returncode == 0) self.on(name, 'systemd-run', '--unit=lm-test-echo', 'python3', '/root/echo.py').returncode == 0)
def vpn_user(self, name): def vpn_user(self, name):
"""Add the VPN user alice, whose password is the administrator's; True when it was added.""" """Add the VPN user alice, whose password is the administrator's, read from a file the Vault gives the
return self.on(name, 'linux-manager-user', '--json', 'add', 'alice', '--first-name', 'Alice', server; True when it was added."""
'--last-name', 'Test', '--email', 'alice@example.org', secret = f'{HANDOVER_DIR}/alice.password'
input=self.admin_password + '\n').returncode == 0 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): def alice(self, name):
"""User alice from the server's user list, or None.""" """User alice from the server's user list, or None."""
@@ -259,10 +336,13 @@ class Lab:
return next((user for user in listing.get('users', []) if user.get('name') == 'alice'), None) return next((user for user in listing.get('users', []) if user.get('name') == 'alice'), None)
def wireguard_client(self, client, server, endpoint, address, allowed): 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.""" """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() The client's private key is made in the client and never leaves it; wg0.conf is completed there.
if not private_key or not public_key: """
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 return False
if not self.push(TESTS / 'wireguard_peer.py', server, '/root/wireguard_peer.py'): if not self.push(TESTS / 'wireguard_peer.py', server, '/root/wireguard_peer.py'):
return False return False
@@ -271,9 +351,14 @@ class Lab:
if not self.setup_run(server): if not self.setup_run(server):
return False return False
server_key = self.on(server, 'cat', '/etc/wireguard/wg0.pub').stdout.strip() 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') 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) self.on(client, 'bash', '/usr/bin/wg-quick', 'up', 'wg0').returncode == 0)
def wireguard_module(self, name): def wireguard_module(self, name):
@@ -291,6 +376,8 @@ class Lab:
listing = self.lxc('list', f'{self.remote}:', '-c', 'n', '-f', 'csv', check=False) listing = self.lxc('list', f'{self.remote}:', '-c', 'n', '-f', 'csv', check=False)
for name in listing.stdout.split(): for name in listing.stdout.split():
self.lxc('delete', '--force', f'{self.remote}:{name}', check=False) 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: for name in self.networks:
subprocess.run(['lxc', 'network', 'delete', f'{self.remote}:{name}'], capture_output=True) subprocess.run(['lxc', 'network', 'delete', f'{self.remote}:{name}'], capture_output=True)
self.networks = [] self.networks = []
@@ -300,39 +387,36 @@ class Lab:
def main(): def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('scenarios', nargs='+', metavar='scenario', help=f'{", ".join(SCENARIOS)} or all') 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('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--pool', default=os.environ.get('LXD_POOL'), parser.add_argument('--pool',
help='the storage pool of the project (LXD_POOL)') help='the storage pool of the project (LXD_POOL)')
parser.add_argument('--project', default=os.environ.get('LXD_TEST_PROJECT', 'lm-test'), parser.add_argument('--project', default=setting('LXD_TEST_PROJECT', 'lm-test'),
help='the project the instances live in (LXD_TEST_PROJECT, default lm-test)') help='the project the instances live in (LXD_TEST_PROJECT, default lm-test)')
parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'), parser.add_argument('--image', default=setting('LXD_IMAGE', 'ubuntu:26.04'),
help='the image of every instance (LXD_IMAGE, default 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('--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() args = parser.parse_args()
if not args.remote: try:
parser.error('--remote or LXD_REMOTE is required') args.remote = args.remote or setting('LXD_REMOTE')
if not args.pool: args.pool = args.pool or setting('LXD_POOL')
parser.error('--pool or LXD_POOL is required') except MissingSetting as missing:
parser.error(f'--{missing.name.removeprefix("LXD_").lower()} or {missing}')
scenarios = SCENARIOS if args.scenarios == ['all'] else args.scenarios scenarios = SCENARIOS if args.scenarios == ['all'] else args.scenarios
unknown = [name for name in scenarios if name not in SCENARIOS] unknown = [name for name in scenarios if name not in SCENARIOS]
if unknown: if unknown:
parser.error(f'no scenario {", ".join(unknown)}') parser.error(f'no scenario {", ".join(unknown)}')
debs = sorted((ROOT / 'out').glob('linux-manager_*_all.deb')) deb = pathlib.Path(args.deb) if args.deb else newest_deb()
if not debs: if deb is None or not deb.is_file():
sys.exit('no out/linux-manager_*_all.deb; run ./build.sh first') 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: 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') sys.exit(f'project {args.project} exists on {args.remote}; remove it or choose another with --project')
TMP.mkdir(parents=True, exist_ok=True) 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)) secrets.token_hex(16), secrets.token_hex(24))
env = ROOT / 'tmp' / 'remote-test.env' print(f'package: {deb}; remote: {args.remote}; project: {args.project}; image: {args.image}')
env.touch(mode=0o600)
env.chmod(0o600)
env.write_text(f'PSK={lab.psk}\n', encoding='utf-8')
set_dotenv({'ADMIN_USERNAME': 'admin', 'ADMIN_PASSWORD': lab.admin_password})
print(f'package: {debs[-1].name}; remote: {args.remote}; project: {args.project}; image: {args.image}')
sys.path.insert(0, str(TESTS)) sys.path.insert(0, str(TESTS))
try: try:
@@ -341,6 +425,7 @@ def main():
'-c', 'features.images=false'], capture_output=True, check=True) '-c', 'features.images=false'], capture_output=True, check=True)
print(f'== {name}') print(f'== {name}')
try: try:
lab.start_vault()
importlib.import_module(f'scenarios.{name}').run(lab) importlib.import_module(f'scenarios.{name}').run(lab)
except (subprocess.CalledProcessError, RuntimeError) as error: except (subprocess.CalledProcessError, RuntimeError) as error:
detail = error.stderr.strip() if isinstance(error, subprocess.CalledProcessError) else str(error) detail = error.stderr.strip() if isinstance(error, subprocess.CalledProcessError) else str(error)
@@ -351,8 +436,8 @@ def main():
sys.exit(130) sys.exit(130)
print(f'== passed {lab.passed}, failed {lab.failed}, skipped {lab.skipped}') 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("Not covered: IKEv2 client access, HTTPS with Let's Encrypt, passkeys, PowerDNS answering from")
print('PowerDNS answering from outside, the Azure and GCP platform modules.') print('outside, the Azure and GCP platform modules.')
sys.exit(1 if lab.failed else 0) sys.exit(1 if lab.failed else 0)
+90 -56
View File
@@ -3,34 +3,42 @@
create launches the VM --vm (lm-dev by default) on the remote --remote (LXD_REMOTE) in the project create launches the VM --vm (lm-dev by default) on the remote --remote (LXD_REMOTE) in the project
--project (LXD_PROJECT, lm-dev by default) with that project's default profile. In a test project --project (LXD_PROJECT, lm-dev by default) with that project's default profile. In a test project
made by lm-dev-lxd-project.py, which tmp/lxd-project-PROJECT.json describes, the VM gets the package 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; from that project's repository, as its apt source, so later dev builds reach it as updates;
elsewhere it gets the newest out/linux-manager_*_all.deb. The administrator is admin with a elsewhere it gets --deb, or else the package built last, in out/ or out/dev/. The administrator is admin with a
generated password, set as ADMIN_USERNAME and ADMIN_PASSWORD in the repository's .env. The VM generated password, kept as username and password in .lm-dev-config/vm-PROJECT-VM.json, and a TOTP
gets a configuration from tests/remote/configs/ (--config, core.json by default), whose @ETH0@ is token, the key VM-admin of the project's Vault's TOTP engine, unless --no-otp is given;
the interface of its default route, @CIDR0@ its network and @PSK@ a generated key, written to lm-dev-otp-code.py prints its codes. The VM gets a configuration from tests/remote/configs/
tmp/vm-VM.env. (--config, core.json by default), whose @ETH0@ is the interface of its default route, @CIDR0@ its
network and @PSK@ a generated key. 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 creates its TOTP key; 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 and 7081 of a listen address lead to The VM's leased address is pinned on its NIC, and ports 7080 and 7081 of a listen address lead to
the same ports of the VM, and port 2222 to its SSH port. In a test project the listen address is a the same ports of the VM, and port 2222 to its SSH port. In a test project the listen address is a
network forward's on the project's WAN, allocated from its uplink's routes; elsewhere NAT proxy 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 devices listen on the host address --listen (LXD_LISTEN, by default the IPv4 address of the host of
the remote's URL). remove deletes the VM, its forward and tmp/vm-VM.env; .env is left as it is. the remote's URL). remove deletes the VM, its forward, its .lm-dev-config/vm-PROJECT-VM.json and what
the Vault keeps for it. The defaults of the options come from the environment, else from
.lm-dev-config/settings.json (lm_dev.setting).
""" """
import argparse import argparse
import ipaddress import ipaddress
import json import json
import os import pathlib
import re import re
import secrets import secrets
import socket
import subprocess import subprocess
import sys import sys
import time import time
import urllib.parse
from lm_dev import PROJECT, ROOT, TESTS, lxc_exec, set_dotenv from lm_dev import HANDOVER_DIR, PROJECT, 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, the status web service and SSH. # The listen port and the VM port of each forward or proxy: the Manager, the status web service and SSH.
PORTS = ((7080, 7080), (7081, 7081), (2222, 22)) PORTS = ((7080, 7080), (7081, 7081), (2222, 22))
@@ -39,39 +47,42 @@ PORTS = ((7080, 7080), (7081, 7081), (2222, 22))
def main(): def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('action', choices=('create', 'remove')) parser.add_argument('action', choices=('create', 'remove'))
parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)') parser.add_argument('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT), parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})') help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)') parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)')
parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'), parser.add_argument('--image', default=setting('LXD_IMAGE', 'ubuntu:26.04'),
help='the image of the VM (LXD_IMAGE, default ubuntu:26.04)') help='the image of the VM (LXD_IMAGE, default ubuntu:26.04)')
parser.add_argument('--config', default='core.json', parser.add_argument('--config', default='core.json',
help='the configuration from tests/remote/configs/ (default core.json)') help='the configuration from tests/remote/configs/ (default core.json)')
parser.add_argument('--listen', default=os.environ.get('LXD_LISTEN'), parser.add_argument('--listen', default=setting('LXD_LISTEN', None),
help="outside a test project, the LXD host address the proxies listen on (LXD_LISTEN, " help="outside a test project, the LXD host address the proxies listen on (LXD_LISTEN, "
"default the IPv4 address of the remote URL's host)") "default the IPv4 address of the remote URL's host)")
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() args = parser.parse_args()
if not args.remote: try:
parser.error('--remote or LXD_REMOTE is required') args.remote = args.remote or setting('LXD_REMOTE')
project_file = ROOT / 'tmp' / f'lxd-project-{args.project}.json' 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 project = json.loads(project_file.read_text(encoding='utf-8')) if project_file.is_file() else None
if project and project['remote'] != args.remote: if project and project['remote'] != args.remote:
sys.exit(f'{project_file} is of remote {project["remote"]}, not {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: 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. # The default listen address is the IPv4 address of the remote's host in its lxc URL.
remotes = json.loads(subprocess.run(['lxc', 'remote', 'list', '--format', 'json'], capture_output=True, args.listen = host_address(args.remote)
text=True, check=True).stdout)
host = urllib.parse.urlsplit(remotes.get(args.remote, {}).get('Addr', '')).hostname
try:
args.listen = socket.getaddrinfo(host, None, socket.AF_INET)[0][4][0] if host else None
except socket.gaierror:
pass
if not args.listen: if not args.listen:
parser.error(f'no IPv4 address of the host of remote {args.remote}; give --listen or LXD_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})' 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], exists = subprocess.run(['lxc', 'info', f'{args.remote}:{args.vm}', '--project', args.project],
capture_output=True).returncode == 0 capture_output=True).returncode == 0
env = ROOT / 'tmp' / f'vm-{args.vm}.env'
def inside(*command, input=None): def inside(*command, input=None):
return lxc_exec(args.remote, args.project, args.vm, *command, input=input) return lxc_exec(args.remote, args.project, args.vm, *command, input=input)
@@ -95,7 +106,12 @@ def main():
if project and (listen := forward_of_vm()): if project and (listen := forward_of_vm()):
subprocess.run(['lxc', 'network', 'forward', 'delete', wan, listen, '--project', args.project], check=True) 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) subprocess.run(['lxc', 'delete', '--force', f'{args.remote}:{args.vm}', '--project', args.project], check=True)
env.unlink(missing_ok=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)
credentials.unlink(missing_ok=True)
print(f'removed {where}') print(f'removed {where}')
return return
@@ -104,17 +120,17 @@ def main():
config = TESTS / 'configs' / args.config config = TESTS / 'configs' / args.config
if not config.is_file(): if not config.is_file():
parser.error(f'no tests/remote/configs/{args.config}') parser.error(f'no tests/remote/configs/{args.config}')
debs = sorted((ROOT / 'out').glob('linux-manager_*_all.deb')) deb = pathlib.Path(args.deb) if args.deb else newest_deb()
if not project and not debs: if not project and (deb is None or not deb.is_file()):
sys.exit('no out/linux-manager_*_all.deb; run ./build.sh first') 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 debs[-1].name 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')
password, psk = secrets.token_hex(16), secrets.token_hex(24) password, psk = secrets.token_hex(16), secrets.token_hex(24)
env.parent.mkdir(parents=True, exist_ok=True) write_private(credentials, json.dumps({'username': 'admin', 'password': password}, indent=2) + '\n')
env.touch(mode=0o600)
env.chmod(0o600)
env.write_text(f'PSK={psk}\n', encoding='utf-8')
set_dotenv({'ADMIN_USERNAME': 'admin', 'ADMIN_PASSWORD': password})
reached = f'a forward on {project["networks"][0]}' if project else f'proxies on {args.listen}' 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}') print(f'launching {where} from {args.image} with {source}; reached through {reached}')
@@ -130,6 +146,9 @@ def main():
time.sleep(5) time.sleep(5)
else: else:
sys.exit(f'{args.vm} did not boot; remove it with remove') 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): for _ in range(24):
route = re.search(r'\bdev (\S+)', inside('ip', '-4', '-o', 'route', 'show', 'default').stdout) route = re.search(r'\bdev (\S+)', inside('ip', '-4', '-o', 'route', 'show', 'default').stdout)
address = route and re.search(r' inet (\S+) ', address = route and re.search(r' inet (\S+) ',
@@ -152,8 +171,10 @@ def main():
subprocess.run(['lxc', 'config', 'device', 'override', f'{args.remote}:{args.vm}', device, subprocess.run(['lxc', 'config', 'device', 'override', f'{args.remote}:{args.vm}', device,
f'ipv4.address={interface.ip}', '--project', args.project], check=True) f'ipv4.address={interface.ip}', '--project', args.project], check=True)
if project: if project:
# An OVN network refuses NAT proxies; the forward's listen address is allocated from the uplink's routes. # An OVN network refuses NAT proxies; the forward's listen address is --forward-address, or one allocated
subprocess.run(['lxc', 'network', 'forward', 'create', wan, '--allocate=ipv4', f'user.vm={args.vm}', # 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) '--project', args.project], check=True)
args.listen = forward_of_vm() args.listen = forward_of_vm()
if not args.listen: if not args.listen:
@@ -180,12 +201,22 @@ def main():
sys.exit(f'apt-get update failed in {args.vm}: {updated.stderr.strip()}') sys.exit(f'apt-get update failed in {args.vm}: {updated.stderr.strip()}')
package = 'linux-manager' package = 'linux-manager'
else: else:
if not push(debs[-1], '/tmp/linux-manager.deb', '0644'): if not push(deb, '/tmp/linux-manager.deb', '0644'):
sys.exit(f'could not copy {debs[-1].name} into {args.vm}') sys.exit(f'could not copy {deb} into {args.vm}')
package = '/tmp/linux-manager.deb' package = '/tmp/linux-manager.deb'
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 {password}\n') f'linux-manager linux-manager/admin_password password {password}\n')
if inside('debconf-set-selections', input=preseed).returncode != 0: 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}') sys.exit(f'debconf-set-selections failed in {args.vm}')
result = inside('env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y', package) result = inside('env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y', package)
log = ROOT / 'tmp' / f'vm-{args.vm}-install.log' log = ROOT / 'tmp' / f'vm-{args.vm}-install.log'
@@ -194,22 +225,25 @@ def main():
sys.exit(f'the package did not install; see {log}') sys.exit(f'the package did not install; see {log}')
# Apply the configuration twice, as the server's certificates follow the first run. # 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)) text = config.read_text(encoding='utf-8').replace('@ETH0@', nic).replace('@CIDR0@', str(interface.network))
.replace('@PSK@', psk)) problem = hand_over(args.remote, args.project, args.vm, vault, 'config', text.replace('@PSK@', psk),
rendered = ROOT / 'tmp' / f'vm-{args.vm}.json' '/etc/linux-manager/linux-manager.json', '0600')
rendered.touch(mode=0o600) if problem:
rendered.chmod(0o600) sys.exit(f'could not give {args.vm} {args.config}: {problem}')
rendered.write_text(text, encoding='utf-8')
pushed = push(rendered, '/etc/linux-manager/linux-manager.json', '0600')
rendered.unlink()
if not pushed:
sys.exit(f'could not copy {args.config} into {args.vm}')
for _ in range(2): for _ in range(2):
if inside('systemctl', 'restart', 'linux-manager-setup').returncode != 0: 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') 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'{args.vm} is up at {interface.ip} with {args.config}')
print(f'administrator: admin password: {password} (also in {ROOT / ".env"})') 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: http://{args.listen}:7080/ status: http://{args.listen}:7081/ ssh: {args.listen} port 2222') print(f'manager: http://{args.listen}:7080/ status: http://{args.listen}:7081/ ssh: {args.listen} port 2222')
print(f'shell: lxc exec {args.remote}:{args.vm} --project {args.project} -- su -l') 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}') print(f'remove: {sys.argv[0]} remove --remote {args.remote} --project {args.project} --vm {args.vm}')
+313 -10
View File
@@ -1,13 +1,59 @@
"""What the lm-dev scripts share: the repository's paths, lxc exec in an instance, and the .env of the repository.""" """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 pathlib
import socket
import subprocess import subprocess
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
ROOT = pathlib.Path(__file__).resolve().parent.parent ROOT = pathlib.Path(__file__).resolve().parent.parent
# The test data: scenarios, configurations, cloud-init files, the repository's script and the files copied in. # The test data: scenarios, configurations, cloud-init files, the repository's script and the files copied in.
TESTS = ROOT / 'tests' / 'remote' TESTS = ROOT / 'tests' / 'remote'
# The project of the manual tests, which lm-dev-lxd-project.py makes. # The project of the manual tests, which lm-dev-lxd-project.py makes.
PROJECT = 'lm-dev' PROJECT = 'lm-dev'
# 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): def lxc_exec(remote, project, instance, *command, input=None):
@@ -16,12 +62,269 @@ def lxc_exec(remote, project, instance, *command, input=None):
input=input, capture_output=True, text=True) input=input, capture_output=True, text=True)
def set_dotenv(values): def lxc_push(remote, project, instance, source, path, mode):
"""Set the variables in the repository's .env, readable by its owner only, keeping its other lines.""" """Copy the local file to the path in the instance with the mode; True when it was copied."""
dotenv = ROOT / '.env' return subprocess.run(['lxc', 'file', 'push', str(source), f'{remote}:{instance}{path}', '--mode', mode,
lines = dotenv.read_text(encoding='utf-8').splitlines() if dotenv.is_file() else [] '--project', project], capture_output=True, text=True).returncode == 0
kept = [line for line in lines if line.split('=', 1)[0] not in values]
dotenv.touch(mode=0o600)
dotenv.chmod(0o600) class MissingSetting(Exception):
dotenv.write_text(''.join(f'{line}\n' for line in kept + [f'{key}={value}' for key, value in values.items()]), """A setting without a default that neither the environment nor SETTINGS has; name is the setting."""
encoding='utf-8')
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 new TOTP token for the user of the VM, replacing one the user had; the problem, or None.
The VM has the Vault generate the key with its AppRole and enrols its secret with its current code; the codes are
read from the Vault (otp_code). When the user is the administrator of the VM's credentials_path, the key's otpauth
URI, read from the VM's file before it is removed, is kept there as otp_url, to add the token to an authenticator.
"""
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
steps = (('install', '-d', '-m', '0700', HANDOVER_DIR), (HELPER, 'totp', key, instance, user, target, '0600'),
*((('cat', target),) if keep else ()), ('python3', '-c', OTP_ENROL, user, target))
for command in steps:
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']
+31 -12
View File
@@ -1,11 +1,14 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""An authenticator app on the command line: make a TOTP secret or print its current code: otp.py new|code. """An authenticator app on the command line: make a TOTP secret or print its current code: otp.py new|code.
The secret, base32, is kept in the file --secret-file or OTP_FILE names, readable by its owner The secret is kept in the file --secret-file or OTP_FILE names, readable by its owner only, as
only. new makes a new secret of 20 random bytes in that file, refusing to replace one without nothing but its base32 secret, or with --url as its otpauth URI, each without a line end, so the
--force, and prints its otpauth URI, labelled with --account and --issuer when given. code prints file is a value Vault's TOTP engine imports as it is (key=@FILE or url=@FILE). new makes a new
the code of the secret now, or at the Unix time --at. The codes are RFC 6238's, with --algorithm secret of 20 random bytes in that file, refusing to replace one without --force, and prints its
(sha1 by default), --digits (6) and --period (30 seconds). 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 argparse
@@ -33,17 +36,30 @@ def code_of(secret, now=None, digits=6, period=30, algorithm='sha1'):
return f'{value % 10 ** digits:0{digits}d}' 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(): def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('action', choices=('new', 'code')) parser.add_argument('action', choices=('new', 'code'))
parser.add_argument('--secret-file', default=os.environ.get('OTP_FILE'), parser.add_argument('--secret-file', default=os.environ.get('OTP_FILE'),
help='the file of the base32 secret (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('--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('--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('--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('--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('--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('--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') parser.add_argument('--force', action='store_true', help='new: replace an existing secret')
args = parser.parse_args() args = parser.parse_args()
if not args.secret_file: if not args.secret_file:
@@ -55,21 +71,24 @@ def main():
if args.action == 'code': if args.action == 'code':
if not secret_file.is_file(): if not secret_file.is_file():
sys.exit(f'no {secret_file}; make a secret with new') sys.exit(f'no {secret_file}; make a secret with new')
print(code_of(secret_file.read_text(encoding='utf-8').strip(), args.at, args.digits, args.period, args.algorithm)) 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 return
if secret_file.exists() and not args.force: if secret_file.exists() and not args.force:
sys.exit(f'{secret_file} exists; give --force to replace its secret') sys.exit(f'{secret_file} exists; give --force to replace its secret')
secret = base64.b32encode(secrets.token_bytes(20)).decode() secret = base64.b32encode(secrets.token_bytes(20)).decode()
secret_file.parent.mkdir(parents=True, exist_ok=True)
secret_file.touch(mode=0o600)
secret_file.chmod(0o600)
secret_file.write_text(f'{secret}\n', encoding='utf-8')
label = urllib.parse.quote(':'.join(part for part in (args.issuer, args.account) if part) or 'otp') 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} query = {'secret': secret, 'algorithm': args.algorithm.upper(), 'digits': args.digits, 'period': args.period}
if args.issuer: if args.issuer:
query['issuer'] = args.issuer query['issuer'] = args.issuer
print(f'otpauth://totp/{label}?{urllib.parse.urlencode(query)}') 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__': if __name__ == '__main__':
Executable
+46
View File
@@ -0,0 +1,46 @@
#!/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 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():
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, *sys.argv[1:], '.']
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
+7
View File
@@ -67,6 +67,7 @@ fi
db_go || true db_go || true
db_input high linux-manager/local_fqdn || true db_input high linux-manager/local_fqdn || true
db_input high linux-manager/https_enabled || true
if [ "$ROUTER" = "true" ] || [ "$VPN" = "true" ]; then if [ "$ROUTER" = "true" ] || [ "$VPN" = "true" ]; then
db_input high linux-manager/local_cidrs || true db_input high linux-manager/local_cidrs || true
fi fi
@@ -84,6 +85,12 @@ if [ "$VPN" = "true" ]; then
fi fi
db_go || true db_go || true
db_get linux-manager/https_enabled
if [ "$RET" = "true" ]; then
db_input high linux-manager/https_disable_auto_redirect || true
db_go || true
fi
db_get linux-manager/pki_root db_get linux-manager/pki_root
if [ "$RET" = "local" ]; then if [ "$RET" = "local" ]; then
db_input high linux-manager/pki_root_name || true db_input high linux-manager/pki_root_name || true
+11 -11
View File
@@ -9,11 +9,6 @@ Rules-Requires-Root: no
Package: linux-manager Package: linux-manager
Architecture: all Architecture: all
Depends: ${misc:Depends}, Depends: ${misc:Depends},
strongswan-swanctl (>= 5.0),
charon-systemd (>= 5.0),
libstrongswan-extra-plugins,
libcharon-extra-plugins,
wireguard-tools,
ufw, ufw,
debconf, debconf,
ucf, ucf,
@@ -29,20 +24,25 @@ Depends: ${misc:Depends},
python3-psutil, python3-psutil,
python3-prometheus-client, python3-prometheus-client,
python3-requests, python3-requests,
caddy,
postgresql, postgresql,
slapd, slapd,
nslcd, nslcd,
libnss-ldapd, libnss-ldapd,
libpam-ldapd, libpam-ldapd,
sudo, sudo,
openvpn,
openvpn-auth-ldap,
iproute2, iproute2,
systemd-resolved, systemd-resolved,
dnsmasq-base,
zstd zstd
Recommends: bash-completion 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, rclone,
pdns-server, pdns-server,
pdns-backend-pgsql, pdns-backend-pgsql,
@@ -57,8 +57,8 @@ Description: Ubuntu Linux Manager: directory, PKI, web, optional router and VPN
user, and WireGuard; without the router its clients reach the server's 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 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 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 general use, and publishes their certificates and CRLs. Caddy, from the
the package from the Ubuntu archive or from Caddy's repository, serves HTTPS 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 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, 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 and an optional OpenID Provider signs the directory's users in to other
-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-config-edit usr/sbin/
src/usr/sbin/linux-manager-backup usr/sbin/ src/usr/sbin/linux-manager-backup usr/sbin/
src/usr/sbin/linux-manager-ca 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/sbin/linux-manager-site usr/sbin/
src/usr/lib/linux-manager/configure usr/lib/linux-manager/ src/usr/lib/linux-manager/configure usr/lib/linux-manager/
src/usr/lib/linux-manager/docker-rules usr/lib/linux-manager/ src/usr/lib/linux-manager/docker-rules usr/lib/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
+3
View File
@@ -24,6 +24,8 @@ case "$1" in
answer linux-manager/external_interface; LINUX_MANAGER_EXTERNAL_INTERFACE="$ANSWER" answer linux-manager/external_interface; LINUX_MANAGER_EXTERNAL_INTERFACE="$ANSWER"
answer linux-manager/internal_interface; LINUX_MANAGER_INTERNAL_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/local_fqdn; LINUX_MANAGER_LOCAL_FQDN="$ANSWER"
answer linux-manager/https_enabled; LINUX_MANAGER_HTTPS_ENABLED="$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_id_mode; LINUX_MANAGER_LOCAL_ID_MODE="$ANSWER"
answer linux-manager/local_cidrs; LINUX_MANAGER_LOCAL_CIDRS="$ANSWER" answer linux-manager/local_cidrs; LINUX_MANAGER_LOCAL_CIDRS="$ANSWER"
answer linux-manager/int_gateway_ip; LINUX_MANAGER_INT_GATEWAY_IP="$ANSWER" answer linux-manager/int_gateway_ip; LINUX_MANAGER_INT_GATEWAY_IP="$ANSWER"
@@ -44,6 +46,7 @@ case "$1" in
LINUX_MANAGER_ROUTER_ENABLED LINUX_MANAGER_VPN_ENABLED \ LINUX_MANAGER_ROUTER_ENABLED LINUX_MANAGER_VPN_ENABLED \
LINUX_MANAGER_EXTERNAL_INTERFACE \ LINUX_MANAGER_EXTERNAL_INTERFACE \
LINUX_MANAGER_INTERNAL_INTERFACE LINUX_MANAGER_LOCAL_FQDN \ LINUX_MANAGER_INTERNAL_INTERFACE LINUX_MANAGER_LOCAL_FQDN \
LINUX_MANAGER_HTTPS_ENABLED LINUX_MANAGER_HTTPS_DISABLE_AUTO_REDIRECT \
LINUX_MANAGER_LOCAL_ID_MODE LINUX_MANAGER_LOCAL_CIDRS \ LINUX_MANAGER_LOCAL_ID_MODE LINUX_MANAGER_LOCAL_CIDRS \
LINUX_MANAGER_INT_GATEWAY_IP \ LINUX_MANAGER_INT_GATEWAY_IP \
LINUX_MANAGER_REMOTE_ADDRS LINUX_MANAGER_REMOTE_ID \ LINUX_MANAGER_REMOTE_ADDRS LINUX_MANAGER_REMOTE_ID \
+2 -3
View File
@@ -73,7 +73,7 @@ case "$1" in
# The name service no longer looks up the console accounts of the server's directory. # The name service no longer looks up the console accounts of the server's directory.
sed -i '/^passwd:/s/ ldap\b//' /etc/nsswitch.conf sed -i '/^passwd:/s/ ldap\b//' /etc/nsswitch.conf
rm -rf /var/lib/linux-manager/backup/staging /var/lib/linux-manager/backup/restore \ 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 /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 rmdir --ignore-fail-on-non-empty /var/lib/linux-manager/backup /var/lib/linux-manager 2>/dev/null || true
@@ -100,8 +100,7 @@ case "$1" in
# in slapd, the WireGuard key pair, everything under /etc/swanctl, the # 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 # 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 # what a restore replaced are left in place. Caddy, rclone and PowerDNS
# stay installed, so Caddy's repository, which linux-manager-caddy # stay installed.
# configures, stays too.
rmdir --ignore-fail-on-non-empty /etc/linux-manager 2>/dev/null || true rmdir --ignore-fail-on-non-empty /etc/linux-manager 2>/dev/null || true
;; ;;
esac 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-bootstrap --no-enable --no-start
dh_installsystemd --name=linux-manager-backup --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-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-webdav --no-enable --no-start
dh_installsystemd --name=linux-manager-resolver --no-enable --no-start dh_installsystemd --name=linux-manager-resolver --no-enable --no-start
dh_installsystemd --name=linux-manager-install@ --no-enable --no-start dh_installsystemd --name=linux-manager-install@ --no-enable --no-start
+17
View File
@@ -95,6 +95,23 @@ Description: Local router FQDN:
router.example.com). Used as the IKEv2 server identity and router.example.com). Used as the IKEv2 server identity and
certificate common name. certificate common name.
Template: linux-manager/https_enabled
Type: boolean
Default: true
Description: Serve the status page and the Manager over HTTPS?
If enabled, Caddy serves the status page and the Manager over HTTPS for the
router FQDN, with a certificate of the Servers Issuing CA when the server
creates its root CA, and a self-signed one otherwise. The status page stays
available over plain HTTP either way.
Template: linux-manager/https_disable_auto_redirect
Type: boolean
Default: false
Description: Keep the Manager available over plain HTTP?
If enabled, the Manager answers on its plain HTTP port. Otherwise, while
HTTPS is on, it redirects there to its HTTPS address. The status page never
redirects.
Template: linux-manager/local_id_mode Template: linux-manager/local_id_mode
Type: select Type: select
Choices: fqdn, public_ip, internal_ip Choices: fqdn, public_ip, internal_ip
@@ -7,8 +7,8 @@ this script never writes to /etc and never has to worry about destroying an
administrator's edits. administrator's edits.
The candidate is the current /etc/linux-manager/linux-manager.json as it is, or the 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 shipped defaults when there is none, with https.certificate empty for the first
written over it. Without an answer that changes it, the candidate is the current 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 file byte for byte, so
an upgrade or a reconfiguration that changes nothing gives ucf nothing to ask; 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 defaults the file leaves out are applied by linuxmanager.load_config() when the
@@ -43,6 +43,8 @@ ANSWERS = {
'LINUX_MANAGER_EXTERNAL_INTERFACE': (('interfaces', 'external'),), 'LINUX_MANAGER_EXTERNAL_INTERFACE': (('interfaces', 'external'),),
'LINUX_MANAGER_INTERNAL_INTERFACE': (('interfaces', 'internal'),), 'LINUX_MANAGER_INTERNAL_INTERFACE': (('interfaces', 'internal'),),
'LINUX_MANAGER_LOCAL_FQDN': (('wan', 'local_fqdn'),), 'LINUX_MANAGER_LOCAL_FQDN': (('wan', 'local_fqdn'),),
'LINUX_MANAGER_HTTPS_ENABLED': (('https', 'enabled'),),
'LINUX_MANAGER_HTTPS_DISABLE_AUTO_REDIRECT': (('https', 'disable_auto_redirect'),),
'LINUX_MANAGER_LOCAL_ID_MODE': ((*FIRST, 'local_id_mode'),), 'LINUX_MANAGER_LOCAL_ID_MODE': ((*FIRST, 'local_id_mode'),),
'LINUX_MANAGER_LOCAL_CIDRS': (('local', 'cidrs'), (*FIRST, 'local_cidrs')), 'LINUX_MANAGER_LOCAL_CIDRS': (('local', 'cidrs'), (*FIRST, 'local_cidrs')),
'LINUX_MANAGER_INT_GATEWAY_IP': (('local', 'int_gateway_ip'),), 'LINUX_MANAGER_INT_GATEWAY_IP': (('local', 'int_gateway_ip'),),
@@ -73,6 +75,8 @@ def main():
current = None current = None
if current is None: if current is None:
cfg = linuxmanager.load_config() cfg = linuxmanager.load_config()
# A new installation leaves the source of the HTTPS certificate to its first setup.
cfg['https']['certificate'] = ''
else: else:
try: try:
cfg = json.loads(current) cfg = json.loads(current)
@@ -1,19 +1,31 @@
#!/usr/bin/python3 #!/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 Run by linux-manager-install@<component>.service, which linux-manager-setup starts when the component is on and its
missing: webdav (rclone) and dns (PowerDNS with its gpgsql backend). Recommended packages are left out, so PowerDNS packages are missing or marked as installed automatically: the components and their packages are
comes without its bind backend. A failure is a message on standard error and the exit status 1. 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 os
import subprocess import subprocess
import sys import sys
#: The packages of each feature. sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
FEATURES = {'webdav': ['rclone'], 'dns': ['pdns-server', 'pdns-backend-pgsql']}
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-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'] 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: if len(sys.argv) != 2 or sys.argv[1] not in FEATURES:
sys.exit(f'usage: install-packages {"|".join(FEATURES)}') sys.exit(f'usage: install-packages {"|".join(FEATURES)}')
environment = dict(os.environ, DEBIAN_FRONTEND='noninteractive') 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', 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]]]): '-o', 'Dpkg::Options::=--force-confold', 'install', *FEATURES[sys.argv[1]]]):
print(f'$ {" ".join(args)}', flush=True) print(f'$ {" ".join(args)}', flush=True)
if subprocess.run(args, env=environment).returncode != 0: if subprocess.run(args, env=environment).returncode != 0:
sys.exit(f'install-packages: {args[0]} failed') 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 return 0
@@ -12,8 +12,10 @@ import os
import pathlib import pathlib
import re import re
import shutil import shutil
import subprocess
import sys import sys
import tempfile import tempfile
import time
import urllib.parse import urllib.parse
import jinja2 import jinja2
@@ -27,12 +29,21 @@ import linuxmanager_ldap
import linuxmanager_pki import linuxmanager_pki
import linuxmanager_platforms import linuxmanager_platforms
import linuxmanager_status 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_FILE = pathlib.Path('/etc/linux-manager/linux-manager.json')
CONFIG_LOCK = pathlib.Path('/run/linux-manager/config.lock') CONFIG_LOCK = pathlib.Path('/run/linux-manager/config.lock')
#: What setup resolved and runs, for the web service (setup's refresh_web). #: What setup resolved and runs, for the web service (setup's refresh_web).
WEB_STATE = pathlib.Path('/run/linux-manager/web.json') 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') TEMPLATE_DIR = pathlib.Path('/usr/share/linux-manager/templates')
SWANCTL_CONF_D = pathlib.Path('/etc/swanctl/conf.d') SWANCTL_CONF_D = pathlib.Path('/etc/swanctl/conf.d')
@@ -68,14 +79,17 @@ SCHEMA = {
'status_content': 'basic', 'shell': False, 'shell_idle_minutes': 15, 'shell_auth_timeout': 15, 'status_content': 'basic', 'shell': False, 'shell_idle_minutes': 15, 'shell_auth_timeout': 15,
'log_files': []}, 'log_files': []},
'ssh': {'ldap_login': False}, 'ssh': {'ldap_login': False},
'https': {'enabled': True, 'email': '', 'web_port': 7444, 'manager_port': 7443, 'caddy_source': 'ubuntu', 'https': {'enabled': True, 'email': '', 'web_port': 7444, 'manager_port': 7443,
'acme_staging': 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}, 'oidc': {'enabled': False},
'sites': {'enabled': False, 'upload_max_mb': 512, 'webdav': False, 'webdav_port': 7445}, 'sites': {'enabled': False, 'upload_max_mb': 512, 'webdav': False, 'webdav_port': 7445},
'dns': {'enabled': False, 'secondary': '', 'listen': 'external', 'ttl': 300}, 'dns': {'enabled': False, 'secondary': '', 'listen': 'external', 'ttl': 300},
'pki': {'root_name': 'Linux Manager Root CA', 'root_days': 7300, 'ca_days': 3650, 'key': 'rsa-4096', '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', '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': {}, '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': ''}, 'extended_key_usages': {}, 'root': 'local', 'simple_ca_url': ''},
'metrics': {'enabled': True, 'listen': 'internal', 'port': 9464, 'https_port': 9465, 'service_account': 'metrics', 'metrics': {'enabled': True, 'listen': 'internal', 'port': 9464, 'https_port': 9465, 'service_account': 'metrics',
'otlp_endpoint': '', 'otlp_username': '', 'otlp_password': '', 'otlp_endpoint': '', 'otlp_username': '', 'otlp_password': '',
@@ -143,6 +157,16 @@ LOG_FILES_MAX = 32
#: The port rclone serves WebDAV on, on the loopback address, behind Caddy. #: The port rclone serves WebDAV on, on the loopback address, behind Caddy.
WEBDAV_LOOPBACK_PORT = 7446 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. #: The largest sites.upload_max_mb, 10 GiB.
UPLOAD_MAX_MB = 10240 UPLOAD_MAX_MB = 10240
@@ -167,17 +191,20 @@ BOOTSTRAP_PORTS = (17081,)
MANAGER_CONFIG = pathlib.Path('/etc/linux-manager/manager.json') MANAGER_CONFIG = pathlib.Path('/etc/linux-manager/manager.json')
MANAGER_PORT = 7080 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. #: 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' 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. #: The ACME directory of Let's Encrypt's production CA.
CADDY_APT_SOURCE = pathlib.Path('/etc/apt/sources.list.d/caddy-stable.sources') ACME_PRODUCTION_CA = 'https://acme-v02.api.letsencrypt.org/directory'
CADDY_KEYRING = pathlib.Path('/etc/apt/keyrings/caddy-stable.asc')
CADDY_KEY_URL = 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' #: Where the certificate of wan.local_fqdn comes from, https.certificate: ACME, a self-signed certificate, the
CADDY_REPOSITORY = 'https://dl.cloudsmith.io/public/caddy/stable/deb/debian' #: 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. #: The key types of the CAs, pki.key, and of the templates.
PKI_KEYS = ('rsa-2048', 'rsa-3072', 'rsa-4096', 'ec-p256', 'ec-p384') PKI_KEYS = ('rsa-2048', 'rsa-3072', 'rsa-4096', 'ec-p256', 'ec-p384')
@@ -224,7 +251,7 @@ PKI_TEMPLATES = {
'vpn-server': {'key_usage': ['digital_signature', 'key_encipherment'], 'vpn-server': {'key_usage': ['digital_signature', 'key_encipherment'],
'extended_key_usage': ['server_auth', 'ike_intermediate'], 'subject': 'dns', 'sans': ['dns', 'ip']}, 'extended_key_usage': ['server_auth', 'ike_intermediate'], 'subject': 'dns', 'sans': ['dns', 'ip']},
'vpn-user': {'extended_key_usage': ['client_auth'], 'subject': 'name', 'sans': ['dns', 'email']}, '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']}, 'extended_key_usage': ['server_auth', 'client_auth'], 'subject': 'dns', 'sans': ['dns', 'ip']},
'server': {'key_usage': ['digital_signature', 'key_encipherment'], 'extended_key_usage': ['server_auth'], 'server': {'key_usage': ['digital_signature', 'key_encipherment'], 'extended_key_usage': ['server_auth'],
'subject': 'dns', 'sans': ['dns', 'ip']}, 'subject': 'dns', 'sans': ['dns', 'ip']},
@@ -234,8 +261,11 @@ PKI_TEMPLATES = {
#: The templates only the server issues: its VPN server certificate and the users' certificates. #: The templates only the server issues: its VPN server certificate and the users' certificates.
ROUTER_TEMPLATES = ('vpn-server', 'vpn-user') 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. #: The built-in issuing CAs: name -> the pki option of the common name and the templates the CA issues: the VPN, the
BUILTIN_CAS = {'p2s': ('p2s_name', ['vpn-server', 'vpn-user']), 's2s': ('s2s_name', ['site-to-site'])} #: 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. #: 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} ISSUING_CA = {'name': '', 'templates': [], 'acme': False}
@@ -350,6 +380,45 @@ def config_lock():
yield 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): def save_config(data):
"""Write the settings to the configuration file, indented, with mode 0600, replacing it in one step. """Write the settings to the configuration file, indented, with mode 0600, replacing it in one step.
@@ -366,6 +435,19 @@ def save_config(data):
raise 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): def _split_list(value):
return [item.strip() for item in value.split(',') if item.strip()] return [item.strip() for item in value.split(',') if item.strip()]
@@ -586,9 +668,24 @@ def validate(cfg):
if not item.startswith('/') or '/../' in f'{item}/': if not item.startswith('/') or '/../' in f'{item}/':
raise ConfigError(f'web.log_files: {item!r} is not an absolute path') raise ConfigError(f'web.log_files: {item!r} is not an absolute path')
caddy_source = _get(cfg, 'https', 'caddy_source') if _get(cfg, 'https', 'certificate') not in ('', *HTTPS_CERTIFICATES):
if caddy_source not in CADDY_SOURCES: raise ConfigError(f'https.certificate: {_get(cfg, "https", "certificate")!r} is not one of '
raise ConfigError(f'https.caddy_source: {caddy_source!r} is not one of {", ".join(CADDY_SOURCES)}') 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, 'oidc', 'enabled') and not (_get(cfg, 'web', 'enabled') and _get(cfg, 'https', 'enabled') if _get(cfg, 'oidc', 'enabled') and not (_get(cfg, 'web', 'enabled') and _get(cfg, 'https', 'enabled')
and _get(cfg, 'wan', 'local_fqdn')): and _get(cfg, 'wan', 'local_fqdn')):
@@ -634,7 +731,7 @@ def validate(cfg):
f'addresses is the resolver of the remote access clients (p2s.dns_listen {resolver_listen}) ' 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') '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) value = _get(cfg, 'pki', option)
if not value or len(value) > CA_NAME_MAX or not value.isprintable(): 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') raise ConfigError(f'pki.{option} must have 1 to {CA_NAME_MAX} printable characters')
@@ -703,8 +800,8 @@ def validate(cfg):
prefix = f'pki.issuing_cas.{name}' prefix = f'pki.issuing_cas.{name}'
if not PKI_NAME.match(name) or name in BUILTIN_CAS or name in ('root', 'upstream'): 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 ' 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, upstream, ' f'lowercase letters, digits and hyphens, and is not root, upstream or '
f'{" or ".join(BUILTIN_CAS)}') f'{", ".join(BUILTIN_CAS)}')
if not isinstance(authority, dict): if not isinstance(authority, dict):
raise ConfigError(f'{prefix} must be {TYPE_NAMES[dict]}') raise ConfigError(f'{prefix} must be {TYPE_NAMES[dict]}')
_check_options(authority, ISSUING_CA, prefix) _check_options(authority, ISSUING_CA, prefix)
@@ -727,6 +824,15 @@ def validate(cfg):
taken = {web_port: 'web.port', ACME_HTTP_PORT: 'the HTTP challenge', taken = {web_port: 'web.port', ACME_HTTP_PORT: 'the HTTP challenge',
https_ports[0]: 'https.web_port', https_ports[1]: 'https.manager_port'} https_ports[0]: 'https.web_port', https_ports[1]: 'https.manager_port'}
# 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
if 'https-default' in publish: if 'https-default' in publish:
if HTTPS_DEFAULT_PORT in taken: if HTTPS_DEFAULT_PORT in taken:
raise ConfigError(f'pki.publish: https-default takes port {HTTPS_DEFAULT_PORT}, the port of ' raise ConfigError(f'pki.publish: https-default takes port {HTTPS_DEFAULT_PORT}, the port of '
@@ -813,13 +919,12 @@ def validate(cfg):
f'docker.exposed_ports: {item!r} is not a port or a port range') f'docker.exposed_ports: {item!r} is not a port or a port range')
weight += 2 if ':' in item else 1 weight += 2 if ':' in item else 1
first, _, last = item.partition(':') first, _, last = item.partition(':')
if _get(cfg, 'https', 'enabled'): caddy_ports = (web_port, manager_port(), _get(cfg, 'metrics', 'port'),
caddy_ports = (ACME_HTTP_PORT, *https_ports, *([HTTPS_DEFAULT_PORT] if 'https-default' in publish else [])) *((ACME_HTTP_PORT, *https_ports, *([HTTPS_DEFAULT_PORT] if 'https-default' in publish else []))
for port in caddy_ports: if _get(cfg, 'https', 'enabled') else ()))
if int(first) <= port <= int(last or first): for port in caddy_ports:
raise ConfigError( if int(first) <= port <= int(last or first):
f'docker.exposed_ports: {item!r} takes port {port}, which Caddy serves while ' raise ConfigError(f'docker.exposed_ports: {item!r} takes port {port}, which Caddy serves')
'https.enabled is true')
if weight > DOCKER_PORT_LIMIT: if weight > DOCKER_PORT_LIMIT:
raise ConfigError( raise ConfigError(
f'docker.exposed_ports: at most {DOCKER_PORT_LIMIT} ports are allowed, ' f'docker.exposed_ports: at most {DOCKER_PORT_LIMIT} ports are allowed, '
@@ -847,8 +952,8 @@ def extended_key_usages(cfg):
def issuing_cas(cfg): def issuing_cas(cfg):
"""The issuing CAs, name -> {name, templates, acme, builtin}: p2s and s2s (BUILTIN_CAS) with their common names from """The issuing CAs, name -> {name, templates, acme, builtin}: p2s, s2s and servers (BUILTIN_CAS) with their common names
the pki section, then those of pki.issuing_cas, each filled from ISSUING_CA.""" 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} found = {name: {'name': _get(cfg, 'pki', option), 'templates': list(templates), 'acme': False, 'builtin': True}
for name, (option, templates) in BUILTIN_CAS.items()} for name, (option, templates) in BUILTIN_CAS.items()}
for name, options in cfg['pki']['issuing_cas'].items(): for name, options in cfg['pki']['issuing_cas'].items():
@@ -870,7 +975,8 @@ def pki_base_urls(cfg):
def manager_port(): 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: try:
port = json.loads(MANAGER_CONFIG.read_text(encoding='utf-8')).get('port') port = json.loads(MANAGER_CONFIG.read_text(encoding='utf-8')).get('port')
except (OSError, ValueError, AttributeError): except (OSError, ValueError, AttributeError):
@@ -878,6 +984,16 @@ def manager_port():
return port if isinstance(port, int) and not isinstance(port, bool) and 1 <= port <= 65535 else 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): 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, without the port when it is HTTPS_DEFAULT_PORT."""
port = _get(cfg, 'https', 'web_port') port = _get(cfg, 'https', 'web_port')
@@ -1034,6 +1150,8 @@ def build_context(cfg, public_ip=None):
'mode': _get(cfg, 'general', 'mode') or 'manual', 'mode': _get(cfg, 'general', 'mode') or 'manual',
'router_enabled': _get(cfg, 'router', 'enabled'), 'router_enabled': _get(cfg, 'router', 'enabled'),
'vpn_enabled': _get(cfg, 'vpn', '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, 'wan_iface': ext_iface,
'int_iface': int_iface, 'int_iface': int_iface,
'local_addrs': ', '.join(local_addrs), 'local_addrs': ', '.join(local_addrs),
@@ -1080,15 +1198,24 @@ def build_context(cfg, public_ip=None):
'ldap_users': linuxmanager_ldap.USERS, 'ldap_users': linuxmanager_ldap.USERS,
'web_enabled': _get(cfg, 'web', 'enabled'), 'web_enabled': _get(cfg, 'web', 'enabled'),
'web_port': _get(cfg, 'web', 'port'), 'web_port': _get(cfg, 'web', 'port'),
'web_listen': _get(cfg, 'web', 'listen'),
'https_enabled': _get(cfg, 'https', 'enabled'), 'https_enabled': _get(cfg, 'https', 'enabled'),
'https_email': _get(cfg, 'https', 'email'), '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_web_port': _get(cfg, 'https', 'web_port'),
'https_manager_port': _get(cfg, 'https', 'manager_port'), 'https_manager_port': _get(cfg, 'https', 'manager_port'),
'pki_publish': _get_list(cfg, 'pki', 'publish'), 'pki_publish': _get_list(cfg, 'pki', 'publish'),
'pki_acme': [name for name, authority in issuing_cas(cfg).items() if authority['acme']], 'pki_acme': [name for name, authority in issuing_cas(cfg).items() if authority['acme']],
'metrics_enabled': _get(cfg, 'metrics', 'enabled'), 'metrics_enabled': _get(cfg, 'metrics', 'enabled'),
'metrics_port': _get(cfg, 'metrics', 'port'), 'metrics_port': _get(cfg, 'metrics', 'port'),
'metrics_listen': _get(cfg, 'metrics', 'listen'),
'metrics_https_port': _get(cfg, 'metrics', 'https_port'), 'metrics_https_port': _get(cfg, 'metrics', 'https_port'),
'metrics_service_account': _get(cfg, 'metrics', 'service_account'), 'metrics_service_account': _get(cfg, 'metrics', 'service_account'),
'sites_enabled': _get(cfg, 'sites', 'enabled'), 'sites_enabled': _get(cfg, 'sites', 'enabled'),
@@ -1101,8 +1228,8 @@ def build_context(cfg, public_ip=None):
def s2s_ready(ctx): def s2s_ready(ctx):
"""True when the router is on and any site_to_site connection is ready.""" """True when the router is on and installed and any site_to_site connection is ready."""
return bool(ctx['router_enabled'] and any(connection['ready'] for connection in ctx['connections'])) return bool(ctx['router_enabled'] and ctx['router_installed'] and any(connection['ready'] for connection in ctx['connections']))
def routing_ready(ctx): def routing_ready(ctx):
@@ -1112,19 +1239,21 @@ def routing_ready(ctx):
def p2s_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.""" """IKEv2 access needs the VPN on and installed, its settings and the server's VPN server certificate, which the P2S
return bool(ctx['vpn_enabled'] and ctx['p2s_enabled'] and ctx['p2s_address_pool'] and ctx['local_fqdn'] 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']) and ctx['server_certificate'])
def wg_ready(ctx): def wg_ready(ctx):
"""WireGuard needs the VPN on and its settings.""" """WireGuard needs the VPN on and installed and its settings."""
return bool(ctx['vpn_enabled'] and ctx['wg_enabled'] and ctx['wg_address']) return bool(ctx['vpn_enabled'] and ctx['vpn_installed'] and ctx['wg_enabled'] and ctx['wg_address'])
def openvpn_ready(ctx): def openvpn_ready(ctx):
"""OpenVPN needs the VPN on, its settings and the server's VPN server certificate, which the P2S CA issues.""" """OpenVPN needs the VPN on and installed, its settings and the server's VPN server certificate, which the P2S CA
return bool(ctx['vpn_enabled'] and ctx['openvpn_enabled'] and ctx['openvpn_pool'] and ctx['local_fqdn'] 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']) and ctx['server_certificate'])
@@ -1150,6 +1279,25 @@ def webdav_ready(ctx):
return bool(ctx['webdav_enabled'] and https_ready(ctx)) return bool(ctx['webdav_enabled'] and https_ready(ctx))
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): def dns_ready(ctx):
"""The name server answers for its domains while dns.enabled is true.""" """The name server answers for its domains while dns.enabled is true."""
return bool(ctx['dns_enabled']) return bool(ctx['dns_enabled'])
@@ -1276,6 +1424,9 @@ def configure(cfg=None, public_ip=None):
fail(str(failure)) fail(str(failure))
except ldap.LDAPError as exc: except ldap.LDAPError as exc:
notices = [f'the PKI is left as it is: the directory cannot be reached: {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: for notice in notices:
warn(notice) warn(notice)
# The WireGuard peers of the users; None keeps those of wg0.conf while the directory cannot be reached. # 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: if result.returncode != 0:
raise Failure(f'pg_restore of {item} failed: {result.stderr.decode(errors="replace").strip()}') 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) 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: for unit in RESTORE_RESTARTS:
subprocess.run(['systemctl', 'try-restart', unit], capture_output=True) subprocess.run(['systemctl', 'try-restart', unit], capture_output=True)
subprocess.run(['ufw', 'reload'], capture_output=True) subprocess.run(['ufw', 'reload'], capture_output=True)
@@ -255,11 +255,11 @@ def domain_remove(name):
def secondary_addresses(cfg): def secondary_addresses(cfg):
"""The addresses dns.secondary resolves to, which are notified of the zones' changes and may transfer them; none, """The addresses dns.secondary resolves to, which are notified of the zones' changes and may transfer them; none while
with a warning, while it is not set or does not resolve.""" 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() secondary = cfg['dns']['secondary'].strip()
if not secondary: if not secondary:
linuxmanager.warn('dns.secondary is not set: the domains have no secondary name server')
return [] return []
try: try:
found = socket.getaddrinfo(secondary, 53, proto=socket.IPPROTO_UDP) found = socket.getaddrinfo(secondary, 53, proto=socket.IPPROTO_UDP)
@@ -84,7 +84,10 @@ OVERLAYS = ('ppolicy', 'otp')
#: certificate and CRL (cACertificate and certificateRevocationList of RFC 4523), its key, the #: certificate and CRL (cACertificate and certificateRevocationList of RFC 4523), its key, the
#: CSR it waits with for its certificate, the number of its last CRL, where the CRL came from, #: CSR it waits with for its certificate, the number of its last CRL, where the CRL came from,
#: and when it was retired; the root also holds the Simple CA token, linuxManagerToken, and the #: and when it was retired; the root also holds the Simple CA token, linuxManagerToken, and the
#: name of the Simple CA issuing CA that signs with it, linuxManagerUpstreamName. linuxManagerCertificate is a certificate a CA issued, named by its #: name of the Simple CA issuing CA that signs with it, linuxManagerUpstreamName.
#: linuxManagerHostCertificate, cn=https, is the server's HTTPS certificate when no ACME CA or
#: issuing CA gives it: the certificate with its chain, its key, the CSR waiting for a certificate
#: of another CA and that CSR's key, and its kind, self-signed or external. 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' #: 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. #: certificates, its kind, template, names and expiry, and its revocation.
SCHEMA_OID = '1.3.6.1.4.1.67380.10.1.2' SCHEMA_OID = '1.3.6.1.4.1.67380.10.1.2'
@@ -134,6 +137,9 @@ SCHEMA_ATTRIBUTE_TYPES = (
f"{_OCTETS} )", f"{_OCTETS} )",
f"( {SCHEMA_OID}.1.25 NAME 'linuxManagerUpstreamName' DESC 'Linux Manager: the Simple CA issuing CA of the token' " f"( {SCHEMA_OID}.1.25 NAME 'linuxManagerUpstreamName' DESC 'Linux Manager: the Simple CA issuing CA of the token' "
f"{_STRING} )", f"{_STRING} )",
f"( {SCHEMA_OID}.1.26 NAME 'linuxManagerCertificateChain' DESC 'Linux Manager: a certificate and its chain, PEM' "
f"{_OCTETS} )",
f"( {SCHEMA_OID}.1.27 NAME 'linuxManagerRequestKey' DESC 'Linux Manager: the private key of a CSR, PEM' {_OCTETS} )",
) )
SCHEMA_OBJECT_CLASSES = ( SCHEMA_OBJECT_CLASSES = (
f"( {SCHEMA_OID}.2.1 NAME 'linuxManagerAccount' DESC 'Linux Manager: properties of a user or a Manager-only account' " f"( {SCHEMA_OID}.2.1 NAME 'linuxManagerAccount' DESC 'Linux Manager: properties of a user or a Manager-only account' "
@@ -150,6 +156,9 @@ SCHEMA_OBJECT_CLASSES = (
"linuxManagerSubjectAltName $ linuxManagerNotAfter $ linuxManagerRevoked $ linuxManagerRevocationReason ) )", "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 " 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 ) )", "STRUCTURAL MUST cn MAY ( description $ member ) )",
f"( {SCHEMA_OID}.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 ) )",
) )
#: The TOTP parameters: digits, the OID of HMAC-SHA1, seconds per time step, and the time steps accepted before and after now. #: The TOTP parameters: digits, the OID of HMAC-SHA1, seconds per time step, and the time steps accepted before and after now.
@@ -173,7 +182,7 @@ CONSOLE_HOMES = '/home'
#: The ACLs of the database, in order. #: The ACLs of the database, in order.
ACCESS = ( ACCESS = (
'to attrs=linuxManagerPrivateKey,linuxManagerToken by * none', 'to attrs=linuxManagerPrivateKey,linuxManagerToken,linuxManagerRequestKey by * none',
f'to attrs=userPassword by dn.exact="{MANAGER}" =wx by self =wx by anonymous auth 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 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="{USERS}" by dn.exact="{MANAGER}" manage by * read',
@@ -7,15 +7,22 @@ this module too.
import pathlib import pathlib
import subprocess 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') 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' 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' 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): class ConfigError(Exception):
"""A setting is present but malformed.""" """A setting is present but malformed."""
@@ -68,6 +75,12 @@ def _is_virtual(name):
return '/devices/virtual/' in str(link.resolve()) 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(): def _addressed_interfaces():
"""Names of the NICs holding at least one IPv4 address; virtual interfaces are left out.""" """Names of the NICs holding at least one IPv4 address; virtual interfaces are left out."""
names = [] 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 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 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. Without the router (router.enabled false) the external interface is also the internal side.
""" """
if choice not in LISTEN_CHOICES: 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)) return list(dict.fromkeys(address for address in addresses if address))
def web_listen(configuration, default_port): def web_listen(configuration):
"""Where the web service listens, from linux-manager.json read as configuration, as ([(address, port), ...], ''). """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."""
The addresses are those of the interfaces web.listen names (listen_addresses), then if _section(configuration, 'web').get('enabled', True) is False:
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:
return [], 'the web service is disabled in the configuration' return [], 'the web service is disabled in the configuration'
port = web.get('port', default_port) return [(LOOPBACK, WEB_LOOPBACK_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]], ''
@@ -1,7 +1,8 @@
"""The server's PKI, for linux-manager-setup, the web service, linux-manager-ca and the user module. """The server's PKI, for linux-manager-setup, the web service, linux-manager-ca and the user module.
The root CA signs the issuing CAs, and only them: p2s, which signs the server's VPN server certificate and the users' The root CA signs the issuing CAs, and only them: p2s, which signs the server's VPN server certificate and the users'
certificates, s2s, which signs the server's site-to-site certificate and those of its peers, and the general-purpose certificates, s2s, which signs the server's site-to-site certificate and those of its peers, servers, the Servers Issuing
CA of mTLS certificates, which signs the server's HTTPS certificate with https.certificate ca, and the general-purpose
CAs of pki.issuing_cas. The PKI is kept in ou=pki of the server's directory (linuxmanager_ldap), which root reaches through CAs of pki.issuing_cas. The PKI is kept in ou=pki of the server's directory (linuxmanager_ldap), which root reaches through
the local socket. Each CA is an entry cn=<name> of class linuxManagerAuthority, with its certificate, key, CRL and CRL the local socket. Each CA is an entry cn=<name> of class linuxManagerAuthority, with its certificate, key, CRL and CRL
number. Each certificate a CA issued is an entry serialNumber=<serial> of class linuxManagerCertificate under the CA, number. Each certificate a CA issued is an entry serialNumber=<serial> of class linuxManagerCertificate under the CA,
@@ -101,7 +102,12 @@ OPENVPN_CRL = pathlib.Path('/etc/openvpn/server/linux-manager-crl.pem')
TRUST_ANCHOR = pathlib.Path('/usr/local/share/ca-certificates/linux-manager-ca.crt') TRUST_ANCHOR = pathlib.Path('/usr/local/share/ca-certificates/linux-manager-ca.crt')
#: The server's own certificates: name -> the issuing CA and the template, and the files strongSwan reads. #: The server's own certificates: name -> the issuing CA and the template, and the files strongSwan reads.
ROUTER_CERTS = {'vpn-server': ('p2s', 'vpn-server'), 'site-to-site': ('s2s', 'site-to-site')} ROUTER_CERTS = {'vpn-server': ('p2s', 'vpn-server'), 'site-to-site': ('s2s', 'mtls'), 'https': ('servers', 'mtls')}
#: The server's HTTPS certificate when it is self-signed or of another CA, and the attributes of its entry.
HOST_DN = f'cn=https,{linuxmanager_ldap.PKI}'
HOST_ATTRIBUTES = ['linuxManagerCertificateChain', 'linuxManagerPrivateKey', 'linuxManagerCertificateRequest',
'linuxManagerRequestKey', 'linuxManagerKind']
#: The component, a section of the configuration, that a built-in issuing CA and the server's certificate it issues #: The component, a section of the configuration, that a built-in issuing CA and the server's certificate it issues
#: belong to: provision creates them only while the component's enabled is true. #: belong to: provision creates them only while the component's enabled is true.
@@ -586,11 +592,11 @@ def is_address(value):
def router_identities(name, ctx): def router_identities(name, ctx):
"""The common name and the subject alternative names of one of the server's certificates (ROUTER_CERTS): the VPN """The common name and the subject alternative names of one of the server's certificates (ROUTER_CERTS): the VPN
server certificate names wan.local_fqdn, and the site-to-site certificate also the local identity of each server and the HTTPS certificates name wan.local_fqdn, and the site-to-site certificate also the local identity of each
site_to_site connection with certificate authentication, the public or the internal address of its site_to_site connection with certificate authentication, the public or the internal address of its
local_id_mode; None while such an identity is not known yet.""" local_id_mode; None while such an identity is not known yet."""
fqdn = ctx['local_fqdn'] fqdn = ctx['local_fqdn']
if name == 'vpn-server': if name in ('vpn-server', 'https'):
return fqdn, [fqdn] return fqdn, [fqdn]
names = [fqdn] names = [fqdn]
for connection in ctx['connections']: for connection in ctx['connections']:
@@ -663,6 +669,22 @@ def check_source(cfg, entry):
'root is fixed once the root exists', 4) 'root is fixed once the root exists', 4)
def check_names(cfg, connection):
"""Refuse a CA name of the configuration that differs from the common name of the CA's certificate or CSR: the
name of a CA is fixed once the CA has its key. pki.root_name counts for a root the server created only."""
options = {name: f'pki.{option}' for name, (option, _) in linuxmanager.BUILTIN_CAS.items()}
names = {name: (options.get(name, f'pki.issuing_cas.{name}.name'), settings['name'].strip())
for name, settings in linuxmanager.issuing_cas(cfg).items()}
if cfg['pki']['root'] == 'local':
names['root'] = ('pki.root_name', cfg['pki']['root_name'].strip())
for name, (option, wanted) in names.items():
entry = authority(connection, name)
made = entry and (entry['cert'] or (x509.load_pem_x509_csr(entry['csr']) if entry['csr'] else None))
if made and common_name(made) != wanted:
raise Failure(f'{option} is {wanted!r}, but CA {name} was made as {common_name(made)!r}; the name of a CA '
'is fixed once the CA exists', 4)
def jwt_part(text): def jwt_part(text):
return base64.urlsafe_b64decode(text + '=' * (-len(text) % 4)) return base64.urlsafe_b64decode(text + '=' * (-len(text) % 4))
@@ -843,6 +865,188 @@ def fetch_crls(connection):
return notices return notices
def host_entry(connection):
"""The server's HTTPS certificate kept at HOST_DN: {chain, key, csr (PEM), request_key, kind}, None when there is
none; chain is the certificate followed by its chain."""
try:
attributes = connection.search_s(HOST_DN, ldap.SCOPE_BASE, attrlist=HOST_ATTRIBUTES)[0][1]
except ldap.NO_SUCH_OBJECT:
return None
chain, key, request_key = (first(attributes, name) for name in
('linuxManagerCertificateChain', 'linuxManagerPrivateKey', 'linuxManagerRequestKey'))
return {
'chain': x509.load_pem_x509_certificates(chain) if chain else [],
'key': serialization.load_pem_private_key(key, None) if key else None,
'csr': first(attributes, 'linuxManagerCertificateRequest'),
'request_key': serialization.load_pem_private_key(request_key, None) if request_key else None,
'kind': (first(attributes, 'linuxManagerKind') or b'').decode() or None,
}
def update_host(connection, values):
"""Set attributes of HOST_DN, adding the entry when it is missing; a value None removes its attribute."""
try:
connection.search_s(HOST_DN, ldap.SCOPE_BASE, attrlist=['1.1'])
except ldap.NO_SUCH_OBJECT:
connection.add_s(HOST_DN, ldap.modlist.addModlist({
'objectClass': [b'linuxManagerHostCertificate'], 'cn': [b'https'],
**{attribute: [value] for attribute, value in values.items() if value is not None}}))
return
connection.modify_s(HOST_DN, [(ldap.MOD_REPLACE, attribute, [value] if value is not None else [])
for attribute, value in values.items()])
def covers(cert, fqdn):
"""Whether a DNS name of the certificate is fqdn, or a wildcard of one label that matches it."""
for value in san_values(cert):
kind, _, name = value.partition(':')
name = name.lower()
if kind == 'DNS' and (name == fqdn or (name.startswith('*.') and fqdn.partition('.')[2] == name[2:])):
return True
return False
def usable(cert, fqdn):
"""Whether the certificate is valid now and names fqdn."""
moment = now()
return utc(cert, 'not_valid_before') <= moment < utc(cert, 'not_valid_after') and covers(cert, fqdn)
def chain_pem(chain):
return b''.join(cert_pem(cert) for cert in chain)
def served_certificate(connection, cfg):
"""What Caddy serves for wan.local_fqdn: (served, chain, key), served being https.certificate, or self-signed while
the chosen certificate is not available; (acme, [], None) with acme, and (None, [], None) while there is none."""
source, fqdn = cfg['https']['certificate'], cfg['wan']['local_fqdn'].strip().lower()
if source == 'acme':
return 'acme', [], None
if source == 'ca':
issuer = authority(connection, 'servers')
current = holders(connection, 'servers', router_condition('https'))
if issuer and issuer['cert'] is not None and current and usable(current[0][1], fqdn):
above = x509.load_pem_x509_certificates(upper_chain(connection))
return 'ca', [current[0][1], issuer['cert'], *above], current[0][2]
entry = host_entry(connection)
if entry and entry['chain'] and entry['key'] is not None and usable(entry['chain'][0], fqdn):
if entry['kind'] == source or entry['kind'] == 'self-signed':
return entry['kind'], entry['chain'], entry['key']
return None, [], None
def ensure_host_cert(connection, cfg):
"""Make the self-signed certificate of wan.local_fqdn while https.certificate is self-signed, or while the chosen
certificate is not available, when there is none, it is due for renewal or it names another name; the notices."""
source, fqdn = cfg['https']['certificate'], cfg['wan']['local_fqdn'].strip().lower()
if source == 'acme' or not cfg['https']['enabled'] or not fqdn:
return []
served, _, _ = served_certificate(connection, cfg)
if served == source and served != 'self-signed':
return []
entry = host_entry(connection)
current = entry['chain'][0] if entry and entry['kind'] == 'self-signed' and entry['chain'] else None
if current is None or renewal_due(current) or not usable(current, fqdn) or common_name(current) != fqdn:
template = linuxmanager.pki_templates(cfg)['mtls']
key = new_key(template['key'])
cert = sign(fqdn, key.public_key(), None, key, cfg['https']['self_signed_days'],
leaf_extensions(cfg, template, general_names([fqdn], {'dns'})))
update_host(connection, {'linuxManagerCertificateChain': cert_pem(cert), 'linuxManagerPrivateKey': key_pem(key),
'linuxManagerKind': b'self-signed'})
if source == 'self-signed':
return []
return [f'the HTTPS certificate of {fqdn} is self-signed until the https.certificate {source} certificate is '
'available' + (': import it with linux-manager-ca https import or import-pfx' if source == 'external'
else '')]
def https_files(cfg):
"""The PEM chain and key Caddy serves for wan.local_fqdn, None with https.certificate acme or while there is none."""
with directory() as connection:
served, chain, key = served_certificate(connection, cfg)
if served in (None, 'acme'):
return None
return chain_pem(chain), key_pem(key)
def https_status(cfg):
"""The server's HTTPS certificate: {source, served, subject, issuer, sans, expires, pending}, served being the
source Caddy's certificate comes from, self-signed as the fallback, and pending whether a CSR waits."""
with directory() as connection:
served, chain, _ = served_certificate(connection, cfg)
entry = host_entry(connection)
cert = chain[0] if chain else None
return {
'source': cfg['https']['certificate'], 'served': served,
'subject': common_name(cert) if cert is not None else None,
'issuer': next((attribute.value for attribute in cert.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)),
None) if cert is not None else None,
'sans': [value.split(':', 1)[1] for value in san_values(cert)] if cert is not None else [],
'expires': iso(utc(cert, 'not_valid_after')) if cert is not None else None,
'pending': bool(entry and entry['csr']),
}
def https_csr(cfg):
"""Make a key and a CSR for wan.local_fqdn, to be signed by another CA, replacing a pending one: {csr} in PEM."""
fqdn = cfg['wan']['local_fqdn'].strip().lower()
if not fqdn:
raise Failure('the server has no wan.local_fqdn', 4)
key = new_key(linuxmanager.pki_templates(cfg)['mtls']['key'])
request = (x509.CertificateSigningRequestBuilder()
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, fqdn)]))
.add_extension(x509.SubjectAlternativeName([x509.DNSName(fqdn)]), False)
.sign(key, digest(key)))
pem = request.public_bytes(serialization.Encoding.PEM)
with directory() as connection:
update_host(connection, {'linuxManagerCertificateRequest': pem, 'linuxManagerRequestKey': key_pem(key)})
return {'csr': pem.decode()}
def keep_external(connection, cfg, chain, key):
"""Keep an imported certificate of another CA as the server's HTTPS certificate: it must be the key's, valid now
and name wan.local_fqdn; {subject, issuer, expires}."""
fqdn = cfg['wan']['local_fqdn'].strip().lower()
if cfg['https']['certificate'] != 'external':
raise Failure('https.certificate is not external', 4)
cert = chain[0]
if not same_key(cert.public_key(), key.public_key()):
raise Failure('the certificate is not for the key', 2)
if not usable(cert, fqdn):
raise Failure(f'the certificate is not valid now, or does not name {fqdn}', 2)
update_host(connection, {'linuxManagerCertificateChain': chain_pem(chain), 'linuxManagerPrivateKey': key_pem(key),
'linuxManagerKind': b'external'})
issuer = next((attribute.value for attribute in cert.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)), None)
return {'subject': common_name(cert), 'issuer': issuer, 'expires': iso(utc(cert, 'not_valid_after'))}
def import_https_certificate(cfg, text):
"""Take the certificate another CA signed for the pending CSR, PEM, followed by its chain."""
try:
chain = x509.load_pem_x509_certificates(text.strip().encode() if isinstance(text, str) else b'')
except ValueError:
raise Failure('the certificate is not a PEM certificate', 2)
with directory() as connection:
entry = host_entry(connection)
if entry is None or entry['request_key'] is None:
raise Failure('no CSR waits for a certificate: make one with linux-manager-ca https csr', 4)
document = keep_external(connection, cfg, chain, entry['request_key'])
update_host(connection, {'linuxManagerCertificateRequest': None, 'linuxManagerRequestKey': None})
return document
def import_https_pfx(cfg, data, password):
"""Take a PKCS#12 file of another CA's certificate, with its key and chain, protected by the password."""
try:
key, cert, more = pkcs12.load_key_and_certificates(data, password.encode() if password else None)
except (ValueError, TypeError):
raise Failure('the file is not a PKCS#12 file, or the password is wrong', 2)
if key is None or cert is None:
raise Failure('the PKCS#12 file holds no key or no certificate', 2)
with directory() as connection:
return keep_external(connection, cfg, [cert, *more], key)
def provision(cfg, ctx): def provision(cfg, ctx):
"""Create what the configuration needs and is missing, and keep it current; the notices to report. """Create what the configuration needs and is missing, and keep it current; the notices to report.
@@ -852,7 +1056,9 @@ def provision(cfg, ctx):
(simple-ca, upstream_sign), or is pending until its certificate is imported (offline, or simple-ca while Simple CA (simple-ca, upstream_sign), or is pending until its certificate is imported (offline, or simple-ca while Simple CA
cannot sign). An issuing CA that pki.issuing_cas no longer names is retired; its certificate is revoked on the root cannot sign). An issuing CA that pki.issuing_cas no longer names is retired; its certificate is revoked on the root
CRL, or, with an external root, a notice says to revoke it there. Stale CRLs are signed again or, with simple-ca, CRL, or, with an external root, a notice says to revoke it there. Stale CRLs are signed again or, with simple-ca,
fetched, the server's certificates issued or renewed (ensure_router_cert), and the copies of PUBLISH_DIR written. A fetched. While https.certificate is empty, the first setup chooses it: ca when the Servers Issuing CA has its
certificate, else self-signed (linuxmanager.choose_https_certificate). The server's certificates are issued or
renewed (ensure_router_cert), and the copies of PUBLISH_DIR written. A
built-in CA and the server's certificate it issues are created only while their component (BUILTIN_COMPONENTS) is built-in CA and the server's certificate it issues are created only while their component (BUILTIN_COMPONENTS) is
on; switching the component off keeps them. While the VPN is on, each VPN user without a certificate gets one. on; switching the component off keeps them. While the VPN is on, each VPN user without a certificate gets one.
""" """
@@ -865,6 +1071,7 @@ def provision(cfg, ctx):
with directory() as connection: with directory() as connection:
check_source(cfg, authority(connection, 'root')) check_source(cfg, authority(connection, 'root'))
check_names(cfg, connection)
notice = take_setup_code(cfg) notice = take_setup_code(cfg)
if notice: if notice:
notices.append(notice) notices.append(notice)
@@ -950,9 +1157,14 @@ def provision(cfg, ctx):
refresh_crls(connection, cfg, force) refresh_crls(connection, cfg, force)
if pki['root'] == 'simple-ca': if pki['root'] == 'simple-ca':
notices.extend(fetch_crls(connection)) notices.extend(fetch_crls(connection))
if not cfg['https']['certificate']:
servers = authority(connection, 'servers')
linuxmanager.choose_https_certificate(cfg, ctx, 'ca' if servers and servers['cert'] is not None else 'self-signed')
https_ca = cfg['https']['enabled'] and cfg['https']['certificate'] == 'ca'
for name in ROUTER_CERTS: for name in ROUTER_CERTS:
if component_on(ROUTER_CERTS[name][0]): if component_on(ROUTER_CERTS[name][0]) and (name != 'https' or https_ca):
ensure_router_cert(connection, cfg, ctx, name, urls) ensure_router_cert(connection, cfg, ctx, name, urls)
notices.extend(ensure_host_cert(connection, cfg))
publish(connection) publish(connection)
p2s = authority(connection, 'p2s') p2s = authority(connection, 'p2s')
missing = connection.search_s(linuxmanager_ldap.USERS, ldap.SCOPE_ONELEVEL, missing = connection.search_s(linuxmanager_ldap.USERS, ldap.SCOPE_ONELEVEL,
@@ -1013,8 +1225,9 @@ def install_crls(connection):
def reload_crls(connection): def reload_crls(connection):
"""Install the CRLs, and have strongSwan load them when they changed; OpenVPN reads its file when it changes.""" """Install the CRLs, and have strongSwan load them when they changed and it is installed; OpenVPN reads its file when
if install_crls(connection): it changes."""
if install_crls(connection) and shutil.which('swanctl'):
subprocess.run(['swanctl', '--load-creds'], capture_output=True, text=True) subprocess.run(['swanctl', '--load-creds'], capture_output=True, text=True)
@@ -1308,6 +1521,9 @@ def import_ca(cfg, name, text):
raise Failure(f'the certificate is not for the key of the CSR of {name}', 2) raise Failure(f'the certificate is not for the key of the CSR of {name}', 2)
if not is_ca(cert): if not is_ca(cert):
raise Failure('the certificate is not a CA certificate', 2) raise Failure('the certificate is not a CA certificate', 2)
if entry['csr'] is not None and common_name(cert) != common_name(x509.load_pem_x509_csr(entry['csr'])):
raise Failure(f'the certificate is for {common_name(cert)!r}, but the CSR of {name} is for '
f'{common_name(x509.load_pem_x509_csr(entry["csr"]))!r}', 2)
update(connection, name, {'cACertificate;binary': cert_der(cert), 'linuxManagerCertificateRequest': None}) update(connection, name, {'cACertificate;binary': cert_der(cert), 'linuxManagerCertificateRequest': None})
record(connection, cert, 'root', 'ca') record(connection, cert, 'root', 'ca')
sign_crl(connection, cfg, name) sign_crl(connection, cfg, name)
@@ -1351,15 +1567,19 @@ def import_root_crl(cfg, data):
def maintain(cfg): def maintain(cfg):
"""Sign the stale CRLs again or, with simple-ca, fetch them, publish and install them; the notices, and True when """Sign the stale CRLs again or, with simple-ca, fetch them, publish and install them; the notices, and True when
one of the server's certificates is due for renewal or, with simple-ca, an issuing CA waits for Simple CA, which one of the server's certificates is due for renewal, the HTTPS certificate among them while the server issues it,
linux-manager-setup does.""" or, with simple-ca, an issuing CA waits for Simple CA, which linux-manager-setup does."""
with directory() as connection: with directory() as connection:
refresh_crls(connection, cfg) refresh_crls(connection, cfg)
notices = fetch_crls(connection) if cfg['pki']['root'] == 'simple-ca' else [] notices = fetch_crls(connection) if cfg['pki']['root'] == 'simple-ca' else []
publish(connection) publish(connection)
reload_crls(connection) reload_crls(connection)
https_ca = cfg['https']['certificate'] == 'ca'
due = [current[0][1] for current in (holders(connection, ROUTER_CERTS[name][0], router_condition(name)) due = [current[0][1] for current in (holders(connection, ROUTER_CERTS[name][0], router_condition(name))
for name in ROUTER_CERTS) if current] for name in ROUTER_CERTS if name != 'https' or https_ca) if current]
served, chain, _ = served_certificate(connection, cfg)
if served == 'self-signed':
due.append(chain[0])
root = authority(connection, 'root') root = authority(connection, 'root')
waiting = cfg['pki']['root'] == 'simple-ca' and root is not None and root['token'] is not None and any( waiting = cfg['pki']['root'] == 'simple-ca' and root is not None and root['token'] is not None and any(
entry is not None and entry['cert'] is None and entry['csr'] is not None entry is not None and entry['cert'] is None and entry['csr'] is not None
@@ -1374,7 +1594,8 @@ def acme_url(cfg, name):
def status(cfg): def status(cfg):
"""The root, the upstream CA, the issuing CAs, the retired CAs and the warnings, as /ca and linux-manager-ca status """The root, the upstream CA, the issuing CAs, the retired CAs and the warnings, as /ca and linux-manager-ca status
show them.""" show them. An issuing CA is active, pending while it waits for its certificate, off while it is a built-in CA whose
component (BUILTIN_COMPONENTS), named by its component, is off and it was never made, or missing."""
moment = now() moment = now()
soon = moment + datetime.timedelta(days=WARN_DAYS) soon = moment + datetime.timedelta(days=WARN_DAYS)
warnings = [] warnings = []
@@ -1399,7 +1620,9 @@ def status(cfg):
'(&(objectClass=linuxManagerAuthority)(linuxManagerRetired=*))', '(&(objectClass=linuxManagerAuthority)(linuxManagerRetired=*))',
['cn', 'linuxManagerRetired', 'cACertificate;binary']) ['cn', 'linuxManagerRetired', 'cACertificate;binary'])
router_certs = [current[0][1] for current in (holders(connection, ROUTER_CERTS[name][0], router_condition(name)) router_certs = [current[0][1] for current in (holders(connection, ROUTER_CERTS[name][0], router_condition(name))
for name in ROUTER_CERTS) if current] for name in ROUTER_CERTS
if name != 'https' or cfg['https']['certificate'] == 'ca') if current]
served, chain, _ = served_certificate(connection, cfg)
source = cfg['pki']['root'] source = cfg['pki']['root']
token = root_entry['token'] if root_entry else None token = root_entry['token'] if root_entry else None
@@ -1435,9 +1658,12 @@ def status(cfg):
for name, settings in linuxmanager.issuing_cas(cfg).items(): for name, settings in linuxmanager.issuing_cas(cfg).items():
entry = entries[name] entry = entries[name]
cert = entry['cert'] if entry else None cert = entry['cert'] if entry else None
kind = 'active' if cert is not None else 'pending' if entry and entry['csr'] is not None else 'missing' component = BUILTIN_COMPONENTS.get(name)
kind = 'active' if cert is not None else 'pending' if entry and entry['csr'] is not None \
else 'off' if component and not cfg[component]['enabled'] else 'missing'
authorities.append({ authorities.append({
'name': name, 'common_name': settings['name'], 'state': kind, 'builtin': settings['builtin'], 'name': name, 'common_name': settings['name'], 'state': kind, 'builtin': settings['builtin'],
'component': component,
'templates': settings['templates'], 'acme': settings['acme'], 'templates': settings['templates'], 'acme': settings['acme'],
'subject': common_name(cert) if cert is not None else None, 'subject': common_name(cert) if cert is not None else None,
'expires': iso(utc(cert, 'not_valid_after')) if cert is not None else None, 'expires': iso(utc(cert, 'not_valid_after')) if cert is not None else None,
@@ -1464,4 +1690,11 @@ def status(cfg):
for cert in router_certs: for cert in router_certs:
if utc(cert, 'not_valid_after') <= soon: if utc(cert, 'not_valid_after') <= soon:
warnings.append(f'the server certificate {common_name(cert)} expires on {iso(utc(cert, "not_valid_after"))}') warnings.append(f'the server certificate {common_name(cert)} expires on {iso(utc(cert, "not_valid_after"))}')
https_source = cfg['https']['certificate']
if cfg['https']['enabled'] and https_source != 'acme':
if served != https_source:
warnings.append(f'the HTTPS certificate is {"self-signed" if served else "missing"} until the https.certificate '
f'{https_source} certificate is available')
if served == 'external' and utc(chain[0], 'not_valid_after') <= soon:
warnings.append(f'the HTTPS certificate expires on {iso(utc(chain[0], "not_valid_after"))}; import a new one')
return {'root': root, 'authorities': authorities, 'retired': retired, 'warnings': warnings} return {'root': root, 'authorities': authorities, 'retired': retired, 'warnings': warnings}
@@ -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. 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 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. 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. 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['https']['manager_port']: 'https.manager_port', cfg['metrics']['port']: 'metrics.port',
cfg['metrics']['https_port']: 'metrics.https_port', linuxmanager.manager_port(): 'the Manager', 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', 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: for port in linuxmanager.BOOTSTRAP_PORTS:
taken[port] = 'the bootstrap service' taken[port] = 'the bootstrap service'
if cfg['openvpn']['protocol'] == 'tcp': if cfg['openvpn']['protocol'] == 'tcp':
@@ -3,13 +3,14 @@
The settings file (CONFIG_FILE unless another is given) sets, all optional: router_url, database, 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 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 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 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. A setting that is not given comes from the server's it to run the manager on a workstation. On the server, where ROUTER_CONFIG_FILE is, the manager
configuration, ROUTER_CONFIG_FILE: without bind the manager listens on the addresses of the listens without bind on linuxmanager_net.MANAGER_LOOPBACK_PORT of the loopback address, where
interfaces listen names, internal, external or both (the default), and on the loopback address, Caddy calls it: Caddy serves port over plain HTTP and https.manager_port over HTTPS, and the
where the server's HTTPS proxy calls it, router_url is the first address and web.port of the firewall opens port on the interfaces listen names, internal, external or both (the default).
server's web service, and database is the DATABASE database on this host, with the password in A setting that is not given comes from the server's configuration: router_url is the web
DATABASE_SECRET. service on its loopback port, and database is the DATABASE database on this host, with the
password in DATABASE_SECRET.
""" """
import json 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. #: The role and the database the manager creates on the server.
DATABASE = 'linux-manager-ui' 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 DEFAULT_PORT = 7080
#: The port of the server's web service when web.port is not set. #: 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): 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) configuration = read_json(config_file)
bind = text_setting(configuration, 'bind') bind = text_setting(configuration, 'bind')
port = port_setting(configuration.get('port'), DEFAULT_PORT)
if bind: if bind:
return [(bind, port)], '' return [(bind, port_setting(configuration.get('port'), DEFAULT_PORT))], ''
addresses = linuxmanager_net.listen_addresses(read_json(ROUTER_CONFIG_FILE), text_setting(configuration, 'listen')) if os.path.exists(ROUTER_CONFIG_FILE):
if not addresses: return [(linuxmanager_net.LOOPBACK, linuxmanager_net.MANAGER_LOOPBACK_PORT)], ''
return [], "the server's addresses to listen on are not known yet" return [], f'bind is not set, and {ROUTER_CONFIG_FILE} is not here'
return [(address, port) for address in [*addresses, linuxmanager_net.LOOPBACK]], ''
def settings(config_file): def settings(config_file):
@@ -128,20 +129,20 @@ def settings(config_file):
if password: if password:
result['database'] = f'host=localhost dbname={DATABASE} user={DATABASE} password={password}' result['database'] = f'host=localhost dbname={DATABASE} user={DATABASE} password={password}'
if not result['router_url']: if not result['router_url']:
targets, _ = linuxmanager_net.web_listen(router, ROUTER_PORT) targets, _ = linuxmanager_net.web_listen(router)
if targets: if targets:
result['router_url'] = f'http://{targets[0][0]}:{targets[0][1]}' result['router_url'] = f'http://{targets[0][0]}:{targets[0][1]}'
result['router_url'] = result['router_url'].rstrip('/') result['router_url'] = result['router_url'].rstrip('/')
return result return result
def status_url(config_file, host, address, https): 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 its address. """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 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 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 through Caddy's HTTPS site, https and https.web_port; else, while the web service is enabled,
service listens on address, http and web.port. Otherwise it is router_url, or '' without one. http and web.port, Caddy's plain HTTP site. Otherwise it is router_url, or '' without one.
""" """
configuration = read_json(config_file) configuration = read_json(config_file)
try: try:
@@ -155,13 +156,21 @@ def status_url(config_file, host, address, https):
if https: if https:
options = router.get('https') if isinstance(router.get('https'), dict) else {} options = router.get('https') if isinstance(router.get('https'), dict) else {}
return f'https://{name}:{port_setting(options.get("web_port"), ROUTER_HTTPS_PORT)}' return f'https://{name}:{port_setting(options.get("web_port"), ROUTER_HTTPS_PORT)}'
targets, _ = linuxmanager_net.web_listen(router, ROUTER_PORT) web = router.get('web') if isinstance(router.get('web'), dict) else {}
ports = [port for listened, port in targets if listened == address] if web.get('enabled', True) is not False:
if ports: return f'http://{name}:{port_setting(web.get("port"), ROUTER_PORT)}'
return f'http://{name}:{ports[0]}'
return settings(config_file)['router_url'] 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): 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. """Work out where to listen every interval seconds with wanted, and run an HTTP server of handler at each place.
@@ -84,6 +84,7 @@ import uuid
import ldap import ldap
import ldap.filter import ldap.filter
import ldap.modlist import ldap.modlist
from ldap.controls import RequestControl
import pyotp import pyotp
from cryptography import x509 from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives import hashes, serialization
@@ -150,6 +151,8 @@ GROUP_ATTRIBUTES = ['cn', 'description', 'member']
DESCRIPTION_MAX = 256 DESCRIPTION_MAX = 256
#: The value of pwdAccountLockedTime that disables an account until it is enabled. #: The value of pwdAccountLockedTime that disables an account until it is enabled.
LOCKED = linuxmanager_ldap.DISABLED.encode() 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. #: The group whose members manage the server through the web service.
ADMIN_GROUP = 'admins' ADMIN_GROUP = 'admins'
#: The digits of a TOTP code given to login(). #: The digits of a TOTP code given to login().
@@ -720,7 +723,7 @@ def update(connection, name, values):
def apply_wireguard(): def apply_wireguard():
"""Have linux-manager-setup write the WireGuard peers of the users into wg0.conf, without waiting for it.""" """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): def update_service(connection, name, values):
@@ -793,14 +796,15 @@ def enable(connection, name):
def unlock(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) entry(connection, name)
current = connection.search_s(dn_of(name), ldap.SCOPE_BASE, attrlist=['pwdAccountLockedTime', 'pwdFailureTime'])[0][1] 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 [] changes = [(ldap.MOD_DELETE, 'pwdFailureTime', None)] if 'pwdFailureTime' in current else []
if 'pwdAccountLockedTime' in current and current['pwdAccountLockedTime'] != [LOCKED]: if 'pwdAccountLockedTime' in current and current['pwdAccountLockedTime'] != [LOCKED]:
changes.append((ldap.MOD_DELETE, 'pwdAccountLockedTime', None)) changes.append((ldap.MOD_DELETE, 'pwdAccountLockedTime', None))
if changes: 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)) return summary(entry(connection, name))
@@ -54,17 +54,20 @@ Pages:
/sites the web sites Caddy serves: the settings of sites, list, add, change and remove (see sites()), /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 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 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 /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()) remove, each with the records it serves and its manual records (see dns())
/postgresql /postgresql
the databases of each PostgreSQL cluster on the server with their sizes, as JSON (see the databases of each PostgreSQL cluster on the server with their sizes, as JSON (see
postgresql_databases()); /config has the clusters' settings postgresql_databases()); /config has the clusters' settings
/.well-known/openid-configuration, /oidc/... /.well-known/openid-configuration, /oidc/...
while oidc.enabled is true, the OpenID Provider (linuxmanager_oidc), answered only on the while oidc.enabled is true, the OpenID Provider (linuxmanager_oidc), answered only for Caddy's
loopback address, where Caddy passes the requests of the HTTPS site; POST /oidc/login counts calls of the HTTPS site, from the loopback address with X-Forwarded-Proto https; POST
towards the limit of /auth calls /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; 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 /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 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 current secret
POST /backup/run start a backup now, without waiting for it; 409 while one runs 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)): if body == 'invalid' or (body is not None and not isinstance(body, dict)):
return 400, {'error': 'the body must be a JSON object'} 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}'} return 500, {'error': f'the configuration cannot be written: {exc}'}
except SystemExit as exc: except SystemExit as exc:
return 500, {'error': str(exc.code)} 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'])} 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, """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 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 json
import sys import sys
@@ -59,15 +59,17 @@ def unit_state(unit):
return result.stdout.strip() if result and result.stdout.strip() else 'unknown' return result.stdout.strip() if result and result.stdout.strip() else 'unknown'
def section_change(name, body): def settings_change(changes):
"""Change any of the settings of the configuration's section as /backup changes its own; the section, or the HTTP """Change settings of sections of the configuration in one step, section -> {setting: value}, keeping only the
status and the error document as a tuple.""" settings of SCHEMA, validated as a whole, and run setup; the configuration, or the HTTP status and the error document
settings = {option: body[option] for option in linuxmanager.SCHEMA[name] if option in body} as a tuple."""
try: try:
with linuxmanager.config_lock(): with linuxmanager.config_lock():
data = linuxmanager.read_settings() data = linuxmanager.read_settings()
current = data.get(name) for name, body in changes.items():
data[name] = {**(current if isinstance(current, dict) else {}), **settings} 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) cfg = linuxmanager.with_defaults(data)
linuxmanager.validate(cfg) linuxmanager.validate(cfg)
linuxmanager.save_config(data) linuxmanager.save_config(data)
@@ -77,8 +79,15 @@ def section_change(name, body):
return 500, {'error': f'the configuration cannot be written: {exc}'} return 500, {'error': f'the configuration cannot be written: {exc}'}
except SystemExit as exc: except SystemExit as exc:
return 500, {'error': str(exc.code)} return 500, {'error': str(exc.code)}
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service') linuxmanager.request_setup()
return cfg[name] 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): 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 ipaddress
import linuxmanager import linuxmanager
from linuxmanager_status import established_each, run from linuxmanager_status import established_each
from .common import section from .common import section
@@ -37,7 +37,7 @@ def site_to_site(method, path, body):
DELETE /site-to-site/<name> remove the connection 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 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)): if body == 'invalid' or (body is not None and not isinstance(body, dict)):
return 400, {'error': 'the body must be a JSON object'} 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}'} return 500, {'error': f'the configuration cannot be written: {exc}'}
except SystemExit as exc: except SystemExit as exc:
return 500, {'error': str(exc.code)} return 500, {'error': str(exc.code)}
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service') linuxmanager.request_setup()
if method == 'DELETE': if method == 'DELETE':
return 200, {'name': name, 'removed': True} return 200, {'name': name, 'removed': True}
return (201 if method == 'POST' else 200), connection_of(name, cfg['site_to_site'][name], None) 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) configuration needs of the server (wireguard_server)
PUT /remote-access/<system> change any of the settings of the system's section; answers the section 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)): if body == 'invalid' or (body is not None and not isinstance(body, dict)):
return 400, {'error': 'the body must be a JSON object'} 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}'} return 500, {'error': f'the configuration cannot be written: {exc}'}
except SystemExit as exc: except SystemExit as exc:
return 500, {'error': str(exc.code)} return 500, {'error': str(exc.code)}
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service') linuxmanager.request_setup()
return 200, cfg[system] return 200, cfg[system]
@@ -2,7 +2,6 @@
import linuxmanager import linuxmanager
import linuxmanager_dns import linuxmanager_dns
from linuxmanager_status import run
from .common import section_change, unit_state from .common import section_change, unit_state
@@ -30,7 +29,7 @@ def dns(method, path, query, body):
DELETE /dns/domains/<domain>/records DELETE /dns/domains/<domain>/records
remove the manual records of name= and type=, with content= only that one 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)): if body == 'invalid' or (body is not None and not isinstance(body, dict)):
return 400, {'error': 'the body must be a JSON object'} 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)} return 500, {'error': str(exc)}
except SystemExit as exc: except SystemExit as exc:
return 500, {'error': str(exc.code)} return 500, {'error': str(exc.code)}
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service') linuxmanager.request_setup()
return code, document return code, document
@@ -18,11 +18,12 @@ import linuxmanager_sites
from .auth import auth, auth_wait, refusal from .auth import auth, auth_wait, refusal
from .backup import backup from .backup import backup
from .common import BODY_LIMIT, CONFIG_FILE, current, log, read_json, section 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 .connectivity import remote_access, site_to_site
from .dns import dns from .dns import dns
from .identities import account, groups, service_accounts, users from .identities import account, groups, service_accounts, users
from .logs import logs 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 .metrics import metrics_history, metrics_settings
from .pki import PUBLISHED, ca from .pki import PUBLISHED, ca
from .shell import EDITOR_BODY_LIMIT, shell, shell_editor, shell_passkey, shell_ticket from .shell import EDITOR_BODY_LIMIT, shell, shell_editor, shell_passkey, shell_ticket
@@ -65,14 +66,14 @@ class Handler(BaseHTTPRequestHandler):
if self.command not in ('GET', 'HEAD'): if self.command not in ('GET', 'HEAD'):
self.close_connection = True self.close_connection = True
directory = next((name for name in ('users', 'service-accounts', 'groups', 'account', 'site-to-site', 'backup', 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) 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 \ '/postgresql') or \
directory is not None directory is not None
signing = path in ('/auth', '/auth/passkey', '/auth/passkey/complete', '/auth/refresh', '/auth/logout') signing = path in ('/auth', '/auth/passkey', '/auth/passkey/complete', '/auth/refresh', '/auth/logout')
oidc = (path == '/.well-known/openid-configuration' or path.startswith('/oidc/')) and \ 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 files = SITE_FILES.match(path) if directory == 'sites' else None
query = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query) query = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query)
state = current() if protected or signing else {} state = current() if protected or signing else {}
@@ -115,8 +116,8 @@ class Handler(BaseHTTPRequestHandler):
elif path == '/metrics/settings': elif path == '/metrics/settings':
code, document = metrics_settings(self.command, payload) code, document = metrics_settings(self.command, payload)
body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json' body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json'
elif path == '/https/settings': elif path in HTTPS_PATHS:
code, document = https_settings(self.command, payload) code, document = https(self.command, path, payload)
body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json' body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json'
elif directory == 'shell' and (path, self.command) == ('/shell', 'GET'): elif directory == 'shell' and (path, self.command) == ('/shell', 'GET'):
return shell(self, claims.get('sub')) return shell(self, claims.get('sub'))
@@ -160,6 +161,9 @@ class Handler(BaseHTTPRequestHandler):
elif directory == 'dns': elif directory == 'dns':
code, document = dns(self.command, path, query, payload) code, document = dns(self.command, path, query, payload)
body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json' 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': elif directory == 'service-accounts':
code, document = service_accounts(self.command, path, payload) code, document = service_accounts(self.command, path, payload)
body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json' body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json'
@@ -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
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. #: The settings of the https section PUT /https/settings changes.
CHANGEABLE = ('acme_staging',) CHANGEABLE = ('acme_staging', 'certificate', 'self_signed_days', '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): def shown(settings):
"""Answer a /https/settings request: the HTTP status and the JSON document. """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 wan.local_fqdn: {"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)): if body == 'invalid' or (body is not None and not isinstance(body, dict)):
return 400, {'error': 'the body must be a JSON object'} return 400, {'error': 'the body must be a JSON object'}
if method in ('GET', 'HEAD'): body = body or {}
try: try:
return 200, {'settings': linuxmanager.load_config()['https']} cfg = linuxmanager.load_config()
except SystemExit as exc: if path == '/https/settings' and method in ('GET', 'HEAD'):
return 500, {'error': str(exc.code)} return 200, {'settings': shown(cfg['https']), 'certificate': linuxmanager_pki.https_status(cfg)}
if method != 'PUT': if path == '/https/settings' and method == 'PUT':
return 404, {'error': f'no route {method} /https/settings'} others = sorted(set(body) - set(CHANGEABLE))
others = sorted(set(body or {}) - set(CHANGEABLE)) if others:
if others: return 400, {'error': f'https.{", https.".join(others)}: changed on the server with '
return 400, {'error': f'https.{", https.".join(others)}: changed on the server with linux-manager-config-edit only'} 'linux-manager-config-edit only'}
changed = section_change('https', body or {}) if 'certificate' in body and body['certificate'] not in linuxmanager.HTTPS_CERTIFICATES:
return changed if isinstance(changed, tuple) else (200, {'settings': changed}) 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. #: 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', 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') '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. #: 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 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 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)): if body == 'invalid' or (body is not None and not isinstance(body, dict)):
return 400, {'error': 'the body must be a JSON object'} return 400, {'error': 'the body must be a JSON object'}
@@ -4,7 +4,6 @@ import ldap
import linuxmanager import linuxmanager
import linuxmanager_pki import linuxmanager_pki
from linuxmanager_status import run
from .common import PKI_STATUS from .common import PKI_STATUS
@@ -38,7 +37,7 @@ def ca(method, path, body):
answers {"upstream", "expires"} answers {"upstream", "expires"}
A change of the settings is made as /site-to-site makes one; it, a revoked router certificate, an imported root A change of the settings is made as /site-to-site makes one; it, a revoked router certificate, an imported root
or issuing CA certificate and a new Simple CA token are applied by restarting linux-manager-setup without waiting or issuing CA certificate and a new Simple CA token are applied by a run of linux-manager-setup, without waiting
for it. for it.
""" """
if body == 'invalid' or (body is not None and not isinstance(body, dict)): if body == 'invalid' or (body is not None and not isinstance(body, dict)):
@@ -66,7 +65,7 @@ def ca(method, path, body):
with linuxmanager_pki.directory() as connection: with linuxmanager_pki.directory() as connection:
linuxmanager_pki.check_source(cfg, linuxmanager_pki.authority(connection, 'root')) linuxmanager_pki.check_source(cfg, linuxmanager_pki.authority(connection, 'root'))
linuxmanager.save_config(data) 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)} return 200, {'settings': cfg['pki'], 'templates': linuxmanager.pki_templates(cfg)}
with linuxmanager_pki.locked(): with linuxmanager_pki.locked():
if route == ('POST', 'certificates'): if route == ('POST', 'certificates'):
@@ -98,5 +97,5 @@ def ca(method, path, body):
except SystemExit as exc: except SystemExit as exc:
return 500, {'error': str(exc.code)} return 500, {'error': str(exc.code)}
if route[1] in ('issuing', 'root') or document.get('reissue'): if route[1] in ('issuing', 'root') or document.get('reissue'):
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service') linuxmanager.request_setup()
return 200, document return 200, document
@@ -10,7 +10,6 @@ import ldap
import linuxmanager import linuxmanager
import linuxmanager_sites import linuxmanager_sites
from linuxmanager_status import run
from .common import MIB, SITE_STATUS, section_change 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 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 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)): if body == 'invalid' or (body is not None and not isinstance(body, dict)):
return 400, {'error': 'the body must be a JSON object'} 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}'} return 500, {'error': f'the site cannot be changed: {exc}'}
except SystemExit as exc: except SystemExit as exc:
return 500, {'error': str(exc.code)} return 500, {'error': str(exc.code)}
run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service') linuxmanager.request_setup()
return code, document return code, document
@@ -232,7 +232,7 @@ def postgresql_databases():
def details(state): def details(state):
"""What /config shows: the configuration without its secrets, and what the server resolved and runs; caddy is the """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 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 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.""" docker.service is installed, as docker_status finds it."""
configuration = state.get('configuration', {}) configuration = state.get('configuration', {})
@@ -252,9 +252,7 @@ def details(state):
'rules': lines_of('iptables', '-S', 'LINUX-MANAGER-DOCKER'), 'rules': lines_of('iptables', '-S', 'LINUX-MANAGER-DOCKER'),
}, },
'postgresql': postgresql_configuration(), 'postgresql': postgresql_configuration(),
# Caddy is upstream's once its repository is configured (linux-manager-caddy). 'caddy': {'version': caddy, 'service': unit_state('caddy.service')} if caddy else None,
'caddy': {'version': caddy, 'source': 'upstream' if linuxmanager.CADDY_APT_SOURCE.is_file() else 'ubuntu',
'service': unit_state('caddy.service')} if caddy else None,
'oidc': {'enabled': oidc, 'issuer': linuxmanager.oidc_issuer(configuration) if oidc 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. linuxmanager_ui.
Pages: 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"?}, /api/session POST signs in through the server's /auth with {"name", "password", "code"?},
GET answers the signed-in user, DELETE signs out GET answers the signed-in user, DELETE signs out
/api/session/passkey /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. 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 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 works out where to listen, bind, or on the server the loopback port Caddy calls
(linuxmanager_ui.serve). Every request (linuxmanager_ui.listen), and runs a server at each address (linuxmanager_ui.serve). Every
reads the settings when it is made. request reads the settings when it is made.
""" """
import argparse import argparse
@@ -77,11 +78,9 @@ import requests
import urllib3 import urllib3
import linuxmanager_ui import linuxmanager_ui
from linuxmanager_net import LOOPBACK
from linuxmanager_ui import DATABASE, DATABASE_SECRET, ROUTER_CONFIG_FILE 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 CONFIG_FILE = linuxmanager_ui.CONFIG_FILE
WEB_DIR = '/usr/share/linux-manager/manager/web' WEB_DIR = '/usr/share/linux-manager/manager/web'
DOCS_DIR = '/usr/share/linux-manager/manager/docs' DOCS_DIR = '/usr/share/linux-manager/manager/docs'
@@ -792,8 +791,14 @@ class Handler(BaseHTTPRequestHandler):
self.close_connection = True self.close_connection = True
if route == '/api/info': if route == '/api/info':
https = self.proxied() and self.headers.get('X-Forwarded-Proto') == 'https' 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) status = linuxmanager_ui.status_url(CONFIG_FILE, self.headers.get('Host', ''), https)
body = json.dumps({'version': package_version(), 'status_url': status or None}).encode() # 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' code, kind = 200, 'application/json'
elif route == '/api/shell' and self.command == 'GET' and self.headers.get('Upgrade', '').lower() == 'websocket': elif route == '/api/shell' and self.command == 'GET' and self.headers.get('Upgrade', '').lower() == 'websocket':
try: 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 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 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 /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 lock the account as for any user. The service listens on the loopback address only, behind
names and on the loopback address, where Caddy serves it over HTTPS at metrics.https_port; the Caddy, which serves it over plain HTTP at metrics.port, on the interfaces metrics.listen names
address of a call through Caddy is the last entry of its X-Forwarded-For header. 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 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. ExportMetricsServiceRequest, with HTTP Basic authentication when metrics.otlp_username is set.
@@ -431,19 +432,11 @@ class Handler(BaseHTTPRequestHandler):
def wanted(): def wanted():
"""Where the service listens: the addresses of the interfaces metrics.listen names and LOOPBACK, at metrics.port.""" """Where the service listens: METRICS_LOOPBACK_PORT of LOOPBACK, where Caddy calls it, while metrics are enabled."""
configuration = read_json(CONFIG_FILE) metrics = section(read_json(CONFIG_FILE), 'metrics')
metrics = section(configuration, 'metrics') if metrics.get('enabled', linuxmanager.SCHEMA['metrics']['enabled']) is False:
defaults = linuxmanager.SCHEMA['metrics']
if metrics.get('enabled', defaults['enabled']) is False:
return [], 'metrics are disabled in the configuration' return [], 'metrics are disabled in the configuration'
port = metrics.get('port', defaults['port']) return [(linuxmanager_net.LOOPBACK, linuxmanager_net.METRICS_LOOPBACK_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]], ''
def main(): def main():
+106 -76
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. would be a silent and security-relevant mistake.
""" """
import fcntl
import grp import grp
import json import json
import os import os
@@ -27,6 +28,7 @@ import socket
import subprocess import subprocess
import sys import sys
import time import time
import traceback
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) 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_UNIT = 'caddy.service'
CADDY_GROUP = 'caddy' 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 #: 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. #: key.pem.
CADDY_PKI_DIR = pathlib.Path('/etc/caddy/linux-manager-pki') CADDY_PKI_DIR = pathlib.Path('/etc/caddy/linux-manager-pki')
@@ -81,6 +80,9 @@ 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. #: 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') CADDY_SITES_DIR = pathlib.Path('/etc/caddy/linux-manager-sites')
#: The certificate and key of wan.local_fqdn Caddy serves when they come from no ACME CA.
CADDY_HTTPS_DIR = pathlib.Path('/etc/caddy/linux-manager-https')
#: The unit of dnsmasq, the resolver of the remote access clients. #: The unit of dnsmasq, the resolver of the remote access clients.
RESOLVER_UNIT = 'linux-manager-resolver.service' RESOLVER_UNIT = 'linux-manager-resolver.service'
@@ -155,8 +157,8 @@ def resolve_public_ip(fqdn):
def setup_wireguard(ctx): def setup_wireguard(ctx):
"""Generate the WireGuard key pair when it does not exist.""" """Generate the WireGuard key pair when it does not exist, once the VPN's packages are installed."""
if not ctx['wg_enabled']: if not ctx['wg_enabled'] or not ctx['vpn_installed']:
return return
WG_DIR.mkdir(mode=0o700, parents=True, exist_ok=True) WG_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
key_file = WG_DIR / 'wg0.key' key_file = WG_DIR / 'wg0.key'
@@ -262,16 +264,18 @@ def filter_block(ctx):
] ]
lines += ['# P2S DNS RULES END'] lines += ['# P2S DNS RULES END']
# The web service, the Manager and the metrics service choose their interfaces themselves, so their ports are open on # Caddy serves the plain HTTP ports of the web service, the Manager and the metrics service on every address; each is
# both; without the router both are the one interface. # 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)) interfaces = list(dict.fromkeys(name for name in (ctx['int_iface'], ctx['wan_iface']) if name))
if ctx['web_enabled'] and interfaces:
lines += [ def opened(choice, port):
'', return [f'-A ufw-before-input -i {name} -p tcp --dport {port} -j ACCEPT'
'# WEB RULES START', for name in dict.fromkeys(listened[choice]) if name]
*(f'-A ufw-before-input -i {name} -p tcp --dport {ctx["web_port"]} -j ACCEPT' for name in interfaces),
'# WEB RULES END', if ctx['web_enabled']:
] lines += ['', '# WEB RULES START', *opened(ctx['web_listen'], ctx['web_port']), '# WEB RULES END']
if not SETUP_DONE.exists() and ctx['int_iface']: if not SETUP_DONE.exists() and ctx['int_iface']:
lines += [ lines += [
@@ -282,25 +286,15 @@ def filter_block(ctx):
'# BOOTSTRAP RULES END', '# BOOTSTRAP RULES END',
] ]
if interfaces: lines += ['', '# MANAGER RULES START', *opened(linuxmanager.manager_listen(), linuxmanager.manager_port()),
port = linuxmanager.manager_port() '# MANAGER RULES END']
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: if linuxmanager.metrics_ready(ctx):
lines += [ lines += ['', '# METRICS RULES START', *opened(ctx['metrics_listen'], ctx['metrics_port']),
'', '# METRICS RULES END']
'# 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 # The ACME CA reaches the HTTP challenge on the external interface while it issues the server's certificate, and
# read on both; the HTTPS ports are open on both. # 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: if linuxmanager.https_ready(ctx) and interfaces:
publish = ctx['pki_publish'] publish = ctx['pki_publish']
ports = [port for wanted, port in ((ctx['web_enabled'] or 'https' in publish or ctx['pki_acme'], ports = [port for wanted, port in ((ctx['web_enabled'] or 'https' in publish or ctx['pki_acme'],
@@ -314,7 +308,7 @@ def filter_block(ctx):
'', '',
'# HTTPS RULES START', '# HTTPS RULES START',
*([f'-A ufw-before-input -i {ctx["wan_iface"]} -p tcp --dport {linuxmanager.ACME_HTTP_PORT} -j ACCEPT'] *([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 'http-80' not in publish 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), *(f'-A ufw-before-input -i {name} -p tcp --dport {port} -j ACCEPT' for name in interfaces for port in ports),
'# HTTPS RULES END', '# HTTPS RULES END',
] ]
@@ -752,42 +746,28 @@ def manage_resolver(changed):
def manage_caddy(cfg, ctx): 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 """Run Caddy, a dependency of the package, which serves every HTTP and HTTPS port of the server's services and the
stop it when not. web sites; the services listen on loopback only.
While HTTPS is ready, CADDYFILE serves the web service on https.web_port, the manager on CADDYFILE serves over plain HTTP the web service on web.port while it is enabled, the manager on its port, or a
https.manager_port, while metrics are enabled the metrics service on metrics.https_port, and while redirect (308) to its HTTPS address while HTTPS is ready and https.disable_auto_redirect is off, and while metrics
WebDAV is ready WebDAV on sites.webdav_port, all for wan.local_fqdn with a certificate from Let's Encrypt, and all are enabled the metrics service on metrics.port. While HTTPS is ready, it serves the web service on
calling the service on its loopback address. It also serves the CA files of linuxmanager_pki.PUBLISH_DIR at /pki/ on https.web_port, the manager on https.manager_port, while metrics are enabled the metrics service on
the endpoints of pki.publish that are Caddy's, and an ACME server at /acme/<name>/ on https.web_port for each metrics.https_port, and while WebDAV is ready WebDAV on sites.webdav_port, all for wan.local_fqdn. Every site calls
issuing CA with acme and a certificate. 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 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.
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 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 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), 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. 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'] sites = ctx['sites']
if not linuxmanager.https_ready(ctx) and not sites: if shutil.which('caddy') is None:
if sites is None: fail('caddy is not installed; it is a dependency of the package')
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 sites is None: if sites is None:
warn('the web sites cannot be read; the Caddyfile is left as it is') warn('the web sites cannot be read; the Caddyfile is left as it is')
if not unit_is_active(CADDY_UNIT) and CADDYFILE.exists(): if not unit_is_active(CADDY_UNIT) and CADDYFILE.exists():
@@ -798,6 +778,26 @@ def manage_caddy(cfg, ctx):
except KeyError: except KeyError:
fail(f'the group {CADDY_GROUP} does not exist; is the caddy package installed?') fail(f'the group {CADDY_GROUP} does not exist; is the caddy package installed?')
https = linuxmanager.https_ready(ctx) https = linuxmanager.https_ready(ctx)
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 []), wanted = list(dict.fromkeys([*(ctx['pki_acme'] if https else []),
*(site['ca'] for site in sites if site['tls'] == 'ca')])) *(site['ca'] for site in sites if site['tls'] == 'ca')]))
try: try:
@@ -810,7 +810,6 @@ def manage_caddy(cfg, ctx):
if site['tls'] == 'ca' and site['ca'] not in authorities: 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') 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] 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 []): for folder in (CADDY_PKI_DIR.iterdir() if CADDY_PKI_DIR.is_dir() else []):
if folder.name not in authorities: if folder.name not in authorities:
shutil.rmtree(folder) shutil.rmtree(folder)
@@ -837,12 +836,18 @@ def manage_caddy(cfg, ctx):
linuxmanager_sites.ensure_folders(site['name'] for site in sites) linuxmanager_sites.ensure_folders(site['name'] for site in sites)
names = linuxmanager.issuing_cas(cfg) names = linuxmanager.issuing_cas(cfg)
caddy_ctx = dict(ctx, https=https, manager_port=linuxmanager.manager_port(), caddy_ctx = dict(ctx, https=https, manager_port=linuxmanager.manager_port(),
redirect=https and not cfg['https']['disable_auto_redirect'],
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_publish_dir=str(linuxmanager_pki.PUBLISH_DIR),
pki_cas=[{'id': name, 'name': names[name]['name'].strip(), pki_cas=[{'id': name, 'name': names[name]['name'].strip(),
'cert': str(CADDY_PKI_DIR / name / 'cert.pem'), 'cert': str(CADDY_PKI_DIR / name / 'cert.pem'),
'key': str(CADDY_PKI_DIR / name / 'key.pem')} for name in authorities], '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']], 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'], 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']), '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']] 'addresses': [caddy_address(host, site['port'], site['tls']) for host in site['hosts']]
@@ -864,15 +869,24 @@ def install_packages(feature):
warn(f'the packages of {feature} are installed by {unit}, which runs setup again') 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): 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 """Run rclone's WebDAV server of the sites' folders while WebDAV is ready and rclone is installed
when it is missing.""" (manage_components), and stop it when not."""
if not linuxmanager.webdav_ready(ctx): if not linuxmanager.webdav_ready(ctx):
if unit_is_active(WEBDAV_UNIT): if unit_is_active(WEBDAV_UNIT):
run(['systemctl', 'disable', '--now', WEBDAV_UNIT], check=False) run(['systemctl', 'disable', '--now', WEBDAV_UNIT], check=False)
return return
if shutil.which('rclone') is None: if shutil.which('rclone') is None:
install_packages('webdav')
return return
linuxmanager_sites.ensure_folders([]) linuxmanager_sites.ensure_folders([])
run(['systemctl', 'enable', '--now', WEBDAV_UNIT], check=False) run(['systemctl', 'enable', '--now', WEBDAV_UNIT], check=False)
@@ -899,7 +913,7 @@ def site_addresses(cfg, ctx):
def manage_dns(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 """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 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 installation starts answers on those addresses only, beside systemd-resolved's stub on 127.0.0.53. The host names
@@ -927,7 +941,6 @@ def manage_dns(cfg, ctx):
linuxmanager_dns.PDNS_CONF.parent.mkdir(mode=0o755, parents=True, exist_ok=True) 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) 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(): if not linuxmanager_dns.PDNS_SERVER.exists() or not linuxmanager_dns.PDNS_SCHEMA.exists():
install_packages('dns')
return return
os.chown(linuxmanager_dns.PDNS_CONF, 0, grp.getgrnam(linuxmanager_dns.GROUP).gr_gid) os.chown(linuxmanager_dns.PDNS_CONF, 0, grp.getgrnam(linuxmanager_dns.GROUP).gr_gid)
linuxmanager_dns.provision() linuxmanager_dns.provision()
@@ -1090,6 +1103,8 @@ def main():
failed_step = 'user directory' failed_step = 'user directory'
progress('running', failed_step) progress('running', failed_step)
problem = manage_directory() problem = manage_directory()
progress('running', 'components')
manage_components(cfg)
progress('running', 'configuration') progress('running', 'configuration')
ctx, changed = linuxmanager.configure(cfg) ctx, changed = linuxmanager.configure(cfg)
@@ -1195,13 +1210,28 @@ def record_failure(error):
if __name__ == '__main__': if __name__ == '__main__':
# A failing step ends with SystemExit carrying its message (linuxmanager.fail). # The run holds SETUP_RUNNING while it works, and runs again while a request came during it (request_setup).
try: linuxmanager.SETUP_RUNNING.parent.mkdir(parents=True, exist_ok=True)
code = main() running = open(linuxmanager.SETUP_RUNNING, 'a', encoding='utf-8')
except SystemExit as exc: fcntl.flock(running, fcntl.LOCK_EX)
record_failure(str(exc.code)) while True:
raise with linuxmanager.setup_lock():
except Exception as exc: linuxmanager.SETUP_REQUEST.unlink(missing_ok=True)
record_failure(repr(exc)) # A failing step ends with SystemExit carrying its message (linuxmanager.fail).
raise 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) sys.exit(code)
+7 -11
View File
@@ -1,5 +1,6 @@
#!/usr/bin/python3 #!/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 Run by linux-manager-web.service. Users are managed with linuxmanager_users, the module that
linux-manager-user uses too. 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. 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 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, reads web.enabled from /etc/linux-manager/linux-manager.json and listens on
internal, external or both, as general.mode directs, with web.port and web.enabled linuxmanager_net.WEB_LOOPBACK_PORT of the loopback address while it is on (linuxmanager_net.web_listen,
(linuxmanager_net.web_listen), and runs a server on each (linuxmanager_serve.serve): it starts them, linuxmanager_serve.serve). Every request reads what it needs when it is made: the signing
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
key, the configuration, and the features of the server and the facts shown by /config from 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 /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. 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. #: Seconds between two attempts of the initialization.
INIT_RETRY_SECONDS = 15 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. #: Seconds between two discoveries of where the service should listen.
DISCOVERY_SECONDS = 30 DISCOVERY_SECONDS = 30
@@ -88,8 +84,8 @@ def main():
initialize() initialize()
threading.Thread(target=editor_listen, name='editor socket', daemon=True).start() threading.Thread(target=editor_listen, name='editor socket', daemon=True).start()
try: try:
linuxmanager_serve.serve(lambda: linuxmanager_net.web_listen(read_json(CONFIG_FILE), DEFAULT_PORT), Handler, log, linuxmanager_serve.serve(lambda: linuxmanager_net.web_listen(read_json(CONFIG_FILE)), Handler, log,
DISCOVERY_SECONDS) DISCOVERY_SECONDS)
except KeyboardInterrupt: except KeyboardInterrupt:
pass pass
return 0 return 0
+36 -11
View File
@@ -6,8 +6,10 @@ or makes a key and writes a PFX file whose password is read from the first line
CSR of an issuing CA that waits for the offline root, with the openssl extensions to sign it with, and ca import takes 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, and, named root, the certificate of the offline root. root import-crl takes a CRL of the 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 offline root, and root setup-code exchanges a setup code of a Simple CA token, read from the first line of standard
input, for the token. maintain signs the stale CRLs again, or fetches those of Simple CA; linux-manager-pki.service input, for the token. https status shows the server's HTTPS certificate, https csr prints a new CSR for
runs it daily. A change that needs linux-manager-setup restarts it without waiting. 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 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 JSON on standard output, and a failure is {"error": ...} there too. The exit status says what failed: 2 the request
@@ -24,6 +26,9 @@ commands and their options.
linux-manager-ca [--json] ca import NAME|root FILE linux-manager-ca [--json] ca import NAME|root FILE
linux-manager-ca [--json] root import-crl FILE linux-manager-ca [--json] root import-crl FILE
linux-manager-ca [--json] root setup-code (setup code on stdin) 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 import argparse
@@ -31,7 +36,6 @@ import base64
import json import json
import os import os
import pathlib import pathlib
import subprocess
import sys import sys
sys.path.insert(0, '/usr/lib/linux-manager') sys.path.insert(0, '/usr/lib/linux-manager')
@@ -56,10 +60,6 @@ def secret():
return sys.stdin.readline().rstrip('\r\n') 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): def show_status(document):
root = document['root'] root = document['root']
source = {'local': 'created by the server', 'offline': 'offline', source = {'local': 'created by the server', 'offline': 'offline',
@@ -95,6 +95,13 @@ def run(options):
if options.command == 'status': if options.command == 'status':
document = linuxmanager_pki.status(cfg) document = linuxmanager_pki.status(cfg)
return document, None 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': if options.command == 'list':
found = [entry for entry in linuxmanager_pki.certificates() if options.ca in (None, entry['ca'])] 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"]} ' text = '\n'.join(f'{entry["serial"]} {entry["ca"]} {entry["kind"]} {entry["subject"]} {entry["state"]} '
@@ -117,13 +124,13 @@ def run(options):
if options.command == 'revoke': if options.command == 'revoke':
document = linuxmanager_pki.revoke(cfg, options.serial, options.reason) document = linuxmanager_pki.revoke(cfg, options.serial, options.reason)
if document['reissue']: if document['reissue']:
restart_setup() linuxmanager.request_setup()
return document, f'Certificate {document["serial"]} revoked' + \ return document, f'Certificate {document["serial"]} revoked' + \
('; linux-manager-setup issues a new one.' if document['reissue'] else '.') ('; linux-manager-setup issues a new one.' if document['reissue'] else '.')
if options.command == 'maintain': if options.command == 'maintain':
notices, due = linuxmanager_pki.maintain(cfg) notices, due = linuxmanager_pki.maintain(cfg)
if due: if due:
restart_setup() linuxmanager.request_setup()
return {'renewal': due, 'notices': notices}, '\n'.join( return {'renewal': due, 'notices': notices}, '\n'.join(
['CRLs checked' + ('; linux-manager-setup renews the certificates.' if due else '.'), ['CRLs checked' + ('; linux-manager-setup renews the certificates.' if due else '.'),
*(f'Warning: {notice}' for notice in notices)]) *(f'Warning: {notice}' for notice in notices)])
@@ -132,12 +139,24 @@ def run(options):
return document, document['csr'] + '\n' + document['extensions'] return document, document['csr'] + '\n' + document['extensions']
if options.command == 'ca': if options.command == 'ca':
document = linuxmanager_pki.import_ca(cfg, options.name, pathlib.Path(options.file).read_text(encoding='ascii')) document = linuxmanager_pki.import_ca(cfg, options.name, pathlib.Path(options.file).read_text(encoding='ascii'))
restart_setup() linuxmanager.request_setup()
what = 'The root' if options.name == 'root' else f'Issuing CA {options.name}' what = 'The root' if options.name == 'root' else f'Issuing CA {options.name}'
return document, f'{what} has its certificate, which expires {document["expires"]}.' 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': if options.action == 'setup-code':
document = linuxmanager_pki.exchange_code(cfg, secret()) document = linuxmanager_pki.exchange_code(cfg, secret())
restart_setup() linuxmanager.request_setup()
return document, (f'Simple CA token of issuing CA {document["upstream"]} taken' return document, (f'Simple CA token of issuing CA {document["upstream"]} taken'
+ (f', valid until {document["expires"]}.' if document['expires'] else '.')) + (f', valid until {document["expires"]}.' if document['expires'] else '.'))
document = linuxmanager_pki.import_root_crl(cfg, pathlib.Path(options.file).read_bytes()) document = linuxmanager_pki.import_root_crl(cfg, pathlib.Path(options.file).read_bytes())
@@ -172,6 +191,12 @@ def main(argv):
root_actions = root.add_subparsers(dest='action', required=True, parser_class=Parser) root_actions = root.add_subparsers(dest='action', required=True, parser_class=Parser)
root_actions.add_parser('import-crl', help='take a CRL of the offline root').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') 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) options = parser.parse_args(argv)
os.umask(0o077) 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 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 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 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 run, which set and remove remind of. With --restart they have linux-manager-setup run and wait until
it has applied the change. A failure is a message on standard error; the exit status is 2 for an it has applied the change, as apply does without a change: a run in progress is not cut short but
invalid request and 1 for any other failure, a failed run of linux-manager-setup included. -h or runs once more (linuxmanager.request_setup). A failure is a message on standard error; the exit
--help shows the options. 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 show
linux-manager-config-edit set [--restart] SECTION.OPTION VALUE 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 set [--restart] site_to_site.NAME.OPTION VALUE
linux-manager-config-edit remove [--restart] site_to_site.NAME linux-manager-config-edit remove [--restart] site_to_site.NAME
linux-manager-config-edit apply
""" """
import argparse import argparse
import copy import copy
import json import json
import subprocess
import sys import sys
sys.path.insert(0, '/usr/lib/linux-manager') 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.') 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 = parser.add_subparsers(dest='command', required=True, parser_class=Parser)
commands.add_parser('show', help='print the configuration as indented JSON') 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 = commands.add_parser('set', help='set a setting and write the configuration')
setter.add_argument('key', metavar='SECTION.OPTION', setter.add_argument('key', metavar='SECTION.OPTION',
help='the setting, such as web.port or site_to_site.NAME.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') remover.add_argument('key', metavar='site_to_site.NAME', help='the connection')
for changer in (setter, remover): for changer in (setter, remover):
changer.add_argument('--restart', action='store_true', 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) options = parser.parse_args(argv)
if options.command == 'show': if options.command == 'show':
print(json.dumps(read(), indent=2)) print(json.dumps(read(), indent=2))
return 0 return 0
if options.command == 'apply':
return applied()
with linuxmanager.config_lock(): with linuxmanager.config_lock():
data = read() data = read()
@@ -131,10 +135,15 @@ def main(argv):
else: else:
print(f'{options.key} removed from {linuxmanager.CONFIG_FILE}.') print(f'{options.key} removed from {linuxmanager.CONFIG_FILE}.')
if not options.restart: 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 return 0
print('Restarting linux-manager-setup...', flush=True) return applied()
if subprocess.run(['systemctl', 'restart', 'linux-manager-setup.service']).returncode != 0:
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) print('linux-manager-config-edit: linux-manager-setup failed; see journalctl -u linux-manager-setup', file=sys.stderr)
return 1 return 1
print('linux-manager-setup applied it.') 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 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 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). 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 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 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. 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 argparse
import json import json
import subprocess
import sys import sys
sys.path.insert(0, '/usr/lib/linux-manager') sys.path.insert(0, '/usr/lib/linux-manager')
@@ -151,7 +150,7 @@ def main(argv):
message, status = f'the user directory failed: {exc}', 1 message, status = f'the user directory failed: {exc}', 1
else: else:
if changed: 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)) print(json.dumps(answer) if as_json else text_of(answer))
return 0 return 0
if as_json: if as_json:
@@ -22,7 +22,7 @@ _linux_manager_ca()
local cur prev words cword split local cur prev words cword split
_init_completion -s || return _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. # words after them but option values.
local i command='' action='' args=0 local i command='' action='' args=0
for ((i = 1; i < cword; i++)); do for ((i = 1; i < cword; i++)); do
@@ -32,7 +32,7 @@ _linux_manager_ca()
*) *)
if [[ -z $command ]]; then if [[ -z $command ]]; then
command=${words[i]} command=${words[i]}
elif [[ $command == @(ca|root) && -z $action ]]; then elif [[ $command == @(ca|root|https) && -z $action ]]; then
action=${words[i]} action=${words[i]}
else else
((args++)) ((args++))
@@ -68,7 +68,7 @@ _linux_manager_ca()
if [[ $cur == -* ]]; then if [[ $cur == -* ]]; then
COMPREPLY=($(compgen -W '--json --help' -- "$cur")) COMPREPLY=($(compgen -W '--json --help' -- "$cur"))
else 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 fi
return return
fi fi
@@ -87,9 +87,10 @@ _linux_manager_ca()
case $command,$action,$args in case $command,$action,$args in
ca,,*) COMPREPLY=($(compgen -W 'csr import' -- "$cur")) ;; ca,,*) COMPREPLY=($(compgen -W 'csr import' -- "$cur")) ;;
root,,*) COMPREPLY=($(compgen -W 'import-crl setup-code' -- "$cur")) ;; 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,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,0) COMPREPLY=($(compgen -W "root $(_linux_manager_ca_python cas)" -- "$cur")) ;;
ca,import,1 | root,import-crl,0) _filedir ;; ca,import,1 | root,import-crl,0 | https,import,0 | https,import-pfx,0) _filedir ;;
esac esac
} && } &&
complete -F _linux_manager_ca linux-manager-ca 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 fi
case $command,${#args[@]} in 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,0) COMPREPLY=($(compgen -W "$(_vpn_config_edit_python settings)" -- "$cur")) ;;
set,1) COMPREPLY=($(compgen -W "$(_vpn_config_edit_python values "${args[0]}")" -- "$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")) ;; remove,0) COMPREPLY=($(compgen -W "$(_vpn_config_edit_python connections)" -- "$cur")) ;;
@@ -82,8 +82,7 @@
"enabled": true, "enabled": true,
"email": "", "email": "",
"web_port": 7444, "web_port": 7444,
"manager_port": 7443, "manager_port": 7443
"caddy_source": "ubuntu"
}, },
"oidc": { "oidc": {
"enabled": false "enabled": false
@@ -4,8 +4,15 @@
{%- if https_email %} {%- if https_email %}
email {{ https_email }} email {{ https_email }}
{%- endif %} {%- endif %}
{%- if https_acme_ca %} {%- if https_acme_provider == 'zerossl' %}
acme_ca {{ https_acme_ca }} 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 %} {%- endif %}
{%- if pki_cas %} {%- if pki_cas %}
skip_install_trust skip_install_trust
@@ -26,8 +33,38 @@
} }
{%- endif %} {%- endif %}
} }
{% if https and (web_enabled or 'https' in pki_publish or acme_cas) %} {% if web_enabled %}
http://:{{ web_port }} {
header -Server
reverse_proxy {{ loopback }}:{{ web_loopback_port }} {
header_down -Server
}
}
{% endif %}
http://:{{ manager_port }} {
header -Server
{%- if redirect %}
redir https://{{ local_fqdn }}:{{ 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 'https' in pki_publish or acme_cas) %}
{{ local_fqdn }}:{{ https_web_port }} { {{ local_fqdn }}:{{ https_web_port }} {
header -Server
{%- if https_tls %}
tls {{ https_tls.cert }} {{ https_tls.key }}
{%- endif %}
{%- if 'https' in pki_publish %} {%- if 'https' in pki_publish %}
handle_path /pki/* { handle_path /pki/* {
root * {{ pki_publish_dir }} root * {{ pki_publish_dir }}
@@ -43,7 +80,9 @@
{%- endfor %} {%- endfor %}
handle { handle {
{%- if web_enabled %} {%- if web_enabled %}
reverse_proxy {{ loopback }}:{{ web_port }} reverse_proxy {{ loopback }}:{{ web_loopback_port }} {
header_down -Server
}
{%- else %} {%- else %}
respond 404 respond 404
{%- endif %} {%- endif %}
@@ -52,6 +91,7 @@
{% endif %} {% endif %}
{%- if https and 'http-80' in pki_publish %} {%- if https and 'http-80' in pki_publish %}
http://{{ local_fqdn }} { http://{{ local_fqdn }} {
header -Server
handle_path /pki/* { handle_path /pki/* {
root * {{ pki_publish_dir }} root * {{ pki_publish_dir }}
file_server file_server
@@ -63,6 +103,10 @@ http://{{ local_fqdn }} {
{% endif %} {% endif %}
{%- if https and 'https-default' in pki_publish %} {%- if https and 'https-default' in pki_publish %}
{{ local_fqdn }}:443 { {{ local_fqdn }}:443 {
header -Server
{%- if https_tls %}
tls {{ https_tls.cert }} {{ https_tls.key }}
{%- endif %}
handle_path /pki/* { handle_path /pki/* {
root * {{ pki_publish_dir }} root * {{ pki_publish_dir }}
file_server file_server
@@ -74,22 +118,41 @@ http://{{ local_fqdn }} {
{% endif %} {% endif %}
{%- if https %} {%- if https %}
{{ local_fqdn }}:{{ https_manager_port }} { {{ local_fqdn }}:{{ https_manager_port }} {
reverse_proxy {{ loopback }}:{{ manager_port }} header -Server
{%- if https_tls %}
tls {{ https_tls.cert }} {{ https_tls.key }}
{%- endif %}
reverse_proxy {{ loopback }}:{{ manager_loopback_port }} {
header_down -Server
}
} }
{% endif %} {% endif %}
{%- if https and metrics_enabled %} {%- if https and metrics_enabled %}
{{ local_fqdn }}:{{ metrics_https_port }} { {{ local_fqdn }}:{{ metrics_https_port }} {
reverse_proxy {{ loopback }}:{{ metrics_port }} header -Server
{%- if https_tls %}
tls {{ https_tls.cert }} {{ https_tls.key }}
{%- endif %}
reverse_proxy {{ loopback }}:{{ metrics_loopback_port }} {
header_down -Server
}
} }
{% endif %} {% endif %}
{%- if webdav %} {%- if webdav %}
{{ local_fqdn }}:{{ webdav_port }} { {{ local_fqdn }}:{{ webdav_port }} {
reverse_proxy {{ loopback }}:{{ webdav_loopback_port }} header -Server
{%- if https_tls %}
tls {{ https_tls.cert }} {{ https_tls.key }}
{%- endif %}
reverse_proxy {{ loopback }}:{{ webdav_loopback_port }} {
header_down -Server
}
} }
{% endif %} {% endif %}
{%- for site in sites %} {%- for site in sites %}
# Site {{ site.name }} # Site {{ site.name }}
{{ site.addresses | join(', ') }} { {{ site.addresses | join(', ') }} {
header -Server
root * {{ site.root }} root * {{ site.root }}
{%- if site.tls == 'ca' %} {%- if site.tls == 'ca' %}
tls { 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
+49 -13
View File
@@ -1,19 +1,27 @@
# Certificates # Certificates
The server's CA: a root CA and issuing CAs that sign the certificates. The root is created by the The server's HTTPS certificate and its CA: a root CA and issuing CAs that sign the certificates.
server, an offline CA, or the root of a Simple CA service whose issuing CA signs the server's The root is created by the server, an offline CA, or the root of a Simple CA service whose issuing
issuing CAs; that is chosen at setup and fixed once the root exists. CA signs the server's issuing CAs; that is chosen at setup and fixed once the root exists.
## Above the tabs ## 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 - **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. as a PFX file protected by a password; the server keeps no copy of the key.
- **Settings:** the names, lifetimes, key type, CRL validity, publishing endpoints and, with a - **Settings:** the names of the P2S and S2S CAs while they do not exist yet, the lifetimes, key
Simple CA root, the URL of the service. type, CRL validity, publishing endpoints and, with a Simple CA root, the URL of the service.
- **Warnings:** what needs attention, such as a CRL about to expire. - **Warnings:** what needs attention, such as a CRL about to expire.
## Tabs ## Tabs
- **Server:** the first tab, shown also while the PKI cannot be read: HTTPS and the name 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 - **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 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 certificate. An offline root takes its certificate with **Import root certificate**, before the
@@ -24,11 +32,39 @@ issuing CAs; that is chosen at setup and fixed once the root exists.
**Reset** for a changed built-in one. **Reset** for a changed built-in one.
- **Extended key usages:** the usages templates may give, with their OIDs; custom ones are added - **Extended key usages:** the usages templates may give, with their OIDs; custom ones are added
with a name and an OID. with a name and an OID.
- **P2S Issuing CA** and **S2S Issuing CA:** the CAs of the VPN users and of site-to-site - **Issuing CAs:** the built-in CAs, P2S for the VPN users, S2S for site-to-site connections and
connections. An active CA gives its CA bundle; a pending CA, waiting for the offline root, gives the Servers Issuing CA `servers` for mTLS certificates and the server's HTTPS certificate, and the
its CSR and takes the certificate the root signed, and one waiting for Simple CA is signed once custom CAs, each with its templates and an optional ACME server. P2S is off while the VPN is,
the server reaches it. and S2S while the router is, until they are switched on. An active CA gives its CA
- **Issuing CAs:** general-purpose CAs, each with its templates and an optional ACME server. bundle; a pending CA, waiting for the offline root, gives its CSR and takes the certificate the
**Add issuing CA**, **Edit** and **Remove**; a removed CA is retired and its certificate revoked. root signed, and one waiting for Simple CA is signed once the server reaches it. **Add issuing
- **Certificates:** each with its kind, template, names, expiry and state; one of another system CA**, **Edit** and **Remove** are for the custom CAs; a removed CA is retired and its
or of the server is revoked after a confirmation with a reason. 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.
## 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. 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.
While HTTPS is on, the Manager's plain HTTP address redirects to its HTTPS address, unless the
installer's `https_disable_auto_redirect` or `https.disable_auto_redirect` says otherwise; the
status page never redirects.
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`.
+9 -8
View File
@@ -1,19 +1,20 @@
# DNS # DNS
The server's name server (PowerDNS), the primary of the server's domains. Every domain has the The server's name server (PowerDNS), the primary of the server's domains, on a page of its own,
same two name servers: the server's FQDN and a secondary name server. The [web sites](sites.md) in the page menu while the name server is on. Every domain has the same name servers: the server's
whose DNS is Router managed get their records in the domain they are in. 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 ## Settings
- **State:** disabled, running, or not running yet; the server installs PowerDNS when it is - **State:** disabled, running, or not running yet. The name server is switched on the
enabled. [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 - **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, 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. wherever that is, not by the server's domains.
- **Secondary name server:** the second NS of every domain, required while the name server is - **Secondary name server:** the second NS of every domain, optional; without it the server's FQDN
enabled. The server notifies the addresses it resolves to of every change and allows them to is the domains' only name server. The server notifies the addresses it resolves to of every
transfer the domains. 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 - **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. 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, - **Listen:** the interfaces port 53 is open on. While IKEv2 or OpenVPN remote access is enabled,
+3 -3
View File
@@ -4,9 +4,9 @@ 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 its users, connections, certificates and services. Members of the server's group `admins` see all
pages; any other user sees only their own account. 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` The VPN, the router, the name server and WebDAV are components switched on the
and `vpn.enabled`). While the VPN is off the page menu has no Remote Access page; while the router [System](system.md) tab, which installs their software. While the VPN is off the page menu has no
is off the Connectivity page shows only its Network tab. Without Docker on the server the page menu 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. has no Docker page.
The help opens at the topic of the page you are on. Links between topics open in this panel; The help opens at the topic of the page you are on. Links between topics open in this panel;
+3 -3
View File
@@ -3,9 +3,9 @@
A tab each for IKEv2, OpenVPN and WireGuard access: the settings, whether the server 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. 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 The page is there while the VPN component is on, switched on the [System](system.md) tab. While
off, the clients reach the networks of `local.cidrs` through NAT from the server's address, on the router component is off, the clients reach the networks of `local.cidrs` through NAT from the
its one interface; while it is on, they are routed with their own addresses. server's address, on its one interface; while it is on, they are routed with their own addresses.
## Edit ## 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 - **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; `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, IKEv2, OpenVPN and WireGuard; and the status web service and its port.
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`.
- **Services:** the state of each of the server's systemd services and of Caddy; the chip on the - **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. 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 - **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, - **Configuration:** the sections of the server's configuration the other pages do not show,
among them the status web service (`web`) and HTTPS (`https`). 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 ## Updates
- **Check update** asks the server's package repository for newer versions. - **Check update** asks the server's package repository for newer versions.
+12 -9
View File
@@ -1,16 +1,17 @@
# Web sites # Web sites
Static web sites that Caddy serves on the server, each from its own folder, 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 `/var/lib/linux-manager/sites/<name>`. The files of a site are on the [Files](site-files.md) tab,
the name server of their domain on the [DNS](dns.md) tab. and the name server of their domain on the [DNS](dns.md) page.
## Settings ## Settings
- **State:** whether the sites are served. - **State:** whether the sites are served.
- **Largest upload:** the largest file or zip archive the Files tab and the server's API take. - **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 ## Columns
@@ -18,12 +19,12 @@ the name server of their domain on the [DNS](dns.md) tab.
name on its port. name on its port.
- **Port** and **Listen:** the TCP port, and the interfaces its firewall opens: internal, - **Port** and **Listen:** the TCP port, and the interfaces its firewall opens: internal,
external or both. external or both.
- **TLS:** None (plain HTTP), Let's Encrypt, an issuing CA of the Certificates page, or a - **TLS:** None (plain HTTP), ACME, from the CA set on the Server tab of the Certificates page,
certificate and key given with the site. 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. - **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 - **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 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 DNS settings), **Internal interface IP** or **External interface IP**. A host name in none of
the server's domains gets no record. the server's domains gets no record.
@@ -39,9 +40,11 @@ the DNS of its domain.
## Rules ## 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. - 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. - 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. - 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 # 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 ## 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. - 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 - Only one upgrade runs at a time: this one or the upgrade of `linux-manager` on the
[Overview](router.md) tab. [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). up).
- An SSH key pair for `admin_ssh_public_key`. - 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 - 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 project's Gitea Debian registry). See [Building](../../README.md#building) for
`build.sh`/`publish.sh`. `build.py`/`publish.py`.
- That repository must allow anonymous reads, since the server pulls the package with no - 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 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 upload, only reads are anonymous. This is a one-time change made on the Gitea side, outside
this repository. this repository.
+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). or a service account).
- An SSH key pair for `admin_ssh_public_key`. - 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 - 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 project's Gitea Debian registry). See [Building](../../README.md#building) for
`build.sh`/`publish.sh`. That repository must allow anonymous reads, since the server pulls `build.py`/`publish.py`. That repository must allow anonymous reads, since the server pulls
the package with no credentials configured. the package with no credentials configured.
## Usage ## Usage
Executable
+68
View File
@@ -0,0 +1,68 @@
#!/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 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():
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 -60
View File
@@ -1,25 +1,39 @@
#!/usr/bin/env python3 #!/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 The newest entry of CHANGELOG.md (bin/changelog.py reads it) is released: its heading gets 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 current time, "## 0.5.1 - 2026-11-24 10:00:00 +0100", and everything is committed with its summary
starts the release workflow. Once the release succeeds, .dev-build.serial, the serial of the last paragraph, its lines joined, as the message. The commit marks the entry as released: a second run
dev build (bin/lm-dev-build.py), is written as 0, so the dev builds of the next entry start at for the same entry is refused, and the next change needs a new entry. With --push, the version of
~dev1. 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 argparse
import datetime
import json
import pathlib import pathlib
import shlex import shlex
import subprocess import subprocess
import sys import sys
ROOT = pathlib.Path(__file__).resolve().parent ROOT = pathlib.Path(__file__).resolve().parent
CHANGELOG = ROOT / 'debian-package' / 'debian' / 'changelog' sys.path.insert(0, str(ROOT / 'bin'))
DEV_SERIAL = ROOT / '.dev-build.serial'
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 DRY_RUN = False
@@ -34,67 +48,63 @@ def git(*args):
sys.exit(result.returncode) 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(): def main():
global DRY_RUN global DRY_RUN
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) 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',
parser.add_argument('-n', '--dry-run', action='store_true', help='print the git commands instead of running them') help='print the changes and the git commands instead of making them')
parser.add_argument('--no-push', action='store_true', help='commit and tag, but do not push') 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() args = parser.parse_args()
DRY_RUN = args.dry_run DRY_RUN = args.dry_run
message = args.message or summary() text = CHANGELOG.read_text(encoding='utf-8')
if not message: try:
sys.exit(f'no commit message: pass -m, or start the newest entry of {CHANGELOG} with a summary paragraph ' found = changelog.entries(text)
'not starting with "*", indented by two spaces, with a blank line above and below it') except ValueError as error:
tag = version() 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, if subprocess.run(['git', 'rev-parse', '-q', '--verify', f'refs/tags/{tag}'], cwd=ROOT,
capture_output=True).returncode == 0: capture_output=True).returncode == 0:
sys.exit(f'tag {tag} exists; add a new changelog entry first') sys.exit(f'tag {tag} exists; add a new changelog entry first')
git('add', '-A') log = subprocess.run(['git', 'log', '--format=%s'], cwd=ROOT, capture_output=True, text=True)
git('commit', '-m', message) committed = log.returncode == 0 and message in log.stdout.splitlines()
git('tag', tag) dirty = subprocess.run(['git', 'status', '--porcelain'], cwd=ROOT, capture_output=True,
if not args.no_push: text=True).stdout.strip() != ''
git('push', 'origin', 'main', '--tags') if committed and dirty:
if DRY_RUN: sys.exit(f'{tag} is released; add a new changelog entry for the changes')
print(f'echo 0 > {shlex.quote(str(DEV_SERIAL))}') if committed and not args.push:
else: sys.exit(f'{tag} is released; add a new changelog entry, or publish it with --push')
DEV_SERIAL.write_text('0\n', encoding='utf-8') 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 return 0
+140 -46
View File
@@ -3,20 +3,26 @@
The scripts are in `bin/` of the repository; this directory holds their data: `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. `configs/`, `cloud-init/`, `repo/` and the files copied into instances.
`bin/lm-dev-run.py` installs the newest `out/linux-manager_*_all.deb` into instances of an LXD `bin/lm-dev-run.py` installs the package built last, a release in `out/` or a dev build in
remote and checks the router and VPN components in three scenarios: `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; - `core`: one interface, router and VPN off;
- `nat`: VPN on, router off, one interface; WireGuard and OpenVPN clients reach a target through - `nat`: VPN on, router off, one interface; WireGuard and OpenVPN clients reach a target through
NAT, then the VPN is switched off; 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 - `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 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 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 `lm-dev-run.py`. scenario is a module in `scenarios/` whose `run(lab)` uses the `Lab` class of `lm-dev-run.py`.
`wireguard_peer.py` and `echo.py` are copied into the instances: the first gives the test user a `wireguard_peer.py`, `echo.py` and `oidc_login.py` are copied into the instances: the first gives
WireGuard peer on the server, the second answers HTTP with the client's address. 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 ```sh
export LXD_REMOTE=... export LXD_REMOTE=...
@@ -24,7 +30,7 @@ export LXD_POOL=...
``` ```
```sh ```sh
./build.sh ./build.py
bin/lm-dev-run.py core nat s2s bin/lm-dev-run.py core nat s2s
``` ```
@@ -41,32 +47,91 @@ Options:
| `--project` | `LXD_TEST_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 | | `--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 | | `--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 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. The its end. Its first instance is its Vault, `lm-vault` on the bridge `lmt-vault` (`10.99.99.0/24`),
administrator's name and password are set as `ADMIN_USERNAME` and `ADMIN_PASSWORD` in the reached by the Mac and the instances on the LXD host's address, port 8200, through a proxy
repository's `.env`, keeping its other lines, and the key is written to `tmp/remote-test.env`. 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 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. when the host kernel has no WireGuard module.
The configurations in `configs/` have placeholders that are filled in for each server: 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; - `@ETH0@` and `@ETH1@`: the names of its interfaces;
- `@CIDR0@`: the network of its first address. - `@CIDR0@`: the network of its first address.
## 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"
}
```
## A VM to work with ## A VM to work with
`lm-dev-vm.py create` launches one server VM, `lm-dev` by default, on the LXD remote and leaves `lm-dev-vm.py create` launches one server VM, `lm-dev` by default, on the LXD remote and leaves
it running. The VM is created in a project, the test project `lm-dev` by default, with that 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 project's default profile, and takes its address from DHCP. It gets the package with the
administrator `admin` and a generated password, set as `ADMIN_USERNAME` and `ADMIN_PASSWORD` in the administrator `admin` and a generated password, kept as `username` and `password` in
repository's `.env`, and a configuration from `configs/`, `core.json` by default; `@ETH0@` is the `.lm-dev-config/vm-<project>-<vm>.json`, a TOTP token for `admin` in the project's Vault unless `--no-otp` is given,
interface of the VM's default route. and a configuration from `configs/`, `core.json` by default; `@ETH0@` is the interface of the VM's
default route.
In a test project made by `lm-dev-lxd-project.py`, the VM installs the package from the project's In a test project made by `lm-dev-lxd-project.py`, the VM installs the package from the project's
repository, so later dev builds reach it as updates; in another project it installs the newest repository, so later dev builds reach it as updates; in another project it installs `--deb`, or
`out/linux-manager_*_all.deb`. The leased address is pinned on the VM's NIC, and these ports lead 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: to the VM:
- `7080` to the Manager; - `7080` to the Manager;
@@ -74,13 +139,13 @@ to the VM:
- `2222` to SSH, port `22`. - `2222` to SSH, port `22`.
In a test project they lead through a network forward on the project's `wan`, whose listen address In a test project they lead through a network forward on the project's `wan`, whose listen address
LXD allocates from the uplink's `--routes`, as LXD refuses NAT proxy devices in a project with is `--forward-address`, or else one LXD allocates from the uplink's `--routes`, as LXD refuses
networks of its own. In another project NAT proxy devices listen on the LXD host address NAT proxy devices in a project with networks of its own. In another project NAT proxy devices
`--listen`, by default the IPv4 address of the host in the remote's URL (`lxc remote list`), which listen on the LXD host address `--listen`, by default the IPv4 address of the host in the remote's
must be an address of the LXD host itself. URL (`lxc remote list`), which must be an address of the LXD host itself.
The script prints the VM's address, the administrator's password, the URLs, the command of a The script prints the VM's address, where the administrator's password is kept, the URLs, the
shell in it and the command that removes it. command of a shell in it and the command that removes it; it never prints the password.
```sh ```sh
bin/lm-dev-vm.py create bin/lm-dev-vm.py create
@@ -90,8 +155,10 @@ bin/lm-dev-vm.py create
bin/lm-dev-vm.py remove bin/lm-dev-vm.py remove
``` ```
`remove` deletes the VM, its forward and `tmp/vm-<vm>.env`, its pre-shared key; `.env` is left as `create` needs the project's Vault (`lm-dev-lxd-project.py vault create`): the VM gets its
it is. Options: AppRole there, and reads the preseed and the configuration, kept as `<vm>/preseed` and
`<vm>/config`, and creates the TOTP key `<vm>-admin` with it. `remove` deletes the VM, its forward,
its `vm-<project>-<vm>.json` and what the Vault keeps for it. Options:
| Option | Variable | Default | Meaning | | Option | Variable | Default | Meaning |
|---|---|---|---| |---|---|---|---|
@@ -101,6 +168,9 @@ it is. Options:
| `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of the VM | | `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of the VM |
| `--config` | | `core.json` | The configuration from `configs/` | | `--config` | | `core.json` | The configuration from `configs/` |
| `--listen` | `LXD_LISTEN` | the remote URL's host | Outside a test project, the address the proxies listen on | | `--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 |
| `--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 ## A test project with dev builds
@@ -114,11 +184,21 @@ project has:
gateway; gateway;
- a default profile with a root disk on the pool and `eth0` on `wan`; - 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, - 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 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`. `.lm-dev-config/lxd-project-<project>.json`, and the repository's key to
`remove` deletes the project's instances, its networks, the project and those files. `.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 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 LAN, whose host address stays on the bridge. `uplink setup` creates on it, once per remote, the
@@ -156,6 +236,7 @@ bin/lm-dev-lxd-project.py remove
| `--pool` | `LXD_POOL` | required by `create` | The storage pool of the project's root disks | | `--pool` | `LXD_POOL` | required by `create` | The storage pool of the project's root disks |
| `--project` | `LXD_PROJECT` | `lm-dev` | The project | | `--project` | `LXD_PROJECT` | `lm-dev` | The project |
| `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of the repository container | | `--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 | | `--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 | | `--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 | | `--gateway` | `LXD_UPLINK_GATEWAY` | required by `uplink setup` | The LAN's gateway, address/prefix |
@@ -163,12 +244,12 @@ bin/lm-dev-lxd-project.py remove
| `--ovn-ranges` | `LXD_UPLINK_OVN_RANGES` | required by `uplink setup` | LAN addresses for OVN routers | | `--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 | | `--routes` | `LXD_UPLINK_ROUTES` | required by `uplink setup` | A LAN subnet for network forwards |
`lm-dev-build.py` builds and publishes the next dev build. Its version is the newest changelog `lm-dev-build.py` builds and publishes the next dev build. Its version is the Debian version of
entry's with `~dev<N>` before the Debian revision, `0.41.0~dev7-1` for `0.41.0-1`, so the release the newest entry of `CHANGELOG.md` with `~dev<N>` before the Debian revision, `0.41.0~dev7-1` for
of that entry is newer than its dev builds. `N` is that of the last dev build, kept in `0.41.0`, so the release of that entry is newer than its dev builds. `N` is that of the last dev build,
`.dev-build.serial` of the repository; each build that succeeds writes its own, one higher, and `LXD_DEV_BUILD_SERIAL`, 0 by default; each build that succeeds writes its own, one higher, into
`release.py` writes 0 when it releases, so the next entry's builds start at `~dev1`. `./build.sh` builds it, with `CONTAINER_RUNTIME` and `DOCKER_CONTEXT` from the `.lm-dev-config/settings.json`, and `release.py` writes 0 there when it releases, so the next
environment; the build is moved to `out/dev/`, copied into the repository and published there. A 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` VM of the project then gets it with Check update and Upgrade in the Manager, or `apt-get update`
and `apt-get upgrade`. and `apt-get upgrade`.
@@ -182,36 +263,40 @@ read from its state file, so the script takes no `--remote`.
## A TOTP token for a user of a test VM ## A TOTP token for a user of a test VM
`bin/lm-dev-otp-register.py` enrols a new TOTP token for a user of a VM, `admin` of `lm-dev` by `bin/lm-dev-otp-register.py` enrols a new TOTP token for a user of a VM, `admin` of `lm-dev` by
default, through `lxc exec`: in the VM, as root, the package's `linuxmanager_users` makes a new default, replacing a token the user had. The project's Vault generates the key `<vm>-<user>` in its
secret and stores it once a code the script computes from it verifies, replacing a token the user TOTP engine and hands it to the VM (see Secrets), where the package's `linuxmanager_users` stores
had. The secret, base32, is then written to the file `--secret-file` or `OTP_FILE` names, it. A new token of the VM's administrator replaces `otp_url` in `vm-<project>-<vm>.json`.
readable by its owner only; `otp.py code` prints its codes (see below). `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 ```sh
export OTP_FILE=tmp/admin.otp
bin/lm-dev-otp-register.py bin/lm-dev-otp-register.py
``` ```
```sh
bin/lm-dev-otp-code.py
```
| Option | Variable | Default | Meaning | | Option | Variable | Default | Meaning |
|---|---|---|---| |---|---|---|---|
| `--secret-file` | `OTP_FILE` | required | The file the secret is written to | | `--remote` | `LXD_REMOTE` | required by `lm-dev-otp-register.py` | The `lxc` remote |
| `--remote` | `LXD_REMOTE` | required | The `lxc` remote |
| `--project` | `LXD_PROJECT` | `lm-dev` | The project of the VM | | `--project` | `LXD_PROJECT` | `lm-dev` | The project of the VM |
| `--vm` | | `lm-dev` | The name of the VM | | `--vm` | | `lm-dev` | The name of the VM |
| `--user` | | `admin` | The user to enrol | | `--user` | | `admin` | The user |
## A command-line authenticator app ## 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 `bin/otp.py` is an authenticator app on the command line, in place of one on a phone, not tied to
Linux Manager or LXD. It keeps a base32 secret in the file `--secret-file` or `OTP_FILE` names, Linux Manager or LXD. It keeps a secret in the file `--secret-file` or `OTP_FILE` names, readable
readable by its owner only. The codes are by its owner only: the base32 secret alone, or with `--url` its `otpauth://` URI, without a line
RFC 6238's, SHA-1, 6 digits and 30 seconds by default. 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: Options of both actions:
| Option | Variable | Default | Meaning | | Option | Variable | Default | Meaning |
|---|---|---|---| |---|---|---|---|
| `--secret-file` | `OTP_FILE` | required | The file of the base32 secret | | `--secret-file` | `OTP_FILE` | required | The file of the base32 secret or its `otpauth://` URI |
| `--algorithm` | | `sha1` | `sha1`, `sha256` or `sha512` | | `--algorithm` | | `sha1` | `sha1`, `sha256` or `sha512` |
| `--digits` | | `6` | The digits of a code, 6 to 10 | | `--digits` | | `6` | The digits of a code, 6 to 10 |
| `--period` | | `30` | The seconds a code is valid | | `--period` | | `30` | The seconds a code is valid |
@@ -223,9 +308,18 @@ algorithm, digits and period, for a server or an app that enrols a given secret:
bin/otp.py new --account admin --issuer lm-dev 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 | | Option | Default | Meaning |
|---|---|---| |---|---|---|
| `--account`, `--issuer` | none | The label of the URI | | `--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 | | `--force` | off | Replace an existing secret |
`code` prints the current code of the secret, for the Manager's sign-in, SSH or `sudo`: `code` prints the current code of the secret, for the Manager's sign-in, SSH or `sudo`:
@@ -240,5 +334,5 @@ bin/otp.py code
## Scope of the tests ## Scope of the tests
Not covered by `lm-dev-run.py`: IKEv2 client access, HTTPS with Let's Encrypt, the OpenID Not covered by `lm-dev-run.py`: IKEv2 client access, HTTPS with Let's Encrypt, passkeys,
Provider and passkeys, PowerDNS answering from outside, and the Azure and GCP platform modules. 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
+9
View File
@@ -0,0 +1,9 @@
{
"general": {"platform": "generic", "mode": "manual"},
"router": {"enabled": false},
"vpn": {"enabled": false},
"interfaces": {"external": "@ETH0@"},
"wan": {"local_fqdn": "lm-oidc.test"},
"https": {"enabled": true, "certificate": "ca"},
"oidc": {"enabled": true}
}
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/python3
"""The test project's Vault seen from an instance, which logs in with its own AppRole: lm-dev-vault init|get|totp.
lm-dev-vault init ROLE
lm-dev-vault get PATH FIELD OUTPUT MODE
lm-dev-vault totp KEY ISSUER ACCOUNT OUTPUT MODE
/etc/vault (0700) holds the Vault's URL (url), the role ID of the instance's AppRole (role-id) and its secret ID
(secret-id), both 0600. init takes the secret ID from the wrapping token in secret-id.wrapped, which is removed: the
token's creation path must be the secret-id request of the role ROLE, and it is unwrapped once. get logs in and writes
the field FIELD of the KV v2 secret PATH to OUTPUT with MODE, octal. totp logs in, has the Vault generate the TOTP key
KEY for ACCOUNT of ISSUER, SHA1, 6 digits and 30 seconds, and writes its otpauth URI to OUTPUT with MODE. No argument
is a secret.
"""
import json
import os
import pathlib
import stat
import sys
import urllib.error
import urllib.request
ETC = pathlib.Path('/etc/vault')
KV_MOUNT = 'kv'
TOTP_MOUNT = 'totp'
def call(path, body=None, token=None, method='POST'):
"""Send the request to the Vault; the JSON answer."""
url = (ETC / 'url').read_text(encoding='utf-8').strip()
headers = {'Content-Type': 'application/json'}
if token:
headers['X-Vault-Token'] = token
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:
return json.loads(response.read() or b'{}')
except urllib.error.HTTPError as error:
sys.exit(f'lm-dev-vault: {method} {path}: {error.code}')
except (urllib.error.URLError, OSError) as error:
sys.exit(f'lm-dev-vault: {url} cannot be reached: {error}')
def write(output, text, mode):
"""Write the text to the regular file output with the octal mode."""
descriptor = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, int(mode, 8))
if not stat.S_ISREG(os.fstat(descriptor).st_mode):
os.close(descriptor)
sys.exit(f'lm-dev-vault: {output} is not a regular file')
os.ftruncate(descriptor, 0)
os.fchmod(descriptor, int(mode, 8))
with os.fdopen(descriptor, 'w', encoding='utf-8') as handle:
handle.write(text)
def login():
"""A token of the instance's AppRole."""
answer = call('/v1/auth/approle/login', {'role_id': (ETC / 'role-id').read_text(encoding='utf-8').strip(),
'secret_id': (ETC / 'secret-id').read_text(encoding='utf-8').strip()})
return answer['auth']['client_token']
def main():
action, arguments = (sys.argv[1], sys.argv[2:]) if len(sys.argv) > 1 else (None, [])
if action == 'init' and len(arguments) == 1:
wrapped = ETC / 'secret-id.wrapped'
try:
token = wrapped.read_text(encoding='utf-8').strip()
finally:
wrapped.unlink(missing_ok=True)
expected = f'auth/approle/role/{arguments[0]}/secret-id'
created = call('/v1/sys/wrapping/lookup', {'token': token}).get('data', {}).get('creation_path')
if created != expected:
sys.exit(f'lm-dev-vault: the token wraps {created}, not {expected}')
write(ETC / 'secret-id', call('/v1/sys/wrapping/unwrap', token=token)['data']['secret_id'] + '\n', '0600')
elif action == 'get' and len(arguments) == 4:
path, field, output, mode = arguments
values = call(f'/v1/{KV_MOUNT}/data/{path}', token=login(), method='GET')['data']['data']
if field not in values:
sys.exit(f'lm-dev-vault: {path} has no {field}')
write(output, values[field], mode)
elif action == 'totp' and len(arguments) == 5:
key, issuer, account, output, mode = arguments
answer = call(f'/v1/{TOTP_MOUNT}/keys/{key}',
{'generate': True, 'exported': True, 'qr_size': 0, 'issuer': issuer, 'account_name': account,
'algorithm': 'SHA1', 'digits': 6, 'period': 30}, token=login())
write(output, answer['data']['url'] + '\n', mode)
else:
sys.exit('usage: lm-dev-vault init ROLE | get PATH FIELD OUTPUT MODE | totp KEY ISSUER ACCOUNT OUTPUT MODE')
if __name__ == '__main__':
main()
+63
View File
@@ -0,0 +1,63 @@
"""Sign a user in at the server's OpenID Provider as a browser would, in the client of the oidc scenario.
It reads the authorization URL a relying party made from /run/lm-dev/oidc-url, the user's name, password and TOTP code
from /run/lm-dev/oidc-name, /run/lm-dev/oidc-password and /run/lm-dev/oidc-code, and removes the password and the code,
trusts the server's root CA in /root/oidc-root.pem, opens the URL, which answers the sign-in page, and posts the page's
form to /oidc/login without following the redirect. It prints {"page", "status", "location"} as JSON: whether the
sign-in page came, the status of the sign-in, and the Location of its redirect, null without one.
python3 oidc_login.py
"""
import json
import os
import ssl
import sys
import urllib.error
import urllib.parse
import urllib.request
HANDOVER = '/run/lm-dev'
ROOT_PEM = '/root/oidc-root.pem'
class NoRedirect(urllib.request.HTTPRedirectHandler):
"""A redirect is answered as it is, not followed."""
def redirect_request(self, request, fp, code, message, headers, new_url):
return None
def read(name, remove=False):
path = os.path.join(HANDOVER, name)
with open(path, encoding='utf-8') as handle:
value = handle.read().strip()
if remove:
os.remove(path)
return value
def main():
url = read('oidc-url')
name = read('oidc-name')
password = read('oidc-password', remove=True)
code = read('oidc-code', remove=True)
context = ssl.create_default_context(cafile=ROOT_PEM)
opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=context), NoRedirect())
with opener.open(url, timeout=30) as response:
page = response.status == 200 and 'name="password"' in response.read().decode(errors='replace')
parts = urllib.parse.urlsplit(url)
form = urllib.parse.urlencode({'request': parts.query, 'name': name, 'password': password, 'code': code}).encode()
request = urllib.request.Request(f'{parts.scheme}://{parts.netloc}/oidc/login', data=form, method='POST',
headers={'Content-Type': 'application/x-www-form-urlencoded'})
try:
with opener.open(request, timeout=30) as response:
status, location = response.status, response.headers.get('Location')
except urllib.error.HTTPError as error:
status, location = error.code, error.headers.get('Location')
print(json.dumps({'page': page, 'status': status, 'location': location}))
return 0
if __name__ == '__main__':
sys.exit(main())
+3 -1
View File
@@ -19,13 +19,15 @@ def run(lab):
'lm-core', 'cat', '/etc/ufw/before.rules') 'lm-core', 'cat', '/etc/ufw/before.rules')
for unit in ('strongswan', 'wg-quick@wg0', 'openvpn-server@linux-manager', 'linux-manager-resolver'): for unit in ('strongswan', 'wg-quick@wg0', 'openvpn-server@linux-manager', 'linux-manager-resolver'):
lab.refuse(f'core: {unit} inactive', r'^active', 'lm-core', 'systemctl', 'is-active', unit) lab.refuse(f'core: {unit} inactive', r'^active', 'lm-core', 'systemctl', 'is-active', unit)
lab.refuse('core: no VPN or router package installed', r'(?m)^installed$', 'lm-core', 'sh', '-c',
"dpkg-query -W -f='${db:Status-Status}\\n' strongswan-swanctl openvpn 2>/dev/null")
lab.expect('core: schema under the PEN arc', r"1\.3\.6\.1\.4\.1\.67380\.10\.1\.2\.2\.1 NAME 'linuxManagerAccount'", lab.expect('core: schema under the PEN arc', r"1\.3\.6\.1\.4\.1\.67380\.10\.1\.2\.2\.1 NAME 'linuxManagerAccount'",
'lm-core', 'slapcat', '-n', '0', '-o', 'ldif-wrap=no') 'lm-core', 'slapcat', '-n', '0', '-o', 'ldif-wrap=no')
lab.expect('core: base DN dc=linux-manager,dc=local', r'^dn: dc=linux-manager,dc=local$', lab.expect('core: base DN dc=linux-manager,dc=local', r'^dn: dc=linux-manager,dc=local$',
'lm-core', 'slapcat', '-b', 'dc=linux-manager,dc=local', '-o', 'ldif-wrap=no') 'lm-core', 'slapcat', '-b', 'dc=linux-manager,dc=local', '-o', 'ldif-wrap=no')
status = lab.json_of('lm-core', 'linux-manager-ca', '--json', 'status') or {} status = lab.json_of('lm-core', 'linux-manager-ca', '--json', 'status') or {}
states = {authority.get('name'): authority.get('state') for authority in status.get('authorities', [])} states = {authority.get('name'): authority.get('state') for authority in status.get('authorities', [])}
lab.result('core: p2s and s2s CAs missing', states.get('p2s') == 'missing' and states.get('s2s') == 'missing') lab.result('core: p2s and s2s CAs off', states.get('p2s') == 'off' and states.get('s2s') == 'off')
lab.result('core: VPN user added', lab.vpn_user('lm-core')) lab.result('core: VPN user added', lab.vpn_user('lm-core'))
user = lab.alice('lm-core') user = lab.alice('lm-core')
lab.result('core: VPN user has no certificate', user is not None and not user.get('certificate')) lab.result('core: VPN user has no certificate', user is not None and not user.get('certificate'))
+2 -2
View File
@@ -47,8 +47,8 @@ def run(lab):
lab.skip('nat: WireGuard (no wireguard module on the host)') lab.skip('nat: WireGuard (no wireguard module on the host)')
profile = (lab.json_of('lm-nat', 'linux-manager-user', '--json', 'profile', 'alice') or {}).get('profile', '') profile = (lab.json_of('lm-nat', 'linux-manager-user', '--json', 'profile', 'alice') or {}).get('profile', '')
lab.push_text(profile, 'lm-nat-client', '/root/alice.ovpn', '0600') lab.hand_over('lm-nat-client', 'openvpn-profile', profile, '/root/alice.ovpn')
lab.push_text(f'alice\n{lab.admin_password}\n', 'lm-nat-client', '/root/alice.pass', '0600') lab.hand_over('lm-nat-client', 'alice', f'alice\n{lab.admin_password}\n', '/root/alice.pass')
lab.on('lm-nat-client', 'sh', '-c', f'echo "{server} lm-nat.test" >>/etc/hosts') lab.on('lm-nat-client', 'sh', '-c', f'echo "{server} lm-nat.test" >>/etc/hosts')
lab.on('lm-nat-client', 'openvpn', '--config', '/root/alice.ovpn', '--auth-user-pass', '/root/alice.pass', lab.on('lm-nat-client', 'openvpn', '--config', '/root/alice.ovpn', '--auth-user-pass', '/root/alice.pass',
'--route-nopull', '--disable-dco', '--route', target, '255.255.255.255', '--route-nopull', '--disable-dco', '--route', target, '255.255.255.255',
+111
View File
@@ -0,0 +1,111 @@
"""OpenID Provider: the lab's Vault signs the user alice in through the server's provider, as a relying party
(auth/oidc) with the authorization code flow and PKCE, the sign-in driven in a client as a browser would."""
import secrets
import urllib.parse
from lm_dev import TESTS, VaultError, enrol_otp, otp_code, store_secret, vault_call
#: The FQDN of the server, the host of its issuer.
FQDN = 'lm-oidc.test'
#: The server's OpenID Provider, the HTTPS site of its web service.
ISSUER = f'https://{FQDN}:7444'
#: The redirect URI of Vault's CLI convention, registered on both sides; the driver reads it, nothing follows it.
REDIRECT = 'http://localhost:8250/oidc/callback'
#: The server's root CA, which the server trusts and publishes.
ROOT_PEM = '/usr/local/share/ca-certificates/linux-manager-ca.crt'
def vault(lab, method, path, body=None, token=None):
"""A call to the lab's Vault with the root token, or the token given; the answer, or None with the problem printed."""
try:
return vault_call(lab.vault['url'], method, path, body, token or lab.vault['root_token'])
except VaultError as error:
print(f'oidc: {error}')
return None
def sign_in(lab, url, code):
"""Hand the client the authorization URL, alice's password and the code, and run the driver; its answer or {}."""
ok = (lab.push_text(url, 'lm-oidc-client', '/run/lm-dev/oidc-url') and
lab.push_text('alice', 'lm-oidc-client', '/run/lm-dev/oidc-name') and
lab.hand_over('lm-oidc-client', 'oidc-password', lab.admin_password, '/run/lm-dev/oidc-password') and
lab.hand_over('lm-oidc-client', 'oidc-code', code, '/run/lm-dev/oidc-code'))
return (lab.json_of('lm-oidc-client', 'python3', '/root/oidc_login.py') or {}) if ok else {}
def run(lab):
lab.network('lmt-oidc-ext', '172.31.12.1/24')
lab.instance('lm-oidc', 'vm', 'server.yaml', ('lmt-oidc-ext', '00:16:3e:4c:12:10', '172.31.12.10/24', '172.31.12.1'))
lab.instance('lm-oidc-client', 'container', 'client.yaml',
('lmt-oidc-ext', '00:16:3e:4c:12:30', '172.31.12.30/24', '172.31.12.1'))
if not lab.ready('lm-oidc', 'lm-oidc-client'):
lab.result('oidc: instances ready', False)
lab.result('oidc: package installed and configured', lab.server('lm-oidc', 'oidc.json'))
server = str(lab.address('lm-oidc').ip)
lab.result('oidc: user alice added', lab.vpn_user('lm-oidc'))
lab.result('oidc: TOTP token of alice enrolled', enrol_otp(lab.remote, lab.project, 'lm-oidc', 'alice') is None)
# The client: a service account with the redirect URI, its secret handed over as a file and kept in the Vault.
secret = secrets.token_urlsafe(24)
store_secret(lab.vault, 'lm-oidc/vault-client', {'secret': secret})
file = '/run/lm-dev/vault-client.secret'
registered = lab.hand_over('lm-oidc', 'vault-client', f'{secret}\n', file) and lab.on(
'lm-oidc', 'sh', '-c', f'linux-manager-user --json add vault --service --display-name Vault --redirect-uri '
f'{REDIRECT} < {file}; status=$?; rm -f {file}; exit $status').returncode == 0
lab.result('oidc: client vault registered', registered)
root = lab.on('lm-oidc', 'cat', ROOT_PEM).stdout
hosts = f'echo "{server} {FQDN}" >>/etc/hosts'
lab.on('lm-oidc-client', 'sh', '-c', hosts)
lab.push_text(root, 'lm-oidc-client', '/root/oidc-root.pem')
lab.push(TESTS / 'oidc_login.py', 'lm-oidc-client', '/root/oidc_login.py')
lab.expect('oidc: discovery answers over HTTPS with the server CA', rf'"issuer": ?"{ISSUER}"',
'lm-oidc-client', 'curl', '-s', '--cacert', '/root/oidc-root.pem',
f'{ISSUER}/.well-known/openid-configuration')
# Vault, a relying party of the server, configured with the root token.
lab.on('lm-vault', 'sh', '-c', hosts)
vault(lab, 'POST', '/v1/sys/auth/oidc', {'type': 'oidc'})
configured = vault(lab, 'POST', '/v1/auth/oidc/config', {
'oidc_discovery_url': ISSUER, 'oidc_discovery_ca_pem': root, 'oidc_client_id': 'vault',
'oidc_client_secret': secret, 'default_role': 'lab'})
lab.result('oidc: Vault reads the discovery document', configured is not None)
role = vault(lab, 'POST', '/v1/auth/oidc/role/lab', {
'role_type': 'oidc', 'user_claim': 'preferred_username', 'groups_claim': 'groups',
'oidc_scopes': ['profile', 'email', 'groups'], 'allowed_redirect_uris': [REDIRECT],
'claim_mappings': {'email': 'email'}, 'token_policies': ['default']})
lab.result('oidc: Vault role lab written', role is not None)
# The authorization code flow: Vault's URL, the sign-in in the client, the code back to Vault.
url = ((vault(lab, 'POST', '/v1/auth/oidc/oidc/auth_url', {'role': 'lab', 'redirect_uri': REDIRECT}) or {})
.get('data') or {}).get('auth_url') or ''
query = urllib.parse.parse_qs(urllib.parse.urlsplit(url).query)
lab.result('oidc: authorization URL asks for PKCE S256', query.get('code_challenge_method') == ['S256'])
answer = sign_in(lab, url, otp_code(lab.project, 'lm-oidc', 'alice')) if url else {}
lab.result('oidc: sign-in page shown', answer.get('page') is True)
location = urllib.parse.parse_qs(urllib.parse.urlsplit(answer.get('location') or '').query)
lab.result('oidc: sign-in redirects with a code and the state',
answer.get('status') == 302 and bool(location.get('code')) and location.get('state') == query.get('state'))
login = vault(lab, 'GET', '/v1/auth/oidc/oidc/callback?' + urllib.parse.urlencode({
'state': (location.get('state') or [''])[0], 'code': (location.get('code') or [''])[0],
'nonce': (query.get('nonce') or [''])[0]})) if location.get('code') else None
token = ((login or {}).get('auth') or {}).get('client_token')
lab.result('oidc: Vault issues a token for alice', bool(token))
looked = vault(lab, 'GET', '/v1/auth/token/lookup-self', token=token) if token else None
entity = (looked or {}).get('data', {}).get('entity_id')
aliases = ((vault(lab, 'GET', f'/v1/identity/entity/id/{entity}') or {}).get('data') or {}).get('aliases', []) \
if entity else []
alias = next((item for item in aliases if item.get('name') == 'alice'), {})
lab.result('oidc: the token is of the entity alias alice', bool(alias))
lab.result('oidc: the email claim is mapped', (alias.get('metadata') or {}).get('email') == 'alice@example.org')
# A wrong code: the sign-in page again, no redirect.
url = ((vault(lab, 'POST', '/v1/auth/oidc/oidc/auth_url', {'role': 'lab', 'redirect_uri': REDIRECT}) or {})
.get('data') or {}).get('auth_url') or ''
wrong = f'{(int(otp_code(lab.project, "lm-oidc", "alice")) + 1) % 1000000:06d}'
answer = sign_in(lab, url, wrong) if url else {}
lab.result('oidc: a wrong code is refused without a redirect', answer.get('status') == 401 and not answer.get('location'))
+55 -27
View File
@@ -11,15 +11,19 @@ import { useEffect, useState, type FormEvent } from 'react'
import OtpDialog from './OtpDialog.tsx' import OtpDialog from './OtpDialog.tsx'
import PasskeyDialog from './PasskeyDialog.tsx' import PasskeyDialog from './PasskeyDialog.tsx'
import ProfileDialog from './ProfileDialog.tsx' import ProfileDialog from './ProfileDialog.tsx'
import { Section } from './ServerPanel.tsx' import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import Toolbar from './Toolbar.tsx'
import { ACCOUNT_SHAPE, CODE_PATTERN, USER_SHAPE, request, type Account, type User } from './api.ts' import { ACCOUNT_SHAPE, CODE_PATTERN, USER_SHAPE, request, type Account, type User } from './api.ts'
/** The localStorage key of the page's layout. */
const LAYOUT_KEY = 'linux-manager-ui.account-layout'
/** /**
* The account of the signed-in user, from the server's /account, in two columns: the details with Change password, * The account of the signed-in user, from the server's /account, in two columns: the details with Change password,
* which opens the password dialog, and the passkeys in the first row, the enrolment for one-time passwords and the * which opens the password dialog, and the passkeys in the first row, the enrolment for one-time passwords and the
* OpenVPN and the Apple VPN profile of a user with a certificate in the second. Each change but the removal of a * OpenVPN and the Apple VPN profile of a user with a certificate in the second. Each change but the removal of a
* passkey takes the current password and, for an enrolled user, a current code. A changed password ends the session, * passkey takes the current password and, for an enrolled user, a current code. A changed password ends the session,
* through onPasswordChanged. * through onPasswordChanged. The panels are on a PanelBoard whose layout is kept in the browser.
*/ */
export default function AccountPanel(props: { onPasswordChanged: () => void }) { export default function AccountPanel(props: { onPasswordChanged: () => void }) {
const [account, setAccount] = useState<Account | null>(null) const [account, setAccount] = useState<Account | null>(null)
@@ -35,6 +39,7 @@ export default function AccountPanel(props: { onPasswordChanged: () => void }) {
const [addingPasskey, setAddingPasskey] = useState(false) const [addingPasskey, setAddingPasskey] = useState(false)
const [profile, setProfile] = useState<'openvpn' | 'apple' | null>(null) const [profile, setProfile] = useState<'openvpn' | 'apple' | null>(null)
const [passkeyError, setPasskeyError] = useState<string | null>(null) const [passkeyError, setPasskeyError] = useState<string | null>(null)
const board = useBoard(LAYOUT_KEY)
useEffect(() => { useEffect(() => {
request<Account>('GET', '/account', ACCOUNT_SHAPE) request<Account>('GET', '/account', ACCOUNT_SHAPE)
@@ -100,20 +105,28 @@ export default function AccountPanel(props: { onPasswordChanged: () => void }) {
['One-time passwords', account.otp ? 'enrolled' : 'not enrolled'], ['One-time passwords', account.otp ? 'enrolled' : 'not enrolled'],
] ]
return ( const panels: BoardPanel[] = [
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' }, alignItems: 'start' }}> {
<Section title="Account"> id: 'account',
<Box component="dl" sx={{ display: 'grid', gridTemplateColumns: 'max-content 1fr', columnGap: 2, rowGap: 0.5, m: 0 }}> title: 'Account',
{rows.map(([label, value]) => ( content: (
<Box key={label} sx={{ display: 'contents' }}> <>
<Typography component="dt" variant="body2" color="text.secondary">{label}</Typography> <Box component="dl" sx={{ display: 'grid', gridTemplateColumns: 'max-content 1fr', columnGap: 2, rowGap: 0.5, m: 0 }}>
<Typography component="dd" variant="body2" sx={{ m: 0 }}>{value}</Typography> {rows.map(([label, value]) => (
</Box> <Box key={label} sx={{ display: 'contents' }}>
))} <Typography component="dt" variant="body2" color="text.secondary">{label}</Typography>
</Box> <Typography component="dd" variant="body2" sx={{ m: 0 }}>{value}</Typography>
<Button variant="outlined" startIcon={<Password />} sx={{ mt: 2 }} onClick={() => setChangingPassword(true)}>Change password</Button> </Box>
</Section> ))}
<Section title="Passkeys"> </Box>
<Button variant="outlined" startIcon={<Password />} sx={{ mt: 2 }} onClick={() => setChangingPassword(true)}>Change password</Button>
</>
),
},
{
id: 'passkeys',
title: 'Passkeys',
content: (
<Stack sx={{ gap: 2, alignItems: 'flex-start' }}> <Stack sx={{ gap: 2, alignItems: 'flex-start' }}>
{passkeyError && <Alert severity="error" sx={{ whiteSpace: 'pre-line', alignSelf: 'stretch' }}>{passkeyError}</Alert>} {passkeyError && <Alert severity="error" sx={{ whiteSpace: 'pre-line', alignSelf: 'stretch' }}>{passkeyError}</Alert>}
{account.passkeys.length === 0 {account.passkeys.length === 0
@@ -144,8 +157,12 @@ export default function AccountPanel(props: { onPasswordChanged: () => void }) {
)} )}
<Button variant="outlined" startIcon={<Key />} onClick={() => setAddingPasskey(true)}>Add a passkey</Button> <Button variant="outlined" startIcon={<Key />} onClick={() => setAddingPasskey(true)}>Add a passkey</Button>
</Stack> </Stack>
</Section> ),
<Section title="One-time passwords"> },
{
id: 'otp',
title: 'One-time passwords',
content: (
<Stack sx={{ gap: 2, alignItems: 'flex-start' }}> <Stack sx={{ gap: 2, alignItems: 'flex-start' }}>
<Typography variant="body2" color="text.secondary"> <Typography variant="body2" color="text.secondary">
{account.otp {account.otp
@@ -154,15 +171,26 @@ export default function AccountPanel(props: { onPasswordChanged: () => void }) {
</Typography> </Typography>
<Button variant="outlined" onClick={() => setEnrolling(true)}>{account.otp ? 'Replace the authenticator' : 'Enrol'}</Button> <Button variant="outlined" onClick={() => setEnrolling(true)}>{account.otp ? 'Replace the authenticator' : 'Enrol'}</Button>
</Stack> </Stack>
</Section> ),
{account.certificate && ( },
<Section title="VPN profiles"> ...(account.certificate ? [{
<Stack sx={{ gap: 2, alignItems: 'flex-start' }}> id: 'profiles',
<Button variant="outlined" startIcon={<Download />} onClick={() => setProfile('openvpn')}>Download the OpenVPN profile</Button> title: 'VPN profiles',
<Button variant="outlined" startIcon={<Apple />} onClick={() => setProfile('apple')}>Download the Apple VPN profile (IKEv2)</Button> content: (
</Stack> <Stack sx={{ gap: 2, alignItems: 'flex-start' }}>
</Section> <Button variant="outlined" startIcon={<Download />} onClick={() => setProfile('openvpn')}>Download the OpenVPN profile</Button>
)} <Button variant="outlined" startIcon={<Apple />} onClick={() => setProfile('apple')}>Download the Apple VPN profile (IKEv2)</Button>
</Stack>
),
}] : []),
]
return (
<Box component="section">
<Toolbar description="The account you are signed in with.">
<BoardButtons board={board} />
</Toolbar>
<Board board={board} panels={panels} />
<Dialog open={changingPassword} onClose={closePasswordDialog} fullWidth maxWidth="xs"> <Dialog open={changingPassword} onClose={closePasswordDialog} fullWidth maxWidth="xs">
<form onSubmit={changePassword}> <form onSubmit={changePassword}>
<DialogTitle>Change password</DialogTitle> <DialogTitle>Change password</DialogTitle>
+132
View File
@@ -0,0 +1,132 @@
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, MenuItem, Stack, Switch, TextField, Typography } from '@mui/material'
import { useState, type FormEvent } from 'react'
import { ACME_PROVIDERS, type AcmeProvider, type HttpsChange, type HttpsSettings } from './api.ts'
/** The labels of the ACME providers. */
export const PROVIDER_LABELS: Record<AcmeProvider, string> = {
letsencrypt: 'Let\'s Encrypt',
zerossl: 'ZeroSSL',
custom: 'Custom directory URL',
}
/** The problem of a custom ACME directory URL, or ''. */
function urlProblem(value: string) {
try {
const url = new URL(value.trim())
return url.protocol === 'https:' && url.hostname !== '' && url.hash === '' ? '' : 'An https:// URL.'
} catch {
return 'An https:// URL.'
}
}
/**
* A dialog that edits the ACME CA Caddy takes certificates from, for the server's FQDN with https.certificate acme and
* for the web sites with TLS acme: Let's Encrypt, with its staging environment, ZeroSSL, with an optional API key, or a
* custom directory URL with optional EAB credentials. A secret left empty keeps its value. onSave sends the ACME
* settings only; the dialog closes when it succeeds and shows the server's message when it fails.
*/
export default function AcmeSettingsDialog(props: {
current: HttpsSettings
onSave: (settings: HttpsChange) => Promise<void>
onCancel: () => void
}) {
const current = props.current
const [provider, setProvider] = useState<AcmeProvider>(current.acme_provider)
const [staging, setStaging] = useState(current.acme_staging)
const [url, setUrl] = useState(current.acme_url)
const [keyId, setKeyId] = useState(current.acme_eab_key_id)
const [macKey, setMacKey] = useState('')
const [apiKey, setApiKey] = useState('')
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const custom = provider === 'custom'
const eabProblem = custom && ((keyId !== '' && macKey === '' && !current.acme_eab_mac_key_set) || (keyId === '' && macKey !== ''))
? 'The key ID and the MAC key are given together.' : ''
const blocked = (custom && urlProblem(url) !== '') || eabProblem !== ''
async function submit(event: FormEvent) {
event.preventDefault()
if (blocked) {
return
}
setSaving(true)
setError(null)
const change: HttpsChange = {
acme_provider: provider, acme_staging: staging,
acme_url: custom ? url.trim() : current.acme_url, acme_eab_key_id: custom ? keyId.trim() : current.acme_eab_key_id,
}
if (custom && macKey !== '') {
change.acme_eab_mac_key = macKey
}
if (custom && keyId.trim() === '') {
change.acme_eab_mac_key = ''
}
if (provider === 'zerossl' && apiKey !== '') {
change.zerossl_api_key = apiKey
}
try {
await props.onSave(change)
} catch (caught) {
setError((caught as Error).message)
setSaving(false)
}
}
return (
<Dialog open onClose={(_event, reason) => reason !== 'backdropClick' && props.onCancel()} maxWidth="sm" fullWidth slotProps={{ paper: { component: 'form', onSubmit: submit } }}>
<DialogTitle>ACME CA</DialogTitle>
<DialogContent>
<Stack sx={{ gap: 2, pt: 1 }}>
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
<Typography variant="body2" color="text.secondary">
Caddy takes certificates from this CA for the server, when its certificate is ACME, and for the web sites with TLS ACME.
</Typography>
<TextField select label="Provider" value={provider} onChange={(event) => setProvider(event.target.value as AcmeProvider)}>
{ACME_PROVIDERS.map((item) => <MenuItem key={item} value={item}>{PROVIDER_LABELS[item]}</MenuItem>)}
</TextField>
{provider === 'letsencrypt' && (
<FormControlLabel control={<Switch checked={staging} onChange={(event) => setStaging(event.target.checked)} />} label="Staging environment, for tests: no browser trusts its certificates" />
)}
{provider === 'zerossl' && (
<TextField
label="API key"
type="password"
value={apiKey}
autoComplete="off"
helperText={current.zerossl_api_key_set ? 'Set; empty keeps it.' : 'Optional; without it the EAB credentials come from the e-mail address of https.email.'}
onChange={(event) => setApiKey(event.target.value.trim())}
/>
)}
{custom && (
<>
<TextField
label="ACME directory URL"
value={url}
autoComplete="off"
error={url !== '' && urlProblem(url) !== ''}
helperText={(url !== '' && urlProblem(url)) || 'Such as a HashiCorp Vault, Caddy or Simple CA ACME directory; the CA of its HTTPS certificate is in the server\'s trust store.'}
onChange={(event) => setUrl(event.target.value.trim())}
/>
<TextField label="EAB key ID" value={keyId} autoComplete="off" helperText="Optional." onChange={(event) => setKeyId(event.target.value.trim())} />
<TextField
label="EAB MAC key"
type="password"
value={macKey}
autoComplete="off"
error={eabProblem !== ''}
helperText={eabProblem || (current.acme_eab_mac_key_set ? 'Set; empty keeps it.' : 'With the key ID.')}
onChange={(event) => setMacKey(event.target.value.trim())}
/>
</>
)}
<Alert severity="info">The server runs its setup again, which applies the change.</Alert>
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={props.onCancel} disabled={saving}>Cancel</Button>
<Button type="submit" variant="contained" disabled={saving || blocked}>Save</Button>
</DialogActions>
</Dialog>
)
}
+37 -18
View File
@@ -14,7 +14,7 @@ import LogsPanel from './LogsPanel.tsx'
import MetricsPanel from './MetricsPanel.tsx' import MetricsPanel from './MetricsPanel.tsx'
import DockerPanel from './DockerPanel.tsx' import DockerPanel from './DockerPanel.tsx'
import DnsPanel from './DnsPanel.tsx' import DnsPanel from './DnsPanel.tsx'
import PageMenu, { CA_PATH, DOCKER_PATH, REMOTE_ACCESS_PATH, SHELL_PATH, SITES_PATH, SITE_TO_SITE_PATH, USERS_PATH, USER_PATH } from './PageMenu.tsx' import PageMenu, { CA_PATH, DNS_PATH, DOCKER_PATH, REMOTE_ACCESS_PATH, SHELL_PATH, SITES_PATH, SITE_TO_SITE_PATH, USERS_PATH, USER_PATH } from './PageMenu.tsx'
import NetworkPanel from './NetworkPanel.tsx' import NetworkPanel from './NetworkPanel.tsx'
import RemoteAccessPanel from './RemoteAccessPanel.tsx' import RemoteAccessPanel from './RemoteAccessPanel.tsx'
import ServerPanel from './ServerPanel.tsx' import ServerPanel from './ServerPanel.tsx'
@@ -31,7 +31,7 @@ import SiteToSiteStatusPanel from './SiteToSiteStatusPanel.tsx'
import ThemeMenu from './ThemeMenu.tsx' import ThemeMenu from './ThemeMenu.tsx'
import UsersPanel from './UsersPanel.tsx' import UsersPanel from './UsersPanel.tsx'
import { import {
ACCOUNT_SHAPE, DETAILS_SHAPE, SESSION_EXPIRED, SESSION_SHAPE, request, type Account, type Info, type RemoteAccessSystem, ACCOUNT_SHAPE, DETAILS_SHAPE, INFO_SHAPE, SESSION_EXPIRED, SESSION_SHAPE, request, type Account, type Info, type RemoteAccessSystem,
type RouterDetails, type Session, type RouterDetails, type Session,
} from './api.ts' } from './api.ts'
@@ -39,16 +39,16 @@ import {
type View = 'router' | 'metrics' | 'logs' | 'backup' | 'system' type View = 'router' | 'metrics' | 'logs' | 'backup' | 'system'
type UsersView = 'users' | 'groups' | 'service-accounts' type UsersView = 'users' | 'groups' | 'service-accounts'
type SiteToSiteView = 'status' | 'network' | 'connections' type SiteToSiteView = 'status' | 'network' | 'connections'
type SitesView = 'sites' | 'files' | 'dns' type SitesView = 'sites' | 'files'
/** The help topic of each tab of the Web Sites page. */ /** The help topic of each tab of the Web Sites page. */
const SITES_TOPICS: Record<SitesView, string> = { sites: 'sites.md', files: 'site-files.md', dns: 'dns.md' } const SITES_TOPICS: Record<SitesView, string> = { sites: 'sites.md', files: 'site-files.md' }
/** The prefix of the sessionStorage keys of the pages the account and the shell page were opened from, by their paths. */ /** The prefix of the sessionStorage keys of the pages the account and the shell page were opened from, by their paths. */
const RETURN_KEY = 'linux-manager-ui.return:' const RETURN_KEY = 'linux-manager-ui.return:'
/** The pages of an administrator besides Router, which every other path shows. */ /** The pages of an administrator besides Router, which every other path shows. */
const PAGE_PATHS = [USER_PATH, USERS_PATH, SITE_TO_SITE_PATH, REMOTE_ACCESS_PATH, CA_PATH, SITES_PATH, DOCKER_PATH, SHELL_PATH] const PAGE_PATHS = [USER_PATH, USERS_PATH, SITE_TO_SITE_PATH, REMOTE_ACCESS_PATH, CA_PATH, SITES_PATH, DNS_PATH, DOCKER_PATH, SHELL_PATH]
/** The help topic of each page, a document of /docs; the Router, the Identities and the Web Sites page have one per tab. */ /** The help topic of each page, a document of /docs; the Router, the Identities and the Web Sites page have one per tab. */
const HELP_TOPICS: Record<string, string> = { const HELP_TOPICS: Record<string, string> = {
@@ -56,6 +56,7 @@ const HELP_TOPICS: Record<string, string> = {
[SITE_TO_SITE_PATH]: 'site-to-site.md', [SITE_TO_SITE_PATH]: 'site-to-site.md',
[REMOTE_ACCESS_PATH]: 'remote-access.md', [REMOTE_ACCESS_PATH]: 'remote-access.md',
[CA_PATH]: 'certificates.md', [CA_PATH]: 'certificates.md',
[DNS_PATH]: 'dns.md',
[DOCKER_PATH]: 'docker.md', [DOCKER_PATH]: 'docker.md',
[SHELL_PATH]: 'shell.md', [SHELL_PATH]: 'shell.md',
} }
@@ -68,7 +69,7 @@ const HELP_KEY = 'linux-manager-ui.help'
* every path, it then shows the user's own account; at USERS_PATH the server's users, groups or service accounts; at * every path, it then shows the user's own account; at USERS_PATH the server's users, groups or service accounts; at
* SITE_TO_SITE_PATH its site-to-site connections, their state and its network with its routes; at REMOTE_ACCESS_PATH its IKEv2, OpenVPN and * SITE_TO_SITE_PATH its site-to-site connections, their state and its network with its routes; at REMOTE_ACCESS_PATH its IKEv2, OpenVPN and
* WireGuard access; at CA_PATH its certificates; at SITES_PATH its web * WireGuard access; at CA_PATH its certificates; at SITES_PATH its web
* sites, the files of a site, opened from the sites too, and its name server; at DOCKER_PATH the state of Docker; at SHELL_PATH a shell on the server; otherwise the state of the server, with the update information of its packages in * sites and the files of a site, opened from the sites too; at DNS_PATH its name server, while it is on; at DOCKER_PATH the state of Docker; at SHELL_PATH a shell on the server; otherwise the state of the server, with the update information of its packages in
* the Status panel, its metrics, its logs, its backups or the updates of its system's packages. A page shows one tab at a time, each read only while shown. An * the Status panel, its metrics, its logs, its backups or the updates of its system's packages. A page shows one tab at a time, each read only while shown. An
* administrator switches pages with the page menu at the right end of the header; the button with the user's name, * administrator switches pages with the page menu at the right end of the header; the button with the user's name,
* left of Sign out, opens the user's own account, and an administrator's shell button, left of it, the shell; pressed * left of Sign out, opens the user's own account, and an administrator's shell button, left of it, the shell; pressed
@@ -86,12 +87,17 @@ export default function App(props: { info: Info }) {
const [sitesView, setSitesView] = useState<SitesView>('sites') const [sitesView, setSitesView] = useState<SitesView>('sites')
const [filesSite, setFilesSite] = useState<string | null>(null) const [filesSite, setFilesSite] = useState<string | null>(null)
const [session, setSession] = useState<Session | null | undefined>(undefined) const [session, setSession] = useState<Session | null | undefined>(undefined)
// /api/info again once signed in, as the version is told only with a session.
const [info, setInfo] = useState<Info>(props.info)
const [role, setRole] = useState<{ name: string; admin: boolean } | null>(null) const [role, setRole] = useState<{ name: string; admin: boolean } | null>(null)
// The router and the VPN components as router.enabled and vpn.enabled of /config, and whether Docker is installed; // The router and the VPN components as router.enabled and vpn.enabled of /config, and whether Docker is installed;
// null while not known, when every page shows. // null while not known, when every page shows.
const [components, setComponents] = useState<{ router: boolean; vpn: boolean; docker: boolean } | null>(null) const [components, setComponents] = useState<{ router: boolean; vpn: boolean; dns: boolean; docker: boolean } | null>(null)
// Raised by the System tab's components, so that the pages follow a component switched there.
const [componentsRead, setComponentsRead] = useState(0)
const routerOff = components?.router === false const routerOff = components?.router === false
const vpnOff = components?.vpn === false const vpnOff = components?.vpn === false
const dnsOff = components?.dns === false
const dockerMissing = components?.docker === false const dockerMissing = components?.docker === false
const page = PAGE_PATHS.find((path) => path === window.location.pathname) ?? '/' const page = PAGE_PATHS.find((path) => path === window.location.pathname) ?? '/'
const userPage = page === USER_PATH const userPage = page === USER_PATH
@@ -137,6 +143,7 @@ export default function App(props: { info: Info }) {
request<Account>('GET', '/account', ACCOUNT_SHAPE) request<Account>('GET', '/account', ACCOUNT_SHAPE)
.then((account) => setRole({ name: session.name, admin: account.admin })) .then((account) => setRole({ name: session.name, admin: account.admin }))
.catch(() => setRole({ name: session.name, admin: false })) .catch(() => setRole({ name: session.name, admin: false }))
request<Info>('GET', '/info', INFO_SHAPE).then(setInfo).catch(() => undefined)
}, [session]) }, [session])
useEffect(() => { useEffect(() => {
@@ -147,10 +154,11 @@ export default function App(props: { info: Info }) {
.then((details) => setComponents({ .then((details) => setComponents({
router: details.configuration.router?.enabled === true, router: details.configuration.router?.enabled === true,
vpn: details.configuration.vpn?.enabled === true, vpn: details.configuration.vpn?.enabled === true,
dns: details.configuration.dns?.enabled === true,
docker: details.docker.installed, docker: details.docker.installed,
})) }))
.catch(() => setComponents(null)) .catch(() => setComponents(null))
}, [admin]) }, [admin, componentsRead])
/** Opens the page of the path, keeping the page it was opened from in sessionStorage, or returns to that page from it. */ /** Opens the page of the path, keeping the page it was opened from in sessionStorage, or returns to that page from it. */
function toggle(path: string) { function toggle(path: string) {
@@ -184,14 +192,16 @@ export default function App(props: { info: Info }) {
<Typography variant="h5" component="h1"> <Typography variant="h5" component="h1">
Ubuntu Linux Manager Ubuntu Linux Manager
</Typography> </Typography>
<Typography variant="caption" color="text.secondary" sx={{ fontFamily: 'monospace' }}> {session && (
{props.info.version ?? 'development'} <Typography variant="caption" color="text.secondary" sx={{ fontFamily: 'monospace' }}>
</Typography> {info.version ?? 'development'}
</Typography>
)}
</Stack> </Stack>
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}> <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
Server status page:{' '} Server status page:{' '}
{props.info.status_url {info.status_url
? <Link href={props.info.status_url} target="_blank" rel="noreferrer">{props.info.status_url}</Link> ? <Link href={info.status_url} target="_blank" rel="noreferrer">{info.status_url}</Link>
: <b>not configured</b>} : <b>not configured</b>}
</Typography> </Typography>
</Box> </Box>
@@ -244,7 +254,7 @@ export default function App(props: { info: Info }) {
</Tooltip> </Tooltip>
)} )}
{session && admin && ( {session && admin && (
<PageMenu path={page} hidden={[...(vpnOff ? [REMOTE_ACCESS_PATH] : []), ...(dockerMissing ? [DOCKER_PATH] : [])]} /> <PageMenu path={page} hidden={[...(vpnOff ? [REMOTE_ACCESS_PATH] : []), ...(dnsOff ? [DNS_PATH] : []), ...(dockerMissing ? [DOCKER_PATH] : [])]} />
)} )}
</Stack> </Stack>
</Stack> </Stack>
@@ -263,7 +273,6 @@ export default function App(props: { info: Info }) {
<Tabs value={sitesView} onChange={(_event, next: SitesView) => setSitesView(next)} sx={{ mb: 3, borderBottom: 1, borderColor: 'divider' }}> <Tabs value={sitesView} onChange={(_event, next: SitesView) => setSitesView(next)} sx={{ mb: 3, borderBottom: 1, borderColor: 'divider' }}>
<Tab value="sites" label="Sites" /> <Tab value="sites" label="Sites" />
<Tab value="files" label="Files" /> <Tab value="files" label="Files" />
<Tab value="dns" label="DNS" />
</Tabs> </Tabs>
{sitesView === 'sites' && ( {sitesView === 'sites' && (
<SitesPanel <SitesPanel
@@ -274,7 +283,17 @@ export default function App(props: { info: Info }) {
/> />
)} )}
{sitesView === 'files' && <SiteFiles key={filesSite ?? ''} site={filesSite} onSite={setFilesSite} />} {sitesView === 'files' && <SiteFiles key={filesSite ?? ''} site={filesSite} onSite={setFilesSite} />}
{sitesView === 'dns' && <DnsPanel />} </>
)}
{session && admin && page === DNS_PATH && dnsOff && (
<Typography color="text.secondary">
The name server is off on this server: it is switched on on the System tab of the Server page.
</Typography>
)}
{session && admin && page === DNS_PATH && !dnsOff && (
<>
<Typography variant="h6" component="h2" sx={{ mb: 2 }}>DNS</Typography>
<DnsPanel />
</> </>
)} )}
{session && admin && page === DOCKER_PATH && dockerMissing && ( {session && admin && page === DOCKER_PATH && dockerMissing && (
@@ -294,7 +313,7 @@ export default function App(props: { info: Info }) {
)} )}
{session && admin && page === REMOTE_ACCESS_PATH && vpnOff && ( {session && admin && page === REMOTE_ACCESS_PATH && vpnOff && (
<Typography color="text.secondary"> <Typography color="text.secondary">
The VPN is off on this server: IKEv2, OpenVPN and WireGuard need vpn.enabled in the configuration. The VPN is off on this server: it is switched on on the System tab of the Server page.
</Typography> </Typography>
)} )}
{session && admin && page === REMOTE_ACCESS_PATH && !vpnOff && ( {session && admin && page === REMOTE_ACCESS_PATH && !vpnOff && (
@@ -344,7 +363,7 @@ export default function App(props: { info: Info }) {
{view === 'metrics' && <MetricsPanel />} {view === 'metrics' && <MetricsPanel />}
{view === 'logs' && <LogsPanel />} {view === 'logs' && <LogsPanel />}
{view === 'backup' && <BackupPanel />} {view === 'backup' && <BackupPanel />}
{view === 'system' && <SystemPanel />} {view === 'system' && <SystemPanel onComponentsChange={() => setComponentsRead((value) => value + 1)} />}
</> </>
)} )}
</Container> </Container>
+96 -74
View File
@@ -5,11 +5,15 @@ import { Alert, Box, Button, Table, TableBody, TableCell, TableHead, TablePagina
import { useCallback, useEffect, useRef, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import BackupDialog from './BackupDialog.tsx' import BackupDialog from './BackupDialog.tsx'
import { BackupChip, TARGET_LABELS, backupRows, when } from './BackupSummary.tsx' import { BackupChip, TARGET_LABELS, backupRows, when } from './BackupSummary.tsx'
import { Pairs, Section, bytes } from './ServerPanel.tsx' import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Pairs, bytes } from './ServerPanel.tsx'
import SearchField, { matches } from './SearchField.tsx' import SearchField, { matches } from './SearchField.tsx'
import Toolbar from './Toolbar.tsx' import Toolbar from './Toolbar.tsx'
import { ApiError, BACKUP_KEEPS, BACKUP_SCHEDULES, BACKUP_SETTINGS_SHAPE, BACKUP_SHAPE, STARTED_SHAPE, request, type Backup } from './api.ts' import { ApiError, BACKUP_KEEPS, BACKUP_SCHEDULES, BACKUP_SETTINGS_SHAPE, BACKUP_SHAPE, STARTED_SHAPE, request, type Backup } from './api.ts'
/** The localStorage key of the tab's layout. */
const LAYOUT_KEY = 'linux-manager-ui.backup-layout'
/** The note shown after a change, which the server applies when linux-manager-setup has run again. */ /** The note shown after a change, which the server applies when linux-manager-setup has run again. */
const APPLIED = 'The server applies the change in the background.' const APPLIED = 'The server applies the change in the background.'
@@ -19,7 +23,8 @@ const WATCH_SECONDS = 3
/** /**
* The server's backups: the settings, the last run and the local archives, searched by name and time and shown a page at * The server's backups: the settings, the last run and the local archives, searched by name and time and shown a page at
* a time; edit the settings and start a backup now. * a time; edit the settings and start a backup now.
* While a backup runs, or after Run now until it has ended, the tab reads every WATCH_SECONDS. * While a backup runs, or after Run now until it has ended, the tab reads every WATCH_SECONDS. The panels are on a
* PanelBoard whose layout is kept in the browser.
*/ */
export default function BackupPanel() { export default function BackupPanel() {
const [backup, setBackup] = useState<Backup | null>(null) const [backup, setBackup] = useState<Backup | null>(null)
@@ -28,6 +33,7 @@ export default function BackupPanel() {
const [note, setNote] = useState<string | null>(null) const [note, setNote] = useState<string | null>(null)
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const [editing, setEditing] = useState(false) const [editing, setEditing] = useState(false)
const board = useBoard(LAYOUT_KEY)
const [watching, setWatching] = useState(false) const [watching, setWatching] = useState(false)
const [search, setSearch] = useState('') const [search, setSearch] = useState('')
const [page, setPage] = useState(0) const [page, setPage] = useState(0)
@@ -87,6 +93,92 @@ export default function BackupPanel() {
const local = settings?.target === 'local' const local = settings?.target === 'local'
const keeps = settings ? BACKUP_KEEPS.slice(BACKUP_SCHEDULES.indexOf(settings.schedule as (typeof BACKUP_SCHEDULES)[number])) : [] const keeps = settings ? BACKUP_KEEPS.slice(BACKUP_SCHEDULES.indexOf(settings.schedule as (typeof BACKUP_SCHEDULES)[number])) : []
const panels: BoardPanel[] = backup && settings ? [
{
id: 'settings',
title: 'Settings',
content: (
<Pairs
rows={[
['Scheduled backups', settings.enabled ? 'on' : 'off'],
['Schedule', settings.schedule],
['Target', TARGET_LABELS[settings.target] ?? settings.target],
['Metrics database', settings.metrics ? 'included' : 'not included'],
...(local
? [
['Folder', settings.path],
['Kept', keeps.map((keep) => `${settings[keep]} ${keep.slice(5)}`).join(', ')],
['Cloud copy', settings.rclone_remote ? `${settings.rclone_mode} to ${settings.rclone_remote}` : 'none'],
] satisfies [string, string][]
: [
['Repository', settings.pbs_repository || '-'],
['Token secret', settings.pbs_password_set ? 'set' : 'missing'],
['Fingerprint', settings.pbs_fingerprint || '-'],
['Namespace', settings.pbs_namespace || '-'],
['Encryption key file', settings.pbs_keyfile || 'none'],
] satisfies [string, string][]),
]}
/>
),
},
{
id: 'last-run',
title: 'Last run',
content: (
<>
<Box sx={{ mb: 1 }}><BackupChip state={backup.state} /></Box>
<Pairs rows={backupRows(backup)} />
</>
),
},
...(local ? [{
id: 'archives',
title: 'Local archives',
wide: true,
content: (
<>
<Box sx={{ mb: 1 }}>
<SearchField value={search} onChange={(value) => { setSearch(value); setPage(0) }} />
</Box>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Archive</TableCell>
<TableCell>Time</TableCell>
<TableCell align="right">Size</TableCell>
</TableRow>
</TableHead>
<TableBody>
{archives.length === 0 && (
<TableRow>
<TableCell colSpan={3} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{archives.slice(shownPage * rows, (shownPage + 1) * rows).map((archive) => (
<TableRow key={archive.name} hover>
<TableCell sx={{ fontFamily: 'monospace' }}>{archive.name}</TableCell>
<TableCell>{when(archive.time)}</TableCell>
<TableCell align="right">{bytes(archive.size)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
<TablePagination
component="div"
count={archives.length}
page={shownPage}
rowsPerPage={rows}
rowsPerPageOptions={[10, 25, 50, 100]}
onPageChange={(_event, next) => setPage(next)}
onRowsPerPageChange={(event) => { setRows(Number(event.target.value)); setPage(0) }}
/>
</>
),
}] : []),
] : []
return ( return (
<Box component="section"> <Box component="section">
<Toolbar description="Backups of the server's configuration, keys, users and metrics."> <Toolbar description="Backups of the server's configuration, keys, users and metrics.">
@@ -96,6 +188,7 @@ export default function BackupPanel() {
<Button variant="outlined" startIcon={<PlayArrow />} disabled={busy || backup === null || running || watching} onClick={() => void runNow()}> <Button variant="outlined" startIcon={<PlayArrow />} disabled={busy || backup === null || running || watching} onClick={() => void runNow()}>
Run now Run now
</Button> </Button>
<BoardButtons board={board} />
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}> <Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>
Refresh Refresh
</Button> </Button>
@@ -114,78 +207,7 @@ export default function BackupPanel() {
</Alert> </Alert>
)} )}
{backup && settings && ( {backup && settings && <Board board={board} panels={panels} />}
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' } }}>
<Section title="Settings">
<Pairs
rows={[
['Scheduled backups', settings.enabled ? 'on' : 'off'],
['Schedule', settings.schedule],
['Target', TARGET_LABELS[settings.target] ?? settings.target],
['Metrics database', settings.metrics ? 'included' : 'not included'],
...(local
? [
['Folder', settings.path],
['Kept', keeps.map((keep) => `${settings[keep]} ${keep.slice(5)}`).join(', ')],
['Cloud copy', settings.rclone_remote ? `${settings.rclone_mode} to ${settings.rclone_remote}` : 'none'],
] satisfies [string, string][]
: [
['Repository', settings.pbs_repository || '-'],
['Token secret', settings.pbs_password_set ? 'set' : 'missing'],
['Fingerprint', settings.pbs_fingerprint || '-'],
['Namespace', settings.pbs_namespace || '-'],
['Encryption key file', settings.pbs_keyfile || 'none'],
] satisfies [string, string][]),
]}
/>
</Section>
<Section title="Last run">
<Box sx={{ mb: 1 }}><BackupChip state={backup.state} /></Box>
<Pairs rows={backupRows(backup)} />
</Section>
{local && (
<Section title="Local archives" wide>
<Box sx={{ mb: 1 }}>
<SearchField value={search} onChange={(value) => { setSearch(value); setPage(0) }} />
</Box>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Archive</TableCell>
<TableCell>Time</TableCell>
<TableCell align="right">Size</TableCell>
</TableRow>
</TableHead>
<TableBody>
{archives.length === 0 && (
<TableRow>
<TableCell colSpan={3} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{archives.slice(shownPage * rows, (shownPage + 1) * rows).map((archive) => (
<TableRow key={archive.name} hover>
<TableCell sx={{ fontFamily: 'monospace' }}>{archive.name}</TableCell>
<TableCell>{when(archive.time)}</TableCell>
<TableCell align="right">{bytes(archive.size)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
<TablePagination
component="div"
count={archives.length}
page={shownPage}
rowsPerPage={rows}
rowsPerPageOptions={[10, 25, 50, 100]}
onPageChange={(_event, next) => setPage(next)}
onRowsPerPageChange={(event) => { setRows(Number(event.target.value)); setPage(0) }}
/>
</Section>
)}
</Box>
)}
{editing && backup && ( {editing && backup && (
<BackupDialog <BackupDialog
+221 -210
View File
@@ -21,7 +21,9 @@ import TemplateDialog from './TemplateDialog.tsx'
import Toolbar from './Toolbar.tsx' import Toolbar from './Toolbar.tsx'
import EkuDialog from './EkuDialog.tsx' import EkuDialog from './EkuDialog.tsx'
import PkiSettingsDialog, { PUBLISH_LABELS, ROOT_SOURCE_LABELS } from './PkiSettingsDialog.tsx' import PkiSettingsDialog, { PUBLISH_LABELS, ROOT_SOURCE_LABELS } from './PkiSettingsDialog.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Pairs, Section } from './ServerPanel.tsx' import { Pairs, Section } from './ServerPanel.tsx'
import ServerCertificatePanel from './ServerCertificatePanel.tsx'
import SetupCodeDialog from './SetupCodeDialog.tsx' import SetupCodeDialog from './SetupCodeDialog.tsx'
import { import {
ApiError, BUNDLE_SHAPE, CA_IMPORTED_SHAPE, CRL_IMPORTED_SHAPE, CSR_SHAPE, ISSUED_SHAPE, PFX_SHAPE, PKI_SETTINGS_SHAPE, PKI_SHAPE, REVOKED_SHAPE, ApiError, BUNDLE_SHAPE, CA_IMPORTED_SHAPE, CRL_IMPORTED_SHAPE, CSR_SHAPE, ISSUED_SHAPE, PFX_SHAPE, PKI_SETTINGS_SHAPE, PKI_SHAPE, REVOKED_SHAPE,
@@ -30,12 +32,16 @@ import {
} from './api.ts' } from './api.ts'
import { saveFile } from './saveFile.ts' import { saveFile } from './saveFile.ts'
/** The tabs of the page: the root and the general information, the templates, the extended key usages, the two /** The tabs of the page: the server's HTTPS (ServerCertificatePanel), the root and the general information, the
* built-in issuing CAs, the general-purpose ones. */ * templates, the extended key usages, the issuing CAs. */
type View = 'root' | 'templates' | 'usages' | 'p2s' | 's2s' | 'issuing' type View = 'server' | 'root' | 'templates' | 'usages' | 'issuing'
/** The built-in CAs and the Simple CA issuing CA above them, whose certificates the Issuing CAs tab leaves out. */ /** The localStorage keys of the layouts of the Root and the Issuing CAs tabs. */
const BUILTIN_CAS = ['root', 'upstream', 'p2s', 's2s'] const ROOT_LAYOUT_KEY = 'linux-manager-ui.certificates-root-layout'
const ISSUING_LAYOUT_KEY = 'linux-manager-ui.certificates-issuing-layout'
/** The CAs above the issuing CAs, whose certificates the Issuing CAs tab leaves out. */
const UPPER_CAS = ['root', 'upstream']
/** Where the root CRL came from. */ /** Where the root CRL came from. */
const CRL_SOURCE_LABELS: Record<string, string> = { signed: 'signed by the server', uploaded: 'uploaded', fetched: 'fetched from Simple CA' } const CRL_SOURCE_LABELS: Record<string, string> = { signed: 'signed by the server', uploaded: 'uploaded', fetched: 'fetched from Simple CA' }
@@ -48,6 +54,7 @@ const STATE_COLORS: Record<string, 'success' | 'warning' | 'error' | 'default'>
active: 'success', active: 'success',
valid: 'success', valid: 'success',
pending: 'warning', pending: 'warning',
off: 'default',
missing: 'error', missing: 'error',
expired: 'default', expired: 'default',
revoked: 'error', revoked: 'error',
@@ -65,15 +72,17 @@ const REASON_LABELS: Record<string, string> = {
/** /**
* The server's PKI in tabs: Root, the root CA with the general settings and the certificates of the issuing CAs; * The server's certificates in tabs: Server, the server's HTTPS (ServerCertificatePanel), shown first and also
* while the PKI cannot be read; Root, the root CA with the general settings and the certificates of the issuing CAs;
* Templates, the certificate templates, which are added, changed, removed and reset there; Extended key usages, the * Templates, the certificate templates, which are added, changed, removed and reset there; Extended key usages, the
* built-in ones and the custom ones, which are added, changed and removed there; P2S Issuing CA and S2S * built-in ones and the custom ones, which are added, changed and removed there; Issuing CAs, the built-in p2s, s2s and
* Issuing CA, each built-in CA with the certificates it issued; Issuing CAs, the general-purpose CAs, which are added, * servers and the custom CAs, which are added, changed and removed there, with the certificates of all of them, filtered
* changed and removed there, with their certificates, filtered by CA. The warnings, Issue and Settings * by CA. The warnings are above the tabs, and so are Issue and Settings but on the Server tab, whose Refresh reads it
* are above the tabs. Settings edits the pki section, Issue issues a certificate from a CSR or into a PFX file, a * again. Settings edits the pki section, Issue issues a certificate from a CSR or into a PFX file, a
* certificate of another system or of the server is revoked, an issuing CA waiting for the offline root gives its CSR * certificate of another system or of the server is revoked, an issuing CA waiting for the offline root gives its CSR
* and takes its signed certificate, the offline root takes its certificate and a CRL signed offline, and a Simple CA * and takes its signed certificate, the offline root takes its certificate and a CRL signed offline, and a Simple CA
* root takes a setup code for a new token. * root takes a setup code for a new token. The panels of the Root and the Issuing CAs tabs are on a PanelBoard per tab
* whose layout is kept in the browser.
*/ */
export default function CertificatesPanel() { export default function CertificatesPanel() {
const [pki, setPki] = useState<Pki | null>(null) const [pki, setPki] = useState<Pki | null>(null)
@@ -91,7 +100,10 @@ export default function CertificatesPanel() {
const [entering, setEntering] = useState(false) const [entering, setEntering] = useState(false)
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null) const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
const [filter, setFilter] = useState('') const [filter, setFilter] = useState('')
const [view, setView] = useState<View>('root') const [view, setView] = useState<View>('server')
const [serverRead, setServerRead] = useState(0)
const rootBoard = useBoard(ROOT_LAYOUT_KEY)
const issuingBoard = useBoard(ISSUING_LAYOUT_KEY)
const refresh = useCallback(async () => { const refresh = useCallback(async () => {
setBusy(true) setBusy(true)
@@ -257,11 +269,11 @@ export default function CertificatesPanel() {
} }
const root = pki?.status.root const root = pki?.status.root
const general = pki?.status.authorities.filter((authority) => !authority.builtin) ?? [] const authorities = pki?.status.authorities ?? []
const generalNames = [...new Set([...general.map((authority) => authority.name), const authorityNames = [...new Set([...authorities.map((authority) => authority.name),
...(pki?.certificates ?? []).map((certificate) => certificate.ca).filter((name) => !BUILTIN_CAS.includes(name))])] ...(pki?.certificates ?? []).map((certificate) => certificate.ca).filter((name) => !UPPER_CAS.includes(name))])]
const generalCertificates = (pki?.certificates ?? []) const issuedCertificates = (pki?.certificates ?? [])
.filter((certificate) => !BUILTIN_CAS.includes(certificate.ca) && (filter === '' || certificate.ca === filter)) .filter((certificate) => !UPPER_CAS.includes(certificate.ca) && (filter === '' || certificate.ca === filter))
/** The actions of an issuing CA waiting for the offline root: download its CSR and import its signed certificate. */ /** The actions of an issuing CA waiting for the offline root: download its CSR and import its signed certificate. */
const pendingActions = (name: string) => ( const pendingActions = (name: string) => (
@@ -347,56 +359,198 @@ export default function CertificatesPanel() {
</Box> </Box>
) )
/** A tab of a built-in issuing CA: its details, the actions while it waits for the offline root, its certificates. */ const rootPanels: BoardPanel[] = pki ? [
const builtinTab = (name: 'p2s' | 's2s', title: string) => { {
const authority = pki?.status.authorities.find((item) => item.name === name) id: 'root',
return ( title: 'Root CA',
<Box sx={{ display: 'grid', gap: 2 }}> content: (
<Section title={title}> <>
{authority ? ( {root && (
<> <>
<Pairs <Pairs
rows={[ rows={[
['Common name', authority.subject ?? authority.common_name], ['Source', root.source === 'simple-ca' ? `Simple CA, ${root.simple_ca_url}` : ROOT_SOURCE_LABELS[root.source]],
['State', <Chip size="small" label={authority.state} color={STATE_COLORS[authority.state] ?? 'default'} />], ['State', <Chip size="small" label={root.state} color={STATE_COLORS[root.state] ?? 'default'} />],
['Expires', when(authority.expires)], ['Subject', root.subject ?? '-'],
['CRL valid until', when(authority.crl_next_update)], ['Expires', when(root.expires)],
['Templates', authority.templates.join(', ')], ['CRL valid until', when(root.crl_next_update)],
['CRL', CRL_SOURCE_LABELS[root.crl_source ?? ''] ?? '-'],
...(root.upstream ? [
['Simple CA issuing CA', `${root.upstream.name}: ${root.upstream.subject}`],
['Its expiry', when(root.upstream.expires)],
['Its CRL valid until', when(root.upstream.crl_next_update)],
] as [string, string][] : []),
...(root.source === 'simple-ca' ? [['Token valid until', root.token_expires ? when(root.token_expires) : 'no token']] as [string, string][] : []),
]} ]}
/> />
{authority.state === 'pending' && ( {root.state === 'pending' && root.source === 'local' && (
<Stack direction="row" sx={{ mt: 1, alignItems: 'center', justifyContent: 'flex-end', gap: 1 }}> <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>The server creates it once a platform is chosen.</Typography>
<Typography variant="body2" color="text.secondary">
{pki?.settings.root === 'offline' ? 'Waits for its certificate signed by the root:' : 'Waits for its certificate signed by Simple CA.'}
</Typography>
{pki?.settings.root === 'offline' && pendingActions(name)}
</Stack>
)} )}
{authority.state === 'active' && ( <Stack direction="row" sx={{ mt: 1, justifyContent: 'flex-end', gap: 1 }}>
<Stack direction="row" sx={{ mt: 1, justifyContent: 'flex-end' }}> {root.state === 'active' && (
<Button size="small" variant="outlined" startIcon={<Download />} disabled={busy} onClick={() => void downloadBundle(name)}> <Button size="small" variant="outlined" startIcon={<Download />} disabled={busy} onClick={() => void downloadBundle('root')}>
Download CA bundle Download root CA
</Button> </Button>
</Stack> )}
)} {root.source === 'offline' && root.state === 'pending' && (
<Button size="small" variant="outlined" startIcon={<UploadFile />} disabled={busy} onClick={() => setImporting('root')}>
Import root certificate
</Button>
)}
{root.source === 'offline' && root.state === 'active' && (
<Button size="small" variant="outlined" startIcon={<UploadFile />} disabled={busy} onClick={() => setUploading(true)}>
Upload CRL
</Button>
)}
{root.source === 'simple-ca' && (
<Button size="small" variant="outlined" startIcon={<Key />} disabled={busy} onClick={() => setEntering(true)}>
Enter setup code
</Button>
)}
</Stack>
</> </>
) : <Typography variant="body2" color="text.secondary">None yet; the server creates it once a platform is chosen.</Typography>} )}
</Section> </>
<Section title="Certificates issued">{certificateTable((pki?.certificates ?? []).filter((certificate) => certificate.ca === name))}</Section> ),
</Box> },
) {
} id: 'general',
title: 'General',
content: (
<Pairs
rows={[
['Published at', pki.settings.publish.map((item) => PUBLISH_LABELS[item] ?? item).join('; ') || 'nowhere'],
['CA key', pki.settings.key],
['Lifetimes', `root ${pki.settings.root_days} days, issuing CAs ${pki.settings.ca_days} days`],
['CRLs', `issuing CAs ${pki.settings.crl_days} days, root ${pki.settings.root_crl_days} days`],
]}
/>
),
},
{
id: 'certificates',
title: 'Issuing CA certificates',
wide: true,
content: (
<>
{certificateTable(pki.certificates.filter((certificate) => certificate.ca === 'root' || certificate.ca === 'upstream'))}
{pki.status.retired.length > 0 && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
{`Retired: ${pki.status.retired.map((retired) => `${retired.name} (${when(retired.retired)})`).join(', ')}`}
</Typography>
)}
</>
),
},
] : []
const issuingPanels: BoardPanel[] = pki ? [
{
id: 'authorities',
title: 'Issuing CAs',
wide: true,
content: (
<>
<Stack direction="row" sx={{ mb: 1, justifyContent: 'flex-end' }}>
<Button size="small" variant="outlined" startIcon={<Add />} disabled={busy} onClick={() => setAuthority({})}>
Add issuing CA
</Button>
</Stack>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Common name</TableCell>
<TableCell>State</TableCell>
<TableCell>Expires</TableCell>
<TableCell>CRL valid until</TableCell>
<TableCell>Templates</TableCell>
<TableCell>ACME</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{authorities.map((authority) => (
<TableRow key={authority.name} hover>
<TableCell sx={{ whiteSpace: 'nowrap' }}>
{authority.name}
{authority.builtin && <Chip size="small" label="built-in" variant="outlined" sx={{ ml: 1 }} />}
</TableCell>
<TableCell>{authority.subject ?? authority.common_name}</TableCell>
<TableCell>
<Tooltip title={authority.state === 'off' ? `Made once ${authority.component}.enabled is true` : ''}>
<Chip size="small" label={authority.state} color={STATE_COLORS[authority.state] ?? 'default'} />
</Tooltip>
</TableCell>
<TableCell>{when(authority.expires)}</TableCell>
<TableCell>{when(authority.crl_next_update)}</TableCell>
<TableCell>{authority.templates.join(', ')}</TableCell>
<TableCell sx={{ wordBreak: 'break-all' }}>{authority.acme_url ?? (authority.acme ? 'waits for the certificate' : '-')}</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
{authority.state === 'pending' && pki.settings.root === 'offline' && pendingActions(authority.name)}
{authority.state === 'active' && (
<Tooltip title="Download the CA bundle: the issuing CA and the CAs above it">
<span>
<IconButton size="small" disabled={busy} onClick={() => void downloadBundle(authority.name)}><Download fontSize="small" /></IconButton>
</span>
</Tooltip>
)}
{!authority.builtin && (
<>
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setAuthority({ name: authority.name })}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => removeAuthority(authority.name)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
</>
),
},
{
id: 'certificates',
title: 'Certificates issued',
wide: true,
content: (
<>
<TextField select size="small" label="Issuing CA" value={filter} sx={{ mb: 1, minWidth: 200 }} onChange={(event) => setFilter(event.target.value)}>
<MenuItem value="">All</MenuItem>
{authorityNames.map((name) => <MenuItem key={name} value={name}>{name}</MenuItem>)}
</TextField>
{certificateTable(issuedCertificates)}
</>
),
},
] : []
return ( return (
<Box component="section"> <Box component="section">
<Toolbar description="The root CA and the issuing CAs for P2S, site-to-site and general use."> <Toolbar description="The server's HTTPS certificate and ACME CA, the root CA and the issuing CAs for P2S, site-to-site, servers and custom uses.">
<Button variant="contained" startIcon={<Add />} disabled={busy || pki === null} onClick={() => setIssuing(true)}> {view !== 'server' && (
Issue <>
</Button> <Button variant="contained" startIcon={<Add />} disabled={busy || pki === null} onClick={() => setIssuing(true)}>
<Button variant="outlined" startIcon={<Settings />} disabled={busy || pki === null} onClick={() => setEditing(true)}> Issue
Settings </Button>
</Button> <Button variant="outlined" startIcon={<Settings />} disabled={busy || pki === null} onClick={() => setEditing(true)}>
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}> Settings
</Button>
</>
)}
{view === 'root' && <BoardButtons board={rootBoard} />}
{view === 'issuing' && <BoardButtons board={issuingBoard} />}
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => view === 'server' ? setServerRead(serverRead + 1) : void refresh()}>
Refresh Refresh
</Button> </Button>
</Toolbar> </Toolbar>
@@ -405,86 +559,17 @@ export default function CertificatesPanel() {
{note && <Alert severity="info" sx={{ mb: 2 }} onClose={() => setNote(null)}>{note}</Alert>} {note && <Alert severity="info" sx={{ mb: 2 }} onClose={() => setNote(null)}>{note}</Alert>}
{pki?.status.warnings.map((warning) => <Alert key={warning} severity="warning" sx={{ mb: 2 }}>{warning}</Alert>)} {pki?.status.warnings.map((warning) => <Alert key={warning} severity="warning" sx={{ mb: 2 }}>{warning}</Alert>)}
{pki && ( <Tabs value={view} onChange={(_event, next: View) => setView(next)} sx={{ mb: 2, borderBottom: 1, borderColor: 'divider' }}>
<Tabs value={view} onChange={(_event, next: View) => setView(next)} sx={{ mb: 2, borderBottom: 1, borderColor: 'divider' }}> <Tab value="server" label="Server" />
<Tab value="root" label="Root" /> {pki && <Tab value="root" label="Root" />}
<Tab value="templates" label="Templates" /> {pki && <Tab value="templates" label="Templates" />}
<Tab value="usages" label="Extended key usages" /> {pki && <Tab value="usages" label="Extended key usages" />}
<Tab value="p2s" label="P2S Issuing CA" /> {pki && <Tab value="issuing" label="Issuing CAs" />}
<Tab value="s2s" label="S2S Issuing CA" /> </Tabs>
<Tab value="issuing" label="Issuing CAs" />
</Tabs>
)}
{pki && view === 'root' && ( {view === 'server' && <ServerCertificatePanel key={serverRead} />}
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' } }}>
<Section title="Root CA"> {pki && view === 'root' && <Board board={rootBoard} panels={rootPanels} />}
{root && (
<>
<Pairs
rows={[
['Source', root.source === 'simple-ca' ? `Simple CA, ${root.simple_ca_url}` : ROOT_SOURCE_LABELS[root.source]],
['State', <Chip size="small" label={root.state} color={STATE_COLORS[root.state] ?? 'default'} />],
['Subject', root.subject ?? '-'],
['Expires', when(root.expires)],
['CRL valid until', when(root.crl_next_update)],
['CRL', CRL_SOURCE_LABELS[root.crl_source ?? ''] ?? '-'],
...(root.upstream ? [
['Simple CA issuing CA', `${root.upstream.name}: ${root.upstream.subject}`],
['Its expiry', when(root.upstream.expires)],
['Its CRL valid until', when(root.upstream.crl_next_update)],
] as [string, string][] : []),
...(root.source === 'simple-ca' ? [['Token valid until', root.token_expires ? when(root.token_expires) : 'no token']] as [string, string][] : []),
]}
/>
{root.state === 'pending' && root.source === 'local' && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>The server creates it once a platform is chosen.</Typography>
)}
<Stack direction="row" sx={{ mt: 1, justifyContent: 'flex-end', gap: 1 }}>
{root.state === 'active' && (
<Button size="small" variant="outlined" startIcon={<Download />} disabled={busy} onClick={() => void downloadBundle('root')}>
Download root CA
</Button>
)}
{root.source === 'offline' && root.state === 'pending' && (
<Button size="small" variant="outlined" startIcon={<UploadFile />} disabled={busy} onClick={() => setImporting('root')}>
Import root certificate
</Button>
)}
{root.source === 'offline' && root.state === 'active' && (
<Button size="small" variant="outlined" startIcon={<UploadFile />} disabled={busy} onClick={() => setUploading(true)}>
Upload CRL
</Button>
)}
{root.source === 'simple-ca' && (
<Button size="small" variant="outlined" startIcon={<Key />} disabled={busy} onClick={() => setEntering(true)}>
Enter setup code
</Button>
)}
</Stack>
</>
)}
</Section>
<Section title="General">
<Pairs
rows={[
['Published at', pki.settings.publish.map((item) => PUBLISH_LABELS[item] ?? item).join('; ') || 'nowhere'],
['CA key', pki.settings.key],
['Lifetimes', `root ${pki.settings.root_days} days, issuing CAs ${pki.settings.ca_days} days`],
['CRLs', `issuing CAs ${pki.settings.crl_days} days, root ${pki.settings.root_crl_days} days`],
]}
/>
</Section>
<Section title="Issuing CA certificates" wide>
{certificateTable(pki.certificates.filter((certificate) => certificate.ca === 'root' || certificate.ca === 'upstream'))}
{pki.status.retired.length > 0 && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
{`Retired: ${pki.status.retired.map((retired) => `${retired.name} (${when(retired.retired)})`).join(', ')}`}
</Typography>
)}
</Section>
</Box>
)}
{pki && view === 'templates' && ( {pki && view === 'templates' && (
<Box sx={{ display: 'grid', gap: 2 }}> <Box sx={{ display: 'grid', gap: 2 }}>
@@ -610,81 +695,7 @@ export default function CertificatesPanel() {
</Box> </Box>
)} )}
{pki && view === 'p2s' && builtinTab('p2s', 'P2S Issuing CA: the VPN server certificate and the users\' certificates')} {pki && view === 'issuing' && <Board board={issuingBoard} panels={issuingPanels} />}
{pki && view === 's2s' && builtinTab('s2s', 'S2S Issuing CA: the site-to-site certificates of the server and its peers')}
{pki && view === 'issuing' && (
<Box sx={{ display: 'grid', gap: 2 }}>
<Section title="General-purpose issuing CAs">
<Stack direction="row" sx={{ mb: 1, justifyContent: 'flex-end' }}>
<Button size="small" variant="outlined" startIcon={<Add />} disabled={busy} onClick={() => setAuthority({})}>
Add issuing CA
</Button>
</Stack>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Common name</TableCell>
<TableCell>State</TableCell>
<TableCell>Expires</TableCell>
<TableCell>CRL valid until</TableCell>
<TableCell>Templates</TableCell>
<TableCell>ACME</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{general.length === 0 && (
<TableRow>
<TableCell colSpan={8} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{general.map((authority) => (
<TableRow key={authority.name} hover>
<TableCell>{authority.name}</TableCell>
<TableCell>{authority.subject ?? authority.common_name}</TableCell>
<TableCell><Chip size="small" label={authority.state} color={STATE_COLORS[authority.state] ?? 'default'} /></TableCell>
<TableCell>{when(authority.expires)}</TableCell>
<TableCell>{when(authority.crl_next_update)}</TableCell>
<TableCell>{authority.templates.join(', ')}</TableCell>
<TableCell sx={{ wordBreak: 'break-all' }}>{authority.acme_url ?? (authority.acme ? 'waits for the certificate' : '-')}</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
{authority.state === 'pending' && pki.settings.root === 'offline' && pendingActions(authority.name)}
{authority.state === 'active' && (
<Tooltip title="Download the CA bundle: the issuing CA and the CAs above it">
<span>
<IconButton size="small" disabled={busy} onClick={() => void downloadBundle(authority.name)}><Download fontSize="small" /></IconButton>
</span>
</Tooltip>
)}
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setAuthority({ name: authority.name })}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => removeAuthority(authority.name)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
</Section>
<Section title="Certificates issued">
<TextField select size="small" label="Issuing CA" value={filter} sx={{ mb: 1, minWidth: 200 }} onChange={(event) => setFilter(event.target.value)}>
<MenuItem value="">All</MenuItem>
{generalNames.map((name) => <MenuItem key={name} value={name}>{name}</MenuItem>)}
</TextField>
{certificateTable(generalCertificates)}
</Section>
</Box>
)}
{editing && pki && ( {editing && pki && (
<PkiSettingsDialog <PkiSettingsDialog
+225
View File
@@ -0,0 +1,225 @@
import { Alert, Box, Button, Chip, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, Table, TableBody, TableCell, TableRow, TextField, Typography } from '@mui/material'
import { useCallback, useEffect, useState, type FormEvent } from 'react'
import ConfirmDialog from './ConfirmDialog.tsx'
import { COMPONENTS_SHAPE, request, type Component } from './api.ts'
/** Seconds between two reads while a component is being installed. */
const POLL_SECONDS = 3
/** The name and what each component is. */
const LABELS: Record<Component['name'], [string, string]> = {
vpn: ['VPN', 'IKEv2, OpenVPN and WireGuard access for users, on the Remote Access page.'],
router: ['Router', 'Routing between the external and the internal interface, and site-to-site IPsec.'],
dns: ['Name server', 'PowerDNS, the primary name server of the server\'s domains, on the DNS page.'],
webdav: ['WebDAV', 'The folders of the web sites over WebDAV, with rclone behind Caddy.'],
}
/** The chip of a component's installation state. */
const STATE_COLORS: Record<Component['state'], 'default' | 'info' | 'success' | 'error'> = {
'not installed': 'default', installing: 'info', installed: 'success', failed: 'error',
}
/** An IPv4 address with its prefix length, as local.int_addr takes it. */
const ADDRESS_PREFIX = /^(\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/
/** An IPv4 address. */
const ADDRESS = /^(\d{1,3}\.){3}\d{1,3}$/
/**
* The installable components of the server from /components, the VPN, the router, the name server and WebDAV, each
* with its switch and whether its packages are installed. Enable switches a component on, and the server installs its
* packages, which the panel follows every POLL_SECONDS seconds; Disable, after a confirmation, switches it off and
* keeps its packages. The router is offered only while the server has an interface for its internal side, and its
* Enable asks for that interface and, in manual mode, its address and gateway. onChange tells of every change made.
*/
export default function ComponentsPanel(props: { onChange?: () => void }) {
const [components, setComponents] = useState<Component[] | null>(null)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [disabling, setDisabling] = useState<Component | null>(null)
const [router, setRouter] = useState<Component | null>(null)
const read = useCallback(async () => {
try {
setComponents((await request<{ components: Component[] }>('GET', '/components', COMPONENTS_SHAPE)).components)
} catch (caught) {
setError(`The server did not give its components: ${(caught as Error).message}`)
}
}, [])
useEffect(() => {
void read()
}, [read])
// A component switched on is followed while its packages are being installed or are still missing.
const pending = components?.some((item) => item.state === 'installing' || (item.enabled && item.state === 'not installed'))
useEffect(() => {
if (!pending) {
return
}
const timer = window.setInterval(() => void read(), POLL_SECONDS * 1000)
return () => window.clearInterval(timer)
}, [pending, read])
/** Sends the switch of a component, with the router's interface settings, and reads the answer. */
async function change(item: Component, body: Record<string, unknown>) {
setBusy(true)
setError(null)
try {
setComponents((await request<{ components: Component[] }>('PUT', `/components/${item.name}`, COMPONENTS_SHAPE, body)).components)
props.onChange?.()
} finally {
setBusy(false)
}
}
async function enable(item: Component) {
if (item.name === 'router') {
setRouter(item)
return
}
try {
await change(item, { enabled: true })
} catch (caught) {
setError((caught as Error).message)
}
}
return (
<Box>
{error && <Alert severity="error" sx={{ mb: 2, whiteSpace: 'pre-line' }} onClose={() => setError(null)}>{error}</Alert>}
{components === null ? (
<Typography variant="body2" color="text.secondary">The components are not read yet.</Typography>
) : (
<Table size="small">
<TableBody>
{components.map((item) => {
const [label, description] = LABELS[item.name]
const unavailable = item.name === 'router' && item.available === false
return (
<TableRow key={item.name}>
<TableCell sx={{ width: 160, fontWeight: 500 }}>{label}</TableCell>
<TableCell>
<Typography variant="body2">{description}</Typography>
{unavailable && (
<Typography variant="body2" color="text.secondary">It needs a second network interface; the server has only one.</Typography>
)}
{item.enabled && item.state === 'failed' && (
<Typography variant="body2" color="error">The installation failed; Enable tries again, and the Logs tab has its output.</Typography>
)}
</TableCell>
<TableCell sx={{ whiteSpace: 'nowrap' }}>
<Stack direction="row" sx={{ gap: 1, alignItems: 'center' }}>
<Chip size="small" label={item.enabled ? 'on' : 'off'} color={item.enabled ? 'success' : 'default'} variant="outlined" />
<Chip size="small" label={item.state} color={STATE_COLORS[item.state]} />
</Stack>
</TableCell>
<TableCell sx={{ width: 120, textAlign: 'right' }}>
{item.enabled && item.state !== 'failed' ? (
<Button size="small" variant="outlined" disabled={busy} onClick={() => setDisabling(item)}>Disable</Button>
) : (
<Button size="small" variant="contained" disabled={busy || unavailable} onClick={() => void enable(item)}>Enable</Button>
)}
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
)}
{disabling && (
<ConfirmDialog
title={`Disable the ${LABELS[disabling.name][0]}`}
message="The component stops and its settings are kept; its packages stay installed."
confirmLabel="Disable"
destructive
onCancel={() => setDisabling(null)}
onConfirm={() => {
const item = disabling
setDisabling(null)
change(item, { enabled: false }).catch((caught: Error) => setError(caught.message))
}}
/>
)}
{router && (
<RouterDialog
component={router}
onCancel={() => setRouter(null)}
onSave={async (values) => {
await change(router, { enabled: true, ...values })
setRouter(null)
}}
/>
)}
</Box>
)
}
/**
* A dialog that switches the router on: the internal interface, chosen from the server's interfaces but the external
* one, and in manual mode its address with the prefix length and the gateway of the internal network; in auto mode the
* server detects them. onSave sends them; the dialog shows the server's message when it fails.
*/
function RouterDialog(props: {
component: Component
onSave: (values: { internal_interface: string; int_addr: string; int_gateway_ip: string }) => Promise<void>
onCancel: () => void
}) {
const choices = props.component.interfaces ?? []
const mode = props.component.mode ?? 'manual'
const [internal, setInternal] = useState(props.component.internal_interface && choices.includes(props.component.internal_interface)
? props.component.internal_interface : choices[0] ?? '')
const [address, setAddress] = useState(props.component.int_addr ?? '')
const [gateway, setGateway] = useState(props.component.int_gateway_ip ?? '')
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const manual = mode === 'manual'
const addressProblem = manual && !ADDRESS_PREFIX.test(address) ? 'An IPv4 address with its prefix length, such as 10.1.1.4/24.' : ''
const gatewayProblem = manual && !ADDRESS.test(gateway) ? 'An IPv4 address.' : ''
const blocked = (mode !== 'auto' && internal === '') || addressProblem !== '' || gatewayProblem !== ''
async function submit(event: FormEvent) {
event.preventDefault()
if (blocked) {
return
}
setSaving(true)
setError(null)
try {
await props.onSave({ internal_interface: mode === 'auto' ? '' : internal, int_addr: manual ? address : '', int_gateway_ip: manual ? gateway : '' })
} catch (caught) {
setError((caught as Error).message)
setSaving(false)
}
}
return (
<Dialog open onClose={(_event, reason) => reason !== 'backdropClick' && props.onCancel()} maxWidth="xs" fullWidth slotProps={{ paper: { component: 'form', onSubmit: submit } }}>
<DialogTitle>Enable the router</DialogTitle>
<DialogContent>
<Stack sx={{ gap: 2, pt: 1 }}>
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
{mode === 'auto' ? (
<Typography variant="body2" color="text.secondary">In auto mode the server detects the internal interface, its address and its gateway.</Typography>
) : (
<TextField select label="Internal interface" value={internal} onChange={(event) => setInternal(event.target.value)}>
{choices.map((name) => <MenuItem key={name} value={name}>{name}</MenuItem>)}
</TextField>
)}
{manual && (
<>
<TextField label="Address on the internal network" value={address} autoComplete="off" error={address !== '' && addressProblem !== ''} helperText={addressProblem || ' '} onChange={(event) => setAddress(event.target.value.trim())} />
<TextField label="Gateway of the internal network" value={gateway} autoComplete="off" error={gateway !== '' && gatewayProblem !== ''} helperText={gatewayProblem || ' '} onChange={(event) => setGateway(event.target.value.trim())} />
</>
)}
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={props.onCancel} disabled={saving}>Cancel</Button>
<Button type="submit" variant="contained" disabled={saving || blocked}>Enable</Button>
</DialogActions>
</Dialog>
)
}
+78 -67
View File
@@ -9,13 +9,17 @@ import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
import DnsDomainDialog from './DnsDomainDialog.tsx' import DnsDomainDialog from './DnsDomainDialog.tsx'
import DnsRecordDialog from './DnsRecordDialog.tsx' import DnsRecordDialog from './DnsRecordDialog.tsx'
import DnsSettingsDialog from './DnsSettingsDialog.tsx' import DnsSettingsDialog from './DnsSettingsDialog.tsx'
import { Pairs, Section } from './ServerPanel.tsx' import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Pairs } from './ServerPanel.tsx'
import Toolbar from './Toolbar.tsx' import Toolbar from './Toolbar.tsx'
import { import {
ApiError, DNS_DOMAIN_REMOVED_SHAPE, DNS_DOMAIN_SHAPE, DNS_RECORD_SHAPE, DNS_REMOVED_SHAPE, DNS_SETTINGS_SHAPE, DNS_SHAPE, ApiError, DNS_DOMAIN_REMOVED_SHAPE, DNS_DOMAIN_SHAPE, DNS_RECORD_SHAPE, DNS_REMOVED_SHAPE, DNS_SETTINGS_SHAPE, DNS_SHAPE,
request, type Dns, type DnsDomain, type DnsRecord, request, type Dns, type DnsDomain, type DnsRecord,
} from './api.ts' } from './api.ts'
/** The localStorage key of the tab's layout. */
const LAYOUT_KEY = 'linux-manager-ui.dns-layout'
/** A table of records: name, type, content and TTL, with a remove action when onRemove is given. */ /** A table of records: name, type, content and TTL, with a remove action when onRemove is given. */
function Records(props: { records: DnsRecord[]; busy: boolean; onRemove?: (record: DnsRecord) => void }) { function Records(props: { records: DnsRecord[]; busy: boolean; onRemove?: (record: DnsRecord) => void }) {
return ( return (
@@ -61,7 +65,8 @@ function Records(props: { records: DnsRecord[]; busy: boolean; onRemove?: (recor
* The server's name server, from its /dns: the settings of the dns section with whether PowerDNS is installed and runs, * The server's name server, from its /dns: the settings of the dns section with whether PowerDNS is installed and runs,
* its primary name server, the server's FQDN, and the server's public IP, edited with Settings; the domains it is the * its primary name server, the server's FQDN, and the server's public IP, edited with Settings; the domains it is the
* primary of: add, edit and remove; and for the selected domain its manual records: add and remove, and the records it * primary of: add, edit and remove; and for the selected domain its manual records: add and remove, and the records it
* serves. The records of the web sites follow the DNS setting of each site on the Sites page. * serves. The records of the web sites follow the DNS setting of each site on the Sites page. The panels are on a
* PanelBoard whose layout is kept in the browser.
*/ */
export default function DnsPanel() { export default function DnsPanel() {
const [dns, setDns] = useState<Dns | null>(null) const [dns, setDns] = useState<Dns | null>(null)
@@ -73,6 +78,7 @@ export default function DnsPanel() {
const [editing, setEditing] = useState<DnsDomain | 'new' | null>(null) const [editing, setEditing] = useState<DnsDomain | 'new' | null>(null)
const [addingRecord, setAddingRecord] = useState(false) const [addingRecord, setAddingRecord] = useState(false)
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null) const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
const board = useBoard(LAYOUT_KEY)
const refresh = useCallback(async () => { const refresh = useCallback(async () => {
setBusy(true) setBusy(true)
@@ -131,6 +137,74 @@ export default function DnsPanel() {
() => request('DELETE', `${path}/records?${query.toString()}`, DNS_REMOVED_SHAPE)) () => request('DELETE', `${path}/records?${query.toString()}`, DNS_REMOVED_SHAPE))
} }
const panels: BoardPanel[] = dns && section ? [
{
id: 'settings',
title: 'Settings',
wide: true,
content: (
<Pairs
rows={[
['State', <Chip key="state" size="small" label={!section.enabled ? 'disabled' : dns.running ? 'running' : 'not running'} color={!section.enabled ? 'default' : dns.running ? 'success' : 'warning'} />],
['PowerDNS', dns.installed ? 'installed' : 'not installed'],
['Primary name server', dns.nameserver || '-'],
['Secondary name server', section.secondary || (section.enabled ? 'not set' : '-')],
['Public IP address', dns.public_address || '-'],
['Listen', section.listen],
['TTL', `${section.ttl} seconds`],
]}
/>
),
},
{
id: 'domains',
title: 'Domains',
wide: true,
content: (
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Domain</TableCell>
<TableCell align="right">Manual records</TableCell>
<TableCell align="right">TTL</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{dns.domains.length === 0 && (
<TableRow>
<TableCell colSpan={4} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{dns.domains.map((item) => (
<TableRow key={item.name} hover selected={item.name === selected} sx={{ cursor: 'pointer' }} onClick={() => setSelected(item.name)}>
<TableCell>{item.name}</TableCell>
<TableCell align="right">{item.manual.length}</TableCell>
<TableCell align="right">{item.ttl ?? section.ttl}</TableCell>
<TableCell align="right" onClick={(event) => event.stopPropagation()}>
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setEditing(item)}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => removeDomain(item)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
),
},
...(domain ? [
{ id: 'records', title: `Records served of ${domain.name}`, wide: true, content: <Records records={domain.records} busy={busy} /> },
{ id: 'manual', title: `Manual records of ${domain.name}`, wide: true, content: <Records records={domain.manual} busy={busy} onRemove={removeRecord} /> },
] : []),
] : []
return ( return (
<Box component="section"> <Box component="section">
<Toolbar description="The primary name server of the server's domains."> <Toolbar description="The primary name server of the server's domains.">
@@ -143,6 +217,7 @@ export default function DnsPanel() {
<Button variant="outlined" startIcon={<Add />} disabled={busy || !domain} onClick={() => setAddingRecord(true)}> <Button variant="outlined" startIcon={<Add />} disabled={busy || !domain} onClick={() => setAddingRecord(true)}>
Add record Add record
</Button> </Button>
<BoardButtons board={board} />
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}> <Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>
Refresh Refresh
</Button> </Button>
@@ -151,71 +226,7 @@ export default function DnsPanel() {
{error && <Alert severity={unavailable ? 'info' : 'error'} sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>} {error && <Alert severity={unavailable ? 'info' : 'error'} sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>}
{dns?.problem && section?.enabled && <Alert severity="warning" sx={{ mb: 2, whiteSpace: 'pre-line' }}>{dns.problem}</Alert>} {dns?.problem && section?.enabled && <Alert severity="warning" sx={{ mb: 2, whiteSpace: 'pre-line' }}>{dns.problem}</Alert>}
{dns && section && ( {dns && section && <Board board={board} panels={panels} />}
<Box sx={{ display: 'grid', gap: 2 }}>
<Section title="Settings">
<Pairs
rows={[
['State', <Chip key="state" size="small" label={!section.enabled ? 'disabled' : dns.running ? 'running' : 'not running'} color={!section.enabled ? 'default' : dns.running ? 'success' : 'warning'} />],
['PowerDNS', dns.installed ? 'installed' : 'not installed'],
['Primary name server', dns.nameserver || '-'],
['Secondary name server', section.secondary || (section.enabled ? 'not set' : '-')],
['Public IP address', dns.public_address || '-'],
['Listen', section.listen],
['TTL', `${section.ttl} seconds`],
]}
/>
</Section>
<Section title="Domains">
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Domain</TableCell>
<TableCell align="right">Manual records</TableCell>
<TableCell align="right">TTL</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{dns.domains.length === 0 && (
<TableRow>
<TableCell colSpan={4} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{dns.domains.map((item) => (
<TableRow key={item.name} hover selected={item.name === selected} sx={{ cursor: 'pointer' }} onClick={() => setSelected(item.name)}>
<TableCell>{item.name}</TableCell>
<TableCell align="right">{item.manual.length}</TableCell>
<TableCell align="right">{item.ttl ?? section.ttl}</TableCell>
<TableCell align="right" onClick={(event) => event.stopPropagation()}>
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setEditing(item)}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => removeDomain(item)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Section>
{domain && (
<>
<Section title={`Records served of ${domain.name}`}>
<Records records={domain.records} busy={busy} />
</Section>
<Section title={`Manual records of ${domain.name}`}>
<Records records={domain.manual} busy={busy} onRemove={removeRecord} />
</Section>
</>
)}
</Box>
)}
{settings && section && ( {settings && section && (
<DnsSettingsDialog <DnsSettingsDialog
+13 -12
View File
@@ -1,22 +1,21 @@
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, MenuItem, Stack, Switch, TextField } from '@mui/material' import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography } from '@mui/material'
import { useState, type FormEvent } from 'react' import { useState, type FormEvent } from 'react'
import { ADDRESS_PATTERN, LISTEN_CHOICES, ZONE_PATTERN, type DnsSettings, type Listen } from './api.ts' import { ADDRESS_PATTERN, LISTEN_CHOICES, ZONE_PATTERN, type DnsSettings, type Listen } from './api.ts'
/** /**
* A dialog that edits the server's dns section: whether the name server runs, the secondary name server of every * A dialog that edits the server's dns section but whether the name server runs, which the System tab switches: the
* domain, the interfaces it answers on and the TTL, and wan.public_address, the server's public IP the records of the * secondary name server of every domain, the interfaces it answers on and the TTL, and wan.public_address, the server's
* sites with Public IP take. The primary name server is the server's FQDN, nameserver, shown and not edited. An enabled * public IP the records of the sites with Public IP take. The primary name server is the server's FQDN, nameserver,
* name server needs a secondary other than the server's FQDN. onSave sends the section and the public address; the * shown and not edited. The secondary is optional and is not the server's FQDN. onSave sends the
* dialog closes when it succeeds and shows the server's message when it fails. * settings and the public address; the dialog closes when it succeeds and shows the server's message when it fails.
*/ */
export default function DnsSettingsDialog(props: { export default function DnsSettingsDialog(props: {
current: DnsSettings current: DnsSettings
nameserver: string nameserver: string
publicAddress: string publicAddress: string
onSave: (settings: DnsSettings, publicAddress: string) => Promise<void> onSave: (settings: Omit<DnsSettings, 'enabled'>, publicAddress: string) => Promise<void>
onCancel: () => void onCancel: () => void
}) { }) {
const [enabled, setEnabled] = useState(props.current.enabled)
const [secondary, setSecondary] = useState(props.current.secondary) const [secondary, setSecondary] = useState(props.current.secondary)
const [publicAddress, setPublicAddress] = useState(props.publicAddress) const [publicAddress, setPublicAddress] = useState(props.publicAddress)
const [listen, setListen] = useState<Listen>(props.current.listen) const [listen, setListen] = useState<Listen>(props.current.listen)
@@ -24,7 +23,7 @@ export default function DnsSettingsDialog(props: {
const [saving, setSaving] = useState(false) const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const secondaryProblem = secondary === '' ? (enabled ? 'Required while enabled.' : '') const secondaryProblem = secondary === '' ? ''
: !ZONE_PATTERN.test(secondary) ? 'A DNS name in lower case.' : !ZONE_PATTERN.test(secondary) ? 'A DNS name in lower case.'
: secondary === props.nameserver ? 'The secondary is not the server\'s FQDN, the primary.' : '' : secondary === props.nameserver ? 'The secondary is not the server\'s FQDN, the primary.' : ''
const addressProblem = publicAddress === '' || ADDRESS_PATTERN.test(publicAddress) ? '' : 'Not an IP address.' const addressProblem = publicAddress === '' || ADDRESS_PATTERN.test(publicAddress) ? '' : 'Not an IP address.'
@@ -39,7 +38,7 @@ export default function DnsSettingsDialog(props: {
setSaving(true) setSaving(true)
setError(null) setError(null)
try { try {
await props.onSave({ enabled, secondary, listen, ttl: Number(ttl) }, publicAddress) await props.onSave({ secondary, listen, ttl: Number(ttl) }, publicAddress)
} catch (caught) { } catch (caught) {
setError((caught as Error).message) setError((caught as Error).message)
setSaving(false) setSaving(false)
@@ -52,7 +51,9 @@ export default function DnsSettingsDialog(props: {
<DialogContent> <DialogContent>
<Stack sx={{ gap: 2, pt: 1 }}> <Stack sx={{ gap: 2, pt: 1 }}>
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>} {error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
<FormControlLabel control={<Switch checked={enabled} onChange={(event) => setEnabled(event.target.checked)} />} label="Enabled" /> <Typography variant="body2" color="text.secondary">
The name server is {props.current.enabled ? 'on' : 'off'}; it is switched on and off on the System tab.
</Typography>
<TextField <TextField
label="Primary name server" label="Primary name server"
value={props.nameserver || '(the server has no FQDN)'} value={props.nameserver || '(the server has no FQDN)'}
@@ -65,7 +66,7 @@ export default function DnsSettingsDialog(props: {
autoFocus autoFocus
autoComplete="off" autoComplete="off"
error={secondaryProblem !== ''} error={secondaryProblem !== ''}
helperText={secondaryProblem || 'The second NS of every domain; the addresses it resolves to may transfer the domains.'} helperText={secondaryProblem || 'Optional: the second NS of every domain; the addresses it resolves to may transfer the domains. Empty: the server is the only name server.'}
onChange={(event) => setSecondary(event.target.value.trim().toLowerCase())} onChange={(event) => setSecondary(event.target.value.trim().toLowerCase())}
/> />
<TextField <TextField
+37 -25
View File
@@ -1,10 +1,14 @@
import Refresh from '@mui/icons-material/Refresh' import Refresh from '@mui/icons-material/Refresh'
import { Alert, Box, Button, Typography } from '@mui/material' import { Alert, Box, Button, Typography } from '@mui/material'
import { Pairs, Section, text } from './ServerPanel.tsx' import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Pairs, text } from './ServerPanel.tsx'
import Toolbar from './Toolbar.tsx' import Toolbar from './Toolbar.tsx'
import { DETAILS_SHAPE, STATUS_SHAPE, request, type RouterDetails, type RouterStatus } from './api.ts' import { DETAILS_SHAPE, STATUS_SHAPE, request, type RouterDetails, type RouterStatus } from './api.ts'
import { useRead } from './useRead.ts' import { useRead } from './useRead.ts'
/** The localStorage key of the tab's layout. */
const LAYOUT_KEY = 'linux-manager-ui.docker-layout'
/** Reads the server's /status/full and /config. */ /** Reads the server's /status/full and /config. */
const readDocker = async () => { const readDocker = async () => {
const [status, details] = await Promise.all([ const [status, details] = await Promise.all([
@@ -17,42 +21,50 @@ const readDocker = async () => {
/** /**
* The state of Docker on the server: whether it is installed, the state of docker.service and of the server's Docker * The state of Docker on the server: whether it is installed, the state of docker.service and of the server's Docker
* rules, from /status/full, and the ports exposed on the external interface and the rules of the LINUX-MANAGER-DOCKER * rules, from /status/full, and the ports exposed on the external interface and the rules of the LINUX-MANAGER-DOCKER
* chain, from /config. * chain, from /config. The panels are on a PanelBoard whose layout is kept in the browser.
*/ */
export default function DockerPanel() { export default function DockerPanel() {
const { data, error, busy, refresh } = useRead(readDocker) const { data, error, busy, refresh } = useRead(readDocker)
const status = data?.status const status = data?.status
const details = data?.details const details = data?.details
const docker = status?.docker const docker = status?.docker
const board = useBoard(LAYOUT_KEY)
const panels: BoardPanel[] = status && details ? [
{
id: 'status',
title: 'Status',
fixed: true,
content: (
<Pairs
rows={[
['Docker', docker === undefined ? 'unknown' : docker.installed ? 'installed' : 'not installed'],
['docker.service', text(docker?.service)],
['Docker rules', text(docker?.rules)],
['Exposed ports', text(details.docker.exposed_ports)],
]}
/>
),
},
{
id: 'rules',
title: 'Rules of LINUX-MANAGER-DOCKER',
content: details.docker.rules === null
? <Typography variant="body2" color="text.secondary">Not available.</Typography>
: (
<Box component="pre" sx={{ m: 0, overflow: 'auto', fontFamily: 'monospace', fontSize: 12 }}>
{details.docker.rules.length === 0 ? '(none)' : details.docker.rules.join('\n')}
</Box>
),
},
] : []
return ( return (
<Box component="section"> <Box component="section">
<Toolbar description="Docker and its firewall rules."> <Toolbar description="Docker and its firewall rules.">
<BoardButtons board={board} />
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>Refresh</Button> <Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>Refresh</Button>
</Toolbar> </Toolbar>
{error && <Alert severity="error" sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>} {error && <Alert severity="error" sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>}
{status && details && ( <Board board={board} panels={panels} />
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' } }}>
<Section title="Status">
<Pairs
rows={[
['Docker', docker === undefined ? 'unknown' : docker.installed ? 'installed' : 'not installed'],
['docker.service', text(docker?.service)],
['Docker rules', text(docker?.rules)],
['Exposed ports', text(details.docker.exposed_ports)],
]}
/>
</Section>
<Section title="Rules of LINUX-MANAGER-DOCKER">
{details.docker.rules === null
? <Typography variant="body2" color="text.secondary">Not available.</Typography>
: (
<Box component="pre" sx={{ m: 0, overflow: 'auto', fontFamily: 'monospace', fontSize: 12 }}>
{details.docker.rules.length === 0 ? '(none)' : details.docker.rules.join('\n')}
</Box>
)}
</Section>
</Box>
)}
</Box> </Box>
) )
} }
+50 -18
View File
@@ -1,27 +1,44 @@
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Stack, Switch, Typography } from '@mui/material' import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography } from '@mui/material'
import { useState, type FormEvent } from 'react' import { useState, type FormEvent } from 'react'
import type { HttpsSettings } from './api.ts' import { HTTPS_CERTIFICATES, type HttpsCertificateSource, type HttpsChange, type HttpsSettings } from './api.ts'
/** The labels of the sources of the server's certificate. */
export const CERTIFICATE_LABELS: Record<HttpsCertificateSource, string> = {
acme: 'ACME',
'self-signed': 'Self-signed',
ca: 'Servers Issuing CA of the server\'s PKI',
external: 'Another CA: a CSR signed there, or a PFX',
}
/** /**
* A dialog that switches the CA of the certificates Caddy obtains on the server: Let's Encrypt's staging environment, * A dialog that edits where the certificate of the server's FQDN comes from, https.certificate: the ACME CA of
* https.acme_staging, or Caddy's default CAs. onSave sends acme_staging; the dialog closes when it succeeds and shows * AcmeSettingsDialog, a self-signed certificate valid for https.self_signed_days, the Servers Issuing CA, or another
* the server's message when it fails. * CA's certificate, imported on the Server tab of the Certificates page; self-signed is selected while the first setup
* has not chosen one. onSave sends the source and the validity
* only; the dialog closes when it succeeds and shows the server's message when it fails.
*/ */
export default function HttpsSettingsDialog(props: { export default function HttpsSettingsDialog(props: {
current: HttpsSettings current: HttpsSettings
onSave: (settings: { acme_staging: boolean }) => Promise<void> onSave: (settings: HttpsChange) => Promise<void>
onCancel: () => void onCancel: () => void
}) { }) {
const [staging, setStaging] = useState(props.current.acme_staging) const [certificate, setCertificate] = useState<HttpsCertificateSource>(props.current.certificate || 'self-signed')
const [days, setDays] = useState(String(props.current.self_signed_days))
const [saving, setSaving] = useState(false) const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const daysProblem = /^\d{1,4}$/.test(days) && Number(days) >= 1 && Number(days) <= 3650 ? '' : '1 to 3650 days.'
const blocked = certificate === 'self-signed' && daysProblem !== ''
async function submit(event: FormEvent) { async function submit(event: FormEvent) {
event.preventDefault() event.preventDefault()
if (blocked) {
return
}
setSaving(true) setSaving(true)
setError(null) setError(null)
try { try {
await props.onSave({ acme_staging: staging }) await props.onSave(certificate === 'self-signed' ? { certificate, self_signed_days: Number(days) } : { certificate })
} catch (caught) { } catch (caught) {
setError((caught as Error).message) setError((caught as Error).message)
setSaving(false) setSaving(false)
@@ -30,24 +47,39 @@ export default function HttpsSettingsDialog(props: {
return ( return (
<Dialog open onClose={(_event, reason) => reason !== 'backdropClick' && props.onCancel()} maxWidth="sm" fullWidth slotProps={{ paper: { component: 'form', onSubmit: submit } }}> <Dialog open onClose={(_event, reason) => reason !== 'backdropClick' && props.onCancel()} maxWidth="sm" fullWidth slotProps={{ paper: { component: 'form', onSubmit: submit } }}>
<DialogTitle>HTTPS settings</DialogTitle> <DialogTitle>HTTPS certificate</DialogTitle>
<DialogContent> <DialogContent>
<Stack sx={{ gap: 2, pt: 1 }}> <Stack sx={{ gap: 2, pt: 1 }}>
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>} {error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
<FormControlLabel control={<Switch checked={staging} onChange={(event) => setStaging(event.target.checked)} />} label="Let's Encrypt staging CA" /> <TextField select label="Certificate of the server" value={certificate} onChange={(event) => setCertificate(event.target.value as HttpsCertificateSource)}>
<Typography variant="body2" color="text.secondary"> {HTTPS_CERTIFICATES.map((item) => <MenuItem key={item} value={item}>{CERTIFICATE_LABELS[item]}</MenuItem>)}
{staging </TextField>
? 'Caddy takes every certificate from Let\'s Encrypt\'s staging environment, the web sites\' included. Its rate limits are far higher, but no browser trusts its certificates: for routers rebuilt often, for tests only.' {certificate === 'acme' && (
: '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.'} <Typography variant="body2" color="text.secondary">
</Typography> Caddy takes the certificate from the ACME CA, which its own settings choose.
{staging !== props.current.acme_staging && ( </Typography>
<Alert severity="info">The server runs its setup again, which applies the change.</Alert>
)} )}
{certificate === 'self-signed' && (
<TextField
label="Validity (days)"
value={days}
error={daysProblem !== ''}
helperText={daysProblem || 'The server makes a new one when a third of it is left.'}
slotProps={{ htmlInput: { inputMode: 'numeric' } }}
onChange={(event) => setDays(event.target.value.trim())}
/>
)}
{certificate === 'external' && (
<Typography variant="body2" color="text.secondary">
The certificate is imported on this tab, from a CSR the server makes or as a PFX file. The server serves a self-signed certificate until then.
</Typography>
)}
<Alert severity="info">The server runs its setup again, which applies the change.</Alert>
</Stack> </Stack>
</DialogContent> </DialogContent>
<DialogActions> <DialogActions>
<Button onClick={props.onCancel} disabled={saving}>Cancel</Button> <Button onClick={props.onCancel} disabled={saving}>Cancel</Button>
<Button type="submit" variant="contained" disabled={saving || staging === props.current.acme_staging}>Save</Button> <Button type="submit" variant="contained" disabled={saving || blocked}>Save</Button>
</DialogActions> </DialogActions>
</Dialog> </Dialog>
) )
+8 -5
View File
@@ -2,13 +2,14 @@ import {
Alert, Autocomplete, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Stack, Switch, TextField, Typography, Alert, Autocomplete, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Stack, Switch, TextField, Typography,
} from '@mui/material' } from '@mui/material'
import { useState, type FormEvent } from 'react' import { useState, type FormEvent } from 'react'
import { NAME_PATTERN, RESERVED, nameProblem } from './PkiSettingsDialog.tsx' import { NAME_PATTERN, RESERVED, made, nameProblem } from './PkiSettingsDialog.tsx'
import { ROUTER_TEMPLATES, type Pki, type PkiIssuingCa } from './api.ts' import { ROUTER_TEMPLATES, type Pki, type PkiIssuingCa } from './api.ts'
/** /**
* A dialog that adds a general-purpose issuing CA, or with name changes one: its name, fixed once it exists, its common * A dialog that adds a general-purpose issuing CA, or with name changes one: its name, fixed once it exists, its common
* name, the templates it issues and whether Caddy runs an ACME server for it. onSave gets the name and the options; the * name, fixed once the CA has its certificate or CSR, the templates it issues and whether Caddy runs an ACME server for
* dialog closes when it succeeds and shows the server's message when it fails. * it. onSave gets the name and the options; the dialog closes when it succeeds and shows the server's message when it
* fails.
*/ */
export default function IssuingCaDialog(props: { export default function IssuingCaDialog(props: {
pki: Pki pki: Pki
@@ -29,6 +30,7 @@ export default function IssuingCaDialog(props: {
const nameError = props.name !== undefined ? '' const nameError = props.name !== undefined ? ''
: !NAME_PATTERN.test(name.trim()) || RESERVED.includes(name.trim()) ? 'Up to 31 lower case letters, digits and dashes, starting with a letter; not root, p2s or s2s.' : !NAME_PATTERN.test(name.trim()) || RESERVED.includes(name.trim()) ? 'Up to 31 lower case letters, digits and dashes, starting with a letter; not root, p2s or s2s.'
: taken ? 'An issuing CA has this name.' : '' : taken ? 'An issuing CA has this name.' : ''
const commonNameFixed = existing !== undefined && made(existing)
const commonNameError = nameProblem(commonName) const commonNameError = nameProblem(commonName)
const templatesError = templates.length === 0 ? 'At least one template.' : '' const templatesError = templates.length === 0 ? 'At least one template.' : ''
const blocked = nameError !== '' || commonNameError !== '' || templatesError !== '' const blocked = nameError !== '' || commonNameError !== '' || templatesError !== ''
@@ -57,7 +59,7 @@ export default function IssuingCaDialog(props: {
<Typography variant="body2" color="text.secondary"> <Typography variant="body2" color="text.secondary">
{props.name === undefined {props.name === undefined
? 'The root signs the new CA at once while its key is on the server; otherwise the CA waits with a CSR for the offline root.' ? 'The root signs the new CA at once while its key is on the server; otherwise the CA waits with a CSR for the offline root.'
: 'The common name applies when the CA is created; the templates and the ACME server apply at once.'} : 'The templates and the ACME server apply at once.'}
</Typography> </Typography>
<TextField <TextField
label="Name" label="Name"
@@ -71,9 +73,10 @@ export default function IssuingCaDialog(props: {
<TextField <TextField
label="Common name" label="Common name"
value={commonName} value={commonName}
disabled={commonNameFixed}
autoComplete="off" autoComplete="off"
error={commonNameError !== ''} error={commonNameError !== ''}
helperText={commonNameError} helperText={commonNameError || (commonNameFixed ? 'Fixed once the CA exists.' : '')}
onChange={(event) => setCommonName(event.target.value)} onChange={(event) => setCommonName(event.target.value)}
/> />
<Autocomplete <Autocomplete
+6 -1
View File
@@ -1,4 +1,5 @@
import ArrowDropDown from '@mui/icons-material/ArrowDropDown' import ArrowDropDown from '@mui/icons-material/ArrowDropDown'
import Dns from '@mui/icons-material/Dns'
import Hub from '@mui/icons-material/Hub' import Hub from '@mui/icons-material/Hub'
import MenuIcon from '@mui/icons-material/Menu' import MenuIcon from '@mui/icons-material/Menu'
import People from '@mui/icons-material/People' import People from '@mui/icons-material/People'
@@ -28,9 +29,12 @@ export const SITE_TO_SITE_PATH = '/site-to-site-manager'
/** The path of the Docker page: the state of Docker and of its rules. */ /** The path of the Docker page: the state of Docker and of its rules. */
export const DOCKER_PATH = '/docker-manager' export const DOCKER_PATH = '/docker-manager'
/** The path of the Web Sites page: the sites Caddy serves, their files and the name server. */ /** The path of the Web Sites page: the sites Caddy serves and their files. */
export const SITES_PATH = '/sites-manager' export const SITES_PATH = '/sites-manager'
/** The path of the DNS page: the name server's settings, domains and records. */
export const DNS_PATH = '/dns-manager'
/** The path of the shell page: a login shell on the server, opened with the shell button of the header, not the menu. */ /** The path of the shell page: a login shell on the server, opened with the shell button of the header, not the menu. */
export const SHELL_PATH = '/shell' export const SHELL_PATH = '/shell'
@@ -42,6 +46,7 @@ const PAGES: { path: string; label: string; icon: ReactNode }[] = [
{ path: REMOTE_ACCESS_PATH, label: 'Remote Access', icon: <VpnKey fontSize="small" /> }, { path: REMOTE_ACCESS_PATH, label: 'Remote Access', icon: <VpnKey fontSize="small" /> },
{ path: CA_PATH, label: 'Certificates', icon: <VerifiedUser fontSize="small" /> }, { path: CA_PATH, label: 'Certificates', icon: <VerifiedUser fontSize="small" /> },
{ path: SITES_PATH, label: 'Web Sites', icon: <Public fontSize="small" /> }, { path: SITES_PATH, label: 'Web Sites', icon: <Public fontSize="small" /> },
{ path: DNS_PATH, label: 'DNS', icon: <Dns fontSize="small" /> },
{ path: DOCKER_PATH, label: 'Docker', icon: <ViewInAr fontSize="small" /> }, { path: DOCKER_PATH, label: 'Docker', icon: <ViewInAr fontSize="small" /> },
] ]
+67
View File
@@ -0,0 +1,67 @@
import UploadFile from '@mui/icons-material/UploadFile'
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Stack, TextField, Typography } from '@mui/material'
import { useState, type FormEvent } from 'react'
/**
* A dialog that takes a PKCS#12 (PFX) file of another CA's certificate for the server's FQDN, with its key and chain,
* and its password. onSave sends the file in base64 and the password; the dialog closes when it succeeds and shows
* the server's message when it fails.
*/
export default function PfxDialog(props: { onSave: (pfx: string, password: string) => Promise<void>; onCancel: () => void }) {
const [file, setFile] = useState<{ name: string; data: string } | null>(null)
const [password, setPassword] = useState('')
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
/** Reads the chosen file as base64. */
async function choose(chosen: File | undefined) {
if (!chosen) {
return
}
const bytes = new Uint8Array(await chosen.arrayBuffer())
let binary = ''
bytes.forEach((byte) => {
binary += String.fromCharCode(byte)
})
setFile({ name: chosen.name, data: btoa(binary) })
}
async function submit(event: FormEvent) {
event.preventDefault()
if (!file) {
return
}
setSaving(true)
setError(null)
try {
await props.onSave(file.data, password)
} catch (caught) {
setError((caught as Error).message)
setSaving(false)
}
}
return (
<Dialog open onClose={(_event, reason) => reason !== 'backdropClick' && props.onCancel()} maxWidth="sm" fullWidth slotProps={{ paper: { component: 'form', onSubmit: submit } }}>
<DialogTitle>Import a PFX file</DialogTitle>
<DialogContent>
<Stack sx={{ gap: 2, pt: 1 }}>
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
<DialogContentText>A certificate of another CA for the server's FQDN, with its key and chain.</DialogContentText>
<Stack direction="row" sx={{ alignItems: 'center', gap: 1 }}>
<Button component="label" variant="outlined" startIcon={<UploadFile />}>
Choose a file
<input hidden type="file" accept=".pfx,.p12" onChange={(event) => void choose(event.target.files?.[0])} />
</Button>
<Typography variant="body2" color="text.secondary">{file?.name ?? 'No file chosen.'}</Typography>
</Stack>
<TextField label="Password" type="password" value={password} autoComplete="off" onChange={(event) => setPassword(event.target.value)} />
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={props.onCancel}>Cancel</Button>
<Button type="submit" variant="contained" disabled={saving || !file}>Import</Button>
</DialogActions>
</Dialog>
)
}
+21 -11
View File
@@ -3,7 +3,7 @@ import {
Typography, Typography,
} from '@mui/material' } from '@mui/material'
import { useState, type FormEvent } from 'react' import { useState, type FormEvent } from 'react'
import { PKI_KEYS, PKI_PUBLISH, type Pki, type PkiRootSource, type PkiSettings, type PkiTemplate } from './api.ts' import { PKI_KEYS, PKI_PUBLISH, type Pki, type PkiAuthority, type PkiRootSource, type PkiSettings, type PkiTemplate } from './api.ts'
/** The labels of the publishing endpoints. */ /** The labels of the publishing endpoints. */
export const PUBLISH_LABELS: Record<string, string> = { export const PUBLISH_LABELS: Record<string, string> = {
@@ -24,7 +24,7 @@ export const ROOT_SOURCE_LABELS: Record<PkiRootSource, string> = {
export const NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}$/ export const NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}$/
/** The names the issuing CAs of pki.issuing_cas cannot have. */ /** The names the issuing CAs of pki.issuing_cas cannot have. */
export const RESERVED = ['root', 'upstream', 'p2s', 's2s'] export const RESERVED = ['root', 'upstream', 'p2s', 's2s', 'servers']
/** The longest common name of a CA, in characters. */ /** The longest common name of a CA, in characters. */
const CA_NAME_MAX = 64 const CA_NAME_MAX = 64
@@ -37,6 +37,11 @@ export const NEW_TEMPLATE: PkiTemplate = {
key: 'rsa-3072', days: 365, key_usage: ['digital_signature'], extended_key_usage: [], subject: 'name', sans: [], policies: [], key: 'rsa-3072', days: 365, key_usage: ['digital_signature'], extended_key_usage: [], subject: 'name', sans: [], policies: [],
} }
/** Whether an issuing CA has its certificate or its CSR, which fix its common name. */
export function made(authority: PkiAuthority) {
return authority.state === 'active' || authority.state === 'pending'
}
/** A common name's problem, or ''. */ /** A common name's problem, or ''. */
export function nameProblem(value: string) { export function nameProblem(value: string) {
return value.trim() === '' || value.trim().length > CA_NAME_MAX ? `1 to ${CA_NAME_MAX} characters.` : '' return value.trim() === '' || value.trim().length > CA_NAME_MAX ? `1 to ${CA_NAME_MAX} characters.` : ''
@@ -59,10 +64,12 @@ export function daysProblem(value: number) {
/** /**
* A dialog that edits the server's pki section but the general-purpose issuing CAs, the templates and the custom * A dialog that edits the server's pki section but the general-purpose issuing CAs, the templates and the custom
* extended key usages, which IssuingCaDialog, TemplateDialog and EkuDialog edit: the names, lifetimes and key type of * extended key usages, which IssuingCaDialog, TemplateDialog and EkuDialog edit: the names of the P2S and site-to-site
* the CAs, the validity of the CRLs, where certificates and CRLs are published and, with a Simple CA root, the URL of * CAs, the lifetimes and key type of the CAs, the validity of the CRLs, where certificates and CRLs are published and,
* the service. The source of the root is shown and not edited, as it is fixed once the root exists. The server applies * with a Simple CA root, the URL of the service. The source of the root is shown and not edited, as it is fixed once
* the names, lifetimes and key type when it creates a CA. onSave sends the settings; the dialog closes when it * the root exists. The root and the Servers CA are made by the first setup, so their names are not shown; the P2S and
* site-to-site CAs are made when the VPN and the router are switched on, and their names are fixed from then on. The
* server applies the lifetimes and key type when it creates a CA. onSave sends the settings; the dialog closes when it
* succeeds and shows the server's message when it fails. * succeeds and shows the server's message when it fails.
*/ */
export default function PkiSettingsDialog(props: { export default function PkiSettingsDialog(props: {
@@ -75,8 +82,9 @@ export default function PkiSettingsDialog(props: {
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const change = (values: Partial<PkiSettings>) => setSettings({ ...settings, ...values }) const change = (values: Partial<PkiSettings>) => setSettings({ ...settings, ...values })
const fixed = (name: string) => props.pki.status.authorities.some((authority) => authority.name === name && made(authority))
const blocked = [ const blocked = [
nameProblem(settings.root_name), nameProblem(settings.p2s_name), nameProblem(settings.s2s_name), nameProblem(settings.p2s_name), nameProblem(settings.s2s_name),
daysProblem(settings.root_days), daysProblem(settings.ca_days), daysProblem(settings.crl_days), daysProblem(settings.root_crl_days), daysProblem(settings.root_days), daysProblem(settings.ca_days), daysProblem(settings.crl_days), daysProblem(settings.root_crl_days),
settings.root === 'simple-ca' ? urlProblem(settings.simple_ca_url) : '', settings.root === 'simple-ca' ? urlProblem(settings.simple_ca_url) : '',
].some((problem) => problem !== '') ].some((problem) => problem !== '')
@@ -107,6 +115,7 @@ export default function PkiSettingsDialog(props: {
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>} {error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
<Typography variant="body2" color="text.secondary"> <Typography variant="body2" color="text.secondary">
Names, lifetimes and the key type apply when the server creates a CA; URLs apply to the certificates signed afterwards. Names, lifetimes and the key type apply when the server creates a CA; URLs apply to the certificates signed afterwards.
The P2S and site-to-site CAs are created when the VPN and the router are switched on.
</Typography> </Typography>
<Typography variant="subtitle2">CAs</Typography> <Typography variant="subtitle2">CAs</Typography>
<TextField label="Root CA source" value={ROOT_SOURCE_LABELS[settings.root]} disabled helperText="Fixed once the root exists." /> <TextField label="Root CA source" value={ROOT_SOURCE_LABELS[settings.root]} disabled helperText="Fixed once the root exists." />
@@ -120,16 +129,17 @@ export default function PkiSettingsDialog(props: {
onChange={(event) => change({ simple_ca_url: event.target.value.trim() })} onChange={(event) => change({ simple_ca_url: event.target.value.trim() })}
/> />
)} )}
{(['root', 'p2s', 's2s'] as const).filter((name) => name !== 'root' || settings.root === 'local').map((name) => { {(['p2s', 's2s'] as const).map((name) => {
const option = `${name}_name` as 'root_name' | 'p2s_name' | 's2s_name' const option = `${name}_name` as 'p2s_name' | 's2s_name'
return ( return (
<TextField <TextField
key={name} key={name}
label={{ root: 'Root CA name', p2s: 'P2S CA name', s2s: 'Site-to-site CA name' }[name]} label={{ p2s: 'P2S CA name', s2s: 'Site-to-site CA name' }[name]}
value={settings[option]} value={settings[option]}
disabled={fixed(name)}
autoComplete="off" autoComplete="off"
error={nameProblem(settings[option]) !== ''} error={nameProblem(settings[option]) !== ''}
helperText={nameProblem(settings[option])} helperText={nameProblem(settings[option]) || (fixed(name) ? 'Fixed once the CA exists.' : '')}
onChange={(event) => change({ [option]: event.target.value })} onChange={(event) => change({ [option]: event.target.value })}
/> />
) )
+92 -64
View File
@@ -3,16 +3,24 @@ import Edit from '@mui/icons-material/Edit'
import Refresh from '@mui/icons-material/Refresh' import Refresh from '@mui/icons-material/Refresh'
import { Alert, Box, Button, Chip, Stack } from '@mui/material' import { Alert, Box, Button, Chip, Stack } from '@mui/material'
import { useCallback, useEffect, useState } from 'react' import { useCallback, useEffect, useState } from 'react'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import RemoteAccessDialog from './RemoteAccessDialog.tsx' import RemoteAccessDialog from './RemoteAccessDialog.tsx'
import Toolbar from './Toolbar.tsx' import Toolbar from './Toolbar.tsx'
import WireGuardConfigDialog from './WireGuardConfigDialog.tsx' import WireGuardConfigDialog from './WireGuardConfigDialog.tsx'
import WireGuardPeers from './WireGuardPeers.tsx' import WireGuardPeers from './WireGuardPeers.tsx'
import { Copyable, Grid, IPSEC_HEADS, Pairs, Section, bytes, ipsecRows, text } from './ServerPanel.tsx' import { Copyable, Grid, IPSEC_HEADS, Pairs, bytes, ipsecRows, text } from './ServerPanel.tsx'
import { import {
DETAILS_SHAPE, REMOTE_ACCESS_LABELS, REMOTE_ACCESS_SECTION_SHAPES, REMOTE_ACCESS_SHAPE, STATUS_SHAPE, USERS_SHAPE, request, DETAILS_SHAPE, REMOTE_ACCESS_LABELS, REMOTE_ACCESS_SECTION_SHAPES, REMOTE_ACCESS_SHAPE, STATUS_SHAPE, USERS_SHAPE, request,
type RemoteAccess, type RemoteAccessSystem, type RouterDetails, type RouterStatus, type Users, type RemoteAccess, type RemoteAccessSystem, type RouterDetails, type RouterStatus, type Users,
} from './api.ts' } from './api.ts'
/** The localStorage key of each system's layout. */
const LAYOUT_KEYS: Record<RemoteAccessSystem, string> = {
p2s: 'linux-manager-ui.remote-access-p2s-layout',
openvpn: 'linux-manager-ui.remote-access-openvpn-layout',
wireguard: 'linux-manager-ui.remote-access-wireguard-layout',
}
/** What each system describes, above its panels. */ /** What each system describes, above its panels. */
const DESCRIPTIONS: Record<RemoteAccessSystem, string> = { const DESCRIPTIONS: Record<RemoteAccessSystem, string> = {
p2s: 'IKEv2 remote access.', p2s: 'IKEv2 remote access.',
@@ -26,7 +34,8 @@ const DESCRIPTIONS: Record<RemoteAccessSystem, string> = {
* IKEv2, from /config too, the IPsec security associations, child SAs, connections and connection children of all but * IKEv2, from /config too, the IPsec security associations, child SAs, connections and connection children of all but
* the site-to-site connections, that is of IKEv2 access; for WireGuard, from /users and /config too, the peers of the users, added and removed here (WireGuardPeers), and each * the site-to-site connections, that is of IKEv2 access; for WireGuard, from /users and /config too, the peers of the users, added and removed here (WireGuardPeers), and each
* connection with its user, found by the peer's key, its IPs, endpoint, handshake and traffic. The server applies a * connection with its user, found by the peer's key, its IPs, endpoint, handshake and traffic. The server applies a
* change in the background; Refresh reads the state again. * change in the background; Refresh reads the state again. The panels are on a PanelBoard whose layout
* is kept in the browser.
*/ */
export default function RemoteAccessPanel(props: { system: RemoteAccessSystem }) { export default function RemoteAccessPanel(props: { system: RemoteAccessSystem }) {
const [access, setAccess] = useState<RemoteAccess | null>(null) const [access, setAccess] = useState<RemoteAccess | null>(null)
@@ -35,6 +44,7 @@ export default function RemoteAccessPanel(props: { system: RemoteAccessSystem })
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const [editing, setEditing] = useState(false) const [editing, setEditing] = useState(false)
const [showConfig, setShowConfig] = useState(false) const [showConfig, setShowConfig] = useState(false)
const board = useBoard(LAYOUT_KEYS[props.system])
// WireGuard's: the users with their peers, and the server's details with each peer's key, endpoint and traffic. // WireGuard's: the users with their peers, and the server's details with each peer's key, endpoint and traffic.
const [users, setUsers] = useState<Users | null>(null) const [users, setUsers] = useState<Users | null>(null)
const [details, setDetails] = useState<RouterDetails | null>(null) const [details, setDetails] = useState<RouterDetails | null>(null)
@@ -91,10 +101,89 @@ export default function RemoteAccessPanel(props: { system: RemoteAccessSystem })
// An IPsec table is shown with rows, or with the note that the server could not read them. // An IPsec table is shown with rows, or with the note that the server could not read them.
const shown = (rows: string[][] | undefined) => ikev2 && details !== null && (rows === undefined || rows.length > 0) const shown = (rows: string[][] | undefined) => ikev2 && details !== null && (rows === undefined || rows.length > 0)
const panels: BoardPanel[] = access ? [
{ id: 'settings', title: 'Settings', content: <Pairs rows={rows} /> },
{
id: 'state',
title: 'State',
content: (
<Pairs
rows={[
['Running', <Chip key="running" size="small" label={running ? 'running' : 'not running'} color={running ? 'success' : 'default'} />],
...(system === 'wireguard'
? [['Peers', peers === undefined || peers === null ? '-' : String(peers.length)] as [string, string]]
: [['Connected clients', clients === undefined || clients === null ? '-' : String(clients)] as [string, string]]),
]}
/>
),
},
...(shown(ipsec.sas) ? [{ id: 'ipsec-sas', title: 'IPsec security associations', wide: true, content: <Grid head={IPSEC_HEADS.sas} rows={ipsec.sas} /> }] : []),
...(shown(ipsec.childSas) ? [{ id: 'ipsec-child-sas', title: 'IPsec child SAs', wide: true, content: <Grid head={IPSEC_HEADS.childSas} rows={ipsec.childSas} /> }] : []),
...(shown(ipsec.connections) ? [{ id: 'ipsec-connections', title: 'IPsec connections', wide: true, content: <Grid head={IPSEC_HEADS.connections} rows={ipsec.connections} /> }] : []),
...(shown(ipsec.children) ? [{ id: 'ipsec-children', title: 'IPsec connection children', wide: true, content: <Grid head={IPSEC_HEADS.children} rows={ipsec.children} /> }] : []),
...(system === 'wireguard' ? [{
id: 'server',
title: 'Server',
wide: true,
content: (
<>
<Pairs
rows={[
['Public key', access.wireguard_server.public_key === null ? 'not made yet; setup makes it once WireGuard is enabled'
: <Copyable key="key" value={access.wireguard_server.public_key} label="public key" />],
['Endpoint', access.wireguard_server.endpoint ?? 'unknown: wan.local_fqdn is not set'],
['Allowed IPs', text(access.wireguard_server.allowed_ips)],
]}
/>
<Stack direction="row" sx={{ mt: 1, justifyContent: 'flex-end' }}>
<Button
size="small"
variant="outlined"
startIcon={<Description />}
disabled={!access.wireguard_server.public_key || !access.wireguard_server.endpoint}
onClick={() => setShowConfig(true)}
>
Show config
</Button>
</Stack>
</>
),
}] : []),
...(system === 'wireguard' ? [{
id: 'peers',
title: 'Peers',
wide: true,
content: <WireGuardPeers server={access.wireguard_server} users={users} onChanged={() => void refresh()} />,
}] : []),
...(system === 'wireguard' && running ? [{
id: 'connections',
title: 'Connections',
wide: true,
content: (
<Grid
head={['User', 'IPs', 'Endpoint', 'Handshake', 'Received', 'Sent']}
rows={details?.wireguard?.peers.map((peer) => {
// A peer is a user's by its key; one added to wg0.conf by hand has no user.
const owner = users?.users.find((user) => user.wireguard_peers.some((own) => own.public_key === peer.public_key))
return [
owner?.name ?? `- (${peer.public_key.slice(0, 8)}...)`,
peer.allowed_ips.join(', '),
peer.endpoint ?? '-',
peer.handshake_seconds_ago === null ? 'none' : `${peer.handshake_seconds_ago} s ago`,
bytes(peer.received_bytes),
bytes(peer.sent_bytes),
]
}) ?? undefined}
/>
),
}] : []),
] : []
return ( return (
<Box component="section"> <Box component="section">
<Toolbar description={DESCRIPTIONS[system]}> <Toolbar description={DESCRIPTIONS[system]}>
<Button variant="outlined" startIcon={<Edit />} disabled={!access || busy} onClick={() => setEditing(true)}>Edit</Button> <Button variant="outlined" startIcon={<Edit />} disabled={!access || busy} onClick={() => setEditing(true)}>Edit</Button>
<BoardButtons board={board} />
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>Refresh</Button> <Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>Refresh</Button>
</Toolbar> </Toolbar>
{error && <Alert severity="error" sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>} {error && <Alert severity="error" sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>}
@@ -105,68 +194,7 @@ export default function RemoteAccessPanel(props: { system: RemoteAccessSystem })
: `${REMOTE_ACCESS_LABELS[system]} is enabled but does not run yet. It needs wan.local_fqdn${access.local_fqdn ? '' : ', which is not set,'} and the server's VPN server certificate of the P2S issuing CA; the server applies a change within a moment.`} : `${REMOTE_ACCESS_LABELS[system]} is enabled but does not run yet. It needs wan.local_fqdn${access.local_fqdn ? '' : ', which is not set,'} and the server's VPN server certificate of the P2S issuing CA; the server applies a change within a moment.`}
</Alert> </Alert>
)} )}
{access && ( {access && <Board board={board} panels={panels} />}
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' } }}>
<Section title="Settings"><Pairs rows={rows} /></Section>
<Section title="State">
<Pairs
rows={[
['Running', <Chip key="running" size="small" label={running ? 'running' : 'not running'} color={running ? 'success' : 'default'} />],
...(system === 'wireguard'
? [['Peers', peers === undefined || peers === null ? '-' : String(peers.length)] as [string, string]]
: [['Connected clients', clients === undefined || clients === null ? '-' : String(clients)] as [string, string]]),
]}
/>
</Section>
{shown(ipsec.sas) && <Section title="IPsec security associations" wide><Grid head={IPSEC_HEADS.sas} rows={ipsec.sas} /></Section>}
{shown(ipsec.childSas) && <Section title="IPsec child SAs" wide><Grid head={IPSEC_HEADS.childSas} rows={ipsec.childSas} /></Section>}
{shown(ipsec.connections) && <Section title="IPsec connections" wide><Grid head={IPSEC_HEADS.connections} rows={ipsec.connections} /></Section>}
{shown(ipsec.children) && <Section title="IPsec connection children" wide><Grid head={IPSEC_HEADS.children} rows={ipsec.children} /></Section>}
{system === 'wireguard' && (
<Section title="Server" wide>
<Pairs
rows={[
['Public key', access.wireguard_server.public_key === null ? 'not made yet; setup makes it once WireGuard is enabled'
: <Copyable key="key" value={access.wireguard_server.public_key} label="public key" />],
['Endpoint', access.wireguard_server.endpoint ?? 'unknown: wan.local_fqdn is not set'],
['Allowed IPs', text(access.wireguard_server.allowed_ips)],
]}
/>
<Stack direction="row" sx={{ mt: 1, justifyContent: 'flex-end' }}>
<Button
size="small"
variant="outlined"
startIcon={<Description />}
disabled={!access.wireguard_server.public_key || !access.wireguard_server.endpoint}
onClick={() => setShowConfig(true)}
>
Show config
</Button>
</Stack>
</Section>
)}
{system === 'wireguard' && <WireGuardPeers server={access.wireguard_server} users={users} onChanged={() => void refresh()} />}
{system === 'wireguard' && running && (
<Section title="Connections" wide>
<Grid
head={['User', 'IPs', 'Endpoint', 'Handshake', 'Received', 'Sent']}
rows={details?.wireguard?.peers.map((peer) => {
// A peer is a user's by its key; one added to wg0.conf by hand has no user.
const owner = users?.users.find((user) => user.wireguard_peers.some((own) => own.public_key === peer.public_key))
return [
owner?.name ?? `- (${peer.public_key.slice(0, 8)}...)`,
peer.allowed_ips.join(', '),
peer.endpoint ?? '-',
peer.handshake_seconds_ago === null ? 'none' : `${peer.handshake_seconds_ago} s ago`,
bytes(peer.received_bytes),
bytes(peer.sent_bytes),
]
}) ?? undefined}
/>
</Section>
)}
</Box>
)}
{showConfig && access && ( {showConfig && access && (
<WireGuardConfigDialog title="WireGuard configuration of a device" server={access.wireguard_server} ips={null} onClose={() => setShowConfig(false)} /> <WireGuardConfigDialog title="WireGuard configuration of a device" server={access.wireguard_server} ips={null} onClose={() => setShowConfig(false)} />
)} )}
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more