Search code examples
cubuntugccdata-security

Segmentation Fault when editing code of executable file


Working on a Cyber Security Project:

When editing the code of a .exe file in c, it's possible to edit the code of a different exe file but not the exe file itself. It results in a segmentation fault.

Is there anyway to get around this ?

Code that produces segmentation fault:

sandbox.c

#include <stdio.h>

int main(){
FILE *fp2 = fopen("sandbox", "r+");
char cbuffer [100000];
int exe_len = fread(cbuffer, 1, sizeof(cbuffer), fp2);

fwrite (cbuffer , sizeof(char), sizeof(cbuffer), fp2);

static char a[10000] = "hello goodbye";
printf("%s\n", a );

return 0;
}

Code that doesn't error, also sandbox.c:

#include <stdio.h>

int main(){
FILE *fp2 = fopen("readme", "r+");
char cbuffer [100000];
int exe_len = fread(cbuffer, 1, sizeof(cbuffer), fp2);

fwrite (cbuffer , sizeof(char), sizeof(cbuffer), fp2);

static char a[10000] = "hello goodbye";
printf("%s\n", a );

return 0;
}

Error: Segmentation fault (core dumped)


Solution

  • Its not possible to open the exe file thats currently running in 'r+' mode. Thats why the when opening the second file of a different name, it produces a Seg Fault. Instead doing the following works:

    Saving the file with a different name and then using mv to update the name and chmod to make an executable file:

    FILE *fp3 = fopen("x.x","w+");
    fwrite (ebuffer , sizeof(char), sizeof(ebuffer), fp3);
    fclose(fp3);
    system("mv x.x readme; chmod +x readme");
    

    This ended up working out. This requires #include <stdlib.h>