centos7 iptables 操作

3月 17, 2019 |

iptables的设置更接近lvs中的描述,决定还是使用iptables


systemctl disable firewalld
yum install iptables-services
systemctl start iptables
systemctl start ip6tables

cat /etc/sysconfig/iptables
可以看到默认的iptables设置,只开放22端口,如果要开放其他的服务,按这一行设置即可。

*filter //filter 表设置规则
:INPUT ACCEPT [0:0] //INPUT链默认的policy为接受
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
//接受状态RELATED,ESTABLISHED
-A INPUT -p icmp -j ACCEPT //接受icmp报文
-A INPUT -i lo -j ACCEPT //接收lo地址的报文
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
//接收目的端口为22的syn报文,如果我们要开放其他端口,按这一行设置即可
-A INPUT -j REJECT --reject-with icmp-host-prohibited //拒绝input的其他报文
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

注意--dport选项是-m tcp模块中的选项,

iptables 使用mangle表添加log功能

iptables -t mangle  -I PREROUTING -p tcp -m tcp --dport 12345 -j LOG --log-prefix  "[mangle_pre    ]";
iptables -t mangle  -I INPUT      -p tcp -m tcp --dport 12345 -j LOG --log-prefix  "[mangle_input  ]";
iptables -t mangle  -I FORWARD    -p tcp -m tcp --dport 12345 -j LOG --log-prefix  "[mangle_forward]";
iptables -t mangle  -I OUTPUT      -p tcp -m tcp --dport 12345 -j LOG --log-prefix "[mangle_output ]";
iptables -t mangle  -I POSTROUTING -p tcp -m tcp --dport 12345 -j LOG --log-prefix "[mangle_post   ]";

配置kern日志

vim /etc/rsyslog.conf 添加如下配置项
kern.* /var/log/iptables.log
重启日志服务
systemctl restart rsyslog

iptables DNAT 操作

修改目的IP
iptables -t nat -A PREROUTING -p tcp -m tcp --dport 12345 -j DNAT --to-destination 172.18.0.2:80
能通过FORWARD链
iptables -t filter -I FORWARD -d 172.18.0.2/32 ! -i br-6318c70b58f5 -o br-6318c70b58f5 -p tcp -m tcp --dport 80 -j ACCEPT

SNAT

内网服务器

ip addr add 192.168.0.1/24 brd 192.168.0.255 dev ens33
ip route add default via 192.168.0.100/24 ens33
/etc/resolv.conf配置和网关服务器一样,当然也可以直接配置成公网dns,比如114.114.114.114

网关服务器

iptables -t nat -A POSTROUTING -s 192.168.0.0/24 -o ens33 -j MASQUERADE

Chain Traversal Order

Incoming packets destined for the local system: PREROUTING -> INPUT
Incoming packets destined to another host: PREROUTING -> FORWARD -> POSTROUTING
Locally generated packets: OUTPUT -> POSTROUTING

deep-dive-into-iptables

Posted in: Linux

Comments are closed.