我使用以下脚本来注入Python 2.7并在其注入的进程的内存中找到一个函数。
import os
import ctypes
from ctypes import *
from ctypes import wintypes
def InjectDLL(pid, filename, procname):
PAGE_READWRITE = 0x04 #Set token values
PROCESS_ALL_ACCESS = ( 0x00F0000 | 0x00100000 | 0xFFF )
VIRTUAL_MEM = ( 0x1000 | 0x2000 )
dll_len = len(filename)
h_process = kernel32.OpenProcess( PROCESS_ALL_ACCESS, False, int(pid) )
arg_address = kernel32.VirtualAllocEx(h_process, 0, dll_len, VIRTUAL_MEM, PAGE_READWRITE)
written = c_int(0)
kernel32.WriteProcessMemory(h_process, arg_address, filename, dll_len, byref(written))
h_kernel32 = kernel32.GetModuleHandleA("kernel32.dll")
h_loadlib = kernel32.GetProcAddress(h_kernel32, "LoadLibraryA")
thread_id = c_ulong(0)
kernel32.CreateRemoteThread(h_process, None, 0, h_loadlib, arg_address, 0, byref(thread_id))
address = GetRemoteProcAddress(pid, filename, procname)
kernel32.CreateRemoteThread(h_process, None, 256, address, 0, 0, byref(thread_id))
def GetRemoteModuleHandle(pid, modname):
modname = modname.upper()
if '.' not in modname:
modname += '.DLL'
while True:
try:
hProcessSnap = kernel32.CreateToolhelp32Snapshot(
TH32CS_SNAPMODULE, pid)
break
except OSError as e:
if e.winerror != ERROR_BAD_LENGTH:
raise
try:
modentry = MODULEENTRY32W()
kernel32.Module32FirstW(hProcessSnap,
ctypes.byref(modentry))
while True:
if modentry.szModule.upper() == modname:
return modentry.hModule
try:
kernel32.Module32NextW(hProcessSnap,
ctypes.byref(modentry))
except OSError as e:
if e.winerror == ERROR_NO_MORE_FILES:
break
raise
raise ctypes.WinError(ERROR_MOD_NOT_FOUND)
finally:
kernel32.CloseHandle(hProcessSnap)
def GetRemoteProcAddress(pid, filename, procname):
procname = procname.encode('utf-8')
global hLocal
hLocal = kernel32.LoadLibraryExW(filename, None,
DONT_RESOLVE_DLL_REFERENCES)
try:
procaddr = kernel32.GetProcAddress(hLocal, procname)
finally:
kernel32.FreeLibrary(hLocal)
modname = os.path.basename(filename)
hRemote = GetRemoteModuleHandle(pid, modname)
return hRemote - hLocal + procaddr
InjectDLL(13052, 'python27.dll', 'Py_InitializeEx')
这不是完整的脚本,这太长了。所需的一切都在这里,其余的都是错误处理程序和ctype结构。
我的问题是,即使它找到了完美的地址(我已经通过进程内存编辑器验证),它也无法在该地址上执行远程线程,否则进程将立即关闭并崩溃。
注射工作正常,它只是执行崩溃它的所述功能。任何人都可以在我的脚本中看到问题吗?感谢。
注意:我已经验证python dll和正在运行的可执行文件都是32位。
整个问题在于这段代码:
kernel32.CreateRemoteThread(h_process, None, 256, address, 0, 0, byref(thread_id))
如果这被注释掉,脚本运行正常(即使函数没有运行)。但是,运行时会导致崩溃。