使用Python模块ctypes和mmap在内存中执行汇编代码

fcipmucu  于 2023-03-21  发布在  Python
关注(0)|答案(1)|浏览(226)

这段代码在linux上工作,打印43,我怎么能编写一个具有类似功能的脚本在windows上运行而不出错呢?

import ctypes
import mmap

buf = mmap.mmap(-1, mmap.PAGESIZE, prot=mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)

ftype = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)
fpointer = ctypes.c_void_p.from_buffer(buf)

f = ftype(ctypes.addressof(fpointer))

buf.write(
    b'\x8b\xc7'  # mov eax, edi
    b'\x83\xc0\x01'  # add eax, 1
    b'\xc3'  # ret
)

r = f(42)
print(r)

del fpointer
buf.close()

当我改变路线:

buf = mmap.mmap(-1, mmap.PAGESIZE, prot=mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)

buf = mmap.mmap(-1, mmap.PAGESIZE, tagname=None, access=mmap.ACCESS_DEFAULT)

Python解释器输出错误:

OSError: exception: access violation writing 0x00EC0000

有谁知道如何纠正这段代码,使其正常运行?所需的输出应该是“43”。

9udxz4iz

9udxz4iz1#

您可以使用VirtualAllocVirtualProtect并标记为PAGE_EXECUTE_READWRITE

import ctypes

asm = """
55                      push   %rbp
48 89 e5                mov    %rsp,%rbp
48 81 ec 00 00 00 00    sub    $0x0,%rsp
48 89 4d 10             mov    %rcx,0x10(%rbp)
8b 45 10                mov    0x10(%rbp),%eax
83 c0 01                add    $0x1,%eax
f3 0f 2a c0             cvtsi2ss %eax,%xmm0
c9                      leave
c3                      ret
""".split('\n')

code = []
for line in asm:
    code.extend(int(x, 16) for x in line[:20].split())

byte_array = bytes(code)

kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

MEM_COMMIT = 0x00001000
MEM_RESERVE = 0x00002000
PAGE_EXECUTE_READWRITE = 0x40

VirtualAlloc = kernel32.VirtualAlloc
VirtualAlloc.restype = ctypes.c_void_p

buf = VirtualAlloc(
        None,
        len(byte_array),
        MEM_COMMIT | MEM_RESERVE,
        PAGE_EXECUTE_READWRITE)

ctypes.memmove(buf, byte_array, len(byte_array))

functype = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)

increment_by_one = functype(buf)
result = increment_by_one(42)
print(result)

相关问题