OiO.lk Blog python How to call the ctypes function from bytes in Python?
python

How to call the ctypes function from bytes in Python?


I have the disassamble bytes of a simple function

89 4C 24 08          mov         dword ptr [sum],ecx  
    while (sum>=1) {
83 7C 24 08 01       cmp         dword ptr [sum],1  
7C 0C                jl          doNothing+17h (07FF636C61017h)  
        sum--;
8B 44 24 08          mov         eax,dword ptr [sum]  
FF C8                dec         eax  
89 44 24 08          mov         dword ptr [sum],eax  
    }
EB ED                jmp         doNothing+4h (07FF636C61004h)  
}
C3                   ret  

which is a bytes object in python bytes.fromhex('89 4c 24 08 83 7c 24 08 01 7c 0c 8b 44 24 08 ff c8 89 44 24 08 eb ed c3 ')

How to call this micro codes in python using ctypes? I tried the code as below, but it crashes.

import ctypes

# raw disassamble bytes
buf = bytes.fromhex('89 4c 24 08 83 7c 24 08 01 7c 0c 8b 44 24 08 ff c8 89 44 24 08 eb ed c3 ')

# function type definition
nothFn = ctypes.CFUNCTYPE(None, ctypes.c_int)

# ctypes buffer
codebuf = ctypes.create_string_buffer(buf)

# raw buffer's address as the function
cfunc = nothFn(ctypes.addressof(codebuf))

# call it then it crashes
cfunc(ctypes.c_int(3))

I also tried to use the address returned from str(codebuf) but it also crashes.

Questions:

  1. Is it due to the memory execution violates? how to make the allocated memory executables then? Does it have be in a dynamic library to be loaded for execution?
  2. Will the same code run under both Windows and Linux if the cpu is the same architecture x86_64? To avoid complication, let’s suppose the function is simple and only operates on the input argument or stack memory.



You need to sign in to view this answers

Exit mobile version