aboutsummaryrefslogtreecommitdiffstats
path: root/host.nix
blob: d034ef305342592b53cfc4b28d24db865d2e3622 (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
# 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
# takes one tap device, so taps is the number of VMs that can run at the
# same time.
#
# Egress: nothing gets forwarded from fcbr0.  The guests' DNS resolves
# every name to 172.16.0.1, where nginx takes TLS connections on port 443,
# 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.
#
# usage (in the host's configuration.nix):
#   imports = [ (import ./host.nix { user = "tv"; }) ];
# The host's firewall has to let the guests in on fcbr0: DHCP (udp 67),
# DNS (udp and tcp 53) and TLS (tcp 443).
{ user, taps ? 8 }: { lib, pkgs, ... }: let
  tapNames = map (i: "fctap${toString i}") (lib.range 0 (taps - 1));
  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-]+)*";

  fc-egress = pkgs.writeShellScriptBin "fc-egress" ''
    set -efu
    export PATH=${lib.makeBinPath [ pkgs.bash pkgs.coreutils pkgs.gnugrep pkgs.gnused pkgs.systemd ]}
    list=${allowed}
    usage() {
      echo "usage: fc-egress list"
      echo "       fc-egress allow DOMAIN..."
      echo "       fc-egress deny DOMAIN..."
      echo "       fc-egress log [JOURNALCTL-OPTION...]"
      echo "Allowing a domain allows its subdomains, too."
    }
    check() {
      for d; do
        case $d in
          ""|.*|*.|*..*|*[!a-z0-9.-]*)
            echo "fc-egress: bad domain: $d" >&2
            exit 1
        esac
      done
    }
    # Rewrite the list in place, as the path unit watches for writes.
    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)
        # 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) '
        ;;
      help|-h|--help)
        usage
        ;;
      *)
        usage >&2
        exit 1
    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" ''
    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
    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 }
        print "resolver" s " ipv6=off;"
      }
    ' /etc/resolv.conf > resolver.conf
  '';

  # 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" ''
    daemon off;
    pid /run/fcbr0-sni/nginx.pid;
    error_log stderr crit;
    worker_processes 1;
    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;
      }

      server {
        listen 172.16.0.1:443;
        ssl_preread on;
        proxy_pass $egress_upstream;
      }
      server {
        listen unix:/run/fcbr0-sni/deny.sock;
        access_log off;
        return "";
      }
    }
  '';
in {
  networking.interfaces = lib.genAttrs tapNames (_: {
    virtual = true;
    virtualType = "tap";
    virtualOwner = user;
  }) // {
    fcbr0.ipv4.addresses = [{ address = "172.16.0.1"; prefixLength = 24; }];
  };
  networking.bridges.fcbr0.interfaces = tapNames;

  # Only rejects; for anything else the host's own forward chain decides.
  networking.nftables.enable = true;
  networking.nftables.tables.firecracker = {
    family = "inet";
    content = ''
      chain forward {
        type filter hook forward priority filter; policy accept;
        iifname "fcbr0" reject with icmpx admin-prohibited
      }
    '';
  };

  # A dnsmasq of its own, so it doesn't get mixed up with one the host might
  # run otherwise.  DHCP, and DNS that resolves every name to 172.16.0.1
  # 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.2,172.16.0.254,1h"
        "--dhcp-leasefile=/run/fcbr0-dnsmasq/leases"
        "--no-resolv"
        "--no-hosts"
        "--address=/#/172.16.0.1"
        "--local=/#/"
      ];
    };
  };

  systemd.tmpfiles.rules = [
    "d ${dir} 0755 ${user} - -"
    "f ${allowed} 0644 ${user} - -"
  ];

  # nginx binds to 172.16.0.1, so it has to wait for fcbr0's address
  # (network-addresses-fcbr0.service with scripted networking; else
  # Restart= gets it 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 = {
    wantedBy = [ "multi-user.target" ];
    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";
      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 ];
}