Linux

Fail2ban + Asterisk12 CentOS7

Asteriskを固定IPでのアクセス制限を行わずにグローバルに置いた場合には海外から猛攻撃されます。

  • Fail2banでブルートフォースを防ぎましょ~!
  • Asteriskのデフォルトポート5060を変更するのもおすすめ

 

環境

  • Asterisk12インストール済
  • Asterisk12サーバはCloco Cloud Sip Trunk2と電話子機を繋ぐ内線網PBXサーバとして外部クラウドで展開済

 

 

Asterisk

ログフォーマット設定

# vi /etc/asterisk/logger.conf


[general]
;
; Customize the display of debug message time stamps
; this example is the ISO 8601 date format (yyyy-mm-dd HH:MM:SS)
;
; see strftime(3) Linux manual for format specifiers.  Note that there is also
; a fractional second parameter which may be used in this field.  Use %1q
; for tenths, %2q for hundredths, etc.
;
;dateformat=%F %T       ; ISO 8601 date format
;dateformat=%F %T.%3q   ; with milliseconds
dateformat=%F %T ←追加

 

設定の反映

# systemctl restart asterisk

 

 

 

Fail2ban

 

Fail2banのインストール

# yum install epel-release
# sed -i -e "s/enabled=1/enabled=0/g" /etc/yum.repos.d/epel.repo
# yum --enablerepo=epel install fail2ban fail2ban-systemd

 

 

# cp -p /etc/fail2ban/jail.conf /etc/fail2ban/jail.d/jail.local

 

 

# vi /etc/fail2ban/jail.d/jail.local


[recidive]
enabled = true ←追加
logpath  = /var/log/fail2ban.log
banaction = %(banaction_allports)s
bantime  = 604800  ; 1 week
findtime = 86400   ; 1 day




[asterisk]

port     = 5060,5061
action   = %(banaction)s[name=%(__name__)s-tcp, port="%(port)s", protocol="tcp", chain="%(chain)s", actname=%(banaction)s-tcp]
           %(banaction)s[name=%(__name__)s-udp, port="%(port)s", protocol="udp", chain="%(chain)s", actname=%(banaction)s-udp]
           %(mta)s-whois[name=%(__name__)s, dest="%(destemail)s"]
logpath  = /var/log/asterisk/messages
maxretry = 10

↓変更

[asterisk]
enabled  = true
port     = 5060,5061
action   = %(banaction)s[name=%(__name__)s-tcp, port="%(port)s", protocol="tcp", chain="%(chain)s", actname=%(banaction)s-tcp]
           %(banaction)s[name=%(__name__)s-udp, port="%(port)s", protocol="udp", chain="%(chain)s", actname=%(banaction)s-udp]
           %(mta)s-whois[name=%(__name__)s, dest="%(destemail)s"]
logpath  = /var/log/asterisk/messages
maxretry = 10
bantime = 3600
findtime = 21600


↓更に変更

[asterisk]
enabled  = true
port     = 5060,5061
action   = %(banaction)s[name=%(__name__)s-tcp, port="%(port)s", protocol="tcp", chain="%(chain)s", actname=%(banaction)s-tcp]
           %(banaction)s[name=%(__name__)s-udp, port="%(port)s", protocol="udp", chain="%(chain)s", actname=%(banaction)s-udp]
logpath  = /var/log/asterisk/messages
maxretry = 10
bantime = 3600
findtime = 21600

maxretry、bantimeの値は御好みで調整して下さいね~!

 

 

 

ログレベルの変更

# vi /etc/fail2ban/fail2ban.conf


[Definition]

# Option: loglevel
# Notes.: Set the log level output.
#         CRITICAL
#         ERROR
#         WARNING
#         NOTICE
#         INFO
#         DEBUG
# Values: [ LEVEL ]  Default: ERROR
#
#loglevel = INFO
loglevel = NOTICE

 

 

フィルター設定

# cat /etc/fail2ban/filter.d/asterisk.conf



# Fail2Ban filter for asterisk authentication failures
#

[INCLUDES]

# Read common prefixes. If any customizations available -- read them from
# common.local
before = common.conf

[Definition]

_daemon = asterisk

__pid_re = (?:\[\d+\])

iso8601 = \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+[+-]\d{4}

# All Asterisk log messages begin like this:
log_prefix= (?:NOTICE|SECURITY|WARNING)%(__pid_re)s:?(?:\[C-[\da-f]*\])? [^:]+:\d*(?:(?: in)? \w+:)?

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>' - 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.* .*: Registration from '.*' failed for '<HOST>' - ACL error (permit/deny)
            NOTICE.* .*: Registration from '.*' failed for '<HOST>' - Device does not match ACL
            NOTICE.* <HOST> failed to authenticate as '.*'$
            NOTICE.* .*: No registration for peer '.*' \(from <HOST>\)
            NOTICE.* .*: Host <HOST> failed MD5 authentication for '.*' (.*)
            NOTICE.* .*: Failed to authenticate user .*@<HOST>.*
            NOTICE.* .*: Sending fake auth rejection for device .*\<sip:.*\@<HOST>\>;tag=.*
            NOTICE.* .*: Registration from '.*' failed for \'<HOST>.*\' - Wrong password
            NOTICE.* .*: Registration from '.*' failed for \'<HOST>.*\' - No matching peer found
            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.* .*: Registration from '.*' failed for \'<HOST>.*\' - ACL error (permit/deny)
            NOTICE.* .*: Registration from '.*' failed for \'<HOST>.*\' - Device does not match ACL
            NOTICE.* \'<HOST>.*\' failed to authenticate as '.*'$
            NOTICE.* .*: No registration for peer '.*' \(from \'<HOST>.*\'\)
            NOTICE.* .*: Host \'<HOST>.*\' failed MD5 authentication for '.*' (.*)
            NOTICE.* .*: Failed to authenticate user .*@\'<HOST>.*\'.*


ignoreregex =

Asterisk12と古いものを利用しています。

環境に合わせて正規表現で設定して下さいませ。

 

 

// 最新のものだと、きっとデフォルトで良いでしょうね。

# Read common prefixes. If any customizations available -- read them from
# common.local
before = common.conf

[Definition]

_daemon = asterisk

__pid_re = (?:\[\d+\])

iso8601 = \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+[+-]\d{4}

# All Asterisk log messages begin like this:
log_prefix= (?:NOTICE|SECURITY|WARNING)%(__pid_re)s:?(?:\[C-[\da-f]*\])? [^:]+:\d*(?:(?: in)? \w+:)?

failregex = ^%(__prefix_line)s%(log_prefix)s Registration from '[^']*' failed for '<HOST>(:\d+)?' - (Wrong password|Username/auth name mismatch|No matching peer found|Not a local domain|Device does not match ACL|Peer is not supposed to register|ACL error \(permit/deny\)|Not a local domain)$
            ^%(__prefix_line)s%(log_prefix)s Call from '[^']*' \(<HOST>:\d+\) to extension '[^']*' rejected because extension not found in context
            ^%(__prefix_line)s%(log_prefix)s Host <HOST> failed to authenticate as '[^']*'$
            ^%(__prefix_line)s%(log_prefix)s No registration for peer '[^']*' \(from <HOST>\)$
            ^%(__prefix_line)s%(log_prefix)s Host <HOST> failed MD5 authentication for '[^']*' \([^)]+\)$
            ^%(__prefix_line)s%(log_prefix)s Failed to authenticate (user|device) [^@]+@<HOST>\S*$
            ^%(__prefix_line)s%(log_prefix)s hacking attempt detected '<HOST>'$
            ^%(__prefix_line)s%(log_prefix)s SecurityEvent="(FailedACL|InvalidAccountID|ChallengeResponseFailed|InvalidPassword)",EventTV="([\d-]+|%(iso8601)s)",Severity="[\w]+",Service="[\w]+",EventVersion="\d+",AccountID="(\d*|<unknown>)",SessionID=".+",LocalAddress="IPV[46]/(UDP|TCP|WS)/[\da-fA-F:.]+/\d+",RemoteAddress="IPV[46]/(UDP|TCP|WS)/<HOST>/\d+"(,Challenge="[\w/]+")?(,ReceivedChallenge="\w+")?(,Response="\w+",ExpectedResponse="\w*")?(,ReceivedHash="[\da-f]+")?(,ACLName="\w+")?$
            ^%(__prefix_line)s%(log_prefix)s "Rejecting unknown SIP connection from <HOST>"$
            ^%(__prefix_line)s%(log_prefix)s Request (?:'[^']*' )?from '[^']*' failed for '<HOST>(?::\d+)?'\s\(callid: [^\)]*\) - (?:No matching endpoint found|Not match Endpoint(?: Contact)? ACL|(?:Failed|Error) to authenticate)\s*$

ignoreregex =


# Author: Xavier Devlamynck / Daniel Black
#
# General log format - main/logger.c:ast_log
# Address format - ast_sockaddr_stringify
#
# First regex: channels/chan_sip.c
#
# main/logger.c:ast_log_vsyslog - "in {functionname}:" only occurs in syslog

 

 

起動、自動起動設定

# systemctl start fail2ban
# systemctl enable fail2ban

 

 

 

Jailの確認

# fail2ban-client status
Status
|- Number of jail:      2
`- Jail list:   asterisk, recidive

 

BANされたIPの確認 Asteriskの場合

# fail2ban-client status asterisk


Status for the jail: asterisk
|- Filter
|  |- Currently failed: 3
|  |- Total failed:     24500
|  `- File list:        /var/log/asterisk/messages
`- Actions
   |- Currently banned: 1
   |- Total banned:     1
   `- Banned IP list:   37.xxx.xxx.155

 

 

BANされたIPの解除

# fail2ban-client set [Jail名] unbanip [IPアドレス]


※例
# fail2ban-client set asterisk unbanip 37.xxx.xxx.155


※解除されない場合はリロード
# firewall-cmd --reload

 

ipsetの確認

# ipset --list fail2ban-asterisk-udp

Name: fail2ban-asterisk-udp
Type: hash:ip
Revision: 1
Header: family inet hashsize 1024 maxelem 65536 timeout 600
Size in memory: 16592
References: 1
Members:


# ipset --list fail2ban-asterisk-tcp
Name: fail2ban-asterisk-tcp
Type: hash:ip
Revision: 1
Header: family inet hashsize 1024 maxelem 65536 timeout 600
Size in memory: 16592
References: 1
Members:

 

Firewalldルールの確認

# firewall-cmd --direct --get-all-rules

ipv4 filter f2b-recidive 1000 -j RETURN
ipv4 filter INPUT 0 -p tcp -m multiport --dports 5060,5061 -m set --match-set fail2ban-asterisk-tcp src -j REJECT --reject-with icmp-port-unreachable
ipv4 filter INPUT 0 -p udp -m multiport --dports 5060,5061 -m set --match-set fail2ban-asterisk-udp src -j REJECT --reject-with icmp-port-unreachable
ipv4 filter INPUT 0 -j f2b-recidive

 

 

うまく動作しない!?

 

フィルターの正規表現の確認

# fail2ban-client get asterisk failregex

 

ログの確認

 

Asterisk

# tail -f /var/log/messages

 

Fail2ban

# tail -f /var/log/fail2ban.log
2018-10-13 21:17:17,320 fail2ban.actions        [32720]: NOTICE  [asterisk] Ban aaa.xxx.yyy.zzz

 

 

Asteriksのリアルタイムデバッグモード

# asterisk -r

Asterisk 12.8.2, Copyright (C) 1999 - 2013 Digium, Inc. and others.
Created by Mark Spencer <markster@digium.com>
Asterisk comes with ABSOLUTELY NO WARRANTY; type 'core show warranty' for details.
This is free software, with components licensed under the GNU General Public
License version 2 and other licenses; you are welcome to redistribute it under
certain conditions. Type 'core show license' for details.
=========================================================================
Connected to Asterisk 12.8.2 currently running on 133-130-121-77 (pid = 32635)

 

子機、サーバへの接続確認

*CLI> sip show peers

 

デバッグモードのオン

133-130-121-77*CLI> sip set debug on

 

 

 

 

 

Amazonおすすめ

iPad 9世代 2021年最新作

iPad 9世代出たから買い替え。安いぞ!🐱 初めてならiPad。Kindleを外で見るならiPad mini。ほとんどの人には通常のiPadをおすすめします><

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)