summaryrefslogtreecommitdiff
path: root/modules/simple-firewall.nix
blob: 3c69d5d4b7e6a359afa4396bce067323418957d6 (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
{ config, lib, pkgs, ... }:
let
  cfg = config.orbekk.simple-firewall;
in
{
  options = {
    orbekk.simple-firewall = {
      enable = lib.mkEnableOption "Enable nftables firewall";

      allowedUDPPorts = lib.mkOption {
        type = lib.types.listOf lib.types.anything;
        default = [];
        description = "List of TCP ports to allow";
      };

      allowedTCPPorts = lib.mkOption {
        type = lib.types.listOf lib.types.anything;
        default = [];
        description = "List of TCP ports to allow";
      };
    };
  };

  config = lib.mkIf cfg.enable {
    networking.firewall.enable = lib.mkForce false;
    networking.nftables.enable = true;

    networking.nftables.ruleset =
      let
        csvPorts = ports: lib.concatStringsSep "," (map toString ports);
      in ''
      table inet filter {
        set allowed_tcp_ports {
          type inet_service
          flags interval
          ${lib.optionalString (cfg.allowedTCPPorts != [])''
            elements = {${csvPorts cfg.allowedTCPPorts}}
          ''}
        }
        set allowed_udp_ports {
          type inet_service
          flags interval
          ${lib.optionalString (cfg.allowedUDPPorts != [])''
            elements = {${csvPorts cfg.allowedUDPPorts}}
          ''}
        }

        chain input {
          type filter hook input priority 0

          iif lo accept

          ct state {established, related} accept

          ip protocol icmp limit rate 4/second counter accept
          ip6 nexthdr ipv6-icmp limit rate 4/second counter accept

	  ip6 saddr 2001:470:8e2e:1000::/64 counter accept

          tcp dport @allowed_tcp_ports counter accept
          udp dport @allowed_udp_ports counter accept

          counter drop
        }

        chain output {
          type filter hook output priority 0
          counter accept
        }
    }
    '';
  };
}