В попередній статті було описано як нагло закритись від світу і користуватись asterisk тільки з довірених ІР адрес та підмереж локальної мережі
Якщо у вас не встановлений fail2ban, то першим ділом вам необхідно його встановити
apt-get install fail2ban (Debian) або yum install fail2ban (CentOS)
Після інсталяції необхідно підготувати конфігараційні файли до нормальної роботи
1. Створюємо лог файл для парсингу повідомлень з небезщпечними зверненнями
nano /var/log/asterisk/security_log
Далі правим logger.conf - в конфігурації асетріска /etc/asterisk/logger.conf вказуючи йому звідки збирати інформацію
[general]
#include logger_general_additional.conf
#include logger_general_custom.conf
security_log => SECURITY,NOTICE
[logfiles]
#include logger_logfiles_additional.conf
#include logger_logfiles_custom.conf
security_log => SECURITY,NOTICE
Перезавантажуємо логи астера
sudo asterisk -rx "logger reload"
Перевірити роботу tail –f /var/log/asterisk/security_log
Переходим до налаштування самих конфігураційних файлів fail2ban
nano /etc/fail2ban/jail.conf повний файл тут
Змінюємо тільки декілька блоків
[DEFAULT]
ignoreip = 127.0.0.1/8 (адреси ваших підмереж)
ignorecommand =
bantime = 6800
findtime = 800
maxretry = 3
backend = auto
usedns = warn
...
[ssh-iptables]
enabled = true
filter = sshd
action = iptables[name=SSH, port=ssh, protocol=tcp]
sendmail-whois[name=SSH, dest=Ця електронна адреса захищена від спам-ботів. Вам необхідно увімкнути JavaScript, щоб побачити її., sender=Ця електронна адреса захищена від спам-ботів. Вам необхідно увімкнути JavaScript, щоб побачити її., sendername="Fail2Ban"]
logpath = /var/log/secure
maxretry = 5
...
[asterisk]
enabled = true
filter = asterisk
action = iptables-asterisk[name=asterisk]
sendmail[name=Asterisk, dest=Ця електронна адреса захищена від спам-ботів. Вам необхідно увімкнути JavaScript, щоб побачити її., sender=Ця електронна адреса захищена від спам-ботів. Вам необхідно увімкнути JavaScript, щоб побачити її.]
logpath = /var/log/asterisk/security_log
maxretry = 3
bantime = 6800
Далі налаштовуємо файл фільтрації ano /etc/fail2ban/filter.d/asterisk.conf
# Fail2Ban configuration file
#
#
# $Revision: 251 $
#
[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
#
# Asterisk 1.8 uses Host:Port format which is reflected here
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.* .*: Registration from '.*' failed for '<HOST>:.*' - ACL error (permit/deny)
NOTICE.* .*: Registration from '.*' failed for '<HOST>:.*' - Device does not match ACL
NOTICE.* .*: Registration from '\".*\".*' failed for '<HOST>:.*' - No matching peer found
NOTICE.* .*: Registration from '\".*\".*' failed for '<HOST>:.*' - Wrong password
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.* .*: <HOST> failed to authenticate as '.*'
NOTICE.* .*: <HOST> tried to authenticate with nonexistent user '.*'
SECURITY.* .*: SecurityEvent="InvalidAccountID",.*,Severity="Error",Service="SIP",.*,.*,.*,.*,RemoteAddress=".*/.*/<HOST>/.*"
SECURITY.* .*: SecurityEvent="ChallengeResponseFailed",.*,Severity="Error",Service="SIP",.*,.*,.*,.*,RemoteAddress=".*/.*/<HOST>/.*",.*
SECURITY.* .*: SecurityEvent="InvalidPassword",.*,Severity="Error",Service="SIP",.*,.*,.*,.*,RemoteAddress=".*/.*/<HOST>/.*",.*
# Option: ignoreregex
# Notes.: regex to ignore. If this regex matches, the line is ignored.
# Values: TEXT
#
ignoreregex =
Ще додамо адне правило в /etc/fail2ban/action.d - iptables-asterisk.conf
# Fail2Ban configuration file
#
# Author: Razvan Turtureanu
#
# $Revision$
#
[Definition]
# Option: actionstart
# Notes.: command executed once at the start of Fail2Ban.
# Values: CMD
#
actionstart = iptables -N fail2ban-<name>
iptables -A fail2ban-<name> -j RETURN
iptables -I <chain> -p tcp --dport 5061 -j fail2ban-<name>
iptables -I <chain> -p tcp --dport 5060 -j fail2ban-<name>
iptables -I <chain> -p udp --dport 5060 -j fail2ban-<name>
iptables -I <chain> -p udp --dport 5061 -j fail2ban-<name>
# Option: actionstop
# Notes.: command executed once at the end of Fail2Ban
# Values: CMD
#
actionstop = iptables -D <chain> -p tcp --dport 5061 -j fail2ban-<name>
iptables -D <chain> -p udp --dport 5060 -j fail2ban-<name>
iptables -D <chain> -p udp --dport 5061 -j fail2ban-<name>
iptables -D <chain> -p tcp --dport 5060 -j fail2ban-<name>
iptables -D <chain> -p tcp --dport 5061 -j fail2ban-<name>
iptables -F fail2ban-<name>
iptables -X fail2ban-<name>
# Option: actioncheck
# Notes.: command executed once before each actionban command
# Values: CMD
#
actioncheck = iptables -n -L <chain> | grep -q fail2ban-<name>
# Option: actionban
# Notes.: command executed when banning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: <ip> IP address
# <failures> number of failures
# <time> unix timestamp of the ban time
# Values: CMD
#
actionban = iptables -I fail2ban-<name> 1 -s <ip> -j DROP
# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: <ip> IP address
# <failures> number of failures
# <time> unix timestamp of the ban time
# Values: CMD
#
actionunban = iptables -D fail2ban-<name> -s <ip> -j DROP
[Init]
# Defaut name of the chain
#
name = default
# Option: chain
# Notes specifies the iptables chain to which the fail2ban rules should be
# added
# Values: STRING Default: INPUT
chain = INPUT
Рестартуєм службу service fail2ban restart
але краще зупитити та запустити stop / start
Перевіряємо статус fail2ban
fail2ban-client status asterisk
Status for the jail: asterisk
|- filter
| |- File list: /var/log/asterisk/security_log
| |- Currently failed: 0
| `- Total failed: 11
`- action
|- Currently banned: 3
| `- IP list: 85.14.242.70 85.14.242.68 213.202.233.79
`- Total banned: 3
chain = INPUT
Ось так і потрапили одразу пару брутфорс ботів
Перевіряємо iptables
iptables -L -n
Бережіть свої сервера ;-)
/etc/asterisk/sip_additional.conf
[pcservice] type=user secret=my password context=custom-get-did-from-sip [voicedata] username=pcservice type=peer secret=mypassword nat=force_rport,comedia host=IPVOICEDATA fromuser=pcservice fromdomain=IPVOICEDATA dtmfmode=rfc2833 authuser=edwinz context=from-trunk-sip-voicedata ;test qualify=yes canreinvite=yes insecure=port,invite disallow=all allow=ulaw,alaw
/etc/asterisk/sip_general_custom.conf
allowguest=no alwaysauthreject=yes externip=MyExternalIP localnet=192.168.50.0/255.255.255.0 localnet=192.168.51.0/255.255.255.0 nat=yes canreinvite=no registertimeout=20 registerattempts=0 maxexpiry=3600 minexpiry=60