通过检查 C 中的魔数(Magic Number)来检查可执行文件或 shell 文件是否有效

标签 c magic-numbers

下表显示了您将认识的魔数(Magic Number)。

文件类型名称文件开头的魔数(Magic Number)(字节):

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

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

标准文件扩展名优先,即使它们包含魔数(Magic Number)。例如,如果文件的扩展名是 .o,那么它会被计为 object 文件,即使 它还具有可执行文件的神奇数字。

我没有运气尝试实现到目前为止的代码,它似乎没有检查数字并添加到 exe 文件的总数中。逻辑是否不正确或者是否有更简单的检查方法?

感谢任何帮助

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);

最佳答案

从文件中读取4个字节的数据,然后执行memcmp ..类似这样的事情

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

关于通过检查 C 中的魔数(Magic Number)来检查可执行文件或 shell 文件是否有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46996466/

相关文章:

c++ - 模拟动态加载程序以修复共享库偏移量

winforms - 43679是魔数(Magic Number)吗?

java - 为什么在java中正则表达式的实现中使用魔数(Magic Number)?

c - ELLCC 嵌入式 LLVM 编译失败,某些 asm 指令针对 Thumb2 Cortex-M0

c - GCC - 编译时出错

c - 取消引用指向结构指针的指针

java - 摆脱 Java 中的魔法数字

c - 为什么 math.h 需要链接到 makefile 而不是 string.h?

c - 为内存数据结构寻找安全的魔数(Magic Number)

c - 从 .au 文件中读取魔数(Magic Number)