iptables基础配置

last modified : 2017-06-07 | published: 2017-06-04 | category:

ChangeLog

# 2017.04

1. 基础命令

查看现有配置

默认filter

iptables -nvL --line-numbers

nat

iptables -t nat -nvL --line-numbers

-A和-I的区别

添加一条规则到尾部:

iptables -A INPUT -s 192.168.1.5 -j DROP

插入一条规则到第三行,将行数直接写到规则链的后面:

iptables -I INPUT 3 -s 192.168.1.3 -j DROP

删除用-D参数

iptables -D INPUT 14

清空已有的iptables

iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -t nat -F
iptables -t mangle -F
iptables -F
iptables -X

2. 常用配置 (INPUT方向)

允许 ping

iptables -A INPUT -p icmp -j ACCEPT

允许已建立的或相关连的通行

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

对loopback访问不限制

iptables -A INPUT -i lo -j ACCEPT

允许ssh

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

避免暴力破解和端口扫描,一般需要安装fail2ban。

apt install fail2ban

允许来自Cloudflare的http/https流量

iptables -N CLOUDFLARE
iptables -t filter -A CLOUDFLARE -p tcp -m multiport --dports http,https -s 199.27.128.0/21 -j ACCEPT
iptables -t filter -A CLOUDFLARE -p tcp -m multiport --dports http,https -s 173.245.48.0/20 -j ACCEPT
iptables -t filter -A CLOUDFLARE -p tcp -m multiport --dports http,https -s 103.21.244.0/22 -j ACCEPT
iptables -t filter -A CLOUDFLARE -p tcp -m multiport --dports http,https -s 103.22.200.0/22 -j ACCEPT
iptables -t filter -A CLOUDFLARE -p tcp -m multiport --dports http,https -s 103.31.4.0/22 -j ACCEPT
iptables -t filter -A CLOUDFLARE -p tcp -m multiport --dports http,https -s 141.101.64.0/18 -j ACCEPT
iptables -t filter -A CLOUDFLARE -p tcp -m multiport --dports http,https -s 108.162.192.0/18 -j ACCEPT
iptables -t filter -A CLOUDFLARE -p tcp -m multiport --dports http,https -s 190.93.240.0/20 -j ACCEPT
iptables -t filter -A CLOUDFLARE -p tcp -m multiport --dports http,https -s 188.114.96.0/20 -j ACCEPT
iptables -t filter -A CLOUDFLARE -p tcp -m multiport --dports http,https -s 197.234.240.0/22 -j ACCEPT
iptables -t filter -A CLOUDFLARE -p tcp -m multiport --dports http,https -s 198.41.128.0/17 -j ACCEPT
iptables -t filter -A CLOUDFLARE -p tcp -m multiport --dports http,https -s 162.158.0.0/15 -j ACCEPT
iptables -t filter -A CLOUDFLARE -p tcp -m multiport --dports http,https -s 104.16.0.0/12 -j ACCEPT
iptables -A INPUT -i eth0 -j CLOUDFLARE

默认策略

全局禁止(重要),相当于cisco路由器最后配置的deny tcp any any

iptables -P INPUT DROP

全局允许(默认,不安全)

iptables -P INPUT ACCEPT

永久保存iptables

debian/ubuntu

安装iptables-persistent

apt install iptables-persistent

保存ipv4:

iptables-save > /etc/iptables/rules.v4

保存ipv6:

ip6tables-save > /etc/iptables/rules.v6

恢复ipv4:

iptables-restore < /etc/sysconfig/iptables

centos/rhel

保存

service iptables save