萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 安裝配置 Fail2ban 防暴力破解:SSH/VSFTPD 實戰規則與日誌輪轉

Fail2ban 監控日誌自動封鎖惡意 IP,支援 iptables、tcp-wrapper、shorewall 等動作。本文涵蓋 Python 環境準備、Fail2ban 源碼安裝、logrotate 配置、核心配置檔結構(action.d/filter.d/jail.conf)、SSH 與 VSFTPD 防暴力破解實戰規則、服務啟動驗證。

1. Python 2.7.3 安裝(若系統版本過舊)

cd /tmp
wget https://python.org/ftp/python/2.7.3/Python-2.7.3.tgz
tar xzf Python-2.7.3.tgz
cd Python-2.7.3
./configure && make && make install
rm -f /usr/bin/python
ln -s /tmp/Python-2.7.3/python /usr/bin/python

2. Fail2ban 安裝

cd /tmp
wget https://github.com/downloads/fail2ban/fail2ban/fail2ban_0.8.6.orig.tar.gz
tar xzf fail2ban_0.8.6.orig.tar.gz
cd fail2ban-*/
./setup.py install
cp files/RedHat-initd /etc/init.d/fail2ban
chmod 755 /etc/init.d/fail2ban

3. 日誌輪轉 /etc/logrotate.d/fail2ban

/var/log/fail2ban.log {
    weekly
    rotate 7
    missingok
    compress
    postrotate
        /etc/init.d/fail2ban restart >/dev/null 2>&1 || true
    endscript
}

4. 核心配置結構

/etc/fail2ban/
├── action.d/     # 封鎖動作(iptables、mail、shorewall)
├── filter.d/     # 正則過濾(sshd、vsftpd、apache 等)
├── fail2ban.conf # 服務啟動參數
├── jail.conf     # 監獄規則(filter+action+logpath+maxretry)
└── *.local       # 覆蓋 .conf 設定,優先級更高

5. 實戰:SSH 與 VSFTPD 防暴力破解

# /etc/fail2ban/jail.local
[ssh-iptables]
enabled = true
filter = sshd
action = iptables[name=SSH, port=ssh, protocol=tcp]
         sendmail-whois[name=SSH, dest=admin@example.com]
logpath = /var/log/secure
maxretry = 5

[vsftpd-iptables]
enabled = true
filter = vsftpd
action = iptables[name=VSFTPD, port=ftp, protocol=tcp]
         sendmail-whois[name=VSFTPD, dest=admin@example.com]
logpath = /var/log/secure
maxretry = 3

6. 啟動驗證

service iptables start
service fail2ban start
fail2ban-client status ssh-iptables
# 輸出應顯示 Currently banned 0 等資訊

擴展應用

同樣邏輯可套用至 FreeSWITCH 註冊攻擊、API 暴力嘗試等,只需編寫對應 filter.d 正則並建立 jail 規則。

copyright © 萬盛學電腦網 all rights reserved