]> git.immae.eu Git - perso/Immae/Config/Nix.git/blob - modules/private/dns.nix
Remove duplicates when generating server list in bind
[perso/Immae/Config/Nix.git] / modules / private / dns.nix
1 { lib, pkgs, config, ... }:
2 {
3 options.myServices.dns.enable = lib.mkEnableOption "enable DNS resolver";
4 config = let
5 # taken from unstable
6 cartesianProductOfSets = attrsOfLists: with lib;
7 lib.foldl' (listOfAttrs: attrName:
8 concatMap (attrs:
9 map (listValue: attrs // { ${attrName} = listValue; }) attrsOfLists.${attrName}
10 ) listOfAttrs
11 ) [{}] (attrNames attrsOfLists);
12 cfg = config.services.bind;
13 keyIncludes = builtins.concatStringsSep "\n" (map (v: "include \"/var/secrets/bind/${v}.key\";") (builtins.attrNames config.myEnv.dns.keys));
14 cartProduct = lib.foldr
15 (s: servers: servers // { ${s.masters} = lib.unique ((servers.${s.masters} or []) ++ [s.keys]); })
16 {}
17 (lib.unique (lib.concatMap (z: cartesianProductOfSets { masters = z.masters or []; keys = z.keys or []; }) config.myEnv.dns.slaveZones));
18 toKeyList = servers: keys: builtins.concatStringsSep "\n" (map (s: ''
19 server ${s} {
20 keys { ${builtins.concatStringsSep ";" keys}; };
21 };
22 '') servers);
23 serverIncludes = builtins.concatStringsSep "\n" (lib.mapAttrsToList (n: toKeyList (lib.flatten (builtins.attrValues config.myEnv.dns.ns."${n}"))) cartProduct);
24 configFile = pkgs.writeText "named.conf" ''
25 include "/etc/bind/rndc.key";
26 controls {
27 inet 127.0.0.1 allow {localhost;} keys {"rndc-key";};
28 };
29
30 acl cachenetworks { ${lib.concatMapStrings (entry: " ${entry}; ") cfg.cacheNetworks} };
31 acl badnetworks { ${lib.concatMapStrings (entry: " ${entry}; ") cfg.blockedNetworks} };
32
33 options {
34 listen-on { ${lib.concatMapStrings (entry: " ${entry}; ") cfg.listenOn} };
35 listen-on-v6 { ${lib.concatMapStrings (entry: " ${entry}; ") cfg.listenOnIpv6} };
36 allow-query { cachenetworks; };
37 blackhole { badnetworks; };
38 forward first;
39 forwarders { ${lib.concatMapStrings (entry: " ${entry}; ") cfg.forwarders} };
40 directory "/var/run/named";
41 pid-file "/var/run/named/named.pid";
42 ${cfg.extraOptions}
43 };
44
45 ${keyIncludes}
46 ${serverIncludes}
47
48 ${cfg.extraConfig}
49
50 ${ lib.concatMapStrings
51 ({ name, file, master ? true, extra ? "", slaves ? [], masters ? [] }:
52 ''
53 zone "${name}" {
54 type ${if master then "master" else "slave"};
55 file "${file}";
56 ${ if lib.lists.length slaves > 0 then
57 ''
58 allow-transfer {
59 ${lib.concatMapStrings (ip: "${ip};\n") slaves}
60 };
61 '' else ""}
62 ${ if lib.lists.length masters > 0 then
63 ''
64 masters {
65 ${lib.concatMapStrings (ip: "${ip};\n") masters}
66 };
67 '' else ""}
68 allow-query { any; };
69 ${extra}
70 };
71 '')
72 cfg.zones }
73 '';
74 mxes = lib.attrsets.filterAttrs
75 (n: v: v.mx.enable)
76 config.myEnv.servers;
77 ip4mxes = builtins.concatStringsSep "\n" (lib.mapAttrsToList
78 (n: v: "${v.mx.subdomain} IN A ${v.ips.main.ip4}")
79 mxes);
80 ip6mxes = builtins.concatStringsSep "\n" (lib.mapAttrsToList
81 (n: v: builtins.concatStringsSep "\n" (map (i: "${v.mx.subdomain} IN AAAA ${i}") v.ips.main.ip6))
82 mxes);
83 mxmxes = n: conf: builtins.concatStringsSep "\n" (lib.mapAttrsToList
84 (_: v: "${n} IN MX ${v.mx.priority} ${v.mx.subdomain}.${conf.name}.")
85 mxes);
86 in lib.mkIf config.myServices.dns.enable {
87 networking.firewall.allowedUDPPorts = [ 53 ];
88 networking.firewall.allowedTCPPorts = [ 53 ];
89 users.users.named.extraGroups = [ "keys" ];
90 secrets.keys = lib.mapAttrsToList (k: v:
91 {
92 dest = "bind/${k}.key";
93 permissions = "0400";
94 user = "named";
95 text = ''
96 key "${k}"
97 {
98 algorithm ${v.algorithm};
99 secret "${v.secret}";
100 };
101 '';
102 }
103 ) config.myEnv.dns.keys;
104 services.bind = {
105 enable = true;
106 cacheNetworks = ["any"];
107 configFile = configFile;
108 extraOptions = ''
109 allow-recursion { 127.0.0.1; };
110 allow-transfer { none; };
111
112 notify-source ${config.myEnv.servers.eldiron.ips.main.ip4};
113 notify-source-v6 ${lib.head config.myEnv.servers.eldiron.ips.main.ip6};
114 version none;
115 hostname none;
116 server-id none;
117 '';
118 zones = with config.myEnv.dns;
119 assert (builtins.substring ((builtins.stringLength soa.email)-1) 1 soa.email) != ".";
120 assert (builtins.substring ((builtins.stringLength soa.primary)-1) 1 soa.primary) != ".";
121 (map (conf: {
122 name = conf.name;
123 master = false;
124 file = "/var/run/named/${conf.name}.zone";
125 masters = if lib.attrsets.hasAttr "masters" conf
126 then lib.lists.flatten (map (n: lib.attrsets.attrValues ns.${n}) conf.masters)
127 else [];
128 }) slaveZones)
129 ++ (map (conf: {
130 name = conf.name;
131 master = true;
132 extra = if lib.attrsets.hasAttr "extra" conf then conf.extra else "";
133 slaves = if lib.attrsets.hasAttr "slaves" conf
134 then lib.lists.flatten (map (n: lib.attrsets.attrValues ns.${n}) conf.slaves)
135 else [];
136 file = pkgs.writeText "${conf.name}.zone" ''
137 $TTL 10800
138 @ IN SOA ${soa.primary}. ${builtins.replaceStrings ["@"] ["."] soa.email}. ${soa.serial} ${soa.refresh} ${soa.retry} ${soa.expire} ${soa.ttl}
139
140 ${lib.concatStringsSep "\n" (map (x: "@ IN NS ${x}.") (lib.concatMap (n: lib.attrsets.mapAttrsToList (k: v: k) ns.${n}) conf.ns))}
141 ${lib.optionalString (conf.withCAA != null) ''
142 ${conf.name}. IN CAA 0 issue "${conf.withCAA}"
143 ''}
144
145 ${conf.entries}
146
147 ${if lib.attrsets.hasAttr "withEmail" conf && lib.lists.length conf.withEmail > 0 then ''
148 ${ip4mxes}
149 ${ip6mxes}
150 ${lib.concatStringsSep "\n\n" (map (e:
151 let
152 n = if e.domain == "" then "@" else "${e.domain} ";
153 suffix = if e.domain == "" then "" else ".${e.domain}";
154 in
155 ''
156 ; ------------------ mail: ${n} ---------------------------
157 ${mxmxes n conf}
158
159 ; https://tools.ietf.org/html/rfc6186
160 _submission._tcp${suffix} SRV 0 1 587 smtp.immae.eu.
161 _submissions._tcp${suffix} SRV 0 1 465 smtp.immae.eu.
162 _imap._tcp${suffix} SRV 0 1 143 imap.immae.eu.
163 _imaps._tcp${suffix} SRV 0 1 993 imap.immae.eu.
164 _pop3._tcp${suffix} SRV 10 1 110 pop3.immae.eu.
165 _pop3s._tcp${suffix} SRV 10 1 995 pop3.immae.eu.
166 _sieve._tcp${suffix} SRV 0 1 4190 imap.immae.eu.
167
168 ; MTA-STS
169 ; https://blog.delouw.ch/2018/12/16/using-mta-sts-to-enhance-email-transport-security-and-privacy/
170 ; https://support.google.com/a/answer/9261504
171 _mta-sts${suffix} IN TXT "v=STSv1;id=20200109150200Z"
172 _smtp._tls${suffix} IN TXT "v=TLSRPTv1;rua=mailto:postmaster+mta-sts@immae.eu"
173 mta-sts${suffix} IN A ${config.myEnv.servers.eldiron.ips.main.ip4}
174 ${builtins.concatStringsSep "\n" (map (i: "mta-sts${suffix} IN AAAA ${i}") config.myEnv.servers.eldiron.ips.main.ip6)}
175
176 ; Mail sender authentications
177 ${n} IN TXT "v=spf1 mx ~all"
178 _dmarc${suffix} IN TXT "v=DMARC1; p=none; adkim=r; aspf=r; fo=1; rua=mailto:postmaster+rua@immae.eu; ruf=mailto:postmaster+ruf@immae.eu;"
179 ${if e.send then ''
180 immae_eu._domainkey${suffix} IN TXT ( "v=DKIM1; k=rsa; s=email; "
181 "p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzl3vLd8W5YAuumC5+ZT9OV7/14Pmh5JYtwyqKI3cfe9NnAqInt3xO4bZ7oqIxRKWN4SD39vm7O/QOvFdBt00ENOOzdP90s5gKw6eIP/4+vPTh0IWltAsmu9B2agzdtWUE7t2xFKIzEn8l9niRE2QYbVaqZv4sub98vY55fIgFoHtjkmNC7325S8fjDJGp6OPbyhAs6Xl5/adjF"
182 "0ko4Y2p6RaxLQfjlS0bxmK4Qg6C14pIXHtzVeqOuWrwApqt5+AULSn97iUtqV/IJlEEjC6DUR44t3C/G0G/k46iFclCqRRi0hdPrOHCtZDbtMubnTN9eaUiNpkXh1WnCflHwtjQwIDAQAB" )
183 eldiron._domainkey${suffix} IN TXT ${config.myEnv.mail.dkim.eldiron.public}
184 '' else ""}
185 '') conf.withEmail)}
186 '' + (if conf.name == "immae.eu" then ''
187 ; ----------------- Accept DMARC reports -------------------
188 ${lib.concatStringsSep "\n" (
189 lib.flatten (
190 map (z: map (e: "${e.domain}${if builtins.stringLength e.domain > 0 then "." else ""}${z.name}._report._dmarc IN TXT \"v=DMARC1;\"") (z.withEmail or [])) masterZones
191 )
192 )}
193 '' else "") else ""}
194 '';
195 }) masterZones);
196 };
197 };
198 }