Search code examples
linuxmmapmemory-mapping

Why in mmap PROT_READ equals PROT_EXEC


I tried to allocate some memory pages with read only access using mmap function. I printed /proc/self/maps to check if the memory protection was working. It showed like this even though the protection argument of mmap was PROT_READ

 7fec0c585000-7fec0c785000 r-xp 00000000 00:00 0

This means that when I ask the kernel to allocate some read only memory pages it mark them as executable too.

I did some other test and I realized that when I ask for a write only pages,PROT_WRITE without PROT_READ, the output of maps file is like this:

7fec0c585000-7fec0c785000 -w-p 00000000 00:00 0 

This means in addition with the previous example that PROT_READ is equivalent to PROT_EXEC

Calling mmap with both PROT_WRITE|PROT_READ, enables execution too.

I wonder if there is a way to map a read only, no executable memory page; or one that is read write and no executable?


Information of the computer where the test were run:

  1. Linux Arch 4.1.6-1-ARCH #1 SMP PREEMPT Mon Aug 17 08:52:28 CEST 2015 x86_64 GNU/Linux

  2. Intel Core i5-2310, x86_64


Solution

  • After doing some research I realized that Linux only activates memory protection when a GNU_STACK program header is included in the ELF program headers. By memory protection I mean the use of the NX bit of the processor, so memory pages can be marked as not executable.

    For what I understand, GNU_STACK program header is designed to tell the kernel that you want some specific properties for the stack, one those properties is a non-executable stack. It appears that if you don't explicitly ask for a non-executable stack, all the ELF sections marked as readable will be executable too. And also all the memory mapping with mmap while have the same behavior.

    Sadly there is no enough documentation on what GNU_STACK does, and the documentation of mmap doesn't specify its connection with GNU_STACK to enable execute protection.

    References:

    https://wiki.gentoo.org/wiki/Hardened/GNU_stack_quickstart