diff options
| -rw-r--r-- | README.md | 10 | ||||
| -rw-r--r-- | modules/host/default.nix | 97 |
2 files changed, 87 insertions, 20 deletions
@@ -94,6 +94,7 @@ fc-egress list fc-egress allow cache.nixos.org # the domain and its subdomains fc-egress allow github.com/NixOS/ # only paths starting with /NixOS/ fc-egress allow tcp://192.0.2.7:22 # plain TCP to that address and port +fc-egress allow tcp://git.example.org:22 # or name (resolved by the host) fc-egress allow udp://192.0.2.0/24:5000-5100 fc-egress deny github.com/NixOS/ fc-egress -l work allow example.com # the list "work" @@ -123,9 +124,12 @@ when the guest gets built, so build the guest on the host after the proxy has started once. Everything else, and anything that isn't HTTPS, gets refused. -tcp:// and udp:// rules take IPv4 addresses (a guest resolves every name -to the host, so it has to use addresses for these, too). Those -connections get forwarded, NATed to the host's address, and logged +tcp:// and udp:// rules take IPv4 addresses or names. The guests +resolve every name to the host, except the names in such rules: the host +resolves those (IPv4) and tells the guests the same addresses, so +`ssh git.example.org` works. They get resolved again every 5 minutes. +(Every guest gets those addresses for those names, but only the VMs +whose list has the rule can connect.) Those connections get forwarded, NATed to the host's address, and logged (rate-limited, kernel log; `fc-egress log` shows them), as are refused ones. If the host has a forward chain of its own, it has to let them through, too (anything from 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 // { |
