iptables配置
filter表:管理本机数据进出(最常用)
nat表:管理NAT映射
mangle表:改变包内容(不常用)
自定义表
常用命令
iptables -L -n
查看filter table的链规则
iptables -t nat -L -n
查看NAT表的链规则
1 2 3 4
| # 清除所有规则 iptables -F iptables -X iptables -Z
|

iptables的工作过程和ACL非常相似,从上到下匹配规则,最后执行预设(默认)的规则
制定防火墙(filter表)规则
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
| -t参数——选择表,如果不用-t,默认使用filter表 -P参数——选择链,在filter中有INPUT OUTPUT FORWARD三个链可选
#设置预设规则,INPUT链预设阻挡,OUTPUT和FORWARD链都预设开启 iptables -P INPUT DROP iptables -P OUTPUT ACCEPT iptables -P FORWARD ACCEPT
#针对ip/网络、网络接口、协议设置过滤规则 参数: -A 添加规则,加入到链最后 -I 添加规则,加入到链第一条 -i 传入的接口(一般用于INPUT) -o 传出的接口(一般用于OUTPUT) -p 指定协议,常用udp tcp icmp all -j ACCEPT接受、DROP丢弃、LOG记录 -m 指定iptables使用的扩展模块,常用tcp -sport 来源端口,可指定范围如1024:10000 -dport 目标端口 iptables [-t tables] [-AI 链] [-io 网络接口] [-p 协议] [-s 来源网段/ip] [-d 目标网段/ip] -j [ACCEPT/DROP/LOG(记录)]
示例: iptables -A INPUT -s 192.168.0.1 -p tcp -m tcp --dport 22 -j ACCEPT iptables -P INPUT DROP ↑只允许192.168.0.1通过ssh连接 iptables -A INPUT -s 192.168.10.0/24 -p tcp -m tcp --dport 80 -j ACCEPT ↑加一条允许一个网段通过80端口访问
#指定网络接口(换回家口) iptables -A INPUT -i lo -j ACCEPT #允许ping iptables -A INPUT -i ens18 -p icmp -j ACCEPT
|
数据状态模块过滤
数据状态模块是iptables特殊的一部分
1 2 3 4 5 6 7 8 9 10
| 参数: -m 模块选项:state状态模块,mac网卡硬件地址 --state 数据封包状态:常用123 1.NEW连接的第一个包 2.ESTABLISHED已建立的连接 3.RELATED和已建立连接关联的连接 4.INVALID无法识别或没有状态(一般禁止) 示例: iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT iptables -A INPUT -m state --state INVALID -j DROP
|
NAT表SNAT操作
现在有两台机器:
A无外网192.168.10.254
B本机
外网IP 192.168 194.113
A添加默认路由指向B
B本机添加规则
iptables -t nat -A POSTROUTING -s 192.168.10.254/32 -j SNAT --to-source 192.168.194.113
↑192.168.10.254对互联网暴露的ip为192.168.194.113