Created
June 25, 2014 06:14
-
-
Save FlyingJester/369647a80d62ea5c7e62 to your computer and use it in GitHub Desktop.
Example of using run-time modified machine code to add two numbers.
This file contains 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 <cstdio> | |
#include <sys/mman.h> | |
#include <sys/types.h> | |
#include <cstring> | |
#include <cctype> | |
#include <cstdlib> | |
int main(int argc, const char * argv[]) | |
{ | |
char a = '\0'; | |
char b = '\0'; | |
do{ | |
printf("Enter a number.\n"); | |
a = getc(stdin); | |
} while(!isdigit(a)); | |
printf("OK, using %c.\n", a); | |
do{ | |
printf("Enter a second number.\n"); | |
b = getc(stdin); | |
} while(!isdigit(b)); | |
printf("OK, using %c.\n", b); | |
printf("Running memory test.\n"); | |
// What we want to execute. | |
unsigned char nop[] = {0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0xC3}; | |
void *lPage = mmap(nullptr, 0xFF, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED, -1, 0); | |
if((lPage==NULL)||(lPage==(void *)(~NULL))){ | |
printf("Memory map failed.\n"); | |
return EXIT_FAILURE; | |
} | |
memcpy(lPage, nop, sizeof(nop)); | |
mprotect(lPage, sizeof(nop), PROT_READ|PROT_EXEC); | |
void (*func)(void); | |
func = (void (*)(void))lPage; | |
func(); | |
printf("Successful memory test. Performing addition:\n"); | |
char ac[] = {a, 0}; | |
char bc[] = {b, 0}; | |
unsigned char adds[] = { | |
0x48, 0xC7, 0xC0, (unsigned char)atoi(ac), /*put a in rax.*/ | |
0, 0, 0, /*align*/ | |
0x48, 0x83, 0xC0, (unsigned char)atoi(bc), /*Add b to rax, storing result in rax.*/ | |
0xC3, /*return. Return values are in rax in x86_64.*/ | |
}; | |
mprotect(lPage, sizeof(adds), PROT_READ|PROT_WRITE); | |
memcpy(lPage, adds, sizeof(adds)); | |
mprotect(lPage, sizeof(adds), PROT_READ|PROT_EXEC); | |
int (*ifunc)(void); | |
ifunc = (int (*)(void))lPage; | |
int r = ifunc(); | |
printf("In program-modified machine code, %c + %c = %i.\n", a, b, r); | |
return EXIT_SUCCESS; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment