iptables

常用配置实例

简单配置实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/bin/bash
# 
# iptables example configuration script
# 
# Flush all current rules from iptables
# 
 iptables -F
# 
# Allow SSH connections on tcp port 22
# This is essential when working on remote servers via SSH to prevent locking yourself out of the system
# 
 iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# 
# Set default policies for INPUT, FORWARD and OUTPUT chains
# 
 iptables -P INPUT DROP
 iptables -P FORWARD DROP
 iptables -P OUTPUT ACCEPT
# 
# Set access for localhost
# 
 iptables -A INPUT -i lo -j ACCEPT
# 
# Accept packets belonging to established and related connections
# 
 iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# 
# Save settings
# 
 /sbin/service iptables save
# 
# List rules
# 
 iptables -L -v

centos 上配置 vsftpd

1
2
3
4
5
6
iptables -I INPUT -p tcp --dport 20 -j ACCEPT
iptables -I INPUT -p tcp --dport 21 -j ACCEPT
iptables -I INPUT -p tcp --dport 1024: -m state --state ESTABLISHED,RELATED -j ACCEPT

service iptables save
service iptables restart

配置注意点

  • 同时配置输入链和输出链

注意:当ping一台外部主机时,看上去好像只是输出链在起作用。但是请记住,外部主机返回的数据要经过输入链的过滤。当配置iptables规则时,请牢记许多协议都需要双向通信,所以你需要同时配置输入链和输出链。人们在配置SSH的时候通常会忘记在输入链和输出链都配置它。

INPUT chian 中加入如下规则,可以避免阻挡主机主动连接出去后(OUTPUT 是全开的),阻挡返回信息。

1
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

原理、规则

链的默认行为

当iptables无法匹配现存的规则时,链的默认行为可以通过 --policy-P 配置。

1
2
3
iptables --policy INPUT ACCEPT
iptables --policy OUTPUT ACCEPT
iptables --policy FORWARD ACCEPT

查看链的默认policy: iptables -L | grep policy

规则链内的匹配顺序

  • 按顺序依次检查,匹配即停止(LOG策略例外)
  • 若找不到相匹配的规则,则按该链的默认策略处理

如何修改rule

  1. iptables 的命令修改rules
  2. service iptables save 保存

开放 http 80 端口的例子

1
2
3
4
5
6
7
# 查看下目前状态
iptables -L --line-numbers

# 规则:接受http 80端口,“-I INPUT 1”:插入规则到INPUT Chain的第一行
iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT

service iptables save

开放 协议和端口

  • destination or source ports (–dport or –sport), you must first specify the protocol (tcp, udp, icmp, all).
1
2
# Accept tcp packets on destination port 6881 (bittorrent)
iptables -A INPUT -p tcp --dport 6881 -j ACCEPT
1
2
# Accept tcp packets on destination ports 6881-6890
iptables -A INPUT -p tcp --dport 6881:6890 -j ACCEPT

删除 rule

1
2
3
iptables -L --line-numbers -n
iptables -D INPUT 【在INPUT里面的序号】
service iptables save

delete all rules in a chain

1
2
3
4
5
# delete all of the rules in the INPUT chain
iptables -F INPUT

# Flush All Chains
iptables -F

配置

check the iptables modules are loaded

1
# lsmod | grep ip_tables

inspect the currently loaded rules:

1
iptables -L --line-numbers

enable iptables

1
# system-config-securitylevel
1
# service iptables start / stop / status