Control Win32 process from injected DLL (VC++.NET 2010) - c++

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.

Related

WinAPI: Non-dll data in hook function

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

Require specific event completion before application launch

I'm working on an application (DLL) that logs specific WIN32 calls using Detours. It is injected into a target application that passes the filter. It has to absolutely log every call that the application makes, starting from the first instruction in the application's entry point.
I now am looking for a way to make my application (the one that always runs) inject the DLL as fast as possible, preferably without the target application making any other calls.
Is there any way to achieve this?
You could use the AppInit_DLLs registry key to load a dll into a process. The dll is loaded during DLL_PROCESS_ATTACH of User32.dll. For regular applications this should happen prior to running any application code.
Keep in mind though that AppInit_DLLs should be renamed Deadlock_Or_Crash_Randomly_DLLs.
As far as I know, there's no straightforward way of doing this in Windows.
Your options are:
Hooking the CreateProcess (or lower) function in all processes. When a new process is created, change the arguments to create it as suspended, inject, and resume if needed.
Using a driver.

Detecting child processes

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.

SetWindowsHookEx - Dll Injection misses out on the first few calls

I am trying to use SetWindowsHookEx to capture calls to a API in java.dll.
So I created another dll, and injected into all other processes using setwindowsHookEx
g_hHook = SetWindowsHookEx(WH_CALLWNDPROC, JLoadSetFunc, g_hHookDll, 0)
The problem is following:
While trying to capture calls from a process, I notice that my dll get attached to that process after a couple of calls to the hooked function has already been executed.
So the problem is my hooking mechanism misses the first few calls of the hooked API.
Please suggest or comment on this problem to guide me.
I am stuck terribly with this one.
I suggest the following:
Register your hook using SetWindowsHookEx()
SendMessage() to the remote process with a special message that only your hook understands
Repeat this until your hook replies
Call the code you want your hook to interact with
In short, wait for the hook to finish installing before you try using it.
#MSalters
A little correction: not into every process - it is loaded only to processes that import/use user32.dll, and not all processes use it (however I agree that most processes do use it).
See Working with the AppInit_DLLs registry value for more details.
There's an awfully dirty hack to load DLLs into every process using a registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs

Detecting multiple launches of a Windows application

What's the approved way to handle second, third, etc launches of application in Windows (C++) application? I need the running (first) instance to take some special action (pop up a dialog) in this case, but for the secondary instances to terminate.
On Mac, AppleEvents sends you a 're-open' message in this scenario. Mozilla on Windows uses DDE to check for an existing instance and pass the command line through. It feels like a pretty nasty solution, all the same.
The windows way is to open a named mutex and, if you can acquire it, it means you're the first instance, if not, there is another one. At this point you can register a windows message (the function is literally RegisterWindowsMessage) which gives you a WM_ msg you can send to all windows and only your app would know to catch it, which allows you to tell your initial copy to open a dialog box or w/e.
How to limit 32-bit applications to one instance in Visual C++
"The method that is used in this article is the one that is described in MSDN under the WinMain topic. It uses the CreateMutex function to create a named mutex that can be checked across processes. Instead of duplicating the same code for every application that you will use as a single instance, the code that you must have is in a C++ wrapper class that you can reuse across each application."
SendMessage Function
"Sends the specified message to a window or windows. The SendMessage function calls the window procedure for the specified window and does not return until the window procedure has processed the message."
"Applications that need to communicate using HWND_BROADCAST should use the RegisterWindowMessage function to obtain a unique message for inter-application communication."
RegisterWindowMessage
"The RegisterWindowMessage function defines a new window message that is guaranteed to be unique throughout the system. The message value can be used when sending or posting messages."
On windows there is not really solution for that at least not out of the box.
You can use mutex to do such things, basically the app check for the mutex at startup create it if it doesn't exist.
There is one issue with CreateMutex method that you might need to consider - the named mutex might have been created by a third party. Now, most of the time, this won't be an issue, there would be no reason for someone else to block your application. However, if you're making a program that does something important, it may be an issue. Consider, if your program was a virus scanner, a virus could disable it by creating the mutex.
Usually, CreateMutex should do the job, but you should be aware of the limits of this method.