LoadLibrary and SetWindowsHookEx inquiry - c++

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).

Related

Unloading DLL while it's code is being executed (From a non-owned thread)

I have a dynamic link library that will hook certain functions in a host process, redirecting them to my the DLL's detour functions. I want to be able to unload this library on a cue that will be given through a call on one of these hooked functions by the host process. Would it be safe to simply unload the DLL while it's code is being executed?
I am aware that FreeLibraryAndExitThread (as opposed to FreeLibrary) exists for unloading a library from within a owned thread, halting the execution immediately. However, I am not able to terminate the thread on which the DLL's code will be running on at the time of the unloading.
I have thought of a solution in case it isn't safe: To spawn a thread that will properly unhook everything and exit using FreeLibraryAndExitThread afterwards, but I'm not sure that is needed or even the best solution if it is.

Is DLL function called from multithreaded application run on same thread?

I have multithreaded application. Now, I have written one function in Windows DLL.
I am calling this DLL function from thread function (called by multiple threads) which is in my application.
So, my question is, does this DLL function also executes on same calling thread?
(And no need to handle multithreading separately in DLL)
Yes, the DLL function will execute on the same thread as the caller. There is no need to handle multithreading separately in the DLL.

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).

is it possible to inject multiple Dlls with MS detours?

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.

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).