summaryrefslogtreecommitdiff
path: root/modules/simple-firewall.nix
blob: eda869a49c7cd9ff629445ddd5417052f70a0c1b (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
{ 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.port;
        default = [];
        description = "List of TCP ports to allow";
      };

      allowedTCPPorts = lib.mkOption {
        type = lib.types.listOf lib.types.port;
        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 {
      chain allowed_ports {
        ${lib.optionalString (cfg.allowedTCPPorts != []) ''
        tcp dport {${csvPorts cfg.allowedTCPPorts}} counter accept
        ''}
        ${lib.optionalString (cfg.allowedUDPPorts != []) ''
        udp dport {${csvPorts cfg.allowedUDPPorts}} counter accept
        ''}
      }

      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

        jump allowed_ports

        counter drop
      }

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