DLL Injection Part 6 — Injecting managed code into specific App Domain

This is the sixth part of the DLL Injection series. For your convenience you can find other parts in the table of contents in Part 1 – Registry

In Part 4 we saw how to inject managed DLL and execute some code in default App Domain. Today we will inject some code into different app domains. Actually, this is not tied to DLL injection (because we might want to do this in our application as well).

Listing App Domains

If you check reflection mechanism you will see that it is possible to list all type members (fields, methods, properties), all assembly types, all assemblies of app domain, but there is no simple way to list of app domains of a process. So how do we do it?

We know that .NET exe file can be executed as an ordinary Windows application. This is because it is in fact ordinary application. What it does at start is initializing .NET platform host and loading actual .NET code. We can use this host to list domains. This code does it (.NET 4, it requires COM reference to mscoree.tlb):

If we don’t want to reference mscoree.tlb, we can use the following code:

And this allows us to list all domains.

Injecting code

In order to execute code in different app domain, we need to create object there. The simplest way is to do it like this:

and now in constructor of Class1 we can do anything we want because we are already in target app domain.