我正在尝试在CreateFileW记事本进程内挂接一个 win32 函数调用 ( ),以使该函数在返回它应该执行的操作之前执行其他操作。最终,这将有助于我为我正在从事的另一个项目进行一些 RE 翻译工作,但我这样做只是作为概念证明。
我最熟悉 Python,所以我一直在尝试用这种语言完成这项任务。
有很多关于如何 RPM/WPM 的小型到大型 Python 库,但钩子/绕道不是这些项目的重点。
这是我尝试使用pymem和PythonForWindows库来完成此任务的示例:
import pymem
import sys
import os
from json import dumps
wdir = os.path.abspath('.')
log_path = os.path.join(wdir, 'out.log').replace("\\", "\\\\")
err_path = os.path.join(wdir, 'err.log').replace("\\", "\\\\")
shellcode = """
import sys
from os import chdir
from traceback import format_exc
sys.path=%s
chdir(sys.path[0])
def write_file(message):
with open("%s", "a") as f:
f.write(str(message))
try:
import windows
from windows.hooks import *
@CreateFileWCallback
def createfile_callback(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile, real_function):
try:
write_file("Trying to open {0}".format(lpFileName))
return real_function()
except:
write_file(format_exc())
peb = windows.current_process.peb.modules[0]
imp = peb.pe.imports
iat_create_file = [entry for entry in imp['kernel32.dll'] if entry.name == "CreateFileW"]
result = iat_create_file[0].set_hook(createfile_callback)
except:
write_file(format_exc())
""" % (
dumps(sys.path).replace("\\", "\\\\"),
'err.log'
)
pm = pymem.Pymem('notepad.exe')
pm.inject_python_interpreter()
pm.inject_python_shellcode(shellcode)
这段代码应该挂钩CreateFileW函数,将它与之交互的文件的名称记录到文件中,然后返回函数的其余部分。我的问题是,当在记事本中调用此函数时,程序只是挂起 - 所以不幸的是没有成功。
我有一种感觉,我的代码在这里:
pm.inject_python_shellcode(shellcode)
正在生成一个线程并立即执行,而不是仅在它被调用时执行 - 但我不知道有什么不同的方法可以做到这一点。
我完全愿意接受不同的方法来解决这个问题。我知道ctypes这项工作很强大,但我不确定如何在这种方法中实现类似的东西。我通过示例代码学习得最好,并且很容易地花费了几十个小时寻找没有成功的方法。感谢您的任何帮助,您可以提供!