Monday, November 21, 2011

Ingeniería Social usando las redes sociales y la Geo Localización


Tabla de Contenidos
Ingeniería Social usando las redes sociales y la Geo Localización 1
Abstract 1
Estadísticas de Twitter 2
Descripción del problema 3
Prueba del concepto 4
¿Por qué, debería preocuparme? 8
¿Cómo puedo protegerme? 8

Abstract


Twitter es una de las redes sociales más usadas y la #1 en micro blogging.

Fue lanzada el 16 de Julio de 2006 con sólo unos pocos usuarios y ahora tiene más de doscientos millones. Su principal función es proveer al usuario la capacidad de compatir texto con otros usuarios con un máximo de 140 caracteres y también tiene servicios asociados como twitpic que le permite subir imágenes asociadas al contenido publicado, a su vez Twitter permite agregar información sobre la ubicación geográfica donde se genera el contenido, latitud y longitud, esta información queda almacenada como metadata del Tweet. Este tipo de metadata no sólo puede ser agregado en fotos sino también en múltiples formatos de archivo s multimedia como videos, SMS, entre otros.

Además de la Geo Localización también existe el Geo Coding donde este proceso convierte a coordenada no geográfica como el nombre de una calle en datos de Geo Localización o vice versa.

Estas características son fantásticas y se han convertido en herramientas muy importantes para todo usuario de smartphone debido a la capacidad y servicios asociados con la Geo Localización y la telefonía móvil. Sin embargo, así como esta información es muy útil en una gran variedad de aspectos de la vida cotidiana, también posibilita el mal uso de esta información por cualquier persona que sea capaz de navegar el sitio de Twitter o alguna de sus aplicaciones, para revisar la línea de tiempo del usuario, analizarla y crear información de inteligencia, que podría ser usada para generar patrones de comportamiento, lugares que frecuenta y actividades que realiza, con el alto riesgo que esta información implica. Es por eso, que así como una funcionalidad tan fantástica se puede convertir en un arma de doble filo que puede atentar contra, incluso la integridad y seguridad de la persona.

Estadísticas de Twitter

  • Twitter actualmente tiene 100 millones de usuarios activos
  • 50 Millones de usuarios conectados diariamente
  • 200 millones de usuarios registrados
  • El número de usuarios que se conectan a Twitter de forma mensual ha ido en aumento desde principios de año
  • 55 millones de usuarios se conectan a Twitter desde su teléfono o tablet, cada mes.
  • Twitter.com recibe 400 millones de visitantes al mes
  • Las visitas a Twitter.com aumentó en un 60% este año
  • El 40% de los usuarios de Twitter, no “Twitea” de forma mensual pero revisa los Tweets de los otros usuarios
  • El crecimiento proyectado para fin de año son 26 Millones de usuarios adicionales.
  • Twitter almacena aproximadamente un billón de tweets cada cinco días.
  • Twitter tiene un nuevo récord de cantidad de Tweets por segundo de 8.900 (TPS)


Figure 1: Distribución de usuarios y utilización de Twitter

Descripción del problema


El explosivo aumento de los dispositivos móviles y la gran democratización del acceso a Internet desde cualquier parte del mundo, ha permitido que gran parte de los usuarios que poseen un dispositivo móvil tenga conexión a Internet.


La Geo localización en los dispositivos móviles es uno de los servicios más usado por los usuarios de smartphones, esto debido a provee una gran gama de servicios asociados, donde permiten a los usuarios encontrar desde el restaurant más cercano y su calificación por usuarios de su mismo grupo etáreo, hasta usarlo como asistente para llegar a una determinada dirección en la ciudad usando la ruta más corta, todo esto al alcance de unos taps.

Es así como los usuarios pueden aprovechar los servicios de geo localización para encontrar servicios disponibles, también pueden, a través de las redes sociales, como Twitter, generar contenido y además agregar la Geo Localización asociada al momento de publicar el contenido.


La metadata de Geo Localización no sólo es posible encontrarla en redes sociales si no también en distintos tipos de archivos multimedia como por ejemplo, videos e imagenes, en este último lo podemos encontrar en su formato EXIFF, donde si el dispositivo donde se tomó la foto tenía Geo Tagging a través de GPS o triangulación de localización a través de A-GPS con las redes celulares o WIFI, esta información quedará almacenada como metadata en la imagen y estará disponible para cualquier persona que tenga acceso a la imagen.


En esta oportunidad nos enfocaremos particularmente en Twitter, por su rápido crecimiento y los innumerables enfoques en que este servicio puede ser usado, sin embargo es necesario señalar que hoy en día la mayoría de las redes sociales como por ejemplo, facebook, linkedin, myspace, orkut, foursquare, entre otras, permiten asociar o sincronizar su contenido a través de Twitter.


El problema de publicar contenido Geo Etiquetado (Fotos, Tweets, Etc) es que en un 99% de las ocasiones esa información estará disponible a todo el mundo. Es así como cualquier persona puede acceder, procesar, analizar esta información y posteriormente usarla con múltiples fines, tales como: Comercial, Marketing focalizado, SPAM o fines reñidos con la moral.


Es así como el acto tan simple e inocente de publicar:

“Esta increible el concierto, La FOX en el movistar arena y quedan dos horas”


Puede utilizarse de varias formas, como lo veremos a continuación en el Proof of Concept.


Prueba del concepto


Con el fin de demostrar la teoría se ha desarrollado un pequeño script en Python, donde se implementan dos librerías, Twytton, HTML y se usa el servicio de libre disponibilidad de Google Maps.

El script, el cual busca a través del Timeline de un usuario X de Twitter si posee contenido con Geo Localización, lo almacena y genera una página HTML con el mapa donde se generó el contenido , sus coordenadas geográficas, latitud y longitud, y finalmente genera una traza de los lugares donde el usuario generó contenido GeoLocalizado.



Ejecución del script via línea de comandos en OS X con los parámetros: Nombre del usuario y cantidad de Tweets que se desea investigar (máximo 200 por el API de Twitter)



Completado el proceso se genera una página HTML con contenido estático y las imágenes son generadas automáticamente usando las coordenadas y el servicio de Google Maps




En este ejemplo el usuario tiene más de cuarenta Tweets con Geo Localización, así es que por fines demostrativos sólo se mostraron algunos resultados tomados de forma aleatoria.


Podemos verificar la teórica que los usuarios tienden a generar el contenido Geo Localizado en los mismos lugares/ocasiones.


Si hacemos click en el link de coordenadas automáticamente creado por la aplicación, podemos revisar la ubicación con el mapa dinámico de Google que nos provee de información adicional y herramientas de zoom in/out. En este caso en particular podemos apreciar que hemos podido obtener la imagen de la residencia del usuario.





Finalmente se genera el trazado de los lugares Geo Localizados por el usuario al momento de generar contenido social:




Así vemos que el simple hecho de generar contenido Geo Localizado puede convertirse de algo “cool” en información crítica, como lo expondremos a continuación.











¿Por qué, debería preocuparme?


En el estudio se comprobó que con una muestra de diez usuarios que publican contenido Geo Localizado, en al menos cinco existe una relación entre la frecuencia y los lugares en que se genera contenido Geo Localizado, es decir, “Twitean” por lo general en los mismos lugares, momentos o situaciones.


Con muy poco análisis se puede utilizar esta información, públicamente disponible, para hacer un perfil de comportamiento de la persona, lugares que frecuenta, duración y permancia en X o Y lugar.


Al publicar este tipo de información usted está generando y ampliando su superficie de ataque, desde el punto de vista de la seguridad, donde esta información puede ser usada que atenten con su seguridad.


No es raro leer de vez en cuando que en EEUU han robado y desvalijado casas completas, usando camiones de mudanza, robando hasta la pecera de la casa, debido a que uno de los dueños, había publicado un Twitter que decía que se había ido de vacaciones por el fin de semana a la playa.


Es así como también no sólo puede poner en peligro bienes materiales sino que también su integridad como persona, donde esta información puede ser usada para generar un perfil y posteriormente ser usada para perpretar hechos tan despreciables como el secuestro o el acoso sexual.

¿Cómo puedo protegerme?


La respuesta es fácil, no publique información sensible o personal, si bien es cierto que existe una tendencia a nivel mundial de publicar a todo el mundo que se está haciendo a todo momento, esto no necesariamente es una práctica segura, como lo hemos visto esta información puede ser usada con fines delictuales y poner en riesgo no sólo a quién publica el contenido, si no que a todo su grupo familiar.


A continuación se describirán como deshabilitar las configuraciones que permiten a las aplicaciones móviles, obtener la Geo Localización del usuario de forma predeterminada.





Dispositivos con Android
Debes inhabilitar completamente Mi ubicación de tu dispositivo para dejar de utilizar Google Maps. En la pantalla principal, accede a "Menú" > "Ajustes" > "Ubicación y seguridad" y desactiva la opción "Usar redes inalámbricas".

Dispositivos BlackBerry
Selecciona "Menú" > "Ayuda" y desactiva la opción "Habilitar Mi ubicación".

Dispositivos iPhone o iPod Touch
Puedes optar por no "Permitir" el acceso a la ubicación la primera vez que utilices una aplicación o puedes inhabilitar por completo los servicios de ubicación del teléfono. Para desactivar los servicios de ubicación, accede a la pantalla principal, selecciona "Ajustes" > "General" y desactiva la opción "Servicios de ubicación".

Dispositivos con Palm webOS
En el menú de aplicaciones, accede a "Servicios de ubicación" y desactiva "Localización automática".

Dispositivos con Symbian S60 y Windows Mobile
Selecciona "Menú" > "Opciones" y, a continuación, selecciona la opción "Desactivar Mi ubicación".

Sony Ericsson y otros dispositivos
Selecciona "Menú" > "Ayuda" > "Mi ubicación (beta)" y, a continuación, selecciona la opción "Desactivar Mi ubicación".

Wednesday, September 21, 2011

MacPorts and OS X Lion

so its been while without messing with MacPorts after upgrading to Lion and I went ahead to check its status and it was outdated, so I tried to get it up to date:

# port selfupdate
Warning: port definitions are more than two weeks old, consider using selfupdate
---> Updating the ports tree
---> Updating MacPorts base sources using rsync
MacPorts base version 1.9.2 installed,
MacPorts base version 2.0.3 downloaded.
---> MacPorts base is outdated, installing new version 2.0.3
Installing new MacPorts release in /opt/local as root:admin; permissions 0755; Tcl-Package in /Library/Tcl

Error: /opt/local/bin/port: port selfupdate failed: Error installing new MacPorts base: shell command failed (see log for details)

so WTF!

after surfing a while learned that after upgrading to OS X Lion the MacPorts seems to have problems AKA doesn't work anymore, there are a few guides to upgrade it out there but as for sanity, I'd rather get it uninstalled.

1) got a list of all your ports:
# port -qv installed > AllMyPorts.txt , you can use porticus as well, its up to you

2) Try to uninstall all the ports:
#port -f uninstall --follow-dependents installed

too many nested evaluations (infinite loop?)
Log for atk is at: /opt/local/var/macports/logs/_opt_local_var_macports_registry_portfiles_atk_1.32.0_0/main.log
Warning: Failed to execute portfile from registry for atk @1.32.0_0
too many nested evaluations (infinite loop?)

that didnt work so:

# sudo port -f uninstall installed (not the ideal but it eventually remove all the dependencies)

3) at this point you will no longer have MacPorts installed so download the new version for Lion (2.0.3)

4) Eventually you will get an error message when installing saying that xCode is not installed or was installed with UNIX development (10.5+) so go and download xCode4 (Apple Store, its free no worries), once the AppleStore says "Installed" you need to actually install it! so go to Applications then look for xCode4 and install it and give it a try again to the MacPorts installer.






Sunday, September 11, 2011

Twython: Python API for Twitter

pretty neat, easy to use API for twitter, its twython, I got it installed and working in less that 2 minutes:

Pre-requesites: Python already installed on the box.

$ sudo easy_install twython
$ python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
>>> from twython import Twython
>>> twitter = Twython()
>>> results = twitter.searchTwitter(q="NASA", rpp='10')
>>> for tweet in results['results']:
... print "User: %s \n Tweet: %s" % (tweet['from_user'], tweet['text'])
...
User: CarlaEid
Tweet: Reading: http://t.co/1Rlpmr0 #Arabic #NASA
User: raccoonTweetzz
Tweet: If NASA sends a pregnant woman into space and gives birth...is the baby an alien? (•͡.̮ •͡ )
User: JHarley36
Tweet: @PrettyMoneyPaid I've been working for NASA.
User: chrome_ghost
Tweet: 9.11 as seen by the only american not on earth at the time. http://t.co/SInyMAh
User: sebargue
Tweet: RT @monterocnn: Así se vieron ataques contra Nueva York desde el espacio. Video: http://t.co/x0BB9tm
User: supermorgy
Tweet: @mariefrance16 Nasa work ako Marie. Downtime kami. Kaya nag hahabol productivity. Will watch it with honnie on Saturday!
User: bongiss
Tweet: @Lalalishh nasa new york ka? Haha
User: UNIVERSITAM
Tweet: UNIVERSITAM: LA NASA LANZA LAS SONDAS GRAIL CON DESTINO A LA LUNA http://t.co/ebBGucY
User: taroshaw
Tweet: RT @Mrkat0: NASAの人工衛星落下へ 重さ6トン、月末にも http://t.co/lKXubuz
ジョー、君はどこに落ちたい…?
User: hugonz
Tweet: Y no, la NASA no cuenta. RT @circulobastiat: "Los grandes avances de la civilización jamás han venido deun gobierno central" Milton Friedman
>>>



Monday, August 29, 2011

New Lab box, Finally! hp N36L with ESXi 4.1


YES! After really long time, I finally decided to go for it.
I was looking for something really particular:
a) small size (mac mini or shuttle like)
b) fan less or very little noise
c) low power consumption

After a little bit of research, several folks were talking about this new micro server compatible with ESXi out of the box, the HP N36L microserver.



I went for it, it comes with an useless 1GB ram which now I use it use it as dart!, so I got it working with the max of ram which is 8GB with 2x4GB Kingston KVR133/PC3-10600.

did I mention it does not come with optic unit? yeah pity, so I had to make a cheap USB Stick bootable with ESXi 4.1 in order to install the server, here is where the pain begins...

I looked at few tutorials out there and none of them worked, on top of that I ran in every single problem you can imagine:

  • USB Stick didn't boot
  • when It booted it didn't recognize the kickstart file
  • when I solved the kickstart file configuration issue It didn't see the hardisks to install (
  • error: /tmp/ks.cfg: line 6: auto part --firstdisk specified, but no suitable disk was found)
  • then I managed to solved that and....
  • It didn't work because I was now getting an "md5 sum mismatch error", which by the way I solved re-copying by *zillion times the 4,1 files into the USB Stick.
  • So I did it! I got ESXi 4.1 working, and this is the log how i created the USB installer stick:

I didn't have any other Linux box other than the actual backtrack 4r2, its based on ubuntu, so anyways:

root@bt:~# fdisk /dev/sdb1

The number of cylinders for this disk is set to 31999.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
(e.g., DOS FDISK, OS/2 FDISK)

Command (m for help): d
Partition number (1-4): 1

Command (m for help): d
Partition number (1-4): 2

Command (m for help): d
Partition number (1-4): 3

Command (m for help): d
Selected partition 4

Command (m for help): d
No partition is defined yet!

Command (m for help): n
Command action
e extended
p primary partition (1-4)
p
Partition number (1-4): 1
First cylinder (1-31999, default 1):
Using default value 1
Last cylinder, +cylinders or +size{K,M,G} (1-31999, default 31999):
Using default value 31999

Command (m for help): a
Partition number (1-4): 1

Command (m for help): t
Selected partition 1
Hex code (type L to list codes): b
Changed system type of partition 1 to b (W95 FAT32)

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 22: Invalid argument.
The kernel still uses the old table.
The new table will be used at the next reboot.

WARNING: If you have created or modified any DOS 6.x
partitions, please see the fdisk manual page for additional
information.
Syncing disks.
root@bt:~# umount /dev/sdb1
root@bt:~# mkfs.vfat -n BOOT -F 32 /dev/sdb1
mkfs.vfat 2.11 (12 Mar 2005)
root@bt:~# syslinux -s /dev/sdb1
root@bt:~# dd if=/usr/lib/syslinux/mbr.bin of=/dev/sdb
0+1 records in
0+1 records out
404 bytes (404 B) copied, 0.0147531 s, 27.4 kB/s
root@bt:~# mount /dev/sdb1 /root/usb
root@bt:~# cp -r /media/cdrom0/* /root/usb/
root@bt:~# cd /root/usb/
root@bt:~/usb# rm isolinux.bin
root@bt:~/usb# mv isolinux.cfg syslinux.cfg


This box can manage easily a couple of VMs of low CPU needs, I'll probably get XBMC or freeNAS running besides some *nix boxes to play around with.


as FPSrussia! says..... as usual, have nice day! hahahaha.




Thursday, August 18, 2011

Converting password/string to Phonetic Alphabet [Python]

So, every time my buddies stop by, ask, what's the WIFI's password? then I usually give them a piece of paper with a 160 Bit password of 20 Characters like:
{[Ck~Yv~xV9~-R9EMi-k so they go like: can you read this back to me?

So as I've been doing some code, I wanted to be lazy and get my generated passwords in the phonetic alphabet in order to make it easy to pass on:

and this is the result:

#!/usr/bin/python
import sys

if len(sys.argv) < 2:
print "[-] Nothing to do, please provide the password or string: python script.py myPa$$w0rd""
sys.exit()

d = {"a":"alpha","b":"bravo","c":"charlie","d":"delta","e":"echo","f":"foxtrot","g":"golf","h":"hotel","i":"india","j":"juliett","k":"kilo","l":"lima","m":"mike","n":"november","o":"oscar","p":"papa","q":"quebec","r":"romeo","s":"sierra","t":"tango","u":"uniform","v":"victor","w":"whiskey","x":"x-ray","y":"yankee","z":"zulu","-":"dash","0":"Zero", "1":"One", "2":"Two", "3":"Three", "4":"Four", "5":"Five", "6":"Six", "7":"Seven", "8":"Eight", "9":"Nine"}

print("[*] Your password/string of lenght:%d can be read as follows:\n" % (len(sys.argv[1])))
for char in sys.argv[1]:
if char.lower() in d:
if char.lower() == char:
print d[char]
else:
print d[char.lower()].upper()
else:
print char

----
output example:

$ python passToWords.py {[Ck~Yv~xV9~-R9EMi-k
[*] Your password/string of lenght:20 can be read as follows:

{
[
CHARLIE
kilo
~
YANKEE
victor
~
x-ray
VICTOR
Nine
~
dash
ROMEO
Nine
ECHO
MIKE
india
dash
kilo

Tuesday, August 16, 2011

Getting HTTP headers and searching for X pattern in the body content with Python

I've done this small script to get the HTTP headers, get the server response and then look for x text:


#!/usr/bin/python
import sys
import httplib
from urlparse import urlparse

#Initializing some vars
target_address=""
resource = ""
conn = ""
res = ""


def UserInput():
global target_address
global resource
i = 0

while True:
if i >= 2:
print "[-] Don't try to be sneaky if you want to test, provide a valid URL, I'm exiting..."
sys.exit();

url = raw_input("Enter a valid URL to Test: ")
if url and "http://" not in url:
print "[-] you need to follow RFC 1808 when working with URLs, but not worries, I've corrected it for you"
url = "http://" + url
o = urlparse(url)
#Validating that user's input has a resource to GET /something.some
if not o.path or o.path == "/":
print "[-] Nothing to do, you need to provide a valid URL and RESOURCE to test i.e http://www.test.com/resource.htm, I'm exiting..."
sys.exit()
#all good and set so lets assign them
target_address = o.netloc
resource = o.path
break
i +=1


def Connection():
global conn
global res
print "\n[?] Trying to connect to: " + target_address
print "[?] Trying to GET: " + resource
conn = httplib.HTTPConnection(target_address,timeout=5)
conn.request("GET", resource)
res = conn.getresponse()
#Goal 1: Print the response of the server:
print "[*] Server Response: " + str(res.status) + " Details: " +res.reason
#Goal 2: Print the response of the server:
print "\n[*] Server HEADER Response:"
for i, (header, value) in enumerate(res.getheaders()):
print "%s: %s" % (header.capitalize(), value.capitalize())

def CheckXSS():
#Goal 3: check if there is an XSS in the body
xss = "alert---document.cookie---" # <- i had to modify the actual text since it seems blogger doesn't like script tags
if xss in res.read():
print "\n[*] WARNING: XSS detected in HTTP response body!, this guy knows to how to get it done!"
else:
print "\n[*] XSS was not found in the body. "

try:
UserInput()
Connection()
#if there is a valid resource and exists, we check it.
if res.status == 200:
CheckXSS()
else:
print "\n[-] Nothing to do, you need to provide a valid URL and RESOURCE to test i.e http://www.test.com/resource.htm, exiting"
conn.close()
print "[*] Done!"
except Exception as msg:
print ("\n[-] There is a Problem, Check OSI tier 8 and try again\n[-] Error Details: %s" % msg)






As always, feedback is appreciate, cut me some slack though, I dont code everyday just from time to time.

Bash script to put all the info from separate files in one

So, I had this directory tree full of python scripts I've written but I wanted to put them all in one file to make it easy to read/find stuff, so I was trying to think a way to cut myself some slack, so I ended up writing this small piece of code in bash to get it done:


#!/bin/bash
for filex in $(ls *.py);do
echo "working on file: $filex"
echo -e "\n----------$filex-------------------\n" >> allTheCode.txt
cat $filex >> allTheCode.txt
echo -e "\n-----------------------------------\n" >> allTheCode.txt
done


I know this looks ugly, however it works :), if you know a better way just drop me a comment!