iptables常用规则

常见的服务的iptables规则设置

注意:配置规则时注意协议的双向性

在安全性更高的系统中可以为每一条命令具体指定双方的IP地址。

基本设置

使用脚本配置规则时要首先清空所有规则

同时建议将默认规则设置为DROP,即使用白名单

# flush all rules

iptables -F -t filter
iptables -F -t mangle
iptables -F -t nat

# set default rules

iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

HTTP服务

http服务默认使用tcp协议的80端口

# I.open http port:80

iptables -t filter -A INPUT -p tcp --dport 80 -j ACCEPT

iptables -t filter -A OUTPUT -p tcp --sport 80 -j ACCEPT

ping命令

ping命令使用icmp协议

发送方发送icmp-type=8,即icmp-request, 接收方发送icmp-type=0,即icmp-reply

注意方向性,可以只放行一个方向的ping命令

# II.open ping

# 1. open outbound

iptables -t filter -I INPUT -p icmp --icmp-type 0 -j ACCEPT

iptables -t filter -I OUTPUT -p icmp --icmp-type 8 -j ACCEPT

# 2. open inbound

iptables -t filter -I INPUT -p icmp --icmp-type 8 -j ACCEPT

iptables -t filter -I OUTPUT -p icmp --icmp-type 0 -j ACCEPT

FTP服务

FTP可以按主动模式或者被动模式运行,客户端登录时指定运行模式

统一使用TCP协议,使用21端口发送控制命令。

抓包分析可以发现,FTP的连接和传输过程主要分为三部分:控制连接建立和命令传输,文件传输,控制端口释放。 因此在iptables规则的设计要根据FTP协议的工作方式确定。

主动模式

使用20端口传输数据。

# III.open ftp active

# 1. open control port:21

iptables -t filter -A INPUT -p tcp --dport 21 -j ACCEPT

iptables -t filter -A OUTPUT -p tcp --sport 21 -j ACCEPT

# 2. open data port:20

iptables -t filter -A INPUT -p tcp --dport 20 -j ACCEPT

iptables -t filter -A OUTPUT  -p tcp --sport 20 -j ACCEPT

被动模式

使用随机生成的端口发送数据,端口范围可以在/etc/vsftpd.conf指定。

因此要使用状态监测来放行相关的端口。

# IV.open ftp passive

# 1. open control port:21

iptables -A INPUT -p tcp --dport 21 -j ACCEPT

iptables -A OUTPUT -p tcp --sport 21 -j ACCEPT

# 2. open data port:random port>=1024

iptables -A INPUT -p tcp --sport 1024: --dport 1024: -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT

iptables -A OUTPUT -p tcp --sport 1024: --dport 1024: -m state --state RELATED,ESTABLISHED -j ACCEPT

SSH连接

默认使用TCP协议的22端口。

同样可以只放行一个方向的数据。

# V. open ssh port:22

# 1. open ssh inbound

iptables -A INPUT -p tcp --dport 22 -j ACCEPT

iptables -A OUTPUT -p tcp --sport 22 -m state --state ESTABLISHED,RELATED -j ACCEPT

# 2. open ssh outbound

iptables -A OUTPUT -p tcp --dport 22 -j ACCEPT

iptables -A INPUT -p tcp --sport 22 -m state --state ESTABLISHED,RELATED -j ACCEPT
Lei Yang
Lei Yang
PhD candidate

My research interests include visual speech recognition and semantics segmentation.