aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-17 01:01:06 +0000
committertv <tv@krebsco.de>2026-11-17 01:01:06 +0000
commitff3dafcc0003ffc2d48244fcd6e98984b6a9174d (patch)
tree155a9ca9fed6d2ab3000665f724d98e8a0890937
parent9d7f66b9cbdc203226ef919a4108706248d9779d (diff)
per-user egress rules
The host module takes users = { NAME = TAPS; ... } instead of a single user: each user gets that many taps, and rules of their own, in /var/lib/fc-egress/USER/allowed, managed with fc-egress as before. The proxy tells whose a guest is by its address: each tap has a fixed one, handed out by dnsmasq by MAC address (derived from the tap's number, as the run script does), and the bridge drops anything a guest sends from another address. The decrypting server gets a socket per user, as it can't see the guest's address. The run script only takes the user's own taps.
-rw-r--r--README.md21
-rw-r--r--modules/host/default.nix150
-rw-r--r--modules/host/egress.lua37
-rw-r--r--pkgs/run-firecracker-vm/default.nix10
4 files changed, 146 insertions, 72 deletions
diff --git a/README.md b/README.md
index 69ee20c..d5fb323 100644
--- a/README.md
+++ b/README.md
@@ -20,17 +20,19 @@ In the host's NixOS configuration:
```nix
imports = [
- (import /path/to/firecracker/modules/host { user = "tv"; })
+ (import /path/to/firecracker/modules/host { users = { tv = 8; alice = 2; }; })
];
```
-This sets up a bridge `fcbr0` (172.16.0.1/24) with tap devices for the
-given user, DHCP and DNS for the guests, the egress proxy, and nftables
-rules that keep the guests from reaching anything else, on the host or
-beyond. It needs `networking.nftables` (and enables it).
+`users` says who may run VMs, and how many at the same time: each gets
+that many tap devices. This sets up a bridge `fcbr0` (172.16.0.1/24)
+with the taps, DHCP and DNS for the guests, the egress proxy, and
+nftables rules that keep the guests from reaching anything else, on the
+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 arguments: `taps` (default 8, the number of VMs that can run at
-the same time) and `proxyPort` (default 10443, where the proxy listens;
+Optional argument: `proxyPort` (default 10443, where the proxy listens;
the guests' port 443 gets redirected there).
If the host has a firewall of its own, it has to let the guests in on
@@ -73,8 +75,9 @@ nix-build pkgs/run-firecracker-vm \
## Egress
The guests resolve every name to the host, and all their HTTPS goes to
-the proxy, which decides by the server name and the rules in
-`/var/lib/fc-egress/allowed`. The user manages these with `fc-egress`:
+the proxy, which decides by the server name and the rules of the guest's
+user, in `/var/lib/fc-egress/USER/allowed`. Each user manages their own
+with `fc-egress`:
```sh
fc-egress list
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).
diff --git a/modules/host/egress.lua b/modules/host/egress.lua
index 7a2b3af..6875608 100644
--- a/modules/host/egress.lua
+++ b/modules/host/egress.lua
@@ -1,6 +1,8 @@
-- The guests' egress policy, for nginx (OpenResty), see default.nix.
--
--- The rules (one per line, read on every connection and request):
+-- Per user: whose a guest is, egress_users.lua says by its address (which
+-- the bridge makes sure of, see default.nix). The user's rules are in
+-- RULES/USER/allowed, one per line, read on every connection and request:
-- example.com example.com and its subdomains, passed through
-- without decrypting
-- example.com/foo/ only requests whose path starts with /foo/,
@@ -13,18 +15,19 @@
local _M = {}
-local RULES = os.getenv("FC_EGRESS_RULES")
+local RULES = os.getenv("FC_EGRESS_RULES") -- RULES/USER/allowed
local STATE = os.getenv("FC_EGRESS_STATE") -- ca.key, ca.pem
-local DECRYPT = os.getenv("FC_EGRESS_DECRYPT") -- the http server's socket
+local RUN = os.getenv("FC_EGRESS_RUN") -- RUN/decrypt-USER.sock: the http server
+local users = require("egress_users") -- guest address -> user
local function valid_name(s)
return s ~= nil and s:match("^[a-z0-9-]+[a-z0-9.-]*$") ~= nil
and not s:find("%.%.") and s:sub(-1) ~= "."
end
-local function rules()
+local function rules(user)
local domains, paths = {}, {}
- local f = io.open(RULES)
+ local f = io.open(RULES .. "/" .. user .. "/allowed")
if not f then
return domains, paths
end
@@ -44,12 +47,12 @@ local function rules()
end
-- nil (deny), "pass", or the list of allowed path prefixes
-local function policy(host)
+local function policy(host, user)
host = host and host:lower()
- if not valid_name(host) then
+ if not user or not valid_name(host) then
return nil
end
- local domains, paths = rules()
+ local domains, paths = rules(user)
local prefixes = {}
local suffix = host
while suffix do
@@ -69,14 +72,15 @@ end
-- stream, preread: pass through, decrypt, or close
function _M.preread()
local sni = ngx.var.ssl_preread_server_name
- local p = policy(sni)
+ local user = users[ngx.var.remote_addr]
+ local p = policy(sni, user)
if p == "pass" then
ngx.var.egress_upstream = sni:lower() .. ":443"
- ngx.var.egress_log = "ALLOW " .. sni:lower()
+ ngx.var.egress_log = "ALLOW " .. user .. " " .. sni:lower()
elseif p then
- ngx.var.egress_upstream = "unix:" .. DECRYPT
+ ngx.var.egress_upstream = "unix:" .. RUN .. "/decrypt-" .. user .. ".sock"
else
- ngx.var.egress_log = "DENY " .. (sni ~= "" and sni or "-")
+ ngx.var.egress_log = "DENY " .. (user or "-") .. " " .. (sni ~= "" and sni or "-")
return ngx.exit(403)
end
end
@@ -123,10 +127,13 @@ local function make_cert(name)
return assert(require("ngx.ssl").parse_pem_cert(cert:to_PEM()))
end
+-- Whose the connection is isn't known here; but only connections that
+-- some user's path rules allow get here (see preread), and each request
+-- gets checked in access.
function _M.certificate()
local ssl = require("ngx.ssl")
local name = ssl.server_name()
- if type(policy(name)) ~= "table" then
+ if not valid_name(name and name:lower()) then
return ngx.exit(ngx.ERROR)
end
name = name:lower()
@@ -142,10 +149,12 @@ end
-- http, access: check host and path of decrypted requests
function _M.access()
+ local user = (ngx.var.server_addr or ""):match("decrypt%-(.+)%.sock$")
+ ngx.var.egress_user = user or "-"
local sni = (ngx.var.ssl_server_name or ""):lower()
local host = (ngx.var.host or ""):lower()
local path = ngx.unescape_uri((ngx.var.request_uri or ""):match("^[^?]*"))
- local p = policy(sni)
+ local p = policy(sni, user)
local ok = type(p) == "table" and host == sni and path:sub(1, 1) == "/"
if ok then
for segment in path:gmatch("[^/]+") do
diff --git a/pkgs/run-firecracker-vm/default.nix b/pkgs/run-firecracker-vm/default.nix
index 37423a8..37047b0 100644
--- a/pkgs/run-firecracker-vm/default.nix
+++ b/pkgs/run-firecracker-vm/default.nix
@@ -370,11 +370,13 @@ pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ ''
args="$args systemd.tty.rows.ttyS0=$rows systemd.tty.columns.ttyS0=$cols"
fi
- # Take the first tap device (see modules/host) that no other VM holds. The
- # lock is held until the script exits. The MAC address is derived from
- # the tap's number, so the VM gets the same DHCP lease every time.
+ # Take the first tap device of the user's (see modules/host) that no other
+ # 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.
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"
if flock -n "$lock"; then
tap=$t
@@ -383,7 +385,7 @@ pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ ''
exec {lock}>&-
done
if test -z "$tap"; then
- echo "$0: no free tap device fctap*, see modules/host" >&2
+ echo "$0: no free tap device fctap* of $(id -un)'s, see modules/host" >&2
exit 1
fi
n=''${tap#fctap}