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.

  • 1
    `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. – Martijn Pieters Jan 21 '13 at 23:35
  • 1
    Are you sure it's not more appropriate to use explicit IPC (which can include shared memory btw)? – Brian Cain Jan 21 '13 at 23:40
  • Changed 'rw' to 'r+' but I still get an IOError – user1998059 Jan 21 '13 at 23:55
  • 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. – engineerC Jan 21 '13 at 23:58
  • @BrianCain No, I am working with closed source binaries so proper IPC is not possible. – user1998059 Jan 22 '13 at 00:00
  • Is ther other process a python process? A kernel process? Need more info. – Zippy Zeppoli Jan 22 '13 at 00:06
  • @ZippyZeppoli The other process is a standard userspace process, albeit closed-source. – user1998059 Jan 22 '13 at 00:09
  • @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. – user1998059 Jan 22 '13 at 00:11
  • 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. – Keith Jan 22 '13 at 00:17
  • @Keith This just changes the error to `OSError: [Errno 22] Invalid argument` – user1998059 Jan 22 '13 at 00:31
  • What flags are you using? – Keith Jan 22 '13 at 00:37
  • Did you see http://unix.stackexchange.com/questions/6301/how-do-i-read-from-proc-pid-mem-under-linux – engineerC Jan 22 '13 at 01:56

1 Answers1

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.