Using EasyHook from unmanaged code...

Jun 18, 2010 at 7:04 PM

Hi,

I'm newbie at this Easyhook field, and trying to hook apis( like ExtTextOut and DrawText ) from Visual Studio 2008 C++ unmanaged code environment.

I found "unmanaged api reference" document really useful and successfully injected my dll into target process by RhInjectLibrary() function.

The problem is I don't know how to write hook handler and main thread ( used to transfer data to the host - Run() in C# examples.)

My code looks like below.

Sorry for dirty code in advance...

 

// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "easyhook.h"
#include <tchar.h>
#include <stdio.h>

#define MAX_BUFFERSIZE 65536

WCHAR TextBuffer[MAX_BUFFERSIZE];
int iCurrentPos = 0;
HANDLE hPipe;

BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}

BOOL ExtTextOut_Hook(
HDC hdc, // handle to DC
int X, // x-coordinate of reference point
int Y, // y-coordinate of reference point
UINT fuOptions, // text-output options
CONST RECT* lprc, // optional dimensions
LPCWSTR lpString, // string
UINT cbCount, // number of characters in string
CONST INT* lpDx // array of spacing values
)
{
if ( iCurrentPos + cbCount < MAX_BUFFERSIZE )
{
for ( int i = 0; i < cbCount; i++ )
{
TextBuffer[iCurrentPos + i] = lpString[i];
}
iCurrentPos += cbCount;
}

return ExtTextOut( hdc, X, Y, fuOptions, lprc, lpString, cbCount, lpDx );
}

extern "C" __declspec(dllexport) void __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO* InRemoteInfo)
{
TRACED_HOOK_HANDLE hHook = new HOOK_TRACE_INFO();
ULONG AclEntries[1] = {0};

NTSTATUS retStatus = LhInstallHook( GetProcAddress(LoadLibraryA("Gdi32.dll"), "ExtTextOutW"), ExtTextOut_Hook, (PVOID)0x12345678, hHook );

/*if ( retStatus == 0 )
MessageBox(NULL, _T("Successful LhInstallHook!"), NULL, MB_OK );
else
{
char errMsg[100];
sprintf(errMsg, "LhInstallHook returned error #%d", retStatus);
MessageBoxA( NULL, errMsg , NULL, MB_OK );
}*/

LhSetInclusiveACL( AclEntries, 1, hHook );

while ( true )
{
Sleep(500);
if (iCurrentPos > 0)
{
CallNamedPipe( _T("\\.\pipe\MySample"), (LPVOID)TextBuffer, (iCurrentPos+1) * sizeof(TCHAR), NULL, 0, NULL, 0 );
iCurrentPos = 0;
}
}
LhUninstallHook(hHook);

// now we can safely release the traced handle
delete hHook;

hHook = NULL;

// even if the hook is removed, we need to wait for memory release
 LhWaitForPendingRemovals();
}

So my question is

1. Can I use NativeInjectionEntryPoint() itself as a main thread or should I create new thread from the function and return that function immediately?

2. In my hook handler, how can I use TDB to avoid recursive calling?

3. Is there any native c++ example I can follow?

Please answer me asap.