Python: writing to another process's memory under linux
Asked Answered
V

1

6

How to write to another process's address space using python under Ubuntu Linux? My attempts:

1) Using the virtual file /proc/$PID/mem and seeking to the address. I have successfully used it to read memory, but attempting to write causes an IOError:

fd=open("/proc/"+pid+"/mem","r+")
fd.seek(address,0)
fd.write("ABC")

Output:

IOError: [Errno 22] Invalid argument

2) Attempting to use the python-ptrace library as suggested in other threads. However, I cannot find good documentation or example code.

Note: this is not a permissions issue, running as root produces the same behaviour.

Vasilikivasilis answered 21/1, 2013 at 23:33 Comment(12)
rw is not a valid mode value for open(). To open a file for both reading and writing you'd have to use r+ instead.Decca
Are you sure it's not more appropriate to use explicit IPC (which can include shared memory btw)?Poleyn
Changed 'rw' to 'r+' but I still get an IOErrorVasilikivasilis
What you're attempting is unusual enough that perhaps sharing what it is you're trying to accomplish would get a better answer, instead of asking about the execution of your presupposed solution.Combat
@BrianCain No, I am working with closed source binaries so proper IPC is not possible.Vasilikivasilis
Is ther other process a python process? A kernel process? Need more info.Grammarian
@ZippyZeppoli The other process is a standard userspace process, albeit closed-source.Vasilikivasilis
@CaptainMurphy I am trying to modify some strings in a running closed-source application, to replace all instances of 'XYZ' with 'ABC'. By sending SIGSTOP to the process and reading /proc/$PID/maps and /proc/$PID/mem, I have managed to obtain the addresses of all such strings. But I need a way to write to the addresses.Vasilikivasilis
Try using low-level IO instead (os.read, os.write) using the fd. Not sure if that will help with this problem, but is generally better in this case.Demello
@Demello This just changes the error to OSError: [Errno 22] Invalid argumentVasilikivasilis
What flags are you using?Demello
Did you see unix.stackexchange.com/questions/6301/…Combat
V
3

Found a solution here: http://tito.googlecode.com/svn-history/r2/trunk/draft/fakefs.py

It uses the ctypes package to load libc, then libc.ptrace with the POKEDATA option to write the bytes.

Vasilikivasilis answered 23/1, 2013 at 17:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.