aboutsummaryrefslogtreecommitdiff
path: root/nixpkgs/nixos/tests/acme.nix
blob: 64193ed8498cbc131fe86acb0db3d4fd2786887b (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
let
  commonConfig = ./common/acme/client;

  dnsServerIP = nodes: nodes.dnsserver.config.networking.primaryIPAddress;

  dnsScript = {pkgs, nodes}: let
    dnsAddress = dnsServerIP nodes;
  in pkgs.writeShellScript "dns-hook.sh" ''
    set -euo pipefail
    echo '[INFO]' "[$2]" 'dns-hook.sh' $*
    if [ "$1" = "present" ]; then
      ${pkgs.curl}/bin/curl --data '{"host": "'"$2"'", "value": "'"$3"'"}' http://${dnsAddress}:8055/set-txt
    else
      ${pkgs.curl}/bin/curl --data '{"host": "'"$2"'"}' http://${dnsAddress}:8055/clear-txt
    fi
  '';

  documentRoot = pkgs: pkgs.runCommand "docroot" {} ''
    mkdir -p "$out"
    echo hello world > "$out/index.html"
  '';

  vhostBase = pkgs: {
    forceSSL = true;
    locations."/".root = documentRoot pkgs;
  };

in import ./make-test-python.nix ({ lib, ... }: {
  name = "acme";
  meta.maintainers = lib.teams.acme.members;

  nodes = {
    # The fake ACME server which will respond to client requests
    acme = { nodes, lib, ... }: {
      imports = [ ./common/acme/server ];
      networking.nameservers = lib.mkForce [ (dnsServerIP nodes) ];
    };

    # A fake DNS server which can be configured with records as desired
    # Used to test DNS-01 challenge
    dnsserver = { nodes, pkgs, ... }: {
      networking.firewall.allowedTCPPorts = [ 8055 53 ];
      networking.firewall.allowedUDPPorts = [ 53 ];
      systemd.services.pebble-challtestsrv = {
        enable = true;
        description = "Pebble ACME challenge test server";
        wantedBy = [ "network.target" ];
        serviceConfig = {
          ExecStart = "${pkgs.pebble}/bin/pebble-challtestsrv -dns01 ':53' -defaultIPv6 '' -defaultIPv4 '${nodes.webserver.config.networking.primaryIPAddress}'";
          # Required to bind on privileged ports.
          AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ];
        };
      };
    };

    # A web server which will be the node requesting certs
    webserver = { pkgs, nodes, lib, config, ... }: {
      imports = [ commonConfig ];
      networking.nameservers = lib.mkForce [ (dnsServerIP nodes) ];
      networking.firewall.allowedTCPPorts = [ 80 443 ];

      # OpenSSL will be used for more thorough certificate validation
      environment.systemPackages = [ pkgs.openssl ];

      # Set log level to info so that we can see when the service is reloaded
      services.nginx.enable = true;
      services.nginx.logError = "stderr info";

      # First tests configure a basic cert and run a bunch of openssl checks
      services.nginx.virtualHosts."a.example.test" = (vhostBase pkgs) // {
        enableACME = true;
      };

      # Used to determine if service reload was triggered
      systemd.targets.test-renew-nginx = {
        wants = [ "acme-a.example.test.service" ];
        after = [ "acme-a.example.test.service" "nginx-config-reload.service" ];
      };

      # Cert config changes will not cause the nginx configuration to change.
      # This tests that the reload service is correctly triggered.
      # It also tests that postRun is exec'd as root
      specialisation.cert-change.configuration = { pkgs, ... }: {
        security.acme.certs."a.example.test".keyType = "ec384";
        security.acme.certs."a.example.test".postRun = ''
          set -euo pipefail
          touch test
          chown root:root test
          echo testing > test
        '';
      };

      # Now adding an alias to ensure that the certs are updated
      specialisation.nginx-aliases.configuration = { pkgs, ... }: {
        services.nginx.virtualHosts."a.example.test" = {
          serverAliases = [ "b.example.test" ];
        };
      };

      # Test using Apache HTTPD
      specialisation.httpd-aliases.configuration = { pkgs, config, lib, ... }: {
        services.nginx.enable = lib.mkForce false;
        services.httpd.enable = true;
        services.httpd.adminAddr = config.security.acme.email;
        services.httpd.virtualHosts."c.example.test" = {
          serverAliases = [ "d.example.test" ];
          forceSSL = true;
          enableACME = true;
          documentRoot = documentRoot pkgs;
        };

        # Used to determine if service reload was triggered
        systemd.targets.test-renew-httpd = {
          wants = [ "acme-c.example.test.service" ];
          after = [ "acme-c.example.test.service" "httpd-config-reload.service" ];
        };
      };

      # Validation via DNS-01 challenge
      specialisation.dns-01.configuration = { pkgs, config, nodes, ... }: {
        security.acme.certs."example.test" = {
          domain = "*.example.test";
          group = config.services.nginx.group;
          dnsProvider = "exec";
          dnsPropagationCheck = false;
          credentialsFile = pkgs.writeText "wildcard.env" ''
            EXEC_PATH=${dnsScript { inherit pkgs nodes; }}
          '';
        };

        services.nginx.virtualHosts."dns.example.test" = (vhostBase pkgs) // {
          useACMEHost = "example.test";
        };
      };

      # Validate service relationships by adding a slow start service to nginx' wants.
      # Reproducer for https://github.com/NixOS/nixpkgs/issues/81842
      specialisation.slow-startup.configuration = { pkgs, config, nodes, lib, ... }: {
        systemd.services.my-slow-service = {
          wantedBy = [ "multi-user.target" "nginx.service" ];
          before = [ "nginx.service" ];
          preStart = "sleep 5";
          script = "${pkgs.python3}/bin/python -m http.server";
        };

        services.nginx.virtualHosts."slow.example.com" = {
          forceSSL = true;
          enableACME = true;
          locations."/".proxyPass = "http://localhost:8000";
        };
      };
    };

    # The client will be used to curl the webserver to validate configuration
    client = {nodes, lib, pkgs, ...}: {
      imports = [ commonConfig ];
      networking.nameservers = lib.mkForce [ (dnsServerIP nodes) ];

      # OpenSSL will be used for more thorough certificate validation
      environment.systemPackages = [ pkgs.openssl ];
    };
  };

  testScript = {nodes, ...}:
    let
      newServerSystem = nodes.webserver.config.system.build.toplevel;
      switchToNewServer = "${newServerSystem}/bin/switch-to-configuration test";
    in
    # Note, wait_for_unit does not work for oneshot services that do not have RemainAfterExit=true,
    # this is because a oneshot goes from inactive => activating => inactive, and never
    # reaches the active state. Targets do not have this issue.

    ''
      import time


      has_switched = False


      def switch_to(node, name):
          global has_switched
          if has_switched:
              node.succeed(
                  "${switchToNewServer}"
              )
          has_switched = True
          node.succeed(
              f"/run/current-system/specialisation/{name}/bin/switch-to-configuration test"
          )


      # Ensures the issuer of our cert matches the chain
      # and matches the issuer we expect it to be.
      # It's a good validation to ensure the cert.pem and fullchain.pem
      # are not still selfsigned afer verification
      def check_issuer(node, cert_name, issuer):
          for fname in ("cert.pem", "fullchain.pem"):
              actual_issuer = node.succeed(
                  f"openssl x509 -noout -issuer -in /var/lib/acme/{cert_name}/{fname}"
              ).partition("=")[2]
              print(f"{fname} issuer: {actual_issuer}")
              assert issuer.lower() in actual_issuer.lower()


      # Ensure cert comes before chain in fullchain.pem
      def check_fullchain(node, cert_name):
          subject_data = node.succeed(
              f"openssl crl2pkcs7 -nocrl -certfile /var/lib/acme/{cert_name}/fullchain.pem"
              " | openssl pkcs7 -print_certs -noout"
          )
          for line in subject_data.lower().split("\n"):
              if "subject" in line:
                  print(f"First subject in fullchain.pem: ", line)
                  assert cert_name.lower() in line
                  return

          assert False


      def check_connection(node, domain, retries=3):
          assert retries >= 0

          result = node.succeed(
              "openssl s_client -brief -verify 2 -CAfile /tmp/ca.crt"
              f" -servername {domain} -connect {domain}:443 < /dev/null 2>&1"
          )

          for line in result.lower().split("\n"):
              if "verification" in line and "error" in line:
                  time.sleep(1)
                  return check_connection(node, domain, retries - 1)


      def check_connection_key_bits(node, domain, bits, retries=3):
          assert retries >= 0

          result = node.succeed(
              "openssl s_client -CAfile /tmp/ca.crt"
              f" -servername {domain} -connect {domain}:443 < /dev/null"
              " | openssl x509 -noout -text | grep -i Public-Key"
          )
          print("Key type:", result)

          if bits not in result:
              time.sleep(1)
              return check_connection_key_bits(node, domain, bits, retries - 1)


      client.start()
      dnsserver.start()

      dnsserver.wait_for_unit("pebble-challtestsrv.service")
      client.wait_for_unit("default.target")

      client.succeed(
          'curl --data \'{"host": "acme.test", "addresses": ["${nodes.acme.config.networking.primaryIPAddress}"]}\' http://${dnsServerIP nodes}:8055/add-a'
      )

      acme.start()
      webserver.start()

      acme.wait_for_unit("default.target")
      acme.wait_for_unit("pebble.service")

      client.succeed("curl https://acme.test:15000/roots/0 > /tmp/ca.crt")
      client.succeed("curl https://acme.test:15000/intermediate-keys/0 >> /tmp/ca.crt")

      with subtest("Can request certificate with HTTPS-01 challenge"):
          webserver.wait_for_unit("acme-finished-a.example.test.target")
          check_fullchain(webserver, "a.example.test")
          check_issuer(webserver, "a.example.test", "pebble")
          check_connection(client, "a.example.test")

      with subtest("Can generate valid selfsigned certs"):
          webserver.succeed("systemctl clean acme-a.example.test.service --what=state")
          webserver.succeed("systemctl start acme-selfsigned-a.example.test.service")
          check_fullchain(webserver, "a.example.test")
          check_issuer(webserver, "a.example.test", "minica")
          # Will succeed if nginx can load the certs
          webserver.succeed("systemctl start nginx-config-reload.service")

      with subtest("Can reload nginx when timer triggers renewal"):
          webserver.succeed("systemctl start test-renew-nginx.target")
          check_issuer(webserver, "a.example.test", "pebble")
          check_connection(client, "a.example.test")

      with subtest("Can reload web server when cert configuration changes"):
          switch_to(webserver, "cert-change")
          webserver.wait_for_unit("acme-finished-a.example.test.target")
          check_connection_key_bits(client, "a.example.test", "384")
          webserver.succeed("grep testing /var/lib/acme/a.example.test/test")

      with subtest("Can request certificate with HTTPS-01 when nginx startup is delayed"):
          switch_to(webserver, "slow-startup")
          webserver.wait_for_unit("acme-finished-slow.example.com.target")
          check_issuer(webserver, "slow.example.com", "pebble")
          check_connection(client, "slow.example.com")

      with subtest("Can request certificate for vhost + aliases (nginx)"):
          # Check the key hash before and after adding an alias. It should not change.
          # The previous test reverts the ed384 change
          webserver.wait_for_unit("acme-finished-a.example.test.target")
          keyhash_old = webserver.succeed("md5sum /var/lib/acme/a.example.test/key.pem")
          switch_to(webserver, "nginx-aliases")
          webserver.wait_for_unit("acme-finished-a.example.test.target")
          check_issuer(webserver, "a.example.test", "pebble")
          check_connection(client, "a.example.test")
          check_connection(client, "b.example.test")
          keyhash_new = webserver.succeed("md5sum /var/lib/acme/a.example.test/key.pem")
          assert keyhash_old == keyhash_new

      with subtest("Can request certificates for vhost + aliases (apache-httpd)"):
          switch_to(webserver, "httpd-aliases")
          webserver.wait_for_unit("acme-finished-c.example.test.target")
          check_issuer(webserver, "c.example.test", "pebble")
          check_connection(client, "c.example.test")
          check_connection(client, "d.example.test")

      with subtest("Can reload httpd when timer triggers renewal"):
          # Switch to selfsigned first
          webserver.succeed("systemctl clean acme-c.example.test.service --what=state")
          webserver.succeed("systemctl start acme-selfsigned-c.example.test.service")
          check_issuer(webserver, "c.example.test", "minica")
          webserver.succeed("systemctl start httpd-config-reload.service")
          webserver.succeed("systemctl start test-renew-httpd.target")
          check_issuer(webserver, "c.example.test", "pebble")
          check_connection(client, "c.example.test")

      with subtest("Can request wildcard certificates using DNS-01 challenge"):
          switch_to(webserver, "dns-01")
          webserver.wait_for_unit("acme-finished-example.test.target")
          check_issuer(webserver, "example.test", "pebble")
          check_connection(client, "dns.example.test")
    '';
})