Docker Community Forums

Share and learn in the Docker community.

How to pass /dev/mem without --privileged?

Hello all.

I am trying to put a script into a docker container that requires access to /dev/mem. I am running into an issue because I cannot control how the docker image is run, basically in production I do not have the ability to add --privileged but that’s one of the only ways I have gotten the container to work as expected.

I have also had success running the container with --cap-add SYS_RAWIO --device /dev/mem:/dev/mem. This is probably a slightly better solution as its not giving the container complete privileged access to the host, however I have the same problem when deploying the container. I cannot add any flags/arguments before the container name.

Does anyone have a possible workaround? Any advice/help would be much appreciated!

Test Host OS’s: Ubuntu 16.04 Desktop, Liunux Mint 19.1, Ubuntu 18 Desktop
Docker version 19.03.6, build 369ce74a3c

I’m not sure if there’re other methods, but you can access physical memory using /dev/mem & system call mmap().

/dev/mem is a character device file that is an image of the main memory of the computer. It may be used, for example, to examine (and even patch) the system. Byte addresses in mem are interpreted as physical memory addresses.

more on /dev/mem: http://linux.about.com/library/cmd/blcmdl4_mem.htm

more on mmap(): http://linux.die.net/man/2/mmap

You can use the mmap() to map a section of /dev/mem and use in your user program. A brief example code:

#define MAPPED_SIZE //place the size here
#define DDR_RAM_PHYS //place the physical address here

int _fdmem;
int *map = NULL;
const char memDevice = “/dev/mem”;

/* open /dev/mem and error checking */
_fdmem = open( memDevice, O_RDWR | O_SYNC );

if (_fdmem < 0){
printf(“Failed to open the /dev/mem !\n”);
return 0;
}
else{
printf(“open /dev/mem successfully !\n”);
}

/* mmap() the opened /dev/mem */
map= (int *)(mmap(0,MAPPED_SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,_fdmem,DDR_RAM_PHYS));

/* use ‘map’ pointer to access the mapped area! /
for (i=0,i<100;i++)
printf(“content: 0x%x\n”,
(map+i));

/* unmap the area & error checking */
if (munmap(map,MAPPED_SIZE)==-1){
perror(“Error un-mmapping the file”);
}

/* close the character device */
close(_fdmem);
However, please make sure the area you are mapping is not used, for example by the kernel, or it will make your system crash/hang, and you will be forced to reboot using hardware power button.