Skip to content

Instantly share code, notes, and snippets.

@mbcrawfo
Last active September 14, 2016 23:01
Show Gist options
  • Save mbcrawfo/1e20e0bcc888e60506e60214e300a2ca to your computer and use it in GitHub Desktop.
Save mbcrawfo/1e20e0bcc888e60506e60214e300a2ca to your computer and use it in GitHub Desktop.
Self modifying C program
#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;
}
@mbcrawfo
Copy link
Author

To use:

  1. Compile with gcc selfmod.c -o selfmod
  2. Run xxd -u ./selfmod | grep '2301 CDAB' to find the offset in the file of x.
  3. Update the variable offset as needed, and change the initial value of x if desired (but change only the variable values).
  4. Recompile with the same command, and run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment