Linux之Iptables简易应用

文档形成时期:2009-2024年
和iptables打交道有15年+了,经过无数实践后,形成一个简易应用文档。
文档主题是简易应用,所以其原理不详述了。
因软件世界之复杂和个人能力之限,难免疏漏和错误,欢迎指正。

文章目录

  • iptables简要说明
  • iptables和firewalld的关系
  • 如何选择防火墙
  • 禁用firewalld
  • 启用iptables
  • 保存经验
    • 通过自定义链并写入开机启动的解决案例
  • 加载内核模块
  • 基本操作
  • 常用模块和参数
    • iprange
    • icmp
    • sport和dport
    • multiport
    • state
    • mac
    • line-numbers
    • limit
    • comment
    • -j 动作
      • SNAT示例
      • DNAT示例
  • 应用案例
    • 通过iptables实现跨地域转发端口
    • LOG示例
    • 调节MTU
    • 简单限速
    • 通过状态模块实现FTP策略
    • 防攻击示例
    • 初始化和默认策略示例
  • 常规简易配置综合脚本范例

iptables简要说明

rhel7以下系列使用iptables,从rhel7开始使用firewalld,但iptables也存在,正因为共同存在,所以常给初用者造成诸多困扰。
rhel8开始firewalld已经与iptables解绑。

iptables和firewalld的关系

在RHEL7里有几种防火墙共存:firewalld、iptables、ebtables,默认是使用firewalld来管理netfilter子系统,不过底层调用的命令仍然是iptables等。

如何选择防火墙

一般来讲:
rhel7或以下,选择iptables;
rhel8或以上,可以采用firewalld,使用iptables也是可以的,但两者选其一即可。
如果有docker、k8s等紧密依赖iptables的环境,建议采用iptables,禁用firewalld,请把这个配置写入新系统初始配置中。
ubuntu22仍然可保持采用iptables。
Linux之Iptables简易应用_第1张图片

禁用firewalld

#停止firewalld服务
systemctl stop firewalld
#禁用firewalld服务
systemctl mask firewalld

启用iptables

yum install -y iptables
yum install -y iptables-services

systemctl enable iptables.service
systemctl start iptables.service

保存经验

默认保存位置:/etc/sysconfig/iptables

两种常见保存方式:

  • 方式一
    service iptables save #安装了iptables套件后才有效,默认保存位置:/etc/sysconfig/iptables,iptables套件配置文件是/etc/sysconfig/iptables-config
  • 方式二
    iptables-save -c > /etc/sysconfig/iptables #没有安装iptables套件也可执行,参数-c是保存计数

保存为不同版本的示例

iptables-save > ipt.v1.0     #版本保存
iptables-restore < ipt.v1.0  #恢复

datetime=$(date +%Y%m%d-%H%M%S)
iptables-save -c > /etc/sysconfig/iptables_${datetime} #以时间为版本保存
iptables-restore -c < /etc/sysconfig/iptables_${datetime}

在多人管理的工作环境中,采用同一脚本去管理iptables是非常推荐的做法,但如果确实混乱不堪,维护好/etc/sysconfig/iptables是最好的选择。参考常规简易配置综合脚本范例

在iptables和firewalld共存的系统,比如rhel7系列,但又没有安装iptables套件,或采用了firewalld和iptables共同管理防火墙,造成了iptables策略混乱,这时候可用iptables-save命令保存策略,不过这时可能更应该考虑采用firewalld去管理iptables

2024年实践中发现,k8s的网络插件calico管理的iptables策略可能造成iptables-save命令也无法完整保存策略,这需要根据生产场景来制定应对方案,以避免重启后策略丢失。

通过自定义链并写入开机启动的解决案例

#!/bin/bash
###################################
# function   iptables防火墙因服务不正常而采用的临时处置
#
# 参考创建或使用示例: mkdir -p /root/sh/log; touch /root/sh/iptables_for_tmp.sh; chmod a+x /root/sh/iptables_for_tmp.sh
#
# if (! grep -q iptables_for_tmp /etc/rc.local); then echo '/root/sh/iptables_for_tmp.sh >> /root/sh/log/iptables_for_tmp.log 2>&1' >> /etc/rc.local; else echo "This script already exists in /etc/rc.local"; fi; chmod a+x /etc/rc.d/rc.local
#
# Change History:
# date        author       note
# 20240105    N        k8s的calico导致防火墙iptables服务无法恢复运行,改用脚本
#
###################################

export LANG=C
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin


# 22端口处理 ###
iptables -F FOR_TMP > /dev/null 2>&1
iptables -D INPUT -j FOR_TMP > /dev/null 2>&1
iptables -X FOR_TMP > /dev/null 2>&1
iptables -N FOR_TMP
iptables -I INPUT -j FOR_TMP

#放通
iptables -I FOR_TMP -s 1.2.3.4 -p tcp --dport 22 -j ACCEPT

#限制
iptables -A FOR_TMP -p tcp --dport 22 -j DROP

#保存
iptables-save -c > /etc/sysconfig/iptables # 执行后保存

if (! grep -q iptables_for_tmp /etc/rc.local); then echo '/root/sh/iptables_for_tmp.sh >> /root/sh/log/iptables_for_tmp.log 2>&1' >> /etc/rc.local; else echo "This script already exists in /etc/rc.local"; fi; chmod a+x /etc/rc.d/rc.local

该脚本可以反复执行,不会产生冗余策略。

加载内核模块

在早期版本的Linux内核,iptables的NAT,一般不能使用FTP的20端口,可以使用下面命令加载模块
insmod /lib/modules/2.6.18-164.el5/kernel/net/ipv4/netfilter/ip_conntrack_ftp.ko
insmod /lib/modules/2.6.18-164.el5/kernel/net/ipv4/netfilter/ip_nat_ftp.ko
或使用modprobe命令加载(推荐modprobe,因为insmod不解决依赖关系)
允许NAT转换FTP的跟踪连接,如下:
modprobe ip_nat_ftp
允许本机FTP的跟踪连接,这样就不必设置允许20和被动端口了
modprobe ip_conntrack_ftp

脚本中常用配置:

modules="ip_conntrack_ftp ip_conntrack_irc ip_nat_pptp ip_gre ip_conntrack_pptp ip_conntrack_proto_gre"
for mod in $modules
do
    testmod=`lsmod | grep "${mod}"`
    if [ "$testmod" == "" ]; then
        modprobe $mod
    fi
done

基于近些年Linux内核版本的系统,比如rhel6+,还未仔细分析过是否默认支持上述模块,没有的话,可以根据业务场景选择是否加载。

基本操作

iptables规则执行顺序是从上到下,前面的匹配后就不再看后面的。
基本语法:
iptables [-t table] -[AD] chain rule-specification [options]
iptables [-t table] -I chain [rulenum] rule-specification [options]
iptables [-t table] -R chain rulenum rule-specification [options]
iptables [-t table] -D chain rulenum [options]
iptables [-t table] -[LFZ] [chain] [options]
iptables [-t table] -N chain
iptables [-t table] -X [chain]
iptables [-t table] -P chain target [options]
iptables [-t table] -E old-chain-name new-chain-name

iptables -A 添加一条规则到末尾
iptables -D 删除
iptables -I 插入一条规则到最前面
iptables -R 替换
iptables -vnL 列表
iptables -vnL --line-numbers 列表时同时显示策略号,方便更新局部策略,而不需要重新配置所有策略。

常用模块和参数

iprange

–src-range ip-ip Match source IP in the specified range.
–dst-range ip-ip
例:
-m iprange --src-range 192.168.10.2-192.168.10.6
iptables -I INPUT -m iprange --src-range 192.168.10.2-192.168.10.6 -p tcp --dport 22 -j ACCEPT

icmp

-p icmp --icmp-type 类型 ping: type 8 pong: type 0

sport和dport

-p tcp
-p udp
–sport 和–dport 必须配合-p 参数使用

multiport

   This  module  matches  a set of source or destination ports.  Up to 15 ports can be specified.  A port range (port:port) counts as two
   ports.  It can only be used in conjunction with -p tcp or -p udp.

   --source-ports [!] port[,port[,port:port...]]
          Match if the source port is one of the given ports.  The flag --sports is a convenient alias for this option.

   --destination-ports [!] port[,port[,port:port...]]
          Match if the destination port is one of the given ports.  The flag --dports is a convenient alias for this option.

   --ports [!] port[,port[,port:port...]]
          Match if either the source or destination ports are equal to one of the given ports.

例:
-p tcp -m multiport --dports 20,21,22

state

-m state --state 状态 状态:NEW、RELATED、ESTABLISHED、INVALID
NEW:有别于tcp 的syn
ESTABLISHED:连接态
RELATED:衍生态,与conntrack 关联(比如FTP常用)
INVALID:不能被识别属于哪个连接或没有任何状态

mac

mac --mac-source [!] address
        Match source MAC address.  It must be of the form XX:XX:XX:XX:XX:XX.  Note that this only makes sense for packets  coming  from
        an Ethernet device and entering the PREROUTING, FORWARD or INPUT chains.

line-numbers

--line-numbers
              When listing rules, add line numbers to the beginning of each rule, corresponding to that rule's position in the chain.

limit

   This module matches at a limited rate using a token bucket filter.  A rule using this extension will match until this limit is reached
   (unless the flag is used).  It can be used in combination with the LOG target to give limited logging, for example.

   --limit rate
          Maximum average matching rate: specified as a number, with an optional second minute hour or day suffix;  the
          default is 3/hour.
   注意:
   limit 英语上看是限制的意思,但实际上只是按一定速率去匹配而已,要想限制的话后面要再跟一条DROP,但使用下面这条就不必了。

   --limit-burst number
          Maximum  initial  number  of  packets  to  match: this number gets recharged by one every time the limit specified above is not
          reached, up to this number; the default is 5.

comment

   Allows you to add comments (up to 256 characters) to any rule.
   --comment comment
   Example:
          iptables -A INPUT -s 192.168.0.0/16 -m comment --comment "A privatized IP block"

-j 动作

-j有如下动作:
DROP 丢弃
ACCEPT 接受
LOG 记入日志,默认是message
–log-tcp-options :记录tcp header的相关资讯
–log-ip-options :记录ip header的相关资讯
RETURN 返回父链,例:假设一个包进入了INPUT 链,匹配了某条target 为–jump EXAMPLE_CHAIN 规则,然后进入了子链EXAMPLE_CHAIN。在子链中又匹配了某条规则,恰巧target 是–jump RETURN,那包就返回INPUT 链了。如果在INPUT链里又遇到了–jump RETURN,那这个包就要交由缺省的策略来处理了。
SNAT 更换源地址,NAT
DNAT 更换目的地址,NAT
MASQUERADE 伪装为-o选项指定的网卡上的IP,比SNAT和DNAT负载稍高

SNAT示例

通常用于客户端上外网
iptables -t nat -A POSTROUTING -s 192.168.0.0/255.255.255.0 -d 1.2.3.0/255.255.255.0 -j SNAT --to-source 192.168.1.2
特别注意192.168.1.2是本系统的出站网口IP,通过ip a可以查看到

DNAT示例

通常用于服务器端口的发布
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to X.X.X.X:8080

应用案例

通过iptables实现跨地域转发端口

iptables端口代理,做到像nginx,haproxy一样转发TCP请求,但是它不能关心应用层的东西,比机主机头,没有超时时间限制,除非网络不稳定

开启系统路由

echo "1" > /proc/sys/net/ipv4/ip_forward

或者修改/etc/sysctl.conf
net.ipv4.ip_forward = 1
然后执行sysctl -p 永久生效

添加nat策略到转发服务器iptables主脚本(假设通过脚本管理iptables且有一个主脚本),在转发服务器添加,示例如下

iptables -t nat -P PREROUTING ACCEPT
iptables -t nat -P OUTPUT ACCEPT
iptables -t nat -P POSTROUTING ACCEPT
iptables -t nat -F PREROUTING
iptables -t nat -F POSTROUTING
iptables -t nat -A PREROUTING -i eth0 -d 转发服务器本机系统ip -p tcp -m multiport --dport 80,8080 -j DNAT --to-destination 目标服务器公网ip
iptables -t nat -A POSTROUTING -o eth0 -d 目标服务器公网ip -p tcp -m multiport --dport 80,8080 -j SNAT --to-source 转发服务器本机系统ip

运行防火墙主脚本

LOG示例

iptables -A INPUT -s x.x.x.x -j LOG --log-tcp-options --log-ip-options --log-prefix '[IPTABLES IMLOG] : ’

调节MTU

iptables -A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1400:1536 -j TCPMSS --clamp-mss-to-pmtu

简单限速

-A FORWARD -m limit -d 192.168.0.2 --limit 86/sec -j ACCEPT # 这句意思是限定每秒只转发86个到达192.168.0.2的数据包(约每秒128KB 一个数据包是1.5KB)

-A FORWARD -d 192.168.0.2 -j DROP #这句作用是超过限制的到达192.168.0.2的数据包不通过)
上面两条同时应用才有效。

通过状态模块实现FTP策略

对于FTP,如果有允许状态RELATED,ESTABLISHED的规则,并加载了ip_conntrack_ftp模块
就不必再单独允许20和被动端口,如:
modprobe ip_conntrack_ftp
modprobe ip_nat_ftp
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -s -p tcp --dport 21 -j ACCEPT

防攻击示例

丢弃坏的TCP包
[root@tp ~]#iptables -A FORWARD -p TCP ! --syn -m state --state NEW -j DROP

处理IP碎片数量,防止攻击,允许每秒100个,-f就是指定碎片包
[root@tp ~]#iptables -A FORWARD -f -m limit --limit 100/s --limit-burst 100 -j ACCEPT

设置ICMP包过滤,允许每秒1个包,限制触发条件是10个包.
[root@tp ~]#iptables -A FORWARD -p icmp -m limit --limit 1/s --limit-burst 10 -j ACCEPT
我在前面只所以允许ICMP包通过,就是因为我在这里有限制.

限制 ping (echo-request) 传入的速度
限制前, 可正常每 0.2 秒 ping 一次
ping your.linux.ip -i 0.2

限制每秒只接受一个 icmp echo-request 封包
iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s --limit-burst 1 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-request -j Drop
–limit 1/s 表示每秒一次; 1/m 则为每分钟一次
–limit-burst 表示允许触发 limit 限制的最大次数

限制 ssh 连入频率
建立自订 Chain, 限制 tcp 连线每分钟一次, 超过者触发 Log 记录 (记录在 /var/log/messages)
iptables -N ratelimit
iptables -A ratelimit -p tcp -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A ratelimit -p tcp --syn -m limit --limit 1/m --limit-burst 1 -j ACCEPT
iptables -A ratelimit -p tcp -j LOG --log-level “NOTICE” --log-prefix “[RATELIMIT]”
iptables -A ratelimit -p tcp -j Drop

引用自定义Chain, 限制 ssh (tcp port 22) 连入频率
iptables -A INPUT -p tcp --dport 22 -s 192.168.0.0/16 -j ACCEPT (特定 IP 来源不受限制)
iptables -A INPUT -p tcp --dport 22 -j ratelimit
结合sshd_config设定
LoginGraceTime 30 密码输入时限为 30 秒
MaxAuthTries 2 最多只能输入 3 次密码

防治 SYN-Flood 碎片攻击
iptables -N syn-flood
iptables -A syn-flood -m limit --limit 100/s --limit-burst 150 -j RETURN
iptables -A syn-flood -j DROP
iptables -I INPUT -j syn-flood

控制单个IP的最大并发连接数
iptables -I INPUT -p tcp --dport 80 -m connlimit --connlimit-above 30 -j REJECT #允许单个IP的最大连接数为 30
iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 16 --connlimit-mask 24 -j REJECT

控制单个IP在一定的时间(比如60秒)内允许新建立的连接数
iptables -A INPUT -p tcp --dport 80 -m recent --name BAD_HTTP_ACCESS --update --seconds 60 --hitcount 30 -j REJECT
iptables -A INPUT -p tcp --dport 80 -m recent --name BAD_HTTP_ACCESS --set -j ACCEPT
#单个IP在60秒内只允许最多新建30个连接

iptables也有缓存cc或ddos攻击的能力,但现如果很多cc和ddos都不是iptables能解决的,这里就略了。

初始化和默认策略示例

初始化(不会影响默认策略)
iptables -F 清空规则
iptables -X 清除自定义规则链
iptables -Z 将所有chain计数归零

默认策略,通过iptables -A或-I等是不会改变默认策略的。
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT

iptables -t nat -P PREROUTING ACCEPT
iptables -t nat -P OUTPUT ACCEPT
iptables -t nat -P POSTROUTING ACCEPT
iptables -t nat -F
iptables -t nat -X

常规简易配置综合脚本范例

一个非常简易通用适用于大部分场景的基础脚本,基于此广泛应用于rhel5-rhel9系列和ubuntu系列的数千台系统,有充分的实践过程,可靠且易于维护。
在有docker或k8s的环境中,建议基于此改用自定义链维护自定义策略,在本文通过自定义链并写入开机启动的解决案例中有采用自定义链的方式可参考。

#!/bin/bash
###################################
# function iptables 常用linux防火墙主脚本 默认阻止所有,允许部分
#
# create: touch /root/sh/iptables.sh; chmod 700 /root/sh/iptables.sh
#
# Change History:
# 2009/12/09 N create
# 2017/08/03 N improve
###################################


######### ENV #################
export LANG=C
#export LC_ALL=C
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

###### filter table ################
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -F
iptables -X

###### INPUT chains ######

# 20190618 TCP的远程拒绝服务漏洞临时解决措施
iptables -I INPUT -p tcp --tcp-flags SYN SYN -m tcpmss --mss 1:500 -j DROP -m comment --comment "TCP的远程拒绝服务漏洞临时解决措施"

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

### ICMP ###
iptables -A INPUT -p icmp -m icmp --icmp-type any -m limit --limit 20/s -j ACCEPT

### web ###
iptables -A INPUT -p tcp -m state --state NEW -m multiport --dport 80,443 --tcp-flags SYN,RST,ACK SYN -j ACCEPT

### mon ###
# zabbix
iptables -A INPUT -s 1.2.3.4 -p tcp --dport 10050 -j ACCEPT
 
### Trust Network #################
adminiplistdata_array=(
'1.2.3.4 VPN1'
'1.2.3.5 VPN2'
)
# 注意:上面是模拟二维数组,确保每行有两个“元素”,并用单引号包住。
for adminipdata in "${adminiplistdata_array[@]}"
do
    adminip=`echo $adminipdata | awk '{ print $1; }'`
    adminip_comment=`echo $adminipdata | awk '{ print $2; }'`
    iptables -A INPUT -s $adminip -p tcp -m multiport --dport 20,21,22,3306 -j ACCEPT -m comment --comment "$adminip_comment"
done
 
### global ###
iptables -A INPUT -j DROP

###### save ####################
iptables-save -c > /etc/sysconfig/iptables
iptables-save -c > /etc/sysconfig/iptables_$(date +%Y%m%d-%H%M%S)

该脚本可以反复执行,不会产生冗余策略。

你可能感兴趣的:(Linux系统运维,#,BashShell,网络信息安全,linux,运维,服务器,安全)