about summary refs log tree commit diff
path: root/modules/nixos/unbound.nix
blob: 4d21fd2c073a4573798d61cb8f0bb097e6e5f91e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
{
  config,
  lib,
  pkgs,
  this,
  ...
}:
with lib; let
  cfg = config.nixfiles.modules.unbound;
in {
  options.nixfiles.modules.unbound = {
    enable = mkEnableOption "Unbound";

    domain = mkOption {
      description = "Domain name sans protocol scheme.";
      type = with types; str;
      default = config.networking.domain;
    };
  };

  config = let
    adblock-conf = "${config.services.unbound.stateDir}/adblock.conf";
  in
    mkIf cfg.enable {
      ark.directories = [config.services.unbound.stateDir];

      nixfiles.modules = {
        redis.enable = true;

        promtail.filters = [
          {
            match = {
              # Should be fixed[1] in the next release.
              #
              # [1]: https://github.com/NLnetLabs/unbound/commit/d7e776114114c16816570e48ab3a27eedc401a0e
              selector = ''{syslog_identifier="unbound"} |~ ".*could not SSL_read crypto.*"'';
              action = "drop";
              drop_counter_reason = "noise";
            };
          }
        ];
      };

      services = {
        unbound = {
          enable = true;

          package = pkgs.unbound-with-systemd.override {
            withRedis = true;
            withTFO = true;
          };

          settings = {
            server = {
              interface = with this.wireguard; [
                "127.0.0.1"
                "::1"
                ipv4.address
                ipv6.address
              ];

              local-zone =
                concatLists
                (mapAttrsToList (h: _: [''"${h}.${cfg.domain}" redirect''])
                  my.configurations);
              local-data = concatLists (mapAttrsToList (hostname: let
                domain = "${hostname}.${cfg.domain}";
              in
                attr: (optionals (hasAttr "wireguard" attr) (with attr.wireguard;
                  [
                    ''"${domain} 604800 IN A ${ipv4.address}"''
                    ''"${domain} 604800 IN AAAA ${ipv6.address}"''
                    ''"${domain}. A ${ipv4.address}"''
                    ''"${domain}. AAAA ${ipv6.address}"''
                  ]
                  ++ concatMap (domain: [
                    ''"${domain}. A ${ipv4.address}"''
                    ''"${domain}. AAAA ${ipv6.address}"''
                  ])
                  attr.domains)))
              my.configurations);
              local-data-ptr = concatLists (mapAttrsToList (hostname: let
                domain = "${hostname}.${cfg.domain}";
              in
                attr: (optionals (hasAttr "wireguard" attr) (with attr.wireguard;
                  [
                    ''"${ipv4.address} ${domain}"''
                    ''"${ipv6.address} ${domain}"''
                  ]
                  ++ concatMap (domain: [
                    ''"${ipv4.address} ${domain}"''
                    ''"${ipv6.address} ${domain}"''
                  ])
                  attr.domains)))
              my.configurations);

              private-domain = map (domain: "${domain}.") [
                cfg.domain
                "local"
              ];
              private-address = with config.nixfiles.modules.wireguard; [
                ipv4.subnet
                ipv6.subnet
              ];

              access-control = with config.nixfiles.modules.wireguard; [
                "0.0.0.0/0 refuse"
                "::/0 refuse"
                "127.0.0.0/8 allow"
                "::1/128 allow"
                "${ipv4.subnet} allow"
                "${ipv6.subnet} allow"
              ];

              cache-min-ttl = 0;

              serve-expired = true;
              serve-expired-reply-ttl = 0;

              prefetch = true;
              prefetch-key = true;

              hide-identity = true;
              hide-version = true;

              extended-statistics = true;

              include = ''"${adblock-conf}"'';
            };

            forward-zone = [
              {
                name = ".";
                forward-tls-upstream = true;
                forward-addr = let
                  mkDnsOverTls = ips: auth: map (ip: concatStrings [ip "@" auth]) ips;
                in
                  mkDnsOverTls dns.const.quad9.default "853#dns.quad9.net";
              }
            ];

            cachedb = with config.services.redis.servers.default; {
              backend = "redis";
              redis-server-host = bind;
              redis-server-port = port;
            };
          };

          enableRootTrustAnchor = true;

          localControlSocketPath = "/run/unbound/unbound.socket";
        };

        # TODO Switch to https://github.com/letsencrypt/unbound_exporter.
        prometheus.exporters.unbound = {
          enable = true;
          listenAddress = mkDefault this.wireguard.ipv4.address;
          port = 9167;
          fetchType = "uds";
          controlInterface = config.services.unbound.localControlSocketPath;
          inherit (config.services.unbound) group user;
        };
      };

      systemd = {
        services = {
          unbound.after = ["unbound-adblock-update.service"];

          unbound-adblock-update = {
            serviceConfig = with config.services.unbound; {
              Type = "oneshot";
              User = user;
              Group = group;
              ExecStart = let
                pkg = with pkgs;
                  writeShellApplication {
                    name = "unbound-adblock-update";
                    runtimeInputs = [curl package];
                    text = ''
                      curl -s \
                        "https://pgl.yoyo.org/adservers/serverlist.php?hostformat=unbound&showintro=0&mimetype=plaintext" \
                        >${adblock-conf}

                      if [[ -f "${localControlSocketPath}" ]]; then
                        unbound-control reload
                      fi
                    '';
                  };
              in "${pkg}/bin/unbound-adblock-update";
            };
          };
        };

        timers.unbound-adblock-update = {
          requires = ["network-online.target"];
          timerConfig = {
            OnCalendar = "daily";
            Persistent = true;
            Unit = "unbound-adblock-update.service";
          };
          wantedBy = ["timers.target"];
        };
      };

      boot.kernel.sysctl."net.ipv4.tcp_fastopen" = mkOverride 200 3;
    };
}

Consider giving Nix/NixOS a try! <3