aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--README.md18
-rw-r--r--modules/host/default.nix188
-rw-r--r--modules/host/egress.lua6
-rw-r--r--pkgs/run-firecracker-vm/default.nix9
4 files changed, 182 insertions, 39 deletions
diff --git a/README.md b/README.md
index ea30fd2..a03cb12 100644
--- a/README.md
+++ b/README.md
@@ -32,8 +32,17 @@ host, beyond, or each other. Each tap has a fixed address, and the bridge
drops anything a guest sends from another, so the proxy knows whose a
connection is. It needs `networking.nftables` (and enables it).
-Optional argument: `proxyPort` (default 10443, where the proxy listens;
-the guests' port 443 gets redirected there).
+Optional arguments:
+
+- `proxyPort` (default 10443): where the proxy listens; the guests' port
+ 443 gets redirected there.
+- `denyDestinations`: addresses no user's rules can open, neither for
+ tcp:// and udp:// rules nor through the proxy, whatever a name resolves
+ to. Default: loopback, private, link-local, CGNAT, multicast and the
+ like (IPv4 and IPv6). The host's own addresses are always out of reach
+ (but for DHCP, DNS and the proxy).
+- `maxConnections` (default 256) and `maxNewConnections` (default 50 per
+ second): limits per guest, so one user can't starve the others.
If the host has a firewall of its own, it has to let the guests in on
`fcbr0`: udp 67 (DHCP), udp and tcp 53 (DNS), and tcp 10443 (the proxy).
@@ -99,8 +108,9 @@ 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, or, if they're
-for one of the host's addresses, let in. If the host has a forward
+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
`fcbr0`; this module rejects what isn't allowed).
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
diff --git a/pkgs/run-firecracker-vm/default.nix b/pkgs/run-firecracker-vm/default.nix
index 37047b0..b6e5387 100644
--- a/pkgs/run-firecracker-vm/default.nix
+++ b/pkgs/run-firecracker-vm/default.nix
@@ -374,10 +374,17 @@ pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ ''
# VM holds. The lock is held until the script exits. The MAC address is
# derived from the tap's number, as modules/host does, for the tap's
# fixed address.
+ # Lock files in a directory of the user's own: in /tmp, another user
+ # could take them first.
+ lockdir=''${XDG_RUNTIME_DIR:-/run/user/$(id -u)}
+ if ! test -d "$lockdir" -a -O "$lockdir"; then
+ echo "$0: $lockdir isn't a directory of $(id -un)'s; set XDG_RUNTIME_DIR" >&2
+ exit 1
+ fi
tap=
for t in $(find /sys/class/net -maxdepth 1 -name 'fctap*' -printf '%f\n' | sort -V); do
test "$(cat /sys/class/net/$t/owner)" = "$(id -u)" || continue
- exec {lock}>"''${XDG_RUNTIME_DIR:-/tmp}/run-firecracker-vm.$t.lock"
+ exec {lock}>"$lockdir/run-firecracker-vm.$t.lock"
if flock -n "$lock"; then
tap=$t
break