diff options
| author | tv <tv@krebsco.de> | 2026-11-17 02:28:41 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-17 02:28:41 +0000 |
| commit | d6c5c010f3764e2a7bc7c6b654ef7986d704199b (patch) | |
| tree | 80fb6fb6f51618e2f81a150db2eb1cef998b9e21 | |
| parent | b050c6af6aedbe78201addb4abe2636ab075d14e (diff) | |
per-VM egress whitelists
Whitelists are now named, any number per user, in
/var/lib/fc-egress/USER/LIST, and each VM uses one of them:
run-firecracker-vm --egress LIST (default: default). The run script
writes the list's name to /run/fc-egress/TAP when it takes the tap, and
empties it when the VM exits; a list that doesn't exist allows nothing.
A user's VMs can only use that user's lists.
So the unit of policy is the tap (i.e. the running VM) rather than the
user: nftables sets allow_TAP, nginx decrypt sockets decrypt-TAP.sock,
egress_taps.lua maps guest addresses to tap and user. fcbr0-firewall
updates a tap when its file in /run/fc-egress changes, and all of a
user's taps when anything in the user's directory does. nginx's
connection limit stays per user.
fc-egress takes -l LIST (default: default), and has new commands lists
and vms (running VMs' taps and their lists). Log lines now say user,
tap and (nginx's) list: "ALLOW|DENY USER TAP LIST ...", kernel:
"fc-egress ALLOW|DENY USER TAP".
The old rules file, /var/lib/fc-egress/USER/allowed, is now just a list
named "allowed"; rename it to "default" to keep using it.
| -rw-r--r-- | README.md | 23 | ||||
| -rw-r--r-- | modules/host/default.nix | 197 | ||||
| -rw-r--r-- | modules/host/egress.lua | 67 | ||||
| -rw-r--r-- | pkgs/run-firecracker-vm/default.nix | 26 |
4 files changed, 214 insertions, 99 deletions
@@ -36,7 +36,7 @@ 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 +- `denyDestinations`: addresses no whitelist 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 @@ -84,9 +84,10 @@ 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 of the guest's -user, in `/var/lib/fc-egress/USER/allowed`. Each user manages their own -with `fc-egress`: +the proxy, which decides by the server name and the VM's whitelist. +Each user has any number of named whitelists, in +`/var/lib/fc-egress/USER/LIST`, and manages them with `fc-egress` +(`-l LIST`; without it, the list `default`): ```sh fc-egress list @@ -95,10 +96,22 @@ fc-egress allow github.com/NixOS/ # only paths starting with /NixOS/ fc-egress allow tcp://192.0.2.7:22 # plain TCP to that address and port fc-egress allow udp://192.0.2.0/24:5000-5100 fc-egress deny github.com/NixOS/ +fc-egress -l work allow example.com # the list "work" +fc-egress lists fc-egress log -f ``` -Changes apply to the next connection. Whole domains get passed through +Each VM uses one list, `default` unless given another: + +```sh +./result/bin/run-firecracker-vm --egress work +``` + +A list that doesn't exist allows nothing. `fc-egress vms` shows the +running VMs' taps (as in the log) and their lists. Which list a running +VM uses is in `/run/fc-egress/TAP`; to switch, write another name there +(`echo default > /run/fc-egress/fctap3`). Changes to lists and switches +apply to the next connection. Whole domains get passed through encrypted. Domains with path rules get decrypted to check each request, with certificates from a CA the host creates on first start (`/var/lib/fcbr0-egress/ca.pem`). The guest trusts that CA if it exists 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). diff --git a/modules/host/egress.lua b/modules/host/egress.lua index 6c507a1..c4c92eb 100644 --- a/modules/host/egress.lua +++ b/modules/host/egress.lua @@ -1,8 +1,9 @@ -- The guests' egress policy, for nginx (OpenResty), see default.nix. -- --- 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: +-- Per VM: which tap (and so whose) a guest is, egress_taps.lua says by its +-- address (which the bridge makes sure of, see default.nix). VMS/TAP has +-- the name of the VM's list, RULES/USER/LIST its rules, one per line, both +-- 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/, @@ -15,19 +16,36 @@ local _M = {} -local RULES = os.getenv("FC_EGRESS_RULES") -- RULES/USER/allowed +local RULES = os.getenv("FC_EGRESS_RULES") -- RULES/USER/LIST +local VMS = os.getenv("FC_EGRESS_VMS") -- VMS/TAP: LIST local STATE = os.getenv("FC_EGRESS_STATE") -- ca.key, ca.pem -local RUN = os.getenv("FC_EGRESS_RUN") -- RUN/decrypt-USER.sock: the http server -local users = require("egress_users") -- guest address -> user +local RUN = os.getenv("FC_EGRESS_RUN") -- RUN/decrypt-TAP.sock: the http server +local guests = require("egress_taps") -- guest address -> { tap, user } +local by_tap = {} +for _, g in pairs(guests) do + by_tap[g.tap] = g +end 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(user) +-- The name of the guest's list, nil if none (or a bad one), and its +-- description for the log: USER TAP LIST. +local function list(guest) + local f = io.open(VMS .. "/" .. guest.tap) + local name = f and f:read(256) + if f then + f:close() + end + name = name and name:match("^([A-Za-z0-9_-]+)\n?$") + return name, guest.user .. " " .. guest.tap .. " " .. (name or "-") +end + +local function rules(guest, name) local domains, paths = {}, {} - local f = io.open(RULES .. "/" .. user .. "/allowed") + local f = name and io.open(RULES .. "/" .. guest.user .. "/" .. name) if not f then return domains, paths end @@ -49,12 +67,12 @@ local function rules(user) end -- nil (deny), "pass", or the list of allowed path prefixes -local function policy(host, user) +local function policy(host, guest, name) host = host and host:lower() - if not user or not valid_name(host) then + if not guest or not name or not valid_name(host) then return nil end - local domains, paths = rules(user) + local domains, paths = rules(guest, name) local prefixes = {} local suffix = host while suffix do @@ -74,15 +92,20 @@ end -- stream, preread: pass through, decrypt, or close function _M.preread() local sni = ngx.var.ssl_preread_server_name - local user = users[ngx.var.remote_addr] - local p = policy(sni, user) + local guest = guests[ngx.var.remote_addr] + local name, who + if guest then + name, who = list(guest) + end + local p = policy(sni, guest, name) + who = who or "- - -" if p == "pass" then ngx.var.egress_upstream = sni:lower() .. ":443" - ngx.var.egress_log = "ALLOW " .. user .. " " .. sni:lower() + ngx.var.egress_log = "ALLOW " .. who .. " " .. sni:lower() elseif p then - ngx.var.egress_upstream = "unix:" .. RUN .. "/decrypt-" .. user .. ".sock" + ngx.var.egress_upstream = "unix:" .. RUN .. "/decrypt-" .. guest.tap .. ".sock" else - ngx.var.egress_log = "DENY " .. (user or "-") .. " " .. (sni ~= "" and sni or "-") + ngx.var.egress_log = "DENY " .. who .. " " .. (sni ~= "" and sni or "-") return ngx.exit(403) end end @@ -130,7 +153,7 @@ local function make_cert(name) 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 +-- some VM's path rules allow get here (see preread), and each request -- gets checked in access. function _M.certificate() local ssl = require("ngx.ssl") @@ -151,12 +174,16 @@ 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 guest = by_tap[(ngx.var.server_addr or ""):match("decrypt%-(.+)%.sock$")] + local name, who + if guest then + name, who = list(guest) + end + ngx.var.egress_guest = who 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, user) + local p = policy(sni, guest, name) 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 b6e5387..5b148da 100644 --- a/pkgs/run-firecracker-vm/default.nix +++ b/pkgs/run-firecracker-vm/default.nix @@ -306,6 +306,7 @@ in pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ '' # usage: run-firecracker-vm [--store FILE] [--store-size SIZE] # [--nixpkgs DIR] [--nixpkgs-cache MODE] + # [--egress LIST] # The guest gets the host's store, read-only, via 9P over vsock, and the # directory xchg (in the current working directory) at /xchg, the same # way. VMs started in the same directory share it. Also the same way, @@ -319,15 +320,18 @@ pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ '' # when the guest exits, or with --store, to FILE, which keeps it across # boots (created if it doesn't exist, of --store-size, default 16G; the # file is sparse, so that's only an upper limit). + # The guest's egress goes by the user's whitelist LIST (default: + # default), see modules/host and fc-egress. set -efu - export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.e2fsprogs pkgs.findutils pkgs.gnused pkgs.util-linux pkgs.firecracker pkgs.unpfs ]} + export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.e2fsprogs pkgs.findutils pkgs.gnugrep pkgs.gnused pkgs.util-linux pkgs.firecracker pkgs.unpfs ]} usage() { - echo "usage: $0 [--store FILE] [--store-size SIZE] [--nixpkgs DIR] [--nixpkgs-cache MODE]" + echo "usage: $0 [--store FILE] [--store-size SIZE] [--nixpkgs DIR] [--nixpkgs-cache MODE] [--egress LIST]" } args= rw_store= rw_store_size=16G + egress=default nixpkgs=${lib.escapeShellArg (toString pkgs.path)} while test $# -gt 0; do case $1 in @@ -336,6 +340,7 @@ pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ '' --store-size) rw_store_size=$2; shift 2 ;; --nixpkgs) nixpkgs=$2; shift 2 ;; --nixpkgs-cache) args="$args fc.9p566=cache=$2"; shift 2 ;; + --egress) egress=$2; shift 2 ;; -h|--help) usage; exit ;; *) usage >&2; exit 1 esac @@ -396,6 +401,21 @@ pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ '' exit 1 fi n=''${tap#fctap} + # The guest's whitelist: modules/host goes by the name in the tap's file + # in /run/fc-egress (emptied again when the guest exits, below). + vm=/run/fc-egress/$tap + if test -w "$vm"; then + if ! printf %s "$egress" | grep -qxE '[A-Za-z0-9_-]+'; then + echo "$0: bad list name: $egress" >&2 + exit 1 + fi + if ! test -f "/var/lib/fc-egress/$(id -un)/$egress"; then + echo "$0: no list $egress (see fc-egress), no egress" >&2 + fi + printf '%s\n' "$egress" > "$vm" + else + vm= + fi mac=$(printf '06:00:ac:10:%02x:%02x' $((n >> 8 & 255)) $((n & 255))) # The 9P servers, for the store, /xchg, and nixpkgs, one each per VM. @@ -415,7 +435,7 @@ pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ '' xchg=$! RUST_LOG=off unpfs "unix!$tmp/vsock!_566" "$nixpkgs" > /dev/null & nixpkgs_server=$! - trap 'kill $store $xchg $nixpkgs_server; rm -rf "$tmp"' EXIT + trap 'kill $store $xchg $nixpkgs_server; rm -rf "$tmp"; if test -n "$vm"; then : > "$vm"; fi' EXIT while ! test -S "$vsock"_565; do sleep 0.01; done sed \ |
