所以我正在尝试将 dll 注入到进程中,到目前为止,我已经设法将 dll 注入到进程中,但我无法让任何代码在注入的 dll 的 DllMain 中运行,当 DllMain 看起来像下面的代码时,它似乎在目标应用程序运行时工作并且进程资源管理器显示 dll 已加载。
BOOL WINAPI DllMain(HANDLE hDllHandle, DWORD dwReason, LPVOID lpreserved)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
break;
case DLL_PROCESS_DETACH:
break;
};
return TRUE;
}
但是,当我在DLL_PROCESS_ATTACH下添加任何代码时,它会导致注入超时。这是我一直在尝试加载的内容:
extern "C" {
BOOL WINAPI DllMain(HANDLE hDllHandle, DWORD dwReason, LPVOID lpreserved)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
MessageBox(0, "Hello, world!", "Hello!", 0);
break;
case DLL_PROCESS_DETACH:
break;
};
return TRUE;
}
}
以下是我注入 dll 的方式:
bool InjectDLL(PROCESS_INFORMATION* pInfo, const char* dllPath) {
bool result = false;
HANDLE nmsProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pInfo->dwProcessId);
if (nmsProcess) {
LPVOID baseAddress = VirtualAllocEx(nmsProcess, NULL, strlen(dllPath) + 1, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (baseAddress) {
LPVOID loadLibraryAddress = (LPVOID)GetProcAddress(LoadLibraryA("kernel32.dll"), "LoadLibraryA");
WriteProcessMemory(nmsProcess, baseAddress, dllPath, strlen(dllPath) + 1, NULL);
HANDLE thread = CreateRemoteThread(nmsProcess, NULL, 0, (LPTHREAD_START_ROUTINE)loadLibraryAddress, baseAddress, 0, 0);
if (thread != NULL) {
switch (WaitForSingleObject(thread, 5000)) {
case WAIT_OBJECT_0:
cout << "Injected" << endl;
result = TRUE;
break;
case WAIT_ABANDONED:
cout << "Abandoned" << endl;
break;
case WAIT_TIMEOUT:
cout << "Timed out" << endl;
break;
case WAIT_FAILED:
cout << "Failed"<< endl;
break;
}
}
else {
cout << "Error: n" << GetLastError() << endl;
}
CloseHandle(thread);
}
else {
cout << "Error: n" << GetLastError() << endl;
}
VirtualFreeEx(nmsProcess, baseAddress, 0, MEM_RELEASE);
CloseHandle(nmsProcess);
}
return result;
}
我对 Dll 注射相当陌生,所以我可能在某处的注射中犯了一个错误,任何帮助将不胜感激。
编辑:
我还尝试在另一个函数中调用 MessageBox,但结果相同:
extern "C" {
void Init(void) {
MessageBox(0, "Hello, world!", "Hello!", 0);
}
BOOL WINAPI DllMain(HANDLE hDllHandle, DWORD dwReason, LPVOID lpreserved)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
Init();
break;
case DLL_PROCESS_DETACH:
break;
};
return TRUE;
}
}
事实证明,解决方案(感谢Hans Passant和Christian.K(是在一个新线程中调用该函数,如下所示:
extern "C" {
void Init() {
MessageBox(0, "Hello, world!", "Hello!", 0);
}
BOOL WINAPI DllMain(HANDLE hDllHandle, DWORD dwReason, LPVOID lpreserved)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Init, NULL, 0, NULL);
break;
case DLL_PROCESS_DETACH:
break;
};
return TRUE;
}
}