viernes, 9 de mayo de 2014

Ponencia de INCIDE sobre Evasión de Antivirus en Mundo Hacker Day 2014



El congreso Mundo Hacker Day se ha celebrado este año con la participación de ponentes nacionales, entre los que se ha contado nuestro CEO Abraham Pasamar en representación de INCIDE, e internacionales de primer nivel, como el famosos hacker Kevin Mitnick*, que han analizado de forma exhaustiva tanto el futuro de la seguridad en la red, como las diferentes estrategias a adoptar por empresas e instituciones.


     

INCIDE ha participado este año en el congreso con la aportación de nuestro CEO, Abraham Pasamar, que en esta ocasión ha centrado su charla, en la evasión de antivirus. Así pues, ha explicado el funcionamiento y utilidad práctica de los crypters/packers. Según Pasamar, "en una red cada vez más dominada por el lucrativo negocio del Malware, los crypters son herramientas muy útiles, pues consiguen ocultar el Malware de los AntiVirus, ya que pese a haber multitud, no todos todos 'pelean' del mismo modo". 

Los antivirus basan sus detecciones en diferentes tipos de firmas, las firmas estáticas y las dinámicas o heurísticas. Algunas firmas heurísiticas son realmente complejas y otras firmas son extremadamente simples. Para mostrar estas debilidades de detección de algunos AntiVirus, en la presentación, nuestro CEO ha mostrado un ejemplo práctico de cómo con una simple rutina de descifrado al comienzo del stub se pueden bypasear 16 AntiVirus de los 28 que detectaban el malware
    
Una de las ilustraciones introductorias de la charla.


Esto se debe, tal y como ha explicado Pasamar, a que "uno de los principales problemas no resueltos por las firmas de Antivirus, es el hecho de que, tal como se comentó en la presentación, los AntiVirus no escanean en Memoria, o mejor dicho, el escaneo en memoria que algunos pocos AVs efectúan, tiene un índice de detección muy bajo". 
     
En opinión de nuestro CEO, la detección en memoria es clave para maximizar la detección, dado que una gran parte del malware utiliza técnicas para permanecer oculto en disco mediante técnicas de cifrado, y ejecutarse directamente en memoria (sin cifrar). Si la detección en memoria fuese más eficiente, se conseguiría localizar gran parte de Malware que ahora permanece oculto. 
     
En cualquier caso, que nadie se confunda, en INCIDE no estamos recomendando que desinstaléis vuestro AV, ni mucho menos; sigue siendo necesario para evitar infectarse de lo que podríamos denominar 'Infecciones conocidas', pero hay que ser conscientes de que podemos infectarnos de cualquier nueva variante infecciosa, al igual que ocurre con las mutaciones de virus de la gripe. Por ello, al igual que en la vida real, no se puede confiar ciegamente en las vacunas, hay que utilizar la lógica y alejarse de los peligros. En resumidas cuentas, si nos referimos a infecciones cibernéticas: no abrir todo lo que nos envían, no abrir archivos de personas que no conozcamos, no visitar páginas de dudosa reputación... Y usar el sentido común, aunque sea el menos común de los sentidos.

Izq. a Drcha.: Kevin Mitnick y Abraham Pasamar, tras el congreso.
Con la asistencia de unas 500 personas en directo y más de 800 por streaming, se ha debatido sobre los retos y dificultades planteados por la protección de datos y la seguridad de la información en los próximos años. Desde la situación actual de la ciberseguridad en el contexto de empresas e infraestructuras, con especial atención a las botnets, hasta el futuro de la seguridad en el Internet de las cosas, (se calcula que para el 2020 habrá 50.000 millones de dispositivos conectados a la red todos ellos susceptibles de ser atacados por la gran cantidad de información que procesarán), pasando por la esperada ponencia de Kevin Mitnick, figura referente mundial del hacking tras su paso por diferentes establecimientos penitenciarios en Estados Unidos con motivo de los ataques a sistemas de procesamiento de datos de empresas e instituciones de telecomunicaciones, defensa y enseñanza. Dedicado en la actualidad a la alta consultoría estratégica, realizó una cadena de demostraciones en directo con intervención de público asistente. Desde engaños entre Smartphone de voluntarios, hasta sustracción en directo de identidades almacenadas en tarjetas digitales pasando por la interceptación de una transacción on-line con tarjeta de crédito y que mostró en directo al auditorio todos los datos del usuario. 

Podéis descargar el pdf de la charla de 'Evasión de AntiVirus' desde Slide Share, tanto en castellano como en inglés, siguiendo los siguientes links:

*NOTA DE LOS EDITORES: Aunque desde distintos medios se ha venido a calificar a Mitnick como ex-hacker, para nosotros un hacker jamás deja de serlo. El hacker nace, se hace, y es. Desde INCIDE trabajamos para divulgar la imagen correcta del hacking y por que este calificativo deje de tener las connotaciones negativas que en muchas ocasiones se le vienen atribuyendo.


martes, 18 de marzo de 2014

"Messages destruction" at Telegram


After the analysis, here at our previous post, about the way messages are stored within the databases of Telegram, we want to test whether the deletion of messages is done correctly. 

Remember that looking for the self-erased messages in the fields of the different tables in the database, its trail had been replaced by "None", then it would be necessary to determine whether such messages are still persistent, without actually being indexed within the database file "tgdata.db" data. 


To do this, we activate a conversation with self-destruction, and wait until the text has been destroyed.



We proceed to launch the command "strings" that will extract all text strings that are contained within the file "tgdata.db" and then we check that the message is within the extracted text (use "incide" and "auto destru" as key words  to search).


As can be seen, the messages appear in clear text into the file, but they are not in the database, it's just that the fields are shown as empty:


In this way, deleted messages could be recovered if a search is performed in the unallocated space, before they are overwritten by continuing to grow the database.

Our friend Luis Delgado has confirmed us that Android systems behave similarly. When you backup with adb, even without being "rooted", some files of database are created where messages are stored. Messages marked for self-destruction, are removed from the database, but not deleted from the file where are contained. Delgado also has a Python script that allows you to automate the extraction of these strings.



We decide to check whether in other versions of Telegram there are same problems arisen, so we test an UNOFFICIAL version for OS X operating systems so-called "Messenger for Telegram". Remember that the only Telegram official versions are iPhone and Android ones, the rest are based on the published open source. 

In this case, two databases are created: "telegram_store11.db" and "yap_store.db". The messages are stored at first one and at the second one, only identifiers of the encrypted conversations. 


As in the previous case, when searching for text strings in the database, it is possible to extract the messages.



Performing these sort of tests, we have seen that the behavior of the client computer does not respond to self-destruct messages.





By accessing the database to search for messages, we observe that them have been encoded in hexadecimal code:
  
 bb608d9f 01000080 f1f4a000 02000000 2260c93b 379779bc 379779bc 9c490f53 01000000 16637265 61746564 20656e63 72797074 65642063 68617400  
 ba6aeb22 02000080 a75d2001 02000000 2260c93b b5757299 b5757299 c5701053 14746573 74746573 74746573 74746573 74746573 74000000 2063ed3d  
 ba6aeb22 03000080 f1f4a000 02000000 2260c93b 379779bc b5757299 25711053 06416868 68686800 2063ed3d  
 ba6aeb22 04000080 f1f4a000 02000000 2260c93b 379779bc b5757299 9d751053 04507574 61000000 2063ed3d  
 ba6aeb22 05000080 a75d2001 02000000 2260c93b b5757299 b5757299 c6751053 18496e63 69646549 6e636964 65496e63 69646549 6e636964 65000000 2063ed3d  
 ba6aeb22 06000080 f1f4a000 02000000 2260c93b 379779bc b5757299 da751053 06526570 75746100 2063ed3d  
 ba6aeb22 07000080 f1f4a000 02000000 2260c93b 379779bc b5757299 05761053 04507574 61000000 2063ed3d  
 bb608d9f 08000080 684bdc00 02000000 e9ea184d 379779bc 379779bc c0761053 01000000 16637265 61746564 20656e63 72797074 65642063 68617400  
 ba6aeb22 09000080 a75d2001 02000000 e9ea184d b5757299 b5757299 d5761053 18507275 65626170 72756562 61707275 65626170 72756562 61000000 2063ed3d  
 ba6aeb22 0a000080 684bdc00 02000000 e9ea184d 379779bc b5757299 64771053 10546573 74657374 65737465 73746573 74000000 2063ed3d  
 ba6aeb22 0b000080 684bdc00 02000000 e9ea184d 379779bc b5757299 79771053 16546573 74657374 65737465 73746573 74657374 65737400 2063ed3d  
 ba6aeb22 01000000 684bdc00 6dbcb19d a75d2001 379779bc b5757299 7b220e53 1c486f6c 61212042 69656e76 656e6964 6f206120 74656c65 6772616d 21000000 2063ed3d  
 ba6aeb22 02000000 a75d2001 6dbcb19d 684bdc00 b5757299 b5757299 3c240e53 1e486f6c 61204162 656c2c20 636f6d6f 20766120 706f7220 696e6369 64653f00 2063ed3d  
 ba6aeb22 03000000 be43a300 6dbcb19d a75d2001 379779bc b5757299 ba240e53 054f6f6f 6f680000 2063ed3d  
 ba6aeb22 04000000 a75d2001 6dbcb19d be43a300 b5757299 b5757299 d9240e53 0a717565 20706173 c3b33f00 2063ed3d  
 ba6aeb22 05000000 a75d2001 6dbcb19d be43a300 b5757299 b5757299 e6240e53 31657374 6f792068 61636965 6e646f20 70727565 62617320 636f6e20 656c2063 6c69656e 74652070 61726120 4d616320 3a500000 2063ed3d  
 ba6aeb22 06000000 be43a300 6dbcb19d 00000000 379779bc b5757299 f4240e53 0647656e 69616c00 2063ed3d  
 ba6aeb22 07000000 11439100 6dbcb19d a75d2001 379779bc b5757299 0b280e53 1757656c 636f6d65 206d722e 74656163 68657220 f09f9881 2063ed3d  
 ba6aeb22 08000000 76f79a00 6dbcb19d a75d2001 379779bc b5757299 c64a0e53 04f09f91 8b000000 2063ed3d  
 ba6aeb22 09000000 f1f4a000 6dbcb19d a75d2001 379779bc b5757299 dc3c0f53 04486f6c 61000000 2063ed3d  

When analyzing the data we realize that there are columns that are very similar or the same. For example, the first column has two values​​:
  • bb608d9f: Belongs to system messages
  • ba6aeb22: Belongs to user messages
La tercera columna parece indicar el usuario con el que se intercambia los mensajes, mientras que a partir de la octava columna se trata del mensaje codificado, hasta la última columna, que indica el final de éste.

Los dos primeros bits de la octava columna indican el tamaño del mensaje, y a continuación se puede descodificar cómodamente. 


The second column matches with the message identifier indicating whether it is encrypted (which ends in 80) or not. 

The third column seems to suggest the user whom messages are exchanged, while from the eighth column there is the coded message, to the last column, which indicates the end of it. 


The first two bits from the eighth column indicate the size of the message, and then we can decode it comfortably.

For example, for the case of the message 

 ba6aeb22 09000000 f1f4a000 6dbcb19d a75d2001 379779bc b5757299 dc3c0f53 04486f6c 61000000 2063ed3d  
  • 04: Size of 04 bytes. 
  • 486f6c 61 = Hi 
  • 000000 = The remaining space is able to be filled

So replacing the bytes correctly it would be shown as follows:


 ba6aeb22 09000000 f1f4a000 6dbcb19d a75d2001 379779bc b5757299 dc3c0f53 04Hol a000000 2063ed3d  


As we have seen in this article, the message deletion is not done safely, as though they are removed from the database, no compaction is done to remove the unallocated space nor an overwrite of these is performed. In the computer application, the situation does not improve, the messages are encoded when stored, but they are still unencrypted, even allowing its self-destruction. 


Therefore, we have doubts. Do these problems are only with the programs analyzed? Or come from a failure in the implementation of the measures?

Abel Gómez is Senior Pentester in INCIDE

You can follow his posts at zprian.blogspot.com.es


lunes, 3 de marzo de 2014

About the myth of Telegram's messaging encryption



Since Facebook announced WhatsApp purchase, their users have been looking for alternatives to this instant messaging application. An alternative application that has increased its popularity in the last few days (2 million new users), due to the WhatsApp recent blackout, is Telegram. Regarding its creators, the key points of Telegram's great success are that it will be free forever and their privacy and security. As a proof of its security, Telegram has offered a reward for anyone who could break their message encryption.



The main difference between Telegram and WhatsApp is that Telegram allows their users to use peer-to-peer encryption and message time expiration. Despite not being activated by default, every Telegram user can use these security options when needed.

However, conversations are not only sent between mobile devices, they are stored in your mobile devices as well. Today we are going to talk about how these conversations are stored “at-rest” in your mobile device, even encrypted ones. We are going to use an iPhone (iOS 7.04), but similar techniques could be used in different platforms such as Android.

Our first approach was to use an iTunes backup. When backing up a mobile device, all information that would be needed to completely restore the device is stored, including all kind of internal information such as WhatsApp or Telegram conversations. As usually happen in mobile device applications, Telegram stores its internal information in SQLite files. In this iTunes backup we find a file called “tgdata_index.db” that contains interesting tables and information.


The most interesting tables in this database are “messageIndex_v29” and “messageIndex_v29_content”. Both of them store the conversation messages, but we can’t identify whom is the user talking with. Analyzing in depth “messageIndex_v29_content” table, we find that “docid” is some kind of message id, but it works in two different ways: Sometimes it is sequential (1, 2, 3, …) and sometimes looks random (-2147483635, 800000013, ...). Regarding our research, this behavior change depending on the kind of communication (encrypted or not).


As a result, anyone that could backup your device or to get access to your backups, would be able to read your messages, even encrypted ones.

Other interesting approach would be to look into the mobile device itself. Using a jailbroken device we copied the application’s directory for further analysis.
In this directory we find a new “tgdata.db” file that we haven’t seen in our backup. However, the most widely used SQLite tools fail to open this file and show the following error message: 
"malformed database schema (unread_by_cid_with_date) - near "WHERE": syntax error"

In order to access to the information, it is necessary to use the sqlite3’s dump feature and to create a new database file from its SQL sentences. We can now access to the full content and rebuild completely the conversations, even identify the people whom the user is talking with.


In addition, encrypted conversation IDs are stored in the “encrypted_cids_v29” table, so you can use this information together with the messages information in order to rebuilt completely all the encrypted conversations.

Finally, we have developed a python script that exports all the conversations to a human readable text format from the original database file.

Given a Telegram conversation such as the following one:


You can use our tool in order to export it from the database files as follows:


As you can see, self-destructed messages are not present in the database, but there is a reference to them. You can know how many messages were sent, when they were sent and whom they were sent. The only removed information is the message itself, which is stored as “None”. Some other SQLite forensic techniques could be used in order to recover these messages, but we will go in depth on this in following posts.

Concluding, It seems that Telegram’s security is mainly focused on network communications, and not in how these conversations are stored in-rest. Does it mean that Telegram communications are completely secure? Well… just let us to go in depth with it and stay tuned with us.

The used python script is following:

1:  #!/usr/bin/python  
2:  #coded by "Abel Gomez at INCIDE"  
3:  import codecs # -*- coding: utf-8 -*-  
4:  import unicodedata  
5:  import datetime  
6:  import os  
7:  import sqlite3 as lite  
8:  import subprocess  
9:  import sys  
10:  reload(sys)  
11:  sys.setdefaultencoding("utf-8")  
12:    
13:  users = {}  
14:  con = None  
15:  directory = "messages"  
16:  try:  
17:      con = lite.connect('./Documents/tgdata.db')  
18:  except Exception:  
19:      print "\nEs necesario ejecutar el archivo desde el directorio raiz de Telegram\n"  
20:      sys.exit()  
21:  if not os.path.exists(directory):  
22:      #if the directory does not exists we create a directory to store the messages extracted  
23:      os.makedirs(directory)  
24:    
25:  # the file that contains the db is corrupted, so we make a dump of the DB and create a new one.   
26:  if os.path.exists('dump.sql'):  
27:      os.remove('dump.sql')  
28:      os.remove('dump.db')  
29:  f = os.system('sqlite3 Documents/tgdata.db ".dump" |grep -v "CREATE INDEX" >dump.sql; sqlite3 dump.db ".read dump.sql"')  
30:    
31:  con = lite.connect('dump.db')  
32:  cur = con.cursor()  
33:  cur.execute("SELECT uid,first_name,last_name FROM users_v29")  
34:  for i in cur.fetchall():  
35:      #user list  
36:      users[i[0]] = "%s %s" % (i[1],i[2])  
37:    
38:  cur.execute("SELECT cid,date,from_uid,message FROM convesations_v29")  
39:  #at this point we have the conversation list  
40:  convs = cur.fetchall()  
41:  sep = "+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n"  
42:  for i in convs:  
43:      #for each conversation, we test if the conversation is encrypted and extract all the conversations  
44:      conv = i[0]  
45:      partner = users[i[2]]  
46:      fd = open(directory+'/conversation_'+str(conv)+'.txt' ,'w');  
47:      fd.write("\nConversation %s with %s :\n\n%s"% (str(conv),partner,sep))  
48:      cur.execute("SELECT 'True' FROM encrypted_cids_v29 WHERE cid='%s'" % (str(conv)))  
49:      cypher = cur.fetchone()  
50:      if cypher is not None:  
51:          fd.write("This conversation is encrypted\n\n%s" % (sep))  
52:      cur.execute("SELECT from_id,to_id,date,message,mid FROM messages_v29 WHERE cid = %s ORDER BY date,mid" % (str(conv)))  
53:      for men in cur.fetchall():  
54:          missage = men[3]  
55:          user_from= users[men[0]]      
56:          if men[1] == conv: user_to = partner  
57:          else: user_to = users[men[1]]  
58:          if men[3] == None: #could be an image or a deleted message  
59:              cur.execute("SELECT 'True' FROM media_v29 WHERE mid = %s" % (str(men[4])))  
60:              if cur.fetchone() is not None: missage = "+-+-+SHARED FILE+-+-+"  
61:          date = datetime.datetime.fromtimestamp(men[2])  
62:            
63:          fd.write("%s ---> %s (%s): %s \n%s\n" % (user_from,user_to,date,missage,sep))  
64:        
65:  print "Ha finalizado el proceso de export, puede consultar los mensajes en './messages'\n"  


Abel Gómez is Senior Pentester at INCIDE

You can read more of his posts in zprian.blogspot.com.es