I have a set of questions regarding /dev/mem:
-
Many articles on the net, seem to refer
/dev/memas the gateway to"Physical RAM". But if I am right,/dev/memis the gateway to the"Physical Address Space"of the processor which might include control registers of many HW peripherals and not just the RAM? Please, correct me if I am wrong! -
In order to prevent attackers from misusing
/dev/memand altering kernel memory, a flagCONFIG_STRICT_DEVMEMneeds to be enabled which will prevent user apps from accessing physical address space beyond 1MB. I checked the config file on my PC (Ubuntu) and found thatCONFIG_STRICT_DEVMEM = y. And I wrote a program which tries to read to physical memory beyond 1 MB and I was able to read! No segmentation fault or anyOperation NOT Permittederror. How is this possible?
My program roughly looks like this:
fd = open ( "/dev/mem", O_RDWR);
ptr = (int*) mmap(0, MAP_SIZE, PROT_READ, fd, myAddress & (~MAP_MASK));
printf("%d", *ptr);
Yes, you’re right, /dev/mem allows you to map any physical address, including non-RAM memory mapped IO. This can can be useful for a quick and dirty hack to access some hardware device without writing a kernel driver.
CONFIG_STRICT_DEVMEM makes the kernel check addresses in /dev/mem with
devmem_is_allowed()inarch/x86/mm/init.c, and the comment there explains:your address
0xFFFF0000is quite likely to be non-RAM, since BIOSes typically put IO memory just below 4GB, so that’s why you’re able to map it even with STRICT_DEVMEM.