Read Memory Protection

I would like to know if there is a way for Linux to restore memory protection. For example, I want to restore protection that existed after it was changed using mprotect.

+4
source share
2 answers

Based on davidg's answer, here is the unsigned int read_mprotection(void* addr) function : re_mprot.c , re_mprot.h from the reDroid project in github (the code works on Android, it must be portable for other linux).

+1
source

The /proc/self/maps file on Linux contains information about the current location of virtual memory, about what each segment is, and about the memory protection of that segment. Changes made using mprotect will cause the file to be updated accordingly.

By developing /proc/self/maps , before you start modifying it with mprotect , you will need to have enough information to restore the previous layout.

The following example shows the contents of /proc/self/maps in three scenarios:

  • Before performing any operation;
  • After mmap (which shows one additional entry in the file); and finally
  • After mprotect (which shows that the permission bits are changing in the file).

(Tested with 32-bit Linux 2.6).

 #include <sys/mman.h> #include <stdio.h> #include <errno.h> #define PAGE_SIZE 4096 void show_mappings(void) { int a; FILE *f = fopen("/proc/self/maps", "r"); while ((a = fgetc(f)) >= 0) putchar(a); fclose(f); printf("-----------------------------------------------\n"); } int main(void) { void *mapping; /* Show initial mappings. */ show_mappings(); /* Map in some pages. */ mapping = mmap(NULL, 16 * PAGE_SIZE, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); printf("*** Returned mapping: %p\n", mapping); show_mappings(); /* Change the mapping. */ mprotect(mapping, PAGE_SIZE, PROT_READ | PROT_WRITE); show_mappings(); return 0; } 

As far as I know, there is no mechanism other than the /proc/ interface that Linux provides so that you can determine the location of your virtual memory. So parsing this file is the best you can do.

+1
source

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


All Articles