简体   繁体   中英

Executing Shellcode in Python

The following code works in C, but is it possible to do something similar in Python? It can be 2.7.x or 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)();
}

I tried the following:

#!/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()

I keep getting Segmentation fault (core dumped) .

The reason your create_string_buffer doesn't work is due to the memory address aren't marked as executable. You need to have a memory page with RX to execute shellcode. An easy way to do that is to use mmap.

The following code will run the shellcode on Python 3 (Tested on 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!")

The output will be like:

0x7fd6ed4c2000
Hello World from shellcode!
Back to python!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM