Qt – Adding External Libs to your Project

February 22, 2009


During Qt Development with Qt Creator, emerged the necessity to add more libraries to my project, at the actual state of art Qt Creator does not provides an automated/graphical system to add libraries and since is using GCC is not possible to use #pragma comment(), so we have to modify by hand some files, here how to.

Suppose that you need to add psapi library, first of all locate into project directory Makefile.Debug and Makefile.Release

Open one of the two files (depends on how you need to deploy you program) and locate

LIBS        =        -L”c:\Qt\QtCreator\qt\lib” -lmingw32 -lqtmaind -lQtGuid4 -lQtCored4

now you can easly add your lib

LIBS        =        -L”c:\Qt\QtCreator\qt\lib” -lmingw32 -lqtmaind -lQtGuid4 -lpsapi -lQtCored4

See you to the next post.. 🙂

Some handy conversion for Qt

February 21, 2009


Long time since my last post, I’m not dead only extremely busy with work! 🙂

Here a little handy collection of String Formats Conversions from/to Qt:

#ifdef UNICODE

#define QStringToTCHAR(x) (wchar_t*) x.utf16()

#define PQStringToTCHAR(x) (wchar_t*) x->utf16()

#define TCHARToQString(x) QString::fromUtf16((x))

#define TCHARToQStringN(x,y) QString::fromUtf16((x),(y))


#define QStringToTCHAR(x) x.local8Bit().constData()

#define PQStringToTCHAR(x) x->local8Bit().constData()

#define TCHARToQString(x) QString::fromLocal8Bit((x))

#define TCHARToQStringN(x,y) QString::fromLocal8Bit((x),(y))


see you to the next post.. 🙂

QtCreator at Work

February 1, 2009

Hi there,

Great news form Qt world, Qt 4.5 are going to be free LGPL, and the new editor works fine!

Here a shot of Qt Creator the Qt IDE actually only for C++ at work:


I hope that more and more ppl will switch to Qt, they are simply fantastic! more refined and advanced of MFC and .NET!

Here a link to Qt HeadQuarter:


See you to the next post.. 🙂

OffensiveC0ding section Opened

February 1, 2009

Hi there,

I’ve opened a new section in my Website, called OffensiveC0ding.

I’m going to collect Source Code Samples of Applications that performs Spy/Surveillance operations, Covert Channels Applications and various other services that needs to perform hidden tasks. The Applications that you will find here will be published without binary files, easly because the scope of this section is to demonstrate how insecure could be a not well hardened system, this kind of demonstration could be only acheived by showing how effectively works a Real OffensiveCode.

Actually there is a little source that acts as Sandbox Detector, Joe of Joebox kindly noticed me that this detection system does not longer affects JoeBox.

Here you can reach my page:


See you to the next post.. 🙂

NtSetDebugFilterState as Anti-Dbg Trick Reverse Engineering

January 9, 2009

Here you can download my last paper related to NtSetDebugFilterState UndocumentAPI that can be used as 
Anti Debugging Trick.


Have a Nice Read 🙂
Giuseppe 'Evilcry' Bonfa'

.NET Framework Rootkit

November 15, 2008


here an truly intersing paper on .NET Framework Rootkits


Have a nice read! 🙂

Debugger Detection Via NtSystemDebugControl

September 15, 2008


NtSystemDebugControl() is a really powerful undocumented function, that allows you Direct Manipulation of System’s Structures.

Here a definition of NtSystemDebugControl:


The use of this function is only limited to the fancy of the coder

I’ve rewritten some basical Anti Debugging Techniques with Direct Structure Reading with NtSystemDebugControl. Obviously there are shorter ways to implement these Anti-Dbg Apps, but I think that more reimplementations exists and more are possibilities to trick an attacker, that may not know/understands the specific trick..especially if embedded in many..many.. Junk Code

Here you can download the Source Code sample:


Have a nice Day,

Fast ApiSpy (of DeviceIoControl) via oSpy2 Defined Hook

September 6, 2008


oSpy2 is the evolution of oSpy-1.9.6 coded by oleavr.

With oSpy2 is possible to Spy API Activity of the selected process, you can think that there are many other ApiSpy Tools, but oSpy2 implements a well organized XML called config.xml that allows you to define the function that you want to Spy, it has also other Logging features such as dump of CPU Registers.

Here an XML Samplied applied to DeviceIoControl Spy


      <function name="DeviceIoControl" callingConvention="stdcall">
        <returnValue type="MSBool"/>
          <argument name="hDevice" direction="in" type="UInt32" hex="true"/>
          <argument name="dwIoControlCode" direction="in" type="UInt32" hex="true" />
          <argument name="lpInBuffer" direction="in" type="ByteArrayPtr" size="arg.nInBufferSize"/>
          <argument name="nInBufferSize" direction="in" type="UInt32"/>
          <argument name="lpOutBuffer" direction="out" type="ByteArrayPtr" size="arg.lpBytesReturned">
            <logCondition>reg.eax !=0</logCondition>
          <argument name="nOutBufferSize" direction="in" type="UInt32"/>
          <argument name="lpBytesReturned" direction="out" type="UInt32Ptr"/>
          <argument name="lpOverlapped" direction="in" type="UInt32" hex="true"/>                    
    <dllModule name="kernel32.dll">
      <function specId="DeviceIoControl"/>


Note that this sample code is thaken from oleavr’s blog but with a basical difference

 <argument name=”dwIoControlCode” direction=”in” type=”UInt32″ hex=”true” />
He used as type IoControlCode and hex disabled, in this way oSpy2 not worked because he wasn’t able to recognize IoControlCode type.
Here thew output result:
<event id="1" type="FunctionCall" timestamp="128651541912187500" processName="_CENSORED_" processId="1924" threadId="2620">
        <entry moduleName="_CENSORED_">
        <entry moduleName="_CENSORED_">
        <entry moduleName="_CENSORED_l">
        <entry moduleName="_CENSORED_l">
        <entry moduleName="_CENSORED_l">
        <entry moduleName="_CENSORED_">
        <entry moduleName="_CENSORED_l">
        <entry moduleName="_CENSORED_l">
    <cpuContext direction="in">
        <register name="eax" value="0x78"/>
        <register name="ebx" value="0x2000"/>
        <register name="ecx" value="0xc3fa28"/>
        <register name="edx" value="0xc3fa28"/>
        <register name="edi" value="0xad0000"/>
        <register name="esi" value="0x62babc"/>
        <register name="ebp" value="0x78"/>
        <register name="esp" value="0xc3f9ec"/>
    <arguments direction="in">
        <argument name="hDevice">
            <value type="UInt32" value="0x78"/>
        <argument name="dwIoControlCode">
            <value type="UInt32" value="0x80012004"/>
        <argument name="lpInBuffer">
            <value type="Pointer" value="0x00C3FA28">
                <value type="ByteArray" size="16">
        <argument name="nInBufferSize">
            <value type="UInt32" value="16"/>
        <argument name="lpOutBuffer">
            <value type="Pointer" value="0x00C3FA28"/>
        <argument name="nOutBufferSize">
            <value type="UInt32" value="16"/>
        <argument name="lpBytesReturned">
            <value type="Pointer" value="0x00C3FA24"/>
        <argument name="lpOverlapped">
            <value type="UInt32" value="0"/>
    <cpuContext direction="out">
        <register name="eax" value="0x1"/>
        <register name="ebx" value="0x2000"/>
        <register name="ecx" value="0x7c801694"/>
        <register name="edx" value="0x7c91eb94"/>
        <register name="edi" value="0xad0000"/>
        <register name="esi" value="0x62babc"/>
        <register name="ebp" value="0x78"/>
        <register name="esp" value="0xc3fa1c"/>
<arguments direction="out">
        <argument name="lpOutBuffer">
            <value type="Pointer" value="0x00C3FA28"/>
        <argument name="lpBytesReturned">
            <value type="Pointer" value="0x00C3FA24">
                <value type="UInt32" value="16"/>
        <value type="Boolean" value="true"/>
What to say..a really powerful tool!
See you to the next post.. :)

Inside DeleteFiber() as Anti Debug Trick

July 31, 2008


Malware is often really boring to reverse because in high percentage they implements basical well known mechanisms of infection and self protection.
But sometimes there are really intersting malware that implements innovative techniques, this is the case of a trojan borned into 2006 that implemented DeleteFiber() as Anti–Debug Trick in a really easy and smart way.

To understand how it works, let’s see whar DeleteFiber is, directly from MSDN:

Deletes an existing fiber.


VOID WINAPI DeleteFiber(
__in  LPVOID lpFiber

lpFiber is the address of the fiber to be deleted.

Important to say that the DeleteFiber function deletes all data associated with the fiber.
This data includes the stack, a subset of the registers, and the fiber data.

Now let’s see a basical use of DeleteFiber():

#define _WIN32_WINNT 0x0400
#include <windows.h>

int main(void)
char fiber[1024] = {0};

After showing the basical use of DeleteFiber let’s see how can be implemented as Anti-Debug Trick,
I insert here direcly the code:

#define _WIN32_WINNT 0x0400
#include <windows.h>
#include <stdio.h>

int main(void)
char fib[1024] = {0};

if(GetLastError() == 0x00000057)
MessageBoxA(NULL,”This process is NOT debugged”,”Info”,MB_OK);
MessageBoxA(NULL,”This process IS debugged”,”Info”,MB_OK);

As you can understant we can resume this trick into two cases:

  • If the process is NOT debugged DeleteFiber give us an Error Code of 0x00000057 that corresponds to ERROR_INVALID_PARAMETER
  • If the process IS debugged the error code is differs from 0x00000057

What to say it’s really easy to implement and really effective for all kind of debuggers, with a

bit of junk code that confuses ideas the conditional check could be placed really distant from the

DeleteFiber() itself.

Inside DeleteFiber()

Now we will see how DeleteFiber internally works to understand why this should be used as

Anti-Debug trick.

This is the Dead List:

00401000 PUSH DF.00403370

00401005 CALL DWORD PTR DS:[<&KERNEL32.DeleteFiber>; kernel32.DeleteFiber

inside DeleteFiber()

7C825A9F > MOV EDI,EDI ; DF.00403778





7C825AA6 MOV EAX,DWORD PTR FS:[18] ;_TEB Struct

7C825AAC MOV ECX,DWORD PTR DS:[EAX+10] ;pointer to _TIB.FiberData field



7C825AB4 JE kernel32.7C826596 ;ExitThread if( FiberData == lpfiber)

7C825ABA AND DWORD PTR SS:[EBP-4],0 ;Clears this Stack location






7C825ACB PUSH -1

7C825ACD CALL DWORD PTR DS:[<&ntdll.NtFreeVirtual> ntdll.ZwFreeVirtualMemory

7C825AD3 MOV EAX,DWORD PTR FS:[18] ;_TEB Struct

7C825AD9 MOV EAX,DWORD PTR DS:[EAX+30] ;points to _PEB Struct

7C825ADC PUSH ESI ;lpFiber

7C825ADD PUSH 0 ;0x00000000

7C825ADF PUSH DWORD PTR DS:[EAX+18] ;PEB.ProcessHeap

7C825AE2 CALL DWORD PTR DS:[<&ntdll.RtlFreeHeap>] ; ntdll.RtlFreeHeap




In the first part of DeleteFiber is retrived the _TEB structure and specifically a member of

_TIB structure located at 10h

0:003> dt nt!_TEB -b


+0x000 NtTib : _NT_TIB

+0x000 ExceptionList : Ptr32

+0x00c SubSystemTib : Ptr32

+0x010 FiberData : Ptr32

and next if FiberData is equal to our Fiber’s Address it means that Fiber is suicinding itself

and system calls ExitThread(), next we can notice a NtFreeVirtualMemory call with the following


NtFreeVirtualMemory(NtCurrentProcess(), &pStackAllocBase,&nSize,MEM_RELEASE);

The system deallocates the used stack and finally calls RtlFreeHeap in this manner:

RtlFreeHeap(GetProcessHeap(), 0, lpFiber);

This last call clarifies totally the presence of ERROR_INVALID_PARAMETER because has we have seen

DeleteFiber is directly correlated with Heap, and Heap Memory presents a set of Flags that

characterize the Heap itself.

These Flags differs in case the process IS debugged or NOT, so we can suppose that these flags

are created when the exe itself is executed, in other words at Process Creation Time. Under

Windows NT processes are created through PspUserThreadStartup and inside it we can found

LdrInitializeThunk, that as Russinovich sais The LdrInitializeThunk routine initializes the

loader, heap manager, NLS tables, thread-local storage (TLS) array, and critical section

structures. By going more deep we can see that there is a specific function that fill the PEB

Struct of the new process MmCreatePeb(), PEB is important because between his various fields

are stored Heap Flags of our process. I’m talking about NtGlobalFlag, for a debugged process

these flags are:

#define FLG_HEAP_ENABLE_TAIL_CHECK 0x00000010

#define FLG_HEAP_ENABLE_FREE_CHECK 0x00000020


Now if a process has these flags enabled ( HeapDebug ) RtlFreeHeap will fail the Heap freeing and

this error will be propagated to DeleteFiber() that will exit with an ERROR_INVALID_PARAMETER.

Anti Anti-Debug

Due to the fact that the Heap Validation is accomplished at Processs Creation Time, one

countermeasure against Anti-Debug will be to attach the debugger after that the process is created.

If you are using WinDbg could be used the HeapDebug option ( -hd )

Between the function involved in process creation we have also LdrQueryImageFileExecutionOptions

that mantains trace of IFEO ( Image File Execution Options structure) this struct is located into

Registry under the path

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\]

The various possible values are:










GlobalFlag can be used to modify NtGlobalFlag, so if you set this key entry to NULL, Heap of the

debugged program will looks as an undebugged one, read this as an Anti-Anti Debug Trick :).
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\



SetUnhandledExceptionFilter Anti Debug Trick

July 24, 2008


SetUnhandledExceptionFilter() Anti Debug Trick is frequently used, especially in Malware Applications. Around here there are various plugins for Olly that allows the Reverser to trasparently debug this kind of protection, so there is not a real necessity add other words about the mere practical part.

Due to the fact that today, too many young reversers uses a ton of plugins anti – anti – xxx without knowing how internally they works, I decided to expose here SetUnhandledExceptionFilter() Anti Debug Trick from Internals.

First of all, what is SetUnhandledExceptionFilter() ? according to MSDN documentation:

Enables an application to supersede the top-level exception handler of each thread of a process.

After calling this function, if an exception occurs in a process that is not being debugged, and the exception makes it to the unhandled exception filter, that filter will call the exception filter function specified by the lpTopLevelExceptionFilter parameter.

And this is the Syntax:

__in  LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter

lpTopLevelExceptionFilter is a pointer to top-level exception filter function that will be called whenever the UnhandledExceptionFilter function gets control, and the process is not being debugged. A value of NULL for this parameter specifies default handling within UnhandledExceptionFilter.

Usually, in absence of an UnhandledExceptionFilter the topmost handler called when an uncatched exception occours, is the default one provided by Windows Itself, the classical MessageBox that advices the user that an Unhandled Exception has occured.

But Windows allow programs to use custom Handlers for UnhandledException. The core of the trick is here, if the application is NOT debugged, the application is able to call the Custom Handler, but if the application IS debugged the Custom Handler will be never called.

The possibility of cognitive differentiation make obviously able the target application to apply a series of countemeasures against debugging, from detection to code hidding.

Just remember that due to the architecture of Windows Exception Handling, in every case is called UnhlandledExceptionFilter() function, and this will our point of attack (for anti – anti dbg trick).

This is the general inner meccanism of SetUnhandledExceptionFilter(), going more deep we observe the call stack of the first thread of any Win32 application, we can see that execution in every case is reported to BaseProcess, here the pseudo definition:

VOID BaseProcessStart( PPROCESS_START_ROUTINE pfnStartAddr )
        ExitThread( (pfnStartAddr)() );
    __except( UnhandledExceptionFilter( GetExceptionInformation()) )
        ExitProcess( GetExceptionCode() );

The same thing happens for threads, by referencing to BaseThreadStart:

VOID BaseThreadStart( PTHREAD_START_ROUTINE pfnStartAddr, PVOID pParam )
        ExitThread( (pfnStartAddr)(pParam) );
    __except( UnhandledExceptionFilter(GetExceptionInformation()) )
        ExitProcess( GetExceptionCode() );

All that happens inside BaseProcessStart() and BaseThreadStart() for what previously said, will be passed to the UnhandledExceptionFilter().

It’s now time to see what really is UnhandledExceptionFilter(), according to MSDN:

An application-defined function that passes unhandled exceptions to the debugger, if the process is being debugged. Otherwise, it optionally displays an Application Error message box and causes the exception handler to be executed. This function can be called only from within the filter expression of an exception handler.


LONG WINAPI UnhandledExceptionFilter(
  __in  struct _EXCEPTION_POINTERS *ExceptionInfo

Became clear that UnhandledExceptionFilter represents the last choise for processing unhandled exceptions, so the Debugger Presence surely is located inside this function, let’s see a simplified version of this function:

LONG UnhandledExceptionFilter( EXCEPTION_POINTERS* pep )
    DWORD rv;

    EXCEPTION_RECORD* per = pep->ExceptionRecord;

    if( ( per->ExceptionCode == EXCEPTION_ACCESS_VIOLATION ) &&
         ( per->ExceptionInformation[0] != 0 ) )
        rv = BasepCheckForReadOnlyResource( per->ExceptionInformation[1] );


    DWORD DebugPort = 0;

    rv = NtQueryInformationProcess( GetCurrentProcess(), ProcessDebugPort,
                                    &DebugPort, sizeof( DebugPort ), 0 );

    if( ( rv >= 0 ) && ( DebugPort != 0 ) )
        // Yes, it is -> Pass exception to the debugger

    // Is custom filter for unhandled exceptions registered ?

    if( BasepCurrentTopLevelFilter != 0 )
        // Yes, it is -> Call the custom filter

        rv = (BasepCurrentTopLevelFilter)(pep);




As you can see, inside UnhandledExceptionFilter() is called NtQueryInformationProcess() that has as first parameter our process and next DebugPort, this is done to know if the process is debugged.

All that we have to do to obtain an apparently undebugged process is to modify the first parameter (last pushed at debugging time), in other words we have to change the retur value of GetCurrentProcess() from 0xFFFFFFFF to 0x00000000.

So remember, when you have to overcome a SetUnhandledExceptionFilter() just put a Breakpoint for UnhandledExceptionFilter() and go inside this function to modify the previously exposed parameter 🙂

Thanks to Oleg Starodumov for pseudocodes 🙂

See you to the next blog post.. 🙂