当前位置: 首页 > 工具软件 > Nftables > 使用案例 >

nftables脚本例子:过滤和NAT

拓拔麒
2023-12-01
#! /bin/bash

#清空当前规则集:
nft flush ruleset
#查询当前规则集:
nft list ruleset
#添加一个表:
nft add table inet filter

#添加input、forward和output三个基本链。input和forward的默认策略是drop。output的默认策略是accept。
nft add chain inet filter input { type filter hook input priority 0 \; policy drop \; }
nft add chain inet filter forward { type filter hook forward priority 0 \; policy drop \; }
nft add chain inet filter output { type filter hook output priority 0 \; policy accept \; }

#添加两个与TCP和UDP关联的常规链:
nft add chain inet filter TCP
nft add chain inet filter UDP
#related和established的流量会accept:
nft add rule inet filter input ct state related,established accept
#loopback接口的流量会accept:
nft add rule inet filter input iif lo accept
#无效的流量会drop:
nft add rule inet filter input ct state invalid drop
#新的echo请求(ping)会accept:
nft add rule inet filter input ip protocol icmp icmp type echo-request ct state new accept
#新的UDP流量跳转到UDP链:
nft add rule inet filter input ip protocol udp ct state new jump UDP
#新的TCP流量跳转到TCP链:
nft add rule inet filter input ip protocol tcp tcp flags \& \(fin\|syn\|rst\|ack\) == syn ct state new jump TCP

#未由其他规则处理的所有通信会reject:
nft add rule inet filter input ip protocol udp reject
nft add rule inet filter input ip protocol tcp reject with tcp reset
nft add rule inet filter input counter reject with icmp type prot-unreachable

#web服务器的连接端口80:
nft add rule inet filter TCP tcp dport 80 accept
#打开web服务器HTTPS连接端口443:
nft add rule inet filter TCP tcp dport 443 accept
#允许SSH连接端口22:
nft add rule inet filter TCP tcp dport 22 accept



#NAT
#删除规则表 dnat1
#nft delete table ip dnat1 
 
#增加规则表 dnat1
nft add table ip dnat1 
 
#在表dnat1中增加一条链 prerouting [SNAT]
nft add chain dnat1 prerouting { type nat hook prerouting priority 0 \;}
 
#在表dnat1中增加一条链 postrouting [DNAT]
nft add chain dnat1 postrouting { type nat hook postrouting priority 100 \; }
 
#
nft add rule dnat1 prerouting ip daddr 192.168.1.1 tcp dport 80 counter dnat 172.16.1.2:80
nft add fule dnat1 postrouting ip daddr 172.16.1.2 tcp dport 80 counter snat to 172.16.1.1 
#
nft add rule dnat1 prerouting ip saddr 172.16.1.2 tcp sport 80 counter dnat 192.168.1.2
nft add rule dnat1 postrouting ip saddr 172.16.1.2 tcp sport 80 counter snat to 192.168.1.1

 

 类似资料: