Fail2Ban

    版本為 13:55, 20 Nov 2024

    到這個版本。

    返回到 版本存檔.

    查閱目前版本

    閱讀更多文章:

    官方首頁:www.fail2ban.org/wiki/index.php

    最新版本下載:https://github.com/fail2ban/fail2ban

    開始安裝

    for Debian)
    #> tar xzf 0.9.2.tar.gz
    #> cd fail2ban-0.9.2/
    #> python setup.py install 
    

    驗證安裝

    #> fail2ban-client -h
    
    for SuSE)

    yast > Software > Software Management >

    Search Phrase = fail2ban <Enter>

    Actions = Install <項目會出現+號>

    Accept <Enter>

    for CentOS)

    透過 EPEL 套件庫安裝
    NOTE: 選擇適合系統版本的 epel-release-XX.noarch.rpm

    wget http://mirror01.idc.hinet.net/EPEL/6/i386/epel-release-6-8.noarch.rpm
    rpm -ivh epel-release-6-8.noarch.rpm
    yum install fail2ban 
    

    設定自動啟動

    chkconfig --add fail2ban
    chkconfig fail2ban on 
    

    設定 Fail2ban

    vi /etc/fail2ban/filter.d/asterisk.conf

    # Fail2Ban configuration file
    #
    #
    # $Revision: 250 $
    #
    
    [INCLUDES]
    
    # Read common prefixes. If any customizations available -- read them from
    # common.local
    #before = common.conf
    
    
    [Definition]
    
    #_daemon = asterisk
    
    # Option:  failregex
    # Notes.:  regex to match the password failures messages in the logfile. The
    #          host must be matched by a group named "host". The tag "<HOST>" can
    #          be used for standard IP/hostname matching and is only an alias for
    #          (?:::f{4,6}:)?(?P<host>\S+)
    # Values:  TEXT
    #
    
    failregex = NOTICE.* .*: Registration from '.*' failed for '<HOST>' - Wrong password
                NOTICE.* .*: Registration from '.*' failed for '<HOST>' - No matching peer found
                NOTICE.* .*: Registration from '.*' failed for '<HOST>' - Username/auth name mismatch
                NOTICE.* .*: Registration from '.*' failed for '<HOST>' - Device does not match ACL
                NOTICE.* .*: Registration from '.*" .* failed for '<HOST>' - Peer is not supposed to register
                NOTICE.* <HOST> failed to authenticate as '.*'$
                NOTICE.* .*: No registration for peer '.*' \(from <HOST>\)
                NOTICE.* .*: Host <HOST> failed MD5 authentication for '.*' (.*)
                
    
    # Option:  ignoreregex
    # Notes.:  regex to ignore. If this regex matches, the line is ignored.
    # Values:  TEXT
    #
    ignoreregex =
    

    vi /etc/fail2ban/jail.conf

    # Important: exclude your local network in the ban IPs list
    ignoreip = 127.0.0.1 192.168.0.0/16

    ## This is for SSH on OpenSUSE only. ## If enable, change 'false' as 'true' [ssh-iptables] enabled = false filter = sshd action = iptables[name=SSH, port=ssh, protocol=tcp] sendmail-whois[name=SSH, dest=you@mail.com, sender=fail2ban@mail.com] logpath = /var/log/messages maxretry = 5 ## [asterisk-iptables] enabled = true filter = asterisk action = iptables-allports[name=ASTERISK, protocol=all] sendmail-whois[name=ASTERISK, dest=root, sender=fail2ban@example.org] logpath = /var/log/asterisk/fail2ban maxretry = 5 bantime = 259200

    NOTES:

    * logpath  路徑必須與下述的 logger.conf 的設定相同。
    * 若有開啟 ssh-iptables,並且在啟動 fail2ban 服務後,檢查 fail2ban.log 若出現錯誤訊息如下,可忽略它。
         fail2ban.actions.action: ERROR  iptables -N fail2ban-SSH
         iptables -A fail2ban-SSH -j RETURN
         iptables -I INPUT -p tcp --dport ssh -j fail2ban-SSH returned 400
    * 別忘了要將 LAN 的網段加入 ignoreip,免得不小心自己都無法登入。

    * 如果是 CentOS 5.x,[ssh-iptables],必須改成
    logpath = /var/log/secure

     

    設定 Asterisk

    適用: 1.6.2.x
    編輯/etc/asterisk/logger.conf

    [general]
    dateformat=%F %T
    
    [logfiles]
    console => notice,warning,error
    messages => notice,warning,error,debug,verbose
    fail2ban => notice
    

    NOTES:

    增加  dateformat 與 fail2ban logfile

    適用: 11.x

    ...
    [logfiles]
    ...
    fail2ban => notice,warning,security 
    

    Asterisk 套用新設定

    #> asterisk -rx "logger reload"
    #> asterisk -rx "logger show channels" 
    

    啟動 Fail2ban

    // 載入 Asterisk 的 logger 設定

    # asterisk -rx "module reload logger"
    # asterisk -rx "logger show channels"
    
    Channel                             Type     Status    Configuration
    -------                             ----     ------    -------------
    /var/log/asterisk/fail2ban          File     Enabled    - Notice
    /var/log/asterisk/messages          File     Enabled    - Debug Verbose Warning Notice Error
                                        Console  Enabled    - Warning Notice Error
    

    // 設定開機自動啟動 Fail2ban

    yast > System

    // 手動立即啟動 Fail2ban

    /etc/init.d/fail2ban start
    

    // 檢查 iptables 規則過濾狀況

    # iptables -L -nv
    
    Chain INPUT (policy ACCEPT 5561K packets, 966M bytes)
     pkts bytes target     prot opt in     out     source               destination
      216 16120 fail2ban-SSH  tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:22
    23182 1973K fail2ban-ASTERISK  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    
    Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
     pkts bytes target     prot opt in     out     source               destination
    
    Chain OUTPUT (policy ACCEPT 5091K packets, 884M bytes)
     pkts bytes target     prot opt in     out     source               destination
    
    Chain fail2ban-ASTERISK (1 references)
     pkts bytes target     prot opt in     out     source               destination
    23182 1973K RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0
    
    Chain fail2ban-SSH (1 references)
     pkts bytes target     prot opt in     out     source               destination
       18  1788 DROP       all  --  *      *       123.123.123.123        0.0.0.0/0
      198 14332 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0
    

    NOTES:

    fail2ban-SSH 的有關項目,只會在 jail.conf 啟用 SSH-iptables 後才會出現。

    增加黑/白名單功能(選用)

    說明:fail2ban 在偵測到異常 IPs 時,只能在指定時間內進行阻擋,這個時間若設定太長,有可能會影響到某些合法操作下被封鎖的情況,所以可以增加黑白名單的控制,方法如下:

    編輯 3 個檔案

    • /etc/fail2ban/action.d/iptables-allports.conf
    • /etc/fail2ban/action.d/iptables-multiport.conf
    • /etc/fail2ban/action.d/iptables.conf

    找到這三行

    actionstart = iptables -N fail2ban-<name>
                  iptables -A fail2ban-<name> -j RETURN
                  iptables -I <chain> -p <protocol> --dport <port> -j fail2ban-<name>
    ...
    actionban = iptables -I fail2ban-<name> 1 -s <ip> -j DROP
    ...
    actionunban = iptables -D fail2ban-<name> -s <ip> -j DROP 
    

    分別取代成

    actionstart = ...
                      ...
                      ...
                      for IP in `cat /etc/fail2ban/ip.deny`; do iptables -I fail2ban-<name> 1 -s $IP -j DROP;done
    ...
    ...
    actionban = if [ -z `awk '$1 == "<ip>" { print "true" }' /etc/fail2ban/ip.allow` ] && [ -z `awk '$1 == "<ip>" { print "true" }' /etc/fail2ban/ip.deny` ]; then iptables -I fail2ban-<name> 1 -s <ip> -j DROP;fi
    ...
    ...
    actionunban = if [ -z `awk '$1 == "<ip>" { print "true" }' /etc/fail2ban/ip.allow` ] && [ -z `awk '$1 == "<ip>" { print "true" }' /etc/fail2ban/ip.deny` ]; then iptables -D fail2ban-<name> -s <ip> -j DROP;fi
    

    新增兩個檔案:

    1. /etc/fail2ban/ip.deny (黑名單)
    2. /etc/fail2ban/ip.allow (白名單)

     註:若有變更黑名單內容時,需重啟 fail2ban 才會被套用。

    F.A.Q

    Q:如何驗證一條新規則

    Ans: 對於特定的 log 內容,要增加一條新規則,該如何驗證是否有效。

    需要過濾的 log 內容:

    [2015-01-28 05:40:16] NOTICE[-1] Ext. 9015448702956577: Incoming SIP connection from unknown peer failed for 31.3.244.234 - Unknown connection from peer
    

    在 /etc/fail2ban/filter.d/asterisk.conf 增加一條新規則

    NOTICE.* .*: Incoming SIP connection from unknown peer failed for <HOST> - Unknown connection from peer
    

    要驗證此規則是否有效,可以使用以下指令

    #> fail2ban-regex /var/log/asterisk/fail2ban "NOTICE.* .*: Incoming SIP connection from unknown peer failed for <HOST> - Unknown connection from peer"
    

    TIPS:

    fail2ban-regex <path/to/log>  <failregex or /etc/fail2ban/filter.s/XXX.conf>

    Q:為何沒有 /var/log/fail2ban.log

    Ans: 檢查 /etc/fail2ban/fail2ban.conf

    #logtarget = SYSLOG
    logtarget = /var/log/fail2ban.log
    

    重啟 fail2ban 服務

    Q:服務啟動後的規則檢查

    Ans: 請注意:在 fail2ban 服務啟動後,只會對新的非法行為所產生的 IP 進行過濾,而對舊紀錄的非法 IP,fail2ban 不會對它們重新檢查。 

    Q:在 Elastix/CentOS 5.3 始終無法 ban IP

    使用 fail2ban-client 檢查,明明 log 內有異常連線,但卻無法 ban IP

    # fail2ban-client status
    Status
    |- Number of jail:      1
    `- Jail list:           asterisk-iptables
    
    # fail2ban-client status asterisk-iptables
    |- filter
    |  |- File list:        /var/log/asterisk/fail2ban
    |  |- Currently failed: 0
    |  `- Total failed:     0
    `- action
       |- Currently banned: 0
       |  `- IP list:       
       `- Total banned:     0
    

    解決方法:

    編輯 /etc/asterisk/logger.conf

    ;syslog keyword : This special keyword logs to syslog facility
    ;將下行註解拿掉
    syslog.local0 => notice,warning,error
    

    Reload Asterisk

    Q:如何將 IP 從阻擋清單移除
    # iptables -D fail2ban-ASTERISK -s 123.123.123.123 -j DROP
    或
    # iptables -L fail2ban-ASTERISK -nv --line-number
    Chain fail2ban-ASTERISK (1 references)
    num   pkts bytes target     prot opt in     out     source               destination
    1        0     0 DROP       all  --  *      *       134.213.134.172      0.0.0.0/0
    2        0     0 DROP       all  --  *      *       46.105.127.222       0.0.0.0/0
    3        0     0 DROP       all  --  *      *       116.255.152.101      0.0.0.0/0
    4     1364  363K RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0
    
    # iptables -D fail2ban-ASTERISK 2     ;刪除第 2 規則
    Q:如何阻擋不會紀錄來源 IP 的 DDoS 攻擊 Received incoming SIP connection...

    CLI Log:

    Received incoming SIP connection from unknown peer to 003333002972597886748"

    NOTE:

    • 以上訊息只有在 sip_general.conf 的 allowguest=yes (by default),才會出現。
    • 此篇也適合解決 Sending fake auth rejection for device 100<sip:100@123.123.123.123> ,這類的攻擊手法。方法是先 註解 allowguest=no,然後完成下面的步驟。
      注意:比較安全的做法應該是將 allowguest=no,然後在 Asterisk 11 以後版本,Log 就可以紀錄到惡意的來源 IP,然後就可以用 Fail2ban 來將其阻擋,詳細資訊可以參考本篇其他章節。

    Ans:

    1. 編輯 /etc/asterisk/extensions.conf

    [from-sip-external]
    ; 註解原有內容,加上以下內容
    exten => _.,1,NoOp(Received incoming SIP connection from unknown peer to ${EXTEN})
    exten => _.,n,Set(DID=${IF($["${EXTEN:1:2}"=""]?s:${EXTEN})})
    exten => _.,n,Set(foo=${SIPCHANINFO(recvip)})
    exten => _.,n,Log(NOTICE,Incoming SIP connection from unknown peer failed for ${foo} - Unknown connection from peer)
    exten => _.,n,Hangup
    exten => h,1,Hangup
    exten => i,1,Hangup
    exten => t,1,Hangup 
    

    套用新設定

    asterisk -rx "dialplan reload"
    

    2. 編輯 /etc/fail2ban/filter.d/asterisk.conf

    ...
    failregex = NOTICE.* .*: Registration from '.*' failed for '<HOST>' - Wrong password
                ...
                ...
                NOTICE.* .*: Incoming SIP connection from unknown peer failed for <HOST> - Unknown connection from peer

    套用新設定

    service fail2ban restart
    
    Q:如何阻擋 Sending fake auth rejection ...

    在 Asterisk 1.11+)

    Failed to authenticate device 1005<sip:1005@123.123.123.123>;tag=2071f8ca

    在 Asterisk 1.8)

    Sending fake auth rejection for device 100<sip:100@123.123.123.123>;tag=99fdd5d7

    123.123.123.123 is my external IP of PBX

    Ans:不同 Asterisk 版本的解決方法

    Asterisk 11)
    此版新增一個 Security Log Level 的功能,透過啟用這個,可以記錄攻擊者的來源 IP,然後再透過 fail2ban 去阻擋。

    編輯 /etc/fail2ban/filter.d/asterisk.conf
    加上 SECURITY 那行

    failregex = Registration from '.*' failed for '<HOST>:.*' - Wrong password
    ...
    ...
                SECURITY.* .*: SecurityEvent="(FailedACL|InvalidAccountID|ChallengeResponseFailed|InvalidPassword)",EventTV="[\d-]+",Severity="[\w]+",Service="[\w]+",EventVersion="\d+",AccountID="\d+",SessionID="0x[\da-f]+",LocalAddress="IPV[46]/(UD|TC)P/[\da-fA-F:.]+/\d+",RemoteAddress="IPV[46]/(UD|TC)P/<HOST>/\d+"(,Challenge="\w+",ReceivedChallenge="\w+")?(,ReceivedHash="[\da-f]+")?$
    

     

    教學連結:

    1. http://highsecurity.blogspot.tw/2013...l2ban-088.html
    2. http://issues.freepbx.org/browse/FREEPBX-7573

    Asterisk 1.8/1.6)
    舊版的 Asterisk 要阻擋這類行為,只能修改原始檔 channels/chan_sip.c,使系統可以記錄攻擊者的來源 IP,修改後必須重新編譯 Asterisk 才能被套用,再設定 fail2abn 去阻擋。

    教學連結:https://bugs.debian.org/cgi-bin/bugr...cgi?bug=706739

    TIP:

    在舊版的 Asterisk 還有一個方法,不用修改 chan_sip.c 原始檔,詳細資訊請參閱本篇其他章節。

    Powered by MindTouch Core