Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What’s the purpose of mmap memory protection PROT_NONE

Tags:

I was reading the documentation of mmap and fell upon this line:

PROT_NONE Pages may not be accessed.

Is there any use to map a file to memory but never access it?

like image 830
qdii Avatar asked Oct 16 '12 14:10

qdii


People also ask

What is mmap () used for?

The mmap() function can be used to map a region of memory that is larger than the current size of the object. Memory access within the mapping but beyond the current end of the underlying objects may result in SIGBUS signals being sent to the process.

How does Mprotect protect memory?

Listing 8.7 (mprotect. The program allocates a page of memory by mapping /dev/zero and writing a value to the allocated page to obtain a private copy. The program protects the memory by calling mprotect with the PROT_NONE permission.

What are guard pages?

These guard pages are unmapped pages placed between all allocations of memory the size of one page or larger. The guard page causes a segmentation fault upon any access.

What is memory mapping in Linux?

Memory mapping of files is a very powerful abstraction that many operating systems support out of the box. Linux does this via the mmap system call. In most cases where an application reads (or writes) to a file at arbitrary positions, using mmap is a solid alternative to the more traditional read / write system calls.


2 Answers

PROT_NONE can be used to implement guard pages, Microsoft has the same concept (MSDN).

To quote the first link:

... allocation of additional inaccessible memory during memory allocation operations is a technique for mitigating against exploitation of heap buffer overflows. These guard pages are unmapped pages placed between all memory allocations of one page or larger. The guard page causes a segmentation fault upon any access.

Thus useful in implementing protection for areas such as network interfacing, virtual machines, and interpreters. An example usage: pthread_attr_setguardsize, pthread_attr_getguardsize.

like image 57
Steve-o Avatar answered Oct 02 '22 08:10

Steve-o


PROT_NONE allocates a contiguous virtual memory region with no permissions granted.

This can be useful, as other have mentioned, to implement guards (pages that on touch cause segfaults, both for bug hunting and security purposes) or "magic" pointers where values within a PROT_NONE mapping are to be interpreted as something other than a pointer.

Another use is when an application wishes to map multiple independent mappings as a virtually contiguous mapping. This would be done by first mmapping a large enough chunk with PROT_NONE, and then performing other mmap calls with the MAP_FIXED flag and an address set within the region of the PROT_NONE mapping (the use of MAP_FIXED automatically unmaps part of mappings that are being "overridden").

like image 31
Kenny Avatar answered Oct 02 '22 07:10

Kenny