Last active
September 14, 2016 23:01
-
-
Save mbcrawfo/1e20e0bcc888e60506e60214e300a2ca to your computer and use it in GitHub Desktop.
Self modifying C program
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 <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/stat.h> | |
int main(int argc, char* argv[]) | |
{ | |
int x = 0xabcd0123; | |
printf("x = %d\n", x); | |
printf("Enter a new value: "); | |
int input; | |
scanf("%d", &input); | |
printf("Updating x to %d\n", input); | |
FILE* src = fopen("selfmod", "r"); | |
if (!src) | |
{ | |
printf("Couldn't open ./selfmod for reading\n"); | |
perror("Error:"); | |
return 1; | |
} | |
// get file size | |
fseek(src, 0, SEEK_END); | |
int size = ftell(src); | |
// read file contents | |
char* buffer = malloc(size); | |
fseek(src, 0, SEEK_SET); | |
fread(buffer, 1, size, src); | |
// ditch the existing file | |
fclose(src); | |
unlink("selfmod"); | |
// create a new file | |
FILE* dst = fopen("selfmod", "w"); | |
if (!dst) | |
{ | |
printf("Couldn't open ./selfmod for writing\n"); | |
perror("Error:"); | |
return 1; | |
} | |
// write the contents back out | |
fwrite(buffer, size, 1, dst); | |
free(buffer); | |
// move to the variable location | |
int offset = 0x000008e8; | |
fseek(dst, offset, SEEK_SET); | |
// and update it | |
fwrite(&input, sizeof(input), 1, dst); | |
fclose(dst); | |
// fix permissions on the new file (chmod 755) | |
chmod("selfmod", 493); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use:
gcc selfmod.c -o selfmod
xxd -u ./selfmod | grep '2301 CDAB'
to find the offset in the file ofx
.offset
as needed, and change the initial value ofx
if desired (but change only the variable values).