实验背景
CentOS7.x 默认使用firewalld服务,防火墙daemon服务为firewalld
如果我们需要使用iptables,并使得通过iptables语法设置的防火墙策略开机自启,怎么办?
一、创建防火墙策略文件
# iptables-save -t raw > /etc/iptables.rules
# iptables-save -t mangle >> /etc/iptables.rules
# iptables-save -t nat >> /etc/iptables.rules
# iptables-save -t filter >> /etc/iptables.rules
# vim /etc/iptables.rules
将filter默认策略改为DROP,只放行特定端口
################################################################
# Generated by iptables-save v1.4.21 on Thu Aug 23 00:21:51 2018
*raw
:PREROUTING ACCEPT [68:4504]
:OUTPUT ACCEPT [37:3732]
COMMIT
# Completed on Thu Aug 23 00:21:51 2018
# Generated by iptables-save v1.4.21 on Thu Aug 23 00:22:18 2018
*mangle
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT
# Completed on Thu Aug 23 00:22:18 2018
# Generated by iptables-save v1.4.21 on Thu Aug 23 00:22:32 2018
*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT
# Completed on Thu Aug 23 00:22:32 2018
# Generated by iptables-save v1.4.21 on Thu Aug 23 00:22:53 2018
*filter
:INPUT DROP [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -p tcp -m tcp --dport 22 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 3306 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 2018 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
COMMIT
# Completed on Thu Aug 23 00:22:53 2018
################################################################
二、创建iptables的service文件
# vim /etc/systemd/system/iptables.service
#######################################
[Unit]
Description=iptables rules service
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/sbin/iptables-restore /etc/iptables.rules
ExecStop=/usr/sbin/iptables -P INPUT ACCEPT
ExecStop=/usr/sbin/iptables -F
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
#######################################
三、关闭selinux
# setenforce 0
# sed -i 's/^SELINUX=.*/SELINUX=permissive/g' /etc/selinux/config
四、启动并设置服务为开机自启
# systemctl daemon-reload
# systemctl start iptables.service
# systemctl enable iptables.service
# systemctl status iptables.service
五、查看加载的防火墙策略
# iptables -nvL --line
六、关闭防火墙,清空策略
# systemctl stop iptables.service
# systemctl status iptables.service
# iptables -nvL --line
七、参考
CentOS7上的防火墙设置简明教程
https://www.jianshu.com/p/8e53f12fda66
关于 Active: active (exited)
https://www.jianshu.com/p/57368ee79761
https://wiki.archlinux.org/index.php/systemd_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)
https://www.freedesktop.org/software/systemd/man/systemd.service.html#Type=
CentOS 7 NFS服务器和客户端设置
https://www.jianshu.com/p/06f50049e761
iptables防火墙配置和使用详解
https://www.cnblogs.com/heiye123/p/7816729.html
Iptables Tutorial 1.2.2
https://www.frozentux.net/iptables-tutorial/iptables-tutorial.html#REDIRECTTARGET
防火墙和iptables
https://www.cnblogs.com/f-ck-need-u/p/7397146.html#3912974