Using nftables for routing and access control#

last update 2025/06/30

Overview diagram#

digraph { graph [ overlap = false, charset = "UTF-8",ranksep = 0.4, rankdir = LR ]; node [ shape = box, fontsize = 9, fontname = "Meiryo UI", width = 1.2, margin = 0.0, style = rounded ]; edge [ minlen = 2, labelfloat = false, fontsize = 8, fontname = "Meiryo UI" ]; subgraph sg { N1 [ label = "vpn client", color = darkgray ]; } subgraph cluster_0 { label = "nftables"; N2 [ label = "eth0", color = darkgray ]; N3 [ label = "tun0", color = darkgray ]; N2 -> N3 [ label = "ip masquerade" ]; } subgraph cluster_1 { label = "openvpn"; N4 [ label = "server", color = darkgray ]; } N1 -> N2 [ label = "udp:1194", fontcolor = red ]; N3 -> N4; }

config#

Back up the default config file#

cp -p /etc/sysconfig/nftables.conf /etc/sysconfig/nftables.conf.org

Configuration item#

config

notes

flush ruleset

Remove the existing nftables ruleset as a precaution.

include

Specify the whitelist file.

table ip filter

Include a condition in this part.

set country_accept

Create a named set of IP addresses.

chain INPUT

Inbound traffic is dropped by default.

iifname "lo" counter accept

ループバックはすべて許可

ct state

各通信ごとに許可設定

icmp type

Echo Reply(ping応答), Destination Unreachable, Time Exceeded のみ許可

chain FORWARD

マスカレードに必要なため、forward通信はすべて許可

chain OUTPUT

outbound通信はすべて許可

chain prerouting

chain postrouting

マスカレードする通信元のNICを指定

Configuration#

注釈

■ OpenVPN用の設定
・Filter
・inbound
・lo を許可
・country_whitelistに記載のIPアドレスからのTCPポート22を許可
・country_whitelistに記載のIPアドレスからのUDPポート1194を許可
・icmpを許可
・forward
・マスカレード用にすべて許可
・outbound
・すべて許可
・NAT
・eth0からのマスカレードを設定
/etc/sysconfig/nftables.conf#
 1flush ruleset
 2
 3include "/etc/nftables/country_whitelist"
 4
 5table ip filter {
 6  set country_accept {
 7    type ipv4_addr; flags interval;
 8    elements = $country_whitelist
 9  }
10
11  chain INPUT {
12    type filter hook input priority 0; policy drop;
13    iifname "lo" counter accept
14
15    ct state established,related counter accept
16    ct state new tcp dport 22 ip saddr @country_accept counter accept
17    ct state new udp dport 1194 ip saddr @country_accept counter accept
18
19    icmp type echo-reply counter accept
20    icmp type destination-unreachable counter accept
21    icmp type time-exceeded counter accept
22  }
23  chain FORWARD {
24    type filter hook forward priority 0; policy accept;
25  }
26  chain OUTPUT {
27    type filter hook output priority 0; policy accept;
28  }
29}
30table ip nat {
31  chain prerouting {
32    type nat hook prerouting priority 0;
33  }
34  chain postrouting {
35    type nat hook postrouting priority 0;
36    oifname "eth0" masquerade
37  }
38}

Start nftables#

start nftables#

systemctl enable nftables
systemctl start nftables

Verify the ruleset#

nft list ruleset