MS Detours 2.1 - Popping out of stack - c++

I wont to detour PlaySoundW function inside Minesweeper.
Game is crashing as soon as it calls PlaySoundW function.
If I uncomment Beep inside my code, game beeps and than crashes.
Now code is calling original function from hooked function so it should't do anything. But it is crashing anyway.
Can you tell me what is wrong?
After debugging app in Olly I found that when detour is active not all rubbish is popped out of stack.
How to fix it?
This is my code:
#include <Windows.h>
#include <tchar.h>
#include <detours.h>
namespace Hooks
{
BOOL(__stdcall *OrgPlaySoundW)(LPCTSTR pszSound, HMODULE hmod, DWORD fdwSound) = &PlaySoundW;
BOOL HookPlaySoundW(LPCTSTR pszSound, HMODULE hmod, DWORD fdwSound)
{
//Beep(1000, 250);
//return TRUE;
return OrgPlaySoundW(pszSound, hmod, fdwSound);
}
void DetourPlaySoundW(BOOL disable)
{
if(!disable)
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)OrgPlaySoundW, &HookPlaySoundW);
DetourTransactionCommit();
} else
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)OrgPlaySoundW, &HookPlaySoundW);
DetourTransactionCommit();
}
}
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
switch(fdwReason)
{
case DLL_PROCESS_ATTACH:
Hooks::DetourPlaySoundW(FALSE);
break;
case DLL_PROCESS_DETACH:
Hooks::DetourPlaySoundW(TRUE);
break;
}
return TRUE;
}

Try setting the calling convention of HookPlaySoundW to __stdcall (because the CC of PlaySoundW is also __stdcall (from Windows.h): WINMMAPI BOOL WINAPI PlaySoundW( __in_opt LPCWSTR pszSound, __in_opt HMODULE hmod, __in DWORD fdwSound);).
I have worked with detours before and after a casual glance everything looks correct except what I mentioned above. If this doesn't resolve your problem I'd be glad to do some further investigation.
The default setting for Visual C++ is __cdecl in which the call*er* cleans up the stack, but in __stdcall the call*ee* cleans up the stack. This is probably (i.e. might possibly be) the reason for all the "rubbish being popped off the stack".

Related

Memory reading not working when hooking WIN32 API functions

I'm trying to inject the DLL into my other program and hook the win32 API function SetConsoleTitle so I can read what parameters are being passed. Everything seems to work except that the strings appear to be unreadable.
When I was hooking my function (non winapi) everything worked just fine.
SetConsoleTitle export and hooked functions:
typedef BOOL(WINAPI* SetConsole)(LPCTSTR str);
BOOL SetConsoleHooked(LPCTSTR str)
{
//im checking the string here in the vs debugger
SetConsole s = (SetConsole)ConsoleAddress;
return s(str);
}
"Error reading characters of string"
The string is showing as nonreadable and I don't know how to access it.
And here is my DLLMain function:
BOOL WINAPI DllMain(
HINSTANCE hinstDLL, // handle to DLL module
DWORD fdwReason, // reason for calling function
LPVOID lpvReserved) // reserved
{
if (fdwReason == DLL_PROCESS_ATTACH)
{
HMODULE hModule = GetModuleHandle(L"SomeFile.exe");
HandleAddress = (DWORD)hModule + (DWORD)0x51D05;
ConsoleAddress = (DWORD)hModule + (DWORD)0x55ACA;
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(LPVOID&)ConsoleAddress, &SetConsoleHooked);
DetourTransactionCommit();
while (true) {}
return true;
}
}
And lastly function from IDA that I've been trying to hook

MS Detours detoured function not being called

I'm working with MS detours 4.0, compiled in VS2005 on Windows 10 (Updating an older application).
I'm trying to detour the WriteProfileStringA function normally found in the kernel32.dll with a DLL injection.
The DLL injects just fine, I can debug the target process and can step through the detouring functions.
DetourTransactionBegin, DetourUpdateThread, DetourAttach and DetourTransactionCommit all pass with flying colours returning 0 each time.
typedef BOOL (__stdcall * WriteProfileStringAType)(CHAR *,LPCSTR,LPCSTR);
static WriteProfileStringAType OriginalWriteProfileStringA = NULL;
BOOL WINAPI DetouredWriteProfileStringA(CHAR * lpAppName,
LPCSTR lpKeyName,
LPCSTR lpString)
{
FILE* file = fopen("c:\\temp\\testdetour.txt","w");
fprintf(file,"DetouredWriteProfileStringA");
fclose(file);
return OriginalWriteProfileStringA(lpAppName,lpKeyName, lpString);
}
...
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID reserved)
{
if (DetourIsHelperProcess()) {
return TRUE;
}
if (dwReason == DLL_PROCESS_ATTACH) {
...
DetourTransactionBegin();
long update = DetourUpdateThread(GetCurrentThread());
OriginalWriteProfileStringA = (WriteProfileStringAType)GetProcAddress(GetModuleHandle("kernel32"),
"WriteProfileStringA");
long attach = DetourAttach(&(PVOID&)OriginalWriteProfileStringA, DetouredWriteProfileStringA);
long commit = DetourTransactionCommit();
...
}
else if (dwReason == DLL_PROCESS_DETACH) {
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)OriginalWriteProfileStringA, DetouredWriteProfileStringA);
DetourTransactionCommit();
}
return TRUE;
}
BUT when the target application calls the WriteProfileStringA function, the registry is updated but the detour function is never called, break points are ignored and the testdetour.txt isn't created in the c:\temp directory(which does exist)...
Anybody have any ideas?

Dll not being loaded in Firefox but loads in custom application

I posted a recent question on SO about code injection, this one is similar but not the same. I am injecting dll into Firefox, it injects successfully but the code in the DLL doesn't run. If i inject the same code into a custom application, it works. Why might that be. This is the code that I'm using.
Injector.exe // the file that's injecting the code
#include <stdio.h>
#include <windows.h>
#define procId 2844
#define dllname "dllinject.dll" // located in same directory
int main()
{
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, false, procId);
LPVOID allocated = (LPVOID)VirtualAllocEx(hProc, NULL, strlen(dllname), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(hProc, (LPVOID)allocated, dllname, strlen(dllname), NULL);
LPVOID libaddr = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
CreateRemoteThread(hProc, NULL, NULL, (LPTHREAD_START_ROUTINE)libaddr, NULL, NULL);
CloseHandle(hProc);
return 0;
}
Simpleinjected.exe // the file being injected
#include <stdio.h>
int main()
{
printf("Hello");
return 0;
}
dllinject.dll
#include <windows.h>
int message(const char *msg)
{
MessageBox(NULL, msg, "Message from Dll", MB_OK);
return 0;
}
BOOL WINAPI DLLMain(HINSTANCE hInstDll, DWORD ulReason, LPVOID lpReserved)
{
switch(ulReason)
{
case DLL_PROCESS_ATTACH:
message("process attach");
break;
case DLL_THREAD_ATTACH:
message("thread attach");
break;
case DLL_PROCESS_DETACH:
message("process detach");
break;
case DLL_THREAD_DETACH:
message("thread detach");
break;
}
return true;
}
It works when injected into simpleinjected.exe but when injected in Firefox, nothing happens even though the dll is injected successfully.
I cannot reproduce your observations. I was able to inject dllinject.dll into other processes (also firefox) but I've never seen a message box.
After a bit of digging I found that your DLLMain is spelled wrong. Change it into DllMain and you'll see message boxes in Firefox.
By the way: You propably want to change MessageBox into MessageBeep since FireFox creates/destroys a lot of threads... (this is annoying even for a quick test!)

CreateProcessWithDLLEx-Hooked process starts but can't resume

Im trying to get a basic hook going using microsoft detours. My program is able to successfully run CreateProcessWithDllEx and inject a dll. However, I cannot seem to resume the actual hooked program. I am using notepad for testing and I can see notepad.exe running in my process list, but the notepad window never actually comes up.
my dll is as follows:
#undef UNICODE
#include <cstdio>
#include <windows.h>
#include <detours.h>
#pragma comment(lib, "detours.lib")
typedef void (WINAPI *pFunc)(void);
DWORD WINAPI MyFunc(void);
pFunc FuncToDetour = (pFunc)DetourFindFunction("Winmm.dll", "timeGetTime"); //Set it at address to detour in
//the process
extern "C" __declspec( dllexport )VOID NullExport( VOID )
{
}
INT APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved)
{
switch(Reason)
{
case DLL_PROCESS_ATTACH:
{
DisableThreadLibraryCalls(hDLL);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
//DetourAttach(&(PVOID&)FuncToDetour, MyFunc);
//DetourTransactionCommit();
}
break;
case DLL_PROCESS_DETACH:
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)FuncToDetour, MyFunc);
DetourTransactionCommit();
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
DWORD WINAPI MyFunc()
{
return 0;
}
And my injector is as follows:
#undef _UNICODE
#include "stdafx.h"
#include <cstdio>
#include <windows.h>
#include <detours.h>
int main()
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(STARTUPINFO));
ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
si.cb = sizeof(STARTUPINFO);
WCHAR DirPath[MAX_PATH+1];
wcscpy_s(DirPath, MAX_PATH, L"C:\\Documents and Settings\\Administrator\\My Documents\\Visual Studio 2010\\Projects\\hbotinjector\\Release");
char DLLPath[MAX_PATH+1] = "C:\\Documents and Settings\\Administrator\\My Documents\\Visual Studio 2010\\Projects\\hbotinjector\\Release\\hbotdll.dll";
WCHAR EXE[MAX_PATH+1]={0};
wcscpy_s( EXE, MAX_PATH, L"C:\\Documents and Settings\\Administrator\\My Documents\\Visual Studio 2010\\Projects\\hbotinjector\\Release\\notepad.exe" );
STARTUPINFO _StartupInfo;
PROCESS_INFORMATION _Information;
ZeroMemory( &_Information, sizeof( PROCESS_INFORMATION ) );
if(DetourCreateProcessWithDllEx( EXE, NULL, NULL, NULL, TRUE,
CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED, NULL, DirPath, &_StartupInfo, &_Information,
DLLPath, NULL ))
{
MessageBoxA(NULL,"INJECTED", NULL, NULL);
ResumeThread(_Information.hThread);
WaitForSingleObject(_Information.hProcess, INFINITE);
}
else
{
char error[100];
sprintf(error, "%d", GetLastError());
MessageBoxA(NULL, error, NULL, NULL);
}
return 0;
}
And I build my dll with a .def file, insuring that there is the required function at ordinal 1 for detours to work properly:
LIBRARY HBOTDLL
EXPORTS
NullExport #1
Does anyone know what is causing the process from not running? As a side note, I've tried it with a blank dll as well where it just contains the required function at ordinal 1 and nothing else and it seems to have identical results.
Also, my injector runs forever as long as the notepad.exe process is showing in the process list. This is in response to WaitForSingleObject, which seems to indicate the process has been spawned correctly.
On the comment of Hans Passant, I went back and realized that I had declared pi and si as well as _Information and _StartupInfo. I wasn't zeroing out the second group I had created, and that was the group I was using. So I changed the call to CreateProcessWithDllEx to use &pi and &si. Everything works fine now.

Detect when a Module (DLL) is unloaded

Is there a way to progammatically detect when a module - specifically a DLL - has been unloaded from a process?
I don't have the DLL source, so I can't change it's DLL entry point. Nor can I poll if the DLL is currently loaded because the DLL may be unloaded and then reloaded between polling.
RESULTS:
I ended up using jimharks solution of detouring the dll entry point and catching DLL_PROCESS_DETACH. I found detouring FreeLibrary() to work as well but code must be added to detect when the module is actually unloaded or if the reference count is just being decreased. Necrolis' link about finding the reference count was handy for on method of doing so.
I should note that I had problems with MSDetours not actually unloading the module from memory if a detour existed within it.
One very bad way(which was used by starcraft 2), is to make your program attach to itsself then monitor for the dll unload debug event(http://msdn.microsoft.com/en-us/library/ms679302(VS.85).aspx), else you'd either need to IAT hook FreeLibrary and FreeLibraryEx in the process or hotpatch the functions in kernel32 them monitor the names being passed and the global reference counts.
Try using LdrRegisterDllNotification if you're on Vista or above. It does require using GetProcAddress to find the function address from ntdll.dll, but it's the proper way of doing it.
Maybe a less bad way then Necrolis's would be to use Microsoft Research's Detours package to hook the dll's entry point to watch for DLL_PROCESS_DETACH notifications.
You can find the entry point given an HMODULE (as returned by LoadLibrary) using this function:
#include <windows.h>
#include <DelayImp.h>
PVOID GetAddressOfEntryPoint(HMODULE hmod)
{
PIMAGE_DOS_HEADER pidh = (PIMAGE_DOS_HEADER)hmod;
PIMAGE_NT_HEADERS pinth = (PIMAGE_NT_HEADERS)((PBYTE)hmod + pidh->e_lfanew);
PVOID pvEntry = (PBYTE)hmod + pinth->OptionalHeader.AddressOfEntryPoint;
return pvEntry;
}
Your entrypoint replacement could take direct action or increment a counter that you check for in your main loop or where it's important to you. (And should almost certainly call the original entrypoint.)
UPDATE: Thanks to #LeoDavidson for pointing this out in the comments below. Detours 4.0 is now licensed using the liberal MIT License.
I hope this helps.
#Necrolis, your link to “The covert way to find the Reference Count of DLL” was just too intriguing for me to ignore because it contains the technical details I needed to implement this alternate solution (that I thought of yesterday, but was lacking the Windows Internals). Thanks. I voted for your answer because of the link you shared.
The linked article shows how to get to the internal LDR_MODULE:
struct _LDR_MODULE
{
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
PVOID BaseAddress;
PVOID EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
ULONG Flags;
USHORT LoadCount;
USHORT TlsIndex;
LIST_ENTRY HashTableEntry;
ULONG TimeDateStamp;
} LDR_MODULE, *PLDR_MODULE;
Right here we have EntryPoint, Window's internal pointer to the module’s entry point. For a dll that’s DllMain (or the language run time function that eventually calls DllMain). What if we just change that? I wrote a test and it seems to work, at least on XP. The DllMain hook gets called with reason DLL_PROCESS_DETACH just before the DLL unloads.
The BaseAddress is the same value as an HMODULE and is useful for finding the right LDR_MODULE. The LoadCount is here so we can track that. And finally FullDllName is helpful for debugging and makes it possible to search for DLL name instead of HMODULE.
This is all Windows internals. It’s (mostly) documented, but the MSDN documentation warns “ZwQueryInformationProcess may be altered or unavailable in future versions of Windows.”
Here’s a full example (but without full error checking). It seems to work but hasn’t seen much testing.
// HookDllEntryPoint.cpp by Jim Harkins (jimhark), Nov 2010
#include "stdafx.h"
#include <stdio.h>
#include <winternl.h>
#include <process.h> // for _beginthread, only needed for testing
typedef NTSTATUS(WINAPI *pfnZwQueryInformationProcess)(
__in HANDLE ProcessHandle,
__in PROCESSINFOCLASS ProcessInformationClass,
__out PVOID ProcessInformation,
__in ULONG ProcessInformationLength,
__out_opt PULONG ReturnLength);
HMODULE hmodNtdll = LoadLibrary(_T("ntdll.dll"));
// Should test pZwQueryInformationProcess for NULL if you
// might ever run in an environment where this function
// is not available (like future version of Windows).
pfnZwQueryInformationProcess pZwQueryInformationProcess =
(pfnZwQueryInformationProcess)GetProcAddress(
hmodNtdll,
"ZwQueryInformationProcess");
typedef BOOL(WINAPI *PDLLMAIN) (
__in HINSTANCE hinstDLL,
__in DWORD fdwReason,
__in LPVOID lpvReserved);
// Note: It's possible for pDllMainNew to be called before
// HookDllEntryPoint returns. If pDllMainNew calls the old
// function, it should pass a pointer to the variable used
// so we can set it here before we hook.
VOID HookDllEntryPoint(
HMODULE hmod, PDLLMAIN pDllMainNew, PDLLMAIN *ppDllMainOld)
{
PROCESS_BASIC_INFORMATION pbi = {0};
ULONG ulcbpbi = 0;
NTSTATUS nts = (*pZwQueryInformationProcess)(
GetCurrentProcess(),
ProcessBasicInformation,
&pbi,
sizeof(pbi),
&ulcbpbi);
BOOL fFoundMod = FALSE;
PLIST_ENTRY pcurModule =
pbi.PebBaseAddress->Ldr->InMemoryOrderModuleList.Flink;
while (!fFoundMod && pcurModule !=
&pbi.PebBaseAddress->Ldr->InMemoryOrderModuleList)
{
PLDR_DATA_TABLE_ENTRY pldte = (PLDR_DATA_TABLE_ENTRY)
(CONTAINING_RECORD(
pcurModule, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks));
// Note: pldte->FullDllName.Buffer is Unicode full DLL name
// *(PUSHORT)&pldte->Reserved5[1] is LoadCount
if (pldte->DllBase == hmod)
{
fFoundMod = TRUE;
*ppDllMainOld = (PDLLMAIN)pldte->Reserved3[0];
pldte->Reserved3[0] = pDllMainNew;
}
pcurModule = pcurModule->Flink;
}
return;
}
PDLLMAIN pDllMain_advapi32 = NULL;
BOOL WINAPI DllMain_advapi32(
__in HINSTANCE hinstDLL,
__in DWORD fdwReason,
__in LPVOID lpvReserved)
{
char *pszReason;
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
pszReason = "DLL_PROCESS_ATTACH";
break;
case DLL_PROCESS_DETACH:
pszReason = "DLL_PROCESS_DETACH";
break;
case DLL_THREAD_ATTACH:
pszReason = "DLL_THREAD_ATTACH";
break;
case DLL_THREAD_DETACH:
pszReason = "DLL_THREAD_DETACH";
break;
default:
pszReason = "*UNKNOWN*";
break;
}
printf("\n");
printf("DllMain(0x%.8X, %s, 0x%.8X)\n",
(int)hinstDLL, pszReason, (int)lpvReserved);
printf("\n");
if (NULL == pDllMain_advapi32)
{
return FALSE;
}
else
{
return (*pDllMain_advapi32)(
hinstDLL,
fdwReason,
lpvReserved);
}
}
void TestThread(void *)
{
// Do nothing
}
// Test HookDllEntryPoint
int _tmain(int argc, _TCHAR* argv[])
{
HMODULE hmodAdvapi = LoadLibrary(L"advapi32.dll");
printf("advapi32.dll Base Addr: 0x%.8X\n", (int)hmodAdvapi);
HookDllEntryPoint(
hmodAdvapi, DllMain_advapi32, &pDllMain_advapi32);
_beginthread(TestThread, 0, NULL);
Sleep(1000);
return 0;
}