Python Ctype Segmentation Fault

This is the code to run shellcode using ctype. The shellcode runs "whoami" on a 64 bit linux. But this program gives me a "segmentation fault". But I m unable to figure out the error in it. The structure of the code is from: ctypes: Cast string to function?


from ctypes import *

# /usr/bin/whoami
shellcode_data = ("\x6a\x3b\x58\x99\x48\xbb\x2f\x62\x69\x6e\x2f\x73\x68\x00\x53"

shellcode = c_char_p(shellcode_data)
function = cast(shellcode, CFUNCTYPE(None))

For 32bits architectures this will be the shell code:

shellcode_data = ("\x6a\x0b\x58\x99\x52\x66\x68\x2d\x63\x89\xe7\x68\x2f\x73\x68"


  • The NX Bit prevents random data being executed on modern processors and OSs. To get around it, call mprotect. You should also define your shellcode as a binary instead of a character string, like this:

    import ctypes
    shellcode_data = (b"\x6a\x3b\x58\x99\x48\xbb\x2f\x62\x69\x6e\x2f\x73\x68\x00\x53"
    shellcode = ctypes.create_string_buffer(shellcode_data)
    function = ctypes.cast(shellcode, ctypes.CFUNCTYPE(None))
    addr = ctypes.cast(function, ctypes.c_void_p).value
    libc = ctypes.CDLL('')
    pagesize = libc.getpagesize()
    addr_page = (addr // pagesize) * pagesize
    for page_start in range(addr_page, addr + len(shellcode_data), pagesize):
        assert libc.mprotect(page_start, pagesize, 0x7) == 0