]> git.immae.eu Git - perso/Immae/Config/Nix.git/blob - modules/private/certificates.nix
Write peertube flake
[perso/Immae/Config/Nix.git] / modules / private / certificates.nix
1 { lib, pkgs, config, name, ... }:
2 {
3 options.myServices.certificates = {
4 enable = lib.mkEnableOption "enable certificates";
5 webroot = lib.mkOption {
6 readOnly = true;
7 default = "/var/lib/acme/acme-challenges";
8 };
9 certConfig = lib.mkOption {
10 default = {
11 webroot = lib.mkForce null; # avoids creation of tmpfiles
12 email = "ismael@bouya.org";
13 postRun = builtins.concatStringsSep "\n" [
14 (lib.optionalString config.services.httpd.Prod.enable "systemctl reload httpdProd.service")
15 (lib.optionalString config.services.httpd.Tools.enable "systemctl reload httpdTools.service")
16 (lib.optionalString config.services.httpd.Inte.enable "systemctl reload httpdInte.service")
17 (lib.optionalString config.services.nginx.enable "systemctl reload nginx.service")
18 ];
19 extraLegoRenewFlags = [ "--reuse-key" ];
20 keyType = lib.mkDefault "ec256"; # https://github.com/NixOS/nixpkgs/pull/83121
21 };
22 description = "Default configuration for certificates";
23 };
24 };
25
26 config = lib.mkIf config.myServices.certificates.enable {
27 services.duplyBackup.profiles.system.excludeFile = ''
28 + ${config.myServices.certificates.webroot}
29 '';
30 services.nginx = {
31 recommendedTlsSettings = true;
32 virtualHosts = {
33 "${config.hostEnv.fqdn}" = {
34 acmeRoot = config.myServices.certificates.webroot;
35 useACMEHost = name;
36 forceSSL = true;
37 };
38 };
39 };
40 services.websites.certs = config.myServices.certificates.certConfig;
41 myServices.databasesCerts = config.myServices.certificates.certConfig;
42 myServices.ircCerts = config.myServices.certificates.certConfig;
43
44 security.acme.acceptTerms = true;
45 security.acme.preliminarySelfsigned = true;
46
47 security.acme.certs = {
48 "${name}" = config.myServices.certificates.certConfig // {
49 domain = config.hostEnv.fqdn;
50 };
51 };
52
53 users.users.acme = {
54 uid = config.ids.uids.acme;
55 group = "acme";
56 description = "Acme user";
57 };
58 users.groups.acme = {
59 gid = config.ids.gids.acme;
60 };
61
62 systemd.services = lib.attrsets.mapAttrs' (k: v:
63 lib.attrsets.nameValuePair "acme-selfsigned-${k}" {
64 wantedBy = [ "acme-selfsigned-certificates.target" ];
65 script = lib.mkAfter ''
66 cp $workdir/server.crt ${config.security.acme.certs."${k}".directory}/cert.pem
67 chown '${v.user}:${v.group}' ${config.security.acme.certs."${k}".directory}/cert.pem
68 chmod ${if v.allowKeysForGroup then "750" else "700"} ${config.security.acme.certs."${k}".directory}/cert.pem
69
70 cp $workdir/ca.crt ${config.security.acme.certs."${k}".directory}/chain.pem
71 chown '${v.user}:${v.group}' ${config.security.acme.certs."${k}".directory}/chain.pem
72 chmod ${if v.allowKeysForGroup then "750" else "700"} ${config.security.acme.certs."${k}".directory}/chain.pem
73 '';
74 }
75 ) config.security.acme.certs //
76 lib.attrsets.mapAttrs' (k: data:
77 lib.attrsets.nameValuePair "acme-${k}" {
78 after = lib.mkAfter [ "bind.service" ];
79 serviceConfig =
80 let
81 cfg = config.security.acme;
82 hashOptions = let
83 domains = builtins.concatStringsSep "," (
84 [ data.domain ] ++ (builtins.attrNames data.extraDomains)
85 );
86 certOptions = builtins.concatStringsSep "," [
87 (if data.ocspMustStaple then "must-staple" else "no-must-staple")
88 ];
89 in
90 builtins.hashString "sha256" (builtins.concatStringsSep ";" [ data.keyType domains certOptions ]);
91 accountsDir = "accounts-${data.keyType}";
92 lpath = "acme/${k}";
93 apath = "/var/lib/${lpath}";
94 spath = "/var/lib/acme/.lego/${k}";
95 fileMode = if data.allowKeysForGroup then "640" else "600";
96 dirFileMode = if data.allowKeysForGroup then "750" else "700";
97 globalOpts = [ "-d" data.domain "--email" data.email "--path" "." "--key-type" data.keyType ]
98 ++ lib.optionals (cfg.acceptTerms) [ "--accept-tos" ]
99 ++ lib.optionals (data.dnsProvider != null && !data.dnsPropagationCheck) [ "--dns.disable-cp" ]
100 ++ lib.concatLists (lib.mapAttrsToList (name: root: [ "-d" name ]) data.extraDomains)
101 ++ (if data.dnsProvider != null then [ "--dns" data.dnsProvider ] else [ "--http" "--http.webroot" config.myServices.certificates.webroot ])
102 ++ lib.optionals (cfg.server != null || data.server != null) ["--server" (if data.server == null then cfg.server else data.server)];
103 certOpts = lib.optionals data.ocspMustStaple [ "--must-staple" ];
104 runOpts = lib.escapeShellArgs (globalOpts ++ [ "run" ] ++ certOpts);
105 renewOpts = lib.escapeShellArgs (globalOpts ++
106 [ "renew" "--days" (builtins.toString cfg.validMinDays) ] ++
107 certOpts ++ data.extraLegoRenewFlags);
108 forceRenewOpts = lib.escapeShellArgs (globalOpts ++
109 [ "renew" "--days" "999" ] ++
110 certOpts ++ data.extraLegoRenewFlags);
111 keyName = builtins.replaceStrings ["*"] ["_"] data.domain;
112 in {
113 User = lib.mkForce "acme";
114 Group = lib.mkForce "acme";
115 WorkingDirectory = lib.mkForce spath;
116 StateDirectory = lib.mkForce "acme/.lego/${k} acme/.lego/${accountsDir}";
117 ExecStartPre =
118 let
119 script = pkgs.writeScript "acme-prestart" ''
120 #!${pkgs.runtimeShell} -e
121 install -m 0755 -o acme -g acme -d ${config.myServices.certificates.webroot}
122 '';
123 in
124 lib.mkForce "+${script}";
125 ExecStart = lib.mkForce (pkgs.writeScript "acme-start" ''
126 #!${pkgs.runtimeShell} -e
127 # lego doesn't check key type after initial creation, we
128 # need to check for him
129 if [ -L ${spath}/accounts -o -d ${spath}/accounts ]; then
130 if [ -L ${spath}/accounts -a "$(readlink ${spath}/accounts)" != ../${accountsDir} ]; then
131 ln -sfn ../${accountsDir} ${spath}/accounts
132 mv -f ${spath}/certificates/${keyName}.key ${spath}/certificates/${keyName}.key.old
133 fi
134 else
135 ln -s ../${accountsDir} ${spath}/accounts
136 fi
137 # check if domain changed: lego doesn't check by itself
138 if [ ! -e ${spath}/certificates/${keyName}.crt -o ! -e ${spath}/certificates/${keyName}.key -o ! -e "${spath}/accounts/acme-v02.api.letsencrypt.org/${data.email}/account.json" ]; then
139 ${pkgs.lego}/bin/lego ${runOpts}
140 elif [ ! -f ${spath}/currentDomains -o "$(cat ${spath}/currentDomains)" != "${hashOptions}" ]; then
141 ${pkgs.lego}/bin/lego ${forceRenewOpts}
142 else
143 ${pkgs.lego}/bin/lego ${renewOpts}
144 fi
145 '');
146 ExecStartPost =
147 let
148 script = pkgs.writeScript "acme-post-start" ''
149 #!${pkgs.runtimeShell} -e
150 install -m 0755 -o root -g root -d /var/lib/acme
151 install -m 0${dirFileMode} -o ${data.user} -g ${data.group} -d /var/lib/acme/${k}
152 cd /var/lib/acme/${k}
153
154 # Test that existing cert is older than new cert
155 KEY=${spath}/certificates/${keyName}.key
156 KEY_CHANGED=no
157 if [ -e $KEY -a $KEY -nt key.pem ]; then
158 KEY_CHANGED=yes
159 cp -p ${spath}/certificates/${keyName}.key key.pem
160 cp -p ${spath}/certificates/${keyName}.crt fullchain.pem
161 cp -p ${spath}/certificates/${keyName}.issuer.crt chain.pem
162 ln -sf fullchain.pem cert.pem
163 cat key.pem fullchain.pem > full.pem
164 echo -n "${hashOptions}" > ${spath}/currentDomains
165 fi
166
167 chmod ${fileMode} *.pem
168 chown '${data.user}:${data.group}' *.pem
169
170 if [ "$KEY_CHANGED" = "yes" ]; then
171 : # noop in case postRun is empty
172 ${data.postRun}
173 fi
174 '';
175 in
176 lib.mkForce "+${script}";
177 };
178 }
179 ) config.security.acme.certs //
180 {
181 httpdProd = lib.mkIf config.services.httpd.Prod.enable
182 { after = [ "acme-selfsigned-certificates.target" ]; wants = [ "acme-selfsigned-certificates.target" ]; };
183 httpdTools = lib.mkIf config.services.httpd.Tools.enable
184 { after = [ "acme-selfsigned-certificates.target" ]; wants = [ "acme-selfsigned-certificates.target" ]; };
185 httpdInte = lib.mkIf config.services.httpd.Inte.enable
186 { after = [ "acme-selfsigned-certificates.target" ]; wants = [ "acme-selfsigned-certificates.target" ]; };
187 };
188 };
189 }