Еще одно добавление к серверу. Дело в том, что все сервера так или иначе "торчащие" в интернет, становятся целью для атак, и наш почтовый сервер - не исключение. Одна из атак - попытка "взлома" паролей пользователей. Такая атака обычно проводится с перебором паролей, и рано или поздно может быть удачной. В нашем случае - это атака на аутентификацию пользователей по imap, pop3, smtp.
Бороться достаточно просто - есть прекрасная программа fail2ban, которая после N неудачных попыток просто прописывает в файрволле правила, запрещающие доступ с атакующего IP-адреса на определенный срок (чаще всего - на час через 3 неудачных попытки). Такие "паузы" делают подобные атаки практически бессмысленными.
Для защиты устанавливаем пакет fail2ban
sudo apt-get install fail2ban
В файле /etc/fail2ban/jail.conf (скопируйте его на всякий случай
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.conf_orig
есть примеры различных сервисов, нас же интересует только следующие:
# Fail2Ban configuration file.
#
# This file was composed for Debian systems from the original one
# provided now under /usr/share/doc/fail2ban/examples/jail.conf
# for additional examples.
#
# To avoid merges during upgrades DO NOT MODIFY THIS FILE
# and rather provide your changes in /etc/fail2ban/jail.local
#
# Author: Yaroslav O. Halchenko <debian@onerussian.com>
#
# $Revision: 281 $
#
# The DEFAULT allows a global definition of the options. They can be override
# in each jail afterwards.
[DEFAULT]
# "ignoreip" can be an IP address, a CIDR mask or a DNS host
ignoreip = 127.0.0.1 10.0.0.0/16
bantime = 3600
maxretry = 3
# "backend" specifies the backend used to get files modification. Available
# options are "gamin", "polling" and "auto".
# yoh: For some reason Debian shipped python-gamin didn't work as expected
# This issue left ToDo, so polling is default backend for now
backend = polling
#
# Destination email address used solely for the interpolations in
# jail.{conf,local} configuration files.
destemail = admin@company.ru
#
# ACTIONS
#
# Default banning action (e.g. iptables, iptables-new,
# iptables-multiport, shorewall, etc) It is used to define
# action_* variables. Can be overriden globally or per
# section within jail.local file
banaction = iptables-multiport
# email action. Since 0.8.1 upstream fail2ban uses sendmail
# MTA for the mailing. Change mta configuration parameter to mail
# if you want to revert to conventional 'mail'.
mta = sendmail
# Default protocol
protocol = tcp
#
# Action shortcuts. To be used to define action parameter
# The simplest action to take: ban only
action_ = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s]
# ban & send an e-mail with whois report to the destemail.
action_mw = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s]
%(mta)s-whois[name=%(__name__)s, dest="%(destemail)s", protocol="%(protocol)s]
# ban & send an e-mail with whois report and relevant log lines
# to the destemail.
action_mwl = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s]
%(mta)s-whois-lines[name=%(__name__)s, dest="%(destemail)s", logpath=%(logpath)s]
# Choose default action. To change, just override value of 'action' with the
# interpolation to the chosen action shortcut (e.g. action_mw, action_mwl, etc) in jail.local
# globally (section [DEFAULT]) or per specific section
action = %(action_)s
#
# JAILS
#
# Next jails corresponds to the standard configuration in Fail2ban 0.6 which
# was shipped in Debian. Enable any defined here jail by including
#
# [SECTION_NAME]
# enabled = true
#
# in /etc/fail2ban/jail.local.
#
# Optionally you may override any other parameter (e.g. banaction,
# action, port, logpath, etc) in that section within jail.local
[ssh]
enabled = true
port = ssh
filter = sshd
banaction = iptables-allports
sendmail-whois
logpath = /var/log/auth.log
maxretry = 3
#
# Mail servers authenticators: might be used for smtp,ftp,imap servers, so
# all relevant ports get banned
#
[courierauth]
enabled = true
port = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter = courierlogin
logpath = /var/log/mail.log
banaction = iptables-allports
sendmail-whois
maxretry = 3
[sasl]
enabled = true
port = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter = sasl
banaction = iptables-allports
sendmail-whois
logpath = /var/log/mail.log
maxretry = 3
Кратко о том, что мы делаем:
- мы игнорируем атаки с адресов 127.0.0.1 и сети 10.0.0.0/255.255.0.0 (предполагаем, что это наша внутренняя сеть, и из нее могут быть разве что ошибочные попытки набора паролей пользователями)
- после 3 неудачных попыток аутентификации мы ставим бан на 3600 секунд (1 час)
- информацию о банах будем посылать на admin@company.ru (поменяйте на свой)
- используем три разных набора правил - ssh, courierauth и sasl, о них чуть ниже (ssh вставлен "на всякий случай", если к серверу есть доступ по ssh)
По правилам, описанным в файле /etc/fail2ban/filter.d/sshd.conf мы:
- анализируем лог-файл /var/log/auth.log
- баним доступ по всем портам и посылаем письмо о возможной атаке через 3 неверные попытки аутентификации
- сами правила в файле sshd.conf оставляем "по умолчанию"
Пример записи в /etc/log/auth.log которая будет "поймана"
Nov 25 10:19:41 bowmore sshd[30769]: Failed password for root from AA.BB.CC.DD port 60031 ssh2
По правилам, описанным в файле /etc/fail2ban/filter.d/courierlogin.conf мы:
- анализируем лог-файл /var/log/mail.log
- баним доступ по всем портам и посылаем письмо о возможной атаке через 3 неверные попытки аутентификации
- сами правила в файле courierlogin.conf оставляем "по умолчанию"
Примеры записей в /etc/log/mail.log которые будут "пойманы"
Nov 24 16:27:05 bowmore imapd: LOGIN FAILED, user=postmaster@company.ru, ip=[::ffff:AA.BB.CC.DD]
Nov 24 16:27:05 bowmore pop3d: LOGIN FAILED, user=sale@company.ru, ip=[::ffff:AA.BB.CC.DD]
По правилам, описанным в файле /etc/fail2ban/filter.d/sasl.conf мы:
- анализируем лог-файл /var/log/mail.log
- баним доступ по всем портам и посылаем письмо о возможной атаке через 3 неверные попытки аутентификации
- правило в файле /etc/fail2ban/filter.d/sasl.conf чуть изменим (с правилом "по умолчанию" срабатываний не будет):
#failregex = (?i): warning: [-._\w]+\[<HOST>\]: SASL (?:LOGIN|PLAIN|(?:CRAM|DIGEST)-MD5) authentication failed(: [A-Za-z0-9+/]*={0,2})?$
failregex = (?i): warning: [-._\w]+\[<HOST>\]: SASL (?:LOGIN|PLAIN|(?:CRAM|DIGEST)-MD5) authentication failed
Примеры записей в /etc/log/mail.log которые будут "пойманы"
Nov 24 19:21:20 bowmore postfix/smtpd[458]: warning: unknown[AA.BB.CC.DD]: SASL LOGIN authentication failed: generic failure
Nov 24 22:32:35 bowmore postfix/smtpd[2593]: warning: unknown[AA.BB.CC.DD]: SASL LOGIN authentication failed: authentication failure
Можно проверить срабатывание написанных нами правил:
fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf
fail2ban-regex /var/log/mail.log /etc/fail2ban/filter.d/courierlogin.conf
fail2ban-regex /var/log/mail.log /etc/fail2ban/filter.d/sasl.conf
Если в лог-файлах были попытки неверной аутентификации, мы получим по ним "отчет".
Когда убедимся, что все работает - перезапустим сервис
/etc/init.d/fail2ban restart
и наслаждаемся попадающими к нам "хакерами".