diff options
| author | tv <tv@krebsco.de> | 2026-11-21 04:10:08 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-21 04:10:08 +0000 |
| commit | 86d6f7341fedd5e0e78969d2c37829a0012dc3ae (patch) | |
| tree | a496937b50b8de3b612d997f1615e8977d9d8319 /modules/host | |
| parent | 4e35ef641c9bca1f63c3248877295fe61d4c1d20 (diff) | |
host: static addresses for VMs, by name, on whichever tap they run
A VM got the first free tap of its user's, and a tap's address came from
its number, so a VM's address depended on what else ran, and on the
users before it, and a reverse proxy on the host could only guess it
(172.16.0.2, i.e. fctap0, for hermes).
Now addresses are the VMs': the host module takes vms, VM name -> user
and address (vms = { hermes = { user = "tv"; ip = "172.16.0.2"; }; }),
any number of them, and a VM takes any free tap of its user's, which
gets its address while it runs, so at most as many run at the same
time as the user has taps. Taps have addresses of their own, for
VMs without one: from 172.16.0.200 on, so they stand out (but for VMs'
there). The MAC address, which dnsmasq hands out every address by, is
06:00 and the address (06:00:ac:10:00:02 for 172.16.0.2), and with it
the IPv6 addresses; the run script takes the VM's from /etc/fc-vms, or
the tap's own from /etc/fc-taps. The VMs' addresses are also in
config.fc.vms.NAME (user, ip, ip6), for the host's configuration, e.g.
proxyPass = "http://${config.fc.vms.hermes.ip}:9120";
Which address a tap has is up to fcbr0-firewall, which now also runs
when a tap's VM's name (/run/fc-egress/TAP.name, which the run script
writes) changes: the VM's, if it's one of the tap's user's in vms and
on none of their other taps, too, else the tap's own. It puts it into
the tap's new nftables sets addr_TAP and addr6_TAP, in the bridge's
table, which lets the tap send from nothing else (instead of the static
set guests), and in the other, whose per-tap rules go by them (instead
of the tap's fixed addresses); and into /run/fcbr0-addr, ADDRESS: TAP
and TAP: ADDRESS, where egress.lua finds a guest's tap (as long as both
agree, and the address and the tap are the same user's), and the run
script waits for its address before starting the guest. fc-egress vms
shows the taps' addresses, too.
Diffstat (limited to 'modules/host')
| -rw-r--r-- | modules/host/default.nix | 304 | ||||
| -rw-r--r-- | modules/host/egress.lua | 34 |
2 files changed, 253 insertions, 85 deletions
diff --git a/modules/host/default.nix b/modules/host/default.nix index 5df9a7c..144a23a 100644 --- a/modules/host/default.nix +++ b/modules/host/default.nix @@ -4,10 +4,18 @@ # running VM takes one tap device, so a user's number of taps is the number # of VMs they can run at the same time. # -# Each tap has a fixed address (172.16.0.2 for fctap0, and so on): dnsmasq -# hands it out by MAC address (the run script derives it from the tap's -# number), and the bridge drops anything coming from a tap with another -# source address, so a guest's address says whose it is. +# Addresses are the VMs' (see vms below), not the taps': a VM takes any of +# its user's taps, and gets its address there. dnsmasq hands out every +# address by MAC address (06:00 and the address, which the run script +# gives the guest, see /etc/fc-vms and /etc/fc-taps), and the bridge drops +# anything coming from a tap with another source address than its VM's, +# so a guest's address says which VM, and whose, it is. Which address a +# tap has is up to fcbr0-firewall (see firewallUpdate): the VM's, by its +# name (/run/fc-egress/TAP.name, see below) and the tap's user, or, for a +# VM without a name in vms, the tap's own. It puts the addresses into +# the tap's nftables sets, in both the bridge's table and the other, and +# into /run/fcbr0-addr (TAP: its address, ADDRESS: its tap), for nginx +# and the run script. # # Egress, per VM: nothing gets forwarded from fcbr0. The guests' DNS # resolves every name to 172.16.0.1, and their TLS connections (tcp port @@ -27,8 +35,9 @@ # writes when it takes the tap (--egress LIST, default: the VM's name # (--name), or "default") and # empties when the VM exits. No list, or one that doesn't exist, allows -# nothing. Likewise /run/fc-egress/TAP.name, the VM's name (--name), so -# fc-egress can take names instead of taps; only fc-egress reads it. +# nothing. Likewise /run/fc-egress/TAP.name, the VM's name (--name), for +# its address (see above), and so fc-egress can take names instead of +# taps. # # Users can also allow plain TCP or UDP to given addresses and ports, like # ssh to some host: rules like tcp://ADDRESS[/PREFIXLEN]:PORT[-PORT] in the @@ -38,9 +47,20 @@ # # usage (in the host's configuration.nix), users and their number of taps: # imports = [ (import ./modules/host { users = { tv = 8; }; }) ]; +# +# VMs get static addresses by name and user (vms = { hermes = { user = +# "tv"; ip = "172.16.0.2"; }; }), any number of them, whichever tap they +# run on, e.g. for the host to reach them with a reverse proxy. The +# addresses are also in config.fc.vms.NAME (user, ip, ip6), e.g. +# proxyPass = "http://${config.fc.vms.hermes.ip}:9120"; +# The taps' own addresses, for VMs without, are from 172.16.0.200 on (but +# for vms'). # The host's firewall has to let the guests in on fcbr0: DHCP (udp 67), # DNS (udp and tcp 53) and the proxy (tcp proxyPort, after the redirect). { users + # VM name -> { user; ip; }: that VM's address (172.16.0.2 to .254), see + # above. +, vms ? { } , proxyPort ? 10443 # The guests' IPv6 /64 (on fcbr0, the host is ::1): each guest gets the # address from its MAC (SLAAC with EUI-64, see taps), for the tcp:// and @@ -59,27 +79,40 @@ , maxConnections ? 256 , maxNewConnections ? 50 }: { lib, pkgs, ... }: let - # [ { name = "fctap0"; user = ...; ip = "172.16.0.2"; ip6 = ...; - # ll6 = ...; mac = ...; } ... ] - taps = let + # An address, with what goes with it: { ip = "172.16.0.N"; ip6 = ...; + # ll6 = ...; mac = ...; }. The MAC is 06:00 and the address (ac:10:00:NN), + # the IPv6 addresses are from the MAC (SLAAC with EUI-64). + address = ip: let hex = n: lib.fixedWidthString 2 "0" (lib.toLower (lib.toHexString n)); - # The EUI-64 interface ID of the MAC below (in the canonical form, as - # nft and nginx print addresses). - eui64 = i: "400:acff:fe10:${lib.toLower (lib.toHexString i)}"; - tap = i: user: { - name = "fctap${toString i}"; - inherit user; - ip = "172.16.0.${toString (i + 2)}"; - ip6 = "${prefix6}${eui64 i}"; - ll6 = "fe80::${eui64 i}"; - mac = "06:00:ac:10:${hex (i / 256)}:${hex (lib.mod i 256)}"; # as the run script - }; - go = i: names: - if names == [ ] then [ ] - else let n = users.${lib.head names}; in - map (k: tap (i + k) (lib.head names)) (lib.range 0 (n - 1)) - ++ go (i + n) (lib.tail names); - in go 0 (lib.attrNames users); + m = builtins.match "172\\.16\\.0\\.([0-9]+)" ip; + n = if m == null then 0 else lib.toInt (lib.head m); # see assertions + # The EUI-64 interface ID of the MAC (in the canonical form, as nft + # and nginx print addresses). + eui64 = "400:acff:fe10:${lib.toLower (lib.toHexString n)}"; + in { + inherit ip; + ip6 = "${prefix6}${eui64}"; + ll6 = "fe80::${eui64}"; + mac = "06:00:ac:10:00:${hex n}"; + }; + # [ { vm = "hermes"; user = ...; ip = ...; ip6 = ...; ll6 = ...; + # mac = ...; } ... ] + vmList = lib.mapAttrsToList (vm: v: { inherit vm; inherit (v) user; } // address v.ip) vms; + # [ { name = "fctap0"; user = ...; ip = ...; ip6 = ...; ll6 = ...; + # mac = ...; } ... ]: each user's taps, in order, with their own + # addresses, for VMs without one in vms: from 172.16.0.200 on, so they + # stand out, those that aren't any VM's, in order. + tapsFrom = 200; + taps = let + free = lib.filter (ip: !lib.elem ip (map (v: v.ip) vmList)) + (lib.genList (k: "172.16.0.${toString (k + tapsFrom)}") (255 - tapsFrom)); + userTaps = lib.concatMap (u: lib.genList (_: u) users.${u}) userNames; + in lib.imap0 (i: user: { + name = "fctap${toString i}"; + inherit user; + } // address (if i < lib.length free then lib.elemAt free i else "172.16.0.0")) userTaps; # see assertions + # Everyone's addresses: taps' and VMs'. + addresses = taps ++ vmList; dir = "/var/lib/fc-egress"; vmDir = "/run/fc-egress"; # TAP: the name of the VM's list # List names: no slashes, no dot files. @@ -94,7 +127,15 @@ # down everyone's egress. maxRulesSize = 65536; tapsOf = user: lib.filter (t: t.user == user) taps; - ipsOf = user: map (t: t.ip) (tapsOf user); + ipsOf = user: map (a: a.ip) (lib.filter (a: a.user == user) addresses); + + # For the run script: the taps' own addresses, TAP USER IP MAC, and the + # VMs', VM USER IP MAC, a line each. + tapsFile = "/etc/fc-taps"; + vmsFile = "/etc/fc-vms"; + # Which address each tap has, and which tap each address: TAP: ADDRESS, + # ADDRESS: TAP, written by fcbr0-firewall (see firewallUpdate). + addrDir = "/run/fcbr0-addr"; # tcp://ADDRESS[/PREFIXLEN]:PORT[-PORT], tcp://[ADDRESS6[/PREFIXLEN]]:..., # tcp://NAME:PORT[-PORT], or udp://... (nft checks the numbers.) @@ -110,16 +151,22 @@ # 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, with - # names resolved by the host (IPv4 and IPv6; 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). + # For the given taps (default: all; a user's name means all of their + # taps), one tap at a time: puts the address of the tap's VM (see the + # top) into the tap's nftables sets addr_TAP and addr6_TAP, and into + # addrDir; and puts the tcp:// and udp:// rules of the tap's VM into the + # tap's nftables sets allow_TAP and allow6_TAP, so one bad rule doesn't + # keep the others' out, with names resolved by the host (IPv4 and IPv6; + # 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.gawk pkgs.getent pkgs.gnugrep pkgs.nftables ]} + # first line of a file, at most 256 bytes, or nothing + line() { + head -c 256 "$1" 2>/dev/null | head -n 1 || : + } status=0 if test $# = 0; then set -- ${lib.escapeShellArgs (map (t: t.name) taps)} @@ -132,9 +179,55 @@ ${lib.concatMapStrings (u: " ${u}) targets=\"$targets ${lib.concatMapStri done for tap in $targets; do case $tap in -${lib.concatMapStrings (t: " ${t.name}) user=${t.user} ;;\n") taps} *) echo "fcbr0-firewall: no tap $tap" >&2; status=1; continue +${lib.concatMapStrings (t: " ${t.name}) user=${t.user} ip=${t.ip} ip6=${t.ip6} ll6=${t.ll6} others=\"${lib.concatMapStringsSep " " (o: o.name) (lib.filter (o: o.name != t.name) (tapsOf t.user))}\" ;;\n") taps} *) echo "fcbr0-firewall: no tap $tap" >&2; status=1; continue esac - list=$(head -c 256 ${vmDir}/$tap 2>/dev/null | head -n 1) || : + + # The tap's address: its own, unless its VM's name is one of the + # user's VMs', and none of the user's other taps has a VM of that + # name, too: then the VM's, or with another, none. + name=$(line ${vmDir}/$tap.name) + vip= + if printf %s "$name" | grep -qxE '${vmName}'; then + case "$user $name" in +${lib.concatMapStrings (v: " \"${v.user} ${v.vm}\") vip=${v.ip} vip6=${v.ip6} vll6=${v.ll6} ;;\n") vmList} esac + fi + if test -n "$vip"; then + ip=$vip ip6=$vip6 ll6=$vll6 + for t in $others; do + if test "$(line ${vmDir}/$t.name)" = "$name"; then + echo "fcbr0-firewall: $tap: $user's VM $name is on $t, too: no address" >&2 + ip= ip6= ll6= + status=1 + fi + done + fi + { + for table in "inet firecracker" "bridge firecracker-bridge"; do + echo "flush set $table addr_$tap" + echo "flush set $table addr6_$tap" + done + if test -n "$ip"; then + echo "add element inet firecracker addr_$tap { $ip }" + echo "add element inet firecracker addr6_$tap { $ip6 }" + echo "add element bridge firecracker-bridge addr_$tap { $ip }" + echo "add element bridge firecracker-bridge addr6_$tap { $ip6, $ll6 }" + fi + } | nft -f - || { echo "fcbr0-firewall: address of $tap ($user: ''${name:--}) not applied" >&2; status=1; continue; } + # The address's tap first, then the tap's address, which the run + # script waits for. An address's file that names another tap is + # stale (that tap's own file says). + old=$(line ${addrDir}/$tap) + if test -n "$old" && test "$old" != "$ip" && test "$(line ${addrDir}/$old)" = "$tap"; then + rm -f ${addrDir}/$old + fi + if test -n "$ip"; then + printf '%s\n' "$tap" > ${addrDir}/.$ip + mv ${addrDir}/.$ip ${addrDir}/$ip + fi + printf '%s\n' "$ip" > ${addrDir}/.$tap + mv ${addrDir}/.$tap ${addrDir}/$tap + + list=$(line ${vmDir}/$tap) file=${dir}/$user/$list rules= if printf %s "$list" | grep -qxE '${listName}' && test -f "$file" && ! test -L "$file"; then @@ -186,7 +279,7 @@ ${lib.concatMapStrings (t: " ${t.name}) user=${t.user} ;;\n") taps} workerConnections = 5 * maxConnections * lib.length taps + 1024; # How fcbr0-firewall runs: not as root, users' files are input. A user - # of its own (not DynamicUser), for the hosts files. + # of its own (not DynamicUser), for the hosts files and addrDir. firewallService = { Type = "oneshot"; User = "fcbr0-firewall"; @@ -197,7 +290,7 @@ ${lib.concatMapStrings (t: " ${t.name}) user=${t.user} ;;\n") taps} ProtectSystem = "strict"; ProtectHome = true; PrivateTmp = true; - ReadWritePaths = [ hostsDir ]; + ReadWritePaths = [ hostsDir addrDir ]; RestrictAddressFamilies = [ "AF_NETLINK" "AF_UNIX" "AF_INET" "AF_INET6" ]; # nft, resolving }; @@ -232,7 +325,8 @@ ${lib.concatMapStrings (t: " ${t.name}) user=${t.user} ;;\n") taps} echo " or tcp://ADDRESS[/PREFIXLEN]:PORT[-PORT] (likewise udp://...)" echo " or tcp://[ADDRESS6[/PREFIXLEN]]:PORT[-PORT] (IPv6, not port 443)" echo " or tcp://NAME:PORT[-PORT] (resolved by the host)" - echo "vms shows the running VMs' taps (as in the log), names and lists" + echo "vms shows the running VMs' taps (as in the log), addresses, names" + echo " and lists" echo "use switches a running VM to another list" } # the tap of a running VM of the user's, by name or tap @@ -324,7 +418,8 @@ ${lib.concatMapStrings (t: " ${t.name}) user=${t.user} ;;\n") taps} find ${vmDir} -mindepth 1 -maxdepth 1 -user "$user" -size +0 -name 'fctap*' ! -name '*.*' -printf '%f\n' | sort -V | while read -r tap; do vm=$(head -n 1 ${vmDir}/$tap.name 2>/dev/null) || : - printf '%s %s %s\n' "$tap" "''${vm:--}" "$(head -n 1 ${vmDir}/$tap)" + ip=$(head -n 1 ${addrDir}/$tap 2>/dev/null) || : + printf '%s %s %s %s\n' "$tap" "$ip" "''${vm:--}" "$(head -n 1 ${vmDir}/$tap)" done ;; use) @@ -390,14 +485,19 @@ ${lib.concatMapStrings (t: " ${t.name}) user=${t.user} ;;\n") taps} -nodes -days 1 -subj /CN=unused -keyout unused.key -out unused.crt 2>/dev/null ''; - # egress.lua, and which guest address is which tap's, and whose. + # egress.lua, and whose each guest address and each tap is (which tap an + # address is on is in addrDir). egressLua = pkgs.runCommand "egress-lua" { - taps = "return {\n" + lib.concatMapStrings (t: " [\"${t.ip}\"] = { tap = \"${t.name}\", user = \"${t.user}\" },\n") taps + "}\n"; - passAsFile = [ "taps" ]; + guests = "return {\n addresses = {\n" + + lib.concatMapStrings (a: " [\"${a.ip}\"] = \"${a.user}\",\n") addresses + + " },\n taps = {\n" + + lib.concatMapStrings (t: " [\"${t.name}\"] = \"${t.user}\",\n") taps + + " },\n}\n"; + passAsFile = [ "guests" ]; } '' mkdir $out cp ${./egress.lua} $out/egress.lua - cp $tapsPath $out/egress_taps.lua + cp $guestsPath $out/egress_guests.lua ''; # stream: reads the ClientHello (ssl_preread), egress.lua decides, and @@ -418,6 +518,7 @@ ${lib.concatMapStrings (t: " ${t.name}) user=${t.user} ;;\n") taps} env FC_EGRESS_STATE=${stateDir}; env FC_EGRESS_RUN=${runDir}; env FC_EGRESS_VMS=${vmDir}; + env FC_EGRESS_ADDR=${addrDir}; events { worker_connections ${toString workerConnections}; } @@ -491,11 +592,44 @@ ${lib.concatMapStrings (t: " listen unix:${runDir}/decrypt-${t.name}.sock } ''; in { - assertions = [{ - assertion = lib.length taps <= 253; - message = "modules/host: at most 253 taps (172.16.0.2 to .254)"; + imports = [{ + options.fc.vms = lib.mkOption { + type = lib.types.attrsOf (lib.types.attrsOf lib.types.str); + default = lib.listToAttrs (map (v: lib.nameValuePair v.vm { + inherit (v) user ip ip6; + }) vmList); + readOnly = true; + description = "The VMs' addresses (see vms), by VM name: user, ip, ip6."; + }; }]; + assertions = [{ + assertion = lib.length taps + lib.length (lib.filter (v: lib.toInt (lib.last (lib.splitString "." v.ip)) >= tapsFrom) vmList) <= 255 - tapsFrom; + message = "modules/host: the taps' own addresses (172.16.0.${toString tapsFrom} to .254, but for vms') aren't enough for ${toString (lib.length taps)} taps"; + }] ++ lib.concatLists (lib.mapAttrsToList (vm: v: [ + { + assertion = builtins.match vmName vm != null; + message = "modules/host: vms.${vm}: not a VM name"; + } + { + assertion = users ? ${v.user}; + message = "modules/host: vms.${vm}: ${v.user} isn't in users"; + } + { + assertion = builtins.match "172\\.16\\.0\\.([2-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])" v.ip != null; + message = "modules/host: vms.${vm}: ${v.ip} isn't 172.16.0.2 to .254"; + } + { + assertion = lib.length (lib.filter (w: w.ip == v.ip) (lib.attrValues vms)) == 1; + message = "modules/host: vms.${vm}: ${v.ip} is another VM's, too"; + } + ]) vms); + + environment.etc.${lib.removePrefix "/etc/" tapsFile}.text = + lib.concatMapStrings (t: "${t.name} ${t.user} ${t.ip} ${t.mac}\n") taps; + environment.etc.${lib.removePrefix "/etc/" vmsFile}.text = + lib.concatMapStrings (v: "${v.vm} ${v.user} ${v.ip} ${v.mac}\n") vmList; + networking.interfaces = lib.listToAttrs (map (t: lib.nameValuePair t.name { virtual = true; virtualType = "tap"; @@ -543,6 +677,15 @@ ${lib.concatMapStrings (t: '' type ipv6_addr . inet_proto . inet_service flags interval } + + # The tap's VM's address (see firewallUpdate). + set addr_${t.name} { + type ipv4_addr + } + + set addr6_${t.name} { + type ipv6_addr + } '') taps} set deny4 { type ipv4_addr @@ -634,14 +777,14 @@ ${lib.concatMapStrings (t: '' chain vms { ${lib.concatMapStrings (t: '' - ip saddr ${t.ip} ip daddr . meta l4proto . th dport @allow_${t.name} limit rate 10/second burst 50 packets log prefix "fc-egress ALLOW ${t.user} ${t.name} " level info - ip saddr ${t.ip} ip daddr . meta l4proto . th dport @allow_${t.name} accept - ip6 saddr ${t.ip6} ip6 daddr . meta l4proto . th dport @allow6_${t.name} limit rate 10/second burst 50 packets log prefix "fc-egress ALLOW ${t.user} ${t.name} " level info - ip6 saddr ${t.ip6} ip6 daddr . meta l4proto . th dport @allow6_${t.name} accept + ip saddr @addr_${t.name} ip daddr . meta l4proto . th dport @allow_${t.name} limit rate 10/second burst 50 packets log prefix "fc-egress ALLOW ${t.user} ${t.name} " level info + ip saddr @addr_${t.name} ip daddr . meta l4proto . th dport @allow_${t.name} accept + ip6 saddr @addr6_${t.name} ip6 daddr . meta l4proto . th dport @allow6_${t.name} limit rate 10/second burst 50 packets log prefix "fc-egress ALLOW ${t.user} ${t.name} " level info + ip6 saddr @addr6_${t.name} ip6 daddr . meta l4proto . th dport @allow6_${t.name} accept '') taps} } chain refused { -${lib.concatMapStrings (t: " ip saddr ${t.ip} limit rate 10/second burst 50 packets log prefix \"fc-egress DENY ${t.user} ${t.name} \" level info\n") taps}${lib.concatMapStrings (t: " ip6 saddr ${t.ip6} limit rate 10/second burst 50 packets log prefix \"fc-egress DENY ${t.user} ${t.name} \" level info\n") taps} reject with icmpx admin-prohibited +${lib.concatMapStrings (t: " ip saddr @addr_${t.name} limit rate 10/second burst 50 packets log prefix \"fc-egress DENY ${t.user} ${t.name} \" level info\n") taps}${lib.concatMapStrings (t: " ip6 saddr @addr6_${t.name} limit rate 10/second burst 50 packets log prefix \"fc-egress DENY ${t.user} ${t.name} \" level info\n") taps} reject with icmpx admin-prohibited } # Only nginx's packets: others, including those the kernel sends on @@ -662,30 +805,31 @@ ${lib.concatMapStrings (t: " ip saddr ${t.ip} limit rate 10/second burst } ''; }; - # On the bridge: each tap may only send from its own addresses (or - # 0.0.0.0, for DHCP and ARP probes, or ::, for IPv6 duplicate address - # detection), IPv4, ARP and IPv6 only, and nothing to other taps. + # On the bridge: each tap may only send from its VM's addresses (addr_TAP + # and addr6_TAP, see firewallUpdate; or 0.0.0.0, for DHCP and ARP probes, + # or ::, for IPv6 duplicate address detection), IPv4, ARP and IPv6 only, + # and nothing to other taps. networking.nftables.tables.firecracker-bridge = { family = "bridge"; content = '' - set guests { - type ifname . ipv4_addr - elements = { ${lib.concatMapStringsSep ", " (t: "\"${t.name}\" . ${t.ip}") taps} } +${lib.concatMapStrings (t: '' + set addr_${t.name} { + type ipv4_addr } - set guests6 { - type ifname . ipv6_addr - elements = { ${lib.concatMapStringsSep ", " (t: "\"${t.name}\" . ${t.ip6}, \"${t.name}\" . ${t.ll6}") taps} } + set addr6_${t.name} { + type ipv6_addr } - +'') taps} chain prerouting { type filter hook prerouting priority filter; policy accept; iifname != "fctap*" accept - ether type ip iifname . ip saddr @guests accept - ether type ip ip saddr 0.0.0.0 udp dport 67 accept - ether type arp iifname . arp saddr ip @guests accept +${lib.concatMapStrings (t: '' + iifname "${t.name}" ether type ip ip saddr @addr_${t.name} accept + iifname "${t.name}" ether type arp arp saddr ip @addr_${t.name} accept + iifname "${t.name}" ether type ip6 ip6 saddr @addr6_${t.name} accept +'') taps} ether type ip ip saddr 0.0.0.0 udp dport 67 accept ether type arp arp saddr ip 0.0.0.0 accept - ether type ip6 iifname . ip6 saddr @guests6 accept ether type ip6 ip6 saddr :: icmpv6 type { nd-neighbor-solicit, mld2-listener-report } accept drop } @@ -698,8 +842,8 @@ ${lib.concatMapStrings (t: " ip saddr ${t.ip} limit rate 10/second burst }; # A dnsmasq of its own, so it doesn't get mixed up with one the host might - # 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 + # run otherwise. DHCP, only the taps' and VMs' addresses, by MAC address + # (see address 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), but # for the names in the VMs' tcp:// and udp:// rules, from the hosts files @@ -733,7 +877,7 @@ ${lib.concatMapStrings (t: " ip saddr ${t.ip} limit rate 10/second burst "--address=/#/172.16.0.1" "--local=/#/" "--hostsdir=${hostsDir}" - ] ++ map (t: "--dhcp-host=${t.mac},${t.ip}") taps); + ] ++ map (a: "--dhcp-host=${a.mac},${a.ip}") addresses); }; }; @@ -744,6 +888,7 @@ ${lib.concatMapStrings (t: " ip saddr ${t.ip} limit rate 10/second burst "d ${dir} 0755 root root -" "d ${vmDir} 0755 root root -" "d ${hostsDir} 0755 fcbr0-firewall fcbr0-firewall -" + "d ${addrDir} 0755 fcbr0-firewall fcbr0-firewall -" ] ++ lib.concatMap (u: [ "d ${dir}/${u} 0755 ${u} - -" @@ -760,12 +905,12 @@ ${lib.concatMapStrings (t: " ip saddr ${t.ip} limit rate 10/second burst boot.kernel.sysctl."net.ipv4.ip_forward" = 1; boot.kernel.sysctl."net.ipv6.conf.all.forwarding" = 1; - # Fills the allow_TAP sets: all of them at start and whenever nftables - # gets reloaded (which empties them), a tap's (fcbr0-firewall@TAP) - # whenever its choice of list changes, and all of a user's - # (fcbr0-firewall@USER) whenever one of their lists changes. By path - # units of each tap's and user's own, so a user who keeps changing - # things can't make it stop for others. + # Fills the addr_TAP and allow_TAP sets: all of them at start and + # whenever nftables gets reloaded (which empties them), a tap's + # (fcbr0-firewall@TAP) whenever its VM's name or choice of list changes, + # and all of a user's (fcbr0-firewall@USER) whenever one of their lists + # changes. By path units of each tap's and user's own, so a user who + # keeps changing things can't make it stop for others. systemd.services.fcbr0-firewall = { wantedBy = [ "multi-user.target" ]; after = [ "nftables.service" "systemd-tmpfiles-setup.service" ]; @@ -801,13 +946,14 @@ ${lib.concatMapStrings (t: " ip saddr ${t.ip} limit rate 10/second burst }; }; systemd.paths = let - path = name: file: lib.nameValuePair "fcbr0-firewall-${name}" { + path = name: instance: file: lib.nameValuePair "fcbr0-firewall-${name}" { wantedBy = [ "multi-user.target" ]; pathConfig.PathChanged = file; # a directory: any file in it - pathConfig.Unit = "fcbr0-firewall@${name}.service"; + pathConfig.Unit = "fcbr0-firewall@${instance}.service"; }; - in lib.listToAttrs (map (u: path u "${dir}/${u}") userNames - ++ map (t: path t.name "${vmDir}/${t.name}") taps); + in lib.listToAttrs (map (u: path u u "${dir}/${u}") userNames + ++ map (t: path t.name t.name "${vmDir}/${t.name}") taps + ++ map (t: path "${t.name}-name" t.name "${vmDir}/${t.name}.name") taps); # A user of its own rather than DynamicUser, as ca.pem has to be readable # by anyone (DynamicUser state lives under /var/lib/private, mode 0700). diff --git a/modules/host/egress.lua b/modules/host/egress.lua index 172805a..d276e05 100644 --- a/modules/host/egress.lua +++ b/modules/host/egress.lua @@ -1,7 +1,8 @@ -- The guests' egress policy, for nginx (OpenResty), see default.nix. -- --- Per VM: which tap (and so whose) a guest is, egress_taps.lua says by its --- address (which the bridge makes sure of, see default.nix). VMS/TAP has +-- Per VM: whose a guest is, egress_guests.lua says by its address (which +-- the bridge makes sure of, see default.nix), and which tap it's on, +-- ADDR/ADDRESS and ADDR/TAP, as long as they agree. VMS/TAP has -- the name of the VM's list, RULES/USER/LIST its rules, one per line, both -- read on every connection and request: -- https://example.com example.com and its subdomains, passed @@ -21,10 +22,31 @@ local RULES = os.getenv("FC_EGRESS_RULES") -- RULES/USER/LIST local VMS = os.getenv("FC_EGRESS_VMS") -- VMS/TAP: LIST local STATE = os.getenv("FC_EGRESS_STATE") -- ca.key, ca.pem local RUN = os.getenv("FC_EGRESS_RUN") -- RUN/decrypt-TAP.sock: the http server -local guests = require("egress_taps") -- guest address -> { tap, user } +local ADDR = os.getenv("FC_EGRESS_ADDR") -- ADDR/TAP: ADDRESS, ADDR/ADDRESS: TAP +-- { addresses = { [ADDRESS] = USER }, taps = { [TAP] = USER } } +local owners = require("egress_guests") local by_tap = {} -for _, g in pairs(guests) do - by_tap[g.tap] = g +for tap, user in pairs(owners.taps) do + by_tap[tap] = { tap = tap, user = user } +end + +local function first_line(path) + local f = io.open(path) + local s = f and f:read("*l") + if f then + f:close() + end + return s +end + +-- The guest at an address: { tap, user }, or nil. +local function guest_at(address) + local user = owners.addresses[address] + local tap = user and first_line(ADDR .. "/" .. address) + local guest = tap and by_tap[tap] + if guest and guest.user == user and first_line(ADDR .. "/" .. tap) == address then + return guest + end end local function valid_name(s) @@ -93,7 +115,7 @@ end -- stream, preread: pass through, decrypt, or close function _M.preread() local sni = ngx.var.ssl_preread_server_name - local guest = guests[ngx.var.remote_addr] + local guest = guest_at(ngx.var.remote_addr) local name, who if guest then name, who = list(guest) |
