我有简单的 dll 代码:
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
if(ul_reason_for_call == DLL_PROCESS_ATTACH)
{
MessageBox(0, L"Hello!", L"Hello!", 0);
}
return TRUE;
}
以及用于将 dll 注入另一个进程的 python 代码:
import ctypes
PAGE_READWRITE = 0x04
PROCESS_ALL_ACCESS = (0x000F0000 | 0x00100000 | 0xFFF)
VIRTUAL_MEM = (0x1000 | 0x2000)
def InjectDLL(DLLPath, PID):
kernel = ctypes.windll.kernel32
dllLen = len(DLLPath)
hProcs = ctypes.windll.kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, PID)
if not hProcs:
print 'OpenProcess failed.'
return None
argAddy = ctypes.windll.kernel32.VirtualAllocEx(hProcs, 0, dllLen, VIRTUAL_MEM, PAGE_READWRITE)
if not argAddy:
print 'VirtualAllocEx failed.'
return None
wrote = ctypes.c_int(0)
kernel.WriteProcessMemory(hProcs, argAddy, DLLPath, dllLen, ctypes.byref(wrote))
hKernel = kernel.GetModuleHandleA("kernel32.dll")
hLib = kernel.GetProcAddress(hKernel, "LoadLibraryA")
t_Id = ctypes.c_ulong(0)
kernel.CreateRemoteThread(hProcs, None, 0, hLib, argAddy, 0, ctypes.byref(t_Id))
return t_Id
result = InjectDLL("injdll.dll", 564)
print result
注入适用于某些进程。例如它适用于 gvim。我可以看到消息框。但是我在 C# 中创建了简单的应用程序。在尝试将我的 dll 注入此应用程序之后,什么也没有发生。
Python 注入器不会使用OpenProcess
orCirtualAllocEx
和 return报告任何错误c_ulong(3968L)
。那为什么我看不到消息框?
编辑:
我的操作系统:Windows XP Professional SP3 32 位。
编辑2:
我用 C 代码做了同样的事情,得到了同样的结果。注入例如适用于 gvim。但不适用于我在 c# 中的过程。我确实用调试器检查过,看起来 DllMain 函数没有执行。
DWORD pid;
cout << "PID: ";
cin >> pid;
HANDLE hproc = OpenProcess(PROCESS_ALL_ACCESS,0,pid);
LPVOID adr =
VirtualAllocEx (
hproc,
(LPVOID)0,
(SIZE_T)0x1000,
MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE
);
WriteProcessMemory (hproc, adr, "injdll.dll", 256, NULL);
HANDLE hthread = CreateRemoteThread
(hproc,
NULL,
0,
(LPTHREAD_START_ROUTINE)
GetProcAddress(GetModuleHandle(L"kernel32"),"LoadLibraryA"),
adr,
0,
NULL);
CloseHandle(hthread);
CloseHandle(hproc);
return 0;