Hooking dll into running process using loadappinit_dlls registry key - c++

Currently I am working on a application in which I need to hook dll into running application. In order to achieve this goal, I have updated the LoadAppInit_DLLs registry key to 1 and AppInit_DLLs has been set to the location of the dll.
This approach works fine as the application get opens the dll get injected into the process of that application.
However, this injection process not only inject the dll into the application that I am interested, but it injects it for all the applications that I am starting in windows operating system. How could I specify this inject to happen only for the application that I need it to inject and not for all the application. I am looking for a way to know from the dll that which application it is calling and then to decide whether to load it or ignore loading it.

How could I specify this inject to happen only for the application that I need it to inject and not for all the application.
Using AppInit_DLLs, you can't.
Working with the AppInit_DLLs registry value
All the DLLs that are specified in this value are loaded by each Microsoft Windows-based application that is running in the current log on session.
I am looking for a way to know from the dll that which application it is calling
A DLL is loaded into the address space of a process. A DLL can call GetModuleFileName(NULL) to get the
full path and filename of the process it has been loaded into.
and then to decide whether to load it or ignore loading it.
Normally, a DLL's DllMain() entry point allows the DLL to selectively abort loading by returning FALSE to the DLL_PROCESS_ATTACH notification. However, AppInit_DLLs specifies additional DLLs that are deemed required for successful app initialization, similar to static-linked DLLs, so it does not allow DLLs the luxury of selective loading. If an AppInit DLL returns FALSE, the whole process is aborted.
You will have to manually hook the DLL into the target app yourself. You can do that by either:
Using CreateRemoteThread() to call LoadLibrary() from inside a specific process to load the DLL into that same process. The DLL's entry point does not need to validate the loaded process, since the loading app has already done so when deciding which process to load the DLL into.
This approach takes some setup, though. You have to use VirtualAllocEx() and WriteProcessMemory() to copy the DLL's full path string into the target process before you can then have the remote thread call LoadLibrary() with that path string as input.
Using SetWindowsHookEx() to install a global system-wide hook that is implemented inside the DLL, so the DLL gets loaded into every running process.
The difference between this approach and using AppInit_DLLs is that this approach is handled dynamically after each process is running, and thus allows the DLL the luxury of selectively aborting its own loading without terminating each process it rejects.
Configuring the Application Compatibility Toolkit to load your DLL into the specific app(s) you are interested in.

All DLLs, listed in the LoadAppInit_DLLs registry key will be loaded to the all processes, linked against user32.dll. If for some reason your dll is unable to load (for example - you had returned FALSE from the DllMain on DLL_PROCESS_ATTACH) the process will be terminated. Using LoadAppInit_DLLs even for the debugging purposes is messy and pretty dangerous. Perhaps you should choose another hooking mechanism, for example using SetWindowsHookEx

Related

How to prevent my dll from running when a certain process isn't active

So I want to make my dll only be injectable by my injector and I figured that a good way to do that is by only letting my dll be able to open when the injector is running. But I have no Idea how to do that.
As Mayur mentioned in comments, your DLL can enumerate running processes using EnumProcesses(), and get their filenames looking for a match to your injector. You can do that in your DLL's entry point function during the DLL_PROCESS_ATTACH stage. If the injector is not detected, your entry point can return FALSE to abort the load.
Alternatively, a much simpler way to detect your injector is to have it create a named mutex via CreateMutex() in the global kernel namespace, and then have the DLL entry point try to access that same object via OpenMutex(), and fail to load if the mutex does not exist. See Using Named Objects for more details.

Loading custom DLLs instead of original DLLs

The question below is for educational purposes only and the discussed featured are not meant to alter registered DLLs or develop a malware but for learning and experiencing.
Recently I've been exploring few methods to load my own custom DLLs instead of an application's original DLLs.
One of the methods that came up was the <exe>.local method.
After experiencing with this method a little bit and after I removed the KnownDlls entry from the registry I managed to replace some system DLLs with my patched DLLs successfully.
These are the DLLs:
However, the DLLs are IN the local folder:
However, there are still some DLLs that insist loading from the system32 directory, although they are present in the local folder.
Is there any way I can force the DLL's to load from the local folder instead of the system32 folder?
This is not an answer so much as a rambling, unsourced, brain dump.
It does serve to explain why I am not surprised at your result. This boils down, for me, to the crucial difference between CreateProcess and LoadLibrary, and how Win32 processes work.
Normally, when using LoadLibrary, you are using it from within the process you want the dll to be loaded into. As such, it can take advantage of a whole bunch of in-process context information about activation contexts, dll search paths etc. including knowledge of things like the app.local flag.
All these values are specific to the current process and it is not the job of any other process (or even the Kernel) to track stuff like this.
But, if we look at CreateProcess we can see some problems. When it is initially called, it is called in the context of the launching, not destination, process, so it knows nothing of the destination processes activation context. In fact, the destination process does not exist yet.
The CreateProcess implementation needs to create a NT process, and execute some code in it asap to perform the process load as it doesn't make any sense to instantiate all that per process context stuff in the current process.
But, to do that, there needs to be at least some code in the destination process: The kernel code responsible for parsing the EXE files header, extracting the headers and building the activation contexts that will be used to load the remaining dlls.
This means that, unfortunately for you, kernel32.dll and some dependencies need to be mapped into a process long before that process is capable of building a dll search context, noticing the app.local flag etc.
You should look at how the Windows loader works. This is OS version dependent, but some of those DLLs load before your program and the loader always looks for them on a path provided by the system. Look at the sequence by starting your program with WinDbg.

DLL injection prior to process execution

I am trying to use dll injection to intercept a call to Direct3DCreate8 from my application to acquire a handle to the Direct3d device and draw an overlay on the screen that it projects. The call to this API happens right after the application's execution which, if I understand correctly, renders useless the dll injection into running process technique as the API call I was after has already happened when I inject the dll.
Is this assumption correct? If yes, how can one inject the dll during process execution to catch a desired API call?
EDIT: I am aware of system-wide api hooks but would be nice to hear a 'local' solution to this problem.
EDIT 2: Forgot to mention, replacing the .dll in the application's folder is of no use, as the application looks for the .dll (d3d8.dll in my case) in System32/SysWOW64 directories.
Being a bit late for the party I wanted to offer you a solution of using Microsoft Detours (which is free for non-commercial use on x86 platforms and costs tremendous money otherwise). They have a DetourCreateProcessWithDllEx function that might suit your needs.
Quoting Detours documentation:
The process is created in a suspended state with the CREATE_SUSPENDED flag to CreateProcess. Detours then modifies the image of the application binary in the new process to include the specified DLL as its first import. Execution in the process is then resumed. When execution resumes, the Windows process loader will first load the target DLL and then any other DLLs in the application's import table, before calling the application entry point.

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.

CreateRemoteThread before DLL's are loaded

I am trying to inject my code to another process using CreateRemoteThread, but if my code is being injected while process is loading DLL's, thread becomes frozen until DLL's are loaded (it is OK according to MSDN). I have tried to detect if process is loaded by injecting code and waiting for result and checking EAX then, but it is very slow.
So, I'm looking for method to check if process is still loading DLL's or it has all DLL's loaded and I can call CreateRemoteThread to wait my code being executed immediately.
Use the Debug API, run your target process as a debugee and have your injecting process be the "debugger", you will then get informed of all of the DLL load/unload events and also when the process is loaded and ready to run (you hit the "loader breakpoint"). It gets more complex for x64 and more complex still if you're trying to inject into managed code but it works pretty well.
I have several tools which use this method (here and here) no source code available, sorry.
If what you are trying to do is hook various APIs, then the canonical way of doing this is to always also hook LoadLibrary() so that you can hook any NEW DLLs that are loaded whilst the process is running. I still find it useful, however, to control the target process using the debug api as it makes it easier to hook as soon as you can (at loader breakpoint, before you resume the process).
Since you already have a HANDLE to the target process, try using WaitForInputIdle() before calling CreateRemoteThread().