9/14/2011

VoIP Information Gathering: Metasploit


Information gathering is the stage of a penetration test when the attacker tries to  collect as much information as possible about the target. This step is normally composed for footprinting and fingerprinting but, in the case of VoIP systems, we should add extension enumeration to the list. During this last step attacker will attempt to obtain valid extensions/users of the target system.


Footprinting & Fingerprinting

My favourite tools for these jobs are FOCA and Nmap, it´s a bit strange combination but it fits for me :). FOCA automates almost all the “dirty job” and it is the best with public documents metadata, while Nmap flexibility let me confirm manually all these discovered stuff. Moreover, in the case of SIP Protocol, FOCA also is able to obtain more information from target  DNS SRV records, they work in a similar way during a call that MX ones for mailing. Next picture taken from the blog of its “father” shows an example of them.


Figure: Adobe SRV records

NOTE: FOCA it is not GPL, it´s only free as in free beer but, in my opinion, there is no replacement for the moment.

There are some other specific tools for VoIP which complement classic ones discussed above. I´m going to focus on Metasploit modules because Sipvicious set of tools, which is the most used for this tasks and works in a very similar way, is a lot of documented over the net. These VoIP specific scans reduce strongly the time in comparison of nmap because they send specific SIP request UDP packets instead of ICMP ones. In this post we can find a complete explanation of that and here is exposed how nmap UDP scan works. You can compare it (nmap -sU -p 5060 -sV TARGET) and check that the speed difference is really huge. One important advantage of Metasploit over Sipvicious is the support of threading which could speed up still more the process.

So, at this point, we are ready to start scanning a testing environment formed by an Ubuntu 11.04 laptop hosting two virtual machines, connected in NAT mode:
- Backtrack 5 R1 box simulating bad guy.
- Debian Squeeze box with a basic installation of Asterisk 1.6.2.9-2 and only 101 and 102 extensions allowed.

There are not too much Metasploit modules involving VoIP but we already have auxiliaries needed for SIP scanning and extension enumeration as showed in the picture:


Figure: Metasploit SIP related modules

Now, I´m going to use Armitage (sorry guys, I like GUIs :P) in order to scan my network using "SIP scan (UDP)" (auxiliary/scanner/sip/options) module. It supports only OPTIONS scanning but it is enough for being the most realiable type. In fact, INVITE scan could be noisy and produce a "ring” at the other end.  If you are interested in all these subjects and how they work more in depth I recommend you (as always) “VoIP Haking Exposed” book.

You only have to specify the target for configure the module, next images show the steps and the correct result.


Figure: Module configuration


Figure: Scan result


Extension enumeration

Instead of explaining how this attack works in a theorethical way (diagrams and all this stuff) I´m going to refer you to the book and show a situation which helps to understand because user/extension enumeration is possible. Firstly I will try to connect my Ekiga softphone to Asterisk server with a non existent user:


Figure: Bad user account configuration


Figure: Bad login result

Ok, Asterisk didn´t allow the connection, now we are going to try with an existent user and bad password:


Figure: Correct user and bad password configuration


Figure: “Not bad” login result

The response is different in both cases so, as you can imagine at this point, we could easily identify different extensions. In order to automate this attack we can use “SIP Username Enumerator (UDP)” module (scanner/sip/enumerator) which supports REGISTER and OPTIONS scan (METHOD module parameter). Really it is a Brute-force attack trying specified extensions, so it is very important to specify PADLEN argument, if not, you could obtain a very long list of non-existent extensions. In my case I choose PADLEN equal to 3 because extensions are 101 and 102, I also modifed MAXENT to fit with it.


Figure: Enumerator module configuration


Figure: REGISTER extension enumeration result


Figure: OPTIONS extension enumeration result

As you can see I got different results, on one side OPTIONS scan identified extensions 500 (Asterisk demo) and 600 (echo demo) and REGISTER scan got real extensions on the other. So it would be necessary to use both types during a pentest process.

At this moment Metasploit does not support Asterisk Exchange protocol (this is also part of VoIP protocols as SIP) scan. We have enumIAX and iaxscan classic tools, but we are only focus in SIP protocol at this time.

Information gathering coutermeasurements is a very interesting subject but I think it is enough for today, typical solutions are Fail2ban combined with Iptables and other specific tools for each type of VoIP system.

Jesús Pérez

8/26/2011

VoIP Eavesdropping: Counter Measurements

As we seen in two last posts SIP(Sesion Initiation Protocol) is a protocol easily sniffeable because of being transmitted unencrypted over the net. There are some solutions which solve this, but they are not definitive. Next picture show a very basic diagram of one VoIP infrastructure which I will use along this post, at this point we should understand SIP is used for creating, modifying and terminating sessions and this sessions are formed for one or several media streams and they occurs between clients, leaving SIP Proxy aside.




Figure: Basic VoIP network infrastructure

Mainly we have two options in order to avoid Eavesdropping attacks: encryption or network separation.




Network separation


It´s too difficult to own necessary resources to separate physically VoIP network of organization data network. The common solution is to use managed switches and setup different VLANs (Virtual Private Networks).


But this is only applicable inside your LAN and there are a lot of techniques for evading this kind of switches control which allow the attacker hop between different VLANs, we can find them with a simple search on Google:
http://www.google.es/search?sourceid=chrome&ie=UTF-8&q=vlan+hop
In fact, software used in previous posts supports it for some Cisco routers as showed in the picture:




Figure: UCSniff VLAN hop



Encryption


In this case we have some options too:


- VPN(Virtual Private Network): As you can see in the figure it is possible to cypher communications between different VoIP terminals of your system using a VPN, if all traffic is encrypted both SIP and RTP are also protected. This solution defends us from Internet sniffers but not inside the organization, this is the reason because a dedicated VLAN is also recommended in order to minimize data exposure. 




Figure: VPN example

- Built encryption: Some proprietary software as Skype uses its own cipher protocol, only understandable for Skype clients. Traffic is encrypted and protocol relies on a P2P network formed for clients and nodes, but this architecture is too complex for resume it in a few words, so I recommend the lecture of these papers:
http://www.linecity.de/INFOTECH_ACS_SS05/acs5_top1_paper.pdf
http://www.mjalali.com/blog/?p=10
Anyway, I wouldn’t use it if I want a real secure communication because i can´t be sure if my conversation is not being transmitted using another Skype user computer(maybe a bad guy one).


- “Standards” SRTP & ZRTP: SRTP(Secure Real Time Transport Protocol) cyphers RTP traffic to provide encryption, message authentication and integrity and replay protection. It depends of an external key management protocol to set up the initial master key, there are some other protocols to do this task: MIKEY, ZRTP(Media Path Key Agreement for Unicast Secure RTP) and SDES which seems to become de facto standard, principally for being an extremely simple technique. Basically, in this method keys are transported in a SIP message (SDP attachment) and ciphered using TLS(Transport Layer Security), you can imagine it if you think in HTTPS protocol. Also it could be possible to use other methods to implement this last funcionality like S/MIME but they are not too much widespread.




Figure: TLS example

On the other hand, ZRTP was developed as part of Zfone Project and its most important advantage is the only able to provide end-to-end encryption. Even SIP/TLS does not provide it because being the IP PBX a trusted third party which could be able to eavesdrop the conversation. Other benefits of this protocol:
- It uses a public key algorithm avoiding PKI(Public Key Infrastructure) complexity.
- It allows the detection of man-in-the-middle (MiTM) attacks, as commented before.
- It supports opportunistic encryption asking the other VoIP client if supports ZRTP before starting a call.




Figure: Detailed SRTP generic communication

NOTE: Eavesdropping through ZRTP protocol seems extremely difficult, but not impossible. To do this, an attacker would have to be present since the first call, be able to fake verbal SAS in real time and, preferably, to imitate voices. (Detailed explanation here)


They are not exactly standards but they are the most used option, in fact, SRTP(RFC4585) and MIKEY (RFC4738) are “Proposed standard” and ZRTP is an “Informational standard”. It was developed by Phil Zimmermann (among others) and published by IETF recently as RFC 6189.


Ok, this is a real mess of protocols, but now, what hardware and software solution would I get? You should choose what level of risk you want to assume, and then select software that supports it, I think this comparative list can help you:
http://en.wikipedia.org/wiki/Comparison_of_VoIP_software


Figure: Ekiga client 

To sum up I should to say I know this was a bored(sorry for that) theoretical post, but I found a lot of confusion in too many sites and forums among this group of protocols and what they can do for us, so I decided deep in and document it. From now I will come back to work on proofs of concept which are much more funny to test, write and read :)


Jesús Pérez

8/17/2011

VoIP Eavesdropping: UCSniff (II)

 VoIP Eavesdropping: UCSniff (I)


To start this second article I'll dig a little deeper in VoIP Eavesdropping techniques. There are different classifications over the net but I´m going to use "Hacking Exposed VoIP" book (I strongly recommend it) one for being , in my opinion, the most complete. According to it we define four categories for these attacks:

TFTP Configuration File Sniffing
IP phones often obtain their configuration parameters from a TFTP server, you can get an idea imagining something similar to DHCP Protocol, but in application layer of course. In this case attacker could obtain some passwords sniffing or downloading them directly from ftp server, moreover he could even reconfigure phone. In fact I have a fun idea in mind for another POC but we are waiting for someone to lend us a proper phone :).

Number Harvesting
Attacker monitors all calls in order to obtain legitimate numbers and extensions of a system which will be used combined with other attacks.

Call Pattern Tracking 
The attack target is the list with all the calls made by a member of an organization in order to detect suspicious activities among the members.

Conversation Eavesdropping and Analysis
This is the most impressive attack because the bad guy try to record both sides of conversations.

That being said, now I´m going to show UCSniff automates the attacks studying results obtained from last post. Next picture shows files generated after the sniffing.

Figure: Generated files

TFTP Configuration File Sniffing 
As I said before I do not have a proper phone for this test, but UCSniff supports it,  even TFTP Modify Attack (cursiva) as you can see in the picture.


Figure: TFTP Modify Attack


Number Harvesting
During the sniffing we could see extensions involved in calls on the Output and Status(cursiva) panel. Now we can consult them in call.log, calldetail.log and sip.log , which also stores it with much more detailed log including all SIP messages (REGISTER, INVITE, etc.)


Figure: Detailed call list

Figure: INVITE from sip.log 

Call Pattern Tracking
Files commented in Number Harvesting cover this point too.

Conversation Eavesdropping and Analysis
In this example 81-Calling-81-18:48:12-3-reverse.wav stores one side conversation for the reasons commented in previous post, but in a real environment we should get something like this:
Figure: Generated .wavs  in real example

Names are really intuitive so, at this point, I think you can understand by yourself all the helpfull information included in other generated files, you can ask me any doubt in a comment or a mail :). In the next post I hope talk about countermesurements porposed for protect a infrastruture against this kind of Eavesdropping attack.


Jesús Pérez

8/05/2011

VoIP Eavesdropping: UCSniff (I)

After a long time without writing because of different reasons I´m going to begin a group of articles trying to cover different type of attacks against any of the components of a common VoIP (Voice Over Internet Protocol) infrastructure and how to stop them. If you are beginning in this world of VoIP I recommend you to read Building Telephony Systems with OpenSIPS 1.6 where the authors go through basic theoretical and practical skills needed to implement a complete system.


This time, I will start with VoIP Eavesdropping attack, as the name suggest it consists on listen a conversation without speakers consent. This attack existed in the traditional telephony systems and nowadays is also possible against VoIP ones (and other protocols too, in example bluetooth).

As you can imagine we are in front of a classic sniffing attack so, first of all, we need to gain access. Any of the techniques you know are ok, moreover, there are another specific ways for this kind of systems of getting the .pcap file we are looking for. For example, some phones have a "feature" which allows saving a .pcap with all traffic passing over its interfaces and more of them have vulnerabilities in their web control panel, so it could be possible to access to this profitable file :). But this is not the topic of this article despite of being an interesting one too, so I hope take it up again another day.

Now we have the capture, then we need a tool able to understand SIP (Session Initiation Protocol) and RTP (Real-time Transport Protocol), among others. The most used option is Whireshark, but it doesn´t support H.264 video codec so we can´t eavesdrop video conversations, in this case we should call it IP Video Eavesdropping not VoIP Eavesdropping. I found this video where we can see an example of this:


I like Wireshark for studying specific situations but, anyway, we need something more automatic for pentesting tests in order to be capable of reconstruct and synchronize conversations correctly. I usually use Xplico for this kind of things but, for the moment, SIP, SDP and RTP protocol are not fully supported as we can see in the website:

Figure: Xplico supported protocols state 

Today we will use UCSniff, a tool which allows to rapidly test for the threat of unauthorized VoIP and Video Eavesdropping. I paste here some features:
- Audio Eavesdropping
- Video Eavesdropping (creates H.264 format file)
- Realtime Audio Monitor
- GUI Support
- Realtime Video Monitor
- Creates an avi file and muxes audio and video
- Creates a wav file and muxes both forward and reverse audio

For this POC (Proof Of Concept) I will use two virtual machines, one with BT (Backtrack) 5 and Zoiper Classic as client (I had problems running Ekiga on BT5) and another with a Debian Squeeze with a basic installation of Asterisk. It is not a very real environment but it´s enough for this POC, so we don´t need to do MitM (Main in the Middle). I’m sure if you are reading this you know how to gain access with you favorite sniffer or UCSniff ;).

OK, first we need to download the latest version of UCSniff (here) and to install dependencies to compile it on BT5 with GUI (Graphical User Interface) and realtime video monitor:

apt-get install build-essential zlib1g-dev liblzo2-dev libpcap0.8-dev libnet1-dev libasound2-dev libbz2-dev libncurses5-dev apt-get install libx11-dev libxext-dev libfreetype6-dev

NOTE: VLC version and development libraries included in BT5 broke the compilation, so we have to install it directly from VLC repositories before:

add-apt-repository ppa:lucid-bleed/ppa
apt-get update
apt-get install vlc libvlc-dev

Now, go in ucsniff-3.0 folder and compile it:

./configure --enable-libvlc --enable-gui
make
make install

We are ready for run it (graphical interface) for the first time:

ucsniff -G

Figure: UCSniff general view

Yes, it´s not too sexy, above all these evil buttons! xD. For this test we have to select Monitor Mode and Start Sniffing like in the picture and the sniffer will start to capture. Next step is making a call, I will call myself (yes, it´s possible! you should try it :D).

Figure: Calling myself


After accepting the incoming Output Console will log it as in the next two pictures (second took after hang up from one side).


Figure: Logging calls

Well done!, we can see the conversation was captured, there are two calls instead of only one because of virtual machine interface really is mapped to another, but it works, one of this two .wav will be empty and the other will contain saved conversation. I think it´s enough for the first day. Next article we will review all the outputs produced by the sniffer and we are going to deep a bit more in this attack. At the moment, I recommend you visiting the site of the tool where you can learn more about it and view examples using the GUI with MitM and Video Eavesdropping: http://ucsniff.sourceforge.net/guiusage.html

Figure: UCSniff Video Eavesdropping


Jesús Pérez

3/02/2011

¿Por qué utilizar un IDS?: Un caso real con Snort

En un artículo anterior expliqué como instalar de forma sencilla un sistema de detección de intrusos (IDS), más concretamente Snort con la interfaz Snorby. Hoy voy a mostrar la potencia de este tipo de aplicaciones a través de un ejemplo que me encontré en mi trabajo como consultor.
Para situarnos un poco imaginemos una PYME sin ningún responsable del área de sistemas, como muchas en España. Cuando llegas tardas un tiempo en conocer el funcionamiento de todo el sistema (ya que no hay una persona a quien consultarle las dudas) y un IDS ayuda mucho en esta tarea detectando anomalías en el tráfico de red de la organización.



En la primera imagen (vista del último año) se observa que al principio se detectaron mas de 70 incidencias clasificadas como graves y muchísimas leves, las medias las provoqué yo probando con el nmap. Ésto me llevó a investigar un poco más y resultó que el antivirus no escaneaba (o no lo hacía bien del todo) un tipo de ficheros específico de una aplicación y ahí se escondía el archifamoso gusano Conficker en algunos de los equipos. Podemos ver en la gráfica anterior que tras la eliminación del virus se redujeron drásticamente las alertas hasta llegar a la situación actual de la siguiente imagen (vista del último mes).
NOTA: Es importante revisar también las de severidad baja aunque siempre se tratan de falsos positivos.



Lo que quiero destacar es que nos ayudó a detectar un problema que no sabíamos que existía como lo puede hacer con muchos otros. Otra ventaja de su uso es que ayuda a conocer un poco más sobre el funcionamiento de la red de la organización. :)

Jesús Pérez

2/28/2011

El que roba a un landrón ... : h4ckc0nt3st GSIC

ACTUALIZACIÓN: Veo en el twitter que no fuimos los únicos :)
El Jueves llegamos tarde a la fic comentando que seguro que ya era tarde para apuntarnos al h4ck0nt3st de las GSIC, pero cuando entramos en la sala estaba empezando Rubén Santamarta y no todos los días tenemos el placer de poder escuchar a alguien que hace "lo que él hace", así que decidimos aplazar lo de la inscripción.
Cuando conseguimos empezar a jugar vimos que alguno ya llevaban 6 o 7 respuestas y tras solucionar los primeros retos que eran facilitos vimos que no iba a haber manera de coger a los que iban en cabeza por lo que nos fuimos a comer con tranquilidad.
Por el camino se nos ocurrió que "esnifando" todos los paquetes de la red inalámbrica (abierta) seríamos capaces de capturar las respuestas del resto de participantes, ya que la aplicación que se utilizaba en el h4ckc0nt3st no cifraba la comunicación. De esta manera iríamos guardando las respuestas y las rellenaríamos poco a poco para que no fuera demasiado descarado.
Tras la comida volvimos a la facultad y hubo suerte, había gente peleándose con las pruebas:
- Primero pusimos la tarjeta en modo monitor:
airmon-ng start wlan0
- Capturamos todo lo de el canal y el BSSID del h4ckc0nt3st:
airodump-ng --bssid X --channel 13 -w capture mon0
- Como teníamos prisa porque nos empezaba el taller de Alejandro Ramos, el cual recomendamos a todo el mundo, en vez de utilizar el Wireshark probamos con el comandostrings y un simple grep y vimos que esto iba a funcionar:
strings capture-01.cap | grep clave



Nos encontramos algunos problemas:
- Obteníamos también las respuestas erróneas y probarlas todas sería muy ruidoso, así que lo solucionamos afinando un poco el filtrado y listo:
strings capture-01.cap | grep -i -C500 superado | grep clave=


El viernes por la mañana se publicó un certificado para cifrar la aplicación y se nos acabó el juego. :(
Aunque no conseguimos quedar segundos que era el objetivo, siempre es divertido un poco de hacking, y más durante estos eventos.
Gracias a la organización por permitirnos pasar unos días así sin salir de A Coruña y ahora a esperar al Rooted CON'2011. :D
Carlos López
Jesús Pérez




1/15/2011

Snort "for dummies": Insta-Snort


Hoy voy a hablar de Snorby, no me centraré en los sistemas de detección de intrusos (IDS), ni en Snort porque hay muchísima documentación al respecto. Snorby es un "fronted" para el IDS Snort, sus creadores tienen el objetivo de conseguir una herramienta altamente competitiva para la monitorización de redes tanto en entornos privados como empresariales.

Llevaba tiempo siguiendo el proyecto desde las versiones iniciales buscando algo similar al IDS Policy manager (sistemas Windows) para entornos Linux. Con la llegada de la versión 2.0 parece, bajo mi punto de vista, que comienza a estar preparado para su uso en entornos de producción. Aunque de momento no dispone de muchas de las funcionalidades del IDS Policy Manager, nos ofrece otras ventajas y es mucho más bonito :). Podemos probar una demo en la siguiente dirección: http://demo.snorby.org/users/login

NOTA: demo@snorby.org/snorby






De las opciones que tenemos para la instalación prefiero Insta-Snort, ya que es una distribución basada enTurnKey Linux muy sencilla de instalar y que provee de todo lo necesario para que podamos disponer un sistema Snort+Barnyard2 funcionando con una interfaz gráfica muy usable y para. De esta forma podemos estudiar la información que proporcionan los sensores de una forma cómoda y ordenada.

La instalación no supone ninguna complicación, comentar simplemente que es recomendable obtener un código Oink para actualizar las reglas de Snort (registro). De forma opcional, podemos utilizar la nueva funcionalidad que permite analizar capturas de paquetes con formato .pcap, para ello debemos registrarnos en el proyecto OpenFPC. Si necesitamos que snort escuche por otra interfaz que no sea eth0 debemos seguir este manual.

Para acceder a la interfaz gráfica nos conectamos al servidor web de la máquina y utilizamos los datos del usuario administrador por defecto, es más que aconsejable crear otro administrador y eliminar éste una vez logueados.

NOTA: snorby@snorby.org/snorby


Listo, en pocos pasos ya podemos disfrutar de nuestro IDS, en la imagen se ven varias alertas porque fue tomada unos días después de realizar la instalación, para comprobar su funcionamiento vamos a realizar un escaneo de puertos con el nmap a ver si lo detecta. En esta ocasión voy a ponérselo fácil, en otras realizaré pruebas mas complejas a ver como responde.

nmap -F 192.168.0.X

:)




Jesús Pérez