aboutsummaryrefslogtreecommitdiffstats
path: root/tests/vm-host.nix
blob: a0e5cdac06c7a601559d1fc7970003e9fbd20603 (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
# NixOS VM test of modules/host: the module for real (systemd units, path
# units, timer, nftables, dnsmasq, nginx), with network namespaces on
# veths in place of tv's taps rigtap1 and rigtap2 as guests:
# g1 as the VM box, with box's address (172.16.0.10, MAC 06:00:ac:10:00:0a),
# g2 without a name, with rigtap2's own (172.16.0.202, ...:ca); SLAAC gives
# them the IPv6 addresses the host expects from those MACs.  Another netns
# is an upstream with 42::1 and 198.51.100.1, there for the names *.test
# (a dnsmasq on the host's lo, as nginx's resolver), with an HTTPS server
# whose certificate the host trusts (but for untrusted.test's).  Covers
# static addresses by name, the tcp:// rules (IPv4, IPv6, names), DNS,
# IPv6 port 443, anti-spoofing, POST /check, and the HTTPS proxy: passed
# through, decrypted with path rules, refused, upstream certificates
# verified, the log, rules effective without reload.
#
#   nix-build tests/vm-host.nix                     # needs kvm
#   nix-build -E '(import ./tests/vm-host.nix {}).driver' -o driver
#   ./driver/bin/nixos-test-driver -o out           # without kvm: TCG, slow
{ pkgs ? import <nixpkgs> {} }:
let
  # Test certificates (keys in the store, for the test only): a CA, the
  # upstream's certificate for the names below from it, and a self-signed
  # one for untrusted.test.
  certs = pkgs.runCommand "rig-test-certs" { nativeBuildInputs = [ pkgs.openssl ]; } ''
    mkdir $out && cd $out
    openssl req -x509 -new -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
      -days 3650 -subj /CN=rig-test-ca -keyout ca.key -out ca.pem \
      -addext basicConstraints=critical,CA:TRUE -addext keyUsage=critical,keyCertSign
    openssl req -x509 -CA ca.pem -CAkey ca.key -new -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
      -days 3650 -subj /CN=allowed.test -keyout server.key -out server.pem \
      -addext basicConstraints=CA:FALSE \
      -addext subjectAltName=DNS:allowed.test,DNS:sub.allowed.test,DNS:paths.test,DNS:denied.test
    openssl req -x509 -new -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
      -days 3650 -subj /CN=untrusted.test -keyout untrusted.key -out untrusted.pem \
      -addext subjectAltName=DNS:untrusted.test
  '';
in
pkgs.testers.runNixOSTest {
  name = "rig-host";
  nodes.host = { pkgs, ... }: {
    # alice: rigtap0, tv: rigtap1 and rigtap2
    imports = [ (import ../modules/host {
      users = { tv = 2; alice = 1; };
      vms.box = { user = "tv"; ip = "172.16.0.10"; };
    }) ];
    users.users.tv.isNormalUser = true;
    users.users.alice.isNormalUser = true;
    networking.useNetworkd = true;
    networking.nameservers = [ "127.0.0.1" ];
    networking.hosts."42::1" = [ "sshhost6.test" ];
    networking.hosts."198.51.100.1" = [ "sshhost.test" ];
    # nginx's resolver (from resolv.conf): the upstream for any *.test.
    services.dnsmasq = {
      enable = true;
      settings = {
        interface = "lo";
        bind-interfaces = true;
        no-resolv = true;
        address = "/test/198.51.100.1";
      };
    };
    security.pki.certificateFiles = [ "${certs}/ca.pem" ];
    # As the host's firewall has to (see README.md).
    networking.firewall.trustedInterfaces = [ "rigbr0" ];
    environment.systemPackages = [ pkgs.socat pkgs.dig pkgs.curl pkgs.openssl ];
    virtualisation.memorySize = 1024;
  };
  testScript = ''
    g1_ip6 = "fdfc:fc::400:acff:fe10:a"
    g2_ip6 = "fdfc:fc::400:acff:fe10:ca"

    host.wait_for_unit("multi-user.target")
    host.wait_for_unit("rig-dnsmasq.service")
    host.wait_for_unit("rig-firewall.service")
    # box on rigtap1, as the run script does it
    host.succeed("su tv -c 'echo box > /run/rig-egress/rigtap1.name'")
    host.wait_until_succeeds("test \"$(head -n 1 /run/rig-addr/rigtap1)\" = 172.16.0.10", timeout=60)
    host.succeed("""
      set -e
      guest() {  # N TAP IP MAC
        ip link del $2
        ip netns add g$1
        ip link add $2 type veth peer name eth0 netns g$1
        ip link set $2 master rigbr0 up
        ip netns exec g$1 sysctl -qw net.ipv6.conf.all.use_tempaddr=0 net.ipv6.conf.default.use_tempaddr=0
        ip netns exec g$1 ip link set eth0 address $4
        ip netns exec g$1 ip link set lo up
        ip netns exec g$1 ip addr add $3/24 dev eth0
        ip netns exec g$1 ip link set eth0 up
        ip netns exec g$1 ip route add default via 172.16.0.1
      }
      guest 1 rigtap1 172.16.0.10 06:00:ac:10:00:0a
      guest 2 rigtap2 172.16.0.202 06:00:ac:10:00:ca
      ip netns add U
      ip link add up0 type veth peer name eth0 netns U
      ip link set up0 up
      ip addr add 42::fe/16 dev up0 nodad
      ip addr add 198.51.100.254/24 dev up0
      ip netns exec U ip link set lo up
      ip netns exec U ip link set eth0 up
      ip netns exec U ip addr add 42::1/16 dev eth0 nodad
      ip netns exec U ip addr add 198.51.100.1/24 dev eth0
      ip netns exec U ip -6 route add default via 42::fe
      ip netns exec U ip route add default via 198.51.100.254
    """)
    host.succeed("ip netns exec U socat TCP6-LISTEN:22,fork,reuseaddr SYSTEM:'echo ssh-ok' >&2 &")
    host.succeed("ip netns exec U socat TCP6-LISTEN:443,fork,reuseaddr,ipv6only=1 SYSTEM:'echo https-direct' >&2 &")
    # networkd can take minutes under TCG
    host.wait_until_succeeds(f"ip netns exec g1 ip -6 addr show dev eth0 | grep -q '{g1_ip6}/64'", timeout=300)
    host.wait_until_succeeds(f"ip netns exec g2 ip -6 addr show dev eth0 | grep -q '{g2_ip6}/64'", timeout=60)

    def tcp(g, dst, port, extra=""):
        return host.succeed(f"ip netns exec {g} timeout 5 socat -T3 - TCP:{dst}:{port}{extra} </dev/null 2>/dev/null || echo blocked").strip()

    def dig(g, t, name):
        return host.execute(f"ip netns exec {g} dig +short {t} {name} @172.16.0.1")[1].strip()

    def check_uris(g, *uris):
        body = "\\n".join(uris)
        return host.succeed(f"printf '{body}\\n' | ip netns exec {g} curl -sS --data-binary @- http://172.16.0.1/check").split()

    def check(what, got, want):
        print(f"{what}: {got}")
        assert got == want, f"{what}: got {got!r}, want {want!r}"

    # rules via rig-egress and the path units
    host.succeed("su tv -c 'rig-egress -l box allow tcp://[42::1]:22 tcp://[42::1]:443 tcp://sshhost6.test:22 tcp://198.51.100.1:22'")
    host.fail("su tv -c 'rig-egress -l box allow tcp://[42::1/129]:22'")
    host.succeed("su tv -c 'echo box > /run/rig-egress/rigtap1'")
    host.wait_until_succeeds("nft list set inet rigs allow6_rigtap1 | grep -q '42::1'", timeout=60)

    check("host reaches the upstream", host.succeed("timeout 5 socat -T3 - TCP6:[42::1]:22 </dev/null").strip(), "ssh-ok")
    check("g1 [42::1]:22, allowed", tcp("g1", "[42::1]", 22), "ssh-ok")
    check("g2 [42::1]:22, not allowed", tcp("g2", "[42::1]", 22), "blocked")
    check("g1 [42::1]:443, IPv6 HTTPS refused", tcp("g1", "[42::1]", 443), "blocked")
    check("g1 198.51.100.1:22, IPv4", tcp("g1", "198.51.100.1", 22), "ssh-ok")
    check("g1 AAAA of a rule's name", dig("g1", "AAAA", "sshhost6.test"), "42::1")
    check("g1 A of another name", dig("g1", "A", "other.test"), "172.16.0.1")
    check("g1 AAAA of another name", dig("g1", "AAAA", "other.test"), "")
    check("g1 checks", check_uris("g1", "tcp://[42::1]:22", "tcp://[42::1]:23", "tcp://[42::1]:443", "tcp://sshhost6.test:22", "tcp://198.51.100.1:22"),
          ["true", "false", "false", "true", "true"])
    check("g2 checks", check_uris("g2", "tcp://[42::1]:22"), ["false"])
    host.succeed(f"ip netns exec g2 ip addr add {g1_ip6}/64 dev eth0 nodad")
    check("g2 sending as g1", tcp("g2", "[42::1]", 22, f",bind=[{g1_ip6}]"), "blocked")
    check("g1 to the host's IPv6 address", tcp("g1", "[fdfc:fc::1]", 22), "blocked")
    host.succeed("su tv -c 'rig-egress -l box deny tcp://[42::1]:22 tcp://sshhost6.test:22'")
    host.wait_until_fails("nft list set inet rigs allow6_rigtap1 | grep -q '42::1 . tcp . 22'", timeout=60)
    check("g1 [42::1]:22 after deny", tcp("g1", "[42::1]", 22), "blocked")
    check("g1 checks after deny", check_uris("g1", "tcp://[42::1]:22"), ["false"])
    host.succeed("systemctl list-timers rig-firewall-refresh.timer --no-pager | grep -q rig-firewall-refresh")

    # The HTTPS proxy.  The upstream serves files (s_server -WWW), as
    # allowed.test & co. with a certificate from the test CA, which the
    # host trusts, and as untrusted.test with a self-signed one.  The
    # guests dial any address: their port 443 goes to the proxy.
    test_ca = "${certs}/ca.pem"
    proxy_ca = "/var/lib/rig-proxy/ca.pem"
    host.succeed("mkdir -p /tmp/www/ok /tmp/www/no && echo hello > /tmp/www/hello && echo ok > /tmp/www/ok/file && echo no > /tmp/www/no/file")
    host.succeed(
        "cd /tmp/www && ip netns exec U openssl s_server -quiet -WWW -accept 198.51.100.1:443"
        " -cert ${certs}/server.pem -key ${certs}/server.key"
        " -servername untrusted.test -cert2 ${certs}/untrusted.pem -key2 ${certs}/untrusted.key >&2 &"
    )
    host.wait_until_succeeds("ip netns exec U ss -ltn | grep -q '198.51.100.1:443'", timeout=30)
    host.wait_for_unit("rig-proxy.service")

    def https(g, url, ca, extra=""):
        name = url.split("/")[2]
        out = host.succeed(
            f"ip netns exec {g} curl -sS --max-time 10 --cacert {ca} --resolve {name}:443:203.0.113.9 {extra}"
            f" -w '\\n%{{http_code}}' {url} 2>/dev/null || echo blocked"
        ).split()
        return "blocked" if out[-1] == "blocked" else f"{' '.join(out[:-1])} {out[-1]}"

    def status(g, url, extra=""):
        return https(g, url, proxy_ca, extra).split()[-1]

    host.succeed("su tv -c 'rig-egress -l box allow https://allowed.test https://paths.test/ok/ https://untrusted.test/ok/'")
    check("g1 allowed.test, passed through", https("g1", "https://allowed.test/hello", test_ca), "hello 200")
    check("g1 allowed.test, not with our CA", https("g1", "https://allowed.test/hello", proxy_ca), "blocked")
    check("g1 sub.allowed.test, subdomain", https("g1", "https://sub.allowed.test/hello", test_ca), "hello 200")
    check("g1 paths.test/ok/, decrypted", https("g1", "https://paths.test/ok/file", proxy_ca), "ok 200")
    check("g1 paths.test/ok/, not the upstream's certificate", https("g1", "https://paths.test/ok/file", test_ca), "blocked")
    check("g1 paths.test/no/", status("g1", "https://paths.test/no/file"), "403")
    check("g1 paths.test/ok/../no/", status("g1", "https://paths.test/ok/../no/file", "--path-as-is"), "403")
    check("g1 paths.test/ok/%2e%2e/no/", status("g1", "https://paths.test/ok/%2e%2e/no/file"), "403")
    check("g1 paths.test, Host not the server name", status("g1", "https://paths.test/ok/file", "-H Host:allowed.test"), "403")
    check("g1 denied.test, no rule", https("g1", "https://denied.test/hello", test_ca), "blocked")
    check("g2 allowed.test, not its rule", https("g2", "https://allowed.test/hello", test_ca), "blocked")
    check("g1 untrusted.test, upstream not verified", status("g1", "https://untrusted.test/ok/file"), "502")
    check("g1 https checks", check_uris("g1", "https://allowed.test", "https://sub.allowed.test/x", "https://paths.test/ok/file", "https://paths.test/no/file", "https://denied.test"),
          ["true", "true", "true", "false", "false"])
    host.wait_until_succeeds("journalctl -t rig_egress --no-pager | grep -q 'ALLOW tv rigtap1 box https://allowed.test'", timeout=30)
    host.wait_until_succeeds("journalctl -t rig_egress --no-pager | grep -q 'DENY tv rigtap1 box https://denied.test'", timeout=30)
    host.wait_until_succeeds("journalctl -t rig_egress --no-pager | grep -qE 'DENY .*GET https://paths.test/no/file'", timeout=30)
    # rules apply to the next connection, without reloading anything
    host.succeed("su tv -c 'rig-egress -l box deny https://allowed.test && rig-egress -l box allow https://denied.test'")
    check("g1 allowed.test after deny", https("g1", "https://allowed.test/hello", test_ca), "blocked")
    check("g1 denied.test after allow", https("g1", "https://denied.test/hello", test_ca), "hello 200")
  '';
}