Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing shared memory without root privilege

I have the following C program

#include <stdio.h>                                                                        
#include <sys/types.h>                                                                    
#include <sys/shm.h>                                                                      
#include <sys/ipc.h>                                                                      

int main()                                                                                
{                                                                                         
  key_t shm_key;                                                                          
  int shm_flag,shm_id,shm_size;                                                           
  void *shm_addr;                                                                         

  shm_key = ftok("/home/meow/Arena",22);                                                  
  perror("SHMKEY");                                                                       

  shm_id = shmget(shm_key,sizeof(int)*20,IPC_CREAT);                                      
  perror("SHMGET");                                                                       

  shm_addr = shmat(shm_id,NULL,0);                                                        
  perror("SHMAT");                                                                     

}

when execute without root privilege I get

meow@darkArts ~/Arena/c $ gcc shm.c && ./a.out 
SHMKEY: Success
SHMGET: Success
SHMAT: Permission denied

And when executed by the root user I get the following message

root@darkArts:/home/meow/Arena/c# gcc shm.c && ./a.out
SHMKEY: Success
SHMGET: Success
SHMAT: Success

Is it possible to bind the shared memory to my address space without the root privileges ?

EDIT:

With shmid = shmget(key, SHMSZ, IPC_CREAT | 0666); and shmid = shmget(key, SHMSZ, IPC_CREAT | 0777); I get
meow@darkArts ~/Arena/c $ gcc shm.c && ./a.out 
SHMKEY: Success
SHMGET: Permission denied
SHMAT: Invalid argument
like image 914
vikkyhacks Avatar asked Apr 09 '26 09:04

vikkyhacks


1 Answers

You can give permissions to the shared memory segment you create. By default only root is allowed access but you can change this while you create the shared memory segment, for example:

shmid = shmget(key, SHMSZ, IPC_CREAT | 0666); 
//or
shmid = shmget(key, SHMSZ, IPC_CREAT | 0777);

Then you may try and access this shared memory segment as any user.

like image 129
vvvv Avatar answered Apr 11 '26 22:04

vvvv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!