MS Detours detoured function not being called - c++

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?

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

The code injects a third-party Qt application and performs some methods to get Qt application information

Code injection can get the Qt application I developed correctly, but third-party applications can't. What should I do?
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
DoSomeThing();
break;
case DLL_THREAD_ATTACH:
DoSomeThing();
break;
default:
break;
}
return TRUE;
}
void DoSomeThing() {
LPCTSTR step = L"GetQCoreApplication";
LPCSTR CustomApplications = "CustomApp";
LPCSTR ThirdPartyApplications = "ThirdPartyApp";
//CustomApplications = ThirdPartyApplications;
HWND hwnd = FindWindowA(NULL, CustomApplications);
DWORD procId;
GetWindowThreadProcessId(hwnd, &procId);
HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procId);
/*Custom programs are available. But third-party applications are not available.*/
QCoreApplication* qCoreApplication = QCoreApplication::instance();
if (qCoreApplication != NULL) {
MessageBox(NULL, L"Get QCoreApplication", TEXT("Inject Code"), MB_OK);
}
else
{
MessageBox(NULL, L"Not Acquired QCoreApplication", TEXT("Inject Code"), MB_OK);
}
ofstream mcfile;
mcfile.open("D://Inject.txt");
mcfile << "This is my message.";
mcfile.close();
/*Custom programs are available. But third-party applications are not available.*/
HWND hwnd11 = FindWindowA(NULL, CustomApplications);
QWidget* q = QWidget::find((WId)hwnd);
if (q != NULL) {
//
}
else {
//
}
}
Custom programs are available. Third-party applications are not available.
When I looked at the qt dynamic library, I found Qtxxxd.dll and Qtxxx.dll. Check out the qt documentation and find that the qt application uses Qtxxxd.dll in debug mode and Qtxxx.dll in release mode.
Make sure your injection program is consistent with the injected program using the same pattern.

Unable to call method in managed dll after loading CLR. Why?

I have met some issues when trying to inject a dll into a process. I am quite new at the topic but am familiar with C# so reading and understand the syntax of C++ wasnt that unfamiliar and i understand it for the most part.
What i am trying is only for learning, and i am trying this with simple applications like notepad.exe and calc.exe.
Project setup:
WPF application - To pick the process i want to tinker with and inject the unmanaged dll.
CppDLL.dll - Unmanaged dll to load CLR, managed dll and call method on managed dll.
SharpDLL.dll - Managed dll.
(wpf) c# of interest
dllToInject = fileDialog.FileName;
Process targetProcess = Process.GetProcessById(processToInject.ID);
var dllInjector = DllInjector.GetInstance;
DllInjectionResult injectResult;
if ((injectResult = dllInjector.Inject(processToInject.Name,dllToInject)) == DllInjectionResult.Success)
{
MessageBox.Show("Success");
} else
{
MessageBox.Show("Error: " + injectResult.ToString());
}
The unmanaged dll is successfully injected when not trying to load clr and managed dll as shown below.
But when i try to load CLR and managed dll it fails.
CppDLL.dll dllmain.cpp :
#include "stdafx.h"
#include <Windows.h>
#include <metahost.h>
#pragma comment(lib, "mscoree.lib")
#import "mscorlib.tlb" raw_interfaces_only \
high_property_prefixes("_get","_put","_putref") \
rename("ReportEvent", "InteropServices_ReportEvent")
void LoadDotNet()
{
HRESULT hr;
ICLRMetaHost *pMetaHost = NULL;
ICLRRuntimeInfo *pRuntimeInfo = NULL;
ICLRRuntimeHost *pClrRuntimeHost = NULL;
hr = CLRCreateInstance(CLSID_CLRMetaHost, IID_PPV_ARGS(&pMetaHost));
hr = pMetaHost->GetRuntime(L"v4.0.30319", IID_PPV_ARGS(&pRuntimeInfo));
hr = pRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost,
IID_PPV_ARGS(&pClrRuntimeHost));
hr = pClrRuntimeHost->Start();
DWORD pReturnValue;
hr = pClrRuntimeHost->ExecuteInDefaultAppDomain(
L"C:\\Users\\DanHovedPC\\Desktop\\inject\\SharpDLL.dll",
L"SharpDLL.Injected",
L"Start",
L"Hello from .NET",
&pReturnValue);
pMetaHost->Release();
pRuntimeInfo->Release();
pClrRuntimeHost->Release();
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
MessageBox(NULL, L"Hi!", L"From cpp DLL", NULL);
//LoadDotNet();
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
SharpDLL.dll Injected.cs
using System.Windows;
namespace SharpDLL
{
class Injected
{
public static int Start(string arg)
{
MessageBox.Show(arg);
return 0;
}
}
}
In CppDLL.dll if i uncomment the function and comment the messagebox it fails. The SharpDLL.dll does not get injected. And when i try to close notepad the process still shows up in Process Explorer.
I have looked at the process in Process Explorer beforehand and the clr.dll is not loaded by default, but it gets loaded when the function runs. Maybe it could be the .NET version? I am running Windows 10 x64.
Update
The code runs until i try to actually start the runtime
void LoadDotNet()
{
HRESULT hr;
ICLRMetaHost *pMetaHost = NULL;
ICLRRuntimeInfo *pRuntimeInfo = NULL;
ICLRRuntimeHost *pClrRuntimeHost = NULL;
hr = CLRCreateInstance(CLSID_CLRMetaHost, IID_PPV_ARGS(&pMetaHost));
hr = pMetaHost->GetRuntime(L"v4.0.30319", IID_PPV_ARGS(&pRuntimeInfo));
hr = pRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost,
IID_PPV_ARGS(&pClrRuntimeHost));
// start runtime
MessageBox(NULL, L"Runs up to here...", L"DEBUG", NULL);
hr = pClrRuntimeHost->Start();
MessageBox(NULL,(LPCWSTR)GetLastError(),L"DEBUG",NULL);
pMetaHost->Release();
pRuntimeInfo->Release();
pClrRuntimeHost->Release();
}
The first messagebox shows.
I figured out that the problem was that code within DllMain must not access the CLR.
Code within DllMain must not access the CLR. This means that DllMain should make no calls to managed functions, directly or indirectly; no managed code should be declared or implemented in DllMain; and no garbage collection or automatic library loading should take place within DllMain.
https://msdn.microsoft.com/en-us/library/ms173266.aspx
When creating a new thread the code runs successfully
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
//printf("DLL Loaded!");
CreateThread(NULL, 0,
(LPTHREAD_START_ROUTINE)LoadDotNet, NULL, 0, NULL);
}
return TRUE;
}
And from reading a comment on another question here on SO CreateThread should be safe in this particular case.

__attribute__((destructor)) equivalent in VC?

I've looked at __attribute__((constructor)) equivalent in VC? and CRT Initialization, which were both helpful regarding the gcc-specific __attribute__((constructor)). But what about __attribute__((destructor))? Is there a VC equivalent?
If you're making a dynamic link library, you can make your DllMain entry point handle this:
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH)
{
// equivalent of __attribute__((constructor))...
// return TRUE if succeeded, FALSE if you failed to initialize properly
return TRUE; // I'm assuming you succeeded.
}
else if (fdwReason == DLL_PROCESS_DETACH)
{
// equivalent of __attribute__((destructor))...
}
// Return value is ignored when fdwReason isn't DLL_PROCESS_ATTACH, so we'll
// just return TRUE.
return TRUE;
}

MS Detours 2.1 - Popping out of stack

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".