[root@server ~]# iptables -F
[root@server ~]# iptables -X
[root@server ~]# iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT # 不允许服务器主动建立新连接
[root@server ~]# iptables -A INPUT -p tcp -m multiport --dport , -m state --state NEW -j ACCEPT # 允许22,80端口的连接和监听
[root@server ~]# iptables -A OUTPUT -p tcp -m multiport --sport 22,80 -j ACCEPT # 允许客户端访问22,80端口
[root@server ~]# iptables -P INPUT DROP # 默认禁止
[root@server ~]# iptables -P FORWARD DROP # 默认禁止
[root@server ~]# iptables -P OUTPUT DROP # 默认禁止
[root@server ~]# iptables -A INPUT -p udp --sport -j ACCEPT # 允许dns服务
[root@server ~]# iptables -A OUTPUT -p udp --dport -j ACCEPT # 允许dns服务
[root@server ~]# iptables -A INPUT -p icmp -j ACCEPT # 开启 icmp协议
[root@server ~]# iptables -A OUTPUT -p icmp -j ACCEPT # 开启 icmp协议
[root@server ~]# service iptables save # 保存配置
iptables: Saving firewall rules to /etc/sysconfig/iptables:[ OK ]
[root@server ~]# service iptables restart
iptables: Setting chains to policy ACCEPT: filter [ OK ]
iptables: Flushing firewall rules: [ OK ]
iptables: Unloading modules: [ OK ]
iptables: Applying firewall rules: [ OK ]
对应一般的简单web服务器基本够用,当然ssh端口肯定会修改,以上命令也进行调整。如果要禁止别人ping服务器,建议进行以下设置:
临时生效:echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all
永久生效:
[root@server ~]# echo "net.ipv4.icmp_echo_ignore_all = 1" >> /etc/sysctl.conf
[root@server ~]# sysctl -p
# Generated by iptables-save v1.4.7 on Mon Mar ::
*filter
:INPUT DROP [:]
:FORWARD DROP [:]
:OUTPUT DROP [:]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m multiport --sports , -m state --state NEW -j ACCEPT
-A INPUT -p udp -m udp --sport -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A OUTPUT -p tcp -m multiport --sports 22,80 -j ACCEPT
-A OUTPUT -p udp -m udp --dport -j ACCEPT
-A OUTPUT -p icmp -j ACCEPT
COMMIT
# Completed on Mon Mar ::
可以直接复制上面iptables配置到vim /etc/sysconfig/iptables 然后重启iptables
关于转发:
因为非root用户不能监听1024以下端口,所以经常使用iptables来进行转发的工作:
iptables -t nat -A PREROUTING -p tcp --dport -j REDIRECT --to-port 8080 # 8080端口映射到80端口
iptables -t nat -A PREROUTING -p tcp --dport -j DNAT --to-destination 192.168.2.11:8080 # 192.168.2.11的8080端口映射到80端口。可用于两台主机转发