使用 firewalld 限制同一 IP 單位時間內之連線數

為了限制同一個 IP 在單位時間內之連線數量,可以運用 iptables 來達成。CentOS 7 之後,改成使用 firewalld 來管理 iptables,當然依然可以使用 iptables 指令來處理,但還是想了解一下如何利用 firewalld 來做到。

IPv4 指令如下:

firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT_direct 0 -p tcp --dport 22 -m state --state NEW -m recent --set
firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT_direct 1 -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 300 --hitcount 4 -j DROP
firewall-cmd --reload

IPv6 指令如下:

firewall-cmd --permanent --direct --add-rule ipv6 filter INPUT_direct 0 -p tcp --dport 22 -m state --state NEW -m recent --set
firewall-cmd --permanent --direct --add-rule ipv6 filter INPUT_direct 1 -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 300 --hitcount 4 -j DROP
firewall-cmd --reload

其實後面那一串還是 iptables 的指令,其中 hitcount 4 是指第 4 次就會 DROP,也就是說,300 秒內,只允許 3 個連線,第 4 個以後連線就會被 DROP。