0

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)

Dhruv
  • 645
  • 9
  • 17
  • maybe you need to check whether `fopen()` returns a null pointer, which means it failed to open the file. also, make sure you got the right permission for the file. – KagurazakaKotori Nov 08 '19 at 04:33
  • just checked it out. It does indeed return a null pointer! – Dhruv Nov 08 '19 at 04:46

1 Answers1

1

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>

Dhruv
  • 645
  • 9
  • 17