aboutsummaryrefslogtreecommitdiffstats
path: root/modules/host/default.nix
blob: 6e202192dc7e5810234cb8b29def9cd2c315a801 (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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
# 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.
#
# Addresses are the VMs' (see vms below), not the taps': a VM takes any of
# its user's taps, and gets its address there.  dnsmasq hands out every
# address by MAC address (06:00 and the address, which the run script
# gives the guest, see /etc/fc-vms and /etc/fc-taps), and the bridge drops
# anything coming from a tap with another source address than its VM's,
# so a guest's address says which VM, and whose, it is.  Which address a
# tap has is up to fcbr0-firewall (see firewallUpdate): the VM's, by its
# name (/run/fc-egress/TAP.name, see below) and the tap's user, or, for a
# VM without a name in vms, the tap's own.  It puts the addresses into
# the tap's nftables sets, in both the bridge's table and the other, and
# into /run/fcbr0-addr (TAP: its address, ADDRESS: its tap), for nginx
# and the run script.
#
# 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 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.
#
# 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: the VM's name
# (--name), or "default") and
# empties when the VM exits.  No list, or one that doesn't exist, allows
# nothing.  Likewise /run/fc-egress/TAP.name, the VM's name (--name), for
# its address (see above), and so fc-egress can take names instead of
# taps.
#
# 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 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; }; }) ];
#
# VMs get static addresses by name and user (vms = { hermes = { user =
# "tv"; ip = "172.16.0.2"; }; }), any number of them, whichever tap they
# run on, e.g. for the host to reach them with a reverse proxy.  The
# addresses are also in config.fc.vms.NAME (user, ip, ip6), e.g.
#   proxyPass = "http://${config.fc.vms.hermes.ip}:9120";
# 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), 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
  # IPv4.
, prefix6 ? "fdfc:fc::"
  # 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 ? [
    "0.0.0.0/8" "10.0.0.0/8" "100.64.0.0/10" "127.0.0.0/8"
    "169.254.0.0/16" "172.16.0.0/12" "192.168.0.0/16" "224.0.0.0/3"
    "::/127" "::ffff:0:0/96" "fc00::/7" "fe80::/10" "ff00::/8"
  ]
  # Limits per guest: open connections, and new connections per second.
, maxConnections ? 256
, maxNewConnections ? 50
}: { lib, pkgs, ... }: let
  # An address, with what goes with it: { ip = "172.16.0.N"; ip6 = ...;
  # ll6 = ...; mac = ...; }.  The MAC is 06:00 and the address (ac:10:00:NN),
  # the IPv6 addresses are from the MAC (SLAAC with EUI-64).
  address = ip: let
    hex = n: lib.fixedWidthString 2 "0" (lib.toLower (lib.toHexString n));
    m = builtins.match "172\\.16\\.0\\.([0-9]+)" ip;
    n = if m == null then 0 else lib.toInt (lib.head m);  # see assertions
    # The EUI-64 interface ID of the MAC (in the canonical form, as nft
    # and nginx print addresses).
    eui64 = "400:acff:fe10:${lib.toLower (lib.toHexString n)}";
  in {
    inherit ip;
    ip6 = "${prefix6}${eui64}";
    ll6 = "fe80::${eui64}";
    mac = "06:00:ac:10:00:${hex n}";
  };
  # [ { vm = "hermes"; user = ...; ip = ...; ip6 = ...; ll6 = ...;
  #     mac = ...; } ... ]
  vmList = lib.mapAttrsToList (vm: v: { inherit vm; inherit (v) user; } // address v.ip) vms;
  # [ { name = "fctap0"; user = ...; ip = ...; ip6 = ...; ll6 = ...;
  #     mac = ...; } ... ]: each user's taps, in order, with their own
  # addresses, for VMs without one in vms: from 172.16.0.200 on, so they
  # stand out, those that aren't any VM's, in order.
  tapsFrom = 200;
  taps = let
    free = lib.filter (ip: !lib.elem ip (map (v: v.ip) vmList))
      (lib.genList (k: "172.16.0.${toString (k + tapsFrom)}") (255 - tapsFrom));
    userTaps = lib.concatMap (u: lib.genList (_: u) users.${u}) userNames;
  in lib.imap0 (i: user: {
    name = "fctap${toString i}";
    inherit user;
  } // address (if i < lib.length free then lib.elemAt free i else "172.16.0.0")) userTaps;  # see assertions
  # Everyone's addresses: taps' and VMs'.
  addresses = taps ++ vmList;
  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_-]+";
  # VM names (run-firecracker-vm --name, also the guest's host name):
  # /run/fc-egress/TAP.name, for fc-egress.
  vmName = "[A-Za-z0-9][A-Za-z0-9-]{0,62}";
  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;
  tapsOf = user: lib.filter (t: t.user == user) taps;
  ipsOf = user: map (a: a.ip) (lib.filter (a: a.user == user) addresses);

  # For the run script: the taps' own addresses, TAP USER IP MAC, and the
  # VMs', VM USER IP MAC, a line each.
  tapsFile = "/etc/fc-taps";
  vmsFile = "/etc/fc-vms";
  # Which address each tap has, and which tap each address: TAP: ADDRESS,
  # ADDRESS: TAP, written by fcbr0-firewall (see firewallUpdate).
  addrDir = "/run/fcbr0-addr";

  # tcp://ADDRESS[/PREFIXLEN]:PORT[-PORT], tcp://[ADDRESS6[/PREFIXLEN]]:...,
  # tcp://NAME:PORT[-PORT], or udp://...  (nft checks the numbers.)
  addressRule = "[0-9]+(\\.[0-9]+){3}(/[0-9]+)?";
  address6Rule = "\\[[0-9A-Fa-f:]+(/[0-9]+)?\\]";
  hostName = "[A-Za-z0-9][A-Za-z0-9-]*(\\.[A-Za-z0-9-]+)*";
  portRule = "(tcp|udp)://(${addressRule}|${address6Rule}|${hostName}):[0-9]+(-[0-9]+)?";

  # The addresses of the names in the tcp:// and udp:// rules, as the
  # firewall update resolves them, a hosts file per tap, for the guests'
  # dnsmasq, so a guest connects to the addresses the rules allow.
  hostsDir = "/run/fcbr0-hosts";
  # How often the names get resolved again.
  refreshInterval = "5min";

  # For the given taps (default: all; a user's name means all of their
  # taps), one tap at a time: puts the address of the tap's VM (see the
  # top) into the tap's nftables sets addr_TAP and addr6_TAP, and into
  # addrDir; and puts the tcp:// and udp:// rules of the tap's VM into the
  # tap's nftables sets allow_TAP and allow6_TAP, so one bad rule doesn't
  # keep the others' out, with names resolved by the host (IPv4 and IPv6;
  # a name that doesn't resolve allows nothing), and those names'
  # addresses into the taps' hosts files.  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.gawk pkgs.getent pkgs.gnugrep pkgs.nftables ]}
    # first line of a file, at most 256 bytes, or nothing
    line() {
      head -c 256 "$1" 2>/dev/null | head -n 1 || :
    }
    status=0
    if test $# = 0; then
      set -- ${lib.escapeShellArgs (map (t: t.name) taps)}
    fi
    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} ip=${t.ip} ip6=${t.ip6} ll6=${t.ll6} others=\"${lib.concatMapStringsSep " " (o: o.name) (lib.filter (o: o.name != t.name) (tapsOf t.user))}\" ;;\n") taps}        *) echo "fcbr0-firewall: no tap $tap" >&2; status=1; continue
      esac

      # The tap's address: its own, unless its VM's name is one of the
      # user's VMs', and none of the user's other taps has a VM of that
      # name, too: then the VM's, or with another, none.
      name=$(line ${vmDir}/$tap.name)
      vip=
      if printf %s "$name" | grep -qxE '${vmName}'; then
        case "$user $name" in
${lib.concatMapStrings (v: "          \"${v.user} ${v.vm}\") vip=${v.ip} vip6=${v.ip6} vll6=${v.ll6} ;;\n") vmList}        esac
      fi
      if test -n "$vip"; then
        ip=$vip ip6=$vip6 ll6=$vll6
        for t in $others; do
          if test "$(line ${vmDir}/$t.name)" = "$name"; then
            echo "fcbr0-firewall: $tap: $user's VM $name is on $t, too: no address" >&2
            ip= ip6= ll6=
            status=1
          fi
        done
      fi
      {
        for table in "inet firecracker" "bridge firecracker-bridge"; do
          echo "flush set $table addr_$tap"
          echo "flush set $table addr6_$tap"
        done
        if test -n "$ip"; then
          echo "add element inet firecracker addr_$tap { $ip }"
          echo "add element inet firecracker addr6_$tap { $ip6 }"
          echo "add element bridge firecracker-bridge addr_$tap { $ip }"
          echo "add element bridge firecracker-bridge addr6_$tap { $ip6, $ll6 }"
        fi
      } | nft -f - || { echo "fcbr0-firewall: address of $tap ($user: ''${name:--}) not applied" >&2; status=1; continue; }
      # The address's tap first, then the tap's address, which the run
      # script waits for.  An address's file that names another tap is
      # stale (that tap's own file says).
      old=$(line ${addrDir}/$tap)
      if test -n "$old" && test "$old" != "$ip" && test "$(line ${addrDir}/$old)" = "$tap"; then
        rm -f ${addrDir}/$old
      fi
      if test -n "$ip"; then
        printf '%s\n' "$tap" > ${addrDir}/.$ip
        mv ${addrDir}/.$ip ${addrDir}/$ip
      fi
      printf '%s\n' "$ip" > ${addrDir}/.$tap
      mv ${addrDir}/.$tap ${addrDir}/$tap

      list=$(line ${vmDir}/$tap)
      file=${dir}/$user/$list
      rules=
      if printf %s "$list" | grep -qxE '${listName}' && test -f "$file" && ! test -L "$file"; then
        rules=$(head -c ${toString maxRulesSize} "$file" | grep -xE '${portRule}') || :
      fi
      elements=
      elements6=
      hosts=
      for rule in $rules; do
        proto=''${rule%%://*}
        rest=''${rule#*://}
        host=''${rest%:*}
        ports=''${rest##*:}
        if printf %s "$host" | grep -qxE '${addressRule}|${address6Rule}'; then
          addresses=$host
        else
          addresses=$(timeout 5 getent ahosts "$host" | awk '{ print $1 }' | sort -u) || :
          for a in $addresses; do
            hosts="$hosts$a $host"$'\n'
          done
        fi
        for a in $addresses; do
          case $a in
            *:*) a=''${a#[}; elements6="$elements6''${elements6:+, }''${a%]} . $proto . $ports" ;;
            *) elements="$elements''${elements:+, }$a . $proto . $ports"
          esac
        done
      done
      {
        echo "flush set inet firecracker allow_$tap"
        echo "flush set inet firecracker allow6_$tap"
        if test -n "$elements"; then
          echo "add element inet firecracker allow_$tap { $elements }"
        fi
        if test -n "$elements6"; then
          echo "add element inet firecracker allow6_$tap { $elements6 }"
        fi
      } | nft -f - || { echo "fcbr0-firewall: rules of $tap ($user: $list) not applied" >&2; status=1; continue; }
      # dnsmasq reads new and changed files, but not dot files.
      printf %s "$hosts" | sort -u > ${hostsDir}/.$tap
      mv ${hostsDir}/.$tap ${hostsDir}/$tap
    done
    exit $status
  '';

  # Each connection a guest makes through nginx takes up to 5 of its
  # connections (decrypted ones: guest, stream, Unix socket both ways,
  # upstream).
  workerConnections = 5 * maxConnections * lib.length taps + 1024;

  # How fcbr0-firewall runs: not as root, users' files are input.  A user
  # of its own (not DynamicUser), for the hosts files and addrDir.
  firewallService = {
    Type = "oneshot";
    User = "fcbr0-firewall";
    Group = "fcbr0-firewall";
    AmbientCapabilities = [ "CAP_NET_ADMIN" ];
    CapabilityBoundingSet = [ "CAP_NET_ADMIN" ];
    NoNewPrivileges = true;
    ProtectSystem = "strict";
    ProtectHome = true;
    PrivateTmp = true;
    ReadWritePaths = [ hostsDir addrDir ];
    RestrictAddressFamilies = [ "AF_NETLINK" "AF_UNIX" "AF_INET" "AF_INET6" ];  # nft, resolving
  };

  # 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.findutils pkgs.gawk pkgs.gnugrep pkgs.gnused pkgs.systemd ]}
    user=$(id -un)
    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 [-l LIST | -v VM] list"
      echo "       fc-egress [-l LIST | -v VM] allow RULE..."
      echo "       fc-egress [-l LIST | -v VM] deny RULE..."
      echo "       fc-egress lists"
      echo "       fc-egress vms"
      echo "       fc-egress use VM LIST"
      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: its --name,"
      echo "     or default)"
      echo "VM is a running VM's name (run-firecracker-vm --name) or tap;"
      echo "     -v VM means the list it uses"
      echo "RULE is https://DOMAIN (with subdomains, not decrypted)"
      echo "     or https://DOMAIN/PATH (decrypted to check the path: PATH itself,"
      echo "     and below it, PATH/..., with any query; with PATH ending in /,"
      echo "     whatever starts with it)"
      echo "     or tcp://ADDRESS[/PREFIXLEN]:PORT[-PORT] (likewise udp://...)"
      echo "     or tcp://[ADDRESS6[/PREFIXLEN]]:PORT[-PORT] (IPv6, not port 443)"
      echo "     or tcp://NAME:PORT[-PORT] (resolved by the host)"
      echo "vms shows the running VMs' taps (as in the log), addresses, names"
      echo "     and lists"
      echo "use switches a running VM to another list"
    }
    # the tap of a running VM of the user's, by name or tap
    tap_of() {
      for f in $(find ${vmDir} -mindepth 1 -maxdepth 1 -user "$user" -size +0 -name 'fctap*' ! -name '*.*' -printf '%f\n'); do
        if test "$f" = "$1" || test "$(head -n 1 ${vmDir}/$f.name 2>/dev/null)" = "$1"; then
          echo "$f"
          return
        fi
      done
      echo "fc-egress: no running VM $1 of $user's" >&2
      exit 1
    }
    name=default
    case ''${1-} in
      -l)
        name=''${2-}
        shift 2 || :
        ;;
      -v)
        tap=$(tap_of "''${2-}")
        name=$(head -n 1 ${vmDir}/$tap)
        shift 2
    esac
    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
          # numbers in range: address bytes, prefix length, ports (IPv6
          # addresses: nft)
          if printf %s "$r" | awk '{
              s = $0; sub(/^[a-z]+:\/\//, "", s)
              match(s, /:[0-9-]+$/); host = substr(s, 1, RSTART - 1); ports = substr(s, RSTART + 1)
              split(host, a, "/"); split(a[1], b, ".")
              if (host ~ /^\[/) {
                sub(/\]$/, "", a[2])
                if (a[2] != "" && a[2] > 128) exit 1
              } else if (host ~ /^[0-9.\/]+$/) {
                for (i = 1; i <= 4; i++) if (b[i] > 255) exit 1
                if (a[2] != "" && a[2] > 32) exit 1
              } else if (length(host) > 253) exit 1
              n = split(ports, 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 'https://[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"
      chmod 644 "$list"
    }
    cmd=''${1-help}
    shift || :
    case $cmd in
      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 -name 'fctap*' ! -name '*.*' -printf '%f\n' | sort -V |
          while read -r tap; do
            vm=$(head -n 1 ${vmDir}/$tap.name 2>/dev/null) || :
            ip=$(head -n 1 ${addrDir}/$tap 2>/dev/null) || :
            printf '%s %s %s %s\n' "$tap" "$ip" "''${vm:--}" "$(head -n 1 ${vmDir}/$tap)"
          done
        ;;
      use)
        if test $# != 2; then usage >&2; exit 1; fi
        tap=$(tap_of "$1")
        if ! printf %s "$2" | grep -qxE '${listName}'; then
          echo "fc-egress: bad list name: $2" >&2
          exit 1
        fi
        if ! test -f ${dir}/$user/"$2"; then
          echo "fc-egress: no list $2, $1 gets no egress" >&2
        fi
        printf '%s\n' "$2" > ${vmDir}/$tap
        ;;
      log)
        # HTTPS connections: ALLOW|DENY, user, tap, list, https://SERVER,
        # guest, upstream, status, bytes sent and received (from the guest's
        # view: received, sent), seconds.  Decrypted requests: ALLOW|DENY,
        # user, tap, list, method, https://HOST/URI, status, bytes sent.
        # Other connections (kernel log, rate-limited): fc-egress
        # ALLOW|DENY, user, tap, tcp://DST:DPT (or udp://; added here), and
        # the packet.  The URIs are as rules take them, for copying.
        journalctl -o short-iso _SYSTEMD_UNIT=fcbr0-egress.service + _TRANSPORT=kernel "$@" |
          grep --line-buffered -E " (ALLOW|DENY) $user " |
          sed -u -E \
            -e 's/( fc-egress (ALLOW|DENY) [^ ]+ [^ ]+ )(.* DST=([0-9.]+) .*PROTO=(TCP|UDP) .*DPT=([0-9]+).*)$/\1\L\5\E:\/\/\4:\6 \3/' \
            -e 's/( fc-egress (ALLOW|DENY) [^ ]+ [^ ]+ )(.* DST=([0-9a-f:]+) .*PROTO=(TCP|UDP) .*DPT=([0-9]+).*)$/\1\L\5\E:\/\/[\4]:\6 \3/'
        ;;
      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 " " (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 whose each guest address and each tap is (which tap an
  # address is on is in addrDir).
  egressLua = pkgs.runCommand "egress-lua" {
    guests = "return {\n  addresses = {\n"
      + 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" ];
  } ''
    mkdir $out
    cp ${./egress.lua} $out/egress.lua
    cp $guestsPath $out/egress_guests.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 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
  # 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;
    worker_rlimit_nofile ${toString (workerConnections + 1024)};
    env FC_EGRESS_RULES=${dir};
    env FC_EGRESS_STATE=${stateDir};
    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};
    }

    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;

      # 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.
${lib.concatMapStrings (u: ''
      map $remote_addr $egress_limit_${u} {
${lib.concatMapStrings (ip: "        ${ip} 1;\n") (ipsOf u)}        default "";
      }
      limit_conn_zone $egress_limit_${u} zone=user_${u}:64k;
'') userNames}
      server {
        listen 172.16.0.1:${toString proxyPort};
${lib.concatMapStrings (u: "        limit_conn user_${u} ${toString (users.${u} * maxConnections)};\n") userNames}
        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_guest $request_method https://$host$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 (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_guest "";

        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;
        }
      }

      # 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 {
  imports = [{
    options.fc.vms = lib.mkOption {
      type = lib.types.attrsOf (lib.types.attrsOf lib.types.str);
      default = lib.listToAttrs (map (v: lib.nameValuePair v.vm {
        inherit (v) user ip ip6;
      }) vmList);
      readOnly = true;
      description = "The VMs' addresses (see vms), by VM name: user, ip, ip6.";
    };
  }];

  assertions = [{
    assertion = lib.length taps + lib.length (lib.filter (v: lib.toInt (lib.last (lib.splitString "." v.ip)) >= tapsFrom) vmList) <= 255 - tapsFrom;
    message = "modules/host: the taps' own addresses (172.16.0.${toString tapsFrom} to .254, but for vms') aren't enough for ${toString (lib.length taps)} taps";
  }] ++ lib.concatLists (lib.mapAttrsToList (vm: v: [
    {
      assertion = builtins.match vmName vm != null;
      message = "modules/host: vms.${vm}: not a VM name";
    }
    {
      assertion = users ? ${v.user};
      message = "modules/host: vms.${vm}: ${v.user} isn't in users";
    }
    {
      assertion = builtins.match "172\\.16\\.0\\.([2-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])" v.ip != null;
      message = "modules/host: vms.${vm}: ${v.ip} isn't 172.16.0.2 to .254";
    }
    {
      assertion = lib.length (lib.filter (w: w.ip == v.ip) (lib.attrValues vms)) == 1;
      message = "modules/host: vms.${vm}: ${v.ip} is another VM's, too";
    }
  ]) vms);

  environment.etc.${lib.removePrefix "/etc/" tapsFile}.text =
    lib.concatMapStrings (t: "${t.name} ${t.user} ${t.ip} ${t.mac}\n") taps;
  environment.etc.${lib.removePrefix "/etc/" vmsFile}.text =
    lib.concatMapStrings (v: "${v.vm} ${v.user} ${v.ip} ${v.mac}\n") vmList;

  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; }];
    fcbr0.ipv6.addresses = [{ address = "${prefix6}1"; prefixLength = 64; }];
  };
  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), 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
  # name, or at any other of its addresses) nor through it, nor to each
  # other (bridge).  nginx itself (chain output) may only reach port 443
  # 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 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;
  # The build's ruleset check runs where fcbr0-egress doesn't exist.
  networking.nftables.preCheckRuleset = ''
    sed -i 's/skuid "fcbr0-egress"/skuid 0/' ruleset.conf
  '';
  networking.nftables.tables.firecracker = {
    family = "inet";
    content = ''
${lib.concatMapStrings (t: ''
      set allow_${t.name} {
        type ipv4_addr . inet_proto . inet_service
        flags interval
      }

      set allow6_${t.name} {
        type ipv6_addr . inet_proto . inet_service
        flags interval
      }

      # The tap's VM's address (see firewallUpdate).
      set addr_${t.name} {
        type ipv4_addr
      }

      set addr6_${t.name} {
        type ipv6_addr
      }
'') taps}
      set deny4 {
        type ipv4_addr
        flags interval
        ${lib.optionalString (deny4 != [ ]) "elements = { ${lib.concatStringsSep ", " deny4} }"}
      }

      set deny6 {
        type ipv6_addr
        flags interval
        ${lib.optionalString (deny6 != [ ]) "elements = { ${lib.concatStringsSep ", " deny6} }"}
      }

      set guest_conns {
        type ipv4_addr
        flags dynamic
        size 1024
      }

      set guest_rate {
        type ipv4_addr
        flags dynamic, timeout
        timeout 1m
        size 1024
      }

      set guest_conns6 {
        type ipv6_addr
        flags dynamic
        size 1024
      }

      set guest_rate6 {
        type ipv6_addr
        flags dynamic, timeout
        timeout 1m
        size 1024
      }

      # 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" 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
      }

      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
        # IPv6 neighbour and router discovery (dnsmasq sends the RAs)
        icmpv6 type { nd-router-solicit, nd-neighbor-solicit, nd-neighbor-advert, mld2-listener-report } accept
        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}, ${toString checkPort} } accept
        jump refused
      }

      chain forward {
        type filter hook forward priority filter; policy accept;
        iifname != "fcbr0" accept
        ct state { established, related } accept
        jump limits
        ip daddr @deny4 jump refused
        ip6 daddr @deny6 jump refused
        # HTTPS goes via nginx, which is IPv4 only (see prerouting).
        meta nfproto ipv6 tcp dport 443 jump refused
        jump vms
        jump refused
      }

      chain limits {
        ct state new add @guest_conns { ip saddr ct count over ${toString maxConnections} } reject with icmpx admin-prohibited
        ct state new update @guest_rate { ip saddr limit rate over ${toString maxNewConnections}/second burst ${toString (2 * maxNewConnections)} packets } reject with icmpx admin-prohibited
        ct state new add @guest_conns6 { ip6 saddr ct count over ${toString maxConnections} } reject with icmpx admin-prohibited
        ct state new update @guest_rate6 { ip6 saddr limit rate over ${toString maxNewConnections}/second burst ${toString (2 * maxNewConnections)} packets } reject with icmpx admin-prohibited
      }

      chain vms {
${lib.concatMapStrings (t: ''
        ip saddr @addr_${t.name} 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 @addr_${t.name} ip daddr . meta l4proto . th dport @allow_${t.name} accept
        ip6 saddr @addr6_${t.name} ip6 daddr . meta l4proto . th dport @allow6_${t.name} limit rate 10/second burst 50 packets log prefix "fc-egress ALLOW ${t.user} ${t.name} " level info
        ip6 saddr @addr6_${t.name} ip6 daddr . meta l4proto . th dport @allow6_${t.name} accept
'') taps}      }

      chain refused {
${lib.concatMapStrings (t: "        ip saddr @addr_${t.name} limit rate 10/second burst 50 packets log prefix \"fc-egress DENY ${t.user} ${t.name} \" level info\n") taps}${lib.concatMapStrings (t: "        ip6 saddr @addr6_${t.name} 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
      }

      # Only nginx's packets: others, including those the kernel sends on
      # its own (ping replies, TCP resets, neighbour discovery; no user, so
      # no skuid matches them at all), pass.
      chain output {
        type filter hook output priority filter; policy accept;
        meta skuid "fcbr0-egress" jump nginx
      }

      chain nginx {
        ct state { established, related } accept # e.g. to the guests
        th dport 53 accept
        fib daddr type local reject
        ip daddr @deny4 reject
        ip6 daddr @deny6 reject
        tcp dport != 443 reject
      }
    '';
  };
  # On the bridge: each tap may only send from its VM's addresses (addr_TAP
  # and addr6_TAP, see firewallUpdate; or 0.0.0.0, for DHCP and ARP probes,
  # or ::, for IPv6 duplicate address detection), IPv4, ARP and IPv6 only,
  # and nothing to other taps.
  networking.nftables.tables.firecracker-bridge = {
    family = "bridge";
    content = ''
${lib.concatMapStrings (t: ''
      set addr_${t.name} {
        type ipv4_addr
      }

      set addr6_${t.name} {
        type ipv6_addr
      }
'') taps}
      chain prerouting {
        type filter hook prerouting priority filter; policy accept;
        iifname != "fctap*" accept
${lib.concatMapStrings (t: ''
        iifname "${t.name}" ether type ip ip saddr @addr_${t.name} accept
        iifname "${t.name}" ether type arp arp saddr ip @addr_${t.name} accept
        iifname "${t.name}" ether type ip6 ip6 saddr @addr6_${t.name} accept
'') taps}        ether type ip ip saddr 0.0.0.0 udp dport 67 accept
        ether type arp arp saddr ip 0.0.0.0 accept
        ether type ip6 ip6 saddr :: icmpv6 type { nd-neighbor-solicit, mld2-listener-report } 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' and VMs' addresses, by MAC address
  # (see address 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), but
  # for the names in the VMs' tcp:// and udp:// rules, from the hosts files
  # in hostsDir (which win over address=; for every guest, there's no
  # telling guests apart here).  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" "systemd-tmpfiles-setup.service" ];
    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"
        # IPv6: router advertisements only, the guests take their
        # addresses from their MACs.
        "--enable-ra"
        "--dhcp-range=${prefix6},ra-only"
        "--dhcp-leasefile=/run/fcbr0-dnsmasq/leases"
        "--no-resolv"
        "--no-hosts"
        "--address=/#/172.16.0.1"
        "--local=/#/"
        "--hostsdir=${hostsDir}"
      ] ++ map (a: "--dhcp-host=${a.mac},${a.ip}") addresses);
    };
  };

  # 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 -"
    "d ${hostsDir} 0755 fcbr0-firewall fcbr0-firewall -"
    "d ${addrDir} 0755 fcbr0-firewall fcbr0-firewall -"
  ]
    ++ lib.concatMap (u: [
      "d ${dir}/${u} 0755 ${u} - -"
      "f ${dir}/${u}/default 0644 ${u} - -"
    ]) userNames
    ++ lib.concatMap (t: [
      "f ${vmDir}/${t.name} 0644 ${t.user} - -"
      "f ${vmDir}/${t.name}.name 0644 ${t.user} - -"
    ]) taps;

  # Forwarding, for the tcp:// and udp:// rules.  (With IPv6 forwarding,
  # the kernel ignores router advertisements on interfaces with accept_ra
  # = 1; networkd, which handles them itself, doesn't mind.)
  boot.kernel.sysctl."net.ipv4.ip_forward" = 1;
  boot.kernel.sysctl."net.ipv6.conf.all.forwarding" = 1;

  # Fills the addr_TAP and allow_TAP sets: all of them at start and
  # whenever nftables gets reloaded (which empties them), a tap's
  # (fcbr0-firewall@TAP) whenever its VM's name or 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" ];
    partOf = [ "nftables.service" ];
    unitConfig.ReloadPropagatedFrom = "nftables.service";
    serviceConfig = firewallService // {
      RemainAfterExit = true;
      ExecStart = firewallUpdate;
      ExecReload = firewallUpdate;
    };
  };
  # Names get resolved again every refreshInterval.
  systemd.services.fcbr0-firewall-refresh = {
    after = [ "fcbr0-firewall.service" ];
    serviceConfig = firewallService // {
      ExecStart = firewallUpdate;
    };
  };
  systemd.timers.fcbr0-firewall-refresh = {
    wantedBy = [ "timers.target" ];
    timerConfig.OnUnitActiveSec = refreshInterval;
    timerConfig.OnActiveSec = refreshInterval;
  };
  users.users.fcbr0-firewall = {
    isSystemUser = true;
    group = "fcbr0-firewall";
  };
  users.groups.fcbr0-firewall = { };
  systemd.services."fcbr0-firewall@" = {
    after = [ "fcbr0-firewall.service" ];
    serviceConfig = firewallService // {
      ExecStart = "${firewallUpdate} %i";
    };
  };
  systemd.paths = let
    path = name: instance: file: lib.nameValuePair "fcbr0-firewall-${name}" {
      wantedBy = [ "multi-user.target" ];
      pathConfig.PathChanged = file;  # a directory: any file in it
      pathConfig.Unit = "fcbr0-firewall@${instance}.service";
    };
  in lib.listToAttrs (map (u: path u u "${dir}/${u}") userNames
    ++ map (t: path t.name t.name "${vmDir}/${t.name}") taps
    ++ map (t: path "${t.name}-name" t.name "${vmDir}/${t.name}.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).
  # 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 ];
}