diff --git a/HANDOVER.md b/HANDOVER.md index 356f8ae..172454b 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -36,6 +36,9 @@ it had published before, which also removed the configuration's record if the na - The `addr` column of `show stat` is empty. The web UI (`loadbalancer.go`) reads addresses from `show servers state` (`srv_addr`, `srv_port`). The `loadbalancer` VM test checks that the real HAProxy has the columns the page reads; keep it when upgrading HAProxy. +- Certificates and CA files live in `/var/lib/router` (0700 root), which HAProxy cannot enter: they go in through + `LoadCredential` and the config names `/run/credentials/haproxy.service/…` (`fileOf`). A path unit restarts + HAProxy when a file changes. 0.14.0 lacked this (fixed after the release; see the git log). - The stats socket is the NixOS module's `/run/haproxy/haproxy.sock`; `System.HAProxySocket` overrides it in tests. - A service's `hosts` become `router.dns.hosts` entries (`mkDefault`) pointing at the router's address in the LANs it listens in; that is how inside and outside use one name. diff --git a/SPECS.md b/SPECS.md index 2bf2cfb..a524b6e 100644 --- a/SPECS.md +++ b/SPECS.md @@ -252,6 +252,7 @@ A service on several hosts that must be reachable from outside and inside, with - **Listening:** `listen.port` and `listen.zones` (`wan` = the uplink, or the zones of LANs and tunnels). The firewall opens that port in those zones itself (`lbInput` in `firewall.nix`), so no rule is needed. IPv4 and IPv6 are bound apart: one dual-stack socket shows IPv4 clients as `::ffff:a.b.c.d` in `X-Forwarded-For` (found by the VM test). - **TLS, a decision per service:** `terminate` (the router decrypts with `certificate`, a PEM with chain and key, or with its own ACME certificate when `router.acme.domains` covers `hosts`; to the backends in the clear or, with `backendTls.enable`, encrypted again, verified only if `backendTls.verify`), `passthrough` (bytes only; the backends have the certificate, and only the checks speak TLS) or `none`. `protocol` is `http` (adds `X-Forwarded-For`) or `tcp` (always with passthrough). `proxyProtocol` sends the client's address to backends that read it (for tcp). +- **Files:** `certificate` and `backendTls.caFile` are paths in the state directory (the settings editor allows nothing else), which is 0700 root: HAProxy runs as its own user, so systemd reads the files as root and hands the service copies (`LoadCredential`, under `/run/credentials/haproxy.service/`; the configuration names those). A path unit restarts HAProxy when one of the files changes (a renewed certificate). Store paths are used as they are. (Found in use in 0.14.0: the `loadbalancer` test used store paths and so missed it; it now keeps both files in `/var/lib/router/lb/` and verifies the backends' certificate.) - **Backends:** names of DHCP reservations or IPv4 addresses, on `backendPort` (default the listen port). `balance`: `roundrobin`, `leastconn`, `source`. Checks: an HTTP GET of `check.path` (2xx/3xx) every `check.interval`, `fall` failures take a backend out, `rise` successes bring it back; `check.useHttp = false` only connects. With no backend up the service answers 503. - **Host names:** `hosts` is the Host header or TLS name that selects the service, so services may share a port (each needs `hosts`; they must agree on `tls` and `protocol`). The names are also published in the local DNS (`dns.hosts`, `mkDefault`) as the router's addresses on the LANs the service listens in, so inside and outside use the same name. This is the host-based routing that was open for ports 80/443 (TLS name or Host header; the web UI's own port still has to be another one). - **Assertions:** a backend that is neither a reservation nor an address, an unknown zone, a port the router itself uses (SSH, DNS, the web UI) or that `firewall.nat` forwards, shared ports without `hosts`, services on a port that disagree, passthrough with `http`, no certificate without ACME, a certificate that does not cover `hosts`. diff --git a/modules/router/loadbalancer.nix b/modules/router/loadbalancer.nix index b3c7ed8..32e20b1 100644 --- a/modules/router/loadbalancer.nix +++ b/modules/router/loadbalancer.nix @@ -13,9 +13,24 @@ let isAddress = b: builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" b != null; addressOf = b: if isAddress b then b else reserved.${b} or null; + # Files the services name (certificates with their keys, certificate + # authorities). The settings editor only accepts paths in the state directory + # (0700 root), which HAProxy, a user of its own, cannot enter: systemd reads + # them as root and hands HAProxy copies (LoadCredential). Store paths are + # public and are used as they are. + isStore = p: lib.hasPrefix "/nix/store/" (toString p); + filesOf = + lb: + lib.optional (lb.tls == "terminate" && lb.certificate != null) lb.certificate + ++ lib.optional (lb.backendTls.caFile != null) lb.backendTls.caFile; + privateFiles = lib.unique (map toString (lib.filter (p: !isStore p) (lib.concatMap filesOf (lib.attrValues lbs)))); + credentialName = p: "lb" + lib.replaceStrings [ "/" ] [ "_" ] p; + fileOf = + p: if isStore p then toString p else "/run/credentials/haproxy.service/${credentialName (toString p)}"; + backendPort = lb: if lb.backendPort != null then lb.backendPort else lb.listen.port; usesAcme = lb: lb.tls == "terminate" && lb.certificate == null; - certOf = lb: if lb.certificate != null then toString lb.certificate else acmePem; + certOf = lb: if lb.certificate != null then fileOf lb.certificate else acmePem; # Services by port: one frontend each, the host name chooses the backend. ports = lib.unique (map (n: lbs.${n}.listen.port) names); @@ -69,7 +84,7 @@ let secure = lb.backendTls.enable; verify = if lb.backendTls.verify then - "verify required${lib.optionalString (lb.backendTls.caFile != null) " ca-file ${toString lb.backendTls.caFile}"}" + "verify required${lib.optionalString (lb.backendTls.caFile != null) " ca-file ${fileOf lb.backendTls.caFile}"}" else "verify none"; # Passthrough sends the client's bytes as they are: only the checks speak TLS. @@ -119,6 +134,25 @@ in config = haproxyConfig; }; + systemd.services.haproxy.serviceConfig.LoadCredential = map (p: "${credentialName p}:${p}") privateFiles; + + # HAProxy has its copies from when it started: a file that changes (a + # renewed certificate) needs it restarted. + systemd.paths.router-lb-files = lib.mkIf (privateFiles != [ ]) { + wantedBy = [ "multi-user.target" ]; + pathConfig = { + PathChanged = privateFiles; + Unit = "router-lb-files.service"; + }; + }; + systemd.services.router-lb-files = lib.mkIf (privateFiles != [ ]) { + description = "Restart the load balancers for changed certificates"; + serviceConfig = { + Type = "oneshot"; + ExecStart = "${config.systemd.package}/bin/systemctl restart haproxy.service"; + }; + }; + # The router's own certificate, for services that decrypt with it. security.acme.certs = lib.mkIf (acme.enable && lib.any (n: usesAcme lbs.${n}) names) { ${acmeName} = { diff --git a/tests/loadbalancer.nix b/tests/loadbalancer.nix index da65682..f176c8b 100644 --- a/tests/loadbalancer.nix +++ b/tests/loadbalancer.nix @@ -129,6 +129,13 @@ pkgs.testers.runNixOSTest { networking.interfaces.eth1.ipv4.addresses = lib.mkForce [ ]; networking.interfaces.eth2.ipv4.addresses = lib.mkForce [ ]; + systemd.tmpfiles.rules = [ + "d /var/lib/router 0700 root root -" + "d /var/lib/router/lb 0700 root root -" + "C /var/lib/router/lb/both.pem 0600 root root - ${cert}/both.pem" + "C /var/lib/router/lb/ca.pem 0600 root root - ${cert}/cert.pem" + ]; + router = { enable = true; wan.interface = "eth1"; @@ -162,12 +169,18 @@ pkgs.testers.runNixOSTest { "main" ]; hosts = [ "api.lb.test" ]; - certificate = "${cert}/both.pem"; + # Files in the router's state directory, as the settings editor requires: + # 0700 root, so HAProxy (its own user) cannot read them itself. + certificate = "/var/lib/router/lb/both.pem"; backends = [ "hv1" "hv2" ]; - backendTls.enable = true; + backendTls = { + enable = true; + verify = true; + caFile = "/var/lib/router/lb/ca.pem"; + }; check.path = "/healthz"; check.interval = "1s"; check.fall = 2; @@ -279,6 +292,13 @@ pkgs.testers.runNixOSTest { with subtest("the port is closed where the service does not listen"): client.fail("curl -sk --max-time 3 https://192.168.10.1:9443/") + with subtest("HAProxy only has copies of the files: a changed one restarts it"): + pid = router.succeed("systemctl show -p MainPID --value haproxy.service").strip() + router.succeed("echo >> /var/lib/router/lb/both.pem") + router.wait_until_succeeds(f"test $(systemctl show -p MainPID --value haproxy.service) != {pid}", timeout=60) + router.wait_until_succeeds("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | grep -c ',UP,' | grep -qx 6", timeout=60) + assert names(answers(upstream, outside)) == {"name=hv1", "name=hv2"} + with subtest("a backend that fails its check gets no connections, and returns when it passes"): hv1.succeed("touch /tmp/sick") router.wait_until_succeeds("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | grep '^be_api,hv1' | grep -q ',DOWN,'", timeout=60)