From e80b1cfb826cf2926d0d87007b77cbd6639773b5 Mon Sep 17 00:00:00 2001 From: tv Date: Tue, 17 Nov 2026 03:21:39 +0000 Subject: host: names in tcp:// and udp:// rules The guests' DNS resolves every name to the host, so ssh somename went to the host, even with a rule for somename's address. Now the rules can take names, tcp://NAME:PORT[-PORT]: the firewall update resolves them on the host (IPv4) into the VM's set, and writes their addresses to a hosts file per tap in /run/fcbr0-hosts, which the guests' dnsmasq reads (--hostsdir; such entries win over address=/#/). A timer resolves them again every 5 minutes. dnsmasq can't tell guests apart, so every guest gets those addresses for those names, but only VMs whose list has the rule can connect. fcbr0-firewall now runs as a static user, fcbr0-firewall, which owns /run/fcbr0-hosts, and may use IPv4 and IPv6 sockets, for resolving. --- modules/host/default.nix | 97 +++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 80 insertions(+), 17 deletions(-) (limited to 'modules') diff --git a/modules/host/default.nix b/modules/host/default.nix index 5e9480e..af1994a 100644 --- a/modules/host/default.nix +++ b/modules/host/default.nix @@ -85,18 +85,29 @@ tapsOf = user: lib.filter (t: t.user == user) taps; ipsOf = user: map (t: t.ip) (tapsOf user); - # tcp://ADDRESS[/PREFIXLEN]:PORT[-PORT] or udp://... (nft checks the - # numbers.) - portRule = "(tcp|udp)://[0-9]+(\\.[0-9]+){3}(/[0-9]+)?:[0-9]+(-[0-9]+)?"; + # tcp://ADDRESS[/PREFIXLEN]:PORT[-PORT], tcp://NAME:PORT[-PORT], or + # udp://... (nft checks the numbers.) + addressRule = "[0-9]+(\\.[0-9]+){3}(/[0-9]+)?"; + hostName = "[A-Za-z0-9][A-Za-z0-9-]*(\\.[A-Za-z0-9-]+)*"; + portRule = "(tcp|udp)://(${addressRule}|${hostName}):[0-9]+(-[0-9]+)?"; + + # The addresses of the names in the tcp:// and udp:// rules, as the + # firewall update resolves them, a hosts file per tap, for the guests' + # dnsmasq, so a guest connects to the addresses the rules allow. + hostsDir = "/run/fcbr0-hosts"; + # How often the names get resolved again. + refreshInterval = "5min"; # Puts the tcp:// and udp:// rules of the given taps' VMs (default: all; # a user's name means all of their taps) into the taps' nftables sets, - # one tap at a time, so one bad rule doesn't keep the others' out. + # one tap at a time, so one bad rule doesn't keep the others' out, with + # names resolved by the host (IPv4; a name that doesn't resolve allows + # nothing), and those names' addresses into the taps' hosts files. # Doesn't follow symlinks (it runs with CAP_NET_ADMIN, though not as # root, see fcbr0-firewall). firewallUpdate = pkgs.writeShellScript "fcbr0-firewall-update" '' set -fu - export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.gnugrep pkgs.gnused pkgs.nftables ]} + export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.gawk pkgs.getent pkgs.gnugrep pkgs.nftables ]} status=0 if test $# = 0; then set -- ${lib.escapeShellArgs (map (t: t.name) taps)} @@ -113,17 +124,38 @@ ${lib.concatMapStrings (t: " ${t.name}) user=${t.user} ;;\n") taps} esac list=$(head -c 256 ${vmDir}/$tap 2>/dev/null | head -n 1) || : file=${dir}/$user/$list - elements= + rules= if printf %s "$list" | grep -qxE '${listName}' && test -f "$file" && ! test -L "$file"; then - elements=$(head -c ${toString maxRulesSize} "$file" | grep -xE '${portRule}' | - sed -E 's#^(tcp|udp)://([^:]+):(.*)$#\2 . \1 . \3#' | paste -sd,) + rules=$(head -c ${toString maxRulesSize} "$file" | grep -xE '${portRule}') || : fi + elements= + hosts= + for rule in $rules; do + proto=''${rule%%://*} + rest=''${rule#*://} + host=''${rest%:*} + ports=''${rest##*:} + if printf %s "$host" | grep -qxE '${addressRule}'; then + addresses=$host + else + addresses=$(timeout 5 getent ahostsv4 "$host" | awk '{ print $1 }' | sort -u) || : + for a in $addresses; do + hosts="$hosts$a $host"$'\n' + done + fi + for a in $addresses; do + elements="$elements''${elements:+, }$a . $proto . $ports" + done + done { echo "flush set inet firecracker allow_$tap" if test -n "$elements"; then echo "add element inet firecracker allow_$tap { $elements }" fi - } | nft -f - || { echo "fcbr0-firewall: rules of $tap ($user: $list) not applied" >&2; status=1; } + } | nft -f - || { echo "fcbr0-firewall: rules of $tap ($user: $list) not applied" >&2; status=1; continue; } + # dnsmasq reads new and changed files, but not dot files. + printf %s "$hosts" | sort -u > ${hostsDir}/.$tap + mv ${hostsDir}/.$tap ${hostsDir}/$tap done exit $status ''; @@ -133,17 +165,20 @@ ${lib.concatMapStrings (t: " ${t.name}) user=${t.user} ;;\n") taps} # upstream). workerConnections = 5 * maxConnections * lib.length taps + 1024; - # How fcbr0-firewall runs: not as root, users' files are input. + # How fcbr0-firewall runs: not as root, users' files are input. A user + # of its own (not DynamicUser), for the hosts files. firewallService = { Type = "oneshot"; - DynamicUser = true; + User = "fcbr0-firewall"; + Group = "fcbr0-firewall"; AmbientCapabilities = [ "CAP_NET_ADMIN" ]; CapabilityBoundingSet = [ "CAP_NET_ADMIN" ]; NoNewPrivileges = true; ProtectSystem = "strict"; ProtectHome = true; PrivateTmp = true; - RestrictAddressFamilies = [ "AF_NETLINK" "AF_UNIX" ]; + ReadWritePaths = [ hostsDir ]; + RestrictAddressFamilies = [ "AF_NETLINK" "AF_UNIX" "AF_INET" "AF_INET6" ]; # nft, resolving }; # Where nginx keeps the CA: ca.key, and ca.pem for the guests (see @@ -175,6 +210,7 @@ ${lib.concatMapStrings (t: " ${t.name}) user=${t.user} ;;\n") taps} echo "RULE is DOMAIN (HTTPS, with subdomains, not decrypted)" echo " or DOMAIN/PATH-PREFIX (HTTPS, decrypted to check the path)" echo " or tcp://ADDRESS[/PREFIXLEN]:PORT[-PORT] (likewise udp://...)" + echo " or tcp://NAME:PORT[-PORT] (resolved by the host, IPv4)" echo "vms shows the running VMs' taps (as in the log), names and lists" echo "use switches a running VM to another list" } @@ -212,8 +248,10 @@ ${lib.concatMapStrings (t: " ${t.name}) user=${t.user} ;;\n") taps} if printf %s "$r" | awk '{ s = $0; sub(/^[a-z]+:\/\//, "", s) split(s, hp, ":"); split(hp[1], a, "/"); split(a[1], b, ".") - for (i = 1; i <= 4; i++) if (b[i] > 255) exit 1 - if (a[2] != "" && a[2] > 32) exit 1 + if (hp[1] ~ /^[0-9.\/]+$/) { + for (i = 1; i <= 4; i++) if (b[i] > 255) exit 1 + if (a[2] != "" && a[2] > 32) exit 1 + } else if (length(hp[1]) > 253) exit 1 n = split(hp[2], p, "-") for (i = 1; i <= n; i++) if (p[i] < 1 || p[i] > 65535) exit 1 if (n == 2 && p[1] > p[2]) exit 1 @@ -591,13 +629,16 @@ ${lib.concatMapStrings (t: " ip saddr ${t.ip} limit rate 10/second burst # run otherwise. DHCP, only the taps' fixed addresses, by MAC address # (see taps above), and DNS that resolves every name to 172.16.0.1 # without asking anyone else (local=/#/; it also makes AAAA queries get - # an empty answer instead of REFUSED, which can fail whole lookups). It only listens on fcbr0 + # an empty answer instead of REFUSED, which can fail whole lookups), but + # for the names in the VMs' tcp:// and udp:// rules, from the hosts files + # in hostsDir (which win over address=; for every guest, there's no + # telling guests apart here). It only listens on fcbr0 # (except-interface=lo, else it would also take 127.0.0.1:53 from a # resolver the host runs there); bind-dynamic copes with fcbr0 not being # there yet. systemd.services.fcbr0-dnsmasq = { wantedBy = [ "multi-user.target" ]; - after = [ "network.target" ]; + after = [ "network.target" "systemd-tmpfiles-setup.service" ]; serviceConfig = { RuntimeDirectory = "fcbr0-dnsmasq"; Restart = "on-failure"; @@ -615,6 +656,7 @@ ${lib.concatMapStrings (t: " ip saddr ${t.ip} limit rate 10/second burst "--no-hosts" "--address=/#/172.16.0.1" "--local=/#/" + "--hostsdir=${hostsDir}" ] ++ map (t: "--dhcp-host=${t.mac},${t.ip}") taps); }; }; @@ -622,7 +664,11 @@ ${lib.concatMapStrings (t: " ip saddr ${t.ip} limit rate 10/second burst # Each user's lists, and each tap's choice of list, readable by anyone, # changeable only by the user (who can't replace the tap's file, though, # e.g. by a symlink). - systemd.tmpfiles.rules = [ "d ${dir} 0755 root root -" "d ${vmDir} 0755 root root -" ] + systemd.tmpfiles.rules = [ + "d ${dir} 0755 root root -" + "d ${vmDir} 0755 root root -" + "d ${hostsDir} 0755 fcbr0-firewall fcbr0-firewall -" + ] ++ lib.concatMap (u: [ "d ${dir}/${u} 0755 ${u} - -" "f ${dir}/${u}/default 0644 ${u} - -" @@ -652,6 +698,23 @@ ${lib.concatMapStrings (t: " ip saddr ${t.ip} limit rate 10/second burst ExecReload = firewallUpdate; }; }; + # Names get resolved again every refreshInterval. + systemd.services.fcbr0-firewall-refresh = { + after = [ "fcbr0-firewall.service" ]; + serviceConfig = firewallService // { + ExecStart = firewallUpdate; + }; + }; + systemd.timers.fcbr0-firewall-refresh = { + wantedBy = [ "timers.target" ]; + timerConfig.OnUnitActiveSec = refreshInterval; + timerConfig.OnActiveSec = refreshInterval; + }; + users.users.fcbr0-firewall = { + isSystemUser = true; + group = "fcbr0-firewall"; + }; + users.groups.fcbr0-firewall = { }; systemd.services."fcbr0-firewall@" = { after = [ "fcbr0-firewall.service" ]; serviceConfig = firewallService // { -- cgit v1.3.1