3

There are plenty of answers how to inject a DLL into another process. How would I do the same thing with an C# Forms application (exe) instead of a DLL.

Basically I want it to run in the virtual address space of another process. First I allocate the Memory, then I create remote thread. Now how do i get my existing exe to run in there? Also are there any limitations to that, (could i have it running inside explorer.exe for example)?

4

1 回答 1

1

I did it quite awhile ago for my own unmanaged app (without any injection - not that it matters). Once you've got your unmanaged DLL injected into the desired app's address space, you should create a dedicated thread, initialize COM on it (with CoInitializeEx or OleInitialize), then do the following (error checks skipped for brevity):

HMODULE hmodMscoree = LoadLibrary(_T("mscoree.dll"))

HRESULT (STDAPICALLTYPE *pCorBindToRuntimeEx)(LPCWSTR pwszVersion, LPCWSTR pwszBuildFlavor, DWORD startupFlags, REFCLSID rclsid, REFIID riid, LPVOID FAR *ppv);
GET_PROC_ADDRESS(hmodMscoree, CorBindToRuntimeEx);

CComQIPtr<ICorRuntimeHost> m_host;
pCorBindToRuntimeEx(NULL, NULL, 0, CLSID_CorRuntimeHost, IID_ICorRuntimeHost, (void**)&m_host);
m_host->Start();

CComQIPtr<IUnknown> unk;
m_host->CreateDomainSetup(&unk);
CComQIPtr<mscorlib::IAppDomainSetup> domainSetup;
unk->QueryInterface(&domainSetup);
domainSetup->put_ApplicationBase(curDir);

CComBSTR appName;
ParseParam(m_commandLine, CMDLINEOPT_APPNAME, &appName);
domainSetup->put_ApplicationName(appName);

CComBSTR config;
ParseParam(m_commandLine, CMDLINEOPT_CONFIGFILE, &config);
domainSetup->put_ConfigurationFile(config);

unk.Release();
m_host->CreateDomainEx(m_managedApp, domainSetup, NULL, &unk);
CComQIPtr<mscorlib::_AppDomain> appDomain;
unk->QueryInterface(&appDomain);
appDomain->ExecuteAssembly_2(m_managedApp, &m_exitCode);

Make sure all dependency assemblies (if any) are available in the base folder (curDir in my code).

EDITED: That was done for .NET 2.0. I don't know if anything has changed since then. You could find more info on CLR hosting here.

EDITED: GET_PROC_ADDRESS does just this:

#ifdef _UNICODE
    #define FUNC_T(func) func##W
    #define GET_PROC_ADDRESS_T(mod, func) \
        ((FARPROC&)p##func = ::GetProcAddress(mod, #func "W"))
#else
    #define FUNC_T(func) func##A
    #define GET_PROC_ADDRESS_T(mod, func) \
        ((FARPROC&)p##func = ::GetProcAddress(mod, #func "A"))
#endif

You'd also need to #include fusion.h and mscoree.h (can be found In Windows SDK) and #import mscorlib.tlb (for .NET 2.0 it was C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.tlb).

于 2013-08-08T13:41:55.303 回答