nektra / Deviare-InProc

Deviare In Process Instrumentation Engine
http://nektra.com/products/deviare-api-hook-windows/deviare-in-process/
Other
330 stars 84 forks source link

Is there anyway to createprocess from a dotnet exe and suspend it at its main method? #24

Closed Meigyoku-Thmn closed 5 years ago

Meigyoku-Thmn commented 5 years ago

Suppose the target exe looks like this:

namespace Target {
   class Target {
      static void Main(string[] args) {
            while (true) {
               Console.WriteLine("NOT HOOKED");
               Thread.Sleep(1000);
            }
      }
   }
}

What I want to do is to hook the Console.WriteLine method right before the target has any chance to run "Main" method, so I tried to open process with HookLib.ProcessCreationFlags.CREATE_SUSPENDED flag:

HookLib.ProcessInfo pi = cHook.CreateProcess(targetPath, "", null, null, false, HookLib.ProcessCreationFlags.CREATE_SUSPENDED, null, null, si);

Then I injected my C++ DLL which would load my C# DLL:

cHook.InjectDll(pi.procId, injecteePath, "ImplantDotNetAssembly", 0);
HRESULT __stdcall ImplantDotNetAssembly() {
   //...
   CLRCreateInstance(CLSID_CLRMetaHost, IID_PPV_ARGS(&metaHost));
   metaHost->GetRuntime(L"v4.0.30319", IID_PPV_ARGS(&runtimeInfo));
   runtimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_PPV_ARGS(&runtimeHost));
   runtimeHost->Start();
   runtimeHost->ExecuteInDefaultAppDomain(
      L"Managed DLL.dll", // my C# DLL
      L"MyCode.Program",
      L"AddHandler",
      L"No need",
      &returnValue);
}

In my C# DLL, the code looks like this:

namespace MyCode {
   public class Program {
      public static int AddHandler(string arg) {
         HookLib cHook;
         cHook = new HookLib();
         Console.WriteLine("Hook WriteLine");
         var o = cHook.Hook(typeof(Console), "WriteLine", new Type[] { typeof(string) }, typeof(Handler), "Hooked_WriteLine", new Type[] { typeof(string) });
         return 1;
      }
      public static void Hooked_WriteLine(string value) {
         Console.WriteLine("HOOKED!");
      }
   }
}

But everytime I run it, when I resume the target process, it just crashes with an error: "CLR error: 80004005. The program will now terminate."

So is there a way to suspend it at its Main method?

bo3b commented 5 years ago

That's actually the role for the Deviare2 code instead. It has direct .net access, and will let you CreateProcess with a suspended mode. In-Proc is compatible with Deviare2, but for .net Deviare2 is a lot easier to use.

Edit: BTW, that error is just a generic error for .net runtimes not working correctly, you might try uninstalling and reinstalling.

Meigyoku-Thmn commented 5 years ago

Thanks for replying! So I will try out Deviare2 instead!