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 = ["acme-example.com.service" "bind.service"]; 214 before = ["acme-example.com.service" "bind.service"]; 215 unitConfig = { 216 ConditionPathExists = "!/var/lib/secrets/dnskeys.conf"; 217 }; 218 serviceConfig = { 219 Type = "oneshot"; 220 UMask = 0077; 221 }; 222 path = [ pkgs.bind ]; 223 script = '' 224 mkdir -p /var/lib/secrets 225 chmod 755 /var/lib/secrets 226 tsig-keygen rfc2136key.example.com > /var/lib/secrets/dnskeys.conf 227 chown named:root /var/lib/secrets/dnskeys.conf 228 chmod 400 /var/lib/secrets/dnskeys.conf 229 230 # extract secret value from the dnskeys.conf 231 while read x y; do if [ "$x" = "secret" ]; then secret="''${y:1:''${#y}-3}"; fi; done < /var/lib/secrets/dnskeys.conf 232 233 cat > /var/lib/secrets/certs.secret << EOF 234 RFC2136_NAMESERVER='127.0.0.1:53' 235 RFC2136_TSIG_ALGORITHM='hmac-sha256.' 236 RFC2136_TSIG_KEY='rfc2136key.example.com' 237 RFC2136_TSIG_SECRET='$secret' 238 EOF 239 chmod 400 /var/lib/secrets/certs.secret 240 ''; 241 }; 242} 243``` 244 245Now you're all set to generate certs! You should monitor the first invocation 246by running `systemctl start acme-example.com.service & 247journalctl -fu acme-example.com.service` and watching its log output. 248 249## Using DNS validation with web server virtual hosts {#module-security-acme-config-dns-with-vhosts} 250 251It is possible to use DNS-01 validation with all certificates, 252including those automatically configured via the Nginx/Apache 253[`enableACME`](#opt-services.nginx.virtualHosts._name_.enableACME) 254option. This configuration pattern is fully 255supported and part of the module's test suite for Nginx + Apache. 256 257You must follow the guide above on configuring DNS-01 validation 258first, however instead of setting the options for one certificate 259(e.g. [](#opt-security.acme.certs._name_.dnsProvider)) 260you will set them as defaults 261(e.g. [](#opt-security.acme.defaults.dnsProvider)). 262 263```nix 264{ 265 # Configure ACME appropriately 266 security.acme.acceptTerms = true; 267 security.acme.defaults.email = "admin+acme@example.com"; 268 security.acme.defaults = { 269 dnsProvider = "rfc2136"; 270 environmentFile = "/var/lib/secrets/certs.secret"; 271 # We don't need to wait for propagation since this is a local DNS server 272 dnsPropagationCheck = false; 273 }; 274 275 # For each virtual host you would like to use DNS-01 validation with, 276 # set acmeRoot = null 277 services.nginx = { 278 enable = true; 279 virtualHosts = { 280 "foo.example.com" = { 281 enableACME = true; 282 acmeRoot = null; 283 }; 284 }; 285 }; 286} 287``` 288 289And that's it! Next time your configuration is rebuilt, or when 290you add a new virtualHost, it will be DNS-01 validated. 291 292## Using ACME with services demanding root owned certificates {#module-security-acme-root-owned} 293 294Some services refuse to start if the configured certificate files 295are not owned by root. PostgreSQL and OpenSMTPD are examples of these. 296There is no way to change the user the ACME module uses (it will always be 297`acme`), however you can use systemd's 298`LoadCredential` feature to resolve this elegantly. 299Below is an example configuration for OpenSMTPD, but this pattern 300can be applied to any service. 301 302```nix 303{ 304 # Configure ACME however you like (DNS or HTTP validation), adding 305 # the following configuration for the relevant certificate. 306 # Note: You cannot use `systemctl reload` here as that would mean 307 # the LoadCredential configuration below would be skipped and 308 # the service would continue to use old certificates. 309 security.acme.certs."mail.example.com".postRun = '' 310 systemctl restart opensmtpd 311 ''; 312 313 # Now you must augment OpenSMTPD's systemd service to load 314 # the certificate files. 315 systemd.services.opensmtpd.requires = ["acme-finished-mail.example.com.target"]; 316 systemd.services.opensmtpd.serviceConfig.LoadCredential = let 317 certDir = config.security.acme.certs."mail.example.com".directory; 318 in [ 319 "cert.pem:${certDir}/cert.pem" 320 "key.pem:${certDir}/key.pem" 321 ]; 322 323 # Finally, configure OpenSMTPD to use these certs. 324 services.opensmtpd = let 325 credsDir = "/run/credentials/opensmtpd.service"; 326 in { 327 enable = true; 328 setSendmail = false; 329 serverConfiguration = '' 330 pki mail.example.com cert "${credsDir}/cert.pem" 331 pki mail.example.com key "${credsDir}/key.pem" 332 listen on localhost tls pki mail.example.com 333 action act1 relay host smtp://127.0.0.1:10027 334 match for local action act1 335 ''; 336 }; 337} 338``` 339 340## Regenerating certificates {#module-security-acme-regenerate} 341 342Should you need to regenerate a particular certificate in a hurry, such 343as when a vulnerability is found in Let's Encrypt, there is now a convenient 344mechanism for doing so. Running 345`systemctl clean --what=state acme-example.com.service` 346will remove all certificate files and the account data for the given domain, 347allowing you to then `systemctl start acme-example.com.service` 348to generate fresh ones. 349 350## Fixing JWS Verification error {#module-security-acme-fix-jws} 351 352It is possible that your account credentials file may become corrupt and need 353to be regenerated. In this scenario lego will produce the error `JWS verification error`. 354The solution is to simply delete the associated accounts file and 355re-run the affected service(s). 356 357```shell 358# Find the accounts folder for the certificate 359systemctl cat acme-example.com.service | grep -Po 'accounts/[^:]*' 360export accountdir="$(!!)" 361# Move this folder to some place else 362mv /var/lib/acme/.lego/$accountdir{,.bak} 363# Recreate the folder using systemd-tmpfiles 364systemd-tmpfiles --create 365# Get a new account and reissue certificates 366# Note: Do this for all certs that share the same account email address 367systemctl start acme-example.com.service 368```