Contenido principal
Abril 25, 2011
Este fin de semana Plaid Parliament of Pwning fueron los anfitriones del plaid CTF, un concurso donde 440 equipos participaron de una serie de retos dirigidos a entusiastas y profesionales de la seguridad informática.
En total eran 38 retos que se debian resolver en 48 horas, las categorías del concurso fueron: Reversing, Web, Crypto, Trivia, Pwnables y QR Code.
Y pues bueno, un torneo grandioso donde los ganadores demostraron sus habilidades, felicitaciones a ellos y a PPP por tan genial y organizado evento!
Ahora sí, la resolución para el problema número 7: I'm feeling lucky.
WriteUp I'm Feeling lucky
Descripción
We found that one of the executives of AED keeps using 'Fortune Cookie' program everyday before he logs in to his *very* important machine.
We extracted the program, and we are certain that there's a key hidden somewhere in the binary.
Reverse engineer and get the key!
Download
http://www.plaidctf.com/chals/43e842e63a795e8f28739a018de547822382e7d3.exe
Resolución
Bueno, este es un breve resumen de lo que hice para obtener la respuesta del reto.
Lo primero que hice fue localizar el código que se ejecutaba al dar clic al botón con Ollydbg, llegando a la instrucción 00412530.
00412530 /$ 68 90000000 PUSH 90
00412535 |. B8 23DA5000 MOV EAX,43e842e6.0050DA23
0041253A |. E8 16550E00 CALL 43e842e6.004F7A55
0041253F |. 8BF9 MOV EDI,ECX
00412541 |. 33C0 XOR EAX,EAX
00412543 |. 8945 F0 MOV [LOCAL.4],EAX
00412546 |. C745 EC FFFFFF7F MOV [LOCAL.5],7FFFFFFF
0041254D |. 8B5D 08 MOV EBX,[ARG.1]
00412550 |. 8945 FC MOV [LOCAL.1],EAX
00412553 |. 81FB 11010000 CMP EBX,111
00412559 |. 75 22 JNZ SHORT 43e842e6.0041257D
0041255B |. FF75 10 PUSH [ARG.3]
0041255E |. 8B07 MOV EAX,DWORD PTR DS:[EDI]
00412560 |. FF75 0C PUSH [ARG.2]
00412563 |. FF90 F4000000 CALL DWORD PTR DS:[EAX+F4]
En la instrucción 00412559 es donde se compara el mensaje enviado con 111 que pertenece a WM_COMMAND (Cuando se presiona el botón).
Luego de numerosas instrucciones el programa llama la función CryptDecrypt pasándole como parámetro general una llave y un texto el cual es luego mostrado como una galleta de la fortuna
Identifiqué todos los llamados (En orden de ejecución) a la biblioteca criptográfica de Microsoft teniendo como resultado el siguiente resumen.
4025F0:
CryptAcquireContext
|Arg1 = 0012FE40 phProv
|Arg2 = 00000000 pszContainer
|Arg3 = 00000000 pszProvider
|Arg4 = 00000001 dwProvType
\Arg5 = F0000000 dwFlags
CryptCreateHash
|Arg1 = 00188DD0 hProv
|Arg2 = 00008003 Algid (CALG_MD5)
|Arg3 = 00000000 hKey
|Arg4 = 00000000 dwFlags
\Arg5 = 0012FE48 phHash
401140:
CryptDestroyHash
\Arg1 = 00186F70 hHash
CryptCreateHash
|Arg1 = 00188DD0 hProv
|Arg2 = 00008003 Algid (CALG_MD5)
|Arg3 = 00000000 hKey
|Arg4 = 00000000 dwFlags
\Arg5 = 0012FE48 phHash
CryptHashData
|Arg1 = 00186F70 hHash
|Arg2 = 00B7ADD0 pbData (This is the key, but this is not the key you are looking for :p)
|Arg3 = 0000003F dwDataLen (63)
\Arg4 = 00000000 dwFlags
CryptDeriveKey
|Arg1 = 00188DD0 hProv
|Arg2 = 00006602 Algid (CALG_RC2)
|Arg3 = 00186F70 hBaseData
|Arg4 = 00000001 dwFlags
\Arg5 = 0012FE44 phKey
00412530:
CryptDecrypt
|Arg1 = 00189368 hKey
|Arg2 = 00000000 hHash
|Arg3 = 00000001 Final
|Arg4 = 00000000 dwFlags
|Arg5 = 00B7F570 pbData
\Arg6 = 0012F664 pdwDataLen
Luego simulé el funcionamiento y extraje la cadenas cifradas que se localizaban en el offset 140D18 del archivo ejecutable.
Creé un programa en C++ y un script en PHP que leyera archivos binarios e hiciera split (Disculpa a los lectores si la solución es un poco ortodoxa).
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#define _WIN32_WINNT 0x0400
#include <windows.h>
#include <wincrypt.h>
int main(int argc, char* argv[]) {
HCRYPTPROV hCryptProv;
HCRYPTHASH hHash;
HCRYPTKEY hKey;
CryptAcquireContext(&hCryptProv, 0, 0, 1, 0xF0000000);
CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash);
BYTE *pbBuffer = (BYTE *)"This is the key, but this is not the key you are looking for :p";
DWORD dwBufferLen = strlen((char *)pbBuffer);
CryptHashData(hHash, pbBuffer, dwBufferLen, 0);
CryptDeriveKey(hCryptProv, CALG_RC2, hHash, 1, &hKey);
FILE *fp = fopen("filetmp.hex", "rb");
fseek(fp, 0, SEEK_END);
ULONG size = ftell(fp);
unsigned char *buffer = (unsigned char*) calloc(size, sizeof(char));
rewind(fp);
fread(buffer, size, 1, fp);
fclose(fp);
CryptDecrypt(hKey, 0, 1, 0, buffer, &size);
printf("%s\n", buffer);
return 0;
}
Y el script de PHP que ejecutaba el anterior código
<?php
$file = file_get_contents('strings.hex'); // Obtain all ciphered strings
$file = str_replace("\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00", $file);
$file = explode("\x00\x00\x00\x00", $file); // Split based on null chars
foreach ($file as $line) { // Loop through all strings
file_put_contents("filetmp.hex", $line); // Save the string in temporal file
system("mission7.exe"); // Call mission7 executable
}
La respuesta se encontraba en una de las últimas galletas de la fortuna
Your character can be described as natural and unrestrained.
Your difficulties will strengthen you.
Oh YEAH, this is THE k3y U r L0ok1ng FOr
Your dreams are worth your best efforts to achieve them.
Your energy returns and you get things done.
Respuesta
Oh YEAH, this is THE k3y U r L0ok1ng FOr 
Archivado en: Criptografía, Ingeniería Inversa, Programación |
Comentarios (5)
Abril 3, 2011
Este fin de semana se llevó a cabo las prequals para Nuit Du Hack, una de las conferencias de seguridad informática más antiguas de Francia.
La modalidad de la prequal: CTF, que consiste en una serie de retos donde se debe encontrar una bandera para ir escalando posiciones en el ranking.
En este caso nos enfrentamos a doce retos en cuatro categorías, este es el resumen de los retos que logramos realizar, logrando 1400 puntos y ocupando el puesto número doce.
Web
Inyección + serialize
Inyección a través de imágenes
Inyección a través de cookies
Forensics
Análisis del dump de memoria encontrando la clave del servidor VNC
Obtención de clave de usuario encontrada en ntds.dit (Active Directory)
Análisis del dump de memoria encontrando el proceso sospechoso
Crypto
Texto cifrado con Vigenere
RCE
Ingeniería inversa al archivo para encontrar la clave de acceso
Ingeniería inversa a una aplicación para Android
Ingeniería inversa a un juego para Nintendo DS
WriteUp Forensic100
Descripción
We have dumped the RAM of a Machine on which was running a VNC server.
The goal is to get the password of that VNC server.
Resolución
Lo primero que hice fue descargar una herramienta que me permitiera por cada proceso separar la memoria que ocupaba en el dump de la RAM, tal herramienta se llama Memoryze.
Entre las características de Memoryze podemos encontrar que puede listar el espacio de direcciones virtuales y mostrar tanto las DLLs cargadas como las porciones de memoria del programa deseado.
Memoryze trae una serie de archivos batch que nos ayudan a obtener estos espacios de memoria, se usó el archivo ProcessDD.bat de la siguiente forma:
ProcessDD.bat -input C:\dump.raw -process winvnc4.exe
El programa creó una carpeta de auditoría que contenía:
El programa ejecutable
Las bibliotecas cargadas por el programa
La pila de ejecución del programa
Los resultados del análisis
Como mi especialidad no es el análisis forense lo que hice fue un ataque de fuerza bruta sobre la pila de ejecución del programa (Archivos .VAD) en busca de 8 bytes que representan la contraseña cifrada del servidor VNC.
La contraseña es cifrada mediante el algoritmo DES (Modo ECB) usando la llave fija "\x17\x52\x6B\x06\x23\x4E\x58\x07" a la que anteriormente se reversó cada uno de sus bits (En el código pueden ver la función bit_mirror usada para reversar los bits de una cadena)
El código usado para hacer fuerza bruta fue el siguiente
<?php
//Fixed key with reversed bits
$key = bit_mirror("\x17\x52\x6B\x06\x23\x4E\x58\x07");
//Directory of audit generated by Memoryze
$audit_dir = "./20110401234944";
$d = dir($audit_dir);
//Loop through files in audit directory
while (false !== ($entry = $d->read())) {
if ($entry != '.' && $entry != '..' && substr($entry, -3) == 'VAD') {
//Read virtual address descriptor
$file = file_get_contents("./20110401234944/$entry");
//Obtain eight bytes that could match VNC password hash
preg_match_all('/\x00([\x00-\xff]{8})/', $file, $match);
//Loop through hashes
foreach ($match[1] as $hash) {
$decrypted = mcrypt_decrypt(MCRYPT_DES, $key, $hash, MCRYPT_MODE_ECB);
//Save possible answer if decrypted text contains printable characters
if (printable($decrypted))
file_put_contents('possible_answers_vnc.txt', $decrypted . "\n", FILE_APPEND);
}
}
}
//Return true if all characters in string are printable
function printable($string) {
$len = strlen($string);
for ($i = 0; $i < $len; $i++) {
if (ord($string[$i]) < 32 || ord($string[$i]) > 127)
return false;
}
return true;
}
//Return string with reversed bits
function bit_mirror($str) {
$tmp = '';
$len = strlen($str);
for ($i = 0; $i < $len; $i++) {
$ord = ord($str[$i]);
$tmp .= chr((($ord * 0x0802 & 0x22110) | ($ord * 0x8020 & 0x88440)) * 0x10101 >> 16);
}
return $tmp;
}
Al realizar el ataque por fuerza bruta encontramos en el archivo "possible_answers_vnc.txt" las posibles contraseñas para el servidor VNC
Q\D!J>'
*@W+SZXT
f-XjyB9E
rgO.;o1k
K]oo=~W`
f-XjyB9E
&dSD uNT
secretpq
b#<1?~_#
\q*QqXh
La contraseña usada entonces fue "secretpq" que corresponde al hash "\xDA\x6E\x31\x84\x95\x77\xAD\x6B" y que además se encuentra en el archivo "1696__SystemMemory%5c0x008c0000-0x008cffff.VAD"
Bandera
secretpq
Archivado en: Criptografía, Programación, Retos informáticos, Seguridad |
Comentarios (4)
Marzo 6, 2011
Este fin de semana nuestro grupo NULL-Life estuvo participando en el juego captura la bandera (CTF) de Codegate 2011.
Las categorías en esta ocasión fueron Vulnerab, Binary, Crypto, Forensics, Network e Issues.
De los 27 problemas planteados solo alcanzamos a realizar 14 para un total de 2600 puntos y lograr la posición 30 de 178 equipos que participaron, inclusive llegamos a quedar como el primer equipo de latinos, así que muchos ánimos para los integrantes del equipo, hay restos de cosas por mejorar!
También debo aclarar que el grupo no representa ninguna institución/región/país y que los integrantes somos de diferentes países incluyendo a Argentina, Colombia, México y Perú.
Fernando ha publicado un corto artículo sobre nuestra participación.
Sin más que decir, les presento la forma en que desarrollamos el tercer reto de la categoría Forensics.
Descripción
we are investigating the military secret's leaking.
we found traffic with leaking secrets while monitoring the network.
Security team was sent to investigate, immediately. But, there was no one present.
It was found by forensics team that all the leaked secrets were completely deleted by wiping tool.
And the team has found a leaked trace using potable device.
Before long, the suspect was detained. But he denies allegations.
Now, the investigation is focused on potable device.
The given files are acquired registry files from system.
The estimated time of the incident is Mon, 21 February 2011 15:24:28(KST).
Find a trace of portable device used for the incident.
The Key : "Vendor name" + "volume name" + "serial number" (please write in capitals)
Down (Archivo F8884B5396EAFE05E798BAB5F19D2E3F en Repositorio Codegate 2011)
Resolución
Extraemos los archivos quedando con la siguiente estructura

Cada archivo es de tipo Windows NT Registry Hive o "grupo lógico de claves, subclaves y valores en el registro que tienen un conjunto de archivos de soporte que contienen respaldos de sus datos".
Debemos primero buscar un editor de estos tipos de archivo encontrando la publicación de Nuno Brito con su editor de registro en crudo y la de erwan.l con su editor offline usando la librería de Windows Offreg.dll
Luego de abrir alguno de los registros y siguiendo la descripción, debemos encontrar un dispositivo extraíble el cual fue conectado al equipo y que posiblemente fue el causante del incidente. Suponemos que fue el último dispositivo conectado.
Buscando localmente encontré dos claves donde se guardan los dispositivos en el registro.
HKLM\SOFTWARE\Microsoft\Windows Portable Devices\Devices
HKLM\SYSTEM\ControlSet001\Enum\WpdBusEnumRoot\UMB
Con la utilidad de Nuno Brito debemos habilitar la opción Show Details desde el menú Options -> Configuration para obtener la fecha de modificación de la clave escogida.
Podemos ver la diferencia entre ver el tiempo de modificación desde un editor hexadecimal y desde la herramienta de Nuno.


Buscamos el último dispositivo conectado guiándonos con el timestamp y encontramos la clave
La respuesta como nos pide el problema es: Nombre del fabricante + Nombre del volumen o label + Serial del dispositivo.
Respuesta
CORSAIRPR0N33RDDF08FB7A86075
Archivado en: Retos informáticos, Seguridad |
Comentarios (8)
Enero 27, 2011
The BLAKE Hash is one of the five finalist algorithms that participates in the NIST SHA-3 competition. This hash functions is based on the HAIFA structure and the ChaCha core function.
The algorithm was designed by Jean-Philippe Aumasson, Luca Henzen, Willi Meier and Raphael C.-W. Phan, official website is http://131002.net/blake/.
There are four instances of the function, the first two, BLAKE224 and BLAKE256 work with 32-bit words and they have an output of 28 and 32 bytes respectively. The other two, BLAKE384 and BLAKE512 work with 64-bit words and they have an output of 48 and 64 bytes respectively.
The algorithm has been designed to be secure and to have a high performance (Even better than SHA-2).
Well, I was looking for an implementation of the hash for PHP but I found nothing, so I had to do it from scratch. My first attempt was to port the code from C to PHP using gmp library for the 64-bit operations (Specially bitwise operations), but the script was incredibly slow, it calculates BLAKE512 in 0.07 seconds (I think that the slow speed was because the gmp library creates a lot of resources), so I wanted to make it faster and the best option was to make a native code in C that was able to work together with PHP.
The code is based on the final round package sent.
The extension
This PHP extension is composed by five functions: blake, blake_file, blake_init, blake_update and blake_final.
Both, blake and blake_file are used to parse strings and files, the rest of the functions are used for incremental hashing.
The functions and its parameters are:
blake()
Description
string blake ( string $data , int $type [, string $salt [, bool $raw_output = false ]] )
Parameters
data: Message to be hashed.
type: Type of instace to use. It must be: BLAKE_224, BLAKE_256, BLAKE_384 or BLAKE_512.
salt: Salt to use. When use BLAKE_224 or BLAKE_256, salt must be 16 bytes, Otherwise, it must be 32 bytes, or a null string for use with raw_output.
raw_output: When set to true, outputs raw binary data.
Return values
Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.
blake_file()
Description
string blake_file ( string $filename , int $type [, string $salt[, bool $raw_output = false ]] )
Parameters
filename: URL describing location of file to be hashed; Supports fopen wrappers.
type: Type of instace to use. It must be: BLAKE_224, BLAKE_256, BLAKE_384 or BLAKE_512.
salt: Salt to use. When use BLAKE_224 or BLAKE_256, salt must be 16 bytes, Otherwise, it must be 32 bytes, or a null string for use with raw_output.
raw_output: When set to true, outputs raw binary data.
Return values
Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.
blake_init
Description
resource blake_init ( int $type [, string $salt ] )
Parameters
type: Type of instace to use. It must be: BLAKE_224, BLAKE_256, BLAKE_384 or BLAKE_512.
salt: Salt to use. When use BLAKE_224 or BLAKE_256, salt must be 16 bytes, Otherwise, it must be 32 bytes, or a null string for use with raw_output.
Return values
Returns a Blake state resource for use with blake_update() and blake_final().
blake_update
Description
bool blake_update ( resource $state, string $data )
Parameters
state: Blake state returned by blake_init()
data: Message to be updated in the incremental hashing.
Return values
Returns TRUE.
blake_final
Description
string blake_final ( resource $state [, bool $raw_output = false ] )
Parameters
state: Blake state returned by blake_init()
raw_output: When set to true, outputs raw binary data.
Return values
Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.
Resources
The package of BLAKE hash extension for PHP contains:
Source code of extension, Windows libraries for VC6 and VC9 (Both with thread safe and non thread safe) and Linux shared library (Compiled with archlinux i686).
Compilation
Compilation in Windows is a bit hard and requires:
Microsoft Visual C++ (6.0 or 9)
Windows SDK
Some binary tools
The wiki site of PHP describes perfectly how to build PHP and PECL extensions step by step.
Compilation in Linux is easier.
Download the package and extract its contents in a folder, then:
cd src
phpize
./configure
make
(If you want to test whether the extension is working properly you should execute "make test" command after compile the extension.)
Then, with administrator privileges copy the shared library contained in modules folder to PHP extension folder.
At the end, add "extension=php_blake.dll" (Windows) or "extension=blake.so" (Linux) to your php.ini file, and that's all.
Examples
<h2 style
="text-align: justify;">Screenshot
</h2
>
<img src
="http://www.sinfocol.org/archivos/2011/01/blake.png" alt
="BLAKE hash extension for PHP" />
Project can be found too at <a href="https://code.google.com/p/blakehash-php/">https://code.google.com/p/blakehash-php/</a>
Archivado en: Criptografía |
Comentarios (9)
Enero 20, 2011
Hello everyone, les presento las resoluciones de algunos de los problemas que logramos resolver con éxito en PAraDOx COnference CTF. En total eran veinticuatro problemas de los cuales solo pudimos resolver diez y poder así entrar al top 20.
Las resoluciones acá presentadas son
Reversing, idx = 1
Reversing, idx = 2
Forensic, idx = 4
Binary, idx =5
Binary, idx = 7
Trivial, idx = 18
Trivial, idx = 19
Web, idx = 23
Wtf400, idx = 26
Wtf500, idx = 27
El archivo Padocon.7z contiene el PDF con la resolución, los enunciados y ganadores de cada prueba y alguno de los recursos utilizados para el desarrollo de los problemas.
El resultado final fue el siguiente, mucho mejor a lo esperado!

Archivado en: Criptografía, Esteganografía, Hacking, Ingeniería Inversa, Programación, Retos informáticos, Seguridad, Sistemas operativos |
Comentarios (14)