From 4e480218c0777ba9342ce2edd3b00ff3488229b2 Mon Sep 17 00:00:00 2001 From: tv Date: Sat, 21 Nov 2026 13:08:29 +0000 Subject: host: guests can check what their egress allows, fc-egress check So a guest can know beforehand whether it gets somewhere, instead of finding out by timeouts and retries, and can tell which rule it lacks. nginx answers POST http://172.16.0.1/check (the guests' port 80 of 172.16.0.1 gets redirected to 172.16.0.1:checkPort, default 10080; plain HTTP anywhere else stays refused): URIs one per line, at most 100, and true or false for each, a line each, by the same rules as the egress: whole domains and path rules for https://HOST[/PATH] (port 443 only), and for tcp:// and udp://HOST:PORT the list's rules, with names as resolved for the guest's tap (its hosts file), but not to denyDestinations or the host's own addresses on fcbr0, and not to tcp port 443, which goes to the proxy. Read-only, about the asking guest's own list only (by its address, as for its egress), and rate-limited. In the guest, fc-egress check URI... asks that, over bash's /dev/tcp, as the guest may have no HTTP client, and prints true or false and the URI, a line each; exit status 0 if all are allowed, 1 if not, 2 on errors. --- README.md | 20 ++- modules/host/default.nix | 39 +++++- modules/host/egress.lua | 268 +++++++++++++++++++++++++++++++++++- pkgs/run-firecracker-vm/default.nix | 57 ++++++++ 4 files changed, 379 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 874cc45..30dc439 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,8 @@ Optional arguments: ``` - `proxyPort` (default 10443): where the proxy listens; the guests' port 443 gets redirected there. +- `checkPort` (default 10080): where the guests' checks of their egress + get answered; their port 80 of 172.16.0.1 gets redirected there. - `prefix6` (default `fdfc:fc::`): the guests' IPv6 /64. Each guest gets the address from its MAC (SLAAC, from router advertisements by the host's dnsmasq), for tcp:// and udp:// rules; HTTPS stays IPv4, @@ -67,7 +69,8 @@ Optional arguments: second): limits per guest, so one user can't starve the others. If the host has a firewall of its own, it has to let the guests in on -`fcbr0`: udp 67 (DHCP), udp and tcp 53 (DNS), and tcp 10443 (the proxy). +`fcbr0`: udp 67 (DHCP), udp and tcp 53 (DNS), tcp 10443 (the proxy), and +tcp 10080 (the checks). ## Running a VM @@ -233,6 +236,21 @@ chain of its own, it has to let them through, too (anything from For `nix-shell` and the like to download, allow `cache.nixos.org`. +Guests can check what their egress allows, before relying on it, with +`fc-egress check` (the guest's own, read-only one), which asks the host: + +```sh +fc-egress check https://github.com/krebs/kartei tcp://172.16.0.1:22 +``` + +prints `true` or `false` and the URI, a line each (exit status 0 if all +are allowed, 1 if not), by the same rules as the egress itself: whole +domains and path rules for `https://`, and for `tcp://` and `udp://` +the rules, their names as resolved for the VM, and `denyDestinations`. +It asks `POST http://172.16.0.1/check`, URIs one per line (at most 100), +`true` or `false` for each, a line each; any guest can only ask about +the list its own VM uses. + ## Layout - `pkgs/run-firecracker-vm/default.nix`: the guest's NixOS configuration, diff --git a/modules/host/default.nix b/modules/host/default.nix index 144a23a..26120b8 100644 --- a/modules/host/default.nix +++ b/modules/host/default.nix @@ -56,12 +56,16 @@ # The taps' own addresses, for VMs without, are from 172.16.0.200 on (but # for vms'). # 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). +# DNS (udp and tcp 53), the proxy (tcp proxyPort, after the redirect), +# and the checks (tcp checkPort, likewise). { users # VM name -> { user; ip; }: that VM's address (172.16.0.2 to .254), see # above. , vms ? { } , proxyPort ? 10443 + # Where nginx answers the guests' checks of their egress (their port 80 + # of 172.16.0.1 gets redirected there). +, checkPort ? 10080 # The guests' IPv6 /64 (on fcbr0, the host is ::1): each guest gets the # address from its MAC (SLAAC with EUI-64, see taps), for the tcp:// and # udp:// rules. Unique local, so forwarded connections get NATed, like @@ -492,6 +496,11 @@ ${lib.concatMapStrings (v: " \"${v.user} ${v.vm}\") vip=${v.ip} vip6=${ + lib.concatMapStrings (a: " [\"${a.ip}\"] = \"${a.user}\",\n") addresses + " },\n taps = {\n" + lib.concatMapStrings (t: " [\"${t.name}\"] = \"${t.user}\",\n") taps + # For checks: where no rule gets a guest (the host's own addresses + # on fcbr0, too; its others are out of reach as well, but unknown + # here). + + " },\n deny = {\n" + + lib.concatMapStrings (d: " \"${d}\",\n") (denyDestinations ++ [ "172.16.0.1" "${prefix6}1" ]) + " },\n}\n"; passAsFile = [ "guests" ]; } '' @@ -519,6 +528,7 @@ ${lib.concatMapStrings (v: " \"${v.user} ${v.vm}\") vip=${v.ip} vip6=${ env FC_EGRESS_RUN=${runDir}; env FC_EGRESS_VMS=${vmDir}; env FC_EGRESS_ADDR=${addrDir}; + env FC_EGRESS_HOSTS=${hostsDir}; events { worker_connections ${toString workerConnections}; } @@ -589,6 +599,27 @@ ${lib.concatMapStrings (t: " listen unix:${runDir}/decrypt-${t.name}.sock proxy_busy_buffers_size 128k; } } + + # The guests' checks of their egress (the guests' port 80 of + # 172.16.0.1 gets redirected here): POST /check, URIs one per line, + # true or false for each, a line each, by the same rules as their + # egress. Read-only, and only ever about the asking guest's own list. + limit_req_zone $binary_remote_addr zone=check:1m rate=10r/s; + server { + listen 172.16.0.1:${toString checkPort}; + access_log off; + client_max_body_size 64k; + client_body_buffer_size 64k; + limit_req zone=check burst=20 nodelay; + location = /check { + limit_except POST { deny all; } + content_by_lua_block { require("egress").check() } + } + location / { + default_type text/plain; + return 200 "POST /check: URIs (https://..., tcp://HOST:PORT, udp://HOST:PORT), one per line;\ntrue or false for each, whether this guest's egress allows it.\n"; + } + } } ''; in { @@ -646,7 +677,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 list's tcp:// and udp:// rules + # 172.16.0.1:proxyPort), checks of their egress (port 80 of 172.16.0.1, + # redirected to 172.16.0.1:checkPort), 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 @@ -733,6 +765,7 @@ ${lib.concatMapStrings (t: '' chain prerouting { type nat hook prerouting priority dstnat - 1; iifname "fcbr0" meta nfproto ipv4 tcp dport 443 redirect to :${toString proxyPort} + iifname "fcbr0" ip daddr 172.16.0.1 tcp dport 80 redirect to :${toString checkPort} iifname "fcbr0" meta nfproto ipv4 meta l4proto { tcp, udp } dnat ip to ip daddr iifname "fcbr0" meta nfproto ipv6 meta l4proto { tcp, udp } dnat ip6 to ip6 daddr } @@ -751,7 +784,7 @@ ${lib.concatMapStrings (t: '' jump limits ip daddr { 172.16.0.1, 255.255.255.255 } udp dport 67 accept ip daddr 172.16.0.1 udp dport 53 accept - ip daddr 172.16.0.1 tcp dport { 53, ${toString proxyPort} } accept + ip daddr 172.16.0.1 tcp dport { 53, ${toString proxyPort}, ${toString checkPort} } accept jump refused } diff --git a/modules/host/egress.lua b/modules/host/egress.lua index d276e05..3741b71 100644 --- a/modules/host/egress.lua +++ b/modules/host/egress.lua @@ -23,7 +23,9 @@ 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-TAP.sock: the http server local ADDR = os.getenv("FC_EGRESS_ADDR") -- ADDR/TAP: ADDRESS, ADDR/ADDRESS: TAP --- { addresses = { [ADDRESS] = USER }, taps = { [TAP] = USER } } +local HOSTS = os.getenv("FC_EGRESS_HOSTS") -- HOSTS/TAP: ADDRESS NAME, the tap's rules' names +-- { addresses = { [ADDRESS] = USER }, taps = { [TAP] = USER }, +-- deny = { ADDRESS/PREFIXLEN, ... } } local owners = require("egress_guests") local by_tap = {} for tap, user in pairs(owners.taps) do @@ -229,4 +231,268 @@ function _M.access() end end +-- For the guests' checks: addresses, as numbers (IPv4) or eight 16-bit +-- groups (IPv6), and whether an address is in a prefix. + +local bit = require("bit") + +local function v4(s) + local a, b, c, d = (s or ""):match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$") + if not a then + return nil + end + local n = 0 + for _, x in ipairs({ a, b, c, d }) do + x = tonumber(x) + if x > 255 then + return nil + end + n = n * 256 + x + end + return n +end + +local function v6(s) + s = s or "" + if not s:match("^[%x:]+$") or s:find(":::") then + return nil + end + local head, tail = s:match("^(.-)::(.*)$") + local function groups(t) + local g = {} + for x in t:gmatch("[^:]+") do + if #x > 4 then + return nil + end + table.insert(g, tonumber(x, 16)) + end + return g + end + local g + if head then + local h, t = groups(head), groups(tail) + if not h or not t or #h + #t > 7 then + return nil + end + g = h + for _ = 1, 8 - #h - #t do + table.insert(g, 0) + end + for _, x in ipairs(t) do + table.insert(g, x) + end + else + g = groups(s) + if not g or #g ~= 8 then + return nil + end + end + return g +end + +-- { family = 4, n = NUMBER } or { family = 6, g = GROUPS }, or nil +local function address(s) + local n = v4(s) + if n then + return { family = 4, n = n } + end + local g = v6(s) + if g then + return { family = 6, g = g } + end +end + +-- Whether address a is in ADDRESS[/PREFIXLEN]. +local function within(a, prefix) + local p, len = prefix:match("^(.-)/(%d+)$") + p = address(p or prefix) + if not p or p.family ~= a.family then + return false + end + len = tonumber(len) or (a.family == 4 and 32 or 128) + if a.family == 4 then + if len > 32 then + return false + end + if len == 0 then + return true + end + local mask = bit.lshift(-1, 32 - len) + return bit.band(bit.tobit(a.n), mask) == bit.band(bit.tobit(p.n), mask) + end + if len > 128 then + return false + end + for i = 1, 8 do + local bits = math.min(math.max(len - (i - 1) * 16, 0), 16) + if bits == 0 then + break + end + local mask = bit.band(bit.lshift(0xffff, 16 - bits), 0xffff) + if bit.band(a.g[i], mask) ~= bit.band(p.g[i], mask) then + return false + end + end + return true +end + +-- The guest's tcp:// and udp:// rules: { proto, host, from, to }, host an +-- ADDRESS[/PREFIXLEN] or a name, as fcbr0-firewall takes them. +local function port_rules(guest, name) + local list = {} + local f = name and io.open(RULES .. "/" .. guest.user .. "/" .. name) + if not f then + return list + end + local text = f:read(65536) or "" + f:close() + for line in text:gmatch("[^\n]+") do + local proto, host, from, to = line:match("^%s*(%a+)://(.+):(%d+)%-?(%d*)%s*$") + if proto == "tcp" or proto == "udp" then + host = host:match("^%[(.+)%]$") or host + table.insert(list, { proto = proto, host = host:lower(), + from = tonumber(from), to = tonumber(to) or tonumber(from) }) + end + end + return list +end + +-- What the tap's guest gets for names in rules (fcbr0-firewall's hosts +-- file for the tap): { [NAME] = { ADDRESS, ... } }; any other name, the +-- guest gets 172.16.0.1. +local function hosts(guest) + local map = {} + local f = io.open(HOSTS .. "/" .. guest.tap) + if not f then + return map + end + for line in (f:read(65536) or ""):gmatch("[^\n]+") do + local a, n = line:match("^(%S+)%s+(%S+)") + if a then + n = n:lower() + map[n] = map[n] or {} + table.insert(map[n], a) + end + end + f:close() + return map +end + +-- Whether the guest can connect to tcp:// or udp://HOST:PORT, as the +-- firewall decides: an address that a rule allows (by address or prefix, +-- or by name, as resolved for the tap), but not in denyDestinations, and +-- not tcp port 443, which goes to the proxy (IPv4) or nowhere (IPv6). +local function port_ok(guest, name, proto, host, port) + if proto == "tcp" and port == 443 then + return false + end + local resolved = hosts(guest) + local candidates + if address(host) then + candidates = { host } + else + candidates = resolved[host:lower()] or {} + end + local list = port_rules(guest, name) + for _, c in ipairs(candidates) do + local a = address(c) + local denied = not a + for _, d in ipairs(owners.deny) do + if a and within(a, d) then + denied = true + end + end + if not denied then + for _, r in ipairs(list) do + if r.proto == proto and port >= r.from and port <= r.to then + if address(r.host:match("^[^/]+")) then + if within(a, r.host) then + return true + end + else + for _, ra in ipairs(resolved[r.host] or {}) do + local b = address(ra) + if b and b.family == a.family and within(a, ra) then + return true + end + end + end + end + end + end + end + return false +end + +-- Whether the guest's egress allows a URI: https://HOST[:443][/PATH] +-- (with path rules, the path matters), or tcp:// and udp://HOST:PORT. +local function allowed(guest, name, uri) + local scheme, rest = uri:match("^(%a+)://(.*)$") + scheme = scheme and scheme:lower() + if scheme == "https" then + local authority, path = rest:match("^([^/?#]*)([^?#]*)") + local host, port = authority:match("^(.-):(%d+)$") + host = host or authority + if port and port ~= "443" then + return false + end + local p = policy(host, guest, name) + if p == "pass" then + return true + end + if type(p) ~= "table" then + return false + end + path = ngx.unescape_uri(path ~= "" and path or "/") + for segment in path:gmatch("[^/]+") do + if segment == "." or segment == ".." then + return false + end + end + for _, prefix in ipairs(p) do + if path:sub(1, #prefix) == prefix then + return true + end + end + return false + elseif scheme == "tcp" or scheme == "udp" then + local host, port = rest:match("^(.+):(%d+)$") + if not host then + return false + end + host = host:match("^%[(.+)%]$") or host + return port_ok(guest, name, scheme, host, tonumber(port)) + end + return false +end + +-- http, content: the guest's checks, one URI per line, one true or false +-- per line back, in the same order. +local MAX_CHECKS = 100 +function _M.check() + local guest = guest_at(ngx.var.remote_addr) + local name = guest and list(guest) + ngx.req.read_body() + local body = ngx.req.get_body_data() or "" + -- The body's last newline ends the last URI, it doesn't start another. + body = body:gsub("\r?\n$", "") + local lines = {} + if body ~= "" then + for line in (body .. "\n"):gmatch("([^\n]*)\n") do + table.insert(lines, (line:gsub("\r$", ""):match("^%s*(.-)%s*$"))) + end + end + if #lines > MAX_CHECKS then + ngx.status = 413 + ngx.say("at most " .. MAX_CHECKS .. " URIs") + return ngx.exit(413) + end + local out = {} + for _, line in ipairs(lines) do + table.insert(out, (guest and name and allowed(guest, name, line)) and "true" or "false") + end + ngx.header.content_type = "text/plain" + ngx.print(table.concat(out, "\n") .. (#out > 0 and "\n" or "")) +end + return _M diff --git a/pkgs/run-firecracker-vm/default.nix b/pkgs/run-firecracker-vm/default.nix index c8a77e5..fa4abc2 100644 --- a/pkgs/run-firecracker-vm/default.nix +++ b/pkgs/run-firecracker-vm/default.nix @@ -42,6 +42,60 @@ let exec ${pkgs.socat}/bin/socat VSOCK-CONNECT:2:"$1" EXEC:"${pkgs.util-linux}/bin/mount -t 9p -o trans=fd -o rfdno=0 -o wfdno=1 -o version=9p2000.L -o msize=1048576$opts vsock9p $2",nofork ''; + # The guest's side of fc-egress (see modules/host): asks the host + # whether the guest's egress allows URIs, over bash's /dev/tcp, as the + # guest may have no HTTP client. + fc-egress = pkgs.writeShellScriptBin "fc-egress" '' + # usage: fc-egress check URI... + # Whether this guest's egress allows each URI (https://HOST[/PATH], + # tcp://HOST:PORT, udp://HOST:PORT): true or false, and the URI, a line + # each. Exit status 0 if all of them are allowed, 1 if not, 2 on + # errors. The whitelist itself is the host's, see fc-egress there. + set -eu + usage() { + echo "usage: fc-egress check URI..." >&2 + exit 2 + } + test "''${1-}" = check || usage + shift + test $# -gt 0 || usage + uris=("$@") + body= + for uri; do + case $uri in *$'\n'* | *$'\r'*) + echo "fc-egress: bad URI" >&2 + exit 2 + esac + body+=$uri$'\n' + done + export LC_ALL=C # for the length in bytes + if ! exec 3<>/dev/tcp/172.16.0.1/80; then + echo "fc-egress: can't reach the host" >&2 + exit 2 + fi + printf 'POST /check HTTP/1.0\r\nHost: 172.16.0.1\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n\r\n%s' "''${#body}" "$body" >&3 + read -r _ status _ <&3 || status= + while IFS= read -r line <&3 && test -n "''${line%$'\r'}"; do :; done + if test "$status" != 200; then + echo "fc-egress: the host answered ''${status:-nothing}" >&2 + cat <&3 >&2 + exit 2 + fi + all=0 + i=0 + while read -r verdict <&3; do + test $i -lt $# || break + printf '%s %s\n' "$verdict" "''${uris[i]}" + test "$verdict" = true || all=1 + i=$((i + 1)) + done + if test $i != $#; then + echo "fc-egress: $i answers for $# URIs" >&2 + exit 2 + fi + exit $all + ''; + # The system of the first n layers (the base system being layer 0), # with n + 1 images. evalSystem = n: import (pkgs.path + "/nixos") { @@ -134,6 +188,9 @@ let (pkgs.runCommand "mount.vsock9p" { } "install -D ${mountVsock9p} $out/bin/mount.vsock9p") ]; + # fc-egress check URI..., see fc-egress above. + environment.systemPackages = [ fc-egress ]; + # sshd, started on demand (a layer may turn that off), with the host # key the run script serves via 9P on vsock port 567 (--ssh-host-key; # not in the store), copied to /run/ssh before sshd (or its socket) -- cgit v1.3.1