I want to install a hook (on Windows using the WinAPI and C++) to get key-input events that are sent to the WindowProc of a specific process/thread (known to my program by process ID). As far as I understood I have to put the hook procedure into a DLL. So far everything is fine for me. But the hook procedure needs to use data from the program that installed the hook. Now I don't know how to access this data from my hook procedure inside the DLL.
My first thoughts were to maintain a data struct inside the DLL itself and update it from outside by calls to another function placed inside the DLL. But I am not sure, how exactly to do that (for example: I assume this data struct would have to be shared data so that it is the same for all calls, no matter from which process/thread, but I am not sure about it).
I've looked at a few examples on how to implement hooks but these examples never used data from the original program that installed the hook (or any other 'user-code').
I would really appreciate it when somebody could explain this to me or even give me a brief outline on how to solve the problem described above (and whether my approach is right).
Many thanks in advance!
You may use Shared Data section
// dll.cpp
#pragma data_seg("myshared")
int iShared;
#pragma data_seg()
#pragma comment(linker, "/section:myshared,RWS")
Export a function from the DLL, allowing to pass the value(s) to be used for the variable(s) in the section. Call that function from your hooking EXE (before hooking). The instance DLL in the hooked process will see the value(s) set by the hooking EXE.
What you really are describing is inter-process communication(IPC): http://en.wikipedia.org/wiki/Inter-process_communication
Your options for windows are to create a socket, a pipe, or shared-memory and use mutexes, semaphores, or events for synchronisation.
Other than that, there is no way to call functions in a dll injected into another process.
You can view an example I posted here: Two separate processes sharing the same Camera feed OpenCv
Related
I've injected a DLL file into another process and I wish to communicate with it though an external EXE. How can I communicate with the injected DLL? :/
If I've understood your question properly, you have injected a DLL to a process and want to communicate with it via some external EXE. You can use the standard methods of IPC (Interprocess Communication) here. I know a link should not be posted by itself but IPC on Windows is too broad a topic to cover comprehensively without copy and pasting from the linked article.
I have done the same thing as what you are attempting here and used named piping and data copying via WM_COPYDATA for IPC. However, there was a particular reason why I used each form of IPC so we really need to understand more from your problem domain before recommending a single one.
Something unrelated that you are doing is that you are calling CreateThread on a function you have casted to LPTHREAD_START_ROUTINE, which means it should point to a ThreadProc callback. Your current signature of void WINAPI () does not match the required DWORD WINAPI (LPVOID).
If all your DLL needs to do is to forward messages, it is possible to have it act as a proxy for messages.
Have the DLL create an invisible window
Pass the window handle to the source process
Have the source process dispatch messages to this window
The DLL will receive these messages and can then forward them to the destination window
However, if this is all you need to do then there is no need to have a DLL in the middle at all. This is why I say we need more information about your problem domain.
If you are trying to have something in the form of an executable which injects a DLL, then communicates with the DLL and the DLL communicates back, you might want to take a look at a project I worked on a while back. This does exactly that.
You need to communicate between your EXE and the application your DLL has been injected into.
So in your DLL you will need to spawn a thread that waits for some kind of communication from the EXE. You cannot wait for the event in the DllMain, because that will deadlock the application.
A simple way to do it is to create a named event and wait for it to be set in your DLL. Then in your external EXE, when your button is clicked, you set the event.
I known such tools
http://portableapps.com/development/projects/registry_rapper
RegRap.exe can get through param other .exe file and catch requests to registry and save it into .ini
That is good, but I need snippt code to set such hundler inside my C++ program and for given Reg KEY return my value...
RegRap.exe written with NSIS scripts that is why is not helpful for me :(
But may be somebody known other project only with c++?
Thx, and sorry for my bad english.
If you want to track registry access within YOUR program, you can #define away the registry API functions, provide your hooks instead, and track it in your hooks.
//in your stdafx.h, or some other universally included file
#define RegCreateKeyEx MyRegCreateKeyEx
//somewhere else
#undef RegCreateKeyEx
LONG WINAPI MyRegCreateKeyEx(stuff...)
{
//Track
//Call the real RegCreateKeyEx
}
That's probably the easiest way of hooking an API. Will not work if you want to track registry usage by your program but outside of your code (i. e. in libraries or DLLs). Then more advanced techniques are in order.
Also, consider Process Monitor by Mark Russinovich: http://technet.microsoft.com/en-us/sysinternals/bb896645
It's not a programmatic hook, but an awesome tool all around, and therefore worth plugging. It monitors registry access by your process(es) and then some.
This post seems to say that there are no hooks for the registry and you can only long poll. Simple way to hook registry access for specific process
If you want to use pure C++, check out the libraries EasyHook and Detours. Both are intended for this sort of function-level hooking. EasyHook works in C++ and C#, 32 and 64-bit, while Detours is somewhat outdated and only for 32-bit C++ (even running it on a 64-bit OS can crash your program).
You need to install the hook within the target process, either by loading your code as a DLL or creating the process (suspended), installing the hooks and then running it.
In EasyHook that goes something like:
LhInstallHook(&RegCreateKeyEx, &MyRegCreateKeyEx, &hookstruct);
You can also hook functions your library is not linked to using the Windows API to get the address.
Is there a way (in C++ & windows XP) to detect if one process spawns any other processes?
for example,
write.exe in system32 spawns wordpad.exe then disappears, is there a function that tells me if the process is about to do this?
for those interested i solved the problem using this section of msdn:
http://msdn.microsoft.com/en-us/library/aa390425(v=VS.85).aspx
Nothing in the Win32 API for this. However, it is supported through WMI with the Win32_ProcessStartTrace query. You'll find some C# code that demonstrates the query in my answer in this thread. Writing WMI code in C++ is fairly painful, you'll find a link to boilerplate code you have to write in the MSDN Library article.
Do beware that this isn't particularly fast. It isn't clear to me how much help the WMI provider gets from the kernel to generate the notification but given the speed it quacks like polling. In other words, the process is likely to be well on its way by the time you get the notification. This is otherwise par for the course on a multitasking operating system.
You can enumerate over the process tree, which identifies running processes and their parents. This is the inverse of what you want (you want to identify child processes, not parent processes). But of course by keeping track of parent process IDs while enumerating, you can identify which sub-processes a given process has spawned.
To do this, call CreateToolhelp32Snapshot and then use Process32First and Process32Next to enumerate the processes. The enumeration will fill in a PROCESSENTRY32 struct that contains a th32ParentProcessID member.
This is a polling method; there may be another way of actually hooking the CreateProcess function, but I don’t have any information about that.
I think you would need to make a global hook DLL that attaches itself to every running process. DLL then finds a place where a function call to CreateProcess is mapped to actual CreateProcess from kernel32, and change a table entry to redirect the call to it's own code to "detect" the call to CreateProcess. All this assuming that some user firewall will not prevent your global hook from executing.
I need to get the list of functions in global hook chain in Windows and get their corresponding application if it's possible. I don't know how to retrieve information from the global hook chain however.
As far as I know there is no windows API for doing this so I think I have to find them by parsing the hook chain link list. The problem is that I don't know the data structure of this link list and it's begin address.
Does anyone know how windows manages its global hook chain?
One approach I've seen is shown in this blog post. It was referenced by this code (beware of slow server). Crazy stuff of course, no idea how well this will port between different Windows versions.
Instead of trying to walk an internal Windows structure, you know that all Window hooks must have a loaded module associated with them that has been injected into the target process; if you're trying to ensure that your own application isn't being hooked, enumerate the loaded module list and look for modules that shouldn't be there.
Suppose I have an OpenGL game running full screen (Left 4 Dead 2). I'd like to programmatically get a screen grab of it and then write it to a video file.
I've tried GDI, D3D, and OpenGL methods (eg glReadPixels) and either receive a blank screen or flickering in the capture stream.
Any ideas?
For what it's worth, a canonical example of something similar to what I'm trying to achieve is Fraps.
There are a few approaches to this problem. Most of them are icky, and it totally depends on what kind of graphics API you want to target, and which functions the target application uses.
Most DirectX, GDI+ and OpenGL applications are double or tripple-buffered, so they all call:
void SwapBuffers(HDC hdc)
at some point. They also generate WM_PAINT messages in their message queue whenever the window should be drawn. This gives you two options.
You can install a global hook or thread-local hook into the target process and capture WM_PAINT messages. This allows you to copy the contents from the device context just before the painting happens. The process can be found by enumerating all the processes on the system and look for a known window name, or a known module handle.
You can inject code into the target process's local copy of SwapBuffers. On Linux this would be easy to do via the LD_PRELOAD environmental variable, or by calling ld-linux.so.2 explicitly, but there is no equivalient on Windows. Luckily there is a framework from Microsoft Research which can do this for you called Detours. You can find this here: link.
The demoscene group Farbrausch made a demo-capturing tool named kkapture which makes use of the Detours library. Their tool targets applications that require no user input however, so they basically run the demos at a fixed framerate by hooking into all the possible time functions, like timeGetTime(), GetTickCount() and QueryPerformanceCounter(). It's totally rad. A presentation written by ryg (I think?) regarding kkapture's internals can be found here. I think that's of interest to you.
For more information about Windows hooks, see here and here.
EDIT:
This idea intrigued me, so I used Detours to hook into OpenGL applications and mess with the graphics. Here is Quake 2 with green fog added:
Some more information about how Detours works, since I've used it first hand now:
Detours works on two levels. The actual hooking only works in the same process space as the target process. So Detours has a function for injecting a DLL into a process and force its DLLMain to run too, as well as functions that are supposed to be used in that DLL. When DLLMain is run, the DLL should call DetourAttach() to specify the functions to hook, as well as the "detour" function, which is the code you want to override with.
So it basically works like this:
You have a launcher application who's only task is to call DetourCreateProcessWithDll(). It works the same way as CreateProcessW, only with a few extra parameters. This injects a DLL into a process and calls its DllMain().
You implement a DLL that calls the Detour functions and sets up trampoline functions. That means calling DetourTransactionBegin(), DetourUpdateThread(), DetourAttach() followed by DetourTransactionEnd().
Use the launcher to inject the DLL you implemented into a process.
There are some caveats though. When DllMain is run, libraries that are imported later with LoadLibrary() aren't visible yet. So you can't necessarily set up everything during the DLL attachment event. A workaround is to keep track of all the functions that are overridden so far, and try to initialize the others inside these functions that you can already call. This way you will discover new functions as soon as LoadLibrary have mapped them into the memory space of the process. I'm not quite sure how well this would work for wglGetProcAddress though. (Perhaps someone else here has ideas regarding this?)
Some LoadLibrary() calls seem to fail. I tested with Quake 2, and DirectSound and the waveOut API failed to initalize for some reason. I'm still investigating this.
I found a sourceforge'd project called taksi:
http://taksi.sourceforge.net/
Taksi does not provide audio capture, though.
I've written screen grabbers in the past (DirectX7-9 era). I found good old DirectDraw worked remarkably well and would reliably grab bits of hardware-accelerated/video screen content which other methods (D3D, GDI, OpenGL) seemed to leave blank or scrambled. It was very fast too.