summaryrefslogtreecommitdiffstats
path: root/nixos/modules/services/networking/pihole-ftl.nix
blob: 00d931781ece59a188f1c232d4b58f16d81a03cc (plain)
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
{
  config,
  lib,
  pkgs,
  ...
}:

with {
  inherit (lib)
    elemAt
    getExe
    getExe'
    hasAttrByPath
    mkEnableOption
    mkIf
    mkOption
    strings
    types
    ;
};

let
  mkDefaults = lib.mapAttrsRecursive (n: v: lib.mkDefault v);

  cfg = config.services.pihole-ftl;

  piholeScript = pkgs.writeScriptBin "pihole" ''
    sudo=exec
    if [[ "$USER" != '${cfg.user}' ]]; then
      sudo='exec /run/wrappers/bin/sudo -u ${cfg.user}'
    fi
    $sudo ${getExe cfg.piholePackage} "$@"
  '';

  settingsFormat = pkgs.formats.toml { };
  settingsFile = settingsFormat.generate "pihole.toml" cfg.settings;
in
{
  options.services.pihole-ftl = {
    enable = mkEnableOption "Pi-hole FTL";

    package = lib.mkPackageOption pkgs "pihole-ftl" { };
    piholePackage = lib.mkPackageOption pkgs "pihole" { };

    privacyLevel = mkOption {
      type = types.numbers.between 0 3;
      description = ''
        Level of detail in generated statistics. 0 enables full statistics, 3
        shows only anonymous statistics.

        See [the documentation](https://docs.pi-hole.net/ftldns/privacylevels).

        Also see services.dnsmasq.settings.log-queries to completely disable
        query logging.
      '';
      default = 0;
      example = 3;
    };

    openFirewallDNS = mkOption {
      type = types.bool;
      default = false;
      description = "Open ports in the firewall for pihole-FTL's DNS server.";
    };

    openFirewallDHCP = mkOption {
      type = types.bool;
      default = false;
      description = "Open ports in the firewall for pihole-FTL's DHCP server.";
    };

    openFirewallWebserver = mkOption {
      type = types.bool;
      default = false;
      description = ''
        Open ports in the firewall for pihole-FTL's webserver, as configured in `settings.webserver.port`.
      '';
    };

    configDirectory = mkOption {
      type = types.path;
      default = "/etc/pihole";
      internal = true;
      readOnly = true;
      description = ''
        Path for pihole configuration.
        pihole does not currently support any path other than /etc/pihole.
      '';
    };

    stateDirectory = mkOption {
      type = types.path;
      default = "/var/lib/pihole";
      description = ''
        Path for pihole state files.
      '';
    };

    logDirectory = mkOption {
      type = types.path;
      default = "/var/log/pihole";
      description = "Path for Pi-hole log files";
    };

    settings = mkOption {
      type = settingsFormat.type;
      description = ''
        Configuration options for pihole.toml.
        See the upstream [documentation](https://docs.pi-hole.net/ftldns/configfile).
      '';
    };

    useDnsmasqConfig = mkOption {
      type = types.bool;
      default = false;
      description = ''
        Import options defined in [](#opt-services.dnsmasq.settings) via
        misc.dnsmasq_lines in Pi-hole's config.
      '';
    };

    macvendorURL = mkOption {
      type = types.str;
      default = "https://ftl.pi-hole.net/macvendor.db";
      description = ''
        URL from which to download the macvendor.db file.
      '';
    };

    pihole = mkOption {
      type = types.package;
      default = piholeScript;
      internal = true;
      description = "Pi-hole admin script";
    };

    lists =
      let
        adlistType = types.submodule {
          options = {
            url = mkOption {
              type = types.str;
              description = "URL of the domain list";
            };
            type = mkOption {
              type = types.enum [
                "allow"
                "block"
              ];
              default = "block";
              description = "Whether domains on this list should be explicitly allowed, or blocked";
            };
            enabled = mkOption {
              type = types.bool;
              default = true;
              description = "Whether this list is enabled";
            };
            description = mkOption {
              type = types.str;
              description = "Description of the list";
              default = "";
            };
          };
        };
      in
      mkOption {
        type = with types; listOf adlistType;
        description = "Deny (or allow) domain lists to use";
        default = [ ];
        example = [
          {
            url = "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts";
          }
        ];
      };

    user = mkOption {
      type = types.str;
      default = "pihole";
      description = "User to run the service as.";
    };

    group = mkOption {
      type = types.str;
      default = "pihole";
      description = "Group to run the service as.";
    };

    queryLogDeleter = {
      enable = mkEnableOption "Pi-hole FTL DNS query log deleter";

      age = mkOption {
        type = types.int;
        default = 90;
        description = ''
          Delete DNS query logs older than this many days, if
          [](#opt-services.pihole-ftl.queryLogDeleter.enable) is on.
        '';
      };

      interval = mkOption {
        type = types.str;
        default = "weekly";
        description = ''
          How often the query log deleter is run. See systemd.time(7) for more
          information about the format.
        '';
      };
    };

    webserverEnabled = mkOption {
      type = types.bool;
      default = (
        (hasAttrByPath [ "webserver" "port" ] cfg.settings)
        && !builtins.elem cfg.settings.webserver.port [
          ""
          null
        ]
      );
      internal = true;
      description = "Whether the webserver is enabled.";
    };
  };

  config = mkIf cfg.enable {
    assertions = [
      {
        assertion = !config.services.dnsmasq.enable;
        message = "pihole-ftl conflicts with dnsmasq. Please disable one of them.";
      }

      {
        assertion = builtins.length cfg.lists == 0 || cfg.webserverEnabled;
        message = ''
          The Pi-hole webserver must be enabled for lists set in services.pihole-ftl.lists to be automatically loaded on startup via the web API.
          services.pihole-ftl.settings.port must be defined, e.g. by enabling services.pihole-web.enable and defining services.pihole-web.port.
        '';
      }

      {
        assertion =
          builtins.length cfg.lists == 0
          || !(hasAttrByPath [ "webserver" "api" "cli_pw" ] cfg.settings)
          || cfg.settings.webserver.api.cli_pw == true;
        message = ''
          services.pihole-ftl.settings.webserver.api.cli_pw must be true for lists set in services.pihole-ftl.lists to be automatically loaded on startup.
          This enables an ephemeral password used by the pihole command.
        '';
      }
    ];

    services.pihole-ftl.settings = lib.mkMerge [
      # Defaults
      (mkDefaults {
        misc.readOnly = true; # Prevent config changes via API or CLI by default
        webserver.port = ""; # Disable the webserver by default
        misc.privacylevel = cfg.privacyLevel;
      })

      # Move state files to cfg.stateDirectory
      {
        # TODO: Pi-hole currently hardcodes dhcp-leasefile this in its
        # generated dnsmasq.conf, and we can't override it
        misc.dnsmasq_lines = [
          # "dhcp-leasefile=${cfg.stateDirectory}/dhcp.leases"
          # "hostsdir=${cfg.stateDirectory}/hosts"
        ];

        files = {
          database = "${cfg.stateDirectory}/pihole-FTL.db";
          gravity = "${cfg.stateDirectory}/gravity.db";
          macvendor = "${cfg.stateDirectory}/macvendor.db";
          log.ftl = "${cfg.logDirectory}/FTL.log";
          log.dnsmasq = "${cfg.logDirectory}/pihole.log";
          log.webserver = "${cfg.logDirectory}/webserver.log";
        };

        webserver.tls.cert = "${cfg.stateDirectory}/tls.pem";
      }

      (lib.optionalAttrs cfg.useDnsmasqConfig {
        misc.dnsmasq_lines = lib.pipe config.services.dnsmasq.configFile [
          builtins.readFile
          (lib.strings.splitString "\n")
          (builtins.filter (s: s != ""))
        ];
      })
    ];

    systemd.tmpfiles.rules = [
      "d ${cfg.configDirectory} 0700 ${cfg.user} ${cfg.group} - -"
      "d ${cfg.stateDirectory} 0700 ${cfg.user} ${cfg.group} - -"
      "d ${cfg.logDirectory} 0700 ${cfg.user} ${cfg.group} - -"
    ];

    systemd.services = {
      pihole-ftl =
        let
          setupService = config.systemd.services.pihole-ftl-setup.name;
        in
        {
          description = "Pi-hole FTL";

          after = [ "network.target" ];
          before = [ setupService ];

          wantedBy = [ "multi-user.target" ];
          wants = [ setupService ];

          environment = {
            # Currently unused, but allows the service to be reloaded
            # automatically when the config is changed.
            PIHOLE_CONFIG = settingsFile;

            # pihole is executed by the /actions/gravity API endpoint
            PATH = lib.mkForce (
              lib.makeBinPath [
                cfg.piholePackage
              ]
            );
          };

          serviceConfig = {
            Type = "simple";
            User = cfg.user;
            Group = cfg.group;
            AmbientCapabilities = [
              "CAP_NET_BIND_SERVICE"
              "CAP_NET_RAW"
              "CAP_NET_ADMIN"
              "CAP_SYS_NICE"
              "CAP_IPC_LOCK"
              "CAP_CHOWN"
              "CAP_SYS_TIME"
            ];
            ExecStart = "${getExe cfg.package} no-daemon";
            Restart = "on-failure";
            RestartSec = 1;
            # Hardening
            NoNewPrivileges = true;
            PrivateTmp = true;
            PrivateDevices = true;
            DevicePolicy = "closed";
            ProtectSystem = "strict";
            ProtectHome = "read-only";
            ProtectControlGroups = true;
            ProtectKernelModules = true;
            ProtectKernelTunables = true;
            ReadWritePaths = [
              cfg.configDirectory
              cfg.stateDirectory
              cfg.logDirectory
            ];
            RestrictAddressFamilies = "AF_UNIX AF_INET AF_INET6 AF_NETLINK";
            RestrictNamespaces = true;
            RestrictRealtime = true;
            RestrictSUIDSGID = true;
            MemoryDenyWriteExecute = true;
            LockPersonality = true;
          };
        };

      pihole-ftl-setup = {
        description = "Pi-hole FTL setup";
        enable = builtins.length cfg.lists > 0;

        # Wait for network so lists can be downloaded
        after = [ "network-online.target" ];
        requires = [ "network-online.target" ];
        serviceConfig = {
          Type = "oneshot";
          User = cfg.user;
          Group = cfg.group;

          # Hardening
          NoNewPrivileges = true;
          PrivateTmp = true;
          PrivateDevices = true;
          DevicePolicy = "closed";
          ProtectSystem = "strict";
          ProtectHome = "read-only";
          ProtectControlGroups = true;
          ProtectKernelModules = true;
          ProtectKernelTunables = true;
          ReadWritePaths = [
            cfg.configDirectory
            cfg.stateDirectory
            cfg.logDirectory
          ];
          RestrictAddressFamilies = "AF_UNIX AF_INET AF_INET6 AF_NETLINK";
          RestrictNamespaces = true;
          RestrictRealtime = true;
          RestrictSUIDSGID = true;
          MemoryDenyWriteExecute = true;
          LockPersonality = true;
        };
        script = import ./pihole-ftl-setup-script.nix {
          inherit
            cfg
            config
            lib
            pkgs
            ;
        };
      };

      pihole-ftl-log-deleter = mkIf cfg.queryLogDeleter.enable {
        description = "Pi-hole FTL DNS query log deleter";
        serviceConfig = {
          Type = "oneshot";
          User = cfg.user;
          Group = cfg.group;
          # Avoid creating an empty database file if it doesn't yet exist
          ConditionFileNotEmpty = cfg.settings.files.database;
          ExecStart =
            let
              days = toString cfg.queryLogDeleter.age;
              database = cfg.settings.files.database;
            in
            [
              "${getExe' pkgs.coreutils "echo"} 'Deleting query logs older than ${days} days'"
              "${getExe cfg.package} sqlite3 '${database}' 'DELETE FROM query_storage WHERE timestamp <= CAST(strftime('%s', date('now', '-${days} day')) AS INT); select changes() from query_storage limit 1'"
            ];
          # Hardening
          NoNewPrivileges = true;
          PrivateTmp = true;
          PrivateDevices = true;
          DevicePolicy = "closed";
          ProtectSystem = "strict";
          ProtectHome = "read-only";
          ProtectControlGroups = true;
          ProtectKernelModules = true;
          ProtectKernelTunables = true;
          ReadWritePaths = [ cfg.stateDirectory ];
          RestrictAddressFamilies = "AF_UNIX AF_INET AF_INET6 AF_NETLINK";
          RestrictNamespaces = true;
          RestrictRealtime = true;
          RestrictSUIDSGID = true;
          MemoryDenyWriteExecute = true;
          LockPersonality = true;
        };
      };
    };

    systemd.timers.pihole-ftl-log-deleter = mkIf cfg.queryLogDeleter.enable {
      description = "Pi-hole FTL DNS query log deleter";
      before = [
        config.systemd.services.pihole-ftl.name
        config.systemd.services.pihole-ftl-setup.name
      ];
      wantedBy = [ "timers.target" ];
      timerConfig = {
        OnCalendar = cfg.queryLogDeleter.interval;
        Unit = "pihole-ftl-log-deleter.service";
      };
    };

    networking.firewall = lib.mkMerge [
      (mkIf cfg.openFirewallDNS {
        allowedUDPPorts = [ 53 ];
        allowedTCPPorts = [ 53 ];
      })

      (mkIf cfg.openFirewallDHCP {
        allowedUDPPorts = [ 67 ];
      })

      (mkIf cfg.openFirewallWebserver {
        allowedTCPPorts = lib.pipe cfg.settings.webserver.port [
          (lib.splitString ",")
          (map (
            port:
            lib.pipe port [
              (builtins.split "[[:alpha:]]+")
              builtins.head
              lib.toInt
            ]
          ))
        ];
      })
    ];

    users.users.${cfg.user} = {
      group = cfg.group;
      isSystemUser = true;
    };

    users.groups.${cfg.group} = { };

    environment.etc = {
      "pihole/pihole.toml" = {
        source = settingsFile;
        user = cfg.user;
        group = cfg.group;
        mode = "400";
      };

      "pihole/versions".text = ''
        CORE_VERSION=${cfg.piholePackage.src.src.tag}
        FTL_VERSION=${cfg.package.src.tag}
      '';
    };

    environment.systemPackages = [ cfg.pihole ];

    services.logrotate.settings = {
      pihole-dnsmasq = {
        files = [ "${cfg.logDirectory}/pihole.log" ];
        frequency = "daily";
        create = "640 ${cfg.user} ${cfg.group}";
        rotate = 5;
        compress = true;
        delaycompress = true;
        # FTL keeps this log open; SIGUSR2 closes and reopens it after rotation.
        # https://docs.pi-hole.net/ftldns/signals/#sigusr2
        postrotate = ''
          ${getExe' pkgs.systemd "systemctl"} kill --kill-whom=main --signal=USR2 pihole-ftl.service 2>/dev/null || true
        '';
      };

      pihole-ftl = {
        files = [
          "${cfg.logDirectory}/FTL.log"
          "${cfg.logDirectory}/webserver.log"
        ];
        frequency = "weekly";
        create = "640 ${cfg.user} ${cfg.group}";
        rotate = 3;
        compress = true;
        delaycompress = true;
      };
    };
  };

  meta = {
    doc = ./pihole-ftl.md;
    maintainers = with lib.maintainers; [ averyvigolo ];
  };
}