Created
April 28, 2024 07:55
-
-
Save gynvael/24a6ac5b97f0a89145a7031a1b571c31 to your computer and use it in GitHub Desktop.
Low-level shellcode execution in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from ctypes import * | |
NULL = 0 | |
PROT_READ = 1 | |
PROT_WRITE = 2 | |
PROT_EXEC = 4 | |
MAP_ANON = 0x20 | |
MAP_PRIVATE = 2 | |
libc = cdll.LoadLibrary("libc.so.6") | |
# Allocate RWX memory. | |
libc.mmap.argtypes = [c_size_t, c_size_t, c_int, c_int, c_int, c_size_t] | |
libc.mmap.restype = c_size_t | |
addr = libc.mmap(NULL, 4096, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_ANON|MAP_PRIVATE, -1, 0) | |
print(f"addr: {addr:x}") | |
# Copy shellcode into memory. | |
shellcode = b'\xb8\x2a\0\0\0\xc3' # MOV EAX, 42; RET | |
shellcode_tmp = create_string_buffer(shellcode, len(shellcode)) | |
libc.memcpy.argtypes = [c_size_t, c_void_p, c_size_t] | |
libc.memcpy(addr, shellcode_tmp, len(shellcode_tmp)) | |
# Execute! | |
shellcode_t = CFUNCTYPE(c_int) | |
shellcode_func_ptr = shellcode_t(addr) | |
res = shellcode_func_ptr() | |
print(f"res: {res} (should be 42)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment