aboutsummaryrefslogtreecommitdiff
path: root/modules/system/firewall.nix
blob: 289f635752b5ccc5bc2a2d566ff0b21de39716c8 (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
{ config, lib, ... }:

let
  inherit (builtins) length toString replaceStrings;
  inherit (lib) flatten concatMapStringsSep optionalString splitString mkOption;
  inherit (lib.types) listOf int either submodule enum str;

  inherit (config.nixsap.system.firewall) whitelist;

  iptablesAllow = { dport, protocol, source, comment, ... }:
    let
      ports = concatMapStringsSep "," toString (flatten [dport]);
      iptables = if 1 < length (splitString ":" source)
                 then "ip6tables" else "iptables";
    in "${iptables} -w -A nixos-fw -m multiport "
     + "-p ${protocol} --dport ${ports} -s ${source} -j nixos-fw-accept"
     + optionalString (comment != "")
      " -m comment --comment '${replaceStrings ["'"] ["'\\''"] comment} '";

in {
  options.nixsap.system.firewall.whitelist = mkOption {
    description = "Inbound connection rules (whitelist)";
    default = [];
    type = listOf (submodule {
      options = {
        dport = mkOption {
          description = "Destination port or list of ports";
          type = either int (listOf int);
        };
        source = mkOption {
          description = "Source specification: a network IP address (with optional /mask)";
          type = str;
        };
        protocol = mkOption {
          description = "The network protocol";
          type = enum [ "tcp" "udp" ];
          default = "tcp";
        };
        comment = mkOption {
          description = "Free-form comment";
          type = str;
          default = "";
        };
      };
    });
  };

  config = {
    networking.firewall.extraCommands =
      concatMapStringsSep "\n" iptablesAllow whitelist;
  };
}