python内存注入代码,python语言编写的DLL注入工具

一、流程

1、第一步,获取要注入进程快照;

2、第二步,在快照中比对进程名,得到进程PID;

3、第三步,用pid去打开进程获取到句柄;

4、第四步,在要注入的进程内申请一块内存;

5、第五步,把要注入的dll路径写入进程内存中;

6、第六步,得到“LoadLibraryA”函数的句柄

7、第七步,通过远程线程运行注入的dll,注入成功

二、代码

#-*- coding: utf-8 -*-

from ctypes import *

import psutil

import win32api

def injectDll(string=None):

PAGE_READWRITE = 0x04

PROCESS_ALL_ACCESS = (0x000F0000|0x00100000|0xFFF)

VIRTUAL_MEM = (0x1000 | 0x2000)

dll_path = 'd://softdp//pyworkspace//wechat_demo//WechatDB.dll'.encode('ascii','ignore')

dll_len = len(dll_path)

print(dll_len)

kernel32 = windll.kernel32

#第一步获取整个系统的进程快照

pids = psutil.pids()

#第二步在快照中去比对进程名

for pid in pids:

p= psutil.Process(pid)

if p.name()==string:

break

print('pid:',pid)

#第三步用找到的pid去打开进程获取到句柄

h_process=kernel32.OpenProcess(PROCESS_ALL_ACCESS,False,int(pid))

if not h_process:

print('could not acquire a handle to pid')

arg_adress=kernel32.VirtualAllocEx(h_process,None,dll_len,VIRTUAL_MEM,PAGE_READWRITE )

written=c_int(0)

whhh=kernel32.WriteProcessMemory(h_process,arg_adress,dll_path,dll_len,byref(written))

print('arg_address:%x'%arg_adress,whhh)

h_kernel32=win32api.GetModuleHandle('kernel32.dll')

h_loadlib =win32api.GetProcAddress(h_kernel32, 'LoadLibraryA')

print('%x'%h_kernel32,'%x'%h_loadlib)

thread_id=c_ulong(0)

handle= kernel32.CreateRemoteThread(h_process, None,0,h_loadlib,arg_adress, 0,byref(thread_id) )

print(handle)

return h_kernel32

三、注意事项:

1、dll_path格式,且要转成ascii。否则格式是Unicode的,且dll_len长度不够。未转ascii需要注意其他处理;

2、kernel32.GetModuleHandle()是错的,需要为kernel32.GetModuleHandleW()。但是kernel32.GetProcAddress执行无法获得句柄;

3、 h_process = win32api.OpenProcess(PROCESS_ALL_ACCESS, False, int(pid)) h_process=int(h_process) print('h_process:', h_process),句柄传入OpenProcess函数中,返回为0,说明获得句柄失败,我也不知道为啥。

4、部分思路参考《Python灰帽子》

5、转载请注明出处。