Tag: Asterisk

  • Защищаем сервер Asterisk с помощью fail2ban

    Итак, пришло время поговорить о защите. На написание поста меня сподвигла атака из США жестким брутом. Дело было так, я зашел на сервер оптимизировать конфиг users.conf(Об этом в следующей статье). После правки файла, я благополучно зашел в консоль Asterisk и увидел кучу сообщений (примерно 5 раз в секунду) о том, что с такого-то IP попытка зайти под пользователем 104. Меня это сначала смутило. А потом я решил поставить fail2ban, чтобы обезопасить себя. Итак, статья в моем стиле – поэтому никакой лишней инфы не будет, только то что нужно чтобы закрыть доступ для атакующего IP. Защищать будем Asterisk, ну и бонусом SSH.

    Шаг 1. Установка fail2ban.

    apt-get install fail2ban

    Шаг 2. Установка python и iptables. Возможно вам понадобиться установить эти пакеты, поэтому

    apt-get install iptables python

    Шаг 3. Конфигурация fail2ban. Итак, займемся конфигурацией. Для этого перейдем в каталог /etc/fail2ban/filter.d.

    cd /etc/fail2ban/filter.d

    Создаем новый фильтр:

    touch asterisk.conf

    Содержимое файла /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 \"\" can
    #          be used for standard IP/hostname matching and is only an alias for
    #          (?:::f{4,6}:)?(?P\\S+)
    # Values:  TEXT
    failregex = NOTICE.* .*: Registration from \'.*\' failed for \'\' - Wrong password
    NOTICE.* .*: Registration from \'.*\' failed for \'\' - No matching peer found
    NOTICE.* .*: Registration from \'.*\' failed for \'\' - Username/auth name mismatch
    NOTICE.* .*: Registration from \'.*\' failed for \'\' - Device does not match ACL
    NOTICE.* failed to authenticate as \'.*\'$
    NOTICE.* .*: No registration for peer \'.*\' \\(from \\)
    NOTICE.* .*: Host failed MD5 authentication for \'.*\' (.*)
    NOTICE.* .*: Failed to authenticate user .*@.*
    # Option:  ignoreregex
    # Notes.:  regex to ignore. If this regex matches, the line is ignored.
    # Values:  TEXT
    ignoreregex =

    Шаг 4. Редактируем /etc/fail2ban/jail.conf. В конец файла добавляем следующее содержимое:

    [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/messages #(Тут внимательно! Посмотрите где у вас логи храняться!)
    maxretry = 5
    bantime = 259200

    Шаг 5. Логирование Asterisk. Открываем /etc/asterisk/logger.conf и раскомментируем:

    [general]
    dateformat=%F %T

    В консоли перегружаем сервис логирования:

    asterisk -rx \"logger reload\"

    Шаг 6. Запуск.

    /etc/init.d/iptables start

    Проверим:

    iptables -L -v

    Должно появиться что то типа этого:

     iptables -L -v
    
    Chain INPUT (policy ACCEPT 20100 packets, 3866K bytes)
    pkts bytes target     prot opt in     out     source               destination
    62  5692 fail2ban-ssh  tcp  --  any    any     anywhere             anywhere            multiport dports ssh
    2049  471K fail2ban-ASTERISK  all  --  any    any     anywhere             anywhere
    
    Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
    pkts bytes target     prot opt in     out     source               destination
    
    Chain OUTPUT (policy ACCEPT 18948 packets, 5246K bytes)
    pkts bytes target     prot opt in     out     source               destination
    
    Chain fail2ban-ASTERISK (1 references)
    pkts bytes target     prot opt in     out     source               destination
    2049  471K RETURN     all  --  any    any     anywhere             anywhere
    
    Chain fail2ban-ssh (1 references)
    pkts bytes target     prot opt in     out     source               destination
    62  5692 RETURN     all  --  any    any     anywhere             anywhere

    Шаг 7. Автозапуск fail2ban и iptables:

    update-rc.d iptables defaults
    update-rc.d fail2ban defaults

    http://www.fail2ban.org/wiki/index.php/Asterisk

    http://www.voip-info.org/wiki/view/Fail2Ban+%28with+iptables%29+And+Asterisk