gpt4 book ai didi

python - 在 Python 中执行 Shellcode

转载 作者:行者123 更新时间:2023-12-04 14:16:17 25 4
gpt4 key购买 nike

以下代码适用于 C,但是否可以在 Python 中执行类似的操作?它可以是 2.7.x 或 3.x。

char bytes[] = "\x90\x90\x90\x90\x90\x90\x90\x90\xeb\x1a\x5e\x31\xc0"
"\x88\x46\x07\x8d\x1e\x89\x5e\x08\x89\x46\x0c\xb0\x0b"
"\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\xe8\xe1\xff"
"\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x20";

int main() {
((int (*)())bytes)();
}
我尝试了以下方法:
#!/usr/bin/python
import ctypes
from subprocess import call

lib = ctypes.cdll.LoadLibrary(None)

shellcode = (b"\x90\x90\x90\x90\x90\x90\x90\x90\xeb\x1a\x5e\x31\xc0"
"\x88\x46\x07\x8d\x1e\x89\x5e\x08\x89\x46\x0c\xb0\x0b"
"\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\xe8\xe1\xff"
"\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x20")

code = ctypes.create_string_buffer(shellcode)
addr = id(shellcode)

# Test Shellcode
functype = ctypes.CFUNCTYPE(ctypes.c_int)
func = functype(addr)
func()
我不断收到 Segmentation fault (core dumped) .

最佳答案

你的原因create_string_buffer不起作用是因为内存地址未标记为可执行文件。你需要有一个带有 RX 的内存页来执行 shellcode。一个简单的方法是使用 mmap。
以下代码将在 Python 3 上运行 shellcode(在 Python 3.8.11 上测试)。

import ctypes
import mmap

# This shellcode will print "Hello World from shellcode!"
shellcode = b"hed \x0b\x814$\x01\x01\x01\x01H\xb8 shellcoPH\xb8rld fromPH\xb8Hello WoPj\x01Xj\x01_j\x1cZH\x89\xe6\x0f\x05XXXX\xc3"

# Allocate an executable memory and write shellcode to it
mem = mmap.mmap(
-1,
mmap.PAGESIZE,
mmap.MAP_SHARED,
mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC,
)
mem.write(shellcode)

# Get actuall mmap address (I don't know the proper way to get the address sorry...)
# Assuming x64
addr = int.from_bytes(ctypes.string_at(id(mem) + 16, 8), "little")
print(hex(addr))

# Create the function
functype = ctypes.CFUNCTYPE(ctypes.c_void_p)
fn = functype(addr)

# Run shellcode
fn()

print("Back to python!")
输出将类似于:
0x7fd6ed4c2000
Hello World from shellcode!
Back to python!

关于python - 在 Python 中执行 Shellcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32707932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com