A small stateful nftables ruleset

A starting point for filtering IPv4 and IPv6 traffic on a server.

An inet table can apply one set of firewall rules to IPv4 and IPv6. This example groups the rules in a file so they can be inspected and loaded together.

#!/usr/sbin/nft -f
flush ruleset

table inet filter {
  set mgmt4 { type ipv4_addr; flags interval; elements = { 10.10.10.0/24 } }

  chain input {
    type filter hook input priority filter; policy drop;
    ct state established,related accept
    ct state invalid drop
    iif lo accept
    meta l4proto { icmp, ipv6-icmp } accept
    tcp dport 22 ip saddr @mgmt4 accept
    tcp dport { 80, 443 } accept
    limit rate 5/minute log prefix "nft-drop: " level info
  }
  chain forward { type filter hook forward priority filter; policy drop; }
  chain output  { type filter hook output priority filter; policy accept; }
}

Applying and inspecting the rules

  • Leave room for ICMP. Dropping path MTU discovery messages can break traffic that otherwise looks healthy. See the MTU note.
  • Check syntax first. Use nft -c -f /etc/nftables.conf. Keep an out-of-band console or a tested way to restore the previous ruleset during remote changes.
  • Look at counters. Place counter before accept and inspect it with nft list chain inet filter input.
  • Review other rule owners. If Docker or another service installs rules, replacing the entire ruleset also affects those tables.