關於 PHP, Linux, Open Source 及個人生活記載的網誌。
RSS icon
  • Iptables 限制每個 ip 連線數

    Posted on February 18th, 2010 Sam Tang No comments

    如果在 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 可能會建立大量的連線。

    Skip proxy server IP 1.2.3.4 from this kind of limitations:

    /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 的連線。

    In this example, limit the parallel http requests to 20 per class C sized network (24 bit netmask)

    /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


    Leave a reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word