在 CentOS 系统中,使用 iptables
设置链策略的步骤如下:
查看当前规则:
在修改任何规则之前,建议先查看当前的 iptables
规则,以便了解现有的配置。
sudo iptables -L -n -v
设置默认策略:
iptables
有五个默认链:INPUT
、FORWARD
和 OUTPUT
,以及自定义链。你可以为每个链设置默认策略,例如 ACCEPT
或 DROP
。
设置 INPUT
链的默认策略为 DROP
:
sudo iptables -P INPUT DROP
设置 FORWARD
链的默认策略为 DROP
:
sudo iptables -P FORWARD DROP
设置 OUTPUT
链的默认策略为 ACCEPT
(通常情况下,我们希望本地主机能够发出流量):
sudo iptables -P OUTPUT ACCEPT
允许必要的流量: 根据你的需求,添加规则以允许特定的流量通过。
允许来自特定 IP 地址的 SSH 连接(假设 SSH 端口为默认的 22):
sudo iptables -A INPUT -p tcp --dport 22 -s 192.168.1.100 -j ACCEPT
允许所有出站 HTTP 和 HTTPS 流量:
sudo iptables -A OUTPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A OUTPUT -p tcp --dport 443 -j ACCEPT
允许已建立的连接和相关流量:
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
保存规则:
默认情况下,iptables
规则在系统重启后会丢失。为了使规则持久化,可以使用 iptables-services
或 firewalld
。
使用 iptables-services
保存规则:
sudo systemctl stop firewalld
sudo systemctl enable iptables
sudo systemctl start iptables
使用 firewalld
保存规则(如果已安装并启用):
sudo firewall-cmd --runtime-to-permanent
验证规则:
最后,再次查看 iptables
规则以确保它们已正确应用。
sudo iptables -L -n -v
通过以上步骤,你可以在 CentOS 系统中使用 iptables
设置链策略,并确保系统安全。