Files
nixconfig/modules/server/nftables/default.nix
soraefir 1a8eb085df fix db ?
2026-05-08 02:13:44 +02:00

62 lines
2.4 KiB
Nix

{ config, lib, ... }:
let
cfg = config.syscfg.server;
DBlistNames = config.syscfg.server.db;
DBcontainerNames = lib.mapAttrsToList
(name: cfg: name)
(lib.filterAttrs (name: cfg: cfg.db or false) config.syscfg.server.containers);
DBallApps = lib.unique (DBlistNames ++ DBcontainerNames);
in{
boot.kernel.sysctl = {
"net.ipv4.ip_forward" = 1;
"net.ipv6.conf.all.forwarding" = 1;
};
networking.nftables.enable = true;
networking.nftables.ruleset = ''
table inet filter {
chain input {
type filter hook input priority filter; policy drop;
ct state established,related accept
iifname "lo" accept
iifname { "podman*", "veth*" } accept
tcp dport {422, 22} accept
${if builtins.length DBallApps > 0 then ''tcp dport {5432, 6379} accept'' else ""}
${if cfg.web then ''tcp dport {80, 443} accept'' else ""}
${if cfg.web then ''udp dport {80, 443} accept'' else ""}
${if cfg.wireguard then ''tcp dport {1515} accept'' else ""}
${if cfg.wireguard then ''udp dport {1515} accept'' else ""}
}
}
${if cfg.nftables.enable then ''
table inet nat {
chain prerouting {
type nat hook prerouting priority dstnat; policy accept;
${lib.concatMapStringsSep "\n" (rule:
let
srcInt = builtins.elemAt rule 0;
dstAddr4 = builtins.elemAt rule 1;
dstAddr6 = builtins.elemAt rule 2;
srcPort = toString (builtins.elemAt rule 3);
dstPort = toString (builtins.elemAt rule 4);
in ''
iifname "${srcInt}" tcp dport ${srcPort} counter dnat ip to ${dstAddr4}:${dstPort}
iifname "${srcInt}" udp dport ${srcPort} counter dnat ip to ${dstAddr4}:${dstPort}
iifname "${srcInt}" tcp dport ${srcPort} counter dnat ip6 to [${dstAddr6}]:${dstPort}
iifname "${srcInt}" udp dport ${srcPort} counter dnat ip6 to [${dstAddr6}]:${dstPort}
''
) config.syscfg.server.nftables.ports}
}
chain postrouting {
type nat hook postrouting priority srcnat; policy accept;
oifname { ${lib.concatMapStringsSep ", " (iface: ''"${iface}"'') config.syscfg.server.nftables.ifs} } masquerade
}
}'' else ""}
'';
}