iptables 防火墙
禁用 自带的防火墙
systemctl stop firewalld.service
systemctl disable firewalld.service
firewall-cmd --state
安装 iptables-service 并设置启动
yum install iptables-services -y
systemctl enable iptables.service
开启内核转发
vi /etc/sysctl.conf
添加变量
net.ipv4.ip_forward = 0
保存后,使修改内容生效
sysctl -p
以上 步骤 安装完成
开启常用端口
设置默认策略。也可以全部放开,然后全不禁止
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT
# 接受已经建立连接的或由已经建立的连接所建立的新连接的TCP连接(状态防火墙能识别TCP或者UDP会话非状态防火墙只能根据端口识别,不能识别会话)
# -m state --state <NEW,ESTATBLISHED,INVALID,RELATED>
# 下面设置已经建立的连接允许
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
#ping
iptables -A INPUT -p icmp --icmp-type 8 -j ACCEPT
#允许来自于lo接口的数据包(本地访问)
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# 开放22
#暴力点
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
#效率高点
iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
# 开放80
iptables -A INPUT -p tcp -ms tate --state NEW -m tcp --dport 80 -j ACCEPT
# 开放443
iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT
# 拒绝其他所有端口请求
iptables -A INPUT -J REJECT
# 拒绝其他所有端口请求(--reject-with icmp-host-prohibited用于发送默认拒绝数据包)
-A INPUT -j REJECT --reject-with icmp-host-prohibited
# 拒绝其他所有端口转发(一般不用)
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
NAT转发
方便起见 设置默认策略全部 允许
iptables -t nat -P INPUT ACCEPT
iptables -t nat -P OUTPUT ACCEPT
iptables -t nat -P PREROUTING ACCEPT
iptables -t nat -P POSTROUTING ACCEPT
举例 将 172.17.100.2:111 数据转发到 172.17.100.14:1115上
用指定ip转发
iptables -t nat -A PREROUTING -p tcp -d 172.17.100.2 --dport 1111 -j DNAT --to-destination 172.17.100.14:1115
iptables -t nat -A POSTROUTING -p tcp -s 172.17.100.14 --sport 1115 -j SNAT --to-source 172.17.100.2
用指定网卡转发
iptables -t nat -A PREROUTING -p tcp -i eth0 --dport 1111 -j DNAT --to 172.17.100.14:443
iptables -t nat -A POSTROUTING -j MASQUERADE
iptables -t nat -A PREROUTING -d 192.168.23.252 -p tcp --dport 80 -j DNAT --to-destination 192.168.23.253:80
#如果进来的route的访问目的地址是192.168.23.252并且访问的目的端口是80,就进行dnat转换,把目的地址改为192.168.23.253 ,端口还是80
iptables -t nat -A POSTROUTING -d 192.168.23.253 -p tcp --dport 80 -j SNAT --to 192.168.23.252
#当FORWARD 出来后,访问的目的地址是192.168.23.253,端口是80的。进行snat地址转换,把原地址改为192.168.23.252
iptables -A FORWARD -o eth0 -d 192.168.23.253 -p tcp --dport 80 -j ACCEPT
#当从eth0出去的访问目的地址是 192.168.23.253且目的端口是80的route,允许通过
iptables -A FORWARD -i eth0 -s 192.168.23.253 -p tcp --dport 80 -j ACCEPT
#当从eth0进来的原地址是 192.168.23.253且目的端口是80的route,允许通过
常用命令
systemctl enable iptables.service
systemctl start iptables.service
systemctl restart iptables.service
service iptables save
iptables -L -n
iptables -t nat -L -n --line-number
vi /etc/sysconfig/iptabes