How to write a Perl, Python, or Ruby program to change the memory of another process on Windows?

后端 未结 6 1872
终归单人心
终归单人心 2020-12-30 12:20

I wonder if Perl, Python, or Ruby can be used to write a program so that it will look for 0x12345678 in the memory of another process (probably the heap, for both data and c

6条回答
  •  春和景丽
    2020-12-30 12:49

    It is possible to do so if you have attached your program as a debugger to the process, which should be possible in those languages if wrappers around the appropriate APIs exist, or by directly accessing the windows functions through something like ctypes (for python). However, it may be easier to do in a more low-level language, since in higher level ones you'll have to be concerned with how to translate highlevel datatypes to lower ones etc.

    Start by calling OpenProcess on the process to debug, with the appropriate access requested (you'll need to be an Admin on the machine / have fairly high privileges to gain access). You should then be able to call functions like ReadProcessMemory and WriteProcessMemory to read from and write to that process's memory.

    [Edit] Here's a quick python proof of concept of a function that successfully reads memory from another process's address space:

    import ctypes
    import ctypes.wintypes
    kernel32 = ctypes.wintypes.windll.kernel32
    
    # Various access flag definitions:
    class Access:
        DELETE      = 0x00010000
        READ_CONTROL= 0x00020000
        SYNCHRONIZE = 0x00100000
        WRITE_DAC   = 0x00040000
        WRITE_OWNER = 0x00080000
        PROCESS_VM_WRITE = 0x0020
        PROCESS_VM_READ = 0x0010
        PROCESS_VM_OPERATION = 0x0008
        PROCESS_TERMINATE = 0x0001
        PROCESS_SUSPEND_RESUME = 0x0800
        PROCESS_SET_QUOTA = 0x0100
        PROCESS_SET_INFORMATION = 0x0200
        PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
        PROCESS_QUERY_INFORMATION = 0x0400
        PROCESS_DUP_HANDLE = 0x0040
        PROCESS_CREATE_THREAD = 0x0002
        PROCESS_CREATE_PROCESS = 0x0080
    
    def read_process_mem(pid, address, size):
        """Read memory of the specified process ID."""
        buf = ctypes.create_string_buffer(size)
        gotBytes = ctypes.c_ulong(0)
        h = kernel32.OpenProcess(Access.PROCESS_VM_READ, False, pid)
        try:
            if kernel32.ReadProcessMemory(h, address, buf, size, ctypes.byref(gotBytes)):
                return buf
            else:
                # TODO: report appropriate error GetLastError
                raise Exception("Failed to access process memory.")
        finally:
            kernel32.CloseHandle(h)
    

    Note that you'll need to determine where in memory to look for things - most of that address space is going to be unmapped, thought there are some standard offsets to look for things like the program code, dlls etc.

提交回复
热议问题