The memory record of the monitored process.

I play with ptrace on Linux. I am trying to write the memory of a traced process using the interface / proc / pid / mem.

To accomplish this task, I use the ma function:

void write_proc(pid_t child, unsigned long int addr) { char mem_file_name[100]; char buf[10]="hope"; int mem_fd; memset( (void*)mem_file_name, 0, 100); memset( (void *)buf, 0, 10); sprintf(mem_file_name, "/proc/%d/mem", child); mem_fd = open(mem_file_name, O_RDONLY); lseek(mem_fd, addr , SEEK_SET); if (write(mem_fd, buf, 5) < 0 ) perror("Writing"); return; } 

But I always get an error: Writing: Bad file descriptor.

Is it possible to record a tracked process using this method?

+4
source share
2 answers

You open the file in read-only mode ( O_RDONLY ). I would suggest trying again with O_RDWR instead:

  mem_fd = open(mem_file_name, O_RDWR); 

However, from man proc it is not clear that this will work:

  /proc/[pid]/mem This file can be used to access the pages of a process memory through open(2), read(2), and lseek(2). 

EDIT:

I was also curious, so I put together this example using only ptrace() :

 #include <sys/ptrace.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #define SHOW(call) ({ int _ret = (int)(call); printf("%s -> %d\n", #call, _ret); if (_ret < 0) { perror(NULL); }}) char changeme[] = "This is a test"; int main (void) { pid_t pid = fork(); int ret; int i; union { char cdata[8]; int64_t data; } u = { "Hijacked" }; switch (pid) { case 0: /* child */ sleep(1); printf("Message: %s\n", changeme); exit(0); case -1: perror("fork"); exit(1); break; default: /* parent */ SHOW(ptrace(PTRACE_ATTACH, pid, 0, 0)); SHOW(ptrace(PTRACE_POKEDATA, pid, changeme, u.data)); SHOW(ptrace(PTRACE_CONT, pid, 0, 0)); wait(NULL); break; } return 0; } 
+4
source

ptrace (2) is a very mysterious syscall, used only by debuggers, etc.

Of course, the documented PTRACE_POKEDATA ptrace request should work (when the traced process is stopped) and gives you the ability to write to the memory of the monitored process. I don't know if writing (or mmap -ing) on /proc/$pid/mem work or not.

Googling on linux write /proc /mem gives me especially this one which assumes that /proc/$pid/mem is read-only, but can be made writable in the latest kernels. But the latest Documentation / filesystems / proc.txt from the source kernel tree does not say much.

I would be careful about writing in /proc/$pid/mem ; if it works (or maybe not), it is probably very specific to the kernel version.

Maybe mmap in some segments of this file /proc/$pid/mem works (but I don't know). Have you tried this?

In contrast, PTRACE_POKEDATA should work (it existed on SunOS and many other Unix before Linux existed). Of course, this is pretty slow.

+1
source

All Articles