-2

I need to inject a dll into the main thread of a process (otherwise my process will crash) How would I go about doing this? My dll is in C++ obviously, my injection method though uses C# and CreateRemoteThread. I've tried using std::thread(func) but that didn't work (of course it probably wouldn't since it most likely creates a new thread) I don't know if this is a problem for my DLL or my injector, so all help and attempts to help is appreciated.

  • Talking about injecting a DLL into a thread sounds like a category error. What DLLs are loaded is a property of a process, not a thread. – David Schwartz May 20 '18 at 22:38
  • This I may actually been too unspecific but what I meant was, how would I execute code in the main thread after injecting a dll? – Krippled Boise May 20 '18 at 22:39

2 Answers2

0

You can create the target process suspended and use CreateRemoteThread() for injection, but mind the following limitations:

  1. You should copy the thread main routine for the remote thread to the address space of the target process.
  2. 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,
  3. 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.

You can read more here: http://blogs.microsoft.co.il/pavely/2017/03/14/injecting-a-dll-without-a-remote-thread/

ssbssa
  • 1,261
  • 1
  • 13
  • 21
EliiTryToLearn
  • 125
  • 1
  • 11
0

Your DllMain will run in the context of every thread... figure out which is the main thread.

Since you can't do much while the loader lock is held, create a callback with thread affinity (for example using SetTimer) and do all the work from that callback.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • Could you elaborate a little bit more? Sorry, I'm just not that advanced to C++ or threading in general. (Specifically the second part, I understand the first part obviously) – Krippled Boise May 22 '18 at 22:57