简体   繁体   English

通过检查C中的幻数来检查是否有效的可执行文件或外壳文件

[英]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. 例如,如果文件扩展名为.o则即使该文件也具有executable文件的幻数,该executable .o视为object文件。

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. 我没有运气尝试实现到目前为止的代码,它似乎没有检查数字并添加到exe文件的总数中。 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);

read 4 bytes of data from file and then do memcmp .. something like this 从文件读取4个字节的数据,然后执行memcmp ..像这样

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM