Files
nixos-router/modules/router/loadbalancer.nix
T
nils 20ec791827 Hand certificates and CA files to HAProxy as credentials
The settings only allow paths in the state directory, which is 0700 root
and which HAProxy (a user of its own) cannot enter. systemd reads the
files and gives the service copies; a path unit restarts it when one
changes. The load balancer test keeps its files in the state directory
now, and verifies the backends' certificate.
2026-11-28 21:23:09 +01:00

177 lines
6.8 KiB
Nix

{ config, lib, ... }:
let
cfg = config.router;
lbs = cfg.loadBalancers;
names = lib.attrNames lbs;
lans = lib.attrValues cfg.lans;
acme = cfg.acme;
acmeName = if acme.domains == [ ] then "unset" else lib.head acme.domains;
acmePem = "/var/lib/acme/${acmeName}/full.pem";
# Reservation name -> address, across the LANs.
reserved = lib.foldl' (acc: l: acc // lib.mapAttrs (_: r: r.address) l.dhcp.reservations) { } lans;
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 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);
onPort = port: lib.filter (n: lbs.${n}.listen.port == port) names;
hostAcl =
lb: hosts:
let
list = lib.concatMapStringsSep " " (h: lib.toLower h) hosts;
in
if lb.tls == "passthrough" then
"{ req_ssl_sni -i ${list} }"
else if lb.protocol == "http" then
"{ hdr(host),field(1,:) -i ${list} }"
else
"{ ssl_fc_sni -i ${list} }";
frontend =
port:
let
members = onPort port;
first = lbs.${lib.head members};
certs = lib.unique (map (n: certOf lbs.${n}) (lib.filter (n: lbs.${n}.tls == "terminate") members));
withHosts = lib.filter (n: lbs.${n}.hosts != [ ]) members;
without = lib.filter (n: lbs.${n}.hosts == [ ]) members;
http = first.protocol == "http";
# (IPv4 and IPv6 apart: one dual-stack socket shows IPv4 clients as ::ffff:a.b.c.d.)
tlsArgs = lib.optionalString (first.tls == "terminate") (
" ssl ${lib.concatMapStringsSep " " (c: "crt ${c}") certs}${lib.optionalString http " alpn h2,http/1.1"}"
);
in
''
frontend fe_${toString port}
mode ${first.protocol}
bind 0.0.0.0:${toString port}${tlsArgs}
bind :::${toString port} v6only${tlsArgs}
${lib.optionalString (first.tls == "passthrough") ''
tcp-request inspect-delay 5s
tcp-request content accept if { req_ssl_hello_type 1 }
''}${lib.concatMapStrings (n: ''
use_backend be_${n} if ${hostAcl lbs.${n} lbs.${n}.hosts}
'') withHosts}${lib.concatMapStrings (n: ''
default_backend be_${n}
'') without}
'';
server =
lb: n: b:
let
addr = addressOf b;
secure = lb.backendTls.enable;
verify =
if lb.backendTls.verify then
"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.
traffic = lib.optionalString (secure && lb.tls != "passthrough") " ssl ${verify}";
checks = " check${lib.optionalString secure " check-ssl ${verify}"}${lib.optionalString lb.proxyProtocol " check-send-proxy"}";
proxy = lib.optionalString lb.proxyProtocol " send-proxy-v2";
in
" server ${lib.replaceStrings [ "." ] [ "-" ] b} ${addr}:${toString (backendPort lb)}${checks}${traffic}${proxy}";
backend = n: ''
backend be_${n}
mode ${lbs.${n}.protocol}
balance ${lbs.${n}.balance}
timeout check ${lbs.${n}.check.timeout}
default-server inter ${lbs.${n}.check.interval} fall ${toString lbs.${n}.check.fall} rise ${toString lbs.${n}.check.rise}
${lib.optionalString lbs.${n}.check.useHttp ''
option httpchk
http-check send meth GET uri ${lbs.${n}.check.path} ver HTTP/1.1 hdr Host ${
if lbs.${n}.hosts == [ ] then "localhost" else lib.head lbs.${n}.hosts
}
''}${lib.optionalString (lbs.${n}.protocol == "http") ''
option forwardfor
''}${
# (An unknown backend is an assertion's to report; the text must still be valid.)
lib.concatMapStringsSep "\n" (b: server lbs.${n} n b) (lib.filter (b: addressOf b != null) lbs.${n}.backends)
}
'';
haproxyConfig = ''
defaults
log stdout format raw local0
timeout connect 5s
timeout client 1m
timeout server 1m
timeout check 2s
option redispatch
retries 2
${lib.concatMapStringsSep "\n" frontend ports}
${lib.concatMapStringsSep "\n" backend names}
'';
in
{
config = lib.mkIf (cfg.enable && names != [ ]) {
services.haproxy = {
enable = true;
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} = {
group = "haproxy";
reloadServices = [ "haproxy.service" ];
};
};
# A service's names are the router's own for the LANs it listens in.
router.dns.hosts = lib.mkMerge (
map (
n:
let
lb = lbs.${n};
addrs = lib.concatMap (l: lib.optional (lib.elem l.zone lb.listen.zones) l.ipv4.address) lans;
in
lib.mkIf (addrs != [ ]) (lib.genAttrs lb.hosts (_: lib.mkDefault addrs))
) names
);
};
}