DLL injection prior to process execution - c++

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.

Related

Hooking dll into running process using loadappinit_dlls registry key

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

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.

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.

Hiding a file from other programs

I need to make a file not appear to another program. For instance, when another program gets the list of files in a folder, I want one particular one not to show up. I am injecting a DLL from which my code will run into the process from which I want to hide the DLL file on the filesystem. I am using Microsoft Visual C++ 2010 and Windows 7.
Yes, as you've mentioned you need to intercept the file/folder enumeration APIs and filter out the specific file/folder from the enumeration result in order to "hide" that file/folder. This can be done either at user mode or kernel mode.
User mode: User mode hooking involves DLL injection. There are many places where you can hook:
IAT hooking of executables: Find out the entry FindXxx in import address table of the target process and overwrite it with the address of trampoline function present in injected DLL.
EAT hooking of DLLs loaded by executables: Find out the entry of FindXxx APIs in export address table of loaded DLL (kernel32.dll in this case) and overwrite it with the address of trampoline function present in injected DLL.
Inline hooking: Overwriting first few instructions of an API code in a loaded DLL with a JMP to your trampoline function.
Generally, user mode tend to become "ugly" (difficult to manage) as you need inject your DLL into all of the running processes if you want a system-wide hook (or at least into Explorer.exe or your target application). Many applications, like security software, have protection mechanisms to detect and deny DLL injection.
A cleaner way to implement user mode hooking is to hook APIs in NTDLL.dll (using either EAT or inline hook). All other APIs (like FindFirstFile/FindNextFile) end up calling an equivalent NtXxx APIs (like NtQueryDirectoryFile) provided by NTDLL.dll. The NtXxx API is the point where control jumps to kernel mode by executing INT 2E/SYSENTER.
Kernel mode: This involves writing a driver. Again, in kernel mode there are many places where you can install hook:
SSDT hook: Install an SSDT hook for the required ZwXxx API (ZwQueryDirectoryFile in this case) by overwriting the corresponding SSDT index with the address of trampoline function in your driver.
Kernel inline hook: Overwrite the first few instructions of NT kernel API exported by kernel (NtQueryDirectoryFile in this case) with a JMP to point to trampoline function in your driver.
File system filter driver: This is a cleaner approach and no hooks are involved. Install a file system filter driver and intercept read/write/enumerate IOCTLs and filter out the results to hide/lock a specific file/folder.
Kernel mode hook tend to be cleaner as they generally installed at one "centralized place". However, you should be very careful as a small mistake/mishandling in driver code can end up with a BSOD.
PS: There are many hooking library/frameworks available to ease the job of writing code. Some popular ones are:
http://www.madshi.net/madCodeHookDescription.htm
http://easyhook.codeplex.com/
PPS: Hiding files/folders using such techniques without user's consent might be a questionable action and can become problematic (Remember Sony DRM protection software issue? ;) ). This is what rootkits do! There are many user mode and kernel mode rootkits that use the techniques mentioned above to hide files/folders. There are various anti-rootkit software available to detect and restore all sorts of hooking described above. Many anti-virus software raise a flag when they detect such rootkit like behavior (like API hooking, hidden files, SSDT hooks etc.)
Few resources:
http://www.codeproject.com/KB/threads/APIHooking.aspx
http://www.codeproject.com/KB/DLL/funapihook.aspx
http://www.codeproject.com/KB/system/api_spying_hack.aspx
http://www.codeproject.com/KB/system/hide-driver.aspx
http://www.uc-forum.com/forum/c-and-c/59147-writing-drivers-perform-kernel-level-ssdt-hooking.html
http://www.security.org.sg/code/apihookcheck.html
Easiest way to do that would be using Microsoft Detours to override the functions you need. It can also be used to inject the DLL, but you already have that covered. If there's a specific function used by the other process that is known to you, hook on that. If not, you'll need to hook on the building blocks of all functions used to list files or open them. Hooking just CreateFile/FindFirst/FindFirstFile/etc would be enough as they just call an internal function. For example, if you hook CreateFile which actually maps to CreateFileA, the process will still be able to access the file using CreateFileW. So you want to hook NtCreateFile and friends. But I guess you know which process you're messing with, so you know exactly which functions to mess with too.

How can I update an in-use COM DLL?

One part of some software I have written is a COM dll.
Other software uses this COM dll.
My software has an update function where it will download a newer version of the dll, but the update will fail if the dll is in use because the file cannot be deleted or written to.
The question is, how can I update a COM dll that is in use?
I have considered popping up a message asking the user to close any applications that are using the DLL if it is in use, if this is the best solution how would I go about detecting if the COM dll was in use before popping up the message?
Thanks in advance.
You cannot update it in place for existing applications, but one way to do this would be to save it with a different file name or different folder and call DllRegisterServer on the DLL to register it under the new name. New applications which begin using your object should now use the new version.
If this is just a matter of detecting whether you can replace the file then it is easy. Just try to open it with a share flag that denies reading. That's going to fail if the DLL is loaded in another process. Use _fsopen() or CreateFile(). Beware of the race condition.
Detecting which processes have the file loaded is a harder problem, CreateToolhelp32Snapshot() and Process32First/Next plus Module32First/Next to enumerate processes and the DLLs they have loaded. Still tough to generate a good diagnostic for the user, the process name isn't that helpful.
When you have downloaded the update, you must launch a third program (which you write) that does not have any dependancies on your COM component, or any other piece that is to be updated. This launcher, or bootstrapper, must shut down all your pieces, uninstall them, and install the update. When the update is installed you may then re-launch your application.
If you need also to download updates to the updater itself, your main program can do that.
Here is a simple solution for you. Create a wrapper DLL, which will be used by the other processes. Inside that DLL you explicitly load/unload your DLL, which is subject to updates. Of course you will have to suspend all callers when an update process kicks in.