1

I am trying to write to memory in python. I need to write an Integer but for the WriteProcessMemory function, I need a buffer.

writeProcessMemory = kernel.WriteProcessMemory
writeProcessMemory.argtypes = [ctypes.wintypes.HANDLE, 
ctypes.wintypes.LPVOID, ctypes.wintypes.LPCVOID, ctypes.c_size_t, 
                         ctypes.POINTER(ctypes.c_size_t)]
writeProcessMemory.restype = ctypes.wintypes.BOOL


openProcess = kernel.OpenProcess
openProcess.argtypes = [ctypes.wintypes.DWORD, ctypes.wintypes.BOOL, 
ctypes.wintypes.DWORD]
openProcess.restype = ctypes.wintypes.HANDLE

handle = openProcess(PROCESS_ALL_ACCESS, False, pid)
addr = 0x024EA498
data = ctypes.c_int(1000)
buffer = #i need to create a buffer here
2
  • create a char buffer with the size multiplied by the size of int in C. Careful as int size isn't normalized Commented Jun 9, 2019 at 20:53
  • But won't that write a char to memory? sorry if this is a dumb question im just trying to understand it Commented Jun 9, 2019 at 21:05

1 Answer 1

1

you can use create_string_buffer

buffer = ctypes.create_string_buffer(b"",1000 * 4)

to create a 0-filled buffer of 1000 4-size integers. This buffer is of type ctypes.c_char_Array_4000 that can be passed as a pointer to write into to imported functions.

This function creates a mutable character buffer. The returned object is a ctypes array of c_char.

init_or_size must be an integer which specifies the size of the array, or a bytes object which will be used to initialize the array items.

If a bytes object is specified as first argument, the buffer is made one item larger than its length so that the last element in the array is a NUL termination character. An integer can be passed as second argument which allows specifying the size of the array if the length of the bytes should not be used.

Now call your imported function, and get the python bytes object just written by using:

python_bytes_array = ctypes.string_at(buffer)

Note: ctypes.string_at(address, size=-1) If size is specified, it is used as size, otherwise the string is assumed to be zero-terminated. ctypes docs

and use struct to get hold of the integer values. No need to specify the endianness. I is 4 bytes. It will work if called functions use 4-byte integers:

import struct
integer_tuple = struct.unpack("1000I",python_bytes_array)
Sign up to request clarification or add additional context in comments.

1 Comment

If you open an interactive console, import ctypes import struct and run those 3 lines of code you get struct.error: unpack requires a buffer of 4000 bytes using python 3.8.6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.