我正在尝试从 Linux 上的纯 Python 代码调用内联机器代码。为此,我将代码嵌入到字节文字中
code = b"\x55\x89\xe5\x5d\xc3"
然后调用mprotect()
viactypes
以允许执行包含代码的页面。最后,我尝试使用ctypes
来调用代码。这是我的完整代码:
#!/usr/bin/python3
from ctypes import *
# Initialise ctypes prototype for mprotect().
# According to the manpage:
# int mprotect(const void *addr, size_t len, int prot);
libc = CDLL("libc.so.6")
mprotect = libc.mprotect
mprotect.restype = c_int
mprotect.argtypes = [c_void_p, c_size_t, c_int]
# PROT_xxxx constants
# Output of gcc -E -dM -x c /usr/include/sys/mman.h | grep PROT_
# #define PROT_NONE 0x0
# #define PROT_READ 0x1
# #define PROT_WRITE 0x2
# #define PROT_EXEC 0x4
# #define PROT_GROWSDOWN 0x01000000
# #define PROT_GROWSUP 0x02000000
PROT_NONE = 0x0
PROT_READ = 0x1
PROT_WRITE = 0x2
PROT_EXEC = 0x4
# Machine code of an empty C function, generated with gcc
# Disassembly:
# 55 push %ebp
# 89 e5 mov %esp,%ebp
# 5d pop %ebp
# c3 ret
code = b"\x55\x89\xe5\x5d\xc3"
# Get the address of the code
addr = addressof(c_char_p(code))
# Get the start of the page containing the code and set the permissions
pagesize = 0x1000
pagestart = addr & ~(pagesize - 1)
if mprotect(pagestart, pagesize, PROT_READ|PROT_WRITE|PROT_EXEC):
raise RuntimeError("Failed to set permissions using mprotect()")
# Generate ctypes function object from code
functype = CFUNCTYPE(None)
f = functype(addr)
# Call the function
print("Calling f()")
f()
此代码在最后一行出现段错误。
为什么会出现段错误?调用表示成功,
mprotect()
所以我应该被允许在页面中执行代码。有没有办法修复代码?我真的可以在纯 Python 和当前进程中调用机器代码吗?
(一些进一步的评论:我并不是真的试图实现一个目标 - 我试图了解事情是如何工作的。我还尝试使用2*pagesize
而不是pagesize
在mprotect()
调用中排除我的 5 字节代码落在页面边界——无论如何这应该是不可能的。我使用 Python 3.1.3 进行测试。我的机器是 32 位 i386 机器。我知道一种可能的解决方案是从纯 Python 代码创建一个 ELF 共享对象并加载它via ctypes
,但这不是我要找的答案:)
编辑:以下 C 版本的代码工作正常:
#include <sys/mman.h>
char code[] = "\x55\x89\xe5\x5d\xc3";
const int pagesize = 0x1000;
int main()
{
mprotect((int)code & ~(pagesize - 1), pagesize,
PROT_READ|PROT_WRITE|PROT_EXEC);
((void(*)())code)();
}
编辑 2:我在我的代码中发现了错误。线
addr = addressof(c_char_p(code))
首先创建一个char*
指向bytes
实例开头的 ctypes code
。 addressof()
应用于这个指针的不是返回这个指针指向的地址,而是指针本身的地址。
我设法弄清楚实际获取代码开头地址的最简单方法是
addr = addressof(cast(c_char_p(code), POINTER(c_char)).contents)
更简单的解决方案的提示将不胜感激:)
修复这一行会使上面的代码“工作”(意味着它什么都不做,而不是段错误......)。