
我在讓fail2ban 做我想做的事情時遇到問題。我在 CLoudFlare 上使用了禁止 IP 的操作,這意味著在 Cloudflare 端的所有內容都更新之前,仍然會有大量請求通過(因此用戶無法再訪問該網站)。
在此之前,fail2ban 會嘗試一遍又一遍地禁止該IP,導致它向cloudflare 發送數千個請求(在發生ddos 的情況下),這需要很長時間,因此在完成之前不會禁止任何其他攻擊者以前的(已經禁止的)。
那麼,有沒有辦法阻止fail2ban再次嘗試禁止它們,而忽略它們呢?
#!/bin/bash
# Make sure that the ip-blacklist file exists
# otherwise we go ahead and create it
if [ ! -e "/etc/fail2ban/ip.blacklist" ] ; then
touch "/etc/fail2ban/ip.blacklist"
fi
if [[ $1 = ban ]]; then
if ! grep -q "$2" /etc/fail2ban/ip.blacklist; then
# Store the IP as we need it later to check if the user is already banned
echo "$2" >> /etc/fail2ban/ip.blacklist
# Submit the ban request
fi
elif [[ $1 = unban ]]; then
# Remove the IP from the blacklist
perl -ni -e "print unless (/^$2$/);" /etc/fail2ban/ip.blacklist
#sed -i '/^$2$/d' /etc/fail2ban/ip.blacklist
# Submit the unban request
fi
答案1
考慮建立一個禁止的 IP 列表,並在發出禁止請求時將 IP 新增到其中。在操作腳本中,如果 IP 在清單中,則忽略禁止請求。您還需要更改取消禁止操作以將 IP 從禁止的 IP 清單中刪除。建立以下腳本:
#!/bin/bash
# Define ourbanfile
banFile=ip.blacklist
# Ensure we have a banFile will be created if missing
if [ ! -e ${banFile} ]; then
touch ${banFile}
fi
# Ban or unban as desired
if [[ $1 = ban ]]; then
if ! grep -q "$2" ${banFile}; then
# Store the IP as we need it later to check if the user is already banned
echo "$2" >> ${banFile}
# Submit the ban request
fi
elif [[ $1 = unban ]]; then
# Remove the IP from the blacklist
perl -ni -e "print unless (/^$2\$/);" ${banFile}
#sed -i '/^$2$/d' ${banFile}
# Submit the unban request
fi
# Cat banfile if running on terminal (testing)
tty -s && cat ${banFile}
# EOF
你的行動將是:
actionban = /path/to/script ban <IP>
actionunban = /path/to/script unban <IP>