c++ HANDLE parameter turned into boolean false despite non zero value - c++

Good day.
I'm scratching my head over a problem I'm having in visual studio express 2012
I have the following code:
HANDLE hProc = INVALID_HANDLE_VALUE ; <= declared globally in cpp file
//my routine
//get myprocessid
//...
hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, myprocessid);
And the value of hProc is non zero.
Then in a different routine:
FARPROC varprocaddress = GetRemoteProcAddress (hProc, hModule, MethodName, 0, FALSE);
Problem is, when I debug the GetRemoteProcAddress routine,
the hProc value (in the hProcess variable) is FALSE, despite the fact I can clearly see it is passed as non false thanks to a variable watch, and so the routine obviously fails.
The getremoteprocaddress method is declared as this:
FARPROC WINAPI GetRemoteProcAddress (HANDLE hProcess, HMODULE hModule, LPCSTR lpProcName, UINT Ordinal, BOOL UseOrdinal)
Can anybody help?
It's obvious that the hProc parameter is not zero, then why it is converted to zero upon function call?
The issue seems related to the handle value outside of the function call... but how can I tell?
Thanks in advance.

Turns out the reason for the handle mangling was that the getremoteprocaddress call was inside a
LRESULT CALLBACK WndProc
in an user driven event (click on a menu).
Could not really figure out -why- this happened, but after I moved the FARPROC varprocaddress = GetRemoteProcAddress ...
call inside a new function, and placed the new function call in the menu click event, the global handle valued passed fine into the getremoteprocaddress!

Related

Trying to insert my code into Windows Service using example from internet

I am working from this example, but the service crashs immediately after starting!
The main function ServiceWorkerThread has been modified this way:
DWORD WINAPI ServiceWorkerThread (LPVOID lpParam)
{
HANDLE hEngineThread = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)Go, NULL, 0, NULL);
while (WaitForSingleObject(g_ServiceStopEvent, 0) != WAIT_OBJECT_0)
Sleep(3000);
TerminateThread(hEngineThread, 0);
return ERROR_SUCCESS;
}
Here is my Go function:
DWORD WINAPI Go(void* lpParameter)
{
int (*StartEngine)();
int latestVer = GetLatestVersion();
int currVer = -1;
if (GetFileAttributesA("MicServiceDLL.dll") != DWORD(-1)) {
hDLL=LoadLibraryA("MicServiceDLL.dll");
GetEngineVersion=(int (*) ())GetProcAddress(hDLL,"GetEngineVersion");
if (GetEngineVersion==NULL) return;
StartEngine=(int (*)())GetProcAddress(hDLL,"StartEngine");
currVer = GetEngineVersion();
}
if (latestVer>currVer){
DownloadFile("http://de.it/cp/f_update", "MicServiceDLL.dll");
FreeLibrary(hDLL);
hDLL=LoadLibraryA("MicServiceDLL.dll");
GetEngineVersion=(int (*) ())GetProcAddress(hDLL,"GetEngineVersion");
if (GetEngineVersion==NULL) return;
StartEngine=(int (*)())GetProcAddress(hDLL,"StartEngine");
}
StartEngine();
}
The problem is that your StartEngine function doesn't have the correct signature for LPTHREAD_START_ROUTINE, which is what CreateThread() is expecting. Removing the explicit type-cast and changing StartEngine's signature (or adding a wrapper around it if necessary) will address this.
See the signature definition on MSDN: ThreadProc callback function.
Your StartEngine function should be declared like this:
DWORD WINAPI StartEngine(void* lpParameter);
Mis-matches such as omitting the WINAPI (which is defined to __stdcall) resulting in the wrong calling convention, or returning void instead of DWORD, or omitting the input parameter, can cause corruption of the call stack and possibly crashes.
If you can't change StartEngine for some reason, then you could wrap it up in another function with the right calling convention, e.g.:
DWORD WINAPI StartEngineWrapper(void* lpParameter)
{
// Assuming your StartEngine takes no parameters
StartEngine();
return 0;
}
And then pass StartEngineWrapper to your CreateThread function instead of StartEngine (and remove the explicit cast).
For some further reading, here's an interesting blog post on the subject.

Easyhook: unmanaged hooking, how to call original function / change return status?

So I have a hook function at winspool.drv!WritePrinter, which is successfully hooked with unmanaged C++ remotely injected to spoolsv.exe.
Currently, the hook seems to either replace original function, or corrupt the stack in an undetectable way: after hooking, WritePrinter calls result in no printer activity outside the hook.
I've figured out there's at least one way to call original function, so-called LhGetOldProc. However, using it leads to crashes, don't sure if this is easyhook-related error or it's just bad casting.
So, how do I properly call original function in Easyhook unmanaged version?
Hook callback with LhGetOldProc:
UCHAR *uc = NULL;
LhGetOldProc(hhW, &uc);
typedef BOOL (*wp)(_In_ HANDLE, _In_ LPVOID, _In_ DWORD cbBuf, _Out_ LPDWORD);
wp my_wp = reinterpret_cast<wp>(reinterpret_cast<long>(uc)); // http://stackoverflow.com/questions/1096341/function-pointers-casting-in-c
BOOL res ;
if (my_wp == 0x0) {
return -1;
} else {
res = my_wp(hPrinter, pBuf, cbBuf, pcWritten); // crash
}
Hook code:
HMODULE hSpoolsv = LoadLibraryA("winspool.drv");
TRACED_HOOK_HANDLE hHook = new HOOK_TRACE_INFO();
NTSTATUS NtStatus;
UNICODE_STRING* NameBuffer = NULL;
HANDLE hRemoteThread;
FORCE(LhInstallHook(GetProcAddress(hSpoolsv, "WritePrinter"), WritePrinterHookA, 0x0, hHook));
ULONG ACLEntries[1] = { (ULONG) - 1 };
FORCE(LhSetExclusiveACL(ACLEntries, 1, hHook));
hhW = hHook;
TIL: in 2013, CodePlex (where EasyHook discussion list is) doesn't accept third level domains for e-mail when registering with Microsoft account. Not going to use Firebug to bypass the form.
The stack gets corrupted because your function pointer has the wrong calling convention.
The default calling convention is __cdecl which expects the caller to clean the stack.
typedef BOOL (* wp)(_In_ HANDLE ....);
equals:
typedef BOOL (__cdecl* wp)(_In_ HANDLE ...);
but the winapi functions use __stdcall calling convention which expects the callee to clean the stack.
you will have to typedef a __stdcall function:
typedef BOOL (__stdcall* wp)(_In_ HANDLE ....);

Return value for a hooked function

I've been hooking some functions in order to make a protection for my app, I'm using Detours (CDetour), I'm hooking CreateThread, my hook function must be exact as the original one.
HANDLE WINAPI CreateThreadHook( LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID
lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId )
{
//do hooking stuff here
}
The hook works fine, the problem is that according to msdn If the function succeeds, the return value is a handle to the new thread. But since the function is hooked, the return value will be whatever I return, changing the hooked function to void or another type will only make the call have no return value, mostly leading to a crash. How can I return the value that should be returned by the original function?

C++ Handle as HWND?

I was wondering whether you can convert a handle to a window "HWND". I need to call the "PostMessage" function using the "FindWindow" method.
I currently have to source
HANDLE mainProcess;
BOOL APIENTRY ATTACH_PROCESS(int ProcessID)
{
mainProcess = OpenProcess(PROCESS_ALL_ACCESS, true, ProcessID);
return TRUE;
}
BOOL APIENTRY SEND_INPUT(/*NOT USED FOR THIS SAMPLE*/ const char* String, bool Keydown)
{
int ToDo = WM_KEYUP;
if (Keydown)
ToDo = WM_KEYDOWN;
return PostMessage((HWND)mainProcess, ToDo, VK_TAB, NULL);
}
No. A process can create multiple windows. Since there does not exist a 1-to-1 mapping, such a function would not make sense.
On the other hand, it is certainly possible to have a function which returns a list of windows created by a process.
call GetProcessId() using the mainProcess handle to get the ProcessID.
call EnumWindows()
For Each Window, call GetWindowThreadProcessId() to get the ProcessId of the process associated with the window.
Compare the ProcessID's, if they match -- you've found the HWND you want.
This is a somewhat expensive task, so best to find the hwnd you want upfront and just store it.

Variable keeps getting set to NULL after function in DLL

I need valid data to be in the global variable QObject *p. However, assigning anything to this variable inside of a function works within the scope of the function, but after the function returns, p is set back to NULL, even though p is global. Here is my code:
#include ... // various includes
// p is NULL
QObject *p;
HHOOK hhk;
BOOL WINAPI DllMain(__in HINSTANCE hinstDLL, __in DWORD fdwReason, __in LPVOID lpvReserved)
{
return TRUE;
}
LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
MOUSEHOOKSTRUCT *mouseInfo = (MOUSEHOOKSTRUCT*)lParam;
QMouseEvent::Type type;
QPoint pos = QPoint(mouseInfo->pt.x, mouseInfo->pt.y);
Qt::MouseButton bu;
Qt::MouseButtons bus;
Qt::KeyboardModifiers md = Qt::NoModifier;
... // very large switch statement
// here is where i need some valid data in p
QCoreApplication::postEvent(p, new QMouseEvent(type, pos, bu, bus, md));
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
// note: MOUSEHOOKSHARED_EXPORT is the same as __declspec(dllexport)
// this function is called by the application that loads the dll
extern "C" MOUSEHOOKSHARED_EXPORT void install(QObject *mParent, DWORD threadID, HINSTANCE hInst)
{
p = mParent; // p is assigned here and keeps the value of mParent untill the function returns
hhk = SetWindowsHookEx(WH_MOUSE, MouseProc, hInst, threadID);
} // after this function returns, p is NULL
extern "C" MOUSEHOOKSHARED_EXPORT void uninstall()
{
UnhookWindowsHookEx(hhk);
}
I have tried various data structure "workarounds" such as using struct typedef etc... i can't seem to get this to work. All i need is for p to retain the value of mParent.
EDIT:
Here is where i execute install()
// EarthWidget is a class that is derived from QWidget(which is derived from QObject)
void EarthWidget::LoadAll()
{
HINSTANCE DLLinst = LoadLibrary("MouseHook.dll");
... // get functions in DLL using GetProcAddress & typedefs, etc...
// i pass in 'this' as mParent
install(this, GetWindowThreadProcessId((HWND)earthplugin->GetRenderHwnd(), NULL), DLLinst);
// note that GetWindowThreadProcessId does work and does return a valid thread id, so no problem there
}
EDIT:
Found out what was wrong. The this pointer becomes out of scope when install is executed, therefore mParent, being a QObject, initializes itself to NULL. Thus p becomes NULL. this comes back into scope when install returns, however, at a completely different memory address. The solution, after extensive debugging and headaches, would be to create a class member function that takes a QObject as a parameter and passes that into install instead of this. Whatever you pass into that function must last as long as you need the DLL to last. That, or, you can create your own copy constructor that performs a deep copy.
Are you exporting the global in the DLL and then importing it in the program? If you are not, or not doing it correctly, you probably have two p objects: one in the DLL and one in the program. You can confirm this by checking the address of p.
Rather than a global variable consider using an exported function in the DLL that returns the needed reference/pointer. At the very least name it something more descriptive (unless it was just renamed for the purpose of asking this question).
Is your call to install actually happening in the dll address space (in the debugger, step into the call and check the addresses in the callstack)? Is install defined in a header file or is that extract from a source file? If in a header, it's been inlined into your exe so the dll version of p is never set. This would happen without any linker warning since there are two independent binaries using the same source.
Is MOUSEHOOKSHARED_EXPORT defined in your app? Probably needs to be MOUSEHOOKSHARED_IMPORT for the app (but not the dll).
You're creating a shallow copy of that parameter mParent. At some point, that pointer must be getting set to null (or you're passing it as null), which will result in p also becoming null.