aboutsummaryrefslogtreecommitdiffstats
path: root/modules/host/default.nix
blob: e2421c05343edc5f55f0bb31d6fe1902d0a619a1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
# Host side of the guests' network: a bridge with tap devices fctap0,
# 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.
#
# 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.
#
# 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.
#
# 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.
#
# 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).
{ 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";
  userNames = lib.attrNames users;
  ipsOf = user: map (t: t.ip) (lib.filter (t: t.user == user) taps);

  # 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 each user's tcp:// and udp:// rules into their nftables set, one
  # user at a time, so one user's bad rule doesn't keep the others' out.
  firewallUpdate = pkgs.writeShellScript "fcbr0-firewall-update" ''
    set -fu
    export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.gnugrep pkgs.gnused pkgs.nftables ]}
    status=0
    for user in ${lib.escapeShellArgs userNames}; do
      elements=$(grep -xE '${portRule}' ${dir}/$user/allowed 2>/dev/null |
        sed -E 's#^(tcp|udp)://([^:]+):(.*)$#\2 . \1 . \3#' | paste -sd,)
      {
        echo "flush set inet firecracker allow_$user"
        if test -n "$elements"; then
          echo "add element inet firecracker allow_$user { $elements }"
        fi
      } | nft -f - || { echo "fcbr0-firewall: rules of $user not applied" >&2; status=1; }
    done
    exit $status
  '';

  # Where nginx keeps the CA: ca.key, and ca.pem for the guests (see
  # caCert in pkgs/run-firecracker-vm).
  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.gawk pkgs.gnugrep pkgs.systemd ]}
    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..."
      echo "       fc-egress deny RULE..."
      echo "       fc-egress log [JOURNALCTL-OPTION...]"
      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://...)"
    }
    check() {
      for r; do
        if printf %s "$r" | grep -qxE '${portRule}'; then
          # numbers in range: address bytes, prefix length, ports
          if printf %s "$r" | awk '{
              s = $0; sub(/^[a-z]+:\/\//, "", s)
              split(s, hp, ":"); split(hp[1], a, "/"); split(a[1], b, ".")
              for (i = 1; i <= 4; i++) if (b[i] > 255) exit 1
              if (a[2] != "" && a[2] > 32) exit 1
              n = split(hp[2], p, "-")
              for (i = 1; i <= n; i++) if (p[i] < 1 || p[i] > 65535) exit 1
              if (n == 2 && p[1] > p[2]) exit 1
            }'; then
            continue
          fi
          echo "fc-egress: bad rule: $r" >&2
          exit 1
        fi
        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
    }
    update() {
      tmp=$(mktemp)
      trap 'rm -f "$tmp"' EXIT
      "$@" > "$tmp"
      cat "$tmp" > "$list"
    }
    cmd=''${1-help}
    shift || :
    case $cmd in
      list)
        cat "$list"
        ;;
      allow)
        check "$@"
        update sh -c '{ cat "$0"; printf "%s\n" "$@"; } | sort -u' "$list" "$@"
        ;;
      deny)
        check "$@"
        update sh -c 'grep -vxF -e "$1" "$0" || :' "$list" "$(printf '%s\n' "$@")"
        ;;
      log)
        # 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
        ;;
      *)
        usage >&2
        exit 1
    esac
  '';

  # 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.openssl ]}
    awk '
      $1 == "nameserver" { s = s " " ($2 ~ /:/ ? "[" $2 "]" : $2) }
      END {
        if (s == "") { print "fcbr0-egress-setup: no nameserver in /etc/resolv.conf" > "/dev/stderr"; exit 1 }
        print "resolver" s " ipv6=off;"
      }
    ' /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}
    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
  '';

  # 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 (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
  # is what egress.lua checks.
  nginxConfig = pkgs.writeText "fcbr0-egress.conf" ''
    daemon off;
    pid ${runDir}/nginx.pid;
    error_log stderr warn;
    worker_processes 1;
    env FC_EGRESS_RULES=${dir};
    env FC_EGRESS_STATE=${stateDir};
    env FC_EGRESS_RUN=${runDir};
    events {}

    stream {
      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 $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 {
${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() }
          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;
          # Room for big response headers (github.com's are over 8k); the
          # other two only have to fit with it.
          proxy_buffer_size 64k;
          proxy_buffers 4 64k;
          proxy_busy_buffers_size 128k;
        }
      }
    }
  '';
in {
  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 = t.user;
  }) taps) // {
    fcbr0.ipv4.addresses = [{ address = "172.16.0.1"; prefixLength = 24; }];
  };
  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.)
  systemd.network.networks."40-fcbr0".networkConfig.ConfigureWithoutCarrier = true;

  # 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).  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 other (bridge).  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;
  networking.nftables.tables.firecracker = {
    family = "inet";
    content = ''
${lib.concatMapStrings (u: ''
      set allow_${u} {
        type ipv4_addr . inet_proto . inet_service
        flags interval
      }
'') userNames}
      # Before the host's own NAT rules (which are for connections to the
      # host, like a redirect of some port to its sshd), so they don't get
      # applied to the guests' connections: the first NAT a connection gets
      # is the only one, so everything else gets a NAT that changes
      # nothing.
      chain prerouting {
        type nat hook prerouting priority dstnat - 1;
        iifname "fcbr0" tcp dport 443 redirect to :${toString proxyPort}
        iifname "fcbr0" meta nfproto ipv4 meta l4proto { tcp, udp } dnat ip to ip daddr
      }

      chain postrouting {
        type nat hook postrouting priority srcnat - 1;
        iifname "fcbr0" masquerade
      }

      chain input {
        type filter hook input priority filter; policy accept;
        iifname != "fcbr0" accept
        ct state { established, related } accept
        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
        jump users
        reject with icmpx admin-prohibited
      }

      chain forward {
        type filter hook forward priority filter; policy accept;
        iifname != "fcbr0" accept
        ct state { established, related } accept
        jump users
        reject with icmpx admin-prohibited
      }

      chain users {
${lib.concatMapStrings (u: "        ip saddr { ${lib.concatStringsSep ", " (ipsOf u)} } ip daddr . meta l4proto . th dport @allow_${u} accept\n") userNames}      }
    '';
  };
  # 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
      }
    '';
  };

  # A dnsmasq of its own, so it doesn't get mixed up with one the host might
  # 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
  # resolver the host runs there); bind-dynamic copes with fcbr0 not being
  # there yet.
  systemd.services.fcbr0-dnsmasq = {
    wantedBy = [ "multi-user.target" ];
    after = [ "network.target" ];
    serviceConfig = {
      RuntimeDirectory = "fcbr0-dnsmasq";
      Restart = "on-failure";
      ExecStart = lib.escapeShellArgs ([
        "${pkgs.dnsmasq}/bin/dnsmasq"
        "--keep-in-foreground"
        "--conf-file=/dev/null"
        "--bind-dynamic"
        "--interface=fcbr0"
        "--except-interface=lo"
        "--dhcp-authoritative"
        "--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);
    };
  };

  # 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);

  # Forwarding, for the tcp:// and udp:// rules.
  boot.kernel.sysctl."net.ipv4.ip_forward" = 1;

  # Fills the allow_USER sets: at start, whenever nftables gets reloaded
  # (which empties them), and whenever a user's rules change.
  systemd.services.fcbr0-firewall = {
    wantedBy = [ "multi-user.target" ];
    after = [ "nftables.service" "systemd-tmpfiles-setup.service" ];
    partOf = [ "nftables.service" ];
    unitConfig.ReloadPropagatedFrom = "nftables.service";
    serviceConfig = {
      Type = "oneshot";
      RemainAfterExit = true;
      ExecStart = firewallUpdate;
      ExecReload = firewallUpdate;
    };
  };
  systemd.paths.fcbr0-firewall = {
    wantedBy = [ "multi-user.target" ];
    pathConfig.PathChanged = map (u: "${dir}/${u}/allowed") userNames;
    pathConfig.Unit = "fcbr0-firewall-reload.service";
  };
  systemd.services.fcbr0-firewall-reload = {
    serviceConfig.Type = "oneshot";
    serviceConfig.ExecStart = "${pkgs.systemd}/bin/systemctl try-reload-or-restart fcbr0-firewall.service";
  };

  # 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).
  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 = 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;
    };
  };

  environment.systemPackages = [ fc-egress ];
}