iptables
是Linux系统网络流量管理的强力工具。
iptables
规则是即时生效的,无需重启服务或加载配置。因此,必须非常小心,否则会把你自己锁在系统之外。
不要同时运行
firewald
和ipatables
。总是优先应用可以让你进入系统的规则。
1. 列出iptables
规则
# 仅列出行号和规则
$ sudo iptables -L --line-numbers
Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 ACCEPT tcp -- 192.168.1.0/24 anywhere tcp dpt:ssh
2 DROP all -- anywhere anywhere
Chain FORWARD (policy ACCEPT)
num target prot opt source destination
Chain OUTPUT (policy ACCEPT)
num target prot opt source destination
- 行号可用于删除规则
- iptables包含三类规则
- INPUT
- FORWARD - 应用于网络接口之间
- OUTPUT
2. 整理规则顺序
iptables总是从上到下读取规则,找到符合条件的规则即停止。如果规则顺序设置错了,可以通过以下方法整理:
# 1. 导出规则
$ sudo iptables-save > ~/iptables.txt
# 2. 使用文本编辑器修改
# 3. 导入规则
$ sudo iptables-restore < ~/iptables.txt
3. INPUT vs. OUTPUT
-
INPUT规则控制进入系统的网络流量
iptables -I INPUT <other options>
-
OUTPUT规则控制流出系统的网络流量
iptables -I OUTPUT <other options>
4. 添加规则
两种添加规则方式:
- 通过参数
-A
添加到规则底部- 一般都会在规则底部添加一条拒绝所有的规则如下:
sudo iptables -A INPUT -j DROP
- 通过参数
-I
插入到规则顶部sudo iptables -I INPUT -s 192.168.1.0/24 -p tcp --dport 22 -j ACCEPT
5. 删除规则
# 1. 列出带行号的规则
$ sudo iptables -L --line-numbers
Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 ACCEPT tcp -- 192.168.1.0/24 anywhere tcp dpt:ssh
2 DROP all -- anywhere anywhere
Chain FORWARD (policy ACCEPT)
num target prot opt source destination
Chain OUTPUT (policy ACCEPT)
num target prot opt source destination
# 2. 根据行号删除规则
$ sudo iptables -D INPUT 2
6. 导出规则
$ sudo iptables-save > /etc/sysconfig/iptables
iptables规则再重启后会清零,可以将规则导出到文件,然后在重启后重新加载。
7. 标准规则
建议:建立最小白名单规则,然后按需添加必要的规则。
网友评论