Linux 技术手札

Iptables 限制每个 ip 连线数

如果在 Linux 下要限制每个 ip 的连线数,可以透过 iptables 实现。详细指令语法如下:

/sbin/iptables -A INPUT -p tcp –syn –dport 22 -m connlimit –connlimit-above 3 -j REJECT
限制每个 ip 只可以有 3 个 ssh 连线 (默认 ssh 使用 port 22)。

/sbin/iptables -A INPUT -p tcp –syn –dport 80 -m connlimit –connlimit-above 20 -j REJECT –reject-with tcp-reset
只接受每个 ip 20 个 http 连线 (httpd.conf 里面的 MaxClients 默认是 60)。
要留意的是,这个设定可能会把 proxy servers 阻隔,因为每个 proxy servers 可能会建立大量的连线。

/sbin/iptables -A INPUT -p tcp –syn –dport 80 -d ! 1.2.3.4 -m connlimit –connlimit-above 20 -j REJECT –reject-with tcp-reset
这句的作用跟上面语法一样,只是把已知的 proxy server (1.2.3.4) 给开通,避免阻隔 proxy servers 的连线。

/sbin/iptables -A INPUT -p tcp –syn –dport 80 -m connlimit –connlimit-above 20 –connlimit-mask 24 -j REJECT –reject-with tcp-reset
这个是限制同一个 class C 网络同时建立 20 个连线。

如果想把在指定时间内建立过多连线的 ip 阻隔,这便要编辑 iptables 的 shell script。
以下例子会阻隔在 100 秒内建立多于 10 个 http 连线的 ip

#!/bin/bash
IPT=/sbin/iptables
# Max connection in seconds
SECONDS=100
# Max connections per IP
BLOCKCOUNT=10
# ….
# ..
# default action can be DROP or REJECT
DACTION=”DROP”
$IPT -A INPUT -p tcp –dport 80 -i eth0 -m state –state NEW -m recent –set
$IPT -A INPUT -p tcp –dport 80 -i eth0 -m state –state NEW -m recent –update –seconds ${SECONDS} –hitcount ${BLOCKCOUNT} -j ${DACTION}
# ….
# ..

要储存 iptables 的修改可以查看 iptables-save 的 man page,在 redhat 下是用以下指令:
service iptables save

Exit mobile version