I made a program which copies all contents of another c prog (binary file), writes them to another file and then executes it (execve()
) after adding execution permission to it (chmod()
).
Now I want to store all the contents of the file in an array inside the prog (I use hex representation) and then execute it. For this purpose I created another program in C which converts a file to hex representation here is the source code of these two programs:
#include <stdio.h> //program used for execution
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
unsigned char prog []= {}// thats the string i am planning to use so i can store the program
void FileCreate(const char *in) {
FILE *fp2 = fopen(in,"wb"); // create afile in binary form with write permission
if (fp2==NULL) { //error checking
fclose(in);
printf("file '%s' isn't here...\n", in);
exit(1);
}
int ch;
int i = 0;
for (i=0; i<sizeof(prog);++i) {
ch = prog[i];
fputc(ch, fp2);
}
fclose(fp2);
}
int main (int argc,char *argv[]){
if (argc != 2) {
fprintf(stderr, "Usage: %s [file_name]\n", argv[0]);
exit(1);
}
FileCreate(argv[1]);
char *cmd[] = {argv[1], NULL};
int err = chmod (argv[1], S_IXUSR);
if (err==-1){
perror ("Change mode");
exit(1);
}
err = execve (cmd[0], cmd,NULL);
if (err==-1){
perror ("Execute file");
exit(1);
}
return 0;
}
converter.c: program that converts file to hex reprentation
#include <stdio.h>
int main (void) {
unsigned char data[1024];
size_t numread, i;
while ((numread = read(0, data, 1024)) > 0) {
for (i = 0; i < numread; i++) {
if(data[i] != 0){ //remove null bytes
printf("0x%02x,", data[i]);
}
}
}
return 0;
}
As you can see in my converter program i remove the null bytes from the executable file. Is that correct or will the program fail to executes? My main issue is that I cant fit the whole program content inside an array. So how can I implement a program that stores the contents of another and then executes them?
- I am using Linux environment and
gcc
compiler. - These programs are done for educational purposes and they are not part of an assignment or an exercise.
- If you need any further information let me now