Syntax: Select all
import ctypes
import types
import platform
MEM_COMMIT = 0x00001000
MEM_RESERVE = 0x00002000
PAGE_EXECUTE_READWRITE = 0x40
if platform.architecture()[0] == '32bit':
VirtualAlloc = ctypes.windll.kernel32.VirtualAlloc
VirtualAlloc.argtypes = (ctypes.c_int32, ctypes.c_int32, ctypes.c_int32, ctypes.c_int32)
VirtualAlloc.restype = ctypes.c_void_p
RtlMoveMemory = ctypes.windll.kernel32.RtlMoveMemory
RtlMoveMemory.argtypes = (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int32)
elif platform.architecture()[0] == '64bit':
VirtualAlloc = ctypes.windll.kernel32.VirtualAlloc
VirtualAlloc.argtypes = (ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64)
VirtualAlloc.restype = ctypes.c_void_p
RtlMoveMemory = ctypes.windll.kernel32.RtlMoveMemory
RtlMoveMemory.argtypes = (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64)
else:
print('Lol. Are you running python at 16 or 128 bits?')
exit(1)
def MakeFunction(opcodes:bytes, restype, *argstypes) -> types.FunctionType:
buf = bytearray(opcodes)
buf_ptr = VirtualAlloc(0, len(buf), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)
mov_buf = (ctypes.c_char * len(buf)).from_buffer(buf)
RtlMoveMemory(buf_ptr, mov_buf, len(buf))
func = ctypes.CFUNCTYPE(restype, *argstypes)(buf_ptr)
return func
if platform.architecture()[0] == '32bit':
f = MakeFunction(b'\x55\x89\xE5\x8B\x45\x08\x03\x45\x0C\x5D\xC3', ctypes.c_int32, ctypes.c_int32, ctypes.c_int32)
'''
push ebp
mov ebp, esp
mov eax, [ebp+0x8]
add eax, [ebp+0xC]
pop ebp
ret
'''
print(f'F(10, 30) = {f(10, 30)} (32bit)')
elif platform.architecture()[0] == '64bit':
f = MakeFunction(b'\x89\x54\x24\x08\x89\x4C\x24\x10\x8B\x44\x24\x10\x8B\x4C\x24\x08\x01\xC1\x89\xC8\xC3', ctypes.c_int64, ctypes.c_int64, ctypes.c_int64)
''' x64
mov [rsp+0x8], edx
mov [rsp+0x10], ecx
mov eax, [rsp+0x10]
mov ecx, [rsp+0x8]
add ecx, eax
mov eax, ecx
ret
'''
print(f'F(10, 30) = {f(10, 30)} (64bit)')
Enjoy :P