Inside DeleteFiber() as Anti Debug Trick

July 31, 2008

Hi,

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.

Syntax

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};
DeleteFiber(fiber);
return EXIT_SUCCESS;
}

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};
DeleteFiber(fib);

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


return EXIT_SUCCESS;
}
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

7C825AA1 PUSH EBP

7C825AA2 MOV EBP,ESP

7C825AA4 PUSH ECX

7C825AA5 PUSH ESI

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

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

7C825AAF MOV ESI,DWORD PTR SS:[EBP+8] ;lpFiber

7C825AB2 CMP ECX,ESI

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

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

7C825ABE PUSH 8000 ;MEM_RELEASE

7C825AC3 LEA EAX,DWORD PTR SS:[EBP-4]

7C825AC6 PUSH EAX

7C825AC7 LEA EAX,DWORD PTR DS:[ESI+10]

7C825ACA PUSH EAX

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

7C825AE8 POP ESI

7C825AE9 LEAVE

7C825AEA RETN 4

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

ntdll!_TEB

+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

parameters:

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

#define FLG_HEAP_VALIDATE_PARAMETERS 0x00000040

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:

Debugger

DisableHeapLookaside

ShutdownFlags

MinimumStackCommitInBytes

ExecuteOptions

GlobalFlag

DebugProcessHeapOnly

ApplicationGoo

RpcThreadPoolThrottle

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\

Target.exe]

"GlobalFlag"=""

My Linkedin Profile

July 30, 2008

Hi,

Here you can see my Linkedin Profile

Have a nice Day,

Evilcry


Fake Italian uTorrent Website and Malicious Application

July 28, 2008

Hi,

Just yesterday I’ve searched the newest uTorrent client, and the first record appeared in google
by searching “uTorrent” is

This is a Fake uTorrent Website, cause the real one is:

As you can see the page looks pretty well engineered apart the repetitions of “Download Here” in the same page.

Let’s see the application..

MALWARE MALWAREMALWARE MALWAREMALWARE MALWAREMALWARE MALWAREMALWARE

MALWARE MALWAREMALWARE MALWAREMALWARE MALWAREMALWARE MALWAREMALWARE

Really suspicious

install_utorrent1.8rc6.upx.exe.exe

First of all because uTorrent is a Standalone Executable and second for the strange final name
upx.exe.exe

By Virus scan with Jotti service we can see that this application is

Kaspersky: Found Backdoor.Win32.Small.exw

See you to the next post.. ๐Ÿ™‚


SetUnhandledExceptionFilter Anti Debug Trick

July 24, 2008

Hi,

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:

LPTOP_LEVEL_EXCEPTION_FILTER WINAPI SetUnhandledExceptionFilter(
__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 )
{
    __try
    {
        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 )
{
    __try
    {
        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.

Syntax

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] );

        if( rv == EXCEPTION_CONTINUE_EXECUTION )
            return EXCEPTION_CONTINUE_EXECUTION;
    }

    DWORD DebugPort = 0;

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

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

    // Is custom filter for unhandled exceptions registered ?

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

        rv = (BasepCurrentTopLevelFilter)(pep);

        if( rv == EXCEPTION_EXECUTE_HANDLER )
            return EXCEPTION_EXECUTE_HANDLER;

        if( rv == EXCEPTION_CONTINUE_EXECUTION )
            return EXCEPTION_CONTINUE_EXECUTION;
    }   

}

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.. ๐Ÿ™‚


CartellaUnicaTasse.exe Italian Malware Reversing

July 15, 2008

Hi,

Long time has passed from my last blog post.

I’ve released CartellaUnicaTasse.exe An Italian Malware Case Study,

the paper can be downloaded here: http://evilcry.altervista.org/tuts/Mw/CartellaUnicaTasse.pdf

See you to the next post ๐Ÿ™‚