aboutsummaryrefslogtreecommitdiffstats
path: root/modules/host
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-17 01:59:29 +0000
committertv <tv@krebsco.de>2026-11-17 01:59:29 +0000
commitb050c6af6aedbe78201addb4abe2636ab075d14e (patch)
treee46faa905fa85748892a5a70ba49678f5670b913 /modules/host
parent31611aa9bd7b39a4f700f1641bca2edb16619c64 (diff)
host: harden against users turning on the host or each other
- denyDestinations (default: loopback, private, link-local, CGNAT, multicast, ...): no user's rules can open those, neither tcp:// and udp:// rules nor the proxy, whatever a name resolves to: nginx's own outgoing connections may only go to port 443 outside them, and not to the host. tcp:// rules no longer open anything on the host itself. - fcbr0-firewall no longer runs as root, but with only CAP_NET_ADMIN, doesn't follow symlinks, and gets started per user when that user's rules change, so one user can't stop the others' updates. Rules files are read up to 64k only, by egress.lua, too. - Limits per guest (maxConnections open, maxNewConnections per second), and per user in nginx, so one user can't starve the others. - tcp:// and udp:// connections, and refused ones, get logged (rate-limited) with the user; fc-egress log shows them. - The run script keeps its lock files in a directory of the user's own, not in /tmp, where others could take them first.
Diffstat (limited to 'modules/host')
-rw-r--r--modules/host/default.nix188
-rw-r--r--modules/host/egress.lua6
2 files changed, 160 insertions, 34 deletions
diff --git a/modules/host/default.nix b/modules/host/default.nix
index e2421c0..c0babb9 100644
--- a/modules/host/default.nix
+++ b/modules/host/default.nix
@@ -32,7 +32,20 @@
# imports = [ (import ./modules/host { users = { tv = 8; }; }) ];
# 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, proxyPort ? 10443 }: { lib, pkgs, ... }: let
+{ users
+, proxyPort ? 10443
+ # Where no user's rules can let guests go, neither via tcp:// and udp://
+ # rules nor via the HTTPS proxy, whatever a name resolves to. The host's
+ # own addresses are always out of reach (but for DHCP, DNS and the proxy).
+, denyDestinations ? [
+ "0.0.0.0/8" "10.0.0.0/8" "100.64.0.0/10" "127.0.0.0/8"
+ "169.254.0.0/16" "172.16.0.0/12" "192.168.0.0/16" "224.0.0.0/3"
+ "::/127" "::ffff:0:0/96" "fc00::/7" "fe80::/10" "ff00::/8"
+ ]
+ # Limits per guest: open connections, and new connections per second.
+, maxConnections ? 256
+, maxNewConnections ? 50
+}: { lib, pkgs, ... }: let
# [ { name = "fctap0"; user = ...; ip = "172.16.0.2"; mac = ...; } ... ]
taps = let
hex = n: lib.fixedWidthString 2 "0" (lib.toLower (lib.toHexString n));
@@ -50,21 +63,35 @@
in go 0 (lib.attrNames users);
dir = "/var/lib/fc-egress";
userNames = lib.attrNames users;
+ deny4 = lib.filter (a: !lib.hasInfix ":" a) denyDestinations;
+ deny6 = lib.filter (a: lib.hasInfix ":" a) denyDestinations;
+ # Rules files are read only up to this size, so a huge one can't slow
+ # down everyone's egress.
+ maxRulesSize = 65536;
ipsOf = user: map (t: t.ip) (lib.filter (t: t.user == user) taps);
# 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]+)?";
- # Puts each user's tcp:// and udp:// rules into their nftables set, one
- # user at a time, so one user's bad rule doesn't keep the others' out.
+ # Puts the given users' (default: all) tcp:// and udp:// rules into their
+ # nftables sets, one user at a time, so one user's bad rule doesn't keep
+ # the others' out. 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 ]}
status=0
- for user in ${lib.escapeShellArgs userNames}; do
- elements=$(grep -xE '${portRule}' ${dir}/$user/allowed 2>/dev/null |
- sed -E 's#^(tcp|udp)://([^:]+):(.*)$#\2 . \1 . \3#' | paste -sd,)
+ if test $# = 0; then
+ set -- ${lib.escapeShellArgs userNames}
+ fi
+ for user; do
+ file=${dir}/$user/allowed
+ elements=
+ if 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,)
+ fi
{
echo "flush set inet firecracker allow_$user"
if test -n "$elements"; then
@@ -75,6 +102,24 @@
exit $status
'';
+ # Each connection a guest makes through nginx takes up to 5 of its
+ # connections (decrypted ones: guest, stream, Unix socket both ways,
+ # upstream).
+ workerConnections = 5 * maxConnections * lib.length taps + 1024;
+
+ # How fcbr0-firewall runs: not as root, users' files are input.
+ firewallService = {
+ Type = "oneshot";
+ DynamicUser = true;
+ AmbientCapabilities = [ "CAP_NET_ADMIN" ];
+ CapabilityBoundingSet = [ "CAP_NET_ADMIN" ];
+ NoNewPrivileges = true;
+ ProtectSystem = "strict";
+ ProtectHome = true;
+ PrivateTmp = true;
+ RestrictAddressFamilies = [ "AF_NETLINK" "AF_UNIX" ];
+ };
+
# Where nginx keeps the CA: ca.key, and ca.pem for the guests (see
# caCert in pkgs/run-firecracker-vm).
stateDir = "/var/lib/fcbr0-egress";
@@ -144,11 +189,13 @@
update sh -c 'grep -vxF -e "$1" "$0" || :' "$list" "$(printf '%s\n' "$@")"
;;
log)
- # Connections: ALLOW|DENY, user, server name, guest, upstream,
- # status, bytes sent and received (from the guest's view: received,
- # sent), seconds. Decrypted requests: ALLOW|DENY, user, host,
- # method, URI, status, bytes sent.
- journalctl -u fcbr0-egress -o short-iso "$@" | grep --line-buffered -E " (ALLOW|DENY) $user "
+ # HTTPS connections: ALLOW|DENY, user, server name, guest,
+ # upstream, status, bytes sent and received (from the guest's view:
+ # received, sent), seconds. Decrypted requests: ALLOW|DENY, user,
+ # host, method, URI, status, bytes sent. Other connections (kernel
+ # log, rate-limited): fc-egress ALLOW|DENY, user, and the packet.
+ journalctl -o short-iso _SYSTEMD_UNIT=fcbr0-egress.service + _TRANSPORT=kernel "$@" |
+ grep --line-buffered -E " (ALLOW|DENY) $user "
;;
help|-h|--help)
usage
@@ -210,10 +257,13 @@
pid ${runDir}/nginx.pid;
error_log stderr warn;
worker_processes 1;
+ worker_rlimit_nofile ${toString (workerConnections + 1024)};
env FC_EGRESS_RULES=${dir};
env FC_EGRESS_STATE=${stateDir};
env FC_EGRESS_RUN=${runDir};
- events {}
+ events {
+ worker_connections ${toString workerConnections};
+ }
stream {
lua_package_path "${egressLua}/?.lua;;";
@@ -221,8 +271,19 @@
log_format egress '$egress_log $remote_addr $upstream_addr $status $bytes_sent $bytes_received $session_time';
access_log syslog:server=unix:/dev/log,nohostname,tag=fc_egress egress if=$egress_log;
+ # Per user: open connections, at most maxConnections per tap, so one
+ # user can't use up the connections everyone's egress goes through.
+ # A zone per user, keyed by a variable that's empty (i.e. not
+ # counted) for other users' guests.
+${lib.concatMapStrings (u: ''
+ map $remote_addr $egress_limit_${u} {
+${lib.concatMapStrings (ip: " ${ip} 1;\n") (ipsOf u)} default "";
+ }
+ limit_conn_zone $egress_limit_${u} zone=user_${u}:64k;
+'') userNames}
server {
listen 172.16.0.1:${toString proxyPort};
+${lib.concatMapStrings (u: " limit_conn user_${u} ${toString (users.${u} * maxConnections)};\n") userNames}
ssl_preread on;
set $egress_upstream "";
set $egress_log "";
@@ -294,13 +355,23 @@ in {
# What the guests may do on the host's network: DHCP and DNS with our
# dnsmasq, TLS to nginx (port 443 of any address, redirected to
# 172.16.0.1:proxyPort), and what their user's tcp:// and udp:// rules
- # allow (set allow_USER, see firewallUpdate). Nothing else, neither to
- # the host (whose own services, like ssh, the guests would otherwise
- # reach at 172.16.0.1, where DNS sends every name, or at any other of
- # its addresses) nor through it, nor to each other (bridge). These
+ # allow (set allow_USER, see firewallUpdate), except to denyDestinations.
+ # Nothing else, neither to the host (whose own services, like ssh, the
+ # guests would otherwise reach at 172.16.0.1, where DNS sends every
+ # name, or at any other of its addresses) nor through it, nor to each
+ # other (bridge). nginx itself (chain output) may only reach port 443
+ # outside denyDestinations and the host (and DNS), so a name can't get a
+ # guest anywhere else either. Each guest gets at most maxConnections
+ # open and maxNewConnections new per second. Allowed and refused
+ # connections get logged (rate-limited), with the user, as
+ # "fc-egress ALLOW USER" and "fc-egress DENY USER" (kernel log). These
# chains only reject; for what they let through, the host's own chains
# decide, too. Forwarded connections get NATed to the host's address.
networking.nftables.enable = true;
+ # The build's ruleset check runs where fcbr0-egress doesn't exist.
+ networking.nftables.preCheckRuleset = ''
+ sed -i 's/skuid != "fcbr0-egress"/skuid != 0/' ruleset.conf
+ '';
networking.nftables.tables.firecracker = {
family = "inet";
content = ''
@@ -310,6 +381,31 @@ ${lib.concatMapStrings (u: ''
flags interval
}
'') userNames}
+ set deny4 {
+ type ipv4_addr
+ flags interval
+ ${lib.optionalString (deny4 != [ ]) "elements = { ${lib.concatStringsSep ", " deny4} }"}
+ }
+
+ set deny6 {
+ type ipv6_addr
+ flags interval
+ ${lib.optionalString (deny6 != [ ]) "elements = { ${lib.concatStringsSep ", " deny6} }"}
+ }
+
+ set guest_conns {
+ type ipv4_addr
+ flags dynamic
+ size 1024
+ }
+
+ set guest_rate {
+ type ipv4_addr
+ flags dynamic, timeout
+ timeout 1m
+ size 1024
+ }
+
# Before the host's own NAT rules (which are for connections to the
# host, like a redirect of some port to its sshd), so they don't get
# applied to the guests' connections: the first NAT a connection gets
@@ -330,23 +426,48 @@ ${lib.concatMapStrings (u: ''
type filter hook input priority filter; policy accept;
iifname != "fcbr0" accept
ct state { established, related } accept
+ jump limits
ip daddr { 172.16.0.1, 255.255.255.255 } udp dport 67 accept
ip daddr 172.16.0.1 udp dport 53 accept
ip daddr 172.16.0.1 tcp dport { 53, ${toString proxyPort} } accept
- jump users
- reject with icmpx admin-prohibited
+ jump refused
}
chain forward {
type filter hook forward priority filter; policy accept;
iifname != "fcbr0" accept
ct state { established, related } accept
+ jump limits
+ ip daddr @deny4 jump refused
jump users
- reject with icmpx admin-prohibited
+ jump refused
+ }
+
+ chain limits {
+ ct state new add @guest_conns { ip saddr ct count over ${toString maxConnections} } reject with icmpx admin-prohibited
+ ct state new update @guest_rate { ip saddr limit rate over ${toString maxNewConnections}/second burst ${toString (2 * maxNewConnections)} packets } reject with icmpx admin-prohibited
}
chain users {
-${lib.concatMapStrings (u: " ip saddr { ${lib.concatStringsSep ", " (ipsOf u)} } ip daddr . meta l4proto . th dport @allow_${u} accept\n") userNames} }
+${lib.concatMapStrings (u: let ips = "{ ${lib.concatStringsSep ", " (ipsOf u)} }"; in ''
+ ip saddr ${ips} ip daddr . meta l4proto . th dport @allow_${u} limit rate 10/second burst 50 packets log prefix "fc-egress ALLOW ${u} " level info
+ ip saddr ${ips} ip daddr . meta l4proto . th dport @allow_${u} accept
+'') userNames} }
+
+ chain refused {
+${lib.concatMapStrings (u: " ip saddr { ${lib.concatStringsSep ", " (ipsOf u)} } limit rate 10/second burst 50 packets log prefix \"fc-egress DENY ${u} \" level info\n") userNames} reject with icmpx admin-prohibited
+ }
+
+ chain output {
+ type filter hook output priority filter; policy accept;
+ meta skuid != "fcbr0-egress" accept
+ ct state { established, related } accept # e.g. to the guests
+ th dport 53 accept
+ fib daddr type local reject
+ ip daddr @deny4 reject
+ ip6 daddr @deny6 reject
+ tcp dport != 443 reject
+ }
'';
};
# On the bridge: each tap may only send from its own address (or
@@ -419,29 +540,32 @@ ${lib.concatMapStrings (u: " ip saddr { ${lib.concatStringsSep ", " (ipsO
# Forwarding, for the tcp:// and udp:// rules.
boot.kernel.sysctl."net.ipv4.ip_forward" = 1;
- # Fills the allow_USER sets: at start, whenever nftables gets reloaded
- # (which empties them), and whenever a user's rules change.
+ # Fills the allow_USER sets: all of them at start and whenever nftables
+ # gets reloaded (which empties them), and a user's (fcbr0-firewall@USER,
+ # by a path unit of the user's own, so a user who keeps changing their
+ # rules can't make it stop for others) whenever their rules change.
systemd.services.fcbr0-firewall = {
wantedBy = [ "multi-user.target" ];
after = [ "nftables.service" "systemd-tmpfiles-setup.service" ];
partOf = [ "nftables.service" ];
unitConfig.ReloadPropagatedFrom = "nftables.service";
- serviceConfig = {
- Type = "oneshot";
+ serviceConfig = firewallService // {
RemainAfterExit = true;
ExecStart = firewallUpdate;
ExecReload = firewallUpdate;
};
};
- systemd.paths.fcbr0-firewall = {
- wantedBy = [ "multi-user.target" ];
- pathConfig.PathChanged = map (u: "${dir}/${u}/allowed") userNames;
- pathConfig.Unit = "fcbr0-firewall-reload.service";
- };
- systemd.services.fcbr0-firewall-reload = {
- serviceConfig.Type = "oneshot";
- serviceConfig.ExecStart = "${pkgs.systemd}/bin/systemctl try-reload-or-restart fcbr0-firewall.service";
+ systemd.services."fcbr0-firewall@" = {
+ after = [ "fcbr0-firewall.service" ];
+ serviceConfig = firewallService // {
+ ExecStart = "${firewallUpdate} %i";
+ };
};
+ systemd.paths = lib.listToAttrs (map (u: lib.nameValuePair "fcbr0-firewall-${u}" {
+ wantedBy = [ "multi-user.target" ];
+ pathConfig.PathChanged = "${dir}/${u}/allowed";
+ pathConfig.Unit = "fcbr0-firewall@${u}.service";
+ }) userNames);
# 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 6875608..6c507a1 100644
--- a/modules/host/egress.lua
+++ b/modules/host/egress.lua
@@ -31,7 +31,10 @@ local function rules(user)
if not f then
return domains, paths
end
- for line in f:lines() do
+ -- Only the first 64k, so a huge file can't slow down everyone's egress.
+ local text = f:read(65536) or ""
+ f:close()
+ for line in text:gmatch("[^\n]+") do
local domain, path = line:match("^%s*([^/%s]+)(/?%S*)%s*$")
if valid_name(domain) then
if path == "" then
@@ -42,7 +45,6 @@ local function rules(user)
end
end
end
- f:close()
return domains, paths
end