Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Header files
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <sys/mman.h>
- #include <unistd.h>
- typedef unsigned char byte;
- bool ProtectMemory(void * addr, int flags)
- {
- // Constant holding the page size value
- const size_t pageSize = sysconf(_SC_PAGE_SIZE);
- // Calculate relative page offset
- size_t temp = (size_t) addr;
- temp -= temp % pageSize;
- // Update address
- addr = (void*) temp;
- // Update memory area protection
- return !mprotect(addr, pageSize, flags);
- }
- typedef int (*testFunc)(int, int);
- int main(void)
- {
- char func[] = {0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d, 0xfc,
- 0x89, 0x75, 0xf8, 0x8b, 0x45, 0xf8,
- 0x8b, 0x55, 0xfc, 0x8d, 0x04, 0x02,
- 0xc9, 0xc3};
- testFunc func_copy = (testFunc) malloc(sizeof(func));
- memcpy(func_copy, func, sizeof(func));
- ProtectMemory(func_copy, PROT_WRITE | PROT_READ | PROT_EXEC);
- printf("1 + 2 = %d\n", func_copy(1,2)); // segfaults here
- free(func_copy);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement