diff options
Diffstat (limited to 'modules')
| -rw-r--r-- | modules/host/default.nix | 150 | ||||
| -rw-r--r-- | modules/host/egress.lua | 37 |
2 files changed, 128 insertions, 59 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). 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 |
