nodejs ~ Usage?

Hi people,

I would like ask you what is the purpose of nodejs…

Is it only a long polling server with events, or is it anything more? (Some of you said me that it is a server to do parallel tasks…).

I have been developing a long polling Comer server… an HTTP bruteforce (hehe, it is a hacker blog!! I built evil tools too!!)… and a system bus :) . So I want to share this last piece because I think that it is quite cool. It is MULTI-CORE and MULTI-SERVER (thanks to Redis) with TCP sockets. If you read it, you will see that it uses 8 bytes + 8 bytes to identify the sender and the listener. I didn’t know how to do it better ^^”

Any comment? :) I want to do cool projects with nodejs (& mongodb) but I don’t have any idea… give me some please! :)

/**
*  NodeJS - Service Cluster BUS using REDIS
http://www.opensource.org/licenses/gpl-2.0.php

$ nodejs sbus.js
(1) $ nc 127.0.0.1 3055; AAAAAAAA
(2) $ echo -e BBBBBBBBAAAAAAAAThisIsSparta | nc 127.0.0.1 3055
*/

process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
});

var redis = require('redis');
var net = require('net');
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
console.log('[CPU_MASTER] ' + process.pid);
for (var i = 0; i < numCPUs; i++) {
var worker = cluster.fork();
console.log('[CPU_WORKER] ' + worker.pid);
cluster.on('death', function(worker) {
console.log('[DEATH] worker ' + worker.pid + ' died. restart...');
cluster.fork();
});
}
}
else { // else ?

var listen = redis.createClient();
var client = redis.createClient();

listen.on('subscribe', function (channel, count) {
console.log('[' + process.pid + ']' + ' (subscribe) channel:(' + channel + ') , count:(' + count + ')');
});

listen.on('message', function (to, data) {
var from = data.substr(0,8);
var to = data.substr(8,8);
var msg = data.substr(16);
console.log('[' + process.pid + ']' + ' (message) from:(' + from + ') , to:(' + to + ') , msg.length:(' + msg.length + ')');
process.emit(to, msg);
});

var server = net.createServer(function (socket) {
socket.setTimeout(0);

var firstTime = true;
var from = null;
var to = null;

socket.on('close', function(count) {
console.log('[' + process.pid + ']' + ' (close) socket');
listen.unsubscribe(from);
console.log('[' + process.pid + ']' + ' (unsubscribe) from:(' + from + ') , count:(' + count + ')');
});

socket.setEncoding('utf8');
socket.on('data', function(data){

from = data.substr(0,8);
to = data.substr(8,8);

process.on(from, function(msg) {
console.log('[' + process.pid + ']' + ' (socket.write) from:(' + from + ') , msg.length:(' + msg.length + ')');
socket.write(msg);
});

if (firstTime) {
listen.subscribe(from);
firstTime = false;
}

if (to.length != 8) {
console.log('[' + process.pid + ']' + ' (to.length<8) => registering service');
return;
}

console.log('[' + process.pid + ']' + ' (data) from:(' + from + ') , to:(' + to + ')');
client.publish(to, data);
});
}).listen(3055);
}

Buscando malware en aplicaciones Android

Después de la estupenda charla de ayer de AppInBilling en el GTUG-Barcelona, me motive a hacer el pequeño experimento narrado a continuación . No tenía muy claro que esperaba conseguir, pero quería probar un vector de testing bastante interesante.

La idea consiste en automatizar un mismo proceso sobre muchos elementos diferentes, obteniendo así mucha información en la que poder grepear y llevarte sorpresas. En este escenario, los elementos son las aplicaciones APK y el proceso es la herramienta apktool.

Etapa 1. Descargando aplicaciones

El sitio más usual para descargar APKs sería el propio Market oficial, pero también hay sitios como http://www.malwaredump.com/ que pueden resultar muy interesantes para este experimento.

Yo encontré freewarelovers.com con Google, y aún sin saber muy bien que tipo de aplicaciones me encontraría, decidí apostar por él. Saqué el patrón para descargar todas sus aplicaciones automáticamente y, aunque hay que hacer 3 peticiones por aplicación, la base de datos son sólo unas 1.670 aplicaciones. El script os lo dejo a continuación:

<?php

ini_set('max_execution_time', 60*60 ); // 1 hora

mkdir('apk');

$pid = pcntl_fork();

if ($pid == -1)
{
die('could not fork');
}
else if ($pid)                        // padre
{
pcntl_wait($status);             //Protect against Zombie children
}
else                                 // hijo
{
$ch = curl_init();
$dl = strtolower(implode('|', glob("apk/*")));

$defaults = array(
CURLOPT_HEADER            => FALSE,
CURLOPT_NOBODY            => FALSE,
CURLOPT_RETURNTRANSFER    => TRUE,
CURLOPT_AUTOREFERER        => TRUE,
CURLOPT_USERAGENT        => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.1) Gecko/20100101 Firefox/6.0.1',
CURLOPT_FOLLOWLOCATION    => TRUE,
CURLOPT_MAXREDIRS        =>  5,
CURLOPT_CONNECTTIMEOUT    => 30,
CURLOPT_TIMEOUT            => 30,
CURLOPT_SSL_VERIFYPEER    => FALSE,
CURLOPT_SSL_VERIFYHOST    => FALSE,
CURLOPT_COOKIEJAR        => tmpfile(),
CURLOPT_VERBOSE            => FALSE,
CURLOPT_CUSTOMREQUEST    => 'GET',
);

$cats = array(
'/communications',
'/entertainment',
'/finance',
'/games',
'/health',
'/multimedia',
'/news',
'/productivity',
'/reference',
'/shopping',
'/sports',
'/system',
'/travel' );

foreach($cats as $cat) {

// descargar lista unica de aplicaciones por categoria
$defaults[CURLOPT_URL] = 'http://www.freewarelovers.com/android/category'.$cat;
curl_setopt_array($ch, $defaults);
$body = curl_exec($ch);

preg_match_all('|"/android/app/([\w\|-]+)"|', $body, $matches);

$apps = array_unique($matches[1]);

foreach($apps as $app) {

if (trim($app)=='') continue;
if (strpos($dl, strtolower($app))) continue;

// consultar el enlace de descripcion de la aplicacion
$defaults[CURLOPT_URL] = 'http://www.freewarelovers.com/android/app/'.$app;
curl_setopt_array($ch, $defaults);
$body = curl_exec($ch);

preg_match_all('|"/android/download/temp/(.*).apk"|', $body, $matches);
$nameApp = substr($matches[1][0],11);
if (trim($nameApp)=='') continue;
if (file_exists('apk/'.$nameApp.'.apk')) continue;

// conseguir el enlace directo a la aplicacion (no-hot-link)
$defaults[CURLOPT_URL] = 'http://www.freewarelovers.com/android/download/temp/'.$matches[1][0].'.apk';
curl_setopt_array($ch, $defaults);
$body = curl_exec($ch);

preg_match_all('|http://www.freewarelovers.com/hotlinkmenot/(.*)\.apk|', $body, $matches);
if (trim($matches[0][0])=='') continue;

// descargar la aplicacion
$defaults[CURLOPT_URL] = $matches[0][0];
curl_setopt_array($ch, $defaults);
$body = curl_exec($ch);

file_put_contents('apk/'.$nameApp.'.apk', $body);
}
}
}
?>

Etapa 2. Decompilar aplicaciones

Una vez todas descargadas, fue cuestión de pasar otro script que las decompilara. Se puede sustituir por cualquier otro proceso como, por ejemplo, “unzip”, “dex2jar”, “jad” y “understand”. Yo decidí hacerlo facilito y usar directamente la herramienta “apktool”.

#!/bin/bash

cd apk2

for f in $( ls ../apk ); do
if [ ! -d "../apk2/${f//.apk}/" ]
then
java -jar ../apktool.jar decode "../apk/$f"
fi
done

Etapa 3. Buscando sorpresas

La parte costosa ya ha terminado, obteniendo así tantos directorios como aplicaciones procesadas. Ahora es momento de buscar patrones “curiosos”, “delicados” y “repetitivos”, como, por ejemplo, aquellas aplicaciones que tienen admob u otra librería.

Centrándonos en “malware”, he realizado la siguiente búsqueda:

grep 'const-string v[0-9], "http[s]*://.*"' * -r

Muchos webservices… muchos dominios rusos… muchos logins… os dejo un dump de la consulta anterior para que os recreéis.

http://dl.dropbox.com/u/7186726/dumpGrep.txt

Etapa 4. AndroidRisk

Visto que hay miga en esto, decidí terminar el experimento con la aplicación AndroidRisk del paquete AndroidGuard. Esta aplicación permite buscar en un directorio de ficheros APKs aquellos que potencialmente se parecen mucho a uno de los últimos virus/troyanos detectados para Android (por ejemplo, DroidDream).

Es lanzar el siguiente comando:

./androrisk.py -d ../apk/

Os dejo el dump también.

http://dl.dropbox.com/u/7186726/dumpRisk.txt

No sé hasta que punto fiarme de los resultados, pero todo apunta a que muchas de estas aplicaciones “tienen sorpresita”. (A más alto el número, más afinidad de ser maligno.)

Etapa 5. Fuzzing

¿Y sí cogemos todas las direcciones que se han extraido y se lanza una herramienta automatizada de intrusión web MUY básica? (Sql Injections, Path Traversal, Remote File Inclusion, Local File Inclusion, … ) Se puede montar una bonita botnet con la tontería… y no sólo eso… sino que cada webservice debe llevar asociada una base de datos de usuarios.

Despedida

Y esto sólo con ~1500 aplicaciones … :-)

Sed buenos y cualquier duda ya sabéis donde estoy.

Challenges

Desde siempre me han gustado los retos.

Empecé en http://hispabyte.net/ realizando lo más básico en el foro (Gracias @Cabrero1964)… Viví Boinas negras e Izhal… Continué con algunos más completos como http://www.hackthissite.org/… Colaboré en algunos mucho más currados como http://yoire.com/… Rompí mi cabeza en sitios como http://bright-shadows.net/ (Gracias @Phas, con quien intenté elaborar un sitio de retos)… y finalmente se me han pasado muchisimos otros, como los de SecurityByDefault, otros del Maligno, etc, etc, etc (no recuerdo el nombre de los que van por terminal… pero han sido siempre muy interesantes). Aún así, superé 0 retos en la última DEFCON CTF (olé!).

Estos últimos días estoy dedicando bastante tiempo a un nuevo site… http://securitytraps.no-ip.pl (Gracias al equipo Activalink http://blog.activalink.org/ (¡que buenos son los cabroncetes!)).

Lo que más me ha impacto respecto a muchos de los otros retos vividos es lo que llegas a aprender. A diferencia del resto de retos, los cuales son pasables sólo si tienes una idea feliz, es que estos son bastante sencillos y simples, pero necesitas ENTENDER y optimizar lo que estas haciendo. La mayoria de pruebas son con el código fuente y el objetivo es conseguir la excepción de ese pedazito de código.

A mi me ha enseñado a ser más paciente y persistente los retos más jodidos, yendo pasito a pasito, y finalmente, poder decir que has aprendido cosas nuevas. Es cuestión de leer bien, localizar los conceptos clave, y buscar información hasta entender perfectamente que esta sucediendo. Sí, es un RTFM bien grande. (RTFM=Read The Fuck Manual)

Lamentablemente, hacer retos, tener 2 papers que terminar, un servidor que configurar, y muchas más cosas que aprender no se puede hacer en un verano entero. ¡Espero postear mejores aportaciones la próxima! :-) ¡Sed pacientes!

Teensy + Panda = ¿PaTeensy o TeenPanda?

Para una prueba de ingeniería social que realizaré en breve, he camuflado mi Teensy

Un peluche panda y mi teensy

Que monos :)

…el resultado…

Hibrido USB - Peluche

Hibrido USB - Peluche

La idea original era un pato de goma junto al Teensy, llamado USB Rubber Ducky. Proviene de la comunidad Hak5, conocida por sus videos de YouTube, pero esta claro que cualquier cosa sirve.

Y algunos os preguntaréis: ¿Que programa usas en el Teensy? Bueno, originalmente utilizo la combinación del programa “osk” y una “cmd” (probadlos abriendo un Tecla-GUI-windows + R y ejecutandolos), principalmente para saltarme kioskos de fotos o parecidos con pantallas táctiles sin teclado, pero en este caso, lo he personalizado y he hecho combinación del Iexplorer con el Squirtle Toolkit.

Your entire SDcard in my webhost ~ Proof Of Concept

Note: I do not care if you want to share or translate the document, but please, quote me ;) . Thanks!

Brief

I have developed a Application for Android which stoles the File List of the SD-Card of the victim.

I do not use any kind of special trick. That is the real problem.

What does the exploit need?

It only needs “Internet” permission, so it is very easy to use in malicious apps (and persuade the user to get into the trap).

How it works…

You can read by DEFAULT the files in the SD-Card, so you only have to read them and send into Internet. I have deployed a webservice in a webhost that I can manage to do this PoC.

Download it here: (pname:poc.SDCard)Proof of Concept - Stealing SD-Card with an Android application

Why am I doing it?

Because I care about your security. I want you that you will experiment HOW EASILY it is. And then…

1) Think twice what kind of information you have in your SDCard

2) Think twice what apps you allow :) The 90% of apps use the “Internet” permission.

Where is the real problem?

The problem is that the Google Developers have say: “Do not store sensitive information into your SDCard! only shared data!” … but the application developers (like Dropbox, whatapps, your camera, …) does not care a bit and they save your files there.

First, the application developers SHOULD care about you. And second, you should care about YOURSELF. If they do not care about you, do not use them.

Can you show us the source-code?

Main function: (yeah… too easy)


private void getFiles(File F) {
 for (File t : F.listFiles()) {
  DATA.add(t.getAbsolutePath()+"\n");
  if (t.canRead() && t.isDirectory()) {
   getFiles(t);
  }
 }
}

Are you storing my data with this App??

Calm. I am only sending your File List (it is a slow app… I know… I did not use Threads) to my webhost. I do not want your data (I could have send it too :P ). I promise you that I am going to remove all the uploaded files of the webhost… BUT…. you can delete it too. Just click the button that appears in the app.

Argg!! It goes really slow…

Yes, I know. It gets the list of files, it is put in a string, it is sent to the webhost, and then it shows you the screen…

I promise it works… so start deleting all your data of the SDcard right now ;-) .

Special Note: Do you use CyanogenMod or another custom Rom? They save by default a backup of your data as *.img files. Do you know that they contain ALL YOUR DATA OF YOUR ACCOUNTS? It is overLOL!…(this image was taken when I was coding the app…)

cyanogen-mod backups in *.img files

Conclusion

Any application that you have stored could do it. I hope you will learn something about it. Use a sniffer to know what the fuck your apps are sending… (yeah… they could send the data by a SSL channel).

Greets!

and if you have any question, contact me, of course!!

Note: If you see any spell mistakes, you can say me it. I would appreciate it ;) . Thanks!

Follow

Get every new post delivered to your Inbox.