Search code examples
cmagic-numbers

Check if valid executable or shell file by checking magic number in C


The magic numbers that you will recognize are shown in the following table.

Name of file type Magic number (bytes) at start of file:

-Executable ASCII characters DEL, ‘E’, ‘L’ and ‘F’

-Shell script ASCII characters ‘#’ and ‘!’

Standard file extensions take precedence even if they contain magic numbers. For example, if a file has extension .o then it is counted as an object file even though it also has the magic number of an executable file.

I have had no luck trying by implementing the code I have so far, it doesn't seem to check numbers and add to the total count of exe files. Is logic incorrect or a simpler way to check?

Any help is appreciated

int main (int argc, char** argv) {

 //

 const unsigned char magic1[4] = {0x7f, 0x45, 0x4c, 0x46}; //DEL, E, L, F

 char *endSlash = strrchr (argv[count], '/');
 endSlash = endSlash ? endSlash + 1: argv[count];
 char *endDot = strrchr (endSlash, '.');
 FILE *file;

 for (count = 1; count < argc; count++) {
     file  = fopen(argv[count], "r");

     if (strcmp(endSlash, "Makefile") == 0 || strcmp(endSlash, "makefile") == 0) {
          Mfile++;
     }
     else if (endDot == NULL) {
          O++;
     }
     else if (endDot[1] == 'c' && endDot[2] == 0) {
          Ccount++;
     }
     else if (endDot[1] == 'h' && endDot[2] == 0) {
         Hcount++;
     }
     else if (endDot[1] == 'o' && endDot[2] == 0) {
         Ocount++;
     }   
     else if (memcmp(file, magic1, sizeof(magic1)) == 0) { //is this actually checking and comparing bytes of magic1?
         Execount++;
    }
     else {
         O++;
    }
}
    printf("C source: %d\n", Ccount);
    printf("C header: %d\n", Hcount);
    printf("Object: %d\n", Ocount);
    printf("Make: %d\n", Mfile);
    printf("Executable: %d\n", Execount);
    printf("Shell: %d\n", Shcount);
    printf("Other: %d\n", O);

Solution

  • read 4 bytes of data from file and then do memcmp .. something like this

    char buf[4] ; 
    fread(buf,sizeof(char),4,file) ; 
    memcmp(buf,magic1,sizeof(magic1));