@@ -1,7 +1,5 @@
11{ config, lib, pkgs, ... }:
2−
32with lib;
4−
53let
64
75 cfg = config.security.acme;
@@ -9,7 +7,8 @@ let
97 certOpts = { name, ... }: {
108 options = {
119 webroot = mkOption {
12− type = types.str;
10+ type = types.nullOr types.str;
11+ default = null;
1312 example = "/var/lib/acme/acme-challenges";
1413 description = ''
1514 Where the webroot of the HTTP vhost is located.
@@ -38,7 +37,7 @@ let
3837
3938 email = mkOption {
4039 type = types.nullOr types.str;
41− default = null;
40+ default = cfg.email;
4241 description = "Contact email address for the CA to be able to reach you.";
4342 };
4443
@@ -76,20 +75,6 @@ let
7675 '';
7776 };
7877
79− plugins = mkOption {
80− type = types.listOf (types.enum [
81− "cert.der" "cert.pem" "chain.pem" "external.sh"
82− "fullchain.pem" "full.pem" "key.der" "key.pem" "account_key.json" "account_reg.json"
83− ]);
84− default = [ "fullchain.pem" "full.pem" "key.pem" "account_key.json" "account_reg.json" ];
85− description = ''
86− Plugins to enable. With default settings simp_le will
87− store public certificate bundle in <filename>fullchain.pem</filename>,
88− private key in <filename>key.pem</filename> and those two previous
89− files combined in <filename>full.pem</filename> in its state directory.
90− '';
91− };
92−
9378 directory = mkOption {
9479 type = types.str;
9580 readOnly = true;
@@ -111,6 +96,46 @@ let
11196 own server roots if needed.
11297 '';
11398 };
99+
100+ keyType = mkOption {
101+ type = types.str;
102+ default = "ec384";
103+ description = ''
104+ Key type to use for private keys.
105+ For an up to date list of supported values check the --key-type option
106+ at https://go-acme.github.io/lego/usage/cli/#usage.
107+ '';
108+ };
109+
110+ dnsProvider = mkOption {
111+ type = types.nullOr types.str;
112+ default = null;
113+ example = "route53";
114+ description = ''
115+ DNS Challenge provider. For a list of supported providers, see the "code"
116+ field of the DNS providers listed at https://go-acme.github.io/lego/dns/.
117+ '';
118+ };
119+
120+ credentialsFile = mkOption {
121+ type = types.path;
122+ description = ''
123+ Path to an EnvironmentFile for the cert's service containing any required and
124+ optional environment variables for your selected dnsProvider.
125+ To find out what values you need to set, consult the documentation at
126+ https://go-acme.github.io/lego/dns/ for the corresponding dnsProvider.
127+ '';
128+ example = "/var/src/secrets/example.org-route53-api-token";
129+ };
130+
131+ dnsPropagationCheck = mkOption {
132+ type = types.bool;
133+ default = true;
134+ description = ''
135+ Toggles lego DNS propagation check, which is used alongside DNS-01
136+ challenge to ensure the DNS entries required are available.
137+ '';
138+ };
114139 };
115140 };
116141
@@ -130,14 +155,21 @@ in
130155 (mkRemovedOptionModule [ "security" "acme" "directory"] "ACME Directory is now hardcoded to /var/lib/acme and its permisisons are managed by systemd. See https://github.com/NixOS/nixpkgs/issues/53852 for more info.")
131156 (mkRemovedOptionModule [ "security" "acme" "preDelay"] "This option has been removed. If you want to make sure that something executes before certificates are provisioned, add a RequiredBy=acme-\${cert}.service to the service you want to execute before the cert renewal")
132157 (mkRemovedOptionModule [ "security" "acme" "activationDelay"] "This option has been removed. If you want to make sure that something executes before certificates are provisioned, add a RequiredBy=acme-\${cert}.service to the service you want to execute before the cert renewal")
158+ (mkChangedOptionModule [ "security" "acme" "validMin"] [ "security" "acme" "validMinDays"] (config: config.security.acme.validMin / (24 * 3600)))
133159 ];
134160 options = {
135161 security.acme = {
136162
137− validMin = mkOption {
163+ validMinDays = mkOption {
138164 type = types.int;
139− default = 30 * 24 * 3600;
140− description = "Minimum remaining validity before renewal in seconds.";
165+ default = 30;
166+ description = "Minimum remaining validity before renewal in days.";
167+ };
168+
169+ email = mkOption {
170+ type = types.nullOr types.str;
171+ default = null;
172+ description = "Contact email address for the CA to be able to reach you.";
141173 };
142174
143175 renewInterval = mkOption {
@@ -173,6 +205,15 @@ in
173205 '';
174206 };
175207
208+ acceptTerms = mkOption {
209+ type = types.bool;
210+ default = false;
211+ description = ''
212+ Accept the CA's terms of service. The default provier is Let's Encrypt,
213+ you can find their ToS at https://letsencrypt.org/repository/
214+ '';
215+ };
216+
176217 certs = mkOption {
177218 default = { };
178219 type = with types; attrsOf (submodule certOpts);
@@ -204,27 +245,55 @@ in
204245 config = mkMerge [
205246 (mkIf (cfg.certs != { }) {
206247
248+ assertions = let
249+ certs = (mapAttrsToList (k: v: v) cfg.certs);
250+ in [
251+ {
252+ assertion = all (certOpts: certOpts.dnsProvider == null || certOpts.webroot == null) certs;
253+ message = ''
254+ Options `security.acme.certs.<name>.dnsProvider` and
255+ `security.acme.certs.<name>.webroot` are mutually exclusive.
256+ '';
257+ }
258+ {
259+ assertion = cfg.email != null || all (certOpts: certOpts.email != null) certs;
260+ message = ''
261+ You must define `security.acme.certs.<name>.email` or
262+ `security.acme.email` to register with the CA.
263+ '';
264+ }
265+ {
266+ assertion = cfg.acceptTerms;
267+ message = ''
268+ You must accept the CA's terms of service before using
269+ the ACME module by setting `security.acme.acceptTerms`
270+ to `true`. For Let's Encrypt's ToS see https://letsencrypt.org/repository/
271+ '';
272+ }
273+ ];
274+
207275 systemd.services = let
208276 services = concatLists servicesLists;
209277 servicesLists = mapAttrsToList certToServices cfg.certs;
210278 certToServices = cert: data:
211279 let
280+ # StateDirectory must be relative, and will be created under /var/lib by systemd
212281 lpath = "acme/${cert}";
282+ apath = "/var/lib/${lpath}";
283+ spath = "/var/lib/acme/.lego";
213284 rights = if data.allowKeysForGroup then "750" else "700";
214− cmdline = [ "-v" "-d" data.domain "--default_root" data.webroot "--valid_min" cfg.validMin ]
215− ++ optionals (data.email != null) [ "--email" data.email ]
216− ++ concatMap (p: [ "-f" p ]) data.plugins
217− ++ concatLists (mapAttrsToList (name: root: [ "-d" (if root == null then name else "${name}:${root}")]) data.extraDomains)
285+ globalOpts = [ "-d" data.domain "--email" data.email "--path" "." "--key-type" data.keyType ]
286+ ++ optionals (cfg.acceptTerms) [ "--accept-tos" ]
287+ ++ optionals (data.dnsProvider != null && !data.dnsPropagationCheck) [ "--dns.disable-cp" ]
288+ ++ concatLists (mapAttrsToList (name: root: [ "-d" name ]) data.extraDomains)
289+ ++ (if data.dnsProvider != null then [ "--dns" data.dnsProvider ] else [ "--http" "--http.webroot" data.webroot ])
218290 ++ optionals (cfg.server != null || data.server != null) ["--server" (if data.server == null then cfg.server else data.server)];
291+ runOpts = escapeShellArgs (globalOpts ++ [ "run" ]);
292+ renewOpts = escapeShellArgs (globalOpts ++ [ "renew" "--days" (toString cfg.validMinDays) ]);
219293 acmeService = {
220294 description = "Renew ACME Certificate for ${cert}";
221295 after = [ "network.target" "network-online.target" ];
222296 wants = [ "network-online.target" ];
223− # simp_le uses requests, which uses certifi under the hood,
224− # which doesn't respect the system trust store.
225− # At least in the acme test, we provision a fake CA, impersonating the LE endpoint.
226− # REQUESTS_CA_BUNDLE is a way to teach python requests to use something else
227− environment.REQUESTS_CA_BUNDLE = "/etc/ssl/certs/ca-certificates.crt";
228297 serviceConfig = {
229298 Type = "oneshot";
230299 # With RemainAfterExit the service is considered active even
@@ -233,18 +302,37 @@ in
233302 # the permissions of the StateDirectory get adjusted
234303 # according to the specified group
235304 RemainAfterExit = true;
236− SuccessExitStatus = [ "0" "1" ];
237305 User = data.user;
238306 Group = data.group;
239307 PrivateTmp = true;
240− StateDirectory = lpath;
308+ StateDirectory = "acme/.lego ${lpath}";
241309 StateDirectoryMode = rights;
242− WorkingDirectory = "/var/lib/${lpath}";
243− ExecStart = "${pkgs.simp_le}/bin/simp_le ${escapeShellArgs cmdline}";
310+ WorkingDirectory = spath;
311+ # Only try loading the credentialsFile if the dns challenge is enabled
312+ EnvironmentFile = if data.dnsProvider != null then data.credentialsFile else null;
313+ ExecStart = pkgs.writeScript "acme-start" ''
314+ #!${pkgs.runtimeShell} -e
315+ ${pkgs.lego}/bin/lego ${renewOpts} || ${pkgs.lego}/bin/lego ${runOpts}
316+ '';
244317 ExecStartPost =
245318 let
319+ keyName = builtins.replaceStrings ["*"] ["_"] data.domain;
246320 script = pkgs.writeScript "acme-post-start" ''
247321 #!${pkgs.runtimeShell} -e
322+ cd ${apath}
323+
324+ # Test that existing cert is older than new cert
325+ KEY=${spath}/certificates/${keyName}.key
326+ if [ -e $KEY -a $KEY -nt key.pem ]; then
327+ cp -p ${spath}/certificates/${keyName}.key key.pem
328+ cp -p ${spath}/certificates/${keyName}.crt cert.pem
329+ cp -p ${spath}/certificates/${keyName}.issuer.crt chain.pem
330+ cat cert.pem chain.pem > fullchain.pem
331+ cat key.pem cert.pem chain.pem > full.pem
332+ chmod ${rights} *.pem
333+ chown '${data.user}:${data.group}' *.pem
334+ fi
335+
248336 ${data.postRun}
249337 '';
250338 in
@@ -276,17 +364,17 @@ in
276364 -out $workdir/server.crt
277365
278366 # Copy key to destination
279− cp $workdir/server.key /var/lib/${lpath}/key.pem
367+ cp $workdir/server.key ${apath}/key.pem
280368
281369 # Create fullchain.pem (same format as "simp_le ... -f fullchain.pem" creates)
282− cat $workdir/{server.crt,ca.crt} > "/var/lib/${lpath}/fullchain.pem"
370+ cat $workdir/{server.crt,ca.crt} > "${apath}/fullchain.pem"
283371
284372 # Create full.pem for e.g. lighttpd
285− cat $workdir/{server.key,server.crt,ca.crt} > "/var/lib/${lpath}/full.pem"
373+ cat $workdir/{server.key,server.crt,ca.crt} > "${apath}/full.pem"
286374
287375 # Give key acme permissions
288− chown '${data.user}:${data.group}' "/var/lib/${lpath}/"{key,fullchain,full}.pem
289− chmod ${rights} "/var/lib/${lpath}/"{key,fullchain,full}.pem
376+ chown '${data.user}:${data.group}' "${apath}/"{key,fullchain,full}.pem
377+ chmod ${rights} "${apath}/"{key,fullchain,full}.pem
290378 '';
291379 serviceConfig = {
292380 Type = "oneshot";
@@ -297,7 +385,7 @@ in
297385 };
298386 unitConfig = {
299387 # Do not create self-signed key when key already exists
300− ConditionPathExists = "!/var/lib/${lpath}/key.pem";
388+ ConditionPathExists = "!${apath}/key.pem";
301389 };
302390 };
303391 in (
@@ -309,8 +397,7 @@ in
309397 servicesAttr;
310398
311399 systemd.tmpfiles.rules =
312− flip mapAttrsToList cfg.certs
313− (cert: data: "d ${data.webroot}/.well-known/acme-challenge - ${data.user} ${data.group}");
400+ map (data: "d ${data.webroot}/.well-known/acme-challenge - ${data.user} ${data.group}") (filter (data: data.webroot != null) (attrValues cfg.certs));
314401
315402 systemd.timers = flip mapAttrs' cfg.certs (cert: data: nameValuePair
316403 ("acme-${cert}")
@@ -334,7 +421,7 @@ in
334421 ];
335422
336423 meta = {
337− maintainers = with lib.maintainers; [ abbradar fpletz globin ];
424+ maintainers = with lib.maintainers; [ abbradar fpletz globin m1cr0man ];
338425 doc = ./acme.xml;
339426 };
340427}