-
-
Save H2CO3/b2c90c60195f9e5ad411 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/mman.h> | |
#include <string.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
void try_mprotect(void *p, size_t len, int prot) | |
{ | |
if (mprotect(p, len, prot) != 0) { | |
perror(strerror(errno)); | |
exit(-1); | |
} | |
} | |
int main() | |
{ | |
/* printf("%d\n", foo(42)); // 0 */ | |
unsigned char *a = mmap( | |
NULL, | |
4096, | |
PROT_READ | PROT_WRITE, | |
MAP_ANON | MAP_PRIVATE, | |
-1, | |
0 | |
); | |
if (a == MAP_FAILED) | |
perror("mmap"); | |
a[0] = 0x48; // add rax, | |
a[1] = 0x83; // ... | |
a[2] = 0xC0; // ... | |
a[3] = 0x2A; // 42 (== 0x2A) | |
a[4] = 0xC3; // ret | |
try_mprotect(a, 5, PROT_EXEC); | |
long (*fp)(long) = (long (*)(long))a; | |
printf("fp() == %ld\n", fp(10)); // 52 | |
try_mprotect(a, 5, PROT_READ | PROT_WRITE); | |
a[0] = 0x48; // xor rax, rax | |
a[1] = 0x31; // ... | |
a[2] = 0xC0; // ... | |
a[3] = 0xC3; // ret | |
try_mprotect(a, 5, PROT_EXEC); | |
printf("fp() == %ld\n", fp(10)); // 0 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment