I'm working on an application that injects a dll when a process starts (Suspend --> Inject --> Resume)
The very first call in DllMain with DLL_PROCESS_ATTACH (in the dll I injected) is a call to MessageBox() (just for debugging purpose).
However, this call to MessageBox() sometimes pops an error and crashes the injected process.
Runtime Error!Program: C:\Program Files\Microsoft
Office\Office14\OUTLOOK.EXER6030- CRT not initialized
This is reproducible with Outlook and Winword for example. Though Notepad, IE, CMD, Calc and many others - print the message box and continue normally.
Printing a message box is not a must-have for me, so I just want to be able to check whether CRT has done initialization or not, so I can continue normally like this:
case DLL_PROCESS_ATTACH:
if (IsCRTInitialized())
MessageBox(...);
Please let me know if some information is missing.
Thanks!
Kernel32.dll is guaranteed to be loaded in the process address space when the entry-point function DLLMain is called. MessageBox resides in user32.dll and as per Best practices for creating DLL calling functions from user32.dll is a strict no-no.
You can either
Call OutputDebugString for any debugger tracing. This function resides in kernel32.dll and should be safe to call.
Before your application loads any other dlls, call MessageBox yourself. This will ensure that user32.dll and its dependencies are
already loaded. This way calling MessageBox in DllMain may have
a better chance of succeeding. But your mileage may vary.
The problem isn't the CRT. You're not allowed to call MessageBox or any other non-trivial function from DllMain
Related
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).
My question is really above, I will give more information on this below however:
I have a program which first takes my "false" d3d9.dll, this DLL is then loaded into the game I am reverse engineering. After the some time and the .dll is loaded, along with all the other games dependencies I want to inject my DLL which will do all the dirty work of the reverse engineering.
I think I can load this DLL into the program using LoadLibrary, however when I'm using the DLL I injected to run the main reverse engineered code. Is there a function I can use to call something from the d3d9.dll?
This is because I still need access to the d3d9 library to render things I may want to add on the screen with my injected .dll. I also don't want to just use the d3d9.dll as this will cause problems with loading times, and the point at which memory is changed.
I also don't plan on using DllMain in the DLL, this means I will also need to call a remote function from the d3d9.dll to the injected DLL in order to ensure a safe process start.
Sorry if this is a stupid question, however thanks for any answers.
Back in the old days we use to CreateRemoteThread and use LoadLibraryA as the address for lpStartAddress (This address happens to be the same in all processes). The trick was to allocate the DLL name you are injecting using VirtualAllocEx and use that as lpParameter. Effectively your thread calls LoadLibraryA with the DLL name you want to inject. When the Dll loads Dllmain gets called and you can run code in Dllmain during a time that the dll is being attached (DLL_PROCESS_ATTACH).
This link has some very good information on doing just that. However this technique relies on a Dllmain function. If you can use Dllmain then this mechanism may work. A summary of the steps from that article gives an overview:
Now, we can summarize this technique in the following steps:
Retrieve a HANDLE to the remote process (OpenProces).
Allocate memory in the remote process's address space for injected data (VirtualAllocEx).
Write a copy of the initialised INJDATA structure to the allocated memory (WriteProcessMemory).
Allocate memory in the remote process's address space for injected code.
Write a copy of ThreadFunc to the allocated memory.
Start the remote copy of ThreadFunc via CreateRemoteThread.
Wait until the remote thread terminates (WaitForSingleObject).
Retrieve the result from the remote process (ReadProcessMemory or GetExitCodeThread).
Free the memory allocated in Steps #2 and #4 (VirtualFreeEx).
Close the handles retrieved in Steps #6 and #1 (CloseHandle).
I saw your comment about too much information. Not sure I quite understand. However Dllmain has some restrictions like most Win32 API calls can't be used. There are some exceptions and one being CreateThread. Had you considered spinning off a thread to do work? If you use CreateThread in a Dllmain it effectively gets blocked until Dllmain exits. So once Dllmain returns the Thread will execute.
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.
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.
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).