1# SSL/TLS Certificates with ACME {#module-security-acme}
2
3NixOS supports automatic domain validation & certificate retrieval and
4renewal using the ACME protocol. Any provider can be used, but by default
5NixOS uses Let's Encrypt. The alternative ACME client
6[lego](https://go-acme.github.io/lego/) is used under
7the hood.
8
9Automatic cert validation and configuration for Apache and Nginx virtual
10hosts is included in NixOS, however if you would like to generate a wildcard
11cert or you are not using a web server you will have to configure DNS
12based validation.
13
14## Prerequisites {#module-security-acme-prerequisites}
15
16To use the ACME module, you must accept the provider's terms of service
17by setting [](#opt-security.acme.acceptTerms)
18to `true`. The Let's Encrypt ToS can be found
19[here](https://letsencrypt.org/repository/).
20
21You must also set an email address to be used when creating accounts with
22Let's Encrypt. You can set this for all certs with
23[](#opt-security.acme.defaults.email)
24and/or on a per-cert basis with
25[](#opt-security.acme.certs._name_.email).
26This address is only used for registration and renewal reminders,
27and cannot be used to administer the certificates in any way.
28
29Alternatively, you can use a different ACME server by changing the
30[](#opt-security.acme.defaults.server) option
31to a provider of your choosing, or just change the server for one cert with
32[](#opt-security.acme.certs._name_.server).
33
34You will need an HTTP server or DNS server for verification. For HTTP,
35the server must have a webroot defined that can serve
36{file}`.well-known/acme-challenge`. This directory must be
37writeable by the user that will run the ACME client. For DNS, you must
38set up credentials with your provider/server for use with lego.
39
40## Using ACME certificates in Nginx {#module-security-acme-nginx}
41
42NixOS supports fetching ACME certificates for you by setting
43`enableACME = true;` in a virtualHost config. We first create self-signed
44placeholder certificates in place of the real ACME certs. The placeholder
45certs are overwritten when the ACME certs arrive. For
46`foo.example.com` the config would look like this:
47
48```nix
49{
50 security.acme.acceptTerms = true;
51 security.acme.defaults.email = "admin+acme@example.com";
52 services.nginx = {
53 enable = true;
54 virtualHosts = {
55 "foo.example.com" = {
56 forceSSL = true;
57 enableACME = true;
58 # All serverAliases will be added as extra domain names on the certificate.
59 serverAliases = [ "bar.example.com" ];
60 locations."/" = {
61 root = "/var/www";
62 };
63 };
64
65 # We can also add a different vhost and reuse the same certificate
66 # but we have to append extraDomainNames manually beforehand:
67 # security.acme.certs."foo.example.com".extraDomainNames = [ "baz.example.com" ];
68 "baz.example.com" = {
69 forceSSL = true;
70 useACMEHost = "foo.example.com";
71 locations."/" = {
72 root = "/var/www";
73 };
74 };
75 };
76 };
77}
78```
79
80## Using ACME certificates in Apache/httpd {#module-security-acme-httpd}
81
82Using ACME certificates with Apache virtual hosts is identical
83to using them with Nginx. The attribute names are all the same, just replace
84"nginx" with "httpd" where appropriate.
85
86## Manual configuration of HTTP-01 validation {#module-security-acme-configuring}
87
88First off you will need to set up a virtual host to serve the challenges.
89This example uses a vhost called `certs.example.com`, with
90the intent that you will generate certs for all your vhosts and redirect
91everyone to HTTPS.
92
93```nix
94{
95 security.acme.acceptTerms = true;
96 security.acme.defaults.email = "admin+acme@example.com";
97
98 # /var/lib/acme/.challenges must be writable by the ACME user
99 # and readable by the Nginx user. The easiest way to achieve
100 # this is to add the Nginx user to the ACME group.
101 users.users.nginx.extraGroups = [ "acme" ];
102
103 services.nginx = {
104 enable = true;
105 virtualHosts = {
106 "acmechallenge.example.com" = {
107 # Catchall vhost, will redirect users to HTTPS for all vhosts
108 serverAliases = [ "*.example.com" ];
109 locations."/.well-known/acme-challenge" = {
110 root = "/var/lib/acme/.challenges";
111 };
112 locations."/" = {
113 return = "301 https://$host$request_uri";
114 };
115 };
116 };
117 };
118 # Alternative config for Apache
119 users.users.wwwrun.extraGroups = [ "acme" ];
120 services.httpd = {
121 enable = true;
122 virtualHosts = {
123 "acmechallenge.example.com" = {
124 # Catchall vhost, will redirect users to HTTPS for all vhosts
125 serverAliases = [ "*.example.com" ];
126 # /var/lib/acme/.challenges must be writable by the ACME user and readable by the Apache user.
127 # By default, this is the case.
128 documentRoot = "/var/lib/acme/.challenges";
129 extraConfig = ''
130 RewriteEngine On
131 RewriteCond %{HTTPS} off
132 RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge [NC]
133 RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301]
134 '';
135 };
136 };
137 };
138}
139```
140
141Now you need to configure ACME to generate a certificate.
142
143```nix
144{
145 security.acme.certs."foo.example.com" = {
146 webroot = "/var/lib/acme/.challenges";
147 email = "foo@example.com";
148 # Ensure that the web server you use can read the generated certs
149 # Take a look at the group option for the web server you choose.
150 group = "nginx";
151 # Since we have a wildcard vhost to handle port 80,
152 # we can generate certs for anything!
153 # Just make sure your DNS resolves them.
154 extraDomainNames = [ "mail.example.com" ];
155 };
156}
157```
158
159The private key {file}`key.pem` and certificate
160{file}`fullchain.pem` will be put into
161{file}`/var/lib/acme/foo.example.com`.
162
163Refer to [](#ch-options) for all available configuration
164options for the [security.acme](#opt-security.acme.certs)
165module.
166
167## Configuring ACME for DNS validation {#module-security-acme-config-dns}
168
169This is useful if you want to generate a wildcard certificate, since
170ACME servers will only hand out wildcard certs over DNS validation.
171There are a number of supported DNS providers and servers you can utilise,
172see the [lego docs](https://go-acme.github.io/lego/dns/)
173for provider/server specific configuration values. For the sake of these
174docs, we will provide a fully self-hosted example using bind.
175
176```nix
177{
178 services.bind = {
179 enable = true;
180 extraConfig = ''
181 include "/var/lib/secrets/dnskeys.conf";
182 '';
183 zones = [
184 rec {
185 name = "example.com";
186 file = "/var/db/bind/${name}";
187 master = true;
188 extraConfig = "allow-update { key rfc2136key.example.com.; };";
189 }
190 ];
191 };
192
193 # Now we can configure ACME
194 security.acme.acceptTerms = true;
195 security.acme.defaults.email = "admin+acme@example.com";
196 security.acme.certs."example.com" = {
197 domain = "*.example.com";
198 dnsProvider = "rfc2136";
199 environmentFile = "/var/lib/secrets/certs.secret";
200 # We don't need to wait for propagation since this is a local DNS server
201 dnsPropagationCheck = false;
202 };
203}
204```
205
206The {file}`dnskeys.conf` and {file}`certs.secret`
207must be kept secure and thus you should not keep their contents in your
208Nix config. Instead, generate them one time with a systemd service:
209
210```nix
211{
212 systemd.services.dns-rfc2136-conf = {
213 requiredBy = [
214 "acme-example.com.service"
215 "bind.service"
216 ];
217 before = [
218 "acme-example.com.service"
219 "bind.service"
220 ];
221 unitConfig = {
222 ConditionPathExists = "!/var/lib/secrets/dnskeys.conf";
223 };
224 serviceConfig = {
225 Type = "oneshot";
226 UMask = 77;
227 };
228 path = [ pkgs.bind ];
229 script = ''
230 mkdir -p /var/lib/secrets
231 chmod 755 /var/lib/secrets
232 tsig-keygen rfc2136key.example.com > /var/lib/secrets/dnskeys.conf
233 chown named:root /var/lib/secrets/dnskeys.conf
234 chmod 400 /var/lib/secrets/dnskeys.conf
235
236 # extract secret value from the dnskeys.conf
237 while read x y; do if [ "$x" = "secret" ]; then secret="''${y:1:''${#y}-3}"; fi; done < /var/lib/secrets/dnskeys.conf
238
239 cat > /var/lib/secrets/certs.secret << EOF
240 RFC2136_NAMESERVER='127.0.0.1:53'
241 RFC2136_TSIG_ALGORITHM='hmac-sha256.'
242 RFC2136_TSIG_KEY='rfc2136key.example.com'
243 RFC2136_TSIG_SECRET='$secret'
244 EOF
245 chmod 400 /var/lib/secrets/certs.secret
246 '';
247 };
248}
249```
250
251Now you're all set to generate certs! You should monitor the first invocation
252by running `systemctl start acme-example.com.service &
253journalctl -fu acme-example.com.service` and watching its log output.
254
255## Using DNS validation with web server virtual hosts {#module-security-acme-config-dns-with-vhosts}
256
257It is possible to use DNS-01 validation with all certificates,
258including those automatically configured via the Nginx/Apache
259[`enableACME`](#opt-services.nginx.virtualHosts._name_.enableACME)
260option. This configuration pattern is fully
261supported and part of the module's test suite for Nginx + Apache.
262
263You must follow the guide above on configuring DNS-01 validation
264first, however instead of setting the options for one certificate
265(e.g. [](#opt-security.acme.certs._name_.dnsProvider))
266you will set them as defaults
267(e.g. [](#opt-security.acme.defaults.dnsProvider)).
268
269```nix
270{
271 # Configure ACME appropriately
272 security.acme.acceptTerms = true;
273 security.acme.defaults.email = "admin+acme@example.com";
274 security.acme.defaults = {
275 dnsProvider = "rfc2136";
276 environmentFile = "/var/lib/secrets/certs.secret";
277 # We don't need to wait for propagation since this is a local DNS server
278 dnsPropagationCheck = false;
279 };
280
281 # For each virtual host you would like to use DNS-01 validation with,
282 # set acmeRoot = null
283 services.nginx = {
284 enable = true;
285 virtualHosts = {
286 "foo.example.com" = {
287 enableACME = true;
288 acmeRoot = null;
289 };
290 };
291 };
292}
293```
294
295And that's it! Next time your configuration is rebuilt, or when
296you add a new virtualHost, it will be DNS-01 validated.
297
298## Using ACME with services demanding root owned certificates {#module-security-acme-root-owned}
299
300Some services refuse to start if the configured certificate files
301are not owned by root. PostgreSQL and OpenSMTPD are examples of these.
302There is no way to change the user the ACME module uses (it will always be
303`acme`), however you can use systemd's
304`LoadCredential` feature to resolve this elegantly.
305Below is an example configuration for OpenSMTPD, but this pattern
306can be applied to any service.
307
308```nix
309{
310 # Configure ACME however you like (DNS or HTTP validation), adding
311 # the following configuration for the relevant certificate.
312 # Note: You cannot use `systemctl reload` here as that would mean
313 # the LoadCredential configuration below would be skipped and
314 # the service would continue to use old certificates.
315 security.acme.certs."mail.example.com".postRun = ''
316 systemctl restart opensmtpd
317 '';
318
319 # Now you must augment OpenSMTPD's systemd service to load
320 # the certificate files.
321 systemd.services.opensmtpd.requires = [ "acme-mail.example.com.service" ];
322 systemd.services.opensmtpd.serviceConfig.LoadCredential =
323 let
324 certDir = config.security.acme.certs."mail.example.com".directory;
325 in
326 [
327 "cert.pem:${certDir}/cert.pem"
328 "key.pem:${certDir}/key.pem"
329 ];
330
331 # Finally, configure OpenSMTPD to use these certs.
332 services.opensmtpd =
333 let
334 credsDir = "/run/credentials/opensmtpd.service";
335 in
336 {
337 enable = true;
338 setSendmail = false;
339 serverConfiguration = ''
340 pki mail.example.com cert "${credsDir}/cert.pem"
341 pki mail.example.com key "${credsDir}/key.pem"
342 listen on localhost tls pki mail.example.com
343 action act1 relay host smtp://127.0.0.1:10027
344 match for local action act1
345 '';
346 };
347}
348```
349
350## Regenerating certificates {#module-security-acme-regenerate}
351
352Should you need to regenerate a particular certificate in a hurry, such
353as when a vulnerability is found in Let's Encrypt, there is now a convenient
354mechanism for doing so. Running
355`systemctl clean --what=state acme-example.com.service`
356will remove all certificate files and the account data for the given domain,
357allowing you to then `systemctl start acme-example.com.service`
358to generate fresh ones.
359
360## Fixing JWS Verification error {#module-security-acme-fix-jws}
361
362It is possible that your account credentials file may become corrupt and need
363to be regenerated. In this scenario lego will produce the error `JWS verification error`.
364The solution is to simply delete the associated accounts file and
365re-run the affected service(s).
366
367```shell
368# Find the accounts folder for the certificate
369systemctl cat acme-example.com.service | grep -Po 'accounts/[^:]*'
370export accountdir="$(!!)"
371# Move this folder to some place else
372mv /var/lib/acme/.lego/$accountdir{,.bak}
373# Recreate the folder using systemd-tmpfiles
374systemd-tmpfiles --create
375# Get a new account and reissue certificates
376# Note: Do this for all certs that share the same account email address
377systemctl start acme-example.com.service
378```
379
380## Ensuring dependencies for services that need to be reloaded when a certificate challenges {#module-security-acme-reload-dependencies}
381
382Services that depend on ACME certificates and need to be reloaded can use one of two approaches to reload upon successfull certificate acquisition or renewal:
383
3841. **Using the `security.acme.certs.<name>.reloadServices` option**: This will cause `systemctl try-reload-or-restart` to be run for the listed services.
385
3862. **Using a separate reload unit**: if you need perform more complex actions you can implement a separate reload unit but need to ensure that it lists the `acme-renew-<name>.service` unit both as `wantedBy` AND `after`. See the nginx module implementation with its `nginx-config-reload` service.