From b4ddbaa1baddaec5411e172e0823b6f5016c5545 Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 16 Nov 2026 20:53:54 +0000 Subject: egress through nginx+lua, with path rules OpenResty replaces the plain nginx SNI proxy, and egress.lua decides by server name and the rules in /var/lib/fc-egress/allowed: DOMAIN passes the domain and its subdomains through without decrypting; DOMAIN/PREFIX decrypts, with certificates made on the fly from the host's own CA, and only forwards requests whose path starts with PREFIX. Upstream is always port 443 of the server name, as resolved by the host, and its certificate gets verified. The rules get read on every connection, so the path unit and reloads are gone. The CA certificate gets published as /var/lib/fcbr0-egress/ca.pem, and the guest trusts it when built on the host. --- default.nix | 6 +- egress.lua | 171 ++++++++++++++++++++++++++++++++++++++++++++++++++ host.nix | 203 ++++++++++++++++++++++++++++++++++++------------------------ 3 files changed, 299 insertions(+), 81 deletions(-) create mode 100644 egress.lua diff --git a/default.nix b/default.nix index 31af3c0..d553c73 100644 --- a/default.nix +++ b/default.nix @@ -1,5 +1,7 @@ { pkgs ? import {} , kernelPackages ? pkgs.linuxPackages_latest + # The CA of the host's egress proxy (see host.nix), if it's there. +, caCert ? "/var/lib/fcbr0-egress/ca.pem" }: let inherit (pkgs) lib; @@ -66,8 +68,10 @@ let networking.useDHCP = false; networking.resolvconf.enable = false; # The host resolves every name to itself and proxies TLS to allowed - # names, see host.nix. + # names, decrypting some with certificates from its CA, see host.nix. environment.etc."resolv.conf".text = "nameserver 172.16.0.1\n"; + security.pki.certificateFiles = + lib.optional (builtins.pathExists caCert) (/. + caCert); systemd.network.enable = true; systemd.network.wait-online.enable = false; systemd.network.networks.eth = { diff --git a/egress.lua b/egress.lua new file mode 100644 index 0000000..a019d7a --- /dev/null +++ b/egress.lua @@ -0,0 +1,171 @@ +-- The guests' egress policy, for nginx (OpenResty), see host.nix. +-- +-- The rules (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/, +-- decrypted to check that +-- A domain with any whole-domain rule is passed through, whatever path +-- rules it has. Everything else gets denied. +-- +-- Upstream is always port 443 of the server name (SNI), as resolved by +-- the host, never the address the guest connected to. + +local _M = {} + +local RULES = os.getenv("FC_EGRESS_RULES") +local STATE = os.getenv("FC_EGRESS_STATE") -- ca.key, ca.pem +local DECRYPT = os.getenv("FC_EGRESS_DECRYPT") -- the http server's socket + +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 domains, paths = {}, {} + local f = io.open(RULES) + if not f then + return domains, paths + end + for line in f:lines() do + local domain, path = line:match("^%s*([^/%s]+)(/?%S*)%s*$") + if valid_name(domain) then + if path == "" then + domains[domain] = true + else + paths[domain] = paths[domain] or {} + table.insert(paths[domain], path) + end + end + end + f:close() + return domains, paths +end + +-- nil (deny), "pass", or the list of allowed path prefixes +local function policy(host) + host = host and host:lower() + if not valid_name(host) then + return nil + end + local domains, paths = rules() + local prefixes = {} + local suffix = host + while suffix do + if domains[suffix] then + return "pass" + end + for _, p in ipairs(paths[suffix] or {}) do + table.insert(prefixes, p) + end + suffix = suffix:match("^[^.]*%.(.+)$") + end + if #prefixes > 0 then + return prefixes + end +end + +-- stream, preread: pass through, decrypt, or close +function _M.preread() + local sni = ngx.var.ssl_preread_server_name + local p = policy(sni) + if p == "pass" then + ngx.var.egress_upstream = sni:lower() .. ":443" + ngx.var.egress_log = "ALLOW " .. sni:lower() + elseif p then + ngx.var.egress_upstream = "unix:" .. DECRYPT + else + ngx.var.egress_log = "DENY " .. (sni ~= "" and sni or "-") + return ngx.exit(403) + end +end + +-- http, ssl_certificate: a certificate for the server name, from our CA + +local ca_cert, ca_key, leaf_key, leaf_key_der +local certs = {} -- server name -> parsed certificate chain + +local function read(path) + local f = assert(io.open(path)) + local s = f:read("*a") + f:close() + return s +end + +local function make_cert(name) + local x509 = require("resty.openssl.x509") + local pkey = require("resty.openssl.pkey") + local bn = require("resty.openssl.bn") + local x509_name = require("resty.openssl.x509.name") + local altname = require("resty.openssl.x509.altname") + local extension = require("resty.openssl.x509.extension") + if not ca_cert then + ca_cert = assert(x509.new(read(STATE .. "/ca.pem"))) + ca_key = assert(pkey.new(read(STATE .. "/ca.key"))) + leaf_key = assert(pkey.new({ type = "EC", curve = "prime256v1" })) + leaf_key_der = assert(leaf_key:tostring("private", "DER")) + end + local serial = require("resty.string").to_hex(require("resty.random").bytes(16)) + local now = ngx.time() + local cert = x509.new() + assert(cert:set_version(3)) + assert(cert:set_serial_number(assert(bn.new(serial, 16)))) + assert(cert:set_not_before(now - 3600)) + assert(cert:set_not_after(now + 30 * 86400)) + assert(cert:set_subject_name(assert(x509_name.new():add("CN", name)))) + assert(cert:set_issuer_name(ca_cert:get_subject_name())) + assert(cert:set_pubkey(leaf_key)) + assert(cert:set_subject_alt_name(assert(altname.new():add("DNS", name)))) + assert(cert:set_basic_constraints({ CA = false })) + assert(cert:add_extension(assert(extension.new("extendedKeyUsage", "serverAuth")))) + assert(cert:sign(ca_key)) + return assert(require("ngx.ssl").parse_pem_cert(cert:to_PEM())) +end + +function _M.certificate() + local ssl = require("ngx.ssl") + local name = ssl.server_name() + if type(policy(name)) ~= "table" then + return ngx.exit(ngx.ERROR) + end + name = name:lower() + local chain = certs[name] + if not chain then + chain = make_cert(name) + certs[name] = chain + end + assert(ssl.clear_certs()) + assert(ssl.set_cert(chain)) + assert(ssl.set_der_priv_key(leaf_key_der)) +end + +-- http, access: check host and path of decrypted requests +function _M.access() + 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 ok = type(p) == "table" and host == sni and path:sub(1, 1) == "/" + if ok then + for segment in path:gmatch("[^/]+") do + if segment == "." or segment == ".." then + ok = false + end + end + end + if ok then + ok = false + for _, prefix in ipairs(p) do + if path:sub(1, #prefix) == prefix then + ok = true + end + end + end + ngx.var.egress_verdict = ok and "ALLOW" or "DENY" + if not ok then + return ngx.exit(403) + end +end + +return _M diff --git a/host.nix b/host.nix index 1907617..bdc69e8 100644 --- a/host.nix +++ b/host.nix @@ -1,6 +1,6 @@ # Host side of the guests' network: a bridge with tap devices fctap0, -# fctap1, ... owned by the user running the VMs, a DHCP server, and a -# transparent TLS proxy as the guests' only way out. Each running VM +# 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. # @@ -8,12 +8,13 @@ # 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 reads the server name (SNI) from the ClientHello, and if it's one -# of the domains (or their subdomains) listed in /var/lib/fc-egress/allowed, -# connects to port 443 of that name, as resolved by the host. The guests -# need no proxy settings, and they can only ever reach the real addresses -# of allowed names. The user can change the list at any time with -# fc-egress (see fc-egress help); nginx picks up changes right away. +# 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 default.nix) 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. # # usage (in the host's configuration.nix): # imports = [ (import ./host.nix { user = "tv"; }) ]; @@ -24,31 +25,32 @@ dir = "/var/lib/fc-egress"; allowed = "${dir}/allowed"; - # One domain per line. fc-egress validates what it adds, sniConfig - # skips lines that are no domains, as the file belongs to the user. - domainPattern = "[a-z0-9-]+(\\.[a-z0-9-]+)*"; + # Where nginx keeps the CA: ca.key, and ca.pem for the guests (see + # caCert in default.nix). + stateDir = "/var/lib/fcbr0-egress"; + runDir = "/run/fcbr0-egress"; fc-egress = pkgs.writeShellScriptBin "fc-egress" '' set -efu - export PATH=${lib.makeBinPath [ pkgs.bash pkgs.coreutils pkgs.gnugrep pkgs.gnused pkgs.systemd ]} + export PATH=${lib.makeBinPath [ pkgs.bash pkgs.coreutils pkgs.gnugrep pkgs.systemd ]} list=${allowed} usage() { echo "usage: fc-egress list" - echo " fc-egress allow DOMAIN..." - echo " fc-egress deny DOMAIN..." + echo " fc-egress allow RULE..." + echo " fc-egress deny RULE..." echo " fc-egress log [JOURNALCTL-OPTION...]" - echo "Allowing a domain allows its subdomains, too." + echo "RULE is DOMAIN (with subdomains, not decrypted)" + echo " or DOMAIN/PATH-PREFIX (decrypted to check the path)" } check() { - for d; do - case $d in - ""|.*|*.|*..*|*[!a-z0-9.-]*) - echo "fc-egress: bad domain: $d" >&2 - exit 1 - esac + for r; do + if ! printf %s "$r" | grep -qxE '[a-z0-9-]+(\.[a-z0-9-]+)*(/[A-Za-z0-9._~!$&()*+,;=:@%/-]*)?' || + printf %s "$r" | grep -qE '/\.\.?(/|$)'; then + echo "fc-egress: bad rule: $r" >&2 + exit 1 + fi done } - # Rewrite the list in place, as the path unit watches for writes. update() { tmp=$(mktemp) trap 'rm -f "$tmp"' EXIT @@ -70,9 +72,11 @@ update sh -c 'grep -vxF -e "$1" "$0" || :' "$list" "$(printf '%s\n' "$@")" ;; log) - # ALLOW|DENY, server name, guest, upstream, status, bytes sent and - # received (from the guest's view: received, sent), seconds - journalctl -u fcbr0-sni -o short-iso "$@" | grep --line-buffered -E ' (ALLOW|DENY) ' + # 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) ' ;; help|-h|--help) usage @@ -83,60 +87,100 @@ esac ''; - # Generates nginx's map of allowed names (".example.com" matches the - # domain and its subdomains) from the list, and its resolver from the - # host's resolv.conf (nginx can't use that itself). - sniConfig = pkgs.writeShellScript "fcbr0-sni-config" '' + # nginx's resolver from the host's resolv.conf (nginx can't use that + # itself), the CA on first start, and a certificate that nginx wants + # but never gets to use (egress.lua sets one for every connection). + egressSetup = pkgs.writeShellScript "fcbr0-egress-setup" '' set -efu - export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.gawk pkgs.gnugrep ]} - cd /run/fcbr0-sni - grep -xE '${domainPattern}' ${allowed} | - awk '{ printf ".%s $ssl_preread_server_name:443;\n", $1 }' > allowed.map.tmp || : - mv allowed.map.tmp allowed.map + export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.gawk pkgs.openssl ]} awk ' $1 == "nameserver" { s = s " " ($2 ~ /:/ ? "[" $2 "]" : $2) } END { - if (s == "") { print "fcbr0-sni-config: no nameserver in /etc/resolv.conf" > "/dev/stderr"; exit 1 } + if (s == "") { print "fcbr0-egress-setup: no nameserver in /etc/resolv.conf" > "/dev/stderr"; exit 1 } print "resolver" s " ipv6=off;" } - ' /etc/resolv.conf > resolver.conf + ' /etc/resolv.conf > ${runDir}/resolver.conf + cd ${stateDir} + if ! test -e ca.key; then + openssl req -x509 -new -newkey rsa:2048 -nodes -days 3650 \ + -subj /CN=fc-egress -keyout ca.key.tmp -out ca.crt \ + -addext basicConstraints=critical,CA:TRUE \ + -addext keyUsage=critical,keyCertSign,cRLSign 2>/dev/null + mv ca.key.tmp ca.key + fi + install -m 644 ca.crt ca.pem + cd ${runDir} + 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 ''; - # Connections without an allowed server name go to the deny server, - # which closes them right away. That makes nginx log an error about the - # reset connection, so errors only get logged from crit up: what went - # wrong also shows in the access log, as $status (502: couldn't connect, - # 500: couldn't resolve, ...). - nginxConfig = pkgs.writeText "fcbr0-sni.conf" '' + egressLua = pkgs.writeTextDir "egress.lua" (builtins.readFile ./egress.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 + # 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 + # is what egress.lua checks. + nginxConfig = pkgs.writeText "fcbr0-egress.conf" '' daemon off; - pid /run/fcbr0-sni/nginx.pid; - error_log stderr crit; + pid ${runDir}/nginx.pid; + error_log stderr warn; worker_processes 1; + env FC_EGRESS_RULES=${allowed}; + env FC_EGRESS_STATE=${stateDir}; + env FC_EGRESS_DECRYPT=${runDir}/decrypt.sock; events {} + stream { - include /run/fcbr0-sni/resolver.conf; - log_format egress '$egress_verdict $ssl_preread_server_name $remote_addr $upstream_addr $status $bytes_sent $bytes_received $session_time'; - access_log syslog:server=unix:/dev/log,nohostname,tag=fcbr0_sni egress; - - map $ssl_preread_server_name $egress_upstream { - hostnames; - default unix:/run/fcbr0-sni/deny.sock; - include /run/fcbr0-sni/allowed.map; - } - map $egress_upstream $egress_verdict { - unix:/run/fcbr0-sni/deny.sock DENY; - default ALLOW; - } + lua_package_path "${egressLua}/?.lua;;"; + include ${runDir}/resolver.conf; + 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; server { listen 172.16.0.1:${toString proxyPort}; ssl_preread on; + set $egress_upstream ""; + set $egress_log ""; + preread_by_lua_block { require("egress").preread() } proxy_pass $egress_upstream; } + } + + http { + lua_package_path "${egressLua}/?.lua;;"; + include ${runDir}/resolver.conf; + log_format egress '$egress_verdict $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:/run/fcbr0-sni/deny.sock; - access_log off; - return ""; + listen unix:${runDir}/decrypt.sock ssl; + 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 ""; + + location / { + access_by_lua_block { require("egress").access() } + proxy_pass https://$ssl_server_name; + proxy_ssl_server_name on; + proxy_ssl_name $ssl_server_name; + proxy_ssl_verify on; + proxy_ssl_verify_depth 4; + proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header Connection ""; + proxy_buffering off; + proxy_request_buffering off; + } } } ''; @@ -150,7 +194,7 @@ in { }; networking.bridges.fcbr0.interfaces = tapNames; # 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 before. (Unused + # i.e. while a VM runs, so nginx couldn't bind to it. (Unused # with scripted networking, which assigns it regardless.) systemd.network.networks."40-fcbr0".networkConfig.ConfigureWithoutCarrier = true; @@ -208,35 +252,34 @@ in { "f ${allowed} 0644 ${user} - -" ]; + # 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). # nginx binds to 172.16.0.1, so it has to wait for fcbr0's address # (network-addresses-fcbr0.service with scripted networking; with # networkd, nothing to order after, so it keeps restarting, without start - # limit, until the address is there). On reload, sniConfig regenerates the map and - # nginx re-reads its config on SIGHUP; if that fails, it keeps the old. - systemd.services.fcbr0-sni = { + # limit, until the address is there). + users.users.fcbr0-egress = { + isSystemUser = true; + group = "fcbr0-egress"; + }; + users.groups.fcbr0-egress = { }; + systemd.services.fcbr0-egress = { wantedBy = [ "multi-user.target" ]; startLimitIntervalSec = 0; after = [ "network.target" "network-addresses-fcbr0.service" "systemd-tmpfiles-setup.service" ]; serviceConfig = { - ExecStartPre = sniConfig; - ExecStart = "${pkgs.nginx}/bin/nginx -e stderr -p /run/fcbr0-sni -c ${nginxConfig}"; - ExecReload = [ sniConfig "${pkgs.coreutils}/bin/kill -HUP $MAINPID" ]; - DynamicUser = true; - AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ]; - RuntimeDirectory = "fcbr0-sni"; - Restart = "on-failure"; + ExecStartPre = egressSetup; + ExecStart = "${pkgs.openresty}/bin/nginx -e stderr -p ${runDir} -c ${nginxConfig}"; + User = "fcbr0-egress"; + Group = "fcbr0-egress"; + StateDirectory = "fcbr0-egress"; + StateDirectoryMode = "0755"; + RuntimeDirectory = "fcbr0-egress"; + UMask = "0077"; + Restart = "always"; RestartSec = 1; }; }; - systemd.paths.fcbr0-sni-reload = { - wantedBy = [ "multi-user.target" ]; - pathConfig.PathChanged = allowed; - }; - systemd.services.fcbr0-sni-reload = { - serviceConfig.Type = "oneshot"; - serviceConfig.ExecStart = "${pkgs.systemd}/bin/systemctl try-reload-or-restart fcbr0-sni.service"; - }; - environment.systemPackages = [ fc-egress ]; } -- cgit v1.3.1