1 ;****************************************** 2 ;coded by Rrouned 3 ;****************************************** 4 ;测试子程序FileIsExe 判断是否为PE文件 5 ;****************************************** 6 7 .386 8 .model flat,stdcall 9 option casemap:none 10 11 include windows.inc 12 include user32.inc 13 includelib user32.lib 14 include kernel32.inc 15 includelib kernel32.lib 16 17 .DATA 18 szFilePath db "C:\1.EXE",0 19 szMsgText db "This is a PE file",0 20 szMsgCaption db "Caption",0 21 .DATA? 22 ;hFile DWORD 23 ;;----------------------------------------- 24 .CODE 25 FileIsExe Proc 26 LOCAL ReadBuffer ;文件读取缓冲区 27 LOCAL NumberOfBytesRW ;文件读写字节数 28 local hFile 29 push esi 30 ;invoke AddLine,addr szFilePath 31 invoke CreateFile,addr szFilePath,GENERIC_READ+GENERIC_WRITE,FILE_SHARE_READ,0,3,FILE_ATTRIBUTE_NORMAL,NULL 32 cmp eax,INVALID_HANDLE_VALUE ; 33 jz OpenFileErr 34 mov hFile,eax 35 mov ReadBuffer,0 36 invoke SetFilePointer,hFile,0h,NULL,FILE_BEGIN ;文件指针指向文件头 37 invoke ReadFile,hFile,ADDR ReadBuffer,2,ADDR NumberOfBytesRW,NULL 38 cmp ReadBuffer,'ZM' 39 JNZ FileIsNotExe 40 mov ReadBuffer,0 41 invoke SetFilePointer,hFile,3Ch,NULL,FILE_BEGIN;文件头指向xx字段,获取PE头指针 42 invoke ReadFile,hFile,ADDR ReadBuffer,2,ADDR NumberOfBytesRW,NULL 43 mov eax,ReadBuffer 44 mov esi,eax 45 mov ReadBuffer,0 46 invoke SetFilePointer,hFile,esi,NULL,FILE_BEGIN;指向PE头 47 invoke ReadFile,hFile,addr ReadBuffer,2,addr NumberOfBytesRW,NULL 48 cmp ReadBuffer,'EP' 49 jnz FileNotPe 50 mov eax,esi ;PE header 51 add eax,16h 52 mov ReadBuffer,0 53 invoke SetFilePointer,hFile,eax,NULL,FILE_BEGIN;指向Characteristics字段 54 invoke ReadFile,hFile,addr ReadBuffer,2,addr NumberOfBytesRW,NULL 55 mov eax,ReadBuffer 56 test ax,2000h 57 jnz FileMayBeDLL 58 ;invoke AddLine,addr M_FileIsExe 59 invoke CloseHandle,hFile 60 pop esi 61 xor eax,eax 62 inc eax 63 invoke MessageBox,0,addr szMsgText,addr szMsgCaption,0 64 ret 65 OpenFileErr: 66 ;invoke AddLine, 67 pop esi 68 xor eax,eax 69 ret 70 FileIsNotExe: 71 ;invoke Addline,ADDR M_FileIsNotExe 72 pop esi 73 xor eax,eax 74 ret 75 FileNotPe: 76 ;invoke 77 pop esi 78 xor eax,eax 79 ret 80 FileMayBeDLL: 81 ;invoke AddLine 82 pop esi 83 xor eax,eax 84 ret 85 FileIsExe ENDP 86 87 start: 88 invoke FileIsExe 89 end start
如果执行没错的话,弹出MSGBOX。
用到的函数如下:
BOOL ReadFile( HANDLE hFile, //文件的句柄 LPVOID lpBuffer, //用于保存读入数据的一个缓冲区 DWORD nNumberOfBytesToRead, //要读入的字节数 LPDWORD lpNumberOfBytesRead, //指向实际读取字节数的指针 LPOVERLAPPED lpOverlapped //如文件打开时指定了FILE_FLAG_OVERLAPPED,那么必须,用这个参数引用一个特殊的结构。 //该结构定义了一次异步读取操作。否则,应将这个参数设为NULL );
HANDLE CreateFile( LPCTSTR lpFileName, //指向文件名的指针 DWORD dwDesiredAccess, //访问模式(写/读) DWORD dwShareMode, //共享模式 LPSECURITY_ATTRIBUTES lpSecurityAttributes, //指向安全属性的指针 DWORD dwCreationDisposition, //如何创建 DWORD dwFlagsAndAttributes, //文件属性 HANDLE hTemplateFile //用于复制文件句柄 );