diff --git a/.gitignore b/.gitignore index 1d4c4d7..f1d2a1e 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,4 @@ web/dist dev.json /.dev-build.serial **/.env +/.lm-dev-config/ diff --git a/ADR.md b/ADR.md index 4460182..47c490c 100644 --- a/ADR.md +++ b/ADR.md @@ -27,7 +27,7 @@ port is reachable from the external interface only when it is in `exposed_ports` in `DOCKER-USER` are not touched, because the package owns only its own chain. Restarting Docker restores the rules. The rules cover IPv4 only. -## ADR-2: A small status web service, on the interfaces web.listen chooses +## ADR-2: A small status web service, reached on the interfaces web.listen chooses Status: Accepted @@ -38,11 +38,12 @@ host, so what the service shows and where it listens matter. Decision: The `linux-manager-web` unit runs one Python script on the standard library's `http.server`, with the package's own modules and the Python packages of the Ubuntu archive that -the package depends on, and no web framework. It listens on `web.port`, 7081 by default, on the -address of the internal interface, of the external interface or of both, as `web.listen` sets -(`internal`, `external` or `both`, the default), with a server for each address, and is on -unless `web.enabled` is `false` (ADR-7). `/` is for people, in plain text for `curl` and `wget` -and as a Tailwind CSS page for a browser, and `/status` is the same status as JSON. Both show as +the package depends on, and no web framework. It listens on the loopback address behind Caddy +(ADR-21), which serves it on `web.port`, 7081 by default, and is on unless `web.enabled` is +`false` (ADR-7). The firewall opens `web.port` on the internal interface, the external interface +or both, as `web.listen` sets (`internal`, `external` or `both`, the default). `/` is for people, +in plain text for `curl` and `wget` and as a Tailwind CSS page for a browser, and `/status` is +the same status as JSON. Both show as much as `web.status_content` says, since the server is reachable from the internet and the operator decides how much it tells strangers: `basic`, the default because it tells the least, the overall status and the Client IP, `standard` also the package versions and the number of @@ -50,16 +51,14 @@ active and other services, and `full` also each service and the state of the sit WireGuard features. The Client IP is the address the request came from, through the trusted proxies, so a person can see the address the server sees. Nothing comes from the configuration. `/status` names its content, so clients such as Cloud Manager and the Manager show what it -has. `linux-manager-setup` opens the -port on both interfaces in UFW, so the choice of `web.listen` is made by the service alone, and -writes the features and the facts it resolves to `/run/linux-manager/web.json`. +has. `linux-manager-setup` writes the firewall rules of `web.listen`, and the features and the +facts it resolves to `/run/linux-manager/web.json`. Consequences: By default the service is reachable from the internet on the external address; -`web.listen` set to `internal` keeps it to the internal network. It serves plain HTTP itself; -HTTPS is Caddy's (ADR-21), so on the plain HTTP port the passwords of `/auth` and the tokens -cross the internet unencrypted. A change of `web.listen` -needs no run of setup, since the firewall does not depend on it; the package's upgrade runs -setup, which writes the rules. `/` and `/status` have no authentication, which is acceptable because they are +`web.listen` set to `internal` keeps it to the internal network. Caddy serves it over plain HTTP +as well as HTTPS (ADR-21), so on the plain HTTP port the passwords of `/auth` and the tokens +cross the internet unencrypted. A change of `web.listen` takes effect with the next run of setup, +which writes the firewall rules. `/` and `/status` have no authentication, which is acceptable because they are read only and show no configuration. It runs as root, because `swanctl` and `wg` need it, with `NoNewPrivileges`, `ProtectSystem=strict`, `ProtectHome` and `PrivateTmp`. The Tailwind style comes from a CDN, so a browser on a network without internet shows the unstyled page, and `curl` is unaffected. @@ -347,7 +346,10 @@ lockout. A Ubuntu Linux Manager signs all its users in from one address. Decision: The default password policy locks an account for 15 minutes after 5 failed binds within 15 minutes; a successful bind clears the count; `linux-manager-user unlock` and `POST /users//unlock` end a lockout and clear the count, and leave a disabled user disabled. -`/auth` answers the same 401 for a wrong name, password or code and for a locked or disabled +The count, `pwdFailureTime`, is NO-USER-MODIFICATION in the ppolicy schema, so the unlock is sent +with the Relax Rules control (`1.3.6.1.4.1.4203.666.5.12`), which slapd honours for the user +manager account; deleting `pwdAccountLockedTime` alone would leave the failures counted, and the +next wrong password would lock the account again. `/auth` answers the same 401 for a wrong name, password or code and for a locked or disabled user. `/auth` and `/auth/refresh` allow 10 calls a minute per client address, counted in memory, and answer 429 with `Retry-After` beyond that. The client address is the peer, or the last `X-Forwarded-For` entry for a peer in `web.trusted_proxies`, by default the address the call came @@ -518,41 +520,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 needs an administrator. -## ADR-21: Caddy from the Ubuntu archive serves HTTPS with a certificate from Let's Encrypt +## ADR-21: Caddy from the Ubuntu archive serves every HTTP and HTTPS port, the services listen on loopback Status: Accepted Context: The status web service and the Manager are reachable from the internet (ADR-2), and `/auth` and the Manager's sign-in carry passwords. Both are small servers on the standard library's `http.server`, which would need certificates, their renewal and a TLS setup of their -own. Browsers trust a public CA, not the server's. +own. Browsers trust a public CA, not the server's; a server off the internet, or of an +organisation with a PKI of its own, cannot use a public CA. Caddy is needed for HTTPS anyway, and +one front for plain HTTP and HTTPS keeps one place where the server's ports, the redirect to HTTPS +and the client's address are decided. -Decision: Caddy, the `caddy` package of the Ubuntu archive, is the HTTPS proxy. While -`https.enabled` is `true` (the default) and `wan.local_fqdn` is set, `linux-manager-setup` writes -`/etc/caddy/linux-manager.Caddyfile`: a site for `wan.local_fqdn` on `https.web_port` (7444) for the -web service and, while the Manager is installed, one on `https.manager_port` (7443) for -the manager, each passing calls to the service on `127.0.0.1`. Caddy obtains and renews the -certificate from Let's Encrypt with the HTTP challenge on port 80, which the firewall opens on -the external interface; `auto_https disable_redirects` keeps port 80 to the challenge. The -package's drop-in for `caddy.service` points it at that file and keeps it from starting before -the file exists, so `/etc/caddy/Caddyfile`, a configuration file of the `caddy` package, is left -unchanged. Both services always listen on `127.0.0.1` as well as on the interfaces their -`listen` settings name, and trust `X-Forwarded-For` from it, which Caddy sets from the peer and -never takes from the client. Let's Encrypt issues at most 5 certificates a week for the same -names, which routers rebuilt for tests reach; `https.acme_staging` sets Caddy's global `acme_ca` -to Let's Encrypt's staging directory, which replaces Caddy's default CAs for every site, so no -test certificate comes from a production CA. `PUT /https/settings` changes `acme_staging` alone: +Decision: Caddy, the `caddy` package of the Ubuntu archive and a dependency of the package +(ADR-31), serves every HTTP and HTTPS port of the server's services. The web service listens on +`127.0.0.1:7091`, the Manager on the server on `127.0.0.1:7090`, the metrics service on +`127.0.0.1:9474` and rclone's WebDAV on `127.0.0.1:7446`, and Caddy calls them there. Once the +server is configured, `linux-manager-setup` writes `/etc/caddy/linux-manager.Caddyfile`: plain +HTTP sites on `web.port` (7081), the Manager's `port` (7080) and, while metrics are on, +`metrics.port` (9464), on every address; while `https.enabled` is `true` and `wan.local_fqdn` is +set, sites for `wan.local_fqdn` on `https.web_port` (7444), `https.manager_port` (7443), +`metrics.https_port` (9465) and `sites.webdav_port` (7445). While HTTPS is on, the Manager's plain +HTTP site redirects (308) to its HTTPS address unless `https.disable_auto_redirect` is set; the +status page's never does, so monitors and clients that do not trust the server's certificate +keep reaching it. The `listen` settings choose the interfaces the firewall opens each plain HTTP +port on, as Caddy listens on every address. The certificate comes from `https.certificate` +(ADR-60); with `acme`, Caddy obtains and renews it with the HTTP challenge on port 80, which the +firewall opens on the external interface then; `auto_https disable_redirects` keeps port 80 to the +challenge. The ACME CA is `https.acme_provider`, written as Caddy's global `cert_issuer`, so it is +also the CA of the web sites with `tls` `acme`: Let's Encrypt, ZeroSSL, whose issuer gets its EAB +credentials itself, or a custom directory with optional EAB. The package's drop-in for +`caddy.service` points it at that file and keeps it from starting before the file exists, so +`/etc/caddy/Caddyfile`, a configuration file of the `caddy` package, is left unchanged. The +services trust `X-Forwarded-For` from `127.0.0.1`, which Caddy sets from the peer and never takes +from the client, and the OpenID Provider answers only calls with `X-Forwarded-Proto: https`, +which Caddy sets on its HTTPS sites. Let's Encrypt issues at most 5 certificates a week for the +same names, which routers rebuilt for tests reach; with `letsencrypt`, `https.acme_staging` makes +the issuer's directory Let's Encrypt's staging one, so no test certificate comes from a +production CA. `PUT /https/settings` changes the certificate source and the ACME settings only: the other settings of the section switch HTTPS off or move its ports, which would end the connection the Manager makes the change on. -Consequences: HTTPS needs `wan.local_fqdn` in public DNS pointing at the server and port 80 -reachable from the internet; until then Caddy retries and the HTTPS ports do not answer. The -certificate and the ACME account are in `/var/lib/caddy`. A router on the staging CA has a -certificate no client trusts. Plain HTTP stays as the `listen` -settings set it, so `internal` keeps passwords off the internet. Caddy's admin endpoint listens -on `localhost:2019`, which `caddy reload` uses. Port 80 and the HTTPS ports are not available -to Docker containers while HTTPS is on. The Manager's HTTPS port is a setting of the server, not -of the manager. +Consequences: HTTPS with a public ACME CA needs `wan.local_fqdn` in public DNS pointing at the +server and port 80 reachable from the internet; until then Caddy retries and the HTTPS ports do +not answer. The certificate and the ACME account are in `/var/lib/caddy`. A router on the staging +CA has a certificate no client trusts. A service that is not behind Caddy cannot be reached from +another host, so while Caddy is stopped, or before the first setup, only the bootstrap page +answers. The loopback ports are fixed, and no site or Docker container may take them or Caddy's +ports. Caddy's admin endpoint listens on `localhost:2019`, which `caddy reload` uses. The +Manager's HTTPS port is a setting of the server, not of the manager. ## ADR-22: Metrics are kept in PostgreSQL and served in the Prometheus format, pushed with OTLP @@ -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 offline from the CSRs the server makes, are imported with `linux-manager-ca` or `/ca`, the root first; `simple-ca`, a Simple CA service (ADR-59). The issuing CAs, path length 0, sign the -certificates. `p2s` signs the server's VPN server certificate and the users' certificates, -`s2s` the site-to-site certificates, and the CAs of `pki.issuing_cas` what their templates -allow. A template fixes the key, the lifetime, the key usages, the extended key usages, the kind +certificates. Three are built in: `p2s` signs the server's VPN server certificate and the +users' certificates, `s2s` the site-to-site certificates, and `servers`, the Servers Issuing CA, mTLS +certificates with both the server and the client purposes, the server's HTTPS certificate among +them (ADR-60); the custom CAs of `pki.issuing_cas` sign what their templates allow, such as code +signing. The Manager shows all of them in one Issuing CAs tab. A template fixes the key, the lifetime, the key usages, the extended key usages, the kind of common name and the subject alternative names a certificate may have; `vpn-server` and `vpn-user` are issued by the server only, so no certificate for another use comes from the P2S CA. The module `linuxmanager_pki.py`, with `python3-cryptography` from the Ubuntu archive, builds @@ -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 the place of revocation. An issuing CA waiting for the offline root has no ACME server. -## ADR-31: linux-manager-setup installs Caddy from the Ubuntu archive or from Caddy's repository +## ADR-31: Caddy is a dependency of the package, from the Ubuntu archive Status: Accepted -Context: Caddy 2.6.2 of the Ubuntu archive lacks later features, such as a pki root without its key -and the settings of the ACME server. Caddy's own repository has current versions of the package of -the same name. A dependency on `caddy` installs the archive's package with `linux-manager`. apt cannot -run inside `linux-manager-setup` when the package's installation runs setup, as dpkg holds its lock. +Context: Caddy fronts every HTTP and HTTPS port of the server (ADR-21), so the server's services +cannot be reached without it. Caddy 2.6.2 of the Ubuntu archive lacks later features, such as a +pki root without its key and the settings of the ACME server; Caddy's own repository has current +versions, but a third-party repository, its key and a version that sorts above the archive's are +one more thing to keep and to trust. -Decision: `linux-manager` only suggests `caddy`. While HTTPS is on, setup has -`linux-manager-caddy.service` install it from `https.caddy_source`: `ubuntu`, or `upstream`, for -which the unit writes the deb822 source and the key it downloads over HTTPS from Caddy's -repository. The unit waits for dpkg's lock and runs setup again when Caddy is in place. -`linux-manager-caddy use-upstream` switches an installed router. Upstream's versions sort above the -archive's, so once the repository is configured apt keeps upstream's Caddy without a pin, and -`ubuntu` has no effect; nothing downgrades Caddy on its own, as a downgrade may break the -configuration and is the administrator's decision. Only the CLI switches the source; the -Manager shows which one is in effect. +Decision: `linux-manager` depends on `caddy`, which apt installs from the Ubuntu archive with the +package and upgrades with the system's packages. The package writes no repository of its own and +installs nothing at setup time, and the configuration uses only what Caddy 2.6.2 supports. -Consequences: The first setup run with HTTPS starts the installation and serves HTTPS on the run -that follows it. The key of Caddy's repository is trusted as downloaded over HTTPS, the way Caddy's -installation instructions do it. Going back to the archive's Caddy is a manual downgrade. +Consequences: Features of later Caddy versions are not available until the archive has them. An +administrator who adds another repository with a `caddy` package gets that version, which the +package does not check. ## ADR-32: The PKI is kept in the server's directory @@ -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 `https://:`; its auth proxy, `webdav-auth`, binds as the user and gives an admin all sites and any other user the sites of its editors groups, one folder each. -rclone and PowerDNS are installed on demand from the archive by `linux-manager-install@`, -like Caddy. +rclone and PowerDNS are installed on demand from the archive by `linux-manager-install@` +(ADR-57). Consequences: Uploads and WebDAV use the directory's passwords, a TOTP code appended for an enrolled user. rclone writes a WebDAV upload to its cache first and to the folder a few seconds @@ -1221,45 +1234,46 @@ later. S3 and Azure Blob clients are not served. Status: Accepted -Context: The server hosts authoritative domains as their primary, with a secondary name server, and -a domain can give the sites their records without a registrar change per site. The server's own -name, `wan.local_fqdn`, belongs to a domain of its own, wherever that is hosted. Ubuntu -has BIND, Knot and PowerDNS; only PowerDNS's gpgsql backend reads records -from PostgreSQL, so changes are rows, without zone files or reloads. systemd-resolved's stub holds -127.0.0.53 and 127.0.0.54, and the remote access clients' resolver answered on the external -addresses, the addresses an authoritative server needs. The clients reach the internal address -just as well, through the tunnel when it is in `local.cidrs` (ADR-43). +Context: The server hosts authoritative domains as their primary, with an optional secondary name +server, and a domain can give the sites their records without a registrar change per site. The +server's own name, `wan.local_fqdn`, belongs to a domain of its own, wherever that is hosted. Ubuntu +has BIND, Knot and PowerDNS; only PowerDNS's gpgsql backend reads records from PostgreSQL, so +changes are rows, without zone files or reloads. systemd-resolved's stub holds 127.0.0.53 and +127.0.0.54, and the remote access clients' resolver answered on the external addresses, the +addresses an authoritative server needs. The clients reach the internal address just as well, +through the tunnel when it is in `local.cidrs` (ADR-43). Decision: While `dns.enabled` is true, setup runs `pdns.service` with `/etc/powerdns/pdns.d/linux-manager.conf`, written before the packages are installed, on the -addresses of `dns.listen`, with the gpgsql backend on the database `linux-manager-dns` and PowerDNS's -own schema, and `primary=yes`. The domains and their manual records are rows of the server's tables -in that database, like the sites in `linux-manager-sites`, not settings of `linux-manager.json`: they are -many and change through the web service. The name servers are settings, the same for every domain: -`wan.local_fqdn`, the server's one name, is the primary, and `dns.secondary` the secondary. Setup -writes each domain as a MASTER zone through the procedure `dns_apply` of -`/usr/share/linux-manager/sql/dns.sql`: SOA with `wan.local_fqdn`, NS of `wan.local_fqdn` and -`dns.secondary`, an A or AAAA record of every host name of a site with `dns` `router` whose closest -domain it is, with the server's address the site chooses (`wan.public_address`, the internal or the -external interface's), and the manual records; the serial grows only when the records change, which -makes PowerDNS notify. `wan.local_fqdn` gets no record in the domains: its A record is in the DNS of -its own domain, which the server does not manage. A site of `dns` `user` gets no records, as its -names are served elsewhere. The addresses `dns.secondary` resolves to at each run go to every -domain's `ALSO-NOTIFY` and `ALLOW-AXFR-FROM` metadata, so the global `allow-axfr-ips` stays the -loopback default. The public address is a setting, since the server sees only private addresses on -its interfaces behind a cloud's NAT and resolving `wan.local_fqdn` would answer from its own DNS -when it hosts that name. `dns.nameserver` and `dns.addresses` of an earlier configuration are left -out when it is read, so that it loads; a missing `dns.secondary` makes setup warn, not fail, so that -a router keeps running until it is set. A host name belongs to its closest domain only, and a -domain inside another is delegated from it with NS records, so a name is never answered by two -zones. The remote access clients' resolver answers on the addresses of the setting -`p2s.dns_listen`, by default the internal one; a `dns.listen` that shares an interface with it is -refused while P2S or OpenVPN is enabled. +addresses of `dns.listen`, with the gpgsql backend on the database `linux-manager-dns` and +PowerDNS's own schema, and `primary=yes`. The domains and their manual records are rows of the +server's tables in that database, like the sites in `linux-manager-sites`, not settings of +`linux-manager.json`: they are many and change through the web service. The name servers are +settings, the same for every domain: `wan.local_fqdn`, the server's one name, is the primary, and +`dns.secondary` the secondary, which is optional: without it the domains have the primary as their +only name server, as a small or internal deployment has no second server to name. Setup writes each +domain as a MASTER zone through the procedure `dns_apply` of `/usr/share/linux-manager/sql/dns.sql`: +SOA with `wan.local_fqdn`, NS of `wan.local_fqdn` and `dns.secondary` while it is set, an A or AAAA +record of every host name of a site with `dns` `router` whose closest domain it is, with the +server's address the site chooses (`wan.public_address`, the internal or the external interface's), +and the manual records; the serial grows only when the records change, which makes PowerDNS notify. +`wan.local_fqdn` gets no record in the domains: its A record is in the DNS of its own domain, which +the server does not manage. A site of `dns` `user` gets no records, as its names are served +elsewhere. The addresses `dns.secondary` resolves to at each run go to every domain's `ALSO-NOTIFY` +and `ALLOW-AXFR-FROM` metadata, so the global `allow-axfr-ips` stays the loopback default. The +public address is a setting, since the server sees only private addresses on its interfaces behind a +cloud's NAT and resolving `wan.local_fqdn` would answer from its own DNS when it hosts that name. +`dns.nameserver` and `dns.addresses` of an earlier configuration are left out when it is read, so +that it loads. A host name belongs to its closest domain only, and a domain inside another is +delegated from it with NS records, so a name is never answered by two zones. The remote access +clients' resolver answers on the addresses of the setting `p2s.dns_listen`, by default the internal +one; a `dns.listen` that shares an interface with it is refused while P2S or OpenVPN is enabled. Consequences: The domains follow the sites at each setup run. Transfers are authorized by the address the secondary's name resolves to, without TSIG, and there is no DNSSEC; the delegation of each domain, with glue for the name servers inside it, is made at its parent zone by hand. Every -domain has the same two name servers. +domain has the same name servers, the primary alone without a secondary, which is not the redundancy +the DNS asks of public zones. ## ADR-43: The remote access clients' resolver is dnsmasq, not systemd-resolved @@ -1525,7 +1539,7 @@ system against a stored light or dark choice. Consequences: A page in the dark theme is dark from its first paint. The script depends on the storage key and class names of MUI's defaults, which `colorSchemeSelector: 'class'` uses. -## ADR-56: One package, linux-manager, installs every component +## ADR-56: One package, linux-manager, with the software of its components installed on demand Status: Accepted @@ -1536,8 +1550,9 @@ creates its first administrator, Caddy proxies it and the status reports it. Pac own would pin each other's versions, and a change of the server's API would need several repositories and changelogs. -Decision: One package, `linux-manager`, installs every component, the Manager included. The -router and the VPN are switched on in the configuration (ADR-57), not by installing packages. The +Decision: One package, `linux-manager`, holds every component, the Manager included. The software +the installable components need, the VPN, the router, the name server and WebDAV, is installed from +the Ubuntu archive when the component is switched on (ADR-57), and the package only suggests it. The programs are in `/usr/lib/linux-manager`, the Manager's application and help in `/usr/share/linux-manager/manager`, the settings and secrets in `/etc/linux-manager` (`linux-manager.json`, `manager.json`, `manager-database.secret`, `manager-admin.json`) and the @@ -1548,37 +1563,49 @@ Manager, which has no bootstrap service of its own. `dev.sh` runs the Manager on with `terraform_dir` and `bind`. Consequences: The repository holds the Manager's `web/` and `docs/`, and its build runs from the -root. A server that runs neither the router nor the VPN still has their programs and -dependencies installed. +root. A server has the programs of the components it has switched on, and keeps them when a +component is switched off. -## ADR-57: The router and the VPN are components switched in the configuration +## ADR-57: The installable components are switched on the System tab and installed on demand Status: Accepted Context: The server is used without its routing and VPN features, as a directory, PKI and web server on one network interface. Routing between two interfaces and site-to-site IPsec need two -interfaces; remote access needs only one, if its clients reach the server's networks from the -server's own address. +interfaces; remote access works with one or two, its clients reaching the server's networks from +the server's own address with one. A component needs its software installed and its setup run, so +switching one only in the configuration file left the Manager unable to reach it. -Decision: `router.enabled` and `vpn.enabled`, both false by default, switch the two components. -With the router off, `site_to_site` must be empty, only `interfaces.external` is used, and it is -also the internal side of the services' `listen` choices; no route, forward rule or `rp_filter` -setting is written. With the VPN off, `p2s.enabled`, `openvpn.enabled` and `wireguard.enabled` -must be false, users get no VPN certificate, WireGuard peers and VPN profiles are refused, and the -Manager hides the Remote Access page. With the router off and the VPN on, setup masquerades each -ready VPN pool out of the external interface, so the clients reach `local.cidrs` from the -server's address. `linux-manager-setup` writes `/etc/sysctl.d/99-linux-manager.conf` while -either component is on: forwarding for both, a loose `rp_filter` for the router; it removes the -file while both are off and leaves the running values alone, as Docker also needs forwarding. The -built-in issuing CAs follow their component: `p2s` the VPN and `s2s` the router; they are created -when their component is first switched on and kept when it is switched off. Switching the VPN on -issues a certificate to each VPN user that has none. The firewall is written once any core -listener (web, HTTPS, metrics, DNS, sites) or component is configured; the IPsec rules only while -site-to-site or IKEv2 is ready. +Decision: The installable components are the VPN (`vpn.enabled`), the router (`router.enabled`), +the name server (`dns.enabled`) and WebDAV (`sites.webdav`), listed with their packages in +`linuxmanager.COMPONENTS`; all are off by default. The Manager's System tab switches them through +`PUT /components/`, and shows whether their packages are installed, being installed or failed +(`GET /components`). While a component is on and any of its packages is missing, or marked as +installed automatically, which `apt autoremove` would remove, setup starts +`linux-manager-install@`, whose `apt-get install` marks them as installed by hand and +runs setup again; until then the component's readiness checks are false. Switching a component off +removes no package. The router is offered only while the server has a network interface besides +the external one, and switching it on takes the internal interface and, in `manual` mode, its +address and gateway, as the installer asks them. With the router off, `site_to_site` must be empty, +only `interfaces.external` is used, and it is also the internal side of the services' `listen` +choices; no route, forward rule or `rp_filter` setting is written. With the VPN off, +`p2s.enabled`, `openvpn.enabled` and `wireguard.enabled` must be false, users get no VPN +certificate, WireGuard peers and VPN profiles are refused, and the Manager hides the Remote Access +page. With the router off and the VPN on, setup masquerades each ready VPN pool out of the external +interface, so the clients reach `local.cidrs` from the server's address. `linux-manager-setup` +writes `/etc/sysctl.d/99-linux-manager.conf` while the router or the VPN is on: forwarding for +both, a loose `rp_filter` for the router; it removes the file while both are off and leaves the +running values alone, as Docker also needs forwarding. The built-in issuing CAs follow their +component: `p2s` the VPN and `s2s` the router; they are created when their component is first +switched on and kept when it is switched off. Switching the VPN on issues a certificate to each VPN +user that has none. The firewall is written once any core listener (web, HTTPS, metrics, DNS, +sites) or component is configured; the IPsec rules only while site-to-site or IKEv2 is ready. -Consequences: A core-only server needs one interface and gets its firewall at its first setup -run. The readiness checks (`routing_ready`, `s2s_ready`, `p2s_ready`, `wg_ready`, -`openvpn_ready`) carry the switches, so every consumer of them follows the components. +Consequences: A core-only server needs one interface, has none of the components' software, and +gets its firewall at its first setup run. A component switched on is served once its packages are +installed, a minute or so later. The readiness checks (`routing_ready`, `s2s_ready`, `p2s_ready`, +`wg_ready`, `openvpn_ready`) carry the switches and the installation, so every consumer of them +follows the components. ## ADR-58: Manual tests get numbered dev builds from a signed apt repository in a test project @@ -1597,8 +1624,10 @@ inside a project; they belong to the project and go with it. `bin/lm-dev-build.p changelog entry as `~dev-`, `N` counted in `.dev-build.serial`, which a release sets to 0, by passing `DEB_VERSION` to the build, which rewrites the version in the image only, and publishes the build in that repository. `bin/lm-dev-vm.py` gives a VM of the project -that repository as its apt source. The automated tests (`lm-dev-run.py`) keep their own project -for one run and install from a file. +that repository as its apt source. The project also has a Vault, through which secrets reach its +instances (ADR-61). The scripts keep their state in `.lm-dev-config/`, which outlives clean-ups of +`tmp/`. The automated tests (`lm-dev-run.py`) keep their own project for one run and install from a +file. Consequences: Every dev build is an apt update of the one before, and the release of the entry, which sorts above all of its `~dev` builds, is an update of them all. The changelog is not @@ -1633,3 +1662,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 a new setup code renews the token. The server cannot revoke a retired issuing CA in Simple CA; its notice says to. Clients see a chain one CA longer than with the other sources. + +## ADR-60: A certificate of the server other than ACME's is kept in the directory, with a self-signed fallback + +Status: Accepted + +Context: A server whose certificate comes from no ACME CA needs one made by the server, one of its +own PKI, or one of another CA, given as a certificate signed for a CSR or as a PFX file with its +key. Caddy takes a certificate file and its key per site. The server's other certificates and +keys are in its directory (ADR-32), which every backup holds. + +Decision: `https.certificate` is `acme`, `self-signed`, `ca` or `external`. With `ca` the +certificate is a router certificate of the built-in Servers Issuing CA, `servers`, with the template +`mtls`, issued and renewed as the VPN server's is. A self-signed or imported certificate, with its +chain and key, a pending CSR and that CSR's key, are the entry `cn=https,ou=pki`, of the class +`linuxManagerHostCertificate`; the keys are unreadable to every account but root's socket. An +import must be for the CSR's key, or the PFX's own, be valid and name `wan.local_fqdn`, directly or +with a wildcard. While the chosen certificate is not available, such as before an import or while +`servers` waits for an offline root, the server makes a self-signed certificate and serves it, with a +warning, so that no ACME CA is asked unasked. Setup writes the served certificate and key to +`/etc/caddy/linux-manager-https/`, group `caddy`, and the server's site blocks name them; when +they cannot be read, the Caddyfile is left as it is. + +`https.certificate` is `self-signed` when the configuration does not set it, as in most +appliances, and ACME is used only when it is set to `acme`: a public name that resolves to the +server and port 80 reachable from the internet are rarely ready when a server is installed. The +file a new installation writes has it empty, and that installation's first setup chooses it and +writes it into the file: `ca` when the Servers Issuing CA has its certificate after the PKI is +provisioned, as with a root the server creates, else `self-signed`. 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//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//*` and +creates the TOTP keys `totp/keys/-*`, 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. diff --git a/Dockerfile b/Dockerfile index c8ec3f8..ff9d8a3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,8 +12,8 @@ FROM ubuntu:${UBUNTU_VERSION} ARG HOST_UID ARG HOST_GID -RUN apt-get update \ - && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ +RUN apt-get -o Acquire::Retries=5 update \ + && DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 install -y --no-install-recommends \ build-essential \ dpkg-dev \ debhelper \ diff --git a/README.md b/README.md index 405a00a..1128b96 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,11 @@ # linux-manager 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 -(`vpn.enabled`) are switched on in the configuration, and the rest is the core. Without the -router the server needs one network interface, and the VPN clients reach the server's networks +Ubuntu Linux Manager. The core is always installed; the installable components, the VPN +(`vpn.enabled`), the router (`router.enabled`), the name server (`dns.enabled`) and WebDAV +(`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: - 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 -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 @@ -51,7 +53,7 @@ host that already runs Docker, and for installing Docker later, are under [Docke ```sh apt-get install linux-manager # answer "none" to the platform question $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 @@ -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_gateway_ip string 10.1.1.1 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/remote_addrs 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` | `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 | -| `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 | +| `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, 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` | `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 | @@ -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` | `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` | `listen` | string | `both` | The interfaces the status web service listens on: `internal`, `external` or `both` | -| `web` | `port` | integer | `7081` | TCP port of the status web service | +| `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, 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` | `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` | `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 | @@ -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 | | `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` | `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` | `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` | `caddy_source` | string | `ubuntu` | Where Caddy is installed from: `ubuntu`, the Ubuntu archive, or `upstream`, Caddy's own repository (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` | `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) | | `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` | `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 | | `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` | `ttl` | integer | `300` | The default TTL of the records, 60 to 86400 seconds: used where neither the record nor its domain has one | | `pki` | `root` | string | `local` | Where the root CA comes from: `local`, `offline` or `simple-ca`; fixed once the root exists (see Certificates) | | `pki` | `simple_ca_url` | string | | The `https://` URL of the Simple CA service, with `root` `simple-ca` | -| `pki` | `root_name` | string | `Linux Manager Root CA` | Common name of the root CA, when the server creates it | +| `pki` | `root_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` | `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` | `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` | `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` | `s2s_name` | string | `Linux Manager Site-to-Site CA` | Common name of the site-to-site 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; 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` | `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) | | `metrics` | `enabled` | boolean | `true` | The metrics service: collection, history and `/metrics` | -| `metrics` | `listen` | string | `internal` | The interfaces `/metrics` is served on: `internal`, `external` or `both` | -| `metrics` | `port` | integer | `9464` | TCP port of `/metrics` | +| `metrics` | `listen` | string | `internal` | The interfaces the firewall opens `metrics.port` on: `internal`, `external` or `both` | +| `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` | `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` | @@ -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, every published port that is not listed is unreachable from the external interface, and 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. 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 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. 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 remove site_to_site.branch 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 @@ -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 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` -and `remove` restart `linux-manager-setup` and wait until it has applied the change, and exit with -status 1 when it fails. The status web service +and `remove` have `linux-manager-setup` run and wait until it has applied the change, and exit with +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 refused request exits with status 2, any other failure with 1. ## Bash completion 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 `/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 @@ -396,10 +409,45 @@ linux-manager-config-edit set oidc. linux-manager-user passwd ``` +## 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@.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/` 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 ```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. @@ -411,7 +459,13 @@ access is configured. It then starts `strongswan`, `wg-quick@wg0` and restarting them only when their inputs changed, and 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 -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 anything: @@ -423,7 +477,7 @@ anything: 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 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 @@ -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 this CA only. - `s2s`, named `pki.s2s_name`, signs the server's site-to-site certificate and the certificates - of its peers. -- The general-purpose CAs of `pki.issuing_cas`, each a name and `{"name": common name, - "templates": [...], "acme": false}`. The name starts with a lowercase letter, has at most 31 - lowercase letters, digits and hyphens, and is not `root`, `p2s` or `s2s`; `templates` are the - templates the CA issues. + of its peers, with the template `mtls`. +- `servers`, the Servers Issuing CA, named `pki.servers_name`, signs mTLS certificates, with both the + server and the client purposes, and the server's HTTPS certificate while `https.certificate` + is `ca`. +- 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` 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-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` | -| `server` | digital signature, key encipherment | server auth | `dns` | `dns`, `ip` | general-purpose CAs | -| `client` | digital signature | client auth | `name` | `dns`, `email` | general-purpose CAs | +| `mtls` | digital signature, key encipherment | server auth, client auth | `dns` | `dns`, `ip` | `s2s`, `servers` | +| `server` | digital signature, key encipherment | server auth | `dns` | `dns`, `ip` | custom 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 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 ``` +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 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 -The `linux-manager-web` service shows the state of the server on the addresses of the interfaces -`web.listen` names, the internal, the external or both (the default), and on `127.0.0.1`, where -Caddy calls it (see HTTPS), with `web.port` (7081 by default). Its pages `/` and `/status` need no authentication and show no +The `linux-manager-web` service shows the state of the server. It listens on `127.0.0.1:7091` +only, behind Caddy, which serves it over plain HTTP on `web.port` (7081 by default), open in the +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 `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 | 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 -behind Caddy or a Ubuntu Linux Manager on the server it is the browser's. `/status` names the content in +request from one of `web.trusted_proxies`, by default `127.0.0.1`, where Caddy and the +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`. 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 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 -default the address the call came in on, the client address is the last entry of -`X-Forwarded-For`. +default `127.0.0.1`, where Caddy and the Manager call from, the client address is the last entry +of `X-Forwarded-For`. 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 @@ -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`. -### The /https/settings API +### The /https API -`/https/settings` shows the settings of HTTPS and changes the CA of Caddy's certificates, with the -same token as `/users`. +`/https` shows the settings of HTTPS and the server's certificate, changes where the certificate +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 `_set`. | Request | Body | Answer | | --- | --- | --- | -| `GET /https/settings` | | `{"settings"}`: the `https` section | -| `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"}` | +| `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` | 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 @@ -1508,7 +1575,7 @@ The answer of `GET /ca` holds: - **`settings`:** the `pki` section. - **`templates`:** every template, the built-in ones included, with all its options. - **`extended_key_usages`:** every extended key usage templates may give, name -> `{"oid", "builtin"}`. -- **`status`:** `root` (`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`. 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 -Caddy serves the status web service on `https.web_port` (7444 by -default), the Manager on `https.manager_port` (7443), and -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 -and renews the certificate from Let's Encrypt with the HTTP challenge, so `wan.local_fqdn` must -resolve to the server's public address and port 80 must be reachable from the internet; the -certificate and the ACME account are kept in `/var/lib/caddy`. Port 80 answers the challenge only; -it does not redirect to HTTPS. Caddy's default CAs are Let's Encrypt and ZeroSSL, which it takes -when Let's Encrypt refuses, such as for its rate limit of 5 certificates a week for the same name. +Caddy, a dependency of the package, serves every HTTP and HTTPS port of the server's services; the +services listen on `127.0.0.1` only. Over plain HTTP it serves the status web service on +`web.port` (7081 by default), the Manager on its `port` (7080), and while metrics are enabled the +metrics service on `metrics.port` (9464). While `https.enabled` is `true` and `wan.local_fqdn` is +set, it also serves the status web service on `https.web_port` (7444), the Manager on +`https.manager_port` (7443), and while metrics are enabled the metrics service on +`metrics.https_port` (9465), all for `wan.local_fqdn`. -While `https.acme_staging` is `true`, Caddy's only CA is Let's Encrypt's staging environment, for -routers that are rebuilt often. Its rate limits are far higher, but no browser or client trusts -its certificates, so they are for tests only. The setting applies to every certificate Caddy -obtains from an ACME CA, those of the web sites with `tls` `acme` included. +The installer asks whether to serve over HTTPS (`https_enabled`) and, with HTTPS, whether to keep +the Manager on plain HTTP (`https_disable_auto_redirect`). While HTTPS is on, Caddy answers the +Manager's plain HTTP port with a redirect (308) to the same path at +`https://:`, 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 -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 -/https/settings API). +An imported certificate must be valid and name `wan.local_fqdn`, directly or with a wildcard, and +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 -`caddy`, the group Caddy runs as, mode 0640), which the -package's drop-in `/usr/lib/systemd/system/caddy.service.d/linux-manager.conf` makes `caddy.service` -read; `caddy.service` does not start before the file exists, and `/etc/caddy/Caddyfile` is not -used. Setup starts Caddy, reloads it when the file changes, and stops it and removes the file when -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 -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 -whatever `web.listen` and the manager's `listen` say, and passes the client's address in -`X-Forwarded-For`, which the manager trusts from `127.0.0.1` and the web service by default, as -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 -`web.listen` and the manager's `listen` set them. `docker.exposed_ports` may not take port 80 or -the HTTPS ports while `https.enabled` is `true`. +`caddy`, the group Caddy runs as, mode 0640), which the package's drop-in +`/usr/lib/systemd/system/caddy.service.d/linux-manager.conf` makes `caddy.service` read; +`caddy.service` does not start before the file exists, and `/etc/caddy/Caddyfile` is not used. +Setup starts Caddy once the server is configured (`general.platform` other than `none`) and +reloads it when the file changes. + +Caddy listens on every address, and the firewall decides who reaches it: `web.port` is open on the +interfaces `web.listen` names, the Manager's port on those of its `listen`, and `metrics.port` on +those of `metrics.listen`, where `internal` is the external interface without the router. Port +80 is open on the external interface while ACME needs it, the HTTPS ports on the 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 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 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, -from the source `https.caddy_source` names: - -- `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=`, the version `apt-cache policy caddy` -lists for the archive. +Caddy is a dependency of the package, the `caddy` package of the Ubuntu archive, installed with +`linux-manager` and kept up to date with the system's packages. ## 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 | | `port` | The TCP port, 443 by default | | `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 | | `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 | @@ -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` | 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 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 @@ -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 the hosts; it is written to `/etc/caddy/linux-manager-sites/` (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`; -its certificates are trusted by clients that trust the server's root. Caddy runs while HTTPS is -ready or a site is served; while the sites cannot be read, setup leaves the Caddyfile as it is. +its certificates are trusted by clients that trust the server's root. While the sites cannot be +read, setup leaves the Caddyfile as it is. ```sh 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 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 -later. rclone is installed from the Ubuntu archive by `linux-manager-install@webdav.service` when it is -missing. +later. WebDAV is a component (see Components): rclone is installed from the Ubuntu archive by +`linux-manager-install@webdav.service` while `sites.webdav` is true and rclone is missing. ```sh 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 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 -`/etc/powerdns/pdns.d/linux-manager.conf` (root, group `pdns`, 0640) and installs `pdns-server` and -`pdns-backend-pgsql` from the Ubuntu archive with `linux-manager-install@dns.service` when they are -missing, without the recommended bind backend. +`/etc/powerdns/pdns.d/linux-manager.conf` (root, group `pdns`, 0640). The name server is a component +(see Components): `pdns-server` and `pdns-backend-pgsql` are installed from the Ubuntu archive with +`linux-manager-install@dns.service` while `dns.enabled` is true and they are missing, without the +recommended bind backend. | 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 `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 -glue records for those of them inside the domain. While `dns.secondary` is not set, the domains have -`wan.local_fqdn` as their only name server, and setup warns. +glue records for those of them inside the domain. The secondary is optional: while `dns.secondary` +is not set, the domains have `wan.local_fqdn` as their only name server. ```sh 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 chmod 0600 /etc/linux-manager/rclone.conf 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: @@ -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 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 -(`/ca-manager`), Web Sites (`/sites-manager`: the Sites, Files and DNS tabs) and -Docker (`/docker-manager`) with the page menu at the +(`/ca-manager`), Web Sites (`/sites-manager`: the Sites and Files tabs), DNS (`/dns-manager`, while the name +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 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. @@ -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 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. - **Templates:** the certificate templates with their key, lifetime, subject, usages, alternative names, certificate policies and the CAs that issue them; Add template, Edit on each, Remove on one of the server's own and Reset on a changed built-in one, which brings back its defaults. A template's extended key usages are chosen from those of the next tab, and its certificate policies are OIDs typed in. - **Extended key usages:** the usages templates may give, with their OIDs and the templates that give them; the built-in ones are shown and not changed, and custom ones are added with a name and an OID, and changed or removed. - - **P2S Issuing CA** and **S2S Issuing CA:** the CA's common name, state (active, or pending while it waits for the offline root), expiry, CRL and templates, and the certificates it issued. An active CA gives its CA bundle, the issuing CA followed by the root, with Download CA bundle; a pending CA gives its CSR with the openssl extensions to sign it with, and takes the certificate signed by the root. - - **Issuing CAs:** the general-purpose CAs with their state, expiry, CRL, templates and ACME directory URL; Add issuing CA, and Edit and Remove on each: its name, fixed once it exists, its common name, the templates it issues and its ACME server; an active CA's download icon gives its CA bundle. A removed CA is retired by the server, which revokes its certificate on the root CRL. Below, their certificates, filtered by CA. - **Certificates:** each with its kind, template, names, expiry and state; a certificate of another system or of the server is revoked after a confirmation with a reason. - - **Issue** (above the tabs): from a CSR, saving the certificate with its chain, or with a key the server makes, saving a PFX file protected by a password; the server keeps no copy of the key. - - **Settings** (above the tabs): the source of the root, shown, the Simple CA URL, the names, lifetimes, key type, CRL validity and publishing endpoints. + - **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. + - **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. + - **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. - **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; 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 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 show each PostgreSQL cluster of the 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:** 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 - 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, 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 @@ -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 instead. New folder, Rename, Remove and Download. A file larger than the server's largest upload is not sent. - - **DNS:** the server's primary name server: its settings with whether PowerDNS is installed - and runs, the server's FQDN as the primary name server, edited with Settings (enabled, - secondary name server, public IP address, interfaces, TTL); the domains, added with Add - domain (domain, TTL), edited and removed with their icons; and for the selected domain the - records it serves, and its manual records, added with Add record (name, type, content and - TTL) and removed with their icon. +- **DNS** (`/dns-manager`, in the page menu while the name server is on): the server's primary + name server: its settings with whether PowerDNS is installed and runs, the server's FQDN as the + primary name server, edited with Settings (optional secondary name server, public IP address, + interfaces, TTL; the name server is switched on the System tab); the domains, added with Add + domain (domain, TTL), edited and removed with their icons; and for the selected domain the + records it serves, and its manual records, added with Add record (name, type, content and TTL) + and removed with their icon. - **Docker** (`/docker-manager`): the state of `docker.service` and of the server's Docker rules, the ports exposed on the external interface and the rules of the `LINUX-MANAGER-DOCKER` chain, from the server's `/status/full` and `/config`. The page menu leaves the page out while @@ -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. 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 @@ -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 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. -- `/api/info` gives the version of the package and the URL of the server's status page, without a - session. On the server, while `router_url` and `terraform_dir` are not set and the status web - service listens on the address the call came in on, the URL has the name or address the browser - used and `web.port`, for example `http://router.example.com:7081`, and for a page opened over +- `/api/info` gives the URL of the server's status page and `manager`, the `port` and `listen` of + the manager's plain HTTP site, without a session, and the version of the package only with one, + so the sign-in page shows no version. On the server, while `router_url` and `terraform_dir` are not set and the status web + 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 `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` @@ -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` | 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 -on, which is the address a manager on the server calls from, so it needs nothing more. +in the server's `web.trusted_proxies`; by default that is `127.0.0.1`, which is the address a +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 -`linux-manager.json` (7443 by default) for `wan.local_fqdn`, with a certificate from Let's Encrypt, -and calls it on `127.0.0.1`, where the manager also listens. 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. +On the server, the manager listens on `127.0.0.1:7090` only. The server's Caddy serves it over +plain HTTP on `port` (7080 by default), open in the firewall on the interfaces `listen` names, or +redirects there to its HTTPS address while HTTPS is on (see HTTPS), and over HTTPS on +`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 -listen and starts, moves or stops a server on each address to match, so a change of `listen`, -`bind` or `port` takes effect within 30 seconds, or when the service restarts. Each request +listen and starts, moves or stops a server on each address to match, so a change of `bind` or +`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. Before it listens, it creates its sessions database on the server when it is missing and connects @@ -2433,11 +2540,11 @@ PostgreSQL is not running yet. | Setting | Meaning | Default | |---------|---------|---------| -| `router_url` | The server's status web service | `http://:`, 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 | -| `listen` | The interfaces to listen on when `bind` is not set: `internal`, `external` or `both`, and always `127.0.0.1` | `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 | -| `port` | The port to listen on, HTTP | `7080` | +| `listen` | On the server, the interfaces the firewall opens `port` on: `internal`, `external` or `both` | `both` | +| `bind` | The one address to listen on, with `port`, off the server, as `dev.sh` sets it | none; on the server `127.0.0.1:7090` | +| `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 | | `iac_tool` | The tool that reads the outputs of `terraform_dir`: `terraform` or `tofu` | `terraform` | diff --git a/bin/lm-dev-build.py b/bin/lm-dev-build.py index 0a635e9..f8baa8c 100755 --- a/bin/lm-dev-build.py +++ b/bin/lm-dev-build.py @@ -8,7 +8,7 @@ is the newest changelog entry's with ~devN before its Debian revision, 0.41.0-1 with CONTAINER_RUNTIME and DOCKER_CONTEXT from the environment; the build is moved to out/dev/, copied into the repository container of the project --project (LXD_PROJECT, lm-dev by default) made by lm-dev-lxd-project.py, and published there. The remote is the project's, read from -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 @@ -18,7 +18,7 @@ import re import subprocess import sys -from lm_dev import PROJECT, ROOT, lxc_exec +from lm_dev import PROJECT, ROOT, config_path, lxc_exec SERIAL = ROOT / '.dev-build.serial' CHANGELOG = ROOT / 'debian-package' / 'debian' / 'changelog' @@ -30,7 +30,7 @@ def main(): help=f'the test project made by lm-dev-lxd-project.py, whose remote is used (LXD_PROJECT, ' f'default {PROJECT})') args = parser.parse_args() - state_file = ROOT / 'tmp' / f'lxd-project-{args.project}.json' + state_file = config_path(f'lxd-project-{args.project}.json') if not state_file.is_file(): sys.exit(f'no {state_file}; create the project with lm-dev-lxd-project.py create') state = json.loads(state_file.read_text(encoding='utf-8')) diff --git a/bin/lm-dev-lxd-project.py b/bin/lm-dev-lxd-project.py index b22feb5..0d6209a 100755 --- a/bin/lm-dev-lxd-project.py +++ b/bin/lm-dev-lxd-project.py @@ -1,17 +1,22 @@ #!/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 -(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, lm-dev by default) with its root disks on --pool (LXD_POOL) and networks of its own, OVN networks on the uplink --uplink (LXD_UPLINK, uplink by default): wan, with NAT and DHCP on a subnet LXD picks, and lana and lanb, on subnets LXD picks without DHCP. The project's default profile puts eth0 on wan. The container repo serves a signed apt repository of the dev builds over HTTP; -lm-dev-build.py publishes into it and lm-dev-vm.py installs from it. What they need is written to -tmp/lxd-project-PROJECT.json, with the repository's key in tmp/lxd-project-PROJECT.gpg. remove -deletes the project's instances, its networks, the project and those files. +lm-dev-build.py publishes into it and lm-dev-vm.py installs from it. The container vault is the +project's Vault, made first, which the scripts hand secrets to the instances through; every other +instance gets an AppRole of its own in it and /etc/vault (lm_dev.enrol_instance). What they need is written +to .lm-dev-config/lxd-project-PROJECT.json, with the repository's key in +.lm-dev-config/lxd-project-PROJECT.gpg. remove deletes the project's instances, its networks, the +project and those files. """ import argparse @@ -22,7 +27,8 @@ import subprocess import sys import time -from lm_dev import PROJECT, ROOT, TESTS, lxc_exec +from lm_dev import PROJECT, TESTS, VAULT_PORT, VaultError, config_path, enrol_instance, lxc_exec, vault_initialise, \ + vault_state, vault_unseal NETWORKS = ('wan', 'lana', 'lanb') @@ -33,8 +39,84 @@ def lxc(*args, project, check=True, input=None): check=check) +def launch(args, name, user_data): + """Launch the container with the cloud-init user data on the project's default profile, wait until it has booted + and has an address on eth0, and pin that address; the address.""" + lxc('launch', args.image, f'{args.remote}:{name}', + '-c', 'cloud-init.user-data=' + (TESTS / 'cloud-init' / user_data).read_text(encoding='utf-8'), + project=args.project) + # cloud-init's status 2 is done with recoverable errors. + for _ in range(120): + if lxc_exec(args.remote, args.project, name, 'cloud-init', 'status', '--wait').returncode in (0, 2): + break + time.sleep(5) + else: + raise RuntimeError(f'the container {name} did not boot') + for _ in range(24): + match = re.search(r' inet (\d+\.\d+\.\d+\.\d+)/', + lxc_exec(args.remote, args.project, name, 'ip', '-4', '-o', 'addr', 'show', 'dev', + 'eth0').stdout) + if match: + break + time.sleep(5) + else: + raise RuntimeError(f'the container {name} has no address on eth0') + lxc('config', 'device', 'override', f'{args.remote}:{name}', 'eth0', f'ipv4.address={match.group(1)}', + project=args.project) + return match.group(1) + + +def vault_forward(args): + """The listen address of the forward of the project's Vault on wan, or None.""" + listing = lxc('network', 'forward', 'list', f'{args.remote}:wan', '-f', 'json', project=args.project, + check=False) + if listing.returncode != 0: + return None + return next((forward['listen_address'] for forward in json.loads(listing.stdout) or [] + if forward.get('config', {}).get('user.service') == 'vault'), None) + + +def vault_create(args): + """Make the project's Vault: the container vault (cloud-init vault.yaml), a forward of its port on wan at + --vault-address or an allocated one, which the scripts reach it on, and its initialisation with one key share, + unsealed, with KV v2, TOTP and AppRole; its key and root token are kept in .lm-dev-config/vault-PROJECT.json; + the state.""" + if vault_state(args.project) is not None: + raise RuntimeError(f'project {args.project} has a Vault; remove it with vault remove first') + print(f'launching the Vault container {args.remote}:vault (project {args.project})') + address = launch(args, 'vault', 'vault.yaml') + listen = [args.vault_address] if args.vault_address else ['--allocate=ipv4'] + lxc('network', 'forward', 'create', f'{args.remote}:wan', *listen, 'user.service=vault', project=args.project) + forward = vault_forward(args) + if not forward: + raise RuntimeError('the forward of the Vault was not made') + lxc('network', 'forward', 'port', 'add', f'{args.remote}:wan', forward, 'tcp', str(VAULT_PORT), address, + str(VAULT_PORT), project=args.project) + state = vault_initialise(args.project, f'http://{forward}:{VAULT_PORT}', f'http://{address}:{VAULT_PORT}') + print(f'the Vault of {args.project} is at {state["url"]}, for the instances {state["internal_url"]}; ' + f'state: {config_path(f"vault-{args.project}.json")}') + return state + + +def vault_remove(args): + """Delete the project's Vault, its forward and its state; True when all went.""" + ok = True + if lxc('info', f'{args.remote}:vault', project=args.project, check=False).returncode == 0: + result = lxc('delete', '--force', f'{args.remote}:vault', project=args.project, check=False) + if result.returncode != 0: + ok = False + print(f'could not delete vault: {result.stderr.strip()}', file=sys.stderr) + forward = vault_forward(args) + if forward: + lxc('network', 'forward', 'delete', f'{args.remote}:wan', forward, project=args.project, check=False) + if ok: + config_path(f'vault-{args.project}.json').unlink(missing_ok=True) + print(f'project {args.project} has no Vault') + return ok + + def create(args, state, key): - """Create the project with its networks and default profile, 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, '-c', 'features.images=false', '-c', 'features.networks=true'], capture_output=True, text=True, check=True) @@ -49,33 +131,16 @@ def create(args, state, key): lxc('profile', 'device', 'add', f'{args.remote}:default', 'eth0', 'nic', 'network=wan', 'name=eth0', project=args.project) + vault = vault_create(args) print(f'launching the repository container {args.remote}:repo (project {args.project})') - lxc('launch', args.image, f'{args.remote}:repo', - '-c', 'cloud-init.user-data=' + (TESTS / 'cloud-init' / 'repo.yaml').read_text(encoding='utf-8'), - project=args.project) + address = launch(args, 'repo', 'repo.yaml') + problem = enrol_instance(args.remote, args.project, 'repo', vault) + if problem: + raise RuntimeError(problem) def inside(*command): return lxc_exec(args.remote, args.project, 'repo', *command) - # 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. generate = ('gpg', '--batch', '--pinentry-mode', 'loopback', '--passphrase', '', '--quick-generate-key', 'Linux Manager test repository', 'default', 'default', 'never') @@ -94,6 +159,7 @@ def create(args, state, key): state.write_text(json.dumps({'remote': args.remote, 'project': args.project, 'networks': list(NETWORKS), 'repository': f'http://{address}/', 'key': str(key)}, indent=2) + '\n', encoding='utf-8') + state.chmod(0o600) print(f'project {args.project} is ready on {args.remote}: networks {", ".join(NETWORKS)}, ' f'repository http://{address}/') print(f'state: {state}') @@ -125,6 +191,7 @@ def remove(args, state, key): if ok: state.unlink(missing_ok=True) key.unlink(missing_ok=True) + config_path(f'vault-{args.project}.json').unlink(missing_ok=True) print(f'removed project {args.project} and its networks from {args.remote}') return ok @@ -163,8 +230,9 @@ def uplink(args): def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument('action', choices=('create', 'remove', 'uplink')) - parser.add_argument('operation', nargs='?', choices=('setup', 'remove'), help='after uplink: setup or remove') + parser.add_argument('action', choices=('create', 'remove', 'vault', 'uplink')) + parser.add_argument('operation', nargs='?', choices=('setup', 'create', 'unseal', 'remove'), + help='after vault: create, unseal or remove; after uplink: setup or remove') parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)') parser.add_argument('--pool', default=os.environ.get('LXD_POOL'), help='the storage pool of the project, for create (LXD_POOL)') @@ -172,6 +240,9 @@ def main(): help=f'the project (LXD_PROJECT, default {PROJECT})') parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'), help='the image of the repository container (LXD_IMAGE, default ubuntu:26.04)') + parser.add_argument('--vault-address', default=os.environ.get('LXD_VAULT_ADDRESS'), + 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=os.environ.get('LXD_UPLINK', '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'), @@ -187,8 +258,9 @@ def main(): args = parser.parse_args() if not args.remote: parser.error('--remote or LXD_REMOTE is required') - if (args.action == 'uplink') != (args.operation is not None): - parser.error('setup or remove follows uplink, and only uplink') + operations = {'uplink': ('setup', 'remove'), 'vault': ('create', 'unseal', 'remove')} + if args.operation not in operations.get(args.action, (None,)): + parser.error('setup or remove follows uplink, create, unseal or remove follows vault, and nothing else') if args.action == 'uplink': try: @@ -196,8 +268,26 @@ def main(): except subprocess.CalledProcessError as error: sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}') return - state = ROOT / 'tmp' / f'lxd-project-{args.project}.json' - key = ROOT / 'tmp' / f'lxd-project-{args.project}.gpg' + state = config_path(f'lxd-project-{args.project}.json') + key = config_path(f'lxd-project-{args.project}.gpg') + + if args.action == 'vault': + try: + if args.operation == 'create': + vault_create(args) + elif args.operation == 'unseal': + current = vault_state(args.project) + if current is None: + sys.exit(f'project {args.project} has no Vault') + vault_unseal(current) + print(f'the Vault of {args.project} is unsealed') + elif not vault_remove(args): + sys.exit(1) + except subprocess.CalledProcessError as error: + sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}') + except (RuntimeError, VaultError) as error: + sys.exit(str(error)) + return if args.action == 'remove': sys.exit(0 if remove(args, state, key) else 1) @@ -212,7 +302,7 @@ def main(): except subprocess.CalledProcessError as error: sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}\n' f'remove what was made with: {sys.argv[0]} remove --remote {args.remote} --project {args.project}') - except RuntimeError as error: + except (RuntimeError, VaultError) as error: sys.exit(f'{error}\nremove what was made with: {sys.argv[0]} remove --remote {args.remote} ' f'--project {args.project}') diff --git a/bin/lm-dev-otp-code.py b/bin/lm-dev-otp-code.py new file mode 100755 index 0000000..22b6272 --- /dev/null +++ b/bin/lm-dev-otp-code.py @@ -0,0 +1,30 @@ +#!/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 - 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 os +import sys + +from lm_dev import PROJECT, VaultError, otp_code + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT), + help=f'the project of the VM (LXD_PROJECT, default {PROJECT})') + parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)') + parser.add_argument('--user', default='admin', help='the user (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() diff --git a/bin/lm-dev-otp-register.py b/bin/lm-dev-otp-register.py index 15183e3..7c390e8 100755 --- a/bin/lm-dev-otp-register.py +++ b/bin/lm-dev-otp-register.py @@ -2,26 +2,17 @@ """Register a TOTP token for a user of a Linux Manager VM on an LXD remote: lm-dev-otp-register.py. The token is enrolled for --user (admin by default) of the VM --vm (lm-dev) in the project --project -(LXD_PROJECT, lm-dev by default) on the remote --remote (LXD_REMOTE), through lxc exec: inside the -VM, as root, linuxmanager_users makes a new secret, and stores it once a code computed here from it -verifies, replacing a token the user had. The secret, base32, is then written to the file ---secret-file or OTP_FILE names, readable by its owner only, so otp.py code prints the user's codes. +(LXD_PROJECT, lm-dev by default) on the remote --remote (LXD_REMOTE): the project's Vault generates +the key in its TOTP engine as - and hands it to the VM, where linuxmanager_users stores +it with its current code, replacing a token the user had. The secret stays in the Vault and the +VM; lm-dev-otp-code.py prints the user's codes. """ import argparse -import json import os -import pathlib import sys -from lm_dev import PROJECT, lxc_exec -from otp import code_of - -# Run in the VM as python3 -c CODE ARGUMENTS..., with the package's modules on the path. -NEW = ("import json, sys; sys.path.insert(0, '/usr/lib/linux-manager'); import linuxmanager_users as users\n" - "with users.session() as connection: print(json.dumps(users.otp_new(connection, sys.argv[1])))") -ENROL = ("import sys; sys.path.insert(0, '/usr/lib/linux-manager'); import linuxmanager_users as users\n" - "with users.session() as connection: users.otp_enrol(connection, sys.argv[1], sys.argv[2], sys.argv[3])") +from lm_dev import PROJECT, enrol_otp, totp_key def main(): @@ -31,31 +22,14 @@ def main(): help=f'the project of the VM (LXD_PROJECT, default {PROJECT})') parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)') parser.add_argument('--user', default='admin', help='the user to enrol (default admin)') - parser.add_argument('--secret-file', default=os.environ.get('OTP_FILE'), - help='the file the base32 secret is written to (OTP_FILE)') args = parser.parse_args() if not args.remote: parser.error('--remote or LXD_REMOTE is required') - if not args.secret_file: - parser.error('--secret-file or OTP_FILE is required') - secret_file = pathlib.Path(args.secret_file) - - def failure(result): - return (result.stderr.strip().splitlines() or ['lxc exec failed'])[-1] - - created = lxc_exec(args.remote, args.project, args.vm, 'python3', '-c', NEW, args.user) - if created.returncode != 0: - sys.exit(f'no new secret for {args.user}: {failure(created)}') - secret = json.loads(created.stdout)['secret'] - enrolled = lxc_exec(args.remote, args.project, args.vm, 'python3', '-c', ENROL, args.user, secret, code_of(secret)) - if enrolled.returncode != 0: - sys.exit(f'{args.user} was not enrolled: {failure(enrolled)}') - - secret_file.parent.mkdir(parents=True, exist_ok=True) - secret_file.touch(mode=0o600) - secret_file.chmod(0o600) - secret_file.write_text(f'{secret}\n', encoding='utf-8') - print(f'{args.user} of {args.remote}:{args.vm} has a new TOTP token; its secret is in {secret_file}') + problem = enrol_otp(args.remote, args.project, args.vm, args.user) + if problem: + sys.exit(problem) + print(f'{args.user} of {args.remote}:{args.vm} has a new TOTP token, the key {totp_key(args.vm, args.user)} ' + f'of the Vault of {args.project}') if __name__ == '__main__': diff --git a/bin/lm-dev-run.py b/bin/lm-dev-run.py index 7f9fee1..29d9f6c 100755 --- a/bin/lm-dev-run.py +++ b/bin/lm-dev-run.py @@ -4,10 +4,12 @@ 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 default), which must not exist and is removed with its networks after each scenario unless --keep -is given. The package is the newest out/linux-manager_*_all.deb. The administrator's name and -password are set as ADMIN_USERNAME and ADMIN_PASSWORD in the repository's .env, and the pre-shared -key is written to tmp/remote-test.env. Each check prints PASS, FAIL or SKIP; the run exits 1 when a -check failed. +is given. The package is --deb, or else the one built last, in out/ or out/dev/. The administrator, admin, has a +password generated per run, kept in the scenario's Vault as /admin. Each scenario's +project gets a Vault, the container lm-vault reached on the LXD host's address; every other instance +with a default route, the hosts of isolated LANs apart, gets an AppRole of its own in it and +/etc/vault once it is ready, and reads the files that hold a secret from it (Lab.hand_over), never as an argument or on standard input. Each check prints PASS, FAIL or SKIP; the run exits 1 when a check +failed. """ import argparse @@ -15,17 +17,25 @@ import importlib import ipaddress import json import os +import pathlib import re import secrets import subprocess import sys import time -from lm_dev import ROOT, TESTS, lxc_exec, set_dotenv +from lm_dev import HANDOVER_DIR, ROOT, TESTS, VAULT_PORT, VaultError, config_path, enrol_instance, hand_over, \ + host_address, lxc_exec, newest_deb, store_secret, vault_initialise 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__') +# 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: """The instances and networks of a run on one LXD remote and project, and the results of its checks. @@ -47,6 +57,9 @@ class Lab: self.networks = [] self.macs = {} self.addresses = {} + self.vault = None + self.enrolled = set() + self.routed = set() def lxc(self, *args, check=True): """Run lxc with the arguments and the project; raise CalledProcessError when it fails, unless check is false.""" @@ -108,6 +121,33 @@ class Lab: result = self.on(name, *command) self.result(description, re.search(pattern, result.stdout + result.stderr, re.M) is None) + def start_vault(self): + """Launch the scenario's Vault, the container lm-vault, reached by the Mac and the instances on the LXD host's + address through a proxy device, and initialise it.""" + host = host_address(self.remote) + if not host: + raise RuntimeError(f'no IPv4 address of the host of remote {self.remote} for the Vault') + network, gateway, mac, address = VAULT_NETWORK + self.network(network, gateway) + self.instance('lm-vault', 'container', 'vault.yaml', (network, mac, address, gateway.split('/')[0])) + if not self.ready('lm-vault'): + raise RuntimeError('the Vault container did not boot') + self.lxc('config', 'device', 'add', f'{self.remote}:lm-vault', 'vault', 'proxy', + f'listen=tcp:{host}:{VAULT_PORT}', f'connect=tcp:127.0.0.1:{VAULT_PORT}') + url = f'http://{host}:{VAULT_PORT}' + try: + self.vault = vault_initialise(self.project, url, url) + except VaultError as error: + raise RuntimeError(f'the Vault was not initialised: {error}') + + def hand_over(self, name, secret, content, destination, mode='0600'): + """Give the instance the content, a file that holds a secret, through the Vault as /, written + to destination; True when it was handed over.""" + problem = hand_over(self.remote, self.project, name, self.vault, secret, content, destination, mode) + if problem: + print(problem, file=sys.stderr) + return problem is None + def network(self, name, address): """Create a bridge with outbound NAT at the gateway address GATEWAY/PREFIX, or without a host address when None. @@ -129,6 +169,8 @@ class Lab: """ self.macs[name] = [nic[1] for nic in nics] self.addresses[name] = nics[0][2] + if any(len(nic) > 3 for nic in nics): + self.routed.add(name) netcfg = 'version: 2\nethernets:\n' for index, (_, mac, address, *gateway) in enumerate(nics): if kind == 'vm': @@ -152,7 +194,8 @@ class Lab: self.lxc('start', f'{self.remote}:{name}') def ready(self, *names): - """Wait for each instance's agent and cloud-init, then for its first address; False when one is not ready. + """Wait for each instance's agent and cloud-init, then for its first address, and give an instance with a + default route, other than the Vault, its AppRole the first time; False when one is not ready. cloud-init's status 2, done with recoverable errors, counts as booted. An instance whose first NIC takes its address from DHCP waits for any IPv4 address outside lo. @@ -174,6 +217,15 @@ class Lab: else: print(f'{name} has no address {address or "from DHCP"}', file=sys.stderr) return False + if name != 'lm-vault' and name in self.routed and name not in self.enrolled: + problem = enrol_instance(self.remote, self.project, name, self.vault) + if problem: + print(problem, file=sys.stderr) + return False + if self.on(name, 'install', '-d', '-m', '0700', HANDOVER_DIR).returncode != 0: + print(f'{HANDOVER_DIR} cannot be made in {name}', file=sys.stderr) + return False + self.enrolled.add(name) return True def nic_of(self, name, index): @@ -204,16 +256,24 @@ class Lab: 'wireguard-tools', 'openvpn', 'curl').returncode == 0) def setup_run(self, name): - """Run linux-manager-setup and wait for it; True when it succeeded.""" - return self.on(name, 'systemctl', 'restart', 'linux-manager-setup').returncode == 0 + """Have linux-manager-setup run, after a run in progress, and wait for it; True when it succeeded.""" + return self.on(name, 'linux-manager-config-edit', 'apply').returncode == 0 def server(self, name, config): """Install the package with the test administrator, then apply the configuration; True when both succeeded.""" if not self.push(self.deb, name, '/tmp/linux-manager.deb'): return False - preseed = (f'linux-manager linux-manager/admin_username string admin\n' + preseed = ('linux-manager linux-manager/admin_username string admin\n' f'linux-manager linux-manager/admin_password password {self.admin_password}\n') - if self.on(name, 'debconf-set-selections', input=preseed).returncode != 0: + try: + store_secret(self.vault, f'{name}/admin', {'password': self.admin_password}) + except VaultError as error: + print(f'the admin password cannot be kept in the Vault: {error}', file=sys.stderr) + return False + if not self.hand_over(name, 'preseed', preseed, f'{HANDOVER_DIR}/preseed'): + return False + if self.on(name, 'sh', '-c', f'debconf-set-selections {HANDOVER_DIR}/preseed; status=$?; ' + f'rm -f {HANDOVER_DIR}/preseed; exit $status').returncode != 0: return False result = self.on(name, 'env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y', '/tmp/linux-manager.deb') @@ -223,10 +283,10 @@ class Lab: def render(self, name, config): """Replace the server's configuration, with its placeholders filled in. - @PSK@ is the pre-shared key, @ETH0@ and @ETH1@ the names of the server's NICs and @CIDR0@ the - network of its first address. + @PSK@ is the pre-shared key, @ETH0@ and @ETH1@ the names of the server's NICs and @CIDR0@ the network of its + first address; the configuration reaches the server through the Vault. """ - text = (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): placeholder = f'@ETH{index}@' if placeholder in text: @@ -236,11 +296,25 @@ class Lab: text = text.replace(placeholder, nic) if '@CIDR0@' in text: text = text.replace('@CIDR0@', str(self.address(name).network)) - return self.push_text(text, name, '/etc/linux-manager/linux-manager.json', '0600') + return self.hand_over(name, 'config', text.replace('@PSK@', self.psk), '/etc/linux-manager/linux-manager.json') + + def installed(self, name): + """Wait for the installations of the server's components (linux-manager-install@*) to end, up to INSTALL_WAIT + seconds; True when none failed.""" + deadline = time.monotonic() + INSTALL_WAIT + while time.monotonic() < deadline: + running = self.on(name, 'systemctl', 'list-units', '--no-legend', '--state=activating,active', + 'linux-manager-install@*').stdout.strip() + if not running: + return not self.on(name, 'systemctl', 'list-units', '--no-legend', '--state=failed', + 'linux-manager-install@*').stdout.strip() + time.sleep(5) + return False def configure(self, name, config): - """Render the configuration and apply it twice, as the server's certificates follow the first run.""" - return self.render(name, config) and self.setup_run(name) and self.setup_run(name) + """Render the configuration and apply it, wait for the packages of its components, and apply it again, as the + components and the server's certificates follow the first run.""" + return self.render(name, config) and self.setup_run(name) and self.installed(name) and self.setup_run(name) def echo_server(self, name): """Answer HTTP on port 8080 of the instance with the address of the client.""" @@ -248,10 +322,14 @@ class Lab: self.on(name, 'systemd-run', '--unit=lm-test-echo', 'python3', '/root/echo.py').returncode == 0) def vpn_user(self, name): - """Add the VPN user alice, whose password is the administrator's; True when it was added.""" - return self.on(name, 'linux-manager-user', '--json', 'add', 'alice', '--first-name', 'Alice', - '--last-name', 'Test', '--email', 'alice@example.org', - input=self.admin_password + '\n').returncode == 0 + """Add the VPN user alice, whose password is the administrator's, read from a file the Vault gives the + server; True when it was added.""" + secret = f'{HANDOVER_DIR}/alice.password' + if not self.hand_over(name, 'alice', f'{self.admin_password}\n', secret): + return False + return self.on(name, 'sh', '-c', 'linux-manager-user --json add alice --first-name Alice --last-name Test ' + f'--email alice@example.org < {secret}; status=$?; rm -f {secret}; ' + 'exit $status').returncode == 0 def alice(self, name): """User alice from the server's user list, or None.""" @@ -259,10 +337,13 @@ class Lab: return next((user for user in listing.get('users', []) if user.get('name') == 'alice'), None) def wireguard_client(self, client, server, endpoint, address, allowed): - """Give alice a peer of a new client key and bring wg0 up on the client towards the server, for allowed only.""" - private_key = self.on(client, 'wg', 'genkey').stdout.strip() - public_key = self.on(client, 'wg', 'pubkey', input=private_key + '\n').stdout.strip() - if not private_key or not public_key: + """Give alice a peer of a new client key and bring wg0 up on the client towards the server, for allowed only. + + The client's private key is made in the client and never leaves it; wg0.conf is completed there. + """ + public_key = self.on(client, 'sh', '-c', 'umask 077; wg genkey > /etc/wireguard/private.key && ' + 'wg pubkey < /etc/wireguard/private.key').stdout.strip() + if not public_key: return False if not self.push(TESTS / 'wireguard_peer.py', server, '/root/wireguard_peer.py'): return False @@ -271,9 +352,14 @@ class Lab: if not self.setup_run(server): return False server_key = self.on(server, 'cat', '/etc/wireguard/wg0.pub').stdout.strip() - conf = (f'[Interface]\nPrivateKey = {private_key}\nAddress = {address}/32\n\n' + conf = (f'[Interface]\nPrivateKey = @KEY@\nAddress = {address}/32\n\n' f'[Peer]\nPublicKey = {server_key}\nEndpoint = {endpoint}:51820\nAllowedIPs = {allowed}\n') - return (self.push_text(conf, client, '/etc/wireguard/wg0.conf', '0600') and + # awk reads the key from its file, so it is no argument of any process. + complete = ("umask 077; awk 'NR == FNR { key = $0; next } { gsub(\"@KEY@\", key) } 1' " + '/etc/wireguard/private.key /etc/wireguard/wg0.template > /etc/wireguard/wg0.conf && ' + 'rm -f /etc/wireguard/wg0.template') + return (self.push_text(conf, client, '/etc/wireguard/wg0.template', '0600') and + self.on(client, 'sh', '-c', complete).returncode == 0 and self.on(client, 'bash', '/usr/bin/wg-quick', 'up', 'wg0').returncode == 0) def wireguard_module(self, name): @@ -291,6 +377,8 @@ class Lab: listing = self.lxc('list', f'{self.remote}:', '-c', 'n', '-f', 'csv', check=False) for name in listing.stdout.split(): self.lxc('delete', '--force', f'{self.remote}:{name}', check=False) + config_path(f'vault-{self.project}.json').unlink(missing_ok=True) + self.vault = None for name in self.networks: subprocess.run(['lxc', 'network', 'delete', f'{self.remote}:{name}'], capture_output=True) self.networks = [] @@ -308,6 +396,7 @@ def main(): parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'), help='the image of every instance (LXD_IMAGE, default ubuntu:26.04)') parser.add_argument('--keep', action='store_true', help='leave the project and the networks in place') + parser.add_argument('--deb', help='the package to test (default the one built last, in out/ or out/dev/)') args = parser.parse_args() if not args.remote: parser.error('--remote or LXD_REMOTE is required') @@ -318,21 +407,16 @@ def main(): if unknown: parser.error(f'no scenario {", ".join(unknown)}') - debs = sorted((ROOT / 'out').glob('linux-manager_*_all.deb')) - if not debs: - sys.exit('no out/linux-manager_*_all.deb; run ./build.sh first') + deb = pathlib.Path(args.deb) if args.deb else newest_deb() + if deb is None or not deb.is_file(): + sys.exit(f'no package {args.deb}' if args.deb else 'no out/linux-manager_*_all.deb; run ./build.sh first') if subprocess.run(['lxc', 'project', 'show', f'{args.remote}:{args.project}'], capture_output=True).returncode == 0: sys.exit(f'project {args.project} exists on {args.remote}; remove it or choose another with --project') TMP.mkdir(parents=True, exist_ok=True) - lab = Lab(args.remote, args.project, args.pool, args.image, args.keep, debs[-1], + lab = Lab(args.remote, args.project, args.pool, args.image, args.keep, deb, secrets.token_hex(16), secrets.token_hex(24)) - env = ROOT / 'tmp' / 'remote-test.env' - env.touch(mode=0o600) - env.chmod(0o600) - env.write_text(f'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}') + print(f'package: {deb}; remote: {args.remote}; project: {args.project}; image: {args.image}') sys.path.insert(0, str(TESTS)) try: @@ -341,6 +425,7 @@ def main(): '-c', 'features.images=false'], capture_output=True, check=True) print(f'== {name}') try: + lab.start_vault() importlib.import_module(f'scenarios.{name}').run(lab) except (subprocess.CalledProcessError, RuntimeError) as error: detail = error.stderr.strip() if isinstance(error, subprocess.CalledProcessError) else str(error) @@ -351,8 +436,8 @@ def main(): sys.exit(130) print(f'== passed {lab.passed}, failed {lab.failed}, skipped {lab.skipped}') - print("Not covered: IKEv2 client access, HTTPS with Let's Encrypt, the OpenID Provider and passkeys,") - print('PowerDNS answering from outside, the Azure and GCP platform modules.') + print("Not covered: IKEv2 client access, HTTPS with Let's Encrypt, passkeys, PowerDNS answering from") + print('outside, the Azure and GCP platform modules.') sys.exit(1 if lab.failed else 0) diff --git a/bin/lm-dev-vm.py b/bin/lm-dev-vm.py index 1cd04d8..9c057e5 100755 --- a/bin/lm-dev-vm.py +++ b/bin/lm-dev-vm.py @@ -3,34 +3,41 @@ create launches the VM --vm (lm-dev by default) on the remote --remote (LXD_REMOTE) in the project --project (LXD_PROJECT, lm-dev by default) with that project's default profile. In a test project -made by lm-dev-lxd-project.py, which tmp/lxd-project-PROJECT.json describes, the VM gets the package +made by lm-dev-lxd-project.py, which .lm-dev-config/lxd-project-PROJECT.json describes, the VM gets the package from that project's repository, as its apt source, so later dev builds reach it as updates; -elsewhere it gets the newest out/linux-manager_*_all.deb. The administrator is admin with a -generated password, set as ADMIN_USERNAME and ADMIN_PASSWORD in the repository's .env. The VM -gets a configuration from tests/remote/configs/ (--config, core.json by default), whose @ETH0@ is -the interface of its default route, @CIDR0@ its network and @PSK@ a generated key, written to -tmp/vm-VM.env. +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, and a TOTP +token, the key VM-admin of the project's Vault's TOTP engine, unless --no-otp is given; +lm-dev-otp-code.py prints its codes. The VM gets a configuration from tests/remote/configs/ +(--config, core.json by default), whose @ETH0@ is the interface of its default route, @CIDR0@ its +network and @PSK@ a generated key. 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 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 -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 and what the Vault keeps for it; .env is left +as it is. """ import argparse import ipaddress import json import os +import pathlib import re import secrets -import socket import subprocess import sys 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, VaultError, config_path, enrol_instance, enrol_otp, \ + forget_instance, hand_over, host_address, lxc_exec, newest_deb, set_dotenv, store_secret, vault_state # 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)) @@ -50,28 +57,27 @@ def main(): parser.add_argument('--listen', default=os.environ.get('LXD_LISTEN'), help="outside a test project, the LXD host address the proxies listen on (LXD_LISTEN, " "default the IPv4 address of the remote URL's host)") + parser.add_argument('--forward-address', default=os.environ.get('LXD_FORWARD_ADDRESS'), + 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() if not args.remote: parser.error('--remote or LXD_REMOTE is required') - project_file = ROOT / 'tmp' / f'lxd-project-{args.project}.json' + project_file = config_path(f'lxd-project-{args.project}.json') project = json.loads(project_file.read_text(encoding='utf-8')) if project_file.is_file() else None if project and project['remote'] != args.remote: sys.exit(f'{project_file} is of remote {project["remote"]}, not {args.remote}') if not project and args.action == 'create' and not args.listen: # The default listen address is the IPv4 address of the remote's host in its lxc URL. - remotes = json.loads(subprocess.run(['lxc', 'remote', 'list', '--format', 'json'], capture_output=True, - 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 + args.listen = host_address(args.remote) if not args.listen: parser.error(f'no IPv4 address of the host of remote {args.remote}; give --listen or LXD_LISTEN') where = f'{args.remote}:{args.vm} (project {args.project})' exists = subprocess.run(['lxc', 'info', f'{args.remote}:{args.vm}', '--project', args.project], capture_output=True).returncode == 0 - env = ROOT / 'tmp' / f'vm-{args.vm}.env' def inside(*command, input=None): return lxc_exec(args.remote, args.project, args.vm, *command, input=input) @@ -95,7 +101,11 @@ def main(): if project and (listen := forward_of_vm()): subprocess.run(['lxc', 'network', 'forward', 'delete', wan, listen, '--project', args.project], check=True) subprocess.run(['lxc', 'delete', '--force', f'{args.remote}:{args.vm}', '--project', args.project], check=True) - 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) print(f'removed {where}') return @@ -104,16 +114,16 @@ def main(): config = TESTS / 'configs' / args.config if not config.is_file(): parser.error(f'no tests/remote/configs/{args.config}') - debs = sorted((ROOT / 'out').glob('linux-manager_*_all.deb')) - if not project and not debs: - sys.exit('no out/linux-manager_*_all.deb; run ./build.sh first') - source = f'the repository {project["repository"]}' if project else debs[-1].name + deb = pathlib.Path(args.deb) if args.deb else newest_deb() + if not project and (deb is None or not deb.is_file()): + sys.exit(f'no package {args.deb}' if args.deb else 'no out/linux-manager_*_all.deb; run ./build.sh first') + source = f'the repository {project["repository"]}' if project else str(deb) + vault = vault_state(args.project) + if vault is None: + sys.exit(f'project {args.project} has no Vault, which the secrets reach the VM through; make it with ' + 'lm-dev-lxd-project.py vault create') password, psk = secrets.token_hex(16), secrets.token_hex(24) - env.parent.mkdir(parents=True, exist_ok=True) - 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}' @@ -130,6 +140,9 @@ def main(): time.sleep(5) else: sys.exit(f'{args.vm} did not boot; remove it with remove') + problem = enrol_instance(args.remote, args.project, args.vm, vault) + if problem: + sys.exit(f'{problem}; remove the VM with remove') for _ in range(24): route = re.search(r'\bdev (\S+)', inside('ip', '-4', '-o', 'route', 'show', 'default').stdout) address = route and re.search(r' inet (\S+) ', @@ -152,8 +165,10 @@ def main(): subprocess.run(['lxc', 'config', 'device', 'override', f'{args.remote}:{args.vm}', device, f'ipv4.address={interface.ip}', '--project', args.project], check=True) if project: - # An OVN network refuses NAT proxies; the forward's listen address is allocated from the uplink's routes. - subprocess.run(['lxc', 'network', 'forward', 'create', wan, '--allocate=ipv4', f'user.vm={args.vm}', + # An OVN network refuses NAT proxies; the forward's listen address is --forward-address, or one allocated + # from the uplink's routes. + address = [args.forward_address] if args.forward_address else ['--allocate=ipv4'] + subprocess.run(['lxc', 'network', 'forward', 'create', wan, *address, f'user.vm={args.vm}', '--project', args.project], check=True) args.listen = forward_of_vm() if not args.listen: @@ -180,12 +195,22 @@ def main(): sys.exit(f'apt-get update failed in {args.vm}: {updated.stderr.strip()}') package = 'linux-manager' else: - if not push(debs[-1], '/tmp/linux-manager.deb', '0644'): - sys.exit(f'could not copy {debs[-1].name} into {args.vm}') + if not push(deb, '/tmp/linux-manager.deb', '0644'): + sys.exit(f'could not copy {deb} into {args.vm}') package = '/tmp/linux-manager.deb' - preseed = (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') - 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}') result = inside('env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y', package) log = ROOT / 'tmp' / f'vm-{args.vm}-install.log' @@ -194,22 +219,25 @@ def main(): sys.exit(f'the package did not install; see {log}') # Apply the configuration twice, as the server's certificates follow the first run. - text = (config.read_text(encoding='utf-8').replace('@ETH0@', nic).replace('@CIDR0@', str(interface.network)) - .replace('@PSK@', psk)) - rendered = ROOT / 'tmp' / f'vm-{args.vm}.json' - rendered.touch(mode=0o600) - rendered.chmod(0o600) - 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}') + text = config.read_text(encoding='utf-8').replace('@ETH0@', nic).replace('@CIDR0@', str(interface.network)) + problem = hand_over(args.remote, args.project, args.vm, vault, 'config', text.replace('@PSK@', psk), + '/etc/linux-manager/linux-manager.json', '0600') + if problem: + sys.exit(f'could not give {args.vm} {args.config}: {problem}') for _ in range(2): - if inside('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') + if not args.no_otp: + problem = enrol_otp(args.remote, args.project, args.vm, 'admin') + if problem: + sys.exit(f'{args.vm} is up, but {problem}') + print(f'{args.vm} is up at {interface.ip} with {args.config}') - print(f'administrator: admin password: {password} (also in {ROOT / ".env"})') + print(f'administrator: admin, password in {ROOT / ".env"} (ADMIN_PASSWORD) and the Vault ({VAULT_MOUNT}/' + f'{args.vm}/admin)') + if not args.no_otp: + print(f'administrator TOTP codes: bin/lm-dev-otp-code.py --project {args.project} --vm {args.vm}') 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'remove: {sys.argv[0]} remove --remote {args.remote} --project {args.project} --vm {args.vm}') diff --git a/bin/lm_dev.py b/bin/lm_dev.py index 7b483d5..b9fedf7 100644 --- a/bin/lm_dev.py +++ b/bin/lm_dev.py @@ -1,13 +1,57 @@ -"""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 .env of the repository, the +persistent state 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//, whole files that hold a secret (hand_over), and creates its +own TOTP keys (enrol_otp). +""" + +import json +import os import pathlib +import socket import subprocess +import tempfile +import time +import urllib.error +import urllib.parse +import urllib.request ROOT = pathlib.Path(__file__).resolve().parent.parent # The test data: scenarios, configurations, cloud-init files, the repository's script and the files copied in. TESTS = ROOT / 'tests' / 'remote' # The project of the manual tests, which lm-dev-lxd-project.py makes. PROJECT = 'lm-dev' +# The state of the scripts that outlives a clean-up of tmp/: project and Vault states, keys and secrets; 0700. +CONFIG = ROOT / '.lm-dev-config' + +# 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): @@ -16,6 +60,12 @@ def lxc_exec(remote, project, instance, *command, input=None): input=input, capture_output=True, text=True) +def lxc_push(remote, project, instance, source, path, mode): + """Copy the local file to the path in the instance with the mode; True when it was copied.""" + return subprocess.run(['lxc', 'file', 'push', str(source), f'{remote}:{instance}{path}', '--mode', mode, + '--project', project], capture_output=True, text=True).returncode == 0 + + def set_dotenv(values): """Set the variables in the repository's .env, readable by its owner only, keeping its other lines.""" dotenv = ROOT / '.env' @@ -25,3 +75,213 @@ def set_dotenv(values): dotenv.chmod(0o600) dotenv.write_text(''.join(f'{line}\n' for line in kept + [f'{key}={value}' for key, value in values.items()]), encoding='utf-8') + + +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// and creates the TOTP + keys -*, 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// 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//, 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 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 secret is + held by the Vault and the VM only, and the codes are read from the Vault (otp_code). + """ + state = vault_state(project) + if state is None: + return f'project {project} has no Vault; make it with lm-dev-lxd-project.py vault create' + key = totp_key(instance, user) + try: + vault_call(state['url'], 'DELETE', f'/v1/{TOTP_MOUNT}/keys/{key}', token=state['root_token']) + except VaultError as error: + return f'the TOTP key {key} cannot be replaced: {error}' + target = f'{HANDOVER_DIR}/otp-url' + for command in (('install', '-d', '-m', '0700', HANDOVER_DIR), (HELPER, 'totp', key, instance, user, target, '0600'), + ('python3', '-c', OTP_ENROL, user, target)): + result = lxc_exec(remote, project, instance, *command) + if result.returncode != 0: + return f'{user} was not enrolled: {(result.stderr.strip().splitlines() or ["lxc exec failed"])[-1]}' + 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'] diff --git a/bin/otp.py b/bin/otp.py index f3065a7..0d6ebbf 100755 --- a/bin/otp.py +++ b/bin/otp.py @@ -1,11 +1,14 @@ #!/usr/bin/env python3 """An authenticator app on the command line: make a TOTP secret or print its current code: otp.py new|code. -The secret, base32, is kept in the file --secret-file or OTP_FILE names, readable by its owner -only. new makes a new secret of 20 random bytes in that file, refusing to replace one without ---force, and prints its otpauth URI, labelled with --account and --issuer when given. code prints -the code of the secret now, or at the Unix time --at. The codes are RFC 6238's, with --algorithm -(sha1 by default), --digits (6) and --period (30 seconds). +The secret is kept in the file --secret-file or OTP_FILE names, readable by its owner only, as +nothing but its base32 secret, or with --url as its otpauth URI, each without a line end, so the +file is a value Vault's TOTP engine imports as it is (key=@FILE or url=@FILE). new makes a new +secret of 20 random bytes in that file, refusing to replace one without --force, and prints its +otpauth URI, labelled with --account and --issuer when given. code prints the code of the secret +now, or at the Unix time --at, from either form of the file. The codes are RFC 6238's, with +--algorithm (sha1 by default), --digits (6) and --period (30 seconds); a file holding an otpauth +URI gives those of the URI instead. """ import argparse @@ -33,17 +36,30 @@ def code_of(secret, now=None, digits=6, period=30, algorithm='sha1'): return f'{value % 10 ** digits:0{digits}d}' +def stored(text, digits, period, algorithm): + """The secret, digits, period and algorithm of the file's text: a base32 secret with the given settings, or an + otpauth URI with its own, the given ones where it has none.""" + if not text.startswith('otpauth://'): + return text, digits, period, algorithm + query = {name: values[0] for name, values in urllib.parse.parse_qs(urllib.parse.urlsplit(text).query).items()} + found = query.get('algorithm', algorithm).lower() + if found not in ALGORITHMS: + sys.exit(f'the otpauth URI has the unknown algorithm {found}') + return query.get('secret', ''), int(query.get('digits', digits)), int(query.get('period', period)), found + + def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument('action', choices=('new', 'code')) parser.add_argument('--secret-file', default=os.environ.get('OTP_FILE'), - help='the file of the base32 secret (OTP_FILE)') + help='the file of the base32 secret or its otpauth URI (OTP_FILE)') parser.add_argument('--algorithm', choices=ALGORITHMS, default='sha1', help='the HMAC hash (default sha1)') parser.add_argument('--digits', type=int, default=6, help='the digits of a code (default 6)') parser.add_argument('--period', type=int, default=30, help='the seconds a code is valid (default 30)') parser.add_argument('--at', type=float, help='code: the Unix time of the code instead of now') parser.add_argument('--account', help='new: the account name in the otpauth URI') parser.add_argument('--issuer', help='new: the issuer in the otpauth URI') + parser.add_argument('--url', action='store_true', help='new: store the otpauth URI instead of the secret alone') parser.add_argument('--force', action='store_true', help='new: replace an existing secret') args = parser.parse_args() if not args.secret_file: @@ -55,21 +71,24 @@ def main(): if args.action == 'code': if not secret_file.is_file(): sys.exit(f'no {secret_file}; make a secret with new') - print(code_of(secret_file.read_text(encoding='utf-8').strip(), args.at, args.digits, args.period, args.algorithm)) + secret, digits, period, algorithm = stored(secret_file.read_text(encoding='utf-8').strip(), args.digits, + args.period, args.algorithm) + print(code_of(secret, args.at, digits, period, algorithm)) return if secret_file.exists() and not args.force: sys.exit(f'{secret_file} exists; give --force to replace its secret') secret = base64.b32encode(secrets.token_bytes(20)).decode() - secret_file.parent.mkdir(parents=True, exist_ok=True) - secret_file.touch(mode=0o600) - secret_file.chmod(0o600) - secret_file.write_text(f'{secret}\n', encoding='utf-8') label = urllib.parse.quote(':'.join(part for part in (args.issuer, args.account) if part) or 'otp') query = {'secret': secret, 'algorithm': args.algorithm.upper(), 'digits': args.digits, 'period': args.period} if args.issuer: query['issuer'] = args.issuer - print(f'otpauth://totp/{label}?{urllib.parse.urlencode(query)}') + 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__': diff --git a/debian-package/debian/changelog b/debian-package/debian/changelog index 70a0a69..6f5f05d 100644 --- a/debian-package/debian/changelog +++ b/debian-package/debian/changelog @@ -1,3 +1,111 @@ +linux-manager (0.42.0-1) unstable; urgency=medium + + feature: the VPN, the router, the name server and WebDAV are components + switched on the System tab and installed on demand, Caddy from the Ubuntu + archive is a dependency and serves every HTTP and HTTPS port, HTTPS is + chosen at install, its certificate is of the Servers Issuing CA or + self-signed by default, of ACME or of another CA, the issuing CAs are in one + tab, a locked account is unlocked again, the name of a CA is fixed once the + CA exists, and a run of setup is no longer cut short by a change. + + * The Manager's System tab has a Components panel: the VPN, the router, + the name server and WebDAV, each switched on and off there, with GET and + PUT /components; the router is offered only with a second network + interface, and its Enable asks for the internal interface and, in manual + mode, its address and gateway. The DNS and sites settings dialogs no + longer switch the name server and WebDAV. + * The Overview's Addresses panel lists each address of the status page + once, and the Manager's plain HTTP addresses while Caddy does not + redirect it; /api/info gives the port and listen of the Manager's site. + * Every page and tab with more than one panel has Edit layout and Panels, + its layout kept in the browser. + * The name server has a DNS page of its own, in the page menu while it is + on, instead of a tab of Web Sites; its secondary name server is optional, + and without it the server is the domains' only name server, with no + warning at each setup run. + * The VPN's and the router's packages are suggested, not depended on, and + linux-manager-install@vpn and @router install them from the Ubuntu + archive while the component is on; setup also has packages of a + component that is on, marked as installed automatically, marked as + installed by hand, so apt autoremove keeps them. + * A change made in the Manager, with the package's commands or by the + installation of a component no longer restarts a run of + linux-manager-setup in progress, which could leave the firewall, the VPN + or the routes half applied; the run runs once more when it ends instead. + linux-manager-config-edit apply runs setup and waits for it, and --restart + of set and remove does the same. + * The package depends on caddy from the Ubuntu archive, which serves + web.port, the Manager's port and metrics.port over plain HTTP as well as + the HTTPS ports; the web service, the Manager and the metrics service + listen on 127.0.0.1 only, on ports 7091, 7090 and 9474, and the firewall + opens each plain HTTP port on the interfaces its listen setting names. + * The Manager's sign-in page and /api/info without a session no longer + show the package's version, and Caddy removes the Server header of + every answer, which named Caddy and the services' Python version. + * https.caddy_source, the upstream Caddy repository and + linux-manager-caddy are removed; a configuration that names + https.caddy_source is refused. + * The installer asks whether to serve over HTTPS, https.enabled, and with + HTTPS whether to keep the Manager on plain HTTP, + https.disable_auto_redirect; while HTTPS is on, Caddy redirects the + Manager's plain HTTP port to its HTTPS address, and the status page never + redirects. + * https.certificate is self-signed when the configuration does not set it, + and acme only when set; a new installation's first setup chooses ca when + the root CA and the Servers Issuing CA are available, else self-signed, + and writes it into the configuration file. A server whose configuration + did not set it moves from acme to self-signed. + * https.certificate, self-signed, ca, acme or external, says + where the certificate of wan.local_fqdn comes from; while the chosen one + is not available, the server serves a self-signed one and warns. + * With external, linux-manager-ca https csr, import and import-pfx, POST + /https/csr, PUT /https/certificate and PUT /https/pfx, and Generate CSR, + Import certificate and Import PFX of the Certificates page's Server tab + make a CSR and take the certificate another CA signed, or a PFX file. + * https.acme_provider, letsencrypt, zerossl or custom with acme_url and + optional EAB, is the ACME CA of the server and of the sites with TLS + acme; https.zerossl_api_key is optional. + * PUT /https/settings changes the source and the ACME settings; the + Certificates page's first tab, Server, shows HTTPS, the certificate, the + ACME CA and Caddy, which the Overview no longer shows; its HTTPS row's + button changes the source and its ACME CA row's button the ACME CA, + which the web sites with TLS ACME also use; port 80 is opened for the + challenge only with acme. + * The built-in Servers Issuing CA servers, named pki.servers_name, issues + mTLS certificates and the server's HTTPS certificate with ca; the + site-to-site template is mtls, and the s2s CA issues it. + * The Certificates page shows the built-in and the custom issuing CAs in + one Issuing CAs tab, with the certificates of all of them; a built-in CA + whose component is off is off, not missing. + * Every test instance gets an AppRole of its own in a Vault of the test + project, with /etc/vault and the helper lm-dev-vault, and reads its + secrets with it, never as an argument or on standard input; + lm-dev-lxd-project.py vault create, unseal and remove manage the Vault, + and the scripts' state is in .lm-dev-config/. + * lm-dev-vm.py takes --forward-address, and enrols a TOTP token for admin + when the VM is created unless --no-otp is given. + * The TOTP tokens of test VMs are keys of the Vault's TOTP engine; + lm-dev-otp-code.py prints their codes, and lm-dev-otp-register.py takes + no --secret-file. bin/otp.py stores its secret without a line end, or + with --url its otpauth URI, so Vault imports the file as it is, and + reads codes from either. + * linux-manager-user unlock, POST /users//unlock and the metrics + account's new password end a lockout again; they failed when the user + had failed binds. + * Setup refuses a CA name that differs from the common name of the CA's + certificate or CSR, and linux-manager-ca ca import a certificate whose + common name differs from the CSR's; the PKI settings dialog edits the + P2S and S2S names only until their CA exists, and the issuing CA dialog + no longer edits the common name of an existing CA. + * lm-dev-run.py keeps the lab's admin password in the scenario's Vault and + no longer replaces ADMIN_PASSWORD in .env. + * lm-dev-run.py and lm-dev-vm.py install the package built last, in out/ + or out/dev/, or the one --deb names; lm-dev-vm.py no longer prints the + admin password. + * The build retries failed downloads of the image's packages. + + -- Slawomir Koszewski Mon, 23 Nov 2026 08:20:31 +0100 + linux-manager (0.41.1-1) unstable; urgency=medium fix: the root CA is created by the server, an offline CA or a Simple CA diff --git a/debian-package/debian/config b/debian-package/debian/config index 7f66e95..31cd2f1 100755 --- a/debian-package/debian/config +++ b/debian-package/debian/config @@ -67,6 +67,7 @@ fi db_go || true db_input high linux-manager/local_fqdn || true +db_input high linux-manager/https_enabled || true if [ "$ROUTER" = "true" ] || [ "$VPN" = "true" ]; then db_input high linux-manager/local_cidrs || true fi @@ -84,6 +85,12 @@ if [ "$VPN" = "true" ]; then fi 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 if [ "$RET" = "local" ]; then db_input high linux-manager/pki_root_name || true diff --git a/debian-package/debian/control b/debian-package/debian/control index e5ae5c9..326ce09 100644 --- a/debian-package/debian/control +++ b/debian-package/debian/control @@ -9,11 +9,6 @@ Rules-Requires-Root: no Package: linux-manager Architecture: all Depends: ${misc:Depends}, - strongswan-swanctl (>= 5.0), - charon-systemd (>= 5.0), - libstrongswan-extra-plugins, - libcharon-extra-plugins, - wireguard-tools, ufw, debconf, ucf, @@ -29,20 +24,25 @@ Depends: ${misc:Depends}, python3-psutil, python3-prometheus-client, python3-requests, + caddy, postgresql, slapd, nslcd, libnss-ldapd, libpam-ldapd, sudo, - openvpn, - openvpn-auth-ldap, iproute2, systemd-resolved, - dnsmasq-base, zstd Recommends: bash-completion -Suggests: caddy, +Suggests: strongswan-swanctl (>= 5.0), + charon-systemd (>= 5.0), + libstrongswan-extra-plugins, + libcharon-extra-plugins, + wireguard-tools, + openvpn, + openvpn-auth-ldap, + dnsmasq-base, rclone, pdns-server, pdns-backend-pgsql, @@ -57,8 +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 networks through NAT on one interface. Its two-level CA, whose root may be kept offline, has issuing CAs for the VPN clients, for site-to-site and for - general use, and publishes their certificates and CRLs. Caddy, installed by - the package from the Ubuntu archive or from Caddy's repository, serves HTTPS + general use, and publishes their certificates and CRLs. Caddy, from the + Ubuntu archive, serves every HTTP and HTTPS port of the server's services and static web sites, whose files are uploaded through the web service or WebDAV, an optional PowerDNS name server answers for a zone of the sites, and an optional OpenID Provider signs the directory's users in to other diff --git a/debian-package/debian/install b/debian-package/debian/install index 267cd8b..7daf4f6 100644 --- a/debian-package/debian/install +++ b/debian-package/debian/install @@ -25,7 +25,6 @@ src/usr/sbin/linux-manager-token usr/sbin/ src/usr/sbin/linux-manager-config-edit usr/sbin/ src/usr/sbin/linux-manager-backup usr/sbin/ src/usr/sbin/linux-manager-ca usr/sbin/ -src/usr/sbin/linux-manager-caddy usr/sbin/ src/usr/sbin/linux-manager-site usr/sbin/ src/usr/lib/linux-manager/configure usr/lib/linux-manager/ src/usr/lib/linux-manager/docker-rules usr/lib/linux-manager/ diff --git a/debian-package/debian/linux-manager.linux-manager-caddy.service b/debian-package/debian/linux-manager.linux-manager-caddy.service deleted file mode 100644 index cdb0b5e..0000000 --- a/debian-package/debian/linux-manager.linux-manager-caddy.service +++ /dev/null @@ -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 diff --git a/debian-package/debian/postinst b/debian-package/debian/postinst index 039154f..a68ab89 100755 --- a/debian-package/debian/postinst +++ b/debian-package/debian/postinst @@ -24,6 +24,8 @@ case "$1" in answer linux-manager/external_interface; LINUX_MANAGER_EXTERNAL_INTERFACE="$ANSWER" answer linux-manager/internal_interface; LINUX_MANAGER_INTERNAL_INTERFACE="$ANSWER" answer linux-manager/local_fqdn; LINUX_MANAGER_LOCAL_FQDN="$ANSWER" + answer linux-manager/https_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_cidrs; LINUX_MANAGER_LOCAL_CIDRS="$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_EXTERNAL_INTERFACE \ 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_INT_GATEWAY_IP \ LINUX_MANAGER_REMOTE_ADDRS LINUX_MANAGER_REMOTE_ID \ diff --git a/debian-package/debian/postrm b/debian-package/debian/postrm index d833cf8..58d0dce 100755 --- a/debian-package/debian/postrm +++ b/debian-package/debian/postrm @@ -73,7 +73,7 @@ case "$1" in # The name service no longer looks up the console accounts of the server's directory. sed -i '/^passwd:/s/ ldap\b//' /etc/nsswitch.conf rm -rf /var/lib/linux-manager/backup/staging /var/lib/linux-manager/backup/restore \ - /var/lib/linux-manager/pki-publish /etc/caddy/linux-manager-pki /etc/caddy/linux-manager-sites \ + /var/lib/linux-manager/pki-publish /etc/caddy/linux-manager-pki /etc/caddy/linux-manager-https /etc/caddy/linux-manager-sites \ /etc/openvpn/server/linux-manager-ca.pem /etc/openvpn/server/linux-manager-crl.pem rmdir --ignore-fail-on-non-empty /var/lib/linux-manager/backup /var/lib/linux-manager 2>/dev/null || true @@ -100,8 +100,7 @@ case "$1" in # in slapd, the WireGuard key pair, everything under /etc/swanctl, the # files of the web sites in /var/lib/linux-manager/sites, the backups and # what a restore replaced are left in place. Caddy, rclone and PowerDNS - # stay installed, so Caddy's repository, which linux-manager-caddy - # configures, stays too. + # stay installed. rmdir --ignore-fail-on-non-empty /etc/linux-manager 2>/dev/null || true ;; esac diff --git a/debian-package/debian/rules b/debian-package/debian/rules index fe05631..28ebd9b 100755 --- a/debian-package/debian/rules +++ b/debian-package/debian/rules @@ -14,7 +14,6 @@ override_dh_installsystemd: dh_installsystemd --name=linux-manager-bootstrap --no-enable --no-start dh_installsystemd --name=linux-manager-backup --no-enable --no-start dh_installsystemd --name=linux-manager-pki --no-enable --no-start - dh_installsystemd --name=linux-manager-caddy --no-enable --no-start dh_installsystemd --name=linux-manager-webdav --no-enable --no-start dh_installsystemd --name=linux-manager-resolver --no-enable --no-start dh_installsystemd --name=linux-manager-install@ --no-enable --no-start diff --git a/debian-package/debian/templates b/debian-package/debian/templates index 121b876..6ae0fd6 100644 --- a/debian-package/debian/templates +++ b/debian-package/debian/templates @@ -95,6 +95,23 @@ Description: Local router FQDN: router.example.com). Used as the IKEv2 server identity and 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 Type: select Choices: fqdn, public_ip, internal_ip diff --git a/debian-package/src/usr/lib/linux-manager/generate-config b/debian-package/src/usr/lib/linux-manager/generate-config index b295104..e077b7b 100755 --- a/debian-package/src/usr/lib/linux-manager/generate-config +++ b/debian-package/src/usr/lib/linux-manager/generate-config @@ -7,8 +7,8 @@ this script never writes to /etc and never has to worry about destroying an administrator's edits. The candidate is the current /etc/linux-manager/linux-manager.json as it is, or the -shipped defaults when there is none, with every debconf answer that was given -written over it. Without an answer that changes it, the candidate is the current +shipped defaults when there is none, with https.certificate empty for the first +setup to choose, with every debconf answer that was given written over it. Without an answer that changes it, the candidate is the current file byte for byte, so an upgrade or a reconfiguration that changes nothing gives ucf nothing to ask; defaults the file leaves out are applied by linuxmanager.load_config() when the @@ -43,6 +43,8 @@ ANSWERS = { 'LINUX_MANAGER_EXTERNAL_INTERFACE': (('interfaces', 'external'),), 'LINUX_MANAGER_INTERNAL_INTERFACE': (('interfaces', 'internal'),), '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_CIDRS': (('local', 'cidrs'), (*FIRST, 'local_cidrs')), 'LINUX_MANAGER_INT_GATEWAY_IP': (('local', 'int_gateway_ip'),), @@ -73,6 +75,8 @@ def main(): current = None if current is None: cfg = linuxmanager.load_config() + # A new installation leaves the source of the HTTPS certificate to its first setup. + cfg['https']['certificate'] = '' else: try: cfg = json.loads(current) diff --git a/debian-package/src/usr/lib/linux-manager/install-packages b/debian-package/src/usr/lib/linux-manager/install-packages index 0f7419f..954c7f4 100755 --- a/debian-package/src/usr/lib/linux-manager/install-packages +++ b/debian-package/src/usr/lib/linux-manager/install-packages @@ -1,19 +1,31 @@ #!/usr/bin/python3 -"""Install the packages of a feature from the Ubuntu archive, then restart linux-manager-setup without waiting. +"""Install the packages of a component from the Ubuntu archive, then have linux-manager-setup run without waiting. -Run by linux-manager-install@.service, which linux-manager-setup starts when the feature is on and its packages are -missing: webdav (rclone) and dns (PowerDNS with its gpgsql backend). Recommended packages are left out, so PowerDNS -comes without its bind backend. A failure is a message on standard error and the exit status 1. +Run by linux-manager-install@.service, which linux-manager-setup starts when the component is on and its +packages are missing or marked as installed automatically: the components and their packages are +linuxmanager.COMPONENTS, the VPN, the router, the name server (PowerDNS with its gpgsql backend) and WebDAV (rclone). +Recommended packages are left out, so PowerDNS comes without its bind backend. apt-get marks the packages as installed +by hand. Installations of several components run one after another (INSTALL_LOCK), as apt locks its package lists. +A run of setup in progress, the one that started the installation, runs again when it ends (request_setup). A failure +is a message on standard error and the exit status 1. - install-packages FEATURE + install-packages COMPONENT """ +import fcntl import os import subprocess import sys -#: The packages of each feature. -FEATURES = {'webdav': ['rclone'], 'dns': ['pdns-server', 'pdns-backend-pgsql']} +sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) + +import linuxmanager # noqa: E402 + +#: The packages of each component. +FEATURES = {name: packages for name, (_, packages) in linuxmanager.COMPONENTS.items()} + +#: The lock that has the installations of several components run one after another. +INSTALL_LOCK = '/run/linux-manager-install.lock' #: apt-get, waiting up to ten minutes for dpkg's lock, which a package installation that runs setup holds. APT = ['apt-get', '-o', 'DPkg::Lock::Timeout=600'] @@ -23,12 +35,15 @@ def main(): if len(sys.argv) != 2 or sys.argv[1] not in FEATURES: sys.exit(f'usage: install-packages {"|".join(FEATURES)}') environment = dict(os.environ, DEBIAN_FRONTEND='noninteractive') + lock = open(INSTALL_LOCK, 'w', encoding='utf-8') + fcntl.flock(lock, fcntl.LOCK_EX) for args in ([*APT, 'update'], [*APT, '-y', '--no-install-recommends', '-o', 'Dpkg::Options::=--force-confdef', '-o', 'Dpkg::Options::=--force-confold', 'install', *FEATURES[sys.argv[1]]]): print(f'$ {" ".join(args)}', flush=True) if subprocess.run(args, env=environment).returncode != 0: sys.exit(f'install-packages: {args[0]} failed') - subprocess.run(['systemctl', 'restart', '--no-block', 'linux-manager-setup.service']) + lock.close() + linuxmanager.request_setup() return 0 diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager.py b/debian-package/src/usr/lib/linux-manager/linuxmanager.py index 0e66537..93c354a 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager.py @@ -12,8 +12,10 @@ import os import pathlib import re import shutil +import subprocess import sys import tempfile +import time import urllib.parse import jinja2 @@ -27,12 +29,21 @@ import linuxmanager_ldap import linuxmanager_pki import linuxmanager_platforms import linuxmanager_status -from linuxmanager_net import DEFAULT_LISTEN, LISTEN_CHOICES, LOOPBACK, ConfigError, detect_interfaces, interface_addresses, ip_output +from linuxmanager_net import DEFAULT_LISTEN, LISTEN_CHOICES, LOOPBACK, MANAGER_LOOPBACK_PORT, METRICS_LOOPBACK_PORT, \ + WEB_LOOPBACK_PORT, ConfigError, detect_interfaces, interface_addresses, ip_output CONFIG_FILE = pathlib.Path('/etc/linux-manager/linux-manager.json') CONFIG_LOCK = pathlib.Path('/run/linux-manager/config.lock') #: What setup resolved and runs, for the web service (setup's refresh_web). WEB_STATE = pathlib.Path('/run/linux-manager/web.json') +#: The unit of linux-manager-setup, which request_setup runs. +SETUP_UNIT = 'linux-manager-setup.service' +#: The lock under which a run of setup is requested and a run of setup decides whether to run again. +SETUP_LOCK = pathlib.Path('/run/linux-manager/setup.lock') +#: The lock a run of setup holds while it applies the configuration. +SETUP_RUNNING = pathlib.Path('/run/linux-manager/setup.running') +#: The file that asks a run of setup in progress to run once more when it ends. +SETUP_REQUEST = pathlib.Path('/run/linux-manager/setup.request') TEMPLATE_DIR = pathlib.Path('/usr/share/linux-manager/templates') SWANCTL_CONF_D = pathlib.Path('/etc/swanctl/conf.d') @@ -68,14 +79,17 @@ SCHEMA = { 'status_content': 'basic', 'shell': False, 'shell_idle_minutes': 15, 'shell_auth_timeout': 15, 'log_files': []}, 'ssh': {'ldap_login': False}, - 'https': {'enabled': True, 'email': '', 'web_port': 7444, 'manager_port': 7443, 'caddy_source': 'ubuntu', - 'acme_staging': False}, + 'https': {'enabled': True, 'email': '', 'web_port': 7444, 'manager_port': 7443, + 'disable_auto_redirect': False, 'acme_staging': False, 'certificate': 'self-signed', 'self_signed_days': 365, + 'acme_provider': 'letsencrypt', 'acme_url': '', 'acme_eab_key_id': '', 'acme_eab_mac_key': '', + 'zerossl_api_key': ''}, 'oidc': {'enabled': False}, 'sites': {'enabled': False, 'upload_max_mb': 512, 'webdav': False, 'webdav_port': 7445}, 'dns': {'enabled': False, 'secondary': '', 'listen': 'external', 'ttl': 300}, 'pki': {'root_name': 'Linux Manager Root CA', 'root_days': 7300, 'ca_days': 3650, 'key': 'rsa-4096', 'crl_days': 7, 'root_crl_days': 180, 'publish': ['http'], 'p2s_name': 'Linux Manager VPN CA', - 's2s_name': 'Linux Manager Site-to-Site CA', 'issuing_cas': {}, 'templates': {}, + 's2s_name': 'Linux Manager Site-to-Site CA', 'servers_name': 'Linux Manager Servers CA', + 'issuing_cas': {}, 'templates': {}, 'extended_key_usages': {}, 'root': 'local', 'simple_ca_url': ''}, 'metrics': {'enabled': True, 'listen': 'internal', 'port': 9464, 'https_port': 9465, 'service_account': 'metrics', 'otlp_endpoint': '', 'otlp_username': '', 'otlp_password': '', @@ -143,6 +157,16 @@ LOG_FILES_MAX = 32 #: The port rclone serves WebDAV on, on the loopback address, behind Caddy. WEBDAV_LOOPBACK_PORT = 7446 +#: The installable components, managed on the Manager's System tab: name -> (section, setting) of their switch and the +#: packages linux-manager-install@ installs from the Ubuntu archive while the switch is on. +STRONGSWAN_PACKAGES = ('strongswan-swanctl', 'charon-systemd', 'libstrongswan-extra-plugins', 'libcharon-extra-plugins') +COMPONENTS = { + 'vpn': (('vpn', 'enabled'), (*STRONGSWAN_PACKAGES, 'openvpn', 'openvpn-auth-ldap', 'wireguard-tools', 'dnsmasq-base')), + 'router': (('router', 'enabled'), STRONGSWAN_PACKAGES), + 'dns': (('dns', 'enabled'), ('pdns-server', 'pdns-backend-pgsql')), + 'webdav': (('sites', 'webdav'), ('rclone',)), +} + #: The largest sites.upload_max_mb, 10 GiB. UPLOAD_MAX_MB = 10240 @@ -167,17 +191,20 @@ BOOTSTRAP_PORTS = (17081,) MANAGER_CONFIG = pathlib.Path('/etc/linux-manager/manager.json') MANAGER_PORT = 7080 -#: Where linux-manager-setup installs Caddy from, https.caddy_source: the Ubuntu archive or Caddy's own repository. -CADDY_SOURCES = ('ubuntu', 'upstream') - #: The ACME directory of Let's Encrypt's staging environment, Caddy's only CA while https.acme_staging is true. ACME_STAGING_CA = 'https://acme-staging-v02.api.letsencrypt.org/directory' -#: Caddy's own repository, which https.caddy_source upstream configures: the source, its signing key and their URLs. -CADDY_APT_SOURCE = pathlib.Path('/etc/apt/sources.list.d/caddy-stable.sources') -CADDY_KEYRING = pathlib.Path('/etc/apt/keyrings/caddy-stable.asc') -CADDY_KEY_URL = 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' -CADDY_REPOSITORY = 'https://dl.cloudsmith.io/public/caddy/stable/deb/debian' +#: The ACME directory of Let's Encrypt's production CA. +ACME_PRODUCTION_CA = 'https://acme-v02.api.letsencrypt.org/directory' + +#: Where the certificate of wan.local_fqdn comes from, https.certificate: ACME, a self-signed certificate, the +#: Servers Issuing CA (servers), or a certificate of another CA, imported; self-signed when not set. A new installation's +#: configuration file has it empty (generate-config) until the first setup chooses ca or self-signed +#: (linuxmanager_pki.provision). +HTTPS_CERTIFICATES = ('acme', 'self-signed', 'ca', 'external') + +#: The ACME CA of the server and of the web sites with TLS acme, https.acme_provider. +ACME_PROVIDERS = ('letsencrypt', 'zerossl', 'custom') #: The key types of the CAs, pki.key, and of the templates. PKI_KEYS = ('rsa-2048', 'rsa-3072', 'rsa-4096', 'ec-p256', 'ec-p384') @@ -224,7 +251,7 @@ PKI_TEMPLATES = { 'vpn-server': {'key_usage': ['digital_signature', 'key_encipherment'], 'extended_key_usage': ['server_auth', 'ike_intermediate'], 'subject': 'dns', 'sans': ['dns', 'ip']}, 'vpn-user': {'extended_key_usage': ['client_auth'], 'subject': 'name', 'sans': ['dns', 'email']}, - 'site-to-site': {'key_usage': ['digital_signature', 'key_encipherment'], + 'mtls': {'key_usage': ['digital_signature', 'key_encipherment'], 'extended_key_usage': ['server_auth', 'client_auth'], 'subject': 'dns', 'sans': ['dns', 'ip']}, 'server': {'key_usage': ['digital_signature', 'key_encipherment'], 'extended_key_usage': ['server_auth'], 'subject': 'dns', 'sans': ['dns', 'ip']}, @@ -234,8 +261,11 @@ PKI_TEMPLATES = { #: The templates only the server issues: its VPN server certificate and the users' certificates. ROUTER_TEMPLATES = ('vpn-server', 'vpn-user') -#: The built-in issuing CAs: name -> the pki option of the common name and the templates the CA issues. -BUILTIN_CAS = {'p2s': ('p2s_name', ['vpn-server', 'vpn-user']), 's2s': ('s2s_name', ['site-to-site'])} +#: The built-in issuing CAs: name -> the pki option of the common name and the templates the CA issues: the VPN, the +#: site-to-site connections, and the Servers Issuing CA of mTLS certificates, which also signs the server's HTTPS +#: certificate. +BUILTIN_CAS = {'p2s': ('p2s_name', ['vpn-server', 'vpn-user']), 's2s': ('s2s_name', ['mtls']), + 'servers': ('servers_name', ['mtls'])} #: A general-purpose issuing CA of pki.issuing_cas: option -> default, the type of the default being the required type. ISSUING_CA = {'name': '', 'templates': [], 'acme': False} @@ -350,6 +380,45 @@ def config_lock(): yield +def setup_lock(): + """The open SETUP_LOCK, held; closing it releases the lock.""" + SETUP_LOCK.parent.mkdir(parents=True, exist_ok=True) + handle = open(SETUP_LOCK, 'a', encoding='utf-8') + fcntl.flock(handle, fcntl.LOCK_EX) + return handle + + +def request_setup(wait=False): + """Have linux-manager-setup apply the configuration; with wait, True when it has applied it and its last run + succeeded, without wait, True when the run was requested. + + A run in progress is not cut short: it holds SETUP_RUNNING, and the request, SETUP_REQUEST, has it run once more + when it ends, however many requests it got. Without a run in progress the unit is restarted. The request is made + under SETUP_LOCK, under which a run of setup also decides whether to end, so no request is missed. + """ + with setup_lock(): + SETUP_REQUEST.touch() + with open(SETUP_RUNNING, 'a', encoding='utf-8') as running: + try: + fcntl.flock(running, fcntl.LOCK_EX | fcntl.LOCK_NB) + idle = True + except BlockingIOError: + idle = False + if idle: + restart = subprocess.run(['systemctl', 'restart', '--no-block', SETUP_UNIT], capture_output=True) + if restart.returncode != 0: + return False + # The unit's start job, the restarted run or the run in progress with its further runs, is waited for. + while wait: + state = subprocess.run(['systemctl', 'show', '-p', 'Job,ActiveState,Result', SETUP_UNIT], + capture_output=True, text=True).stdout + values = dict(line.partition('=')[::2] for line in state.splitlines()) + if not values.get('Job') and values.get('ActiveState') != 'activating': + return values.get('ActiveState') == 'active' and values.get('Result') == 'success' + time.sleep(1) + return True + + def save_config(data): """Write the settings to the configuration file, indented, with mode 0600, replacing it in one step. @@ -366,6 +435,19 @@ def save_config(data): raise +def choose_https_certificate(cfg, ctx, source): + """Write https.certificate, empty until then, as source into the configuration file, and into cfg and ctx for the + rest of the run: the first setup's choice of the server's HTTPS certificate.""" + with config_lock(): + data = read_settings() + section = data.get('https') + data['https'] = {**(section if isinstance(section, dict) else {}), 'certificate': source} + save_config(data) + cfg['https']['certificate'] = source + ctx['https_certificate'] = source + warn(f'https.certificate is set to {source}, chosen by the first setup') + + def _split_list(value): return [item.strip() for item in value.split(',') if item.strip()] @@ -586,9 +668,24 @@ def validate(cfg): if not item.startswith('/') or '/../' in f'{item}/': raise ConfigError(f'web.log_files: {item!r} is not an absolute path') - caddy_source = _get(cfg, 'https', 'caddy_source') - if caddy_source not in CADDY_SOURCES: - raise ConfigError(f'https.caddy_source: {caddy_source!r} is not one of {", ".join(CADDY_SOURCES)}') + if _get(cfg, 'https', 'certificate') not in ('', *HTTPS_CERTIFICATES): + raise ConfigError(f'https.certificate: {_get(cfg, "https", "certificate")!r} is not one of ' + f'{", ".join(HTTPS_CERTIFICATES)}, or empty for the next setup to choose') + if not 1 <= _get(cfg, 'https', 'self_signed_days') <= 3650: + raise ConfigError('https.self_signed_days must be 1 to 3650 days') + provider = _get(cfg, 'https', 'acme_provider') + if provider not in ACME_PROVIDERS: + raise ConfigError(f'https.acme_provider: {provider!r} is not one of {", ".join(ACME_PROVIDERS)}') + acme_url = _get(cfg, 'https', 'acme_url') + if provider == 'custom' and not acme_url: + raise ConfigError('https.acme_url is required while https.acme_provider is custom') + if acme_url: + parts = urllib.parse.urlsplit(acme_url) + if parts.scheme != 'https' or not parts.hostname or parts.fragment: + raise ConfigError('https.acme_url must be an https:// URL without a fragment') + for option in ('email', 'acme_url', 'acme_eab_key_id', 'acme_eab_mac_key', 'zerossl_api_key'): + if any(character.isspace() or character in '{}"' for character in _get(cfg, 'https', option)): + raise ConfigError(f'https.{option} must not hold spaces, braces or quotes') if _get(cfg, 'oidc', 'enabled') and not (_get(cfg, 'web', 'enabled') and _get(cfg, 'https', 'enabled') 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}) ' 'while p2s.enabled, openvpn.enabled or wireguard.enabled is true') - for option in ('root_name', 'p2s_name', 's2s_name'): + for option in ('root_name', 'p2s_name', 's2s_name', 'servers_name'): value = _get(cfg, 'pki', option) if not value or len(value) > CA_NAME_MAX or not value.isprintable(): raise ConfigError(f'pki.{option} must have 1 to {CA_NAME_MAX} printable characters') @@ -703,8 +800,8 @@ def validate(cfg): prefix = f'pki.issuing_cas.{name}' if not PKI_NAME.match(name) or name in BUILTIN_CAS or name in ('root', 'upstream'): raise ConfigError(f'{prefix}: an issuing CA name starts with a lowercase letter and has at most 31 ' - f'lowercase letters, digits and hyphens, and is not root, upstream, ' - f'{" or ".join(BUILTIN_CAS)}') + f'lowercase letters, digits and hyphens, and is not root, upstream or ' + f'{", ".join(BUILTIN_CAS)}') if not isinstance(authority, dict): raise ConfigError(f'{prefix} must be {TYPE_NAMES[dict]}') _check_options(authority, ISSUING_CA, prefix) @@ -727,6 +824,15 @@ def validate(cfg): taken = {web_port: 'web.port', ACME_HTTP_PORT: 'the HTTP challenge', 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_PORT in taken: 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') weight += 2 if ':' in item else 1 first, _, last = item.partition(':') - if _get(cfg, 'https', 'enabled'): - caddy_ports = (ACME_HTTP_PORT, *https_ports, *([HTTPS_DEFAULT_PORT] if 'https-default' in publish else [])) - for port in caddy_ports: - if int(first) <= port <= int(last or first): - raise ConfigError( - f'docker.exposed_ports: {item!r} takes port {port}, which Caddy serves while ' - 'https.enabled is true') + caddy_ports = (web_port, manager_port(), _get(cfg, 'metrics', 'port'), + *((ACME_HTTP_PORT, *https_ports, *([HTTPS_DEFAULT_PORT] if 'https-default' in publish else [])) + if _get(cfg, 'https', 'enabled') else ())) + for port in caddy_ports: + if int(first) <= port <= int(last or first): + raise ConfigError(f'docker.exposed_ports: {item!r} takes port {port}, which Caddy serves') if weight > DOCKER_PORT_LIMIT: raise ConfigError( 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): - """The issuing CAs, name -> {name, templates, acme, builtin}: p2s and s2s (BUILTIN_CAS) with their common names from - the pki section, then those of pki.issuing_cas, each filled from ISSUING_CA.""" + """The issuing CAs, name -> {name, templates, acme, builtin}: p2s, s2s and servers (BUILTIN_CAS) with their common names + from the pki section, then those of pki.issuing_cas, each filled from ISSUING_CA.""" found = {name: {'name': _get(cfg, 'pki', option), 'templates': list(templates), 'acme': False, 'builtin': True} for name, (option, templates) in BUILTIN_CAS.items()} for name, options in cfg['pki']['issuing_cas'].items(): @@ -870,7 +975,8 @@ def pki_base_urls(cfg): def manager_port(): - """The port of the Manager: port in its settings, or MANAGER_PORT when it is not set or not a port.""" + """The port of the Manager, Caddy's plain HTTP site of it: port in its settings, or MANAGER_PORT when it is not set + or not a port.""" try: port = json.loads(MANAGER_CONFIG.read_text(encoding='utf-8')).get('port') except (OSError, ValueError, AttributeError): @@ -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 +def manager_listen(): + """The interfaces the firewall opens the Manager's port on: listen in its settings, one of LISTEN_CHOICES, or + DEFAULT_LISTEN when it is not set or not one.""" + try: + choice = json.loads(MANAGER_CONFIG.read_text(encoding='utf-8')).get('listen') + except (OSError, ValueError, AttributeError): + return DEFAULT_LISTEN + return choice if choice in LISTEN_CHOICES else DEFAULT_LISTEN + + def oidc_issuer(cfg): """The issuer of the OpenID Provider: the web service's HTTPS site, without the port when it is HTTPS_DEFAULT_PORT.""" port = _get(cfg, 'https', 'web_port') @@ -1034,6 +1150,8 @@ def build_context(cfg, public_ip=None): 'mode': _get(cfg, 'general', 'mode') or 'manual', 'router_enabled': _get(cfg, 'router', 'enabled'), 'vpn_enabled': _get(cfg, 'vpn', 'enabled'), + 'router_installed': packages_installed(COMPONENTS['router'][1]), + 'vpn_installed': packages_installed(COMPONENTS['vpn'][1]), 'wan_iface': ext_iface, 'int_iface': int_iface, 'local_addrs': ', '.join(local_addrs), @@ -1080,15 +1198,24 @@ def build_context(cfg, public_ip=None): 'ldap_users': linuxmanager_ldap.USERS, 'web_enabled': _get(cfg, 'web', 'enabled'), 'web_port': _get(cfg, 'web', 'port'), + 'web_listen': _get(cfg, 'web', 'listen'), 'https_enabled': _get(cfg, 'https', 'enabled'), 'https_email': _get(cfg, 'https', 'email'), - 'https_acme_ca': ACME_STAGING_CA if _get(cfg, 'https', 'acme_staging') else '', + 'https_certificate': _get(cfg, 'https', 'certificate'), + 'https_acme_provider': _get(cfg, 'https', 'acme_provider'), + 'https_acme_url': (_get(cfg, 'https', 'acme_url') if _get(cfg, 'https', 'acme_provider') == 'custom' + else ACME_STAGING_CA if _get(cfg, 'https', 'acme_staging') else ACME_PRODUCTION_CA), + 'https_acme_eab': ((_get(cfg, 'https', 'acme_eab_key_id'), _get(cfg, 'https', 'acme_eab_mac_key')) + if _get(cfg, 'https', 'acme_eab_key_id') and _get(cfg, 'https', 'acme_eab_mac_key') + else None), + 'https_zerossl_api_key': _get(cfg, 'https', 'zerossl_api_key'), 'https_web_port': _get(cfg, 'https', 'web_port'), 'https_manager_port': _get(cfg, 'https', 'manager_port'), 'pki_publish': _get_list(cfg, 'pki', 'publish'), 'pki_acme': [name for name, authority in issuing_cas(cfg).items() if authority['acme']], 'metrics_enabled': _get(cfg, 'metrics', 'enabled'), 'metrics_port': _get(cfg, 'metrics', 'port'), + 'metrics_listen': _get(cfg, 'metrics', 'listen'), 'metrics_https_port': _get(cfg, 'metrics', 'https_port'), 'metrics_service_account': _get(cfg, 'metrics', 'service_account'), 'sites_enabled': _get(cfg, 'sites', 'enabled'), @@ -1101,8 +1228,8 @@ def build_context(cfg, public_ip=None): def s2s_ready(ctx): - """True when the router is on and any site_to_site connection is ready.""" - return bool(ctx['router_enabled'] and any(connection['ready'] for connection in ctx['connections'])) + """True when the router is on and installed and any site_to_site connection is ready.""" + return bool(ctx['router_enabled'] and ctx['router_installed'] and any(connection['ready'] for connection in ctx['connections'])) def routing_ready(ctx): @@ -1112,19 +1239,21 @@ def routing_ready(ctx): def p2s_ready(ctx): - """IKEv2 access needs the VPN on, its settings and the server's VPN server certificate, which the P2S CA issues.""" - return bool(ctx['vpn_enabled'] and ctx['p2s_enabled'] and ctx['p2s_address_pool'] and ctx['local_fqdn'] + """IKEv2 access needs the VPN on and installed, its settings and the server's VPN server certificate, which the P2S + CA issues.""" + return bool(ctx['vpn_enabled'] and ctx['vpn_installed'] and ctx['p2s_enabled'] and ctx['p2s_address_pool'] and ctx['local_fqdn'] and ctx['server_certificate']) def wg_ready(ctx): - """WireGuard needs the VPN on and its settings.""" - return bool(ctx['vpn_enabled'] and ctx['wg_enabled'] and ctx['wg_address']) + """WireGuard needs the VPN on and installed and its settings.""" + return bool(ctx['vpn_enabled'] and ctx['vpn_installed'] and ctx['wg_enabled'] and ctx['wg_address']) def openvpn_ready(ctx): - """OpenVPN needs the VPN on, its settings and the server's VPN server certificate, which the P2S CA issues.""" - return bool(ctx['vpn_enabled'] and ctx['openvpn_enabled'] and ctx['openvpn_pool'] and ctx['local_fqdn'] + """OpenVPN needs the VPN on and installed, its settings and the server's VPN server certificate, which the P2S CA + issues.""" + return bool(ctx['vpn_enabled'] and ctx['vpn_installed'] and ctx['openvpn_enabled'] and ctx['openvpn_pool'] and ctx['local_fqdn'] and ctx['server_certificate']) @@ -1150,6 +1279,25 @@ def webdav_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): """The name server answers for its domains while dns.enabled is true.""" return bool(ctx['dns_enabled']) @@ -1276,6 +1424,9 @@ def configure(cfg=None, public_ip=None): fail(str(failure)) except ldap.LDAPError as exc: notices = [f'the PKI is left as it is: the directory cannot be reached: {exc}'] + # Without the directory the first setup has no Servers Issuing CA to choose. + if not cfg['https']['certificate']: + choose_https_certificate(cfg, ctx, 'self-signed') for notice in notices: warn(notice) # The WireGuard peers of the users; None keeps those of wg0.conf while the directory cannot be reached. diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_backup.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_backup.py index 7e1018a..10f2849 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_backup.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_backup.py @@ -416,7 +416,8 @@ def restore(source, pbs, confirm): if result.returncode != 0: raise Failure(f'pg_restore of {item} failed: {result.stderr.decode(errors="replace").strip()}') subprocess.run(['systemctl', 'start', 'linux-manager-web.service'], capture_output=True) - command(['systemctl', 'restart', 'linux-manager-setup.service']) + if not linuxmanager.request_setup(wait=True): + raise Failure('linux-manager-setup failed; see journalctl -u linux-manager-setup') for unit in RESTORE_RESTARTS: subprocess.run(['systemctl', 'try-restart', unit], capture_output=True) subprocess.run(['ufw', 'reload'], capture_output=True) diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_dns.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_dns.py index 288ed98..2e777fc 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_dns.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_dns.py @@ -255,11 +255,11 @@ def domain_remove(name): def secondary_addresses(cfg): - """The addresses dns.secondary resolves to, which are notified of the zones' changes and may transfer them; none, - with a warning, while it is not set or does not resolve.""" + """The addresses dns.secondary resolves to, which are notified of the zones' changes and may transfer them; none while + it is not set, the domains then having the primary as their only name server, and none, with a warning, while it + does not resolve.""" secondary = cfg['dns']['secondary'].strip() if not secondary: - linuxmanager.warn('dns.secondary is not set: the domains have no secondary name server') return [] try: found = socket.getaddrinfo(secondary, 53, proto=socket.IPPROTO_UDP) diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_ldap.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_ldap.py index 31d8b19..3ffe489 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_ldap.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_ldap.py @@ -84,7 +84,10 @@ OVERLAYS = ('ppolicy', 'otp') #: 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, #: 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' #: certificates, its kind, template, names and expiry, and its revocation. SCHEMA_OID = '1.3.6.1.4.1.67380.10.1.2' @@ -134,6 +137,9 @@ SCHEMA_ATTRIBUTE_TYPES = ( f"{_OCTETS} )", f"( {SCHEMA_OID}.1.25 NAME 'linuxManagerUpstreamName' DESC 'Linux Manager: the Simple CA issuing CA of the token' " 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 = ( 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 ) )", 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 ) )", + 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. @@ -173,7 +182,7 @@ CONSOLE_HOMES = '/home' #: The ACLs of the database, in order. 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=oathSecret by dn.exact="{MANAGER}" =w by * none', f'to dn.subtree="{USERS}" by dn.exact="{MANAGER}" manage by * read', diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_net.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_net.py index 69a5e69..402747a 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_net.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_net.py @@ -7,15 +7,22 @@ this module too. import pathlib import subprocess -#: The values of web.listen and of the Manager's listen: the interfaces a service listens on. +#: The values of web.listen, metrics.listen and of the Manager's listen: the interfaces the firewall opens a service's +#: port on. LISTEN_CHOICES = ('internal', 'external', 'both') -#: The interfaces a service listens on when it is not set. +#: The interfaces a service's port is open on when it is not set. DEFAULT_LISTEN = 'both' -#: The address every service also listens on, where the HTTPS proxy calls it. +#: The address the services listen on, where Caddy calls them. LOOPBACK = '127.0.0.1' +#: The ports the web service, the manager on the server and the metrics service listen on, on LOOPBACK only; Caddy +#: serves web.port, the manager's port and metrics.port and calls them. +WEB_LOOPBACK_PORT = 7091 +MANAGER_LOOPBACK_PORT = 7090 +METRICS_LOOPBACK_PORT = 9474 + class ConfigError(Exception): """A setting is present but malformed.""" @@ -68,6 +75,12 @@ def _is_virtual(name): return '/devices/virtual/' in str(link.resolve()) +def nics(): + """The names of the network interfaces with a device behind them; loopback and virtual interfaces are left out.""" + directory = pathlib.Path('/sys/class/net') + return sorted(path.name for path in directory.iterdir() if not _is_virtual(path.name)) if directory.is_dir() else [] + + def _addressed_interfaces(): """Names of the NICs holding at least one IPv4 address; virtual interfaces are left out.""" names = [] @@ -147,7 +160,7 @@ def listen_addresses(configuration, choice): """The addresses a service listens on for choice of LISTEN_CHOICES, from linux-manager.json read as configuration. The internal address comes first; an address not known yet is left out. A choice that is not - one of LISTEN_CHOICES is DEFAULT_LISTEN. LOOPBACK is not among them; web_listen adds it. + one of LISTEN_CHOICES is DEFAULT_LISTEN. LOOPBACK is not among them. Without the router (router.enabled false) the external interface is also the internal side. """ if choice not in LISTEN_CHOICES: @@ -165,20 +178,9 @@ def listen_addresses(configuration, choice): return list(dict.fromkeys(address for address in addresses if address)) -def web_listen(configuration, default_port): - """Where the web service listens, from linux-manager.json read as configuration, as ([(address, port), ...], ''). - - The addresses are those of the interfaces web.listen names (listen_addresses), then - LOOPBACK, the port web.port, else default_port. While web.enabled is false or no address of - an interface is known, the answer is ([], the reason). - """ - web = _section(configuration, 'web') - if web.get('enabled', True) is False: +def web_listen(configuration): + """Where the web service listens, from linux-manager.json read as configuration: ([(LOOPBACK, WEB_LOOPBACK_PORT)], ''), + Caddy serving web.port, or ([], the reason) while web.enabled is false.""" + if _section(configuration, 'web').get('enabled', True) is False: return [], 'the web service is disabled in the configuration' - port = web.get('port', default_port) - if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535: - port = default_port - addresses = listen_addresses(configuration, web.get('listen', DEFAULT_LISTEN)) - if not addresses: - return [], 'the addresses to listen on are not known yet' - return [(address, port) for address in [*addresses, LOOPBACK]], '' + return [(LOOPBACK, WEB_LOOPBACK_PORT)], '' diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_pki.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_pki.py index 0a5bac5..adb071b 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_pki.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_pki.py @@ -1,7 +1,8 @@ """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' -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 the local socket. Each CA is an entry cn= of class linuxManagerAuthority, with its certificate, key, CRL and CRL number. Each certificate a CA issued is an entry serialNumber= 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') #: 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 #: 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): """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 local_id_mode; None while such an identity is not known yet.""" fqdn = ctx['local_fqdn'] - if name == 'vpn-server': + if name in ('vpn-server', 'https'): return fqdn, [fqdn] names = [fqdn] for connection in ctx['connections']: @@ -663,6 +669,22 @@ def check_source(cfg, entry): '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): return base64.urlsafe_b64decode(text + '=' * (-len(text) % 4)) @@ -843,6 +865,188 @@ def fetch_crls(connection): 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): """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 cannot sign). An issuing CA that pki.issuing_cas no longer names is retired; its certificate is revoked on the root CRL, or, with an external root, a notice says to revoke it there. Stale CRLs are signed again or, with simple-ca, - fetched, the server's certificates issued or renewed (ensure_router_cert), and the copies of PUBLISH_DIR written. A + 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 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: check_source(cfg, authority(connection, 'root')) + check_names(cfg, connection) notice = take_setup_code(cfg) if notice: notices.append(notice) @@ -950,9 +1157,14 @@ def provision(cfg, ctx): refresh_crls(connection, cfg, force) if pki['root'] == 'simple-ca': 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: - 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) + notices.extend(ensure_host_cert(connection, cfg)) publish(connection) p2s = authority(connection, 'p2s') missing = connection.search_s(linuxmanager_ldap.USERS, ldap.SCOPE_ONELEVEL, @@ -1013,8 +1225,9 @@ def install_crls(connection): def reload_crls(connection): - """Install the CRLs, and have strongSwan load them when they changed; OpenVPN reads its file when it changes.""" - if install_crls(connection): + """Install the CRLs, and have strongSwan load them when they changed and it is installed; OpenVPN reads its file when + it changes.""" + if install_crls(connection) and shutil.which('swanctl'): 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) if not is_ca(cert): 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}) record(connection, cert, 'root', 'ca') sign_crl(connection, cfg, name) @@ -1351,15 +1567,19 @@ def import_root_crl(cfg, data): def maintain(cfg): """Sign the stale CRLs again or, with simple-ca, fetch them, publish and install them; the notices, and True when - one of the server's certificates is due for renewal or, with simple-ca, an issuing CA waits for Simple CA, which - linux-manager-setup does.""" + one of the server's certificates is due for renewal, the HTTPS certificate among them while the server issues it, + or, with simple-ca, an issuing CA waits for Simple CA, which linux-manager-setup does.""" with directory() as connection: refresh_crls(connection, cfg) notices = fetch_crls(connection) if cfg['pki']['root'] == 'simple-ca' else [] publish(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)) - 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') 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 @@ -1374,7 +1594,8 @@ def acme_url(cfg, name): def status(cfg): """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() soon = moment + datetime.timedelta(days=WARN_DAYS) warnings = [] @@ -1399,7 +1620,9 @@ def status(cfg): '(&(objectClass=linuxManagerAuthority)(linuxManagerRetired=*))', ['cn', 'linuxManagerRetired', 'cACertificate;binary']) 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'] 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(): entry = entries[name] 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({ 'name': name, 'common_name': settings['name'], 'state': kind, 'builtin': settings['builtin'], + 'component': component, 'templates': settings['templates'], 'acme': settings['acme'], '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, @@ -1464,4 +1690,11 @@ def status(cfg): for cert in router_certs: if utc(cert, 'not_valid_after') <= soon: warnings.append(f'the server certificate {common_name(cert)} expires on {iso(utc(cert, "not_valid_after"))}') + 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} diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_sites.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_sites.py index 8cd1332..80d5080 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_sites.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_sites.py @@ -14,7 +14,7 @@ public (wan.public_address), internal or external. A site may use wan.local_fqdn stays where the domain of wan.local_fqdn is. The sites are served while sites.enabled is true; linux-manager-setup writes Caddy's configuration and opens the ports. A -site is changed only through this module, which checks it (check), and its callers then restart linux-manager-setup. +site is changed only through this module, which checks it (check), and its callers then request a run of linux-manager-setup. The files of a site are read and written by path relative to its folder; resolve() refuses a path that leaves it. receive() writes a file from a stream, extract() a zip archive into a folder; both stop at sites.upload_max_mb. @@ -177,7 +177,9 @@ def taken_ports(cfg): cfg['https']['manager_port']: 'https.manager_port', cfg['metrics']['port']: 'metrics.port', cfg['metrics']['https_port']: 'metrics.https_port', linuxmanager.manager_port(): 'the Manager', cfg['sites']['webdav_port']: 'sites.webdav_port', linuxmanager.WEBDAV_LOOPBACK_PORT: 'rclone\'s WebDAV', - 53: 'DNS'} + linuxmanager.WEB_LOOPBACK_PORT: 'the web service behind Caddy', + linuxmanager.MANAGER_LOOPBACK_PORT: 'the Manager behind Caddy', + linuxmanager.METRICS_LOOPBACK_PORT: 'the metrics service behind Caddy', 53: 'DNS'} for port in linuxmanager.BOOTSTRAP_PORTS: taken[port] = 'the bootstrap service' if cfg['openvpn']['protocol'] == 'tcp': diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_ui.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_ui.py index ccc4ade..6dcd722 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_ui.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_ui.py @@ -4,12 +4,13 @@ The settings file (CONFIG_FILE unless another is given) sets, all optional: rout listen, bind, port, terraform_dir and iac_tool. bind is the one address to listen on. Without router_url, terraform_dir names the Terraform root module whose output router_web_url gives the URL of the server's web service, read with iac_tool, terraform (the default) or tofu; dev.sh uses -it to run the manager on a workstation. A setting that is not given comes from the server's -configuration, ROUTER_CONFIG_FILE: without bind the manager listens on the addresses of the -interfaces listen names, internal, external or both (the default), and on the loopback address, -where the server's HTTPS proxy calls it, router_url is the first address and web.port of the -server's web service, and database is the DATABASE database on this host, with the password in -DATABASE_SECRET. +it to run the manager on a workstation. On the server, where ROUTER_CONFIG_FILE is, the manager +listens without bind on linuxmanager_net.MANAGER_LOOPBACK_PORT of the loopback address, where +Caddy calls it: Caddy serves port over plain HTTP and https.manager_port over HTTPS, and the +firewall opens port on the interfaces listen names, internal, external or both (the default). +A setting that is not given comes from the server's configuration: router_url is the web +service on its loopback port, and database is the DATABASE database on this host, with the +password in DATABASE_SECRET. """ import json @@ -30,7 +31,7 @@ DATABASE_SECRET = '/etc/linux-manager/manager-database.secret' #: The role and the database the manager creates on the server. DATABASE = 'linux-manager-ui' -#: The port when port is not set. +#: The port when port is not set: the port of bind, or on the server Caddy's plain HTTP port of the manager. DEFAULT_PORT = 7080 #: The port of the server's web service when web.port is not set. @@ -94,16 +95,16 @@ def output_value(outputs, name): def listen(config_file): - """Where the manager listens, read now: ([(address, port), ...], ''), or ([], the reason) while no address is known.""" + """Where the manager listens, read now: [(bind, port)] with bind, else on the server + [(LOOPBACK, MANAGER_LOOPBACK_PORT)], as ([(address, port), ...], ''), or ([], the reason) off the server without + bind.""" configuration = read_json(config_file) bind = text_setting(configuration, 'bind') - port = port_setting(configuration.get('port'), DEFAULT_PORT) if bind: - return [(bind, port)], '' - addresses = linuxmanager_net.listen_addresses(read_json(ROUTER_CONFIG_FILE), text_setting(configuration, 'listen')) - if not addresses: - return [], "the server's addresses to listen on are not known yet" - return [(address, port) for address in [*addresses, linuxmanager_net.LOOPBACK]], '' + return [(bind, port_setting(configuration.get('port'), DEFAULT_PORT))], '' + if os.path.exists(ROUTER_CONFIG_FILE): + return [(linuxmanager_net.LOOPBACK, linuxmanager_net.MANAGER_LOOPBACK_PORT)], '' + return [], f'bind is not set, and {ROUTER_CONFIG_FILE} is not here' def settings(config_file): @@ -128,20 +129,20 @@ def settings(config_file): if password: result['database'] = f'host=localhost dbname={DATABASE} user={DATABASE} password={password}' if not result['router_url']: - targets, _ = linuxmanager_net.web_listen(router, ROUTER_PORT) + targets, _ = linuxmanager_net.web_listen(router) if targets: result['router_url'] = f'http://{targets[0][0]}:{targets[0][1]}' result['router_url'] = result['router_url'].rstrip('/') return result -def status_url(config_file, host, address, https): - """The URL of the server's status page for a browser that reached the manager as host on its address. +def status_url(config_file, host, https): + """The URL of the server's status page for a browser that reached the manager as host. On the server, while neither router_url nor terraform_dir is set, it has host, without its port, so the link works by whatever name or address the browser used: with https, a call - through the server's HTTPS proxy, https and https.web_port; else, while the server's web - service listens on address, http and web.port. Otherwise it is router_url, or '' without one. + through Caddy's HTTPS site, https and https.web_port; else, while the web service is enabled, + http and web.port, Caddy's plain HTTP site. Otherwise it is router_url, or '' without one. """ configuration = read_json(config_file) try: @@ -155,13 +156,21 @@ def status_url(config_file, host, address, https): if https: options = router.get('https') if isinstance(router.get('https'), dict) else {} return f'https://{name}:{port_setting(options.get("web_port"), ROUTER_HTTPS_PORT)}' - targets, _ = linuxmanager_net.web_listen(router, ROUTER_PORT) - ports = [port for listened, port in targets if listened == address] - if ports: - return f'http://{name}:{ports[0]}' + web = router.get('web') if isinstance(router.get('web'), dict) else {} + if web.get('enabled', True) is not False: + return f'http://{name}:{port_setting(web.get("port"), ROUTER_PORT)}' return settings(config_file)['router_url'] +def plain_site(config_file): + """The manager's plain HTTP site on the server, served by Caddy: {port, listen}, its port and the interfaces the + firewall opens it on, from the settings, with DEFAULT_PORT and linuxmanager_net.DEFAULT_LISTEN when not set.""" + configuration = read_json(config_file) + listen = text_setting(configuration, 'listen') + return {'port': port_setting(configuration.get('port'), DEFAULT_PORT), + 'listen': listen if listen in linuxmanager_net.LISTEN_CHOICES else linuxmanager_net.DEFAULT_LISTEN} + + def serve(wanted, handler, log, interval): """Work out where to listen every interval seconds with wanted, and run an HTTP server of handler at each place. diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_users.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_users.py index f427077..4bf1ab4 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_users.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_users.py @@ -84,6 +84,7 @@ import uuid import ldap import ldap.filter import ldap.modlist +from ldap.controls import RequestControl import pyotp from cryptography import x509 from cryptography.hazmat.primitives import hashes, serialization @@ -150,6 +151,8 @@ GROUP_ATTRIBUTES = ['cn', 'description', 'member'] DESCRIPTION_MAX = 256 #: The value of pwdAccountLockedTime that disables an account until it is enabled. LOCKED = linuxmanager_ldap.DISABLED.encode() +#: The OID of the Relax Rules control. +RELAX_RULES = '1.3.6.1.4.1.4203.666.5.12' #: The group whose members manage the server through the web service. ADMIN_GROUP = 'admins' #: The digits of a TOTP code given to login(). @@ -720,7 +723,7 @@ def update(connection, name, values): def apply_wireguard(): """Have linux-manager-setup write the WireGuard peers of the users into wg0.conf, without waiting for it.""" - subprocess.run(['systemctl', 'restart', '--no-block', 'linux-manager-setup.service'], capture_output=True) + linuxmanager.request_setup() def update_service(connection, name, values): @@ -793,14 +796,15 @@ def enable(connection, name): def unlock(connection, name): - """End a lockout after failed binds and clear the failure count; a disabled user stays disabled.""" + """End a lockout after failed binds and clear the failure count, with the Relax Rules control; a disabled user + stays disabled.""" entry(connection, name) current = connection.search_s(dn_of(name), ldap.SCOPE_BASE, attrlist=['pwdAccountLockedTime', 'pwdFailureTime'])[0][1] changes = [(ldap.MOD_DELETE, 'pwdFailureTime', None)] if 'pwdFailureTime' in current else [] if 'pwdAccountLockedTime' in current and current['pwdAccountLockedTime'] != [LOCKED]: changes.append((ldap.MOD_DELETE, 'pwdAccountLockedTime', None)) if changes: - connection.modify_s(dn_of(name), changes) + connection.modify_ext_s(dn_of(name), changes, serverctrls=[RequestControl(RELAX_RULES, True)]) return summary(entry(connection, name)) diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/__init__.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/__init__.py index ea36487..1f47971 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/__init__.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/__init__.py @@ -54,17 +54,20 @@ Pages: /sites the web sites Caddy serves: the settings of sites, list, add, change and remove (see sites()), and the files of each: list, download, upload, extract a zip archive, create a folder, rename and remove (see Handler.site_files()); a member of a site's editors group may use the site's files + /components + the installable components, the VPN, the router, the name server and WebDAV: their switches and + whether their packages are installed (see components()) /dns the primary name server of the server's domains: its settings, and the domains: add, change and remove, each with the records it serves and its manual records (see dns()) /postgresql the databases of each PostgreSQL cluster on the server with their sizes, as JSON (see postgresql_databases()); /config has the clusters' settings /.well-known/openid-configuration, /oidc/... - while oidc.enabled is true, the OpenID Provider (linuxmanager_oidc), answered only on the - loopback address, where Caddy passes the requests of the HTTPS site; POST /oidc/login counts - towards the limit of /auth calls + while oidc.enabled is true, the OpenID Provider (linuxmanager_oidc), answered only for Caddy's + calls of the HTTPS site, from the loopback address with X-Forwarded-Proto https; POST + /oidc/login counts towards the limit of /auth calls -/status/full, /config, /metrics/history, /metrics/settings, /postgresql, /users, /service-accounts, /groups, /site-to-site, /backup, /remote-access, /ca, /logs, /sites, /dns, /shell and /account need an HS256 JWT in an Authorization: Bearer header signed +/status/full, /config, /metrics/history, /metrics/settings, /postgresql, /users, /service-accounts, /groups, /site-to-site, /backup, /remote-access, /ca, /logs, /sites, /dns, /components, /shell and /account need an HS256 JWT in an Authorization: Bearer header signed with linuxmanager_auth.WEB_KEY (see linuxmanager_auth.verify). A token of /auth names a user in sub; /account serves that user, and the other paths need a member of linuxmanager_users.ADMIN_GROUP. A token of linux-manager-token has the admin claim and names no user; it may call every path but diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/backup.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/backup.py index 5a1cdc8..2d88e3c 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/backup.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/backup.py @@ -36,7 +36,7 @@ def backup(method, path, body): current secret POST /backup/run start a backup now, without waiting for it; 409 while one runs - A change is made as /site-to-site makes one, and applied by restarting linux-manager-setup without waiting for it. + A change is made as /site-to-site makes one, and applied by a run of linux-manager-setup, without waiting for it. """ if body == 'invalid' or (body is not None and not isinstance(body, dict)): return 400, {'error': 'the body must be a JSON object'} @@ -80,5 +80,5 @@ def backup(method, path, body): return 500, {'error': f'the configuration cannot be written: {exc}'} except SystemExit as exc: return 500, {'error': str(exc.code)} - run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service') + linuxmanager.request_setup() return 200, {'settings': backup_settings(cfg['backup'])} diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/common.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/common.py index ed30b5d..c5f7da9 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/common.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/common.py @@ -1,6 +1,6 @@ """What the modules of the web service share: the paths of the configuration and of the state linux-manager-setup writes, the limit of request bodies, the HTTP statuses of the failures of the server's modules, reading the configuration and -the state, changing a section of the configuration, the state of a unit, and the log.""" +the state, changing settings of the configuration, the state of a unit, and the log.""" import json import sys @@ -59,15 +59,17 @@ def unit_state(unit): return result.stdout.strip() if result and result.stdout.strip() else 'unknown' -def section_change(name, body): - """Change any of the settings of the configuration's section as /backup changes its own; the section, or the HTTP - status and the error document as a tuple.""" - settings = {option: body[option] for option in linuxmanager.SCHEMA[name] if option in body} +def settings_change(changes): + """Change settings of sections of the configuration in one step, section -> {setting: value}, keeping only the + settings of SCHEMA, validated as a whole, and run setup; the configuration, or the HTTP status and the error document + as a tuple.""" try: with linuxmanager.config_lock(): data = linuxmanager.read_settings() - current = data.get(name) - data[name] = {**(current if isinstance(current, dict) else {}), **settings} + for name, body in changes.items(): + current = data.get(name) + data[name] = {**(current if isinstance(current, dict) else {}), + **{option: body[option] for option in linuxmanager.SCHEMA[name] if option in body}} cfg = linuxmanager.with_defaults(data) linuxmanager.validate(cfg) linuxmanager.save_config(data) @@ -77,8 +79,15 @@ def section_change(name, body): return 500, {'error': f'the configuration cannot be written: {exc}'} except SystemExit as exc: return 500, {'error': str(exc.code)} - run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service') - return cfg[name] + linuxmanager.request_setup() + return cfg + + +def section_change(name, body): + """Change any of the settings of the configuration's section as /backup changes its own; the section, or the HTTP + status and the error document as a tuple.""" + changed = settings_change({name: body}) + return changed if isinstance(changed, tuple) else changed[name] def log(message): diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/components.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/components.py new file mode 100644 index 0000000..122647e --- /dev/null +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/components.py @@ -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/ 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@), 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)} diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/connectivity.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/connectivity.py index 71bec8f..a2e852a 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/connectivity.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/connectivity.py @@ -3,7 +3,7 @@ import ipaddress import linuxmanager -from linuxmanager_status import established_each, run +from linuxmanager_status import established_each from .common import section @@ -37,7 +37,7 @@ def site_to_site(method, path, body): DELETE /site-to-site/ remove the connection A change is made holding linuxmanager.config_lock, checked as linux-manager-setup checks the configuration (400 with - the reason), written with linuxmanager.save_config, and applied by restarting linux-manager-setup without waiting for it. + the reason), written with linuxmanager.save_config, and applied by a run of linux-manager-setup, without waiting for it. """ if body == 'invalid' or (body is not None and not isinstance(body, dict)): return 400, {'error': 'the body must be a JSON object'} @@ -84,7 +84,7 @@ def site_to_site(method, path, body): return 500, {'error': f'the configuration cannot be written: {exc}'} except SystemExit as exc: return 500, {'error': str(exc.code)} - run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service') + linuxmanager.request_setup() if method == 'DELETE': return 200, {'name': name, 'removed': True} return (201 if method == 'POST' else 200), connection_of(name, cfg['site_to_site'][name], None) @@ -121,7 +121,7 @@ def remote_access(state, method, path, body): configuration needs of the server (wireguard_server) PUT /remote-access/ change any of the settings of the system's section; answers the section - A change is made as /site-to-site makes one, and applied by restarting linux-manager-setup without waiting for it. + A change is made as /site-to-site makes one, and applied by a run of linux-manager-setup, without waiting for it. """ if body == 'invalid' or (body is not None and not isinstance(body, dict)): return 400, {'error': 'the body must be a JSON object'} @@ -151,5 +151,5 @@ def remote_access(state, method, path, body): return 500, {'error': f'the configuration cannot be written: {exc}'} except SystemExit as exc: return 500, {'error': str(exc.code)} - run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service') + linuxmanager.request_setup() return 200, cfg[system] diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/dns.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/dns.py index e62f43a..a1bc783 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/dns.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/dns.py @@ -2,7 +2,6 @@ import linuxmanager import linuxmanager_dns -from linuxmanager_status import run from .common import section_change, unit_state @@ -30,7 +29,7 @@ def dns(method, path, query, body): DELETE /dns/domains//records remove the manual records of name= and type=, with content= only that one - A change is applied by restarting linux-manager-setup without waiting for it. + A change is applied by a run of linux-manager-setup, without waiting for it. """ if body == 'invalid' or (body is not None and not isinstance(body, dict)): return 400, {'error': 'the body must be a JSON object'} @@ -80,5 +79,5 @@ def dns(method, path, query, body): return 500, {'error': str(exc)} except SystemExit as exc: return 500, {'error': str(exc.code)} - run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service') + linuxmanager.request_setup() return code, document diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/handler.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/handler.py index bcdeab2..fd1b7ef 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/handler.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/handler.py @@ -18,11 +18,12 @@ import linuxmanager_sites from .auth import auth, auth_wait, refusal from .backup import backup from .common import BODY_LIMIT, CONFIG_FILE, current, log, read_json, section +from .components import components from .connectivity import remote_access, site_to_site from .dns import dns from .identities import account, groups, service_accounts, users from .logs import logs -from .https import https_settings +from .https import PATHS as HTTPS_PATHS, https from .metrics import metrics_history, metrics_settings from .pki import PUBLISHED, ca from .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'): self.close_connection = True directory = next((name for name in ('users', 'service-accounts', 'groups', 'account', 'site-to-site', 'backup', - 'ca', 'shell', 'remote-access', 'logs', 'sites', 'dns') + 'ca', 'shell', 'remote-access', 'logs', 'sites', 'dns', 'components') if path == f'/{name}' or path.startswith(f'/{name}/')), None) - protected = path in ('/status/full', '/config', '/metrics/history', '/metrics/settings', '/https/settings', + protected = path in ('/status/full', '/config', '/metrics/history', '/metrics/settings', *HTTPS_PATHS, '/postgresql') or \ directory is not None signing = path in ('/auth', '/auth/passkey', '/auth/passkey/complete', '/auth/refresh', '/auth/logout') oidc = (path == '/.well-known/openid-configuration' or path.startswith('/oidc/')) and \ - self.server.server_address[0] == linuxmanager_net.LOOPBACK + self.client_address[0] == linuxmanager_net.LOOPBACK and self.headers.get('X-Forwarded-Proto') == 'https' files = SITE_FILES.match(path) if directory == 'sites' else None query = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query) state = current() if protected or signing else {} @@ -115,8 +116,8 @@ class Handler(BaseHTTPRequestHandler): elif path == '/metrics/settings': code, document = metrics_settings(self.command, payload) body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json' - elif path == '/https/settings': - code, document = https_settings(self.command, payload) + elif path in HTTPS_PATHS: + code, document = https(self.command, path, payload) body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json' elif directory == 'shell' and (path, self.command) == ('/shell', 'GET'): return shell(self, claims.get('sub')) @@ -160,6 +161,9 @@ class Handler(BaseHTTPRequestHandler): elif directory == 'dns': code, document = dns(self.command, path, query, payload) body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json' + elif directory == 'components': + code, document = components(self.command, path, payload) + body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json' elif directory == 'service-accounts': code, document = service_accounts(self.command, path, payload) body, kind = json.dumps(document, indent=2).encode() + b'\n', 'application/json' diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/https.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/https.py index 8c932af..6c486ca 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/https.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/https.py @@ -1,33 +1,82 @@ -"""/https/settings: the settings of HTTPS, of which the API changes the CA of Caddy's certificates.""" +"""/https: the settings of HTTPS and the server's own HTTPS certificate.""" + +import base64 +import binascii + +import ldap import linuxmanager +import linuxmanager_pki -from .common import section_change +from .common import PKI_STATUS, section_change #: The settings of the https section PUT /https/settings changes. -CHANGEABLE = ('acme_staging',) +CHANGEABLE = ('acme_staging', 'certificate', 'self_signed_days', '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 _set instead. +SECRETS = ('acme_eab_mac_key', 'zerossl_api_key') + +#: The paths of /https. +PATHS = ('/https/settings', '/https/csr', '/https/certificate', '/https/pfx') -def https_settings(method, body): - """Answer a /https/settings request: the HTTP status and the JSON document. +def shown(settings): + """The https section without its secrets, each replaced by whether it is set.""" + return {**{key: value for key, value in settings.items() if key not in SECRETS}, + **{f'{key}_set': bool(settings[key]) for key in SECRETS}} - GET /https/settings {"settings"}: the https section - PUT /https/settings change acme_staging; the other settings of the section are changed on the server with - linux-manager-config-edit, and a body naming one is 400 - A change is applied by restarting linux-manager-setup without waiting for it. +def https(method, path, body): + """Answer a /https request: the HTTP status and the JSON document. + + GET /https/settings {"settings", "certificate"}: the https section, its secrets as _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)): return 400, {'error': 'the body must be a JSON object'} - if method in ('GET', 'HEAD'): - try: - return 200, {'settings': linuxmanager.load_config()['https']} - except SystemExit as exc: - return 500, {'error': str(exc.code)} - if method != 'PUT': - return 404, {'error': f'no route {method} /https/settings'} - others = sorted(set(body or {}) - set(CHANGEABLE)) - if others: - return 400, {'error': f'https.{", https.".join(others)}: changed on the server with linux-manager-config-edit only'} - changed = section_change('https', body or {}) - return changed if isinstance(changed, tuple) else (200, {'settings': changed}) + body = body or {} + try: + cfg = linuxmanager.load_config() + if path == '/https/settings' and method in ('GET', 'HEAD'): + return 200, {'settings': shown(cfg['https']), 'certificate': linuxmanager_pki.https_status(cfg)} + if path == '/https/settings' and method == 'PUT': + others = sorted(set(body) - set(CHANGEABLE)) + if others: + return 400, {'error': f'https.{", https.".join(others)}: changed on the server with ' + 'linux-manager-config-edit only'} + if 'certificate' in body and body['certificate'] not in linuxmanager.HTTPS_CERTIFICATES: + return 400, {'error': f'https.certificate must be one of {", ".join(linuxmanager.HTTPS_CERTIFICATES)}'} + changed = section_change('https', body) + return changed if isinstance(changed, tuple) else (200, {'settings': shown(changed)}) + with linuxmanager_pki.locked(): + if (path, method) == ('/https/csr', 'POST'): + return 200, linuxmanager_pki.https_csr(cfg) + if (path, method) == ('/https/certificate', 'PUT'): + document = linuxmanager_pki.import_https_certificate(cfg, body.get('certificate')) + elif (path, method) == ('/https/pfx', 'PUT'): + try: + data = base64.b64decode(body.get('pfx') or '', validate=True) + except (binascii.Error, TypeError): + return 400, {'error': 'pfx must be a PKCS#12 file in base64'} + password = body.get('password') + if password is not None and not isinstance(password, str): + return 400, {'error': 'password must be a string'} + document = linuxmanager_pki.import_https_pfx(cfg, data, password) + else: + return 404, {'error': f'no route {method} {path}'} + except linuxmanager_pki.Failure as failure: + return PKI_STATUS.get(failure.status, 500), {'error': str(failure)} + except ldap.LDAPError as exc: + return 500, {'error': f'the directory, which holds the certificate, failed: {exc}'} + except SystemExit as exc: + return 500, {'error': str(exc.code)} + linuxmanager.request_setup() + return 200, document diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/logs.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/logs.py index 4cc6c7f..508121f 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/logs.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/logs.py @@ -7,7 +7,7 @@ import linuxmanager #: The units whose journal /logs/journal shows, besides the whole journal: the package's own and the services it runs. JOURNAL_UNITS = ('linux-manager-setup', 'linux-manager-web', 'linux-manager-metrics', 'linux-manager-pki', 'linux-manager-backup', - 'linux-manager-caddy', 'linux-manager-ui', 'caddy', 'slapd', 'nslcd', 'postgresql', 'strongswan', + 'linux-manager-ui', 'caddy', 'slapd', 'nslcd', 'postgresql', 'strongswan', 'wg-quick@wg0', 'openvpn-server@linux-manager', 'ssh', 'linux-manager-resolver', 'linux-manager-webdav', 'pdns') #: The most lines /logs answers, the number it answers without lines, and the most bytes it reads from the end of a file. diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/metrics.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/metrics.py index 49f95f2..5e590b7 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/metrics.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/metrics.py @@ -35,7 +35,7 @@ def metrics_settings(method, body): PUT /metrics/settings change any of the settings of the metrics section; an empty or absent otlp_password keeps the current secret, and an empty otlp_username removes it - A change is applied by restarting linux-manager-setup without waiting for it. + A change is applied by a run of linux-manager-setup, without waiting for it. """ if body == 'invalid' or (body is not None and not isinstance(body, dict)): return 400, {'error': 'the body must be a JSON object'} diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/pki.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/pki.py index 24a0a79..f2b1760 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/pki.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/pki.py @@ -4,7 +4,6 @@ import ldap import linuxmanager import linuxmanager_pki -from linuxmanager_status import run from .common import PKI_STATUS @@ -38,7 +37,7 @@ def ca(method, path, body): answers {"upstream", "expires"} 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. """ 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: linuxmanager_pki.check_source(cfg, linuxmanager_pki.authority(connection, 'root')) linuxmanager.save_config(data) - run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service') + linuxmanager.request_setup() return 200, {'settings': cfg['pki'], 'templates': linuxmanager.pki_templates(cfg)} with linuxmanager_pki.locked(): if route == ('POST', 'certificates'): @@ -98,5 +97,5 @@ def ca(method, path, body): except SystemExit as exc: return 500, {'error': str(exc.code)} 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 diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/sites.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/sites.py index 02e70e8..3152b0e 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/sites.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/sites.py @@ -10,7 +10,6 @@ import ldap import linuxmanager import linuxmanager_sites -from linuxmanager_status import run from .common import MIB, SITE_STATUS, section_change @@ -31,7 +30,7 @@ def sites(method, path, query, body): PUT /sites/ change any of the settings of POST but name; an empty or absent private_key keeps the key DELETE /sites/ remove the site, with content=true also its folder - A change is applied by restarting linux-manager-setup without waiting for it. + A change is applied by a run of linux-manager-setup, without waiting for it. """ if body == 'invalid' or (body is not None and not isinstance(body, dict)): return 400, {'error': 'the body must be a JSON object'} @@ -68,7 +67,7 @@ def sites(method, path, query, body): return 500, {'error': f'the site cannot be changed: {exc}'} except SystemExit as exc: return 500, {'error': str(exc.code)} - run('systemctl', 'restart', '--no-block', 'linux-manager-setup.service') + linuxmanager.request_setup() return code, document diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/status.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/status.py index 4ff228f..55e403a 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/status.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/status.py @@ -232,7 +232,7 @@ def postgresql_databases(): def details(state): """What /config shows: the configuration without its secrets, and what the server resolved and runs; caddy is the - installed Caddy, {version, source, service}, service the state of caddy.service, null when it is not installed; oidc + installed Caddy, {version, service}, service the state of caddy.service, null when it is not installed; oidc is {enabled, issuer} of the OpenID Provider, issuer null while it is disabled; docker.installed is whether docker.service is installed, as docker_status finds it.""" configuration = state.get('configuration', {}) @@ -252,9 +252,7 @@ def details(state): 'rules': lines_of('iptables', '-S', 'LINUX-MANAGER-DOCKER'), }, 'postgresql': postgresql_configuration(), - # Caddy is upstream's once its repository is configured (linux-manager-caddy). - 'caddy': {'version': caddy, 'source': 'upstream' if linuxmanager.CADDY_APT_SOURCE.is_file() else 'ubuntu', - 'service': unit_state('caddy.service')} if caddy else None, + 'caddy': {'version': caddy, 'service': unit_state('caddy.service')} if caddy else None, 'oidc': {'enabled': oidc, 'issuer': linuxmanager.oidc_issuer(configuration) if oidc else None}, } diff --git a/debian-package/src/usr/lib/linux-manager/manager b/debian-package/src/usr/lib/linux-manager/manager index 23afe8c..d019b2f 100755 --- a/debian-package/src/usr/lib/linux-manager/manager +++ b/debian-package/src/usr/lib/linux-manager/manager @@ -6,7 +6,8 @@ python3-psycopg to keep the sessions; its settings and its listening loop are in linuxmanager_ui. Pages: - /api/info the version of this package and the server it manages, as JSON + /api/info the URL of the status page of the server it manages, the port and listen of the + manager's plain HTTP site, and with a session the version of this package, as JSON /api/session POST signs in through the server's /auth with {"name", "password", "code"?}, GET answers the signed-in user, DELETE signs out /api/session/passkey @@ -47,9 +48,9 @@ and logging each failure. Then it listens. Its unit starts it only once wait-for libpq in the linker cache, where psycopg looks it up. The service needs nothing else to start and does not end on its own. Every DISCOVERY_SECONDS it -works out where to listen, bind or the interfaces listen names, and runs a server at each address -(linuxmanager_ui.serve). Every request -reads the settings when it is made. +works out where to listen, bind, or on the server the loopback port Caddy calls +(linuxmanager_ui.listen), and runs a server at each address (linuxmanager_ui.serve). Every +request reads the settings when it is made. """ import argparse @@ -77,11 +78,9 @@ import requests import urllib3 import linuxmanager_ui +from linuxmanager_net import LOOPBACK from linuxmanager_ui import DATABASE, DATABASE_SECRET, ROUTER_CONFIG_FILE -#: The address a proxy on this host calls from. -LOOPBACK = '127.0.0.1' - CONFIG_FILE = linuxmanager_ui.CONFIG_FILE WEB_DIR = '/usr/share/linux-manager/manager/web' DOCS_DIR = '/usr/share/linux-manager/manager/docs' @@ -792,8 +791,14 @@ class Handler(BaseHTTPRequestHandler): self.close_connection = True if route == '/api/info': https = self.proxied() and self.headers.get('X-Forwarded-Proto') == 'https' - status = linuxmanager_ui.status_url(CONFIG_FILE, self.headers.get('Host', ''), self.server.server_address[0], https) - body = json.dumps({'version': package_version(), 'status_url': status or None}).encode() + status = linuxmanager_ui.status_url(CONFIG_FILE, self.headers.get('Host', ''), https) + # The version is not told to a browser that has not signed in. + try: + signed_in = session(settings(), self.session_id(), self.client()) is not None + except (Unavailable, psycopg.Error): + signed_in = False + body = json.dumps({'version': package_version() if signed_in else None, 'status_url': status or None, + 'manager': linuxmanager_ui.plain_site(CONFIG_FILE)}).encode() code, kind = 200, 'application/json' elif route == '/api/shell' and self.command == 'GET' and self.headers.get('Upgrade', '').lower() == 'websocket': try: diff --git a/debian-package/src/usr/lib/linux-manager/metrics b/debian-package/src/usr/lib/linux-manager/metrics index 58235bc..ed3b15e 100755 --- a/debian-package/src/usr/lib/linux-manager/metrics +++ b/debian-package/src/usr/lib/linux-manager/metrics @@ -23,9 +23,10 @@ prometheus_client, with OpenTelemetry semantic convention names in their Prometh OpenTelemetry Collector's prometheus receiver. It needs HTTP Basic authentication as the service account metrics.service_account names, which linux-manager-setup keeps with the password in /etc/linux-manager/metrics.secret, checked with a bind to the server's directory, so failed attempts -lock the account as for any user. The service listens on the interfaces metrics.listen -names and on the loopback address, where Caddy serves it over HTTPS at metrics.https_port; the -address of a call through Caddy is the last entry of its X-Forwarded-For header. +lock the account as for any user. The service listens on the loopback address only, behind +Caddy, which serves it over plain HTTP at metrics.port, on the interfaces metrics.listen names +in the firewall, and over HTTPS at metrics.https_port; the address of a call through Caddy is +the last entry of its X-Forwarded-For header. When metrics.otlp_endpoint is set, every sample is also pushed there as an OTLP/HTTP JSON ExportMetricsServiceRequest, with HTTP Basic authentication when metrics.otlp_username is set. @@ -431,19 +432,11 @@ class Handler(BaseHTTPRequestHandler): def wanted(): - """Where the service listens: the addresses of the interfaces metrics.listen names and LOOPBACK, at metrics.port.""" - configuration = read_json(CONFIG_FILE) - metrics = section(configuration, 'metrics') - defaults = linuxmanager.SCHEMA['metrics'] - if metrics.get('enabled', defaults['enabled']) is False: + """Where the service listens: METRICS_LOOPBACK_PORT of LOOPBACK, where Caddy calls it, while metrics are enabled.""" + metrics = section(read_json(CONFIG_FILE), 'metrics') + if metrics.get('enabled', linuxmanager.SCHEMA['metrics']['enabled']) is False: return [], 'metrics are disabled in the configuration' - port = metrics.get('port', defaults['port']) - if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535: - port = defaults['port'] - addresses = linuxmanager_net.listen_addresses(configuration, metrics.get('listen', defaults['listen'])) - if not addresses: - return [], 'the addresses to listen on are not known yet' - return [(address, port) for address in [*addresses, linuxmanager_net.LOOPBACK]], '' + return [(linuxmanager_net.LOOPBACK, linuxmanager_net.METRICS_LOOPBACK_PORT)], '' def main(): diff --git a/debian-package/src/usr/lib/linux-manager/setup b/debian-package/src/usr/lib/linux-manager/setup index a16217b..89043eb 100755 --- a/debian-package/src/usr/lib/linux-manager/setup +++ b/debian-package/src/usr/lib/linux-manager/setup @@ -16,6 +16,7 @@ firewall and NAT rules are written against them, so choosing the wrong one would be a silent and security-relevant mistake. """ +import fcntl import grp import json import os @@ -27,6 +28,7 @@ import socket import subprocess import sys import time +import traceback sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) @@ -71,9 +73,6 @@ CADDYFILE = pathlib.Path('/etc/caddy/linux-manager.Caddyfile') CADDY_UNIT = 'caddy.service' CADDY_GROUP = 'caddy' -#: The unit that installs Caddy from https.caddy_source with linux-manager-caddy, outside setup. -CADDY_INSTALL_UNIT = 'linux-manager-caddy.service' - #: The certificates and keys of the issuing CAs behind Caddy's ACME server and the sites of tls ca, /cert.pem and #: key.pem. 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, /cert.pem and key.pem. 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. RESOLVER_UNIT = 'linux-manager-resolver.service' @@ -155,8 +157,8 @@ def resolve_public_ip(fqdn): def setup_wireguard(ctx): - """Generate the WireGuard key pair when it does not exist.""" - if not ctx['wg_enabled']: + """Generate the WireGuard key pair when it does not exist, once the VPN's packages are installed.""" + if not ctx['wg_enabled'] or not ctx['vpn_installed']: return WG_DIR.mkdir(mode=0o700, parents=True, exist_ok=True) key_file = WG_DIR / 'wg0.key' @@ -262,16 +264,18 @@ def filter_block(ctx): ] lines += ['# P2S DNS RULES END'] - # The web service, the Manager and the metrics service choose their interfaces themselves, so their ports are open on - # both; without the router both are the one interface. + # Caddy serves the plain HTTP ports of the web service, the Manager and the metrics service on every address; each is + # open on the interfaces its listen names, where internal is the external interface without the router. + internal = ctx['int_iface'] if ctx['router_enabled'] else ctx['wan_iface'] + listened = {'internal': [internal], 'external': [ctx['wan_iface']], 'both': [internal, ctx['wan_iface']]} interfaces = list(dict.fromkeys(name for name in (ctx['int_iface'], ctx['wan_iface']) if name)) - if ctx['web_enabled'] and interfaces: - lines += [ - '', - '# WEB RULES START', - *(f'-A ufw-before-input -i {name} -p tcp --dport {ctx["web_port"]} -j ACCEPT' for name in interfaces), - '# WEB RULES END', - ] + + def opened(choice, port): + return [f'-A ufw-before-input -i {name} -p tcp --dport {port} -j ACCEPT' + for name in dict.fromkeys(listened[choice]) if name] + + if ctx['web_enabled']: + lines += ['', '# WEB RULES START', *opened(ctx['web_listen'], ctx['web_port']), '# WEB RULES END'] if not SETUP_DONE.exists() and ctx['int_iface']: lines += [ @@ -282,25 +286,15 @@ def filter_block(ctx): '# BOOTSTRAP RULES END', ] - if interfaces: - port = linuxmanager.manager_port() - lines += [ - '', - '# MANAGER RULES START', - *(f'-A ufw-before-input -i {name} -p tcp --dport {port} -j ACCEPT' for name in interfaces), - '# MANAGER RULES END', - ] + lines += ['', '# MANAGER RULES START', *opened(linuxmanager.manager_listen(), linuxmanager.manager_port()), + '# MANAGER RULES END'] - if linuxmanager.metrics_ready(ctx) and interfaces: - lines += [ - '', - '# METRICS RULES START', - *(f'-A ufw-before-input -i {name} -p tcp --dport {ctx["metrics_port"]} -j ACCEPT' for name in interfaces), - '# METRICS RULES END', - ] + if linuxmanager.metrics_ready(ctx): + lines += ['', '# METRICS RULES START', *opened(ctx['metrics_listen'], ctx['metrics_port']), + '# METRICS RULES END'] - # Let's Encrypt reaches the HTTP challenge on the external interface, and the CA files published on port 80 are - # read on both; the HTTPS ports are open on both. + # The ACME CA reaches the HTTP challenge on the external interface while it issues the server's certificate, and + # the CA files published on port 80 are read on both; the HTTPS ports are open on both. if linuxmanager.https_ready(ctx) and interfaces: publish = ctx['pki_publish'] ports = [port for wanted, port in ((ctx['web_enabled'] or 'https' in publish or ctx['pki_acme'], @@ -314,7 +308,7 @@ def filter_block(ctx): '', '# HTTPS RULES START', *([f'-A ufw-before-input -i {ctx["wan_iface"]} -p tcp --dport {linuxmanager.ACME_HTTP_PORT} -j ACCEPT'] - if ctx['wan_iface'] and 'http-80' not in publish else []), + if ctx['wan_iface'] and '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), '# HTTPS RULES END', ] @@ -752,42 +746,28 @@ def manage_resolver(changed): def manage_caddy(cfg, ctx): - """Run Caddy, the HTTPS proxy of the server's services and the server of the web sites, while either is wanted, and - stop it when not. + """Run Caddy, a dependency of the package, which serves every HTTP and HTTPS port of the server's services and the + web sites; the services listen on loopback only. - While HTTPS is ready, CADDYFILE serves the web service on https.web_port, the manager on - https.manager_port, while metrics are enabled the metrics service on metrics.https_port, and while - WebDAV is ready WebDAV on sites.webdav_port, all for wan.local_fqdn with a certificate from Let's Encrypt, and all - calling the service on its loopback address. It also serves the CA files of linuxmanager_pki.PUBLISH_DIR at /pki/ on - the endpoints of pki.publish that are Caddy's, and an ACME server at /acme// on https.web_port for each - issuing CA with acme and a certificate. + CADDYFILE serves over plain HTTP the web service on web.port while it is enabled, the manager on its port, or a + redirect (308) to its HTTPS address while HTTPS is ready and https.disable_auto_redirect is off, and while metrics + are enabled the metrics service on metrics.port. While HTTPS is ready, it serves the web service on + https.web_port, the manager on https.manager_port, while metrics are enabled the metrics service on + metrics.https_port, and while WebDAV is ready WebDAV on sites.webdav_port, all for wan.local_fqdn. Every site calls + its service on its loopback port. The certificate comes from the ACME CA of https.acme_provider, the global issuer, + with https.certificate acme, and otherwise is the one linuxmanager_pki.https_files gives, written to + CADDY_HTTPS_DIR; while that cannot be read, the HTTPS sites are left out, so that no ACME CA is asked for it. It + also serves the CA files of linuxmanager_pki.PUBLISH_DIR at /pki/ on the endpoints of pki.publish that are Caddy's, + and an ACME server at /acme// on https.web_port for each issuing CA with acme and a certificate. It serves each site of ctx's sites from its folder, with the TLS of the site: an issuing CA of tls ca issues its certificates, and the certificate and key of tls file are written to CADDY_SITES_DIR/. The certificates and keys of the issuing CAs of both are copied to CADDY_PKI_DIR. While the sites cannot be read (ctx's sites is None), the Caddyfile is left as it is. - - Caddy is installed by CADDY_INSTALL_UNIT, outside setup, when it is missing or when - https.caddy_source is upstream and Caddy's repository is not configured; the unit restarts - setup, whose next run serves with it. """ sites = ctx['sites'] - if not linuxmanager.https_ready(ctx) and not sites: - if sites is None: - return - linuxmanager.remove(CADDYFILE) - if unit_is_active(CADDY_UNIT): - run(['systemctl', 'disable', '--now', CADDY_UNIT], check=False) - return - - source = cfg['https']['caddy_source'] - if shutil.which('caddy') is None or (source == 'upstream' and not linuxmanager.CADDY_APT_SOURCE.is_file()): - run(['systemctl', 'start', '--no-block', CADDY_INSTALL_UNIT], check=False) - warn(f'Caddy is installed from the {source} source by {CADDY_INSTALL_UNIT}, which runs setup again') - return - if source == 'ubuntu' and linuxmanager.CADDY_APT_SOURCE.is_file(): - warn("https.caddy_source ubuntu is ignored: Caddy's repository is configured, and Caddy stays upstream's") - + if shutil.which('caddy') is None: + fail('caddy is not installed; it is a dependency of the package') if sites is None: warn('the web sites cannot be read; the Caddyfile is left as it is') if not unit_is_active(CADDY_UNIT) and CADDYFILE.exists(): @@ -798,6 +778,26 @@ def manage_caddy(cfg, ctx): except KeyError: fail(f'the group {CADDY_GROUP} does not exist; is the caddy package installed?') 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 []), *(site['ca'] for site in sites if site['tls'] == 'ca')])) try: @@ -810,7 +810,6 @@ def manage_caddy(cfg, ctx): if site['tls'] == 'ca' and site['ca'] not in authorities: warn(f'site {site["name"]} is left out: issuing CA {site["ca"]} has no certificate') sites = [site for site in sites if site['tls'] != 'ca' or site['ca'] in authorities] - copied = False for folder in (CADDY_PKI_DIR.iterdir() if CADDY_PKI_DIR.is_dir() else []): if folder.name not in authorities: shutil.rmtree(folder) @@ -837,12 +836,18 @@ def manage_caddy(cfg, ctx): linuxmanager_sites.ensure_folders(site['name'] for site in sites) names = linuxmanager.issuing_cas(cfg) 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_cas=[{'id': name, 'name': names[name]['name'].strip(), 'cert': str(CADDY_PKI_DIR / name / 'cert.pem'), 'key': str(CADDY_PKI_DIR / name / 'key.pem')} for name in authorities], acme_cas=[name for name in authorities if https and name in ctx['pki_acme']], - webdav=linuxmanager.webdav_ready(ctx), webdav_loopback_port=linuxmanager.WEBDAV_LOOPBACK_PORT, + webdav=https and linuxmanager.webdav_ready(ctx), webdav_loopback_port=linuxmanager.WEBDAV_LOOPBACK_PORT, sites=[{'name': site['name'], 'tls': site['tls'], 'ca': site['ca'], 'spa': site['spa'], 'index': site['index_file'], 'root': str(linuxmanager_sites.SITES_DIR / site['name']), 'addresses': [caddy_address(host, site['port'], site['tls']) for host in site['hosts']] @@ -864,15 +869,24 @@ def install_packages(feature): warn(f'the packages of {feature} are installed by {unit}, which runs setup again') +def manage_components(cfg): + """Install the packages of each component of linuxmanager.COMPONENTS whose switch is on, when any is missing or + marked as installed automatically, which apt autoremove would remove: an installation by apt-get marks them as + installed by hand. A component's steps wait for its packages; nothing is removed while a component is off.""" + for name, (_, packages) in linuxmanager.COMPONENTS.items(): + if linuxmanager.component_on(cfg, name) and (not linuxmanager.packages_installed(packages) + or linuxmanager.packages_automatic(packages)): + install_packages(name) + + def manage_webdav(ctx): - """Run rclone's WebDAV server of the sites' folders while WebDAV is ready, and stop it when not; rclone is installed - when it is missing.""" + """Run rclone's WebDAV server of the sites' folders while WebDAV is ready and rclone is installed + (manage_components), and stop it when not.""" if not linuxmanager.webdav_ready(ctx): if unit_is_active(WEBDAV_UNIT): run(['systemctl', 'disable', '--now', WEBDAV_UNIT], check=False) return if shutil.which('rclone') is None: - install_packages('webdav') return linuxmanager_sites.ensure_folders([]) run(['systemctl', 'enable', '--now', WEBDAV_UNIT], check=False) @@ -899,7 +913,7 @@ def site_addresses(cfg, ctx): def manage_dns(cfg, ctx): """Run PowerDNS, the primary name server of the domains of linuxmanager_dns, on the addresses of dns.listen while DNS - is enabled, and stop it when not; its packages are installed when they are missing. + is enabled and its packages are installed (manage_components), and stop it when not. The settings, linuxmanager_dns.PDNS_CONF, are written before the packages are installed, so the server their installation starts answers on those addresses only, beside systemd-resolved's stub on 127.0.0.53. The host names @@ -927,7 +941,6 @@ def manage_dns(cfg, ctx): linuxmanager_dns.PDNS_CONF.parent.mkdir(mode=0o755, parents=True, exist_ok=True) changed = write_if_changed(linuxmanager_dns.PDNS_CONF, linuxmanager_dns.config_text(addresses), 0o640) if not linuxmanager_dns.PDNS_SERVER.exists() or not linuxmanager_dns.PDNS_SCHEMA.exists(): - install_packages('dns') return os.chown(linuxmanager_dns.PDNS_CONF, 0, grp.getgrnam(linuxmanager_dns.GROUP).gr_gid) linuxmanager_dns.provision() @@ -1090,6 +1103,8 @@ def main(): failed_step = 'user directory' progress('running', failed_step) problem = manage_directory() + progress('running', 'components') + manage_components(cfg) progress('running', 'configuration') ctx, changed = linuxmanager.configure(cfg) @@ -1195,13 +1210,28 @@ def record_failure(error): if __name__ == '__main__': - # A failing step ends with SystemExit carrying its message (linuxmanager.fail). - try: - code = main() - except SystemExit as exc: - record_failure(str(exc.code)) - raise - except Exception as exc: - record_failure(repr(exc)) - raise + # The run holds SETUP_RUNNING while it works, and runs again while a request came during it (request_setup). + linuxmanager.SETUP_RUNNING.parent.mkdir(parents=True, exist_ok=True) + running = open(linuxmanager.SETUP_RUNNING, 'a', encoding='utf-8') + fcntl.flock(running, fcntl.LOCK_EX) + while True: + with linuxmanager.setup_lock(): + linuxmanager.SETUP_REQUEST.unlink(missing_ok=True) + # A failing step ends with SystemExit carrying its message (linuxmanager.fail). + try: + code = main() + except SystemExit as exc: + record_failure(str(exc.code)) + code = exc.code + except Exception as exc: + record_failure(repr(exc)) + traceback.print_exc() + code = 1 + # The lock is kept to the end of the process, so that a request either comes before this check or finds no run. + lock = linuxmanager.setup_lock() + if not linuxmanager.SETUP_REQUEST.exists(): + break + lock.close() + print('linux-manager: another run was requested during this one; running again', flush=True) + fcntl.flock(running, fcntl.LOCK_UN) sys.exit(code) diff --git a/debian-package/src/usr/lib/linux-manager/web b/debian-package/src/usr/lib/linux-manager/web index d6f2d1d..c4012c8 100755 --- a/debian-package/src/usr/lib/linux-manager/web +++ b/debian-package/src/usr/lib/linux-manager/web @@ -1,5 +1,6 @@ #!/usr/bin/python3 -"""Serve the status of the server on its internal address, its external address or both, as web.listen sets. +"""Serve the status of the server on the loopback address, behind Caddy, which serves web.port over plain HTTP and +https.web_port over HTTPS. Run by linux-manager-web.service. Users are managed with linuxmanager_users, the module that linux-manager-user uses too. @@ -12,11 +13,9 @@ logging each failure. Then it listens. Its unit starts it only once wait-for-lib in the linker cache, where psycopg looks it up. The service needs nothing else to start and does not end on its own. Every DISCOVERY_SECONDS it -works out from /etc/linux-manager/linux-manager.json the addresses of the interfaces web.listen names, -internal, external or both, as general.mode directs, with web.port and web.enabled -(linuxmanager_net.web_listen), and runs a server on each (linuxmanager_serve.serve): it starts them, -moves them when an address or the port changes, and stops them while the service is disabled or -no address is known. Every request reads what it needs when it is made: the signing +reads web.enabled from /etc/linux-manager/linux-manager.json and listens on +linuxmanager_net.WEB_LOOPBACK_PORT of the loopback address while it is on (linuxmanager_net.web_listen, +linuxmanager_serve.serve). Every request reads what it needs when it is made: the signing key, the configuration, and the features of the server and the facts shown by /config from /run/linux-manager/web.json, which linux-manager-setup writes. Before setup has written that file the server has no features, and /config shows no configuration or interfaces. @@ -43,9 +42,6 @@ from linuxmanager_web.shell import editor_listen #: Seconds between two attempts of the initialization. INIT_RETRY_SECONDS = 15 -#: The port when web.port is not set. -DEFAULT_PORT = 7081 - #: Seconds between two discoveries of where the service should listen. DISCOVERY_SECONDS = 30 @@ -88,8 +84,8 @@ def main(): initialize() threading.Thread(target=editor_listen, name='editor socket', daemon=True).start() try: - linuxmanager_serve.serve(lambda: linuxmanager_net.web_listen(read_json(CONFIG_FILE), DEFAULT_PORT), Handler, log, - DISCOVERY_SECONDS) + linuxmanager_serve.serve(lambda: linuxmanager_net.web_listen(read_json(CONFIG_FILE)), Handler, log, + DISCOVERY_SECONDS) except KeyboardInterrupt: pass return 0 diff --git a/debian-package/src/usr/sbin/linux-manager-ca b/debian-package/src/usr/sbin/linux-manager-ca index 65c1e91..f1ac23e 100755 --- a/debian-package/src/usr/sbin/linux-manager-ca +++ b/debian-package/src/usr/sbin/linux-manager-ca @@ -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 the signed certificate, and, named root, the certificate of the offline root. root import-crl takes a CRL of the offline root, and root setup-code exchanges a setup code of a Simple CA token, read from the first line of standard -input, for the token. maintain signs the stale CRLs again, or fetches those of Simple CA; linux-manager-pki.service -runs it daily. A change that needs linux-manager-setup restarts it without waiting. +input, for the token. https status shows the server's HTTPS certificate, https csr prints a new CSR for +wan.local_fqdn, to be signed by another CA, https import takes the certificate signed for it, and https import-pfx a +PKCS#12 file whose password is read from the first line of standard input. maintain signs the stale CRLs again, or +fetches those of Simple CA; linux-manager-pki.service runs it daily. A change that needs linux-manager-setup requests a run of it without waiting. The answer is text for people on standard output, and a failure is a message on standard error. With --json the answer is JSON on standard output, and a failure is {"error": ...} there too. The exit status says what failed: 2 the request @@ -24,6 +26,9 @@ commands and their options. linux-manager-ca [--json] ca import NAME|root FILE linux-manager-ca [--json] root import-crl FILE linux-manager-ca [--json] root setup-code (setup code on stdin) + linux-manager-ca [--json] https status|csr + linux-manager-ca [--json] https import FILE + linux-manager-ca [--json] https import-pfx FILE (password on stdin) """ import argparse @@ -31,7 +36,6 @@ import base64 import json import os import pathlib -import subprocess import sys sys.path.insert(0, '/usr/lib/linux-manager') @@ -56,10 +60,6 @@ def secret(): return sys.stdin.readline().rstrip('\r\n') -def restart_setup(): - subprocess.run(['systemctl', 'restart', '--no-block', 'linux-manager-setup.service'], capture_output=True, text=True) - - def show_status(document): root = document['root'] source = {'local': 'created by the server', 'offline': 'offline', @@ -95,6 +95,13 @@ def run(options): if options.command == 'status': document = linuxmanager_pki.status(cfg) return document, None + if options.command == 'https' and options.action == 'status': + document = linuxmanager_pki.https_status(cfg) + return document, (f'Source: {document["source"]}, served: {document["served"] or "none"}\n' + f'Subject: {document["subject"] or "-"}, issuer: {document["issuer"] or "-"}, ' + f'expires {document["expires"] or "-"}\n' + f'Names: {", ".join(document["sans"]) or "-"}' + ('\nA CSR waits for its certificate.' + if document['pending'] else '')) if options.command == 'list': found = [entry for entry in linuxmanager_pki.certificates() if options.ca in (None, entry['ca'])] text = '\n'.join(f'{entry["serial"]} {entry["ca"]} {entry["kind"]} {entry["subject"]} {entry["state"]} ' @@ -117,13 +124,13 @@ def run(options): if options.command == 'revoke': document = linuxmanager_pki.revoke(cfg, options.serial, options.reason) if document['reissue']: - restart_setup() + linuxmanager.request_setup() return document, f'Certificate {document["serial"]} revoked' + \ ('; linux-manager-setup issues a new one.' if document['reissue'] else '.') if options.command == 'maintain': notices, due = linuxmanager_pki.maintain(cfg) if due: - restart_setup() + linuxmanager.request_setup() return {'renewal': due, 'notices': notices}, '\n'.join( ['CRLs checked' + ('; linux-manager-setup renews the certificates.' if due else '.'), *(f'Warning: {notice}' for notice in notices)]) @@ -132,12 +139,24 @@ def run(options): return document, document['csr'] + '\n' + document['extensions'] if options.command == 'ca': document = linuxmanager_pki.import_ca(cfg, options.name, pathlib.Path(options.file).read_text(encoding='ascii')) - restart_setup() + linuxmanager.request_setup() what = 'The root' if options.name == 'root' else f'Issuing CA {options.name}' return document, f'{what} has its certificate, which expires {document["expires"]}.' + if options.command == 'https' and options.action == 'csr': + document = linuxmanager_pki.https_csr(cfg) + return document, document['csr'] + if options.command == 'https': + if options.action == 'import': + document = linuxmanager_pki.import_https_certificate( + cfg, pathlib.Path(options.file).read_text(encoding='ascii')) + else: + document = linuxmanager_pki.import_https_pfx(cfg, pathlib.Path(options.file).read_bytes(), secret()) + linuxmanager.request_setup() + return document, f'The HTTPS certificate of {document["subject"]}, issued by {document["issuer"]}, ' \ + f'expires {document["expires"]}.' if options.action == 'setup-code': document = linuxmanager_pki.exchange_code(cfg, secret()) - restart_setup() + linuxmanager.request_setup() return document, (f'Simple CA token of issuing CA {document["upstream"]} taken' + (f', valid until {document["expires"]}.' if document['expires'] else '.')) document = linuxmanager_pki.import_root_crl(cfg, pathlib.Path(options.file).read_bytes()) @@ -172,6 +191,12 @@ def main(argv): 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('setup-code', help='exchange a Simple CA setup code from stdin for the token') + host = commands.add_parser('https', help="the server's HTTPS certificate") + host_actions = host.add_subparsers(dest='action', required=True, parser_class=Parser) + host_actions.add_parser('status', help='show the certificate Caddy serves') + host_actions.add_parser('csr', help='print a new CSR for wan.local_fqdn, to be signed by another CA') + host_actions.add_parser('import', help='take the certificate signed for the CSR, PEM with its chain').add_argument('file') + host_actions.add_parser('import-pfx', help='take a PKCS#12 file; the password is read from stdin').add_argument('file') options = parser.parse_args(argv) os.umask(0o077) diff --git a/debian-package/src/usr/sbin/linux-manager-caddy b/debian-package/src/usr/sbin/linux-manager-caddy deleted file mode 100755 index 0c26b42..0000000 --- a/debian-package/src/usr/sbin/linux-manager-caddy +++ /dev/null @@ -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:])) diff --git a/debian-package/src/usr/sbin/linux-manager-config-edit b/debian-package/src/usr/sbin/linux-manager-config-edit index 4b34a98..068563b 100755 --- a/debian-package/src/usr/sbin/linux-manager-config-edit +++ b/debian-package/src/usr/sbin/linux-manager-config-edit @@ -9,21 +9,22 @@ number, true or false, a list of strings separated by commas (an empty value is or a string. remove takes site_to_site.NAME and removes that connection. The configuration with the change is checked as linux-manager-setup checks it, and only then written with linuxmanager.save_config, holding linuxmanager.config_lock; linux-manager-setup applies it at its next -run, which set and remove remind of. With --restart they restart linux-manager-setup and wait until -it has applied the change. A failure is a message on standard error; the exit status is 2 for an -invalid request and 1 for any other failure, a failed run of linux-manager-setup included. -h or ---help shows the options. +run, which set and remove remind of. With --restart they have linux-manager-setup run and wait until +it has applied the change, as apply does without a change: a run in progress is not cut short but +runs once more (linuxmanager.request_setup). A failure is a message on standard error; the exit +status is 2 for an invalid request and 1 for any other failure, a failed run of linux-manager-setup +included. -h or --help shows the options. linux-manager-config-edit show linux-manager-config-edit set [--restart] SECTION.OPTION VALUE linux-manager-config-edit set [--restart] site_to_site.NAME.OPTION VALUE linux-manager-config-edit remove [--restart] site_to_site.NAME + linux-manager-config-edit apply """ import argparse import copy import json -import subprocess import sys sys.path.insert(0, '/usr/lib/linux-manager') @@ -83,6 +84,7 @@ def main(argv): parser = Parser(prog='linux-manager-config-edit', description='Show and change the server configuration.') commands = parser.add_subparsers(dest='command', required=True, parser_class=Parser) commands.add_parser('show', help='print the configuration as indented JSON') + commands.add_parser('apply', help='have linux-manager-setup apply the configuration and wait for it') setter = commands.add_parser('set', help='set a setting and write the configuration') setter.add_argument('key', metavar='SECTION.OPTION', help='the setting, such as web.port or site_to_site.NAME.option') @@ -91,12 +93,14 @@ def main(argv): remover.add_argument('key', metavar='site_to_site.NAME', help='the connection') for changer in (setter, remover): changer.add_argument('--restart', action='store_true', - help='restart linux-manager-setup and wait until it has applied the change') + help='have linux-manager-setup apply the change and wait for it') options = parser.parse_args(argv) if options.command == 'show': print(json.dumps(read(), indent=2)) return 0 + if options.command == 'apply': + return applied() with linuxmanager.config_lock(): data = read() @@ -131,10 +135,15 @@ def main(argv): else: print(f'{options.key} removed from {linuxmanager.CONFIG_FILE}.') if not options.restart: - print('Apply it with: systemctl restart linux-manager-setup, or --restart') + print('Apply it with: linux-manager-config-edit apply, or --restart') return 0 - print('Restarting linux-manager-setup...', flush=True) - if subprocess.run(['systemctl', 'restart', 'linux-manager-setup.service']).returncode != 0: + return applied() + + +def applied(): + """Have linux-manager-setup apply the configuration and wait for it; the exit status.""" + print('Running linux-manager-setup...', flush=True) + if not linuxmanager.request_setup(wait=True): print('linux-manager-config-edit: linux-manager-setup failed; see journalctl -u linux-manager-setup', file=sys.stderr) return 1 print('linux-manager-setup applied it.') diff --git a/debian-package/src/usr/sbin/linux-manager-site b/debian-package/src/usr/sbin/linux-manager-site index 19bd889..4a1415d 100755 --- a/debian-package/src/usr/sbin/linux-manager-site +++ b/debian-package/src/usr/sbin/linux-manager-site @@ -6,7 +6,7 @@ firewall opens it, TLS (none, acme, ca with --ca, or file with --certificate and whether any path without a file is served that file of the site (--spa), the group whose members change its files, and who serves the records of its host names (--dns user, elsewhere, or router, the server's name server, with the server's address of --dns-address). -A change is applied by restarting linux-manager-setup without waiting for it. The answer is text for people on standard +A change is applied by a run of linux-manager-setup, without waiting for it. The answer is text for people on standard output, and a failure is a message on standard error. With --json the answer is JSON on standard output, and a failure is {"error": ...} there too. The exit status says what failed: 2 the request is invalid, 3 the site does not exist, 4 the site exists, 1 anything else. -h or --help shows the commands and their options. @@ -25,7 +25,6 @@ the site exists, 1 anything else. -h or --help shows the commands and their opti import argparse import json -import subprocess import sys sys.path.insert(0, '/usr/lib/linux-manager') @@ -151,7 +150,7 @@ def main(argv): message, status = f'the user directory failed: {exc}', 1 else: if changed: - subprocess.run(['systemctl', 'restart', '--no-block', 'linux-manager-setup.service']) + linuxmanager.request_setup() print(json.dumps(answer) if as_json else text_of(answer)) return 0 if as_json: diff --git a/debian-package/src/usr/share/bash-completion/completions/linux-manager-ca.bash b/debian-package/src/usr/share/bash-completion/completions/linux-manager-ca.bash index 37dbe5f..f498bd8 100644 --- a/debian-package/src/usr/share/bash-completion/completions/linux-manager-ca.bash +++ b/debian-package/src/usr/share/bash-completion/completions/linux-manager-ca.bash @@ -22,7 +22,7 @@ _linux_manager_ca() local cur prev words cword split _init_completion -s || return - # The command and, for ca and root, the action are the first words that are not options; the arguments are the + # The command and, for ca, root and https, the action are the first words that are not options; the arguments are the # words after them but option values. local i command='' action='' args=0 for ((i = 1; i < cword; i++)); do @@ -32,7 +32,7 @@ _linux_manager_ca() *) if [[ -z $command ]]; then command=${words[i]} - elif [[ $command == @(ca|root) && -z $action ]]; then + elif [[ $command == @(ca|root|https) && -z $action ]]; then action=${words[i]} else ((args++)) @@ -68,7 +68,7 @@ _linux_manager_ca() if [[ $cur == -* ]]; then COMPREPLY=($(compgen -W '--json --help' -- "$cur")) else - COMPREPLY=($(compgen -W 'status list issue revoke maintain ca root' -- "$cur")) + COMPREPLY=($(compgen -W 'status list issue revoke maintain ca root https' -- "$cur")) fi return fi @@ -87,9 +87,10 @@ _linux_manager_ca() case $command,$action,$args in ca,,*) COMPREPLY=($(compgen -W 'csr import' -- "$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,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 } && complete -F _linux_manager_ca linux-manager-ca diff --git a/debian-package/src/usr/share/bash-completion/completions/linux-manager-caddy.bash b/debian-package/src/usr/share/bash-completion/completions/linux-manager-caddy.bash deleted file mode 100644 index 232143d..0000000 --- a/debian-package/src/usr/share/bash-completion/completions/linux-manager-caddy.bash +++ /dev/null @@ -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 diff --git a/debian-package/src/usr/share/bash-completion/completions/linux-manager-config-edit.bash b/debian-package/src/usr/share/bash-completion/completions/linux-manager-config-edit.bash index 117d522..a0a2bef 100644 --- a/debian-package/src/usr/share/bash-completion/completions/linux-manager-config-edit.bash +++ b/debian-package/src/usr/share/bash-completion/completions/linux-manager-config-edit.bash @@ -48,7 +48,7 @@ _vpn_config_edit() fi case $command,${#args[@]} in - ,*) COMPREPLY=($(compgen -W 'show set remove' -- "$cur")) ;; + ,*) COMPREPLY=($(compgen -W 'show set remove apply' -- "$cur")) ;; set,0) COMPREPLY=($(compgen -W "$(_vpn_config_edit_python settings)" -- "$cur")) ;; set,1) COMPREPLY=($(compgen -W "$(_vpn_config_edit_python values "${args[0]}")" -- "$cur")) ;; remove,0) COMPREPLY=($(compgen -W "$(_vpn_config_edit_python connections)" -- "$cur")) ;; diff --git a/debian-package/src/usr/share/doc/linux-manager/linux-manager.json.example b/debian-package/src/usr/share/doc/linux-manager/linux-manager.json.example index cd704b8..3686e51 100644 --- a/debian-package/src/usr/share/doc/linux-manager/linux-manager.json.example +++ b/debian-package/src/usr/share/doc/linux-manager/linux-manager.json.example @@ -82,8 +82,7 @@ "enabled": true, "email": "", "web_port": 7444, - "manager_port": 7443, - "caddy_source": "ubuntu" + "manager_port": 7443 }, "oidc": { "enabled": false diff --git a/debian-package/src/usr/share/linux-manager/templates/Caddyfile.j2 b/debian-package/src/usr/share/linux-manager/templates/Caddyfile.j2 index 69eebce..b686b1d 100644 --- a/debian-package/src/usr/share/linux-manager/templates/Caddyfile.j2 +++ b/debian-package/src/usr/share/linux-manager/templates/Caddyfile.j2 @@ -4,8 +4,15 @@ {%- if https_email %} email {{ https_email }} {%- endif %} -{%- if https_acme_ca %} - acme_ca {{ https_acme_ca }} +{%- if https_acme_provider == 'zerossl' %} + cert_issuer zerossl{% if https_zerossl_api_key %} {{ https_zerossl_api_key }}{% endif %} +{%- else %} + cert_issuer acme { + dir {{ https_acme_url }} +{%- if https_acme_eab %} + eab {{ https_acme_eab[0] }} {{ https_acme_eab[1] }} +{%- endif %} + } {%- endif %} {%- if pki_cas %} skip_install_trust @@ -26,8 +33,38 @@ } {%- 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 }} { + header -Server +{%- if https_tls %} + tls {{ https_tls.cert }} {{ https_tls.key }} +{%- endif %} {%- if 'https' in pki_publish %} handle_path /pki/* { root * {{ pki_publish_dir }} @@ -43,7 +80,9 @@ {%- endfor %} handle { {%- if web_enabled %} - reverse_proxy {{ loopback }}:{{ web_port }} + reverse_proxy {{ loopback }}:{{ web_loopback_port }} { + header_down -Server + } {%- else %} respond 404 {%- endif %} @@ -52,6 +91,7 @@ {% endif %} {%- if https and 'http-80' in pki_publish %} http://{{ local_fqdn }} { + header -Server handle_path /pki/* { root * {{ pki_publish_dir }} file_server @@ -63,6 +103,10 @@ http://{{ local_fqdn }} { {% endif %} {%- if https and 'https-default' in pki_publish %} {{ local_fqdn }}:443 { + header -Server +{%- if https_tls %} + tls {{ https_tls.cert }} {{ https_tls.key }} +{%- endif %} handle_path /pki/* { root * {{ pki_publish_dir }} file_server @@ -74,22 +118,41 @@ http://{{ local_fqdn }} { {% endif %} {%- if https %} {{ 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 %} {%- if https and metrics_enabled %} {{ 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 %} {%- if webdav %} {{ 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 %} {%- for site in sites %} # Site {{ site.name }} {{ site.addresses | join(', ') }} { + header -Server root * {{ site.root }} {%- if site.tls == 'ca' %} tls { diff --git a/docs/certificates.md b/docs/certificates.md index 9b936c4..c24d46a 100644 --- a/docs/certificates.md +++ b/docs/certificates.md @@ -1,19 +1,27 @@ # Certificates -The server's CA: a root CA and issuing CAs that sign the certificates. The root is created by the -server, an offline CA, or the root of a Simple CA service whose issuing CA signs the server's -issuing CAs; that is chosen at setup and fixed once the root exists. +The server's HTTPS certificate and its CA: a root CA and issuing CAs that sign the certificates. +The root is created by the server, an offline CA, or the root of a Simple CA service whose issuing +CA signs the server's issuing CAs; that is chosen at setup and fixed once the root exists. ## Above the tabs +Issue and Settings are on every tab but Server. + - **Issue:** a certificate from a CSR, saved with its chain, or with a key the server makes, saved as a PFX file protected by a password; the server keeps no copy of the key. -- **Settings:** the names, lifetimes, key type, CRL validity, publishing endpoints and, with a - Simple CA root, the URL of the service. +- **Settings:** the names of the P2S and S2S CAs while they do not exist yet, the lifetimes, key + type, CRL validity, publishing endpoints and, with a Simple CA root, the URL of the service. - **Warnings:** what needs attention, such as a CRL about to expire. ## Tabs +- **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 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 @@ -24,11 +32,39 @@ issuing CAs; that is chosen at setup and fixed once the root exists. **Reset** for a changed built-in one. - **Extended key usages:** the usages templates may give, with their OIDs; custom ones are added with a name and an OID. -- **P2S Issuing CA** and **S2S Issuing CA:** the CAs of the VPN users and of site-to-site - connections. An active CA gives its CA bundle; a pending CA, waiting for the offline root, gives - its CSR and takes the certificate the root signed, and one waiting for Simple CA is signed once - the server reaches it. -- **Issuing CAs:** general-purpose CAs, each with its templates and an optional ACME server. - **Add issuing CA**, **Edit** and **Remove**; a removed CA is retired and its certificate revoked. -- **Certificates:** each with its kind, template, names, expiry and state; one of another system - or of the server is revoked after a confirmation with a reason. +- **Issuing CAs:** the built-in CAs, P2S for the VPN users, S2S for site-to-site connections and + the Servers Issuing CA `servers` for mTLS certificates and the server's HTTPS certificate, and the + custom CAs, each with its templates and an optional ACME server. P2S is off while the VPN is, + and S2S while the router is, until they are switched on. An active CA gives its CA + bundle; a pending CA, waiting for the offline root, gives its CSR and takes the certificate the + root signed, and one waiting for Simple CA is signed once the server reaches it. **Add issuing + CA**, **Edit** and **Remove** are for the custom CAs; a removed CA is retired and its + certificate revoked. The common name of a CA is fixed once the CA has its certificate or CSR: + a CA with another name is a new CA, added under a new name. Below, the certificates of all of + them, filtered by CA, each with its kind, template, names, expiry and state; one of another + system or of the server is revoked after a confirmation with a reason. + +## 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`. diff --git a/docs/dns.md b/docs/dns.md index ce889a7..a89e515 100644 --- a/docs/dns.md +++ b/docs/dns.md @@ -1,19 +1,20 @@ # DNS -The server's name server (PowerDNS), the primary of the server's domains. Every domain has the -same two name servers: the server's FQDN and a secondary name server. The [web sites](sites.md) -whose DNS is Router managed get their records in the domain they are in. +The server's name server (PowerDNS), the primary of the server's domains, on a page of its own, +in the page menu while the name server is on. Every domain has the same name servers: the server's +FQDN and, when one is set, a secondary name server. The [web sites](sites.md) whose DNS is Router +managed get their records in the domain they are in. ## Settings -- **State:** disabled, running, or not running yet; the server installs PowerDNS when it is - enabled. +- **State:** disabled, running, or not running yet. The name server is switched on the + [System](system.md) tab, which installs PowerDNS. - **Primary name server:** the server's FQDN, the SOA and the first NS of every domain. It is the server's name and is not edited here; its own A record is kept by the DNS of its domain, wherever that is, not by the server's domains. -- **Secondary name server:** the second NS of every domain, required while the name server is - enabled. The server notifies the addresses it resolves to of every change and allows them to - transfer the domains. +- **Secondary name server:** the second NS of every domain, optional; without it the server's FQDN + is the domains' only name server. The server notifies the addresses it resolves to of every + change and allows them to transfer the domains. - **Public IP address:** the server's public IP, which the records of the sites with Public IP take; empty when the server has none or no site uses it. - **Listen:** the interfaces port 53 is open on. While IKEv2 or OpenVPN remote access is enabled, diff --git a/docs/index.md b/docs/index.md index 4fc2045..1b2a27b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -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 pages; any other user sees only their own account. -The router and the VPN are components switched on in the server's configuration (`router.enabled` -and `vpn.enabled`). While the VPN is off the page menu has no Remote Access page; while the router -is off the Connectivity page shows only its Network tab. Without Docker on the server the page menu +The VPN, the router, the name server and WebDAV are components switched on the +[System](system.md) tab, which installs their software. While the VPN is off the page menu has no +Remote Access page; while the router is off the Connectivity page shows only its Network tab. Without Docker on the server the page menu has no Docker page. The help opens at the topic of the page you are on. Links between topics open in this panel; diff --git a/docs/remote-access.md b/docs/remote-access.md index 5d7f7cb..50247b1 100644 --- a/docs/remote-access.md +++ b/docs/remote-access.md @@ -3,9 +3,9 @@ A tab each for IKEv2, OpenVPN and WireGuard access: the settings, whether the server runs the system, why an enabled one does not run yet, and the connected clients. -The page is there while the VPN component is on (`vpn.enabled`). While the router component is -off, the clients reach the networks of `local.cidrs` through NAT from the server's address, on -its one interface; while it is on, they are routed with their own addresses. +The page is there while the VPN component is on, switched on the [System](system.md) tab. While +the router component is off, the clients reach the networks of `local.cidrs` through NAT from the +server's address, on its one interface; while it is on, they are routed with their own addresses. ## Edit diff --git a/docs/router.md b/docs/router.md index 0900d41..6aa838d 100644 --- a/docs/router.md +++ b/docs/router.md @@ -8,10 +8,7 @@ The Overview tab shows the state of the server, read every 10 seconds by default - **Status:** the overall status, ok or degraded, on its title bar; the installed version of `linux-manager` and, when the repository has a newer one, that version; - IKEv2, OpenVPN and WireGuard; the status web service and its port; HTTPS and the name it is for, - with a chip while the certificates come from Let's Encrypt's staging CA and a settings button - (see HTTPS settings below); and Caddy, its HTTPS proxy, with its version, where it comes from (Ubuntu or upstream) and the - state of `caddy.service`. + IKEv2, OpenVPN and WireGuard; and the status web service and its port. - **Services:** the state of each of the server's systemd services and of Caddy; the chip on the title bar tells whether the server's services are active. - **Addresses:** links to the status page over HTTPS and over plain HTTP, and to the @@ -23,19 +20,6 @@ The Overview tab shows the state of the server, read every 10 seconds by default - **Configuration:** the sections of the server's configuration the other pages do not show, among them the status web service (`web`) and HTTPS (`https`). -Caddy is switched to upstream's packages on the server as root with -`linux-manager-caddy use-upstream`. - -## HTTPS settings - -The settings button of the HTTPS row switches **Let's Encrypt staging CA**. While it is on, Caddy -takes every certificate, the web sites' included, from Let's Encrypt's staging environment, whose -rate limits are far higher but whose certificates no browser trusts: it is for routers that are -rebuilt often, for tests only. While it is off, Caddy takes its certificates from Let's Encrypt, -and from ZeroSSL when Let's Encrypt refuses, such as for its limit of 5 certificates a week for the -same name. Saving runs the server's setup again, which applies the change. The other HTTPS -settings are changed on the server with `linux-manager-config-edit`. - ## Updates - **Check update** asks the server's package repository for newer versions. diff --git a/docs/sites.md b/docs/sites.md index 54373a2..1432700 100644 --- a/docs/sites.md +++ b/docs/sites.md @@ -1,16 +1,17 @@ # Web sites Static web sites that Caddy serves on the server, each from its own folder, -`/var/lib/linux-manager/sites/`. The files of a site are on the [Files](site-files.md) tab, and -the name server of their domain on the [DNS](dns.md) tab. +`/var/lib/linux-manager/sites/`. The files of a site are on the [Files](site-files.md) tab, +and the name server of their domain on the [DNS](dns.md) page. ## Settings - **State:** whether the sites are served. - **Largest upload:** the largest file or zip archive the Files tab and the server's API take. -- **WebDAV:** whether the folders are served over WebDAV, and its URL with a copy icon. +- **WebDAV:** whether the folders are served over WebDAV, and its URL with a copy icon. WebDAV is + switched on the [System](system.md) tab, which installs rclone. -**Settings** edits them. +**Settings** edits the state, the largest upload and the WebDAV port. ## Columns @@ -18,12 +19,12 @@ the name server of their domain on the [DNS](dns.md) tab. name on its port. - **Port** and **Listen:** the TCP port, and the interfaces its firewall opens: internal, external or both. -- **TLS:** None (plain HTTP), Let's Encrypt, an issuing CA of the Certificates page, or a - certificate and key given with the site. +- **TLS:** None (plain HTTP), ACME, from the CA set on the Server tab of the Certificates page, + an issuing CA of the same page, or a certificate and key given with the site. - **Editors:** the group whose members may change the files besides the admins. - **DNS:** who serves the records of the host names. **User managed:** a DNS provider outside the router. **Router managed:** the server's name server gives each host name an A or AAAA record in - its domain on the [DNS](dns.md) tab, with the server's **Public IP** (the Public IP address of + its domain on the [DNS](dns.md) page, with the server's **Public IP** (the Public IP address of the DNS settings), **Internal interface IP** or **External interface IP**. A host name in none of the server's domains gets no record. @@ -39,9 +40,11 @@ the DNS of its domain. ## Rules -- The server's own ports, such as 22, 7081, 7443, 7444 and 7445, cannot be taken by a site. +- The server's own ports, such as 22, 7080, 7081, 7443, 7444 and 7445, and the loopback ports of + its services, 7090, 7091 and 9474, cannot be taken by a site. - Sites sharing a port need host names of their own, the same Listen and the same kind of TLS. -- Let's Encrypt needs host names that resolve to the server from the internet, and port 80. +- ACME with a public CA needs host names that resolve to the server from the internet, and port + 80. - A certificate and key must belong together and name the host names. - An issuing CA's certificates are trusted by browsers that trust the server's root CA. diff --git a/docs/system.md b/docs/system.md index b4d9bbc..bb09761 100644 --- a/docs/system.md +++ b/docs/system.md @@ -1,6 +1,6 @@ # System -The System tab manages the server's operating system. +The System tab manages the server's operating system and its installable components. ## System updates @@ -15,3 +15,19 @@ The System tab manages the server's operating system. - A reboot is offered when a package asks for one, as after a new kernel. - Only one upgrade runs at a time: this one or the upgrade of `linux-manager` on the [Overview](router.md) tab. + +## Components + +- The panel lists the **VPN** (IKEv2, OpenVPN and WireGuard), the **Router** (routing between two + interfaces and site-to-site IPsec), the **Name server** (PowerDNS) and **WebDAV** (the sites' + folders), each on or off, with its packages not installed, installing, installed or failed. +- **Enable** switches a component on. The server installs its packages from the Ubuntu archive, + which takes a minute or so, and then runs it; the panel follows the installation. +- **Disable** switches a component off after a confirmation. Its settings and its packages are + kept. The VPN cannot be switched off while IKEv2, OpenVPN or WireGuard is enabled, nor the + router while site-to-site connections exist. +- The router needs a second network interface: without one it is shown unavailable. Its + **Enable** asks for the internal interface and, in `manual` mode, its address with the prefix + length and the gateway of the internal network. +- A failed installation shows **Enable** again, which tries once more; the + [Logs](logs.md) tab has the output of `linux-manager-install@`. diff --git a/tests/remote/README.md b/tests/remote/README.md index 97c7099..b703784 100644 --- a/tests/remote/README.md +++ b/tests/remote/README.md @@ -3,20 +3,26 @@ The scripts are in `bin/` of the repository; this directory holds their data: `scenarios/`, `configs/`, `cloud-init/`, `repo/` and the files copied into instances. -`bin/lm-dev-run.py` installs the newest `out/linux-manager_*_all.deb` into instances of an LXD -remote and checks the router and VPN components in three scenarios: +`bin/lm-dev-run.py` installs the package built last, a release in `out/` or a dev build in +`out/dev/`, or the one `--deb` names, into instances of an LXD remote and checks the server in four +scenarios: - `core`: one interface, router and VPN off; - `nat`: VPN on, router off, one interface; WireGuard and OpenVPN clients reach a target through NAT, then the VPN is switched off; - `s2s`: router and VPN on, two sites with two interfaces each, a site-to-site connection with a pre-shared key, and a routed WireGuard client; the router is then switched off while - `site_to_site` is set, which setup refuses. + `site_to_site` is set, which setup refuses; +- `oidc`: HTTPS with a certificate of the Servers CA and the OpenID Provider on; the scenario's + Vault, a relying party with its `auth/oidc` method, signs the user alice in with the + authorization code flow and PKCE, her password and a TOTP code of the Vault, driven in a client + by `oidc_login.py` as a browser would, and a wrong code is refused. Servers are virtual machines, clients and LAN hosts containers, all from `ubuntu:26.04`. Each scenario is a module in `scenarios/` whose `run(lab)` uses the `Lab` class of `lm-dev-run.py`. -`wireguard_peer.py` and `echo.py` are copied into the instances: the first gives the test user a -WireGuard peer on the server, the second answers HTTP with the client's address. +`wireguard_peer.py`, `echo.py` and `oidc_login.py` are copied into the instances: the first gives +the test user a WireGuard peer on the server, the second answers HTTP with the client's address, +and the third signs a user in at the server's OpenID Provider. ```sh export LXD_REMOTE=... @@ -41,32 +47,75 @@ Options: | `--project` | `LXD_TEST_PROJECT` | `lm-test` | The project the instances live in; it must not exist | | `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of every instance | | `--keep` | | off | Leaves the project and the networks in place; run one scenario then | +| `--deb` | | the package built last | The package to test | Each scenario creates the project and its networks (`lmt--`) and removes them at -its end. The administrator password and the pre-shared key are generated per run. The -administrator's name and password are set as `ADMIN_USERNAME` and `ADMIN_PASSWORD` in the -repository's `.env`, keeping its other lines, and the key is written to `tmp/remote-test.env`. +its end. Its first instance is its Vault, `lm-vault` on the bridge `lmt-vault` (`10.99.99.0/24`), +reached by the Mac and the instances on the LXD host's address, port 8200, through a proxy +device; every secret reaches an instance through it (see Secrets). The administrator password and +the pre-shared key are generated per run and kept in the scenario's Vault, as `/admin` and +`/config`; with `--keep` they stay there. The run leaves `.env` as it is. The run prints PASS, FAIL or SKIP per check and exits non-zero on a failure; WireGuard is skipped when the host kernel has no WireGuard module. The configurations in `configs/` have placeholders that are filled in for each server: -- `@PSK@`: the pre-shared key; +- `@PSK@`: the pre-shared key, filled in on the Mac; the file reaches the server through the Vault; - `@ETH0@` and `@ETH1@`: the names of its interfaces; - `@CIDR0@`: the network of its first address. +## Secrets + +A secret never reaches an instance as a command-line argument or on standard input, where `ps`, +`/proc//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-`, which reads `kv/data//*` and creates the TOTP + keys `totp/keys/-*`, and the role ``, 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//`, 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 +`/admin`. A WireGuard client's private key is made in the client and never leaves it. + +A user's TOTP token is the key `-` 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 is never on the +Mac and cannot be read back from the Vault, which gives the codes (`totp/code/-`). +`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://:8200/ui`; it signs in with +the root token of `vault-.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 project's state and repository key, the +Vault's address, unseal key and root token (`vault-.json`). `tmp/` holds +only what can go: logs and files removed right after use. + ## A VM to work with `lm-dev-vm.py create` launches one server VM, `lm-dev` by default, on the LXD remote and leaves it running. The VM is created in a project, the test project `lm-dev` by default, with that project's default profile, and takes its address from DHCP. It gets the package with the administrator `admin` and a generated password, set as `ADMIN_USERNAME` and `ADMIN_PASSWORD` in the -repository's `.env`, and a configuration from `configs/`, `core.json` by default; `@ETH0@` is the -interface of the VM's default route. +repository's `.env`, a TOTP token for `admin` in the project's Vault unless `--no-otp` is given, +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 -repository, so later dev builds reach it as updates; in another project it installs the newest -`out/linux-manager_*_all.deb`. The leased address is pinned on the VM's NIC, and these ports lead +repository, so later dev builds reach it as updates; in another project it installs `--deb`, or +else the package built last, in `out/` or `out/dev/`. The leased address is pinned on the VM's NIC, and these ports lead to the VM: - `7080` to the Manager; @@ -74,13 +123,13 @@ to the VM: - `2222` to SSH, port `22`. In a test project they lead through a network forward on the project's `wan`, whose listen address -LXD allocates from the uplink's `--routes`, as LXD refuses NAT proxy devices in a project with -networks of its own. In another project NAT proxy devices listen on the LXD host address -`--listen`, by default the IPv4 address of the host in the remote's URL (`lxc remote list`), which -must be an address of the LXD host itself. +is `--forward-address`, or else one LXD allocates from the uplink's `--routes`, as LXD refuses +NAT proxy devices in a project with networks of its own. In another project NAT proxy devices +listen on the LXD host address `--listen`, by default the IPv4 address of the host in the remote's +URL (`lxc remote list`), which must be an address of the LXD host itself. -The script prints the VM's address, the administrator's password, the URLs, the command of a -shell in it and the command that removes it. +The script prints the VM's address, where the administrator's password is kept, the URLs, the +command of a shell in it and the command that removes it; it never prints the password. ```sh bin/lm-dev-vm.py create @@ -90,8 +139,10 @@ bin/lm-dev-vm.py create bin/lm-dev-vm.py remove ``` -`remove` deletes the VM, its forward and `tmp/vm-.env`, its pre-shared key; `.env` is left as -it is. Options: +`create` needs the project's Vault (`lm-dev-lxd-project.py vault create`): the VM gets its +AppRole there, and reads the preseed and the configuration, kept as `/preseed` and +`/config`, and creates the TOTP key `-admin` with it. `remove` deletes the VM, its forward +and what the Vault keeps for it; `.env` is left as it is. Options: | Option | Variable | Default | Meaning | |---|---|---|---| @@ -101,6 +152,9 @@ it is. Options: | `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of the VM | | `--config` | | `core.json` | The configuration from `configs/` | | `--listen` | `LXD_LISTEN` | the remote URL's host | 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 @@ -114,11 +168,21 @@ project has: gateway; - a default profile with a root disk on the pool and `eth0` on `wan`; - the container `repo`, whose nginx serves a signed apt repository of the dev builds, - `resolute main` for amd64 and arm64, at its pinned address. + `resolute main` for amd64 and arm64, at its pinned address; +- the container `vault`, the project's Vault (see Secrets), reached by the Mac through a forward + of port 8200 on `wan` at `--vault-address` (`LXD_VAULT_ADDRESS`), or an allocated address, and + by the instances on its pinned address. What the other scripts need, the repository's URL among it, is written to -`tmp/lxd-project-.json`, and the repository's key to `tmp/lxd-project-.gpg`. -`remove` deletes the project's instances, its networks, the project and those files. +`.lm-dev-config/lxd-project-.json`, and the repository's key to +`.lm-dev-config/lxd-project-.gpg`. `remove` deletes the project's instances, its networks, +the project and those files. + +```sh +bin/lm-dev-lxd-project.py vault create # the Vault of an existing project +bin/lm-dev-lxd-project.py vault unseal # after a restart of the vault container +bin/lm-dev-lxd-project.py vault remove +``` The remote needs OVN, set up as LXD's standalone OVN guide describes, and a host bridge on the LAN, whose host address stays on the bridge. `uplink setup` creates on it, once per remote, the @@ -156,6 +220,7 @@ bin/lm-dev-lxd-project.py remove | `--pool` | `LXD_POOL` | required by `create` | The storage pool of the project's root disks | | `--project` | `LXD_PROJECT` | `lm-dev` | The project | | `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of the repository container | +| `--vault-address` | `LXD_VAULT_ADDRESS` | allocated | The listen address of the Vault's forward, one of the uplink's routes | | `--uplink` | `LXD_UPLINK` | `uplink` | The physical uplink network of the OVN networks | | `--parent` | `LXD_UPLINK_PARENT` | required by `uplink setup` | The host bridge on the LAN | | `--gateway` | `LXD_UPLINK_GATEWAY` | required by `uplink setup` | The LAN's gateway, address/prefix | @@ -167,8 +232,8 @@ bin/lm-dev-lxd-project.py remove entry's with `~dev` before the Debian revision, `0.41.0~dev7-1` for `0.41.0-1`, so the release of that entry is newer than its dev builds. `N` is that of the last dev build, kept in `.dev-build.serial` of the repository; each build that succeeds writes its own, one higher, and -`release.py` writes 0 when it releases, so the next entry's builds start at `~dev1`. `./build.sh` builds it, with `CONTAINER_RUNTIME` and `DOCKER_CONTEXT` from the -environment; the build is moved to `out/dev/`, copied into the repository and published there. A +`release.py` writes 0 when it releases, so the next entry's builds start at `~dev1`. `./build.sh` +builds it, with `CONTAINER_RUNTIME` and `DOCKER_CONTEXT` from the environment; the build is moved to `out/dev/`, copied into the repository and published there. A VM of the project then gets it with Check update and Upgrade in the Manager, or `apt-get update` and `apt-get upgrade`. @@ -182,36 +247,39 @@ read from its state file, so the script takes no `--remote`. ## A TOTP token for a user of a test VM `bin/lm-dev-otp-register.py` enrols a new TOTP token for a user of a VM, `admin` of `lm-dev` by -default, through `lxc exec`: in the VM, as root, the package's `linuxmanager_users` makes a new -secret and stores it once a code the script computes from it verifies, replacing a token the user -had. The secret, base32, is then written to the file `--secret-file` or `OTP_FILE` names, -readable by its owner only; `otp.py code` prints its codes (see below). +default, replacing a token the user had. The project's Vault generates the key `-` in its +TOTP engine and hands it to the VM (see Secrets), where the package's `linuxmanager_users` stores +it. `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 -export OTP_FILE=tmp/admin.otp bin/lm-dev-otp-register.py ``` +```sh +bin/lm-dev-otp-code.py +``` + | Option | Variable | Default | Meaning | |---|---|---|---| -| `--secret-file` | `OTP_FILE` | required | The file the secret is written to | -| `--remote` | `LXD_REMOTE` | required | The `lxc` remote | +| `--remote` | `LXD_REMOTE` | required by `lm-dev-otp-register.py` | The `lxc` remote | | `--project` | `LXD_PROJECT` | `lm-dev` | The project of the VM | | `--vm` | | `lm-dev` | The name of the VM | -| `--user` | | `admin` | The user to enrol | +| `--user` | | `admin` | The user | ## A command-line authenticator app `bin/otp.py` is an authenticator app on the command line, in place of one on a phone, not tied to -Linux Manager or LXD. It keeps a base32 secret in the file `--secret-file` or `OTP_FILE` names, -readable by its owner only. The codes are -RFC 6238's, SHA-1, 6 digits and 30 seconds by default. +Linux Manager or LXD. It keeps a secret in the file `--secret-file` or `OTP_FILE` names, readable +by its owner only: the base32 secret alone, or with `--url` its `otpauth://` URI, without a line +end, so Vault's TOTP engine imports the file as it is. The codes are RFC 6238's, SHA-1, 6 digits +and 30 seconds by default; a file holding a URI gives the URI's. Options of both actions: | Option | Variable | Default | Meaning | |---|---|---|---| -| `--secret-file` | `OTP_FILE` | required | The file of the base32 secret | +| `--secret-file` | `OTP_FILE` | required | The file of the base32 secret or its `otpauth://` URI | | `--algorithm` | | `sha1` | `sha1`, `sha256` or `sha512` | | `--digits` | | `6` | The digits of a code, 6 to 10 | | `--period` | | `30` | The seconds a code is valid | @@ -223,9 +291,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 ``` +Either file is a key of Vault's TOTP engine, the secret with its settings, or the URI with all of +them: + +```sh +vault write totp/keys/admin key=@secret-file issuer=lm-dev account_name=admin +vault write totp/keys/admin url=@otpauth-file +``` + | Option | Default | Meaning | |---|---|---| | `--account`, `--issuer` | none | The label of the URI | +| `--url` | off | Store the `otpauth://` URI instead of the secret alone | | `--force` | off | Replace an existing secret | `code` prints the current code of the secret, for the Manager's sign-in, SSH or `sudo`: @@ -240,5 +317,5 @@ bin/otp.py code ## Scope of the tests -Not covered by `lm-dev-run.py`: IKEv2 client access, HTTPS with Let's Encrypt, the OpenID -Provider and passkeys, PowerDNS answering from outside, and the Azure and GCP platform modules. +Not covered by `lm-dev-run.py`: IKEv2 client access, HTTPS with Let's Encrypt, passkeys, +PowerDNS answering from outside, and the Azure and GCP platform modules. diff --git a/tests/remote/cloud-init/vault.yaml b/tests/remote/cloud-init/vault.yaml new file mode 100644 index 0000000..26964e1 --- /dev/null +++ b/tests/remote/cloud-init/vault.yaml @@ -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 diff --git a/tests/remote/configs/oidc.json b/tests/remote/configs/oidc.json new file mode 100644 index 0000000..db3fd74 --- /dev/null +++ b/tests/remote/configs/oidc.json @@ -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} +} diff --git a/tests/remote/lm-dev-vault b/tests/remote/lm-dev-vault new file mode 100755 index 0000000..f14a20c --- /dev/null +++ b/tests/remote/lm-dev-vault @@ -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() diff --git a/tests/remote/oidc_login.py b/tests/remote/oidc_login.py new file mode 100644 index 0000000..f4d4868 --- /dev/null +++ b/tests/remote/oidc_login.py @@ -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()) diff --git a/tests/remote/scenarios/core.py b/tests/remote/scenarios/core.py index 4e7f3e5..dfcde4e 100644 --- a/tests/remote/scenarios/core.py +++ b/tests/remote/scenarios/core.py @@ -19,13 +19,15 @@ def run(lab): 'lm-core', 'cat', '/etc/ufw/before.rules') 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('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'", '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$', '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 {} 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')) user = lab.alice('lm-core') lab.result('core: VPN user has no certificate', user is not None and not user.get('certificate')) diff --git a/tests/remote/scenarios/nat.py b/tests/remote/scenarios/nat.py index b5f9861..2fde902 100644 --- a/tests/remote/scenarios/nat.py +++ b/tests/remote/scenarios/nat.py @@ -47,8 +47,8 @@ def run(lab): 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', '') - lab.push_text(profile, 'lm-nat-client', '/root/alice.ovpn', '0600') - lab.push_text(f'alice\n{lab.admin_password}\n', 'lm-nat-client', '/root/alice.pass', '0600') + lab.hand_over('lm-nat-client', 'openvpn-profile', profile, '/root/alice.ovpn') + 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', 'openvpn', '--config', '/root/alice.ovpn', '--auth-user-pass', '/root/alice.pass', '--route-nopull', '--disable-dco', '--route', target, '255.255.255.255', diff --git a/tests/remote/scenarios/oidc.py b/tests/remote/scenarios/oidc.py new file mode 100644 index 0000000..6218548 --- /dev/null +++ b/tests/remote/scenarios/oidc.py @@ -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')) diff --git a/web/src/AccountPanel.tsx b/web/src/AccountPanel.tsx index b4645e2..8a6d706 100644 --- a/web/src/AccountPanel.tsx +++ b/web/src/AccountPanel.tsx @@ -11,15 +11,19 @@ import { useEffect, useState, type FormEvent } from 'react' import OtpDialog from './OtpDialog.tsx' import PasskeyDialog from './PasskeyDialog.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' +/** 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, * 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 * 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 }) { const [account, setAccount] = useState(null) @@ -35,6 +39,7 @@ export default function AccountPanel(props: { onPasswordChanged: () => void }) { const [addingPasskey, setAddingPasskey] = useState(false) const [profile, setProfile] = useState<'openvpn' | 'apple' | null>(null) const [passkeyError, setPasskeyError] = useState(null) + const board = useBoard(LAYOUT_KEY) useEffect(() => { request('GET', '/account', ACCOUNT_SHAPE) @@ -100,20 +105,28 @@ export default function AccountPanel(props: { onPasswordChanged: () => void }) { ['One-time passwords', account.otp ? 'enrolled' : 'not enrolled'], ] - return ( - -
- - {rows.map(([label, value]) => ( - - {label} - {value} - - ))} - - -
-
+ const panels: BoardPanel[] = [ + { + id: 'account', + title: 'Account', + content: ( + <> + + {rows.map(([label, value]) => ( + + {label} + {value} + + ))} + + + + ), + }, + { + id: 'passkeys', + title: 'Passkeys', + content: ( {passkeyError && {passkeyError}} {account.passkeys.length === 0 @@ -144,8 +157,12 @@ export default function AccountPanel(props: { onPasswordChanged: () => void }) { )} -
-
+ ), + }, + { + id: 'otp', + title: 'One-time passwords', + content: ( {account.otp @@ -154,15 +171,26 @@ export default function AccountPanel(props: { onPasswordChanged: () => void }) { -
- {account.certificate && ( -
- - - - -
- )} + ), + }, + ...(account.certificate ? [{ + id: 'profiles', + title: 'VPN profiles', + content: ( + + + + + ), + }] : []), + ] + + return ( + + + + +
Change password diff --git a/web/src/AcmeSettingsDialog.tsx b/web/src/AcmeSettingsDialog.tsx new file mode 100644 index 0000000..d29216e --- /dev/null +++ b/web/src/AcmeSettingsDialog.tsx @@ -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 = { + 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 + onCancel: () => void +}) { + const current = props.current + const [provider, setProvider] = useState(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(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 ( + reason !== 'backdropClick' && props.onCancel()} maxWidth="sm" fullWidth slotProps={{ paper: { component: 'form', onSubmit: submit } }}> + ACME CA + + + {error && {error}} + + Caddy takes certificates from this CA for the server, when its certificate is ACME, and for the web sites with TLS ACME. + + setProvider(event.target.value as AcmeProvider)}> + {ACME_PROVIDERS.map((item) => {PROVIDER_LABELS[item]})} + + {provider === 'letsencrypt' && ( + setStaging(event.target.checked)} />} label="Staging environment, for tests: no browser trusts its certificates" /> + )} + {provider === 'zerossl' && ( + setApiKey(event.target.value.trim())} + /> + )} + {custom && ( + <> + setUrl(event.target.value.trim())} + /> + setKeyId(event.target.value.trim())} /> + setMacKey(event.target.value.trim())} + /> + + )} + The server runs its setup again, which applies the change. + + + + + + + + ) +} diff --git a/web/src/App.tsx b/web/src/App.tsx index e623164..aea6054 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -14,7 +14,7 @@ import LogsPanel from './LogsPanel.tsx' import MetricsPanel from './MetricsPanel.tsx' import DockerPanel from './DockerPanel.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 RemoteAccessPanel from './RemoteAccessPanel.tsx' import ServerPanel from './ServerPanel.tsx' @@ -31,7 +31,7 @@ import SiteToSiteStatusPanel from './SiteToSiteStatusPanel.tsx' import ThemeMenu from './ThemeMenu.tsx' import UsersPanel from './UsersPanel.tsx' 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, } from './api.ts' @@ -39,16 +39,16 @@ import { type View = 'router' | 'metrics' | 'logs' | 'backup' | 'system' type UsersView = 'users' | 'groups' | 'service-accounts' 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. */ -const SITES_TOPICS: Record = { sites: 'sites.md', files: 'site-files.md', dns: 'dns.md' } +const SITES_TOPICS: Record = { 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. */ const RETURN_KEY = 'linux-manager-ui.return:' /** 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. */ const HELP_TOPICS: Record = { @@ -56,6 +56,7 @@ const HELP_TOPICS: Record = { [SITE_TO_SITE_PATH]: 'site-to-site.md', [REMOTE_ACCESS_PATH]: 'remote-access.md', [CA_PATH]: 'certificates.md', + [DNS_PATH]: 'dns.md', [DOCKER_PATH]: 'docker.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 * 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 - * 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 * 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 @@ -86,12 +87,17 @@ export default function App(props: { info: Info }) { const [sitesView, setSitesView] = useState('sites') const [filesSite, setFilesSite] = useState(null) const [session, setSession] = useState(undefined) + // /api/info again once signed in, as the version is told only with a session. + const [info, setInfo] = useState(props.info) 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; // 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 vpnOff = components?.vpn === false + const dnsOff = components?.dns === false const dockerMissing = components?.docker === false const page = PAGE_PATHS.find((path) => path === window.location.pathname) ?? '/' const userPage = page === USER_PATH @@ -137,6 +143,7 @@ export default function App(props: { info: Info }) { request('GET', '/account', ACCOUNT_SHAPE) .then((account) => setRole({ name: session.name, admin: account.admin })) .catch(() => setRole({ name: session.name, admin: false })) + request('GET', '/info', INFO_SHAPE).then(setInfo).catch(() => undefined) }, [session]) useEffect(() => { @@ -147,10 +154,11 @@ export default function App(props: { info: Info }) { .then((details) => setComponents({ router: details.configuration.router?.enabled === true, vpn: details.configuration.vpn?.enabled === true, + dns: details.configuration.dns?.enabled === true, docker: details.docker.installed, })) .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. */ function toggle(path: string) { @@ -184,14 +192,16 @@ export default function App(props: { info: Info }) { Ubuntu Linux Manager - - {props.info.version ?? 'development'} - + {session && ( + + {info.version ?? 'development'} + + )} Server status page:{' '} - {props.info.status_url - ? {props.info.status_url} + {info.status_url + ? {info.status_url} : not configured} @@ -244,7 +254,7 @@ export default function App(props: { info: Info }) { )} {session && admin && ( -