0

I need to protect the pages in a parent from the pages in a child

  • I have tried not using shm_open with the MAP_ANONYMOUS flag and fd = -1 in mmap.
  • I have tried protecting the underlying memory with fchmod.

I currently am utilizing the following setup:

shm_unlink("/mymem");
int fd = shm_open("/mymem", O_RDWR | O_CREAT,0777);

printf("FD is :%d\n", fd);
ftruncate(fd, numberPages*getpagesize());

int *z = mmap(NULL, getpagesize()*numberPages, PROT_WRITE|PROT_READ, MAP_SHARED,fd,0);
printf("Memory is at : %p\n", z);

if(fork()){
   printf("Protecting %d\n",mprotect(z, getpagesize(), PROT_NONE));
   printf("(1)No issues, apparently\n");

   sleep(2);
   exit(1);
 }else{
   sleep(1);
   *z = 3;
   printf("(2)No issues, apparently\n");
   sleep(5);
   printf("Value of z: %d\n",*z);
 }

I need the child process to be able to protect the pages (with mprotect, or otherwise) so that the parent process can no longer read/write to the pages.

Received output is:

FD is :3
Memory is at : 0xf581a000
Protecting 0
(1)No issues, apparently
(2)No issues, apparently
Value of z: 3

When I am expecting (or rather, wanting) a segmentation fault to occur at the line *z = 3.

Unfortunately, the child must have this functionality as it is also acting as a TCP server and requests to block a page will be received through the TCP connection (unless there's another method I haven't thought of?).

any advice?

Tabgok
  • 7
  • 1

1 Answers1

2

The mrotect() in your child process is, of course, changing the permissions of the pages in the child process itself, not in the parent process. That's as documented:

mprotect() changes protection for the calling process's memory page(s)

(emphasis added)

Your question boils down to how to change the permissions of memory mappings of another process (not the calling process). Without the participation of the target process (the process whose memory mappings are to be changed), I don't think there's any portable way to do this. The only way I can think of doing it is by attaching to the target process as a debugger (see ptrace() on Linux for example). It's a complicated solution. Have you considered sending a message to the parent process (through a pipe, for example) to ask it to run mprotect() for itself?

Celada
  • 21,627
  • 4
  • 64
  • 78
  • You've nailed the question exactly. I am going to look up ptrace() right now. Unfortunately, the parent process is going to be performing other operations constantly, so I can't have it block while waiting for a message to arrive > – Tabgok Apr 13 '12 at 19:35
  • You could create a thread in the parent process that blocks waiting for messages from the child while the main thread of the parent process gets on with its work. – Celada Apr 13 '12 at 19:47
  • Hmmm - that isn't a bad idea, I'll try it after lunch. – Tabgok Apr 13 '12 at 20:04
  • Problem solved using a separate thread and pipe commands, thank you both! – Tabgok Apr 13 '12 at 23:56