What memory protection flags are allocated by malloc?

According to this thread, the memory allocated by malloc at least PROT_READ | PROT_EXEC PROT_READ | PROT_EXEC , otherwise the programmed function cannot be executed.

man malloc says nothing about protection, so the question is.

+6
source share
3 answers

malloc not a suitable tool for allocating memory for code. You should use mmap , and depending on the paranoid security policies on your system, you may need to use mprotect too to change permissions.

Among the reasons malloc not the right tool:

  • Permissions are set only with the granularity of the page, but the memory obtained with malloc is unlikely to be aligned on the page, and thus you will also set permissions for contiguous memory, possibly violating it.
  • If you do not restore the old permissions before calling free , you can violate the internal malloc elements.
+5
source

malloc() usually returns memory with read and write permissions. Some architectures (for example, older than x86) may not allow direct removal of the execution permission, but this is just platform efficiency.

If you want to execute code from the memory you allocated, you will need to explicitly grant execute permissions, and you may need to remove write permissions, as having write and execute permissions in the same memory is considered potentially dangerous on some systems ( commonly called W ^ X). A.

There were several other threads when executing code from memory allocated by the programmer:

Select executable drum in c on linux
Is it possible to execute code from a stack in standard C?

+4
source

You may need to call mprotect to set the PROT_EXEC flag yourself, after allocating memory.

$ man mprotect

+1
source

Source: https://habr.com/ru/post/890280/


All Articles