Skip to content

Proteger Asterisk de ataques con fail2ban

by Gonzalo on 23 noviembre, 2011

Si tienes un Asterisk abierto hacia afuera por tener un troncal o extensiones SIP que se logueen desde fuera, estarás acostumbrado a recibir ataques de intentos de logueo por fuerza bruta de este tipo (como siempre desde China):

...
'"9994"' failed for 'XXX.XXX.XXX.XXX' - No matching peer found
[Nov 10 15:51:37] NOTICE[2979]: chan_sip.c:XXXXX handle_request_register: Registration from '"9995"' failed for 'XXX.XXX.XXX.XXX' - No matching peer found
[Nov 10 15:51:37] NOTICE[2979]: chan_sip.c:XXXXX handle_request_register: Registration from '"9996"' failed for 'XXX.XXX.XXX.XXX' - No matching peer found
[Nov 10 15:51:37] NOTICE[2979]: chan_sip.c:XXXXX handle_request_register: Registration from '"9997"' failed for 'XXX.XXX.XXX.XXX' - No matching peer found
[Nov 10 15:51:37] NOTICE[2979]: chan_sip.c:XXXXX handle_request_register: Registration from '"9998"' failed for 'XXX.XXX.XXX.XXX' - No matching peer found
[Nov 10 15:51:37] NOTICE[2979]: chan_sip.c:XXXXX handle_request_register: Registration from '"9999"' failed for 'XXX.XXX.XXX.XXX' - No matching peer found
[Nov 10 15:51:37] NOTICE[2979]: chan_sip.c:XXXXX handle_request_register: Registration from '"10000"' failed for 'XXX.XXX.XXX.XXX' - No matching peer found

Es por eso que hay que tener cuidado de tener bien configurado el dialplan y las extensiones para no llevarte una sorpresita algún día de una factura de miles de euros.

Para prevenir estos ataques podemos usar fail2ban para que cuando detecte un cierto nº de registros erróneos banee esa ip.

Instalmos fail2ban:
# apt-get install fail2ban

Esto ya te instala iptables.
Los archivos de config están en /etc/fail2ban
Editamos /etc/fail2ban/jail.conf que es donde se definen los diferentes servicios que queremos banear y lo que queremos hacer en caso de que intenten atacar ese servicio. Podemos echar un vistazo al de ssh para crear el nuestro.
Yo he definido al final uno tal que así:

# Asterisk
[asterisk-iptables]
enabled  = true
filter   = asterisk
action   = iptables-allports[name=ASTERISK, protocol=all]
           sendmail-whois[name=ASTERISK, dest=gonzalo@loquesea.com, sender=loquesea.com]
logpath  = /var/log/asterisk/messages
maxretry = 5
bantime = 259200

omo veis es muy simple. Define una regla que bloquea el acceso por iptables a esa ip si lo intenta de forma errónea mas de 5 veces (maxretry) y la banea durante 72 hor
as (259200 secs).
También nos envía un mail con el whois de la ip y lo guarda en los logs.

Al prinicpio de este archivo quizás queramos definir también las ip’s que no serán baneadas, por si algún día banea la nuestra propia (separadas por espacios):
ignoreip = 127.0.0.1 192.168.1.10 192.168.1.2

A continuación editamos las reglas del servicio asterisk en el archivo /etc/fail2ban/filter.d/asterisk.conf:

[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.* .*: Registration from '.*' failed for '' - Peer is not supposed to registe
        NOTICE.* .*: Registration from '.*' failed for '' - ACL error (permit/deny)
        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 .*@.*
        NOTICE.* .*: Registration from '\".*\".*' failed for '' - Wrong password
        NOTICE.* .*: Registration from '\".*\".*' failed for '' - No matching peer found
        VERBOSE.*SIP/-.*Received incoming SIP connection from unknown peer

# Option:  ignoreregex
# Notes.:  regex to ignore. If this regex matches, the line is ignored.
# Values:  TEXT
#
ignoreregex =

Esto es, cualquiera de estos errores, mas de 5 veces hará que bloquee esa ip.

Antes de reiniciar asterisk, parece que hay que cambiar el formato de la fecha que se pone en los logs, si no fail2ban será incapáz de parsearla y hacer un matching. Para ello editamos el archivo de asterisk /etc/asterisk/logger.conf y descomentamos en la sección [general] la línea:
dateformat=%F %T

y ejecutamos en el CLI> de asterisk:
CLI> logger reload

Ahora ya podemos reiniciar el servicio:
# service fail2ban restart
* Restarting authentication failure monitor fail2ban [ OK ]

Ups!, un cliente cojonero se ha baneado, ¿cómo lo desbaneo?

Comprobamos que ip’s están bloquedadas con iptables:

# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
fail2ban-ASTERISK  tcp  --  anywhere             anywhere

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain fail2ban-ssh (1 references)
target     prot opt source               destination
DROP       0    --  loquesea.net         anywhere
RETURN     0    --  anywhere             anywhere

Podemos ver que loquesea.net está bloqueada, así que para desbloquearla ejecutaremos:
# iptables -D fail2ban-ASTERISK 1

Si ejecutamos iptables -L de nuevo veremos que ya no está.

Bloquear todo lo que no venga de mi troncal de vozip

Aunque si no tenemos ningún cliente externo, seguramente lo mas seguro sea banear a todo el mundo que no sea la IP de nuestro troncal SIP. Para ello nada mejor que iptables, donde cerraríamos todo y habilitamos tan solo la conexión de nuestro proveedor o del troncal:
iptables -I INPUT 10 -p tcp --dport 5060 -s XX.XX.XX.XX -j ACCEPT

Fuentes:
http://www.voip-info.org/wiki/view/Fail2Ban+(with+iptables)+And+Asterisk
http://www.fail2ban.org/wiki/index.php/Asterisk
http://hgeorge123.blogspot.com/2011/01/seguridad-en-asterisk-fail2ban.html
http://www.voip-info.org/wiki/view/Asterisk+firewall+rules

From → asterisk, sistemas, voip

Comments are closed.