Skip to content

Instantly share code, notes, and snippets.

@penafieljlm
Last active June 23, 2017 06:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save penafieljlm/5aff2712d373d72150ecd323f44f5042 to your computer and use it in GitHub Desktop.
Save penafieljlm/5aff2712d373d72150ecd323f44f5042 to your computer and use it in GitHub Desktop.
struct Template {
int64_t data_64;
int32_t data_32;
int16_t data_16;
char data_char;
} value {
// the x'es get instructions written onto them
// notice that those instructions are nops
//xxxxxx
0x90909000001000b9,
// xx
0x01e98390,
0xf775,
0xc3
};
// the data above is actually a bunch of opcodes
//
// .data:00000000 b9 00 10 00 00 mov ecx,0x1000
// .data:00000005 90 nop <<<< this gets filled up by the user and then executed
// .data:00000006 90 nop <<<< this gets filled up by the user and then executed
// .data:00000007 90 nop <<<< this gets filled up by the user and then executed
// .data:00000008 90 nop <<<< this gets filled up by the user and then executed
// .data:00000009 83 e9 01 sub ecx,0x1
// .data:0000000c 75 f7 jne 0x00000005
// .data:0000000e c3 ret
Template* template = &value;
int64_t alloc_page() {
return mmap(
NULL,
4096,
PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE,
-1,
0
);
}
int64_t free_page(page) {
return munmap(page, 4096);
}
void make_page_executable(page) {
mprotect(page, 4096, PROT_READ | PROT_EXEC);
}
int64_t read_byte() {
char chars[16];
chars[15] = 0;
read(NULL, &chars[15], 1);
return chars[15];
}
void read_n(dest, count) {
void* end = dest + count;
void* current = dest;
if (count != 0) {
do {
current++;
*(current-1) = read_byte();
} while(current != end);
}
}
void read_inst(dest) {
read_n(dest, 4);
}
int64_t do_test() {
long duration;
long var_y;
void* page = alloc_page();
*page = *((int64_t*)(template + 0));
*(page + 8) = *((int32_t*)(template + 8));
*(page + 12) = *((int16_t*)(template + 12));
*(page + 14) = *((char*)(template + 14));
read_inst(page + 5);
make_page_executable(page);
time_start = timestamp();
*page();
time_end = timestamp();
duration = time_end - time_start;
write(STDOUT, &duration, 8);
free_page(page);
}
int32_t main(int32_t argc, char** argv, char** envp) {
write(STDOUT, "initializing prof...", 20);
sleep(5);
alarm(30);
write(STDOUT, "ready\n", 6);
do {
dotest();
} while(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment