Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fun things
#include <malloc.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
int getnum1(int x) {
x += 1;
return x * x;
}
/*
int getnum2(int x) {
x += 2;
return x * x;
}
*/
static char *magicbuffer;
int main(void) {
int pagesize;
pagesize = sysconf(_SC_PAGE_SIZE);
if (pagesize == -1) {
printf("Sysconf error\n");
}
printf("Pagesize: %d\n", pagesize);
magicbuffer = memalign(pagesize, 1 * pagesize);
uint8_t magic[20] = {0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d, 0xfc,
0x83, 0x45, 0xfc, 0x02, 0x8b, 0x45, 0xfc,
0x0f, 0xaf, 0x45, 0xfc, 0x5d, 0xc3};
int (*func)(int) = &getnum1;
printf("Num 1: %d\n", func(1));
if (mprotect(magicbuffer, pagesize, PROT_READ | PROT_WRITE | PROT_EXEC) !=
0) {
printf("Setting memory protections failed\n");
}
memcpy(magicbuffer, magic, 20);
func = (int (*)(int))magicbuffer;
printf("Num 2: %d\n", func(1));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.