gpt4 book ai didi

c++ - 在注入(inject)的 Dll 的 DllMain 中运行代码会导致注入(inject)超时

转载 作者:行者123 更新时间:2023-11-30 05:00:58 25 4
gpt4 key购买 nike

所以我试图将一个 dll 注入(inject)到一个进程中,到目前为止我已经设法将 dll 注入(inject)到进程中,但是我无法让任何代码在注入(inject)的 dll 的 DllMain 中运行,当DllMain 看起来像下面的代码,它似乎在目标应用程序运行时工作,并且 Process Explorer 显示 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 下添加任何代码时,它会导致注入(inject)超时。这是我一直在尝试加载的内容:

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;
}
}

下面是我注入(inject) 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 注入(inject)相当陌生,所以我可能在某个地方的注入(inject)中犯了错误,将不胜感激任何帮助。

编辑:

我也试过在另一个函数中调用 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;
}
}

关于c++ - 在注入(inject)的 Dll 的 DllMain 中运行代码会导致注入(inject)超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50488079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com