C++ : Dll injection. Why CreateRemoteThread() fail on Notepad? - c++

I'm pretty new to DLL injection, doing this by curiosty and because I want to create an overlay in a game, without modifying his source code.
But for now, I'm stuck with a basic DLL injection : the one using CreateRemoteThread().
I followed this tutorial (in french, be carefull):
http://xevia.webege.com/old/atoray/2010/06180.php
What I have done :
Injection works fine on a basic program Target.exe (see Xevia's link)
I can see DLL loaded by a process with EnumProcessModules()
After the injection in Target.exe, I can see that my "Hook.dll" has been added.
[edit] Checked the exe version : both notepad and my injector are 32-bits
But when I inject the dll in other processes, it doesn't seems to work, even if CreateRemoteThread() does not return NULL.
So I've checked many posts, including this one: How do I prevent DLL injection
And this one : C++ - CreateRemoteThread DLL Injection [Windows 7] (tried the absolute path, without success)
And many others, without being able to really point what was wrong. So I invoke SO-gods.
1) Could it be an access-rights issue ?
2) Could it be my method of injection, too classical ? Which one should I try ?
3) [Topic question] Why my dll isn't injected in Notepad with CreateRemoteThread?
Thanks for your time.
[open to any grammar/formulation edit]

It works!
What I needed to change :
Build in x86 in order to match with target app
Use an absolute path
I did both but forgot to change my absolute path when switching between x86/x64...
Thanks to Adrian Roman, who put me in the right way.

Related

Load native C++ .dll from RAM in debugger friendly manner

Question concerns only Windows for now - other OS's are not so relevant right now.
Just by quick googling - it's possible to load native .dll from RAM, there are for example following libraries:
https://www.joachim-bauch.de/tutorials/loading-a-dll-from-memory/
=>
https://github.com/fancycode/MemoryModule
https://forum.nim-lang.org/t/7943
But all of them requires:
in-depth knowledge of PE file format
mostly those approaches are not debugger friendly.
What I have checked - windows's LoadLibraryA / LoadLibraryW are directed to ntdll.dll / LdrLoadDll - and best picture of how things works can be found from here: https://github.com/hlldz/RefleXXion
And even thus I don't have windows source code - I've checked same functionality from Wine:
LdrLoadDll: https://source.winehq.org/source/dlls/ntdll/loader.c#3169
load_dll: https://source.winehq.org/source/dlls/ntdll/loader.c#3083
load_native_dll:
https://source.winehq.org/source/dlls/ntdll/loader.c#2564
NtMapViewOfSection: https://source.winehq.org/source/dlls/ntdll/unix/virtual.c#4469
find_dll_file: https://source.winehq.org/source/dlls/ntdll/loader.c#3021
open_dll_file: https://source.winehq.org/source/dlls/ntdll/loader.c#2467
Suspect loading dll happens via following function calls:
NtOpenFile, NtQueryAttributesFile, NtCreateSection/NtOpenSection, NtMapViewOfSection (*)
(More information could be found in
https://github.com/Hagrid29/PELoader
https://gist.github.com/bats3c/59932dfa1f5bb23dd36071119b91af0f
https://www.octawian.ro/fisiere/situri/asor/build/html/_downloads/122f95f9a032396603a837c53b125bb8/Russinovich_M_WinInternals_part1_7th_ed.pdf
)
I was also thinking if I could just override NtOpenFile and just redirect file open (in
https://github.com/SegaraRai/PathRedirector manner)
to different path - but main question what is the alternative location where to store file?
I was thinking if NtOpenFile can open even device, then maybe just replace file
with some sort of named pipe (https://learn.microsoft.com/en-us/windows/win32/ipc/named-pipe-client) - but then in maps on how well this will work with NtMapViewOfSection.
Since I was not able to find any working example of such hook or operation (E.g. LoadLibary("\\.\pipe\mynamedpipe_as_dll")) - there is always a risk that such combination is not simply supported.
Is it possible to load native .dll purely from RAM:
Without using file system (not to store .dll e.g. in temporary folder)
Without involving custom drivers (like Dokan) ?
So loaded .dll would be still debugger friendly ?
Not tightly bound to PE file format structures (or use PE structures as less as possible)
If you miss bit more information, check also my own experiments with native dll loading (maybe can give some hints on solving the issue):
https://github.com/tapika/test_native_dll_loading
https://github.com/tapika/test_native_dll_loading/discussions/2
Distinguish between debug and release use cases. In debug, save the DLL in a temp file and load with LoadLibrary, which will enable debugging. In release, run from memory with no capability for debugging.
Here's another idea, from considering the linked Guthub issue. If the purpose is to let the users provide their own compression/decompression logic while building a ReadyToRun executable, let them provide that as a static library (object) as opposed to a DLL. The larger project is already about packaging stuff into a single executable, might do some linking while at it.
Yet another idea would be to let the users provide the codec in some kind of interpreted language and optionally plug in the interpreter that supports debugging. Windows comes with a built-in JavaScript interpreter, look up Active Scripting, and debugging those is a free bonus. The performance probably won't be on par with a native code implementation, though.
I think you could probably do something similar with Frida. Hook the functions LoadLibraryA / LoadLibraryW and reimplement them in Frida. but I don't believe this is something that would be stable for production.
For some reference
By analyzing existing approaches (like PE Loader https://github.com/Hagrid29/PELoader) and using minhook library - I've managed to load .dll from RAM.
I've created git repository with example code on github:
https://github.com/tapika/dllloader
Could you create a ramdisk to put your DLL there? What exactly is the use-case for this? There are a couple ways to spin up a file in RAM, C#'s MemoryMappedFile for example. I'm not sure if this would be debugger friendly.

How would I go about invoking the ui from within a DLL?

This may be too broad a question, but I have a DLL that contains a UI. It is currently invoked by an EXE. What steps would I do to try and invoke the UI within the DLL? Or put another way, how would I go about teasing out the code that would invoke the UI as it happens in the EXE?
Looks like you have access to source for both dll and executable that uses it. so what you are doing is writing a host for that dll from scratch.
Create a MFC application from VS project templates (make it the same kind as main executable, dialog, single document, multiple document, etc).
Look at what function dll exports, also look at its headers and best of all -- documentation.
Search source code of main exe and find the places the dll functions are called.
Figure out what is being done and why.
Narrow down scenarios you want to reproduce (initialize dll, show basic UI and tear down)
Start reproducing that code in your example app.
Copy the dll call, see what parameters it takes, see how those are initialized, etc.
Fix errors as they come up.

COM Codebase Location - How to pick which version to use?

I have needed to modify code in a C# DLL and use it within a C++ application. I am not savvy at all in C++, so if something isn't clear let me know.
I've registered the C# assembly using:
regasm file.dll /tlb:file.dll /codebase
However, when I try to use this in the c++ application:
CLSID clsid;
CLSIDFromProgID(L"MyApp.MyClass", &clsid);
HRESULT hr = CoCreateInstance(clsid,NULL, CLSCTX_INPROC_SERVER ,IID_MyClass, reinterpret_cast<void**>(&myclass));
hr returns with 0x8013151a: access to this member is denied
I've noticed that in registry, I see multiple versions of the C# dll (with Codebase pointing to different dll locations).
I think the problem is because it's not using the correct dll. (I could be completely wrong).
My question is this, how do you know which version of the dll it's trying to load?
Thanks in advance.
Pretty unlikely that this is a DLL Hell problem. You can double-check by using the debugger's Debug + Windows + Modules window, it shows you the path of the DLL. Keep your registry clean by letting MSBuild register the component, Project + Properties, Build tab, "Register for COM interop" option. VS must run elevated.
This is a MethodAccessException, always a coding bug. Psychic debugging required without seeing your code but the simplest explanation is that your C# class' default constructor is not public.

CreateInstance Returns "The specified module could not be found."

I've been trying to get a program that worked on Windows 2000 to work on Windows 2003. Everything I've had to do so far to get the program to work on Windows 2003 has had to do with incorrect configuration. Right now, this piece of code:
chr = pAdapterEnvPtr.CreateInstance(__uuidof(PFADAPTERMNGLib::PFAdapterEnv));
is returning:
0x8007007E
or in other words:
The specified module could not be found.
I have two other programs and another .dll and I can successfully create instances of those classes. But this seems to fail.
I have used Procmon to try to figure out what the program can't find, but Procmon did not display anything that could indicate that the program could not find something.
In OleView, if I try to create an instance of the class, I see the following image:
If you look on the left side of the image, trying to create an instance of PFComgMng gives me the same error. (PFAdapterEnv and PFCompMng use the same process, PFAdapterMng.exe.) However, PFMQMonitor, PFSend, and PFTrace all work correctly. (Which use PFMQListen.exe, PFSend.dll, and PFTraceService.exe.)
Another thing that I wanted to note is that the following piece of code:
hr = pPFCompMng.CreateInstance(__uuidof(PFADAPTERMNGLib::PFCompMng));
works perfectly fine when it gets called earlier from PFAdapterMng.exe. So it seems like PFAdapterMng.exe can successfully find the module and create the instance, but any other processes that try to create either of the instances of the classes within PFAdapterMng.exe can't find the module, resulting in this error.
Since Procmon isn't helping with this specific case, does anyone know what I could do to figure out what's keeping other processes from finding the module?
UPDATE:
I can't run Dependency Walker with profiling because PFAdapterMng.exe and PFTraceService.exe must be run as services. I tried to run Dependency Walker while profiling OleView and tried to create instances of PFAdapterEnv and PFCompMng to try to find out why I was getting the Module not found message box. Unfortunately, Dependency Walker didn't show that anything was missing.
UPDATE2:
Maybe I missed something in the Procmon log, so I created a new log by capturing events right before I stepped over the call to CreateInstance and right after the call. Maybe someone else could take a look and tell me if i missed it? I simply can't find any indications that PFMQListen.exe could not find something..
Here's a link to a zipped folder with a Procmon file, a .csv file, and a .xml file.
http://www.mediafire.com/?07jq8zj7emmpsvd
UPDATE3:
So, I managed to get Dependency Walker running under Profile mode to create an instance of PFAdapterEnv. Dependency Walker did not find any missing .dll's.
So, Procmon doesn't show anything, and neither does Dependency Walker. I was stepping through the code at the assembly level with ollydbg, and I noticed that the error was created in the function NdrClientCall2. I don't know if this means anything.
Any ideas as to what else I can try? Do people need more information to help me solve this problem? If so, please ask.
UPDATE4:
I tried using /RegServer to register the applications, and it worked. I tried using /RegServer previously, where I just unregistered everything using /UnregServer. This time, I also deleted the component from Component Services which I needed to have because I wanted to run PFAdapterMng under another identity.
So, it seems like everything works when running on /RegServer and double-clicking the applications. However, I would like everything to run under a different configuration.
How do I configure everything to get the applications to work as follows:
PFAdapterMng.exe - Register as /Service and run under another identity through services.msc
PFTraceServer.exe - Register as /Service and run under another identity through services.msc
PFMQListen.exe - Register as /RegServer which will be started by PFAdapterMng
PFMQSend.dll - Registered with Regsvr32 and loaded by PFAdapterMng
Thanks,
Krzys
My guess is that it is related to the search path of some DLL dependencies of the executable.
You can try the "Dependency Walker" on every module to see if all DLL are available: http://www.dependencywalker.com/
And update the search PATH if needed.

How to test if a DLL can be loaded without an error

I have a native C++ application (no fancy .Net stuff just C++). However it uses some optional .Net assemblies through mixed mode wrapper dll files. These dlls are loaded using delay load. Thing with mixed mode wrappers is they need to be fully trusted in order to load. So when the application try to use the dll if it is not there or if it is not trusted entire thing crashes with a nasty error message.
But i my case as long as my main application is concerned it can live without these dll files. So I need a way to check if these dlls can be loaded (files are there and trusted). In order to do this I tried to put a dummy call to one of the dll functions within a try catch block hoping the catch the exception but it still crash with 'module not found' exception.
we also tried replacing unhanded exception filter with a custom one but still no luck.
we also tried to use LoadLibrary method to first load the dll and check the return value.
But that function load the Dll even if it is not trusted but crash when we try to do a method call.
I dont think that this is an unsolved problem. How hard can it be to check if a dll can be used without actually trying to load it and end up crashing? Any ideas?
If all methods fail, try running a separate process (i.e. simple command-line app) that will try to load the library, then analyze its return code.
But, did you try structured exceptions handling - i.e. __try/__catch, not try/catch? See here.
I had the idea of using a separate process to test the dll first and see if it runs in to any errors. I don't want to use that in my app cos it was not really a clan solution. but the __try, __except approach worked with delay load dll calls. I didn't even have to use LoadLibrary. Thanks.