aboutsummaryrefslogtreecommitdiffstats
path: root/modules/host/default.nix
diff options
context:
space:
mode:
Diffstat (limited to 'modules/host/default.nix')
-rw-r--r--modules/host/default.nix197
1 files changed, 126 insertions, 71 deletions
diff --git a/modules/host/default.nix b/modules/host/default.nix
index c0babb9..4f31c19 100644
--- a/modules/host/default.nix
+++ b/modules/host/default.nix
@@ -9,24 +9,30 @@
# number), and the bridge drops anything coming from a tap with another
# source address, so a guest's address says whose it is.
#
-# Egress, per user: nothing gets forwarded from fcbr0. The guests' DNS
+# 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
# 443, whatever the address) get redirected to nginx on
# 172.16.0.1:proxyPort (not 443 itself, as the host may run a web server
-# on 0.0.0.0:443). nginx goes by the server name (SNI) and the rules of
-# the guest's user, in /var/lib/fc-egress/USER/allowed (see egress.lua):
+# on 0.0.0.0:443). nginx goes by the server name (SNI) and the guest's
+# whitelist (see egress.lua):
# whole domains get passed through to port 443 of that name, as resolved
# by the host; domains with path rules get decrypted (with certificates
# from our own CA, which the guests trust, see pkgs/run-firecracker-vm)
-# and only matching requests forwarded. Each user can change their rules
-# at any time with fc-egress (see fc-egress help); they apply to the next
-# connection.
+# and only matching requests forwarded.
+#
+# Whitelists are per user and named: /var/lib/fc-egress/USER/LIST, changed
+# with fc-egress (see fc-egress help) at any time; changes apply to the
+# next connection. Which list a VM uses is in /run/fc-egress/TAP (one
+# line, the list's name, writable by the tap's user), which the run script
+# writes when it takes the tap (--egress LIST, default "default") and
+# empties when the VM exits. No list, or one that doesn't exist, allows
+# nothing.
#
# 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
-# same file. fcbr0-firewall puts them into the user's nftables set
-# allow_USER whenever the file changes, and those connections get
-# forwarded (and NATed), or let in, if they're for the host.
+# same lists. fcbr0-firewall puts a VM's into its tap's nftables set
+# allow_TAP whenever the list or the tap's choice of list changes, and
+# those connections get forwarded (and NATed).
#
# usage (in the host's configuration.nix), users and their number of taps:
# imports = [ (import ./modules/host { users = { tv = 8; }; }) ];
@@ -34,7 +40,7 @@
# DNS (udp and tcp 53) and the proxy (tcp proxyPort, after the redirect).
{ users
, proxyPort ? 10443
- # Where no user's rules can let guests go, neither via tcp:// and udp://
+ # Where no whitelist 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 ? [
@@ -62,42 +68,57 @@
++ go (i + n) (lib.tail names);
in go 0 (lib.attrNames users);
dir = "/var/lib/fc-egress";
+ vmDir = "/run/fc-egress"; # TAP: the name of the VM's list
+ # List names: no slashes, no dot files.
+ listName = "[A-Za-z0-9_-]+";
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);
+ 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]+)?";
- # 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).
+ # 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.
+ # 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
if test $# = 0; then
- set -- ${lib.escapeShellArgs userNames}
+ set -- ${lib.escapeShellArgs (map (t: t.name) taps)}
fi
- for user; do
- file=${dir}/$user/allowed
+ targets=
+ for a; do
+ case $a in
+${lib.concatMapStrings (u: " ${u}) targets=\"$targets ${lib.concatMapStringsSep " " (t: t.name) (tapsOf u)}\" ;;\n") userNames} *) targets="$targets $a"
+ esac
+ 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
+ esac
+ list=$(head -c 256 ${vmDir}/$tap 2>/dev/null | head -n 1) || :
+ file=${dir}/$user/$list
elements=
- if test -f "$file" && ! test -L "$file"; then
+ 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,)
fi
{
- echo "flush set inet firecracker allow_$user"
+ echo "flush set inet firecracker allow_$tap"
if test -n "$elements"; then
- echo "add element inet firecracker allow_$user { $elements }"
+ echo "add element inet firecracker allow_$tap { $elements }"
fi
- } | nft -f - || { echo "fcbr0-firewall: rules of $user not applied" >&2; status=1; }
+ } | nft -f - || { echo "fcbr0-firewall: rules of $tap ($user: $list) not applied" >&2; status=1; }
done
exit $status
'';
@@ -127,22 +148,36 @@
fc-egress = pkgs.writeShellScriptBin "fc-egress" ''
set -efu
- export PATH=${lib.makeBinPath [ pkgs.bash pkgs.coreutils pkgs.gawk pkgs.gnugrep pkgs.systemd ]}
+ export PATH=${lib.makeBinPath [ pkgs.bash pkgs.coreutils pkgs.findutils pkgs.gawk pkgs.gnugrep pkgs.systemd ]}
user=$(id -un)
- list=${dir}/$user/allowed
- if ! test -e "$list"; then
+ if ! test -d ${dir}/$user; then
echo "fc-egress: $user has no VMs (see modules/host)" >&2
exit 1
fi
usage() {
- echo "usage: fc-egress list"
- echo " fc-egress allow RULE..."
- echo " fc-egress deny RULE..."
+ echo "usage: fc-egress [-l LIST] list"
+ echo " fc-egress [-l LIST] allow RULE..."
+ echo " fc-egress [-l LIST] deny RULE..."
+ echo " fc-egress lists"
+ echo " fc-egress vms"
echo " fc-egress log [JOURNALCTL-OPTION...]"
+ echo "LIST is a whitelist's name (default: default); a VM uses the one"
+ echo " given to run-firecracker-vm --egress (default: default)"
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 "vms shows the running VMs' taps (as in the log) and lists"
}
+ name=default
+ if test "''${1-}" = -l; then
+ name=''${2-}
+ shift 2 || :
+ fi
+ if ! printf %s "$name" | grep -qxE '${listName}'; then
+ echo "fc-egress: bad list name: $name" >&2
+ exit 1
+ fi
+ list=${dir}/$user/$name
check() {
for r; do
if printf %s "$r" | grep -qxE '${portRule}'; then
@@ -173,27 +208,38 @@
trap 'rm -f "$tmp"' EXIT
"$@" > "$tmp"
cat "$tmp" > "$list"
+ chmod 644 "$list"
}
cmd=''${1-help}
shift || :
case $cmd in
list)
- cat "$list"
+ if test -e "$list"; then cat "$list"; fi
;;
allow)
check "$@"
+ touch "$list"
update sh -c '{ cat "$0"; printf "%s\n" "$@"; } | sort -u' "$list" "$@"
;;
deny)
check "$@"
+ touch "$list"
update sh -c 'grep -vxF -e "$1" "$0" || :' "$list" "$(printf '%s\n' "$@")"
;;
+ lists)
+ find ${dir}/$user -mindepth 1 -maxdepth 1 -type f -printf '%f\n' | sort
+ ;;
+ vms)
+ find ${vmDir} -mindepth 1 -maxdepth 1 -user "$user" -size +0 -printf '%f\n' | sort -V |
+ while read -r tap; do printf '%s %s\n' "$tap" "$(head -n 1 ${vmDir}/$tap)"; done
+ ;;
log)
- # 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.
+ # HTTPS connections: ALLOW|DENY, user, tap, list, server name,
+ # guest, upstream, status, bytes sent and received (from the guest's
+ # view: received, sent), seconds. Decrypted requests: ALLOW|DENY,
+ # user, tap, list, host, method, URI, status, bytes sent. Other
+ # connections (kernel log, rate-limited): fc-egress ALLOW|DENY,
+ # user, tap, and the packet.
journalctl -o short-iso _SYSTEMD_UNIT=fcbr0-egress.service + _TRANSPORT=kernel "$@" |
grep --line-buffered -E " (ALLOW|DENY) $user "
;;
@@ -229,24 +275,24 @@
fi
install -m 644 ca.crt ca.pem
cd ${runDir}
- rm -f ${lib.concatMapStringsSep " " (u: "decrypt-${u}.sock") (lib.attrNames users)} # in case nginx didn't get to clean up
+ rm -f ${lib.concatMapStringsSep " " (t: "decrypt-${t.name}.sock") taps} # in case nginx didn't get to clean up
openssl req -x509 -new -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \
-nodes -days 1 -subj /CN=unused -keyout unused.key -out unused.crt 2>/dev/null
'';
- # egress.lua, and which guest address is whose.
+ # egress.lua, and which guest address is which tap's, and whose.
egressLua = pkgs.runCommand "egress-lua" {
- users = "return {\n" + lib.concatMapStrings (t: " [\"${t.ip}\"] = \"${t.user}\",\n") taps + "}\n";
- passAsFile = [ "users" ];
+ taps = "return {\n" + lib.concatMapStrings (t: " [\"${t.ip}\"] = { tap = \"${t.name}\", user = \"${t.user}\" },\n") taps + "}\n";
+ passAsFile = [ "taps" ];
} ''
mkdir $out
cp ${./egress.lua} $out/egress.lua
- cp $usersPath $out/egress_users.lua
+ cp $tapsPath $out/egress_taps.lua
'';
# stream: reads the ClientHello (ssl_preread), egress.lua decides, and
# nginx passes the connection through to the server name, or to the http
- # server to decrypt it (on the user's socket, which tells it whose the
+ # server to decrypt it (on the tap's socket, which tells it whose the
# connection is), or closes it. http: egress.lua makes the
# certificate and checks each request, nginx forwards allowed ones to
# the server name, verifying its certificate. The original request URI
@@ -261,6 +307,7 @@
env FC_EGRESS_RULES=${dir};
env FC_EGRESS_STATE=${stateDir};
env FC_EGRESS_RUN=${runDir};
+ env FC_EGRESS_VMS=${vmDir};
events {
worker_connections ${toString workerConnections};
}
@@ -271,7 +318,7 @@
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
+ # Per user (not per VM): 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.
@@ -295,21 +342,21 @@ ${lib.concatMapStrings (u: " limit_conn user_${u} ${toString (users.${u}
http {
lua_package_path "${egressLua}/?.lua;;";
include ${runDir}/resolver.conf;
- log_format egress '$egress_verdict $egress_user $host $request_method $request_uri $status $body_bytes_sent';
+ log_format egress '$egress_verdict $egress_guest $host $request_method $request_uri $status $body_bytes_sent';
# Only requests that got to egress.lua (others, like a TLS
# handshake without request, have no verdict).
access_log syslog:server=unix:/dev/log,nohostname,tag=fc_egress egress if=$egress_verdict;
uninitialized_variable_warn off;
server {
-${lib.concatMapStrings (u: " listen unix:${runDir}/decrypt-${u}.sock ssl;\n") (lib.attrNames users)}
+${lib.concatMapStrings (t: " listen unix:${runDir}/decrypt-${t.name}.sock ssl;\n") taps}
http2 on;
ssl_certificate ${runDir}/unused.crt;
ssl_certificate_key ${runDir}/unused.key;
ssl_certificate_by_lua_block { require("egress").certificate() }
client_max_body_size 0;
set $egress_verdict "";
- set $egress_user "";
+ set $egress_guest "";
location / {
access_by_lua_block { require("egress").access() }
@@ -354,8 +401,8 @@ 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), except to denyDestinations.
+ # 172.16.0.1:proxyPort), and what their list's tcp:// and udp:// rules
+ # allow (set allow_TAP, 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
@@ -363,8 +410,8 @@ in {
# 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
+ # connections get logged (rate-limited), with user and tap, as
+ # "fc-egress ALLOW USER TAP" and "fc-egress DENY USER TAP" (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;
@@ -375,12 +422,12 @@ in {
networking.nftables.tables.firecracker = {
family = "inet";
content = ''
-${lib.concatMapStrings (u: ''
- set allow_${u} {
+${lib.concatMapStrings (t: ''
+ set allow_${t.name} {
type ipv4_addr . inet_proto . inet_service
flags interval
}
-'') userNames}
+'') taps}
set deny4 {
type ipv4_addr
flags interval
@@ -439,7 +486,7 @@ ${lib.concatMapStrings (u: ''
ct state { established, related } accept
jump limits
ip daddr @deny4 jump refused
- jump users
+ jump vms
jump refused
}
@@ -448,14 +495,14 @@ ${lib.concatMapStrings (u: ''
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: 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 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
+'') taps} }
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
+${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} reject with icmpx admin-prohibited
}
chain output {
@@ -530,20 +577,25 @@ ${lib.concatMapStrings (u: " ip saddr { ${lib.concatStringsSep ", " (ipsO
};
};
- # Each user's rules, readable by anyone, changeable only by the user.
- systemd.tmpfiles.rules = [ "d ${dir} 0755 root root -" ]
+ # 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 -" ]
++ lib.concatMap (u: [
"d ${dir}/${u} 0755 ${u} - -"
- "f ${dir}/${u}/allowed 0644 ${u} - -"
- ]) (lib.attrNames users);
+ "f ${dir}/${u}/default 0644 ${u} - -"
+ ]) userNames
+ ++ map (t: "f ${vmDir}/${t.name} 0644 ${t.user} - -") taps;
# Forwarding, for the tcp:// and udp:// rules.
boot.kernel.sysctl."net.ipv4.ip_forward" = 1;
- # 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.
+ # 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.
systemd.services.fcbr0-firewall = {
wantedBy = [ "multi-user.target" ];
after = [ "nftables.service" "systemd-tmpfiles-setup.service" ];
@@ -561,11 +613,14 @@ ${lib.concatMapStrings (u: " ip saddr { ${lib.concatStringsSep ", " (ipsO
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);
+ systemd.paths = let
+ path = name: 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";
+ };
+ in lib.listToAttrs (map (u: path u "${dir}/${u}") userNames
+ ++ map (t: path t.name "${vmDir}/${t.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).