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.nix150
1 files changed, 105 insertions, 45 deletions
diff --git a/modules/host/default.nix b/modules/host/default.nix
index 37f3e83..87a32d3 100644
--- a/modules/host/default.nix
+++ b/modules/host/default.nix
@@ -1,29 +1,48 @@
# Host side of the guests' network: a bridge with tap devices fctap0,
-# fctap1, ... owned by the user running the VMs, a DHCP server, and nginx
-# (OpenResty, i.e. with Lua) as the guests' only way out. Each running VM
-# takes one tap device, so taps is the number of VMs that can run at the
-# same time.
+# fctap1, ..., each owned by one of the users that run VMs, a DHCP server,
+# and nginx (OpenResty, i.e. with Lua) as the guests' only way out. Each
+# 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.
#
-# Egress: 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 in
-# /var/lib/fc-egress/allowed (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.
-# The user can change the rules at any time with fc-egress (see fc-egress
-# help); they apply to the next connection.
+# 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.
#
-# usage (in the host's configuration.nix):
-# imports = [ (import ./modules/host { user = "tv"; }) ];
+# Egress, per user: 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):
+# 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.
+#
+# usage (in the host's configuration.nix), users and their number of taps:
+# 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).
-{ user, taps ? 8, proxyPort ? 10443 }: { lib, pkgs, ... }: let
- tapNames = map (i: "fctap${toString i}") (lib.range 0 (taps - 1));
+{ users, proxyPort ? 10443 }: { 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));
+ tap = i: user: {
+ name = "fctap${toString i}";
+ inherit user;
+ ip = "172.16.0.${toString (i + 2)}";
+ 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);
dir = "/var/lib/fc-egress";
- allowed = "${dir}/allowed";
# Where nginx keeps the CA: ca.key, and ca.pem for the guests (see
# caCert in pkgs/run-firecracker-vm).
@@ -33,7 +52,12 @@
fc-egress = pkgs.writeShellScriptBin "fc-egress" ''
set -efu
export PATH=${lib.makeBinPath [ pkgs.bash pkgs.coreutils pkgs.gnugrep pkgs.systemd ]}
- list=${allowed}
+ user=$(id -un)
+ list=${dir}/$user/allowed
+ if ! test -e "$list"; 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..."
@@ -72,11 +96,11 @@
update sh -c 'grep -vxF -e "$1" "$0" || :' "$list" "$(printf '%s\n' "$@")"
;;
log)
- # Connections: ALLOW|DENY, server name, guest, upstream, status,
- # bytes sent and received (from the guest's view: received, sent),
- # seconds. Decrypted requests: ALLOW|DENY, host, method, URI,
- # status, bytes sent.
- journalctl -u fcbr0-egress -o short-iso "$@" | grep --line-buffered -E ' (ALLOW|DENY) '
+ # 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 "
;;
help|-h|--help)
usage
@@ -110,16 +134,25 @@
fi
install -m 644 ca.crt ca.pem
cd ${runDir}
- rm -f decrypt.sock # in case nginx didn't get to clean up
+ rm -f ${lib.concatMapStringsSep " " (u: "decrypt-${u}.sock") (lib.attrNames users)} # 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
'';
- egressLua = pkgs.writeTextDir "egress.lua" (builtins.readFile ./egress.lua);
+ # egress.lua, and which guest address is whose.
+ egressLua = pkgs.runCommand "egress-lua" {
+ users = "return {\n" + lib.concatMapStrings (t: " [\"${t.ip}\"] = \"${t.user}\",\n") taps + "}\n";
+ passAsFile = [ "users" ];
+ } ''
+ mkdir $out
+ cp ${./egress.lua} $out/egress.lua
+ cp $usersPath $out/egress_users.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, or closes it. http: egress.lua makes the
+ # server to decrypt it (on the user'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
# goes upstream unchanged (proxy_pass with variables and no URI), which
@@ -129,9 +162,9 @@
pid ${runDir}/nginx.pid;
error_log stderr warn;
worker_processes 1;
- env FC_EGRESS_RULES=${allowed};
+ env FC_EGRESS_RULES=${dir};
env FC_EGRESS_STATE=${stateDir};
- env FC_EGRESS_DECRYPT=${runDir}/decrypt.sock;
+ env FC_EGRESS_RUN=${runDir};
events {}
stream {
@@ -153,20 +186,21 @@
http {
lua_package_path "${egressLua}/?.lua;;";
include ${runDir}/resolver.conf;
- log_format egress '$egress_verdict $host $request_method $request_uri $status $body_bytes_sent';
+ log_format egress '$egress_verdict $egress_user $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 {
- listen unix:${runDir}/decrypt.sock ssl;
+${lib.concatMapStrings (u: " listen unix:${runDir}/decrypt-${u}.sock ssl;\n") (lib.attrNames users)}
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 "";
location / {
access_by_lua_block { require("egress").access() }
@@ -191,14 +225,19 @@
}
'';
in {
- networking.interfaces = lib.genAttrs tapNames (_: {
+ assertions = [{
+ assertion = lib.length taps <= 253;
+ message = "modules/host: at most 253 taps (172.16.0.2 to .254)";
+ }];
+
+ networking.interfaces = lib.listToAttrs (map (t: lib.nameValuePair t.name {
virtual = true;
virtualType = "tap";
- virtualOwner = user;
- }) // {
+ virtualOwner = t.user;
+ }) taps) // {
fcbr0.ipv4.addresses = [{ address = "172.16.0.1"; prefixLength = 24; }];
};
- networking.bridges.fcbr0.interfaces = tapNames;
+ networking.bridges.fcbr0.interfaces = map (t: t.name) taps;
# With networkd, fcbr0 would only get its address while it has carrier,
# i.e. while a VM runs, so nginx couldn't bind to it. (Unused
# with scripted networking, which assigns it regardless.)
@@ -237,9 +276,27 @@ in {
}
'';
};
+ # On the bridge: each tap may only send from its own address (or
+ # 0.0.0.0, for DHCP and ARP probes), IPv4 and ARP 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} }
+ }
+
+ 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
+ ether type arp arp saddr ip 0.0.0.0 accept
+ drop
+ }
+
chain forward {
type filter hook forward priority filter; policy accept;
iifname "fctap*" oifname "fctap*" drop
@@ -248,7 +305,8 @@ in {
};
# A dnsmasq of its own, so it doesn't get mixed up with one the host might
- # run otherwise. DHCP, and DNS that resolves every name to 172.16.0.1
+ # 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
# (except-interface=lo, else it would also take 127.0.0.1:53 from a
@@ -260,7 +318,7 @@ in {
serviceConfig = {
RuntimeDirectory = "fcbr0-dnsmasq";
Restart = "on-failure";
- ExecStart = lib.escapeShellArgs [
+ ExecStart = lib.escapeShellArgs ([
"${pkgs.dnsmasq}/bin/dnsmasq"
"--keep-in-foreground"
"--conf-file=/dev/null"
@@ -268,20 +326,22 @@ in {
"--interface=fcbr0"
"--except-interface=lo"
"--dhcp-authoritative"
- "--dhcp-range=172.16.0.2,172.16.0.254,1h"
+ "--dhcp-range=172.16.0.0,static"
"--dhcp-leasefile=/run/fcbr0-dnsmasq/leases"
"--no-resolv"
"--no-hosts"
"--address=/#/172.16.0.1"
"--local=/#/"
- ];
+ ] ++ map (t: "--dhcp-host=${t.mac},${t.ip}") taps);
};
};
- systemd.tmpfiles.rules = [
- "d ${dir} 0755 ${user} - -"
- "f ${allowed} 0644 ${user} - -"
- ];
+ # Each user's rules, readable by anyone, changeable only by the user.
+ systemd.tmpfiles.rules = [ "d ${dir} 0755 root root -" ]
+ ++ lib.concatMap (u: [
+ "d ${dir}/${u} 0755 ${u} - -"
+ "f ${dir}/${u}/allowed 0644 ${u} - -"
+ ]) (lib.attrNames users);
# 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).