Window API Hook

파이썬 ctypes 모듈을 이용한 윈도우 API 후킹 코드입니다.

Managed 코드에 대해서는 모듈을 기준으로하는 함수 오프셋을 구해서 같은 방식으로 사용할 수 있습니다.

from ctypes import *
from capstone import *
from subprocess import Popen
from struct import pack

cnt = 0
dummy = c_int(0)
pid = Popen([r"C:\Program Files\Internet Explorer\iexplore.exe"]).pid
kernel32 = windll.kernel32
user32 = windll.user32
process = kernel32.OpenProcess(0x1F0FFF, False, pid)
target = kernel32.GetProcAddress(user32._handle, "RegisterClassW") # hook target
backup = create_string_buffer(20)
code = kernel32.VirtualAllocEx(process, 0, 0x1000, 0x3000, 0x40)
while dummy.value != 20:kernel32.ReadProcessMemory(process, target, backup, 20, byref(dummy))
md = Cs(CS_ARCH_X86, CS_MODE_32)
for i in md.disasm(backup.raw, 0):
	cnt += i.size
	if cnt > 6:break
##### write here what do you want
asm = lambda s:s.decode("hex")
record = kernel32.VirtualAllocEx(process, 0, 0x1000, 0x3000, 0x40)
shellcode = asm("90909090")
print "%08x" % record
#################################
kernel32.WriteProcessMemory(process, code, "\x60{}\x61{}\x68{}\xc3".format(shellcode, backup.raw[0:cnt], pack("<L", target+cnt)), 8+len(shellcode)+cnt, byref(dummy))
kernel32.WriteProcessMemory(process, target, "\x68{}\xc3".format(pack("<L", code)), 6, byref(dummy))
#Popen(["windbg", "-p", str(pid)])
kernel32.CloseHandle(process)

Leave a Reply

Your email address will not be published. Required fields are marked *