2

I'm making a custom ELF loader to learn how the dynamic loader works behind the scenes, and one of the program headers often found in them is PT_GNU_RELRO, which tells the loader to make that segment read-only after performing relocations.

However, it doesn't look like there's a good way to update existing memory mappings' protections without replacing the entire thing.

MAP_UNINITIALIZED seems to be what I'm looking for, but mmap(2) states that it doesn't work on most systems for security reasons.

MAP_UNINITIALIZED (since Linux 2.6.33)

Don't clear anonymous pages. This flag is intended to improve performance on embedded devices. This flag is honored only if the kernel was configured with the CONFIG_MMAP_ALLOW_UNINITIALIZED option. Because of the security implications, that option is normally enabled only on embedded devices (i.e., devices where one has complete control of the contents of user memory).

Which is reasonable for loosening permissions, but I'm looking to restrict them.

Is there a way, as a user process, to update a mmap mapping to be read-only without replacing existing data at that address?

2 Answers 2

2

You can use mprotect to set the permissions of an existing memory region to read-only, PROT_READ without replacing the data.

mprotect is specifically designed for this task and can changing the access permissions like read/write/execute of an already mapped memory region.

It works on all modern unix/linux systems and is the standard way to implement PT_GNU_RELRO.

mprotect(addr, length, PROT_READ); 

If needed, you can also use PROT_READ, PROT_EXEC or other combinations.

If the memory region needs to be remapped but rarely necessary, you could use mmap with MAP_FIXED, but mprotect is simpler and more efficient.

Sources:

2

I have used mprotect(2) to change the protection on a region of memory. E.g.:

  1. At initialisation when a memory region is writable populate the contents.
  2. Then call mprotect with the prot argument set to PROT_READ.

Where a region is one or more consecutive memory pages.

mprotect can change the permissions on either private or shared mappings (going from my memory, don't access to the code to check at the moment).

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.