is it possible to inject multiple Dlls with MS detours? - c++

In c++ ,I want to hook more than one dll to a process. Right now I use CreateProcesswithdll() which can hook only one api at a time. What can I do to inject multiple dlls?
I came across this problem because MS detours requires us to name our custom dll the same as original dll in order to properly detour the api calls. So even though i could have different api calls handled in the same detour dll I created I need to have different names to hook calls from different apis, which means I need different detour Dlls. This also means I need to inject different DLLs. Am I right?
If I am unclear about something I will try to present it more clearly :D
Thanks!
P.S: Just to make my problem more lucid. I need to inject more than 1 dll onto the same process. CreateProcesswithdll() creates a new process with its thread in sleep state. It is woken up after the detours has finished injecting the dll and setting up the hooks. If I want to inject more than one dll I obviously cant repeatedly call CreateProcesswithdll()
so what do i do?? or Is my understanding about some aspect of this wrong?

Calling LoadLibrary() and FreeLibrary() is NOT SAFE from DLLMain(). From TFA:
"The entry-point function should
perform only simple initialization or
termination tasks. It must not call
the LoadLibrary or LoadLibraryEx
function (or a function that calls
these functions), because this may
create dependency loops in the DLL
load order. This can result in a DLL
being used before the system has
executed its initialization code.
Similarly, the entry-point function
must not call the FreeLibrary function
(or a function that calls FreeLibrary)
during process termination, because
this can result in a DLL being used
after the system has executed its
termination code."
EDIT: Apologies - this was meant as a comment for Serge's answer above.

Seems like detourattach and detourdetach will do the trick for me. Thanks everyone!
I found this blog useful!

Obviously you can load any number of DLLs from the first DLL you inject with detours.
EDIT.
When DLL is loaded system runs DllMain of your DLL (with fdwReason==DLL_PROCESS_ATTACH) and then within that function you can do whatever you like, e.g. you can call LoadLibrary to load other DLLs.
ADD:
I totally agree with comments that calling LoadLibrary from DllMain is unsafe. So you can call LoadLibrary (and all the other tricky things) from thread created in DllMain.

Related

LoadLibrary and SetWindowsHookEx inquiry

I wanted to make sure i fully understand those API functions. If I have an application and a dll where i created a thread. I load this dll inside the application with LoadLibrary function. Does it mean that this dll thread is now a thread of that application?
P.S The thread in the dll created via exported function if that matters.
Thanks.
Understand that threads are an element of an executing process - there's no real notion of a DLL "owning" a thread. The code that starts the thread may well have originated from a function call in code contained in a DLL, but the process that loaded the library is the one that owns the thread. Loading the library merely makes the code in that library available to the calling process dynamically (at runtime).

Injecting a hook DLL into a process before its imports get called?

I have a target process which loads a DLL before its main code gets called. It accomplishes this through a DLL whose name was added to the file's ImportsTable (using StudPE). My goal is to create a hook DLL that will be injected into this process and intercept its calls before it loads its imports. So the target process will load my hook dll before its security DLL. I tried using the conventional method but I hadn't success because the security DLL always gets called before my hook DLL's DllMain is called. Can anybody tell me a method to solve this issue?
You can create the target process suspended and use CreateRemoteThread() for injection, but mind the following limitations:
You should copy the thread main routine for the remote thread to the address space of the target process.
This code cannot contain any external references (e.g. CRTL or direct WinApi calls). I would usually limit this code to loading of the DLL and either executing function from it, or relying on the DllMain to do the job you need. In order to call LoadLibrary and GetProcAddress methods, I obtain their addresses and copy structure containing this information to the target process and pass the address of the remote structure as an argument for the thread main routine in CreateRemoteThread(). You can use VirtualAllocEx() to allocate memory in the remote process.
Remote thread in this situation will be executed before main thread, including process and some Win32/64 initialization. Therefore, not every Win32 API is safe to call in this condition.
If the target process is spawned by someone else, you have to intercept its creation before it is initialized. There are some ways to do that, all of them are undocumented and therefore not future proof.
The DLL are loaded sequentially in the same order as the imports entries in the PE header. Most PE editors will let you reorder the imports. You should also note that if another DLL X has dependencies on the security DLL, then it will be loaded at the same time as DLL X. Also, if security DLL is using static loading, hooking by modifying the import tables at runtime should still be effective even if your DLL is loaded later, though you will miss the calls done in the meantime (but there shouldn't be any).

instancing com object allowed in dllmain() / DLL_PROCESS_ATTACH?

Loading DLLs in in DLLMAIN() / DLL_PROCESS_ATTACH may cause trouble. But may COM Objects be instanced using e.q. CoInitialize() / CoCreateInstance()?
EDIT: The question is:
Could creating COM instances cause similar errors like loading DLLs in this circumstances?
Loading DLLs an creating COM instances seem to me similar in a way.
I'm not sure where you got that quote from, but it doesn't sound right.
You should never put any code of any significance into DllMain. Especially code that invokes LoadLibrary. Many Windows APIs will call LoadLibrary under the hood, so it's best to avoid doing any complex initialization here. Use a global C++ object (for it's constructor) or better yet, export a function for initialization.
CoCreateInstance for in-proc components ultimately will call LoadLibrary or one of its variants. It would not be wise to call this function in DllMain either.

Call DLL function after loading the dll

Is there a way to run a function from DLL after it loads? So it behaves exactly like main() function. I load the dll to my application, and after loading the dll itself without any calls from application it's loaded to it executes?
Just like DllMain function, but it works when I inject the dll into an application. I want it to work the same, but when I load it via LoadLibrary.
DllMain will be called in response to a LoadLibrary, but you are limited to what you can do within it reliably. It won't react well to inter-thread communication, as detailed in the MSDN DllMain documentation. Best to put such code in an Init function. In my experience the more you heap in DllMain the more problems you'll have; do as little as possible.
If you really can't use an Init function then try creating a thread in DllMain (attach) and call your function from there.

Difference between WinMain,main and DllMain in C++

What is the difference between the three functions and when to use them??
main() means your program is a console application.
WinMain() means the program is a GUI application -- that is, it displays windows and dialog boxes instead of showing console.
DllMain() means the program is a DLL. A DLL cannot be run directly but is used by the above two kinds of applications.
Therefore:
Use WinMain when you are writing a program that is going to display windows etc.
Use DLLMain when you write a DLL.
Use main in all other cases.
WinMain is used for an application (ending .exe) to indicate the process is starting. It will provide command line arguments for the process and serves as the user code entry point for a process. WinMain (or a different version of main) is also a required function. The OS needs a function to call in order to start a process running.
DllMain is used for a DLL to signify a lot of different scenarios. Most notably, it will be called when
The DLL is loaded into the process: DLL_PROCESS_ATTACH
The DLL is unloaded from the process: DLL_PROCESS_DETACH
A thread is started in the process: DLL_THREAD_ATTACH
A thread is ended in the process: DLL_THREAD_DETACH
DllMain is an optional construct and has a lot of implicit contracts associated with it. For instance, you should not be calling code that will force another DLL to load. In general it's fairly difficult function to get right and should be avoided unless you have a very specific need for it.
[Addendum to your question]
Also don't forget the DllEntryPoint:
When loading time is involved the entry point is DllMain.
(Ex. COM in-process server DLL).
When running time is involved the entry point is DllEntryPoint.
(Ex. LoadLibrary get called).