Skip to content

Instantly share code, notes, and snippets.

@darkcores
Created May 17, 2019 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darkcores/99397c57676c58c2502c8b6c98bfc36d to your computer and use it in GitHub Desktop.
Save darkcores/99397c57676c58c2502c8b6c98bfc36d to your computer and use it in GitHub Desktop.
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