Last active
August 29, 2015 14:02
-
-
Save FlyingJester/1f6d3464f391045c7a41 to your computer and use it in GitHub Desktop.
You can also modify actual instructions as well as data.
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 <cstdio> | |
| #include <sys/mman.h> | |
| #include <sys/types.h> | |
| #include <cstring> | |
| #include <cctype> | |
| #include <cstdlib> | |
| int main(int argc, const char * argv[]) | |
| { | |
| bool Add = true; | |
| 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); | |
| char t = '\0'; | |
| do{ | |
| t = getc(stdin); | |
| printf("Press 'a' to add, 's' to subtract.\n"); | |
| }while(t!='a' && t!='s'); | |
| if(t=='s') | |
| Add = false; | |
| 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 %s:\n", Add?"addition":"subtraction"); | |
| 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, (unsigned char)(Add?0xC0:0xE8), (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 %c = %i.\n", a, Add?'+':'-', b, r); | |
| return EXIT_SUCCESS; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment