大概原理就是读取一个文件的前面1024个字节,然后根据magic (/etc/magic 或者 /usr/share/misc/magic) 里对应的规则分析出文件头,并打印输出,下面列出了 linux ELF, windows可执行文件, qcow2文件。
linux:
# ELF
#0 string ELF ELF
0 string \177ELF ELF
>4 byte 1 32-bit
>4 byte 2 64-bit
>5 byte 1 LSB
>5 byte 2 MSB
>16 short 0 unknown type
>16 short 1 relocatable
>16 short 2 executable
>16 short 3 dynamic lib
>16 short 4 core file
>18 short 0 unknown machine
>18 short 1 WE32100
>18 short 2 SPARC
>18 short 3 80386
>18 short 4 M68000
>18 short 5 M88000
>20 long 1 Version 1
>36 long 1 MathCoPro/FPU/MAU Required
windows
# MS Windows executables are also valid MS-DOS executables
0 string MZ
>0x18 leshort <0x40 MZ executable (MS-DOS)
# skip the whole block below if it is not an extended executable
>0x18 leshort >0x3f
>>(0x3c.l) string PE\0\0 PE executable (MS-Windows)
>>(0x3c.l) string LX\0\0 LX executable (OS/2)
qcow2:
#--------------------------------------------------------------------
0 string/b QFI\xFB QEMU QCOW Image
>4 belong 3 (v3)
>>8 bequad >0 \b, has backing file
>>>(12.L) string >\0 (path %s) 这里的 L 表示读取这段数据,并以大端形式读取到新的offset
>>24 bequad x \b, %lld bytes
>>32 belong 1 \b, AES-encrypted
>4 default x (unknown version)
*/magic文件内容格式
文件中的每行都指定了一个规则测试去检验文件类型,这个规则由4个域指定:
offset:指定由文件起始的第几个byte开始检验。
type:要进行检验的数据类型,即由offset那个byte开始的那个数据类型是什么。具体有哪些数据类型,可以参才magic(5)。常用的数据类型有
byte:一个byte的值
short:两个byte的值
long:四个byte的值
string:字符串。
test:检验值。用于检验offset下的type是否是这个test值。使用C语言的数值或字符表示形式。
message:用于显示检验结果的信息显示
如果type为数值类型,那么其后面可添加&value,表示先与后面的test值进行‘与’操作,再进行比较。如果type为字符串类型,则其后可跟/[Bbc]*,/b表示忽略空格,/c表示忽略字母大小写。
如果test的值为数值类型,可以数值前添加=,<,>,&,^,~,分别表示相等、小于、大于、与操作、异或操作、取反操作。如果test的值为字符串类型,可以在其前添加=、<、>。