如何获取PE文件签名偏移量?

时间:2013-10-21 19:52:00

标签: c++ windows winapi portable-executable

我正在尝试解析PE文件,我将其加载到内存中,并将WinNT结构指针设置为适当的地址。但是,我无法对PE \ 0 \ 0签名进行愚蠢的检查,因为我有来自DOS头的错误偏移(一个字节太多)。因此,当我检查IMAGE_NT_HEADERS.Signature时,我从'E'开始收到4个字节。

#define SHOW_VAR(x)  std::cout << #x << " = " << x << std::endl
#define SHOW_HEX(x)  std::cout << std::showbase << std::hex << #x << " = " << x << std::endl; std::cout << std::dec

uintmax_t fileSize = boost::filesystem::file_size(m_filePath);
m_image.reset(new char[fileSize]);

boost::filesystem::ifstream file;
file.open(m_filePath, std::ios::in);
file.read(m_image.get(), fileSize);
file.close();

m_DOSHeader = reinterpret_cast<PIMAGE_DOS_HEADER>(m_image.get());
// --m_DOSHeader->e_lfanew; <---- THIS SOLVES THE PROBLEM BUT WHY?
m_NTHeaders = reinterpret_cast<PIMAGE_NT_HEADERS>(m_image.get() + m_DOSHeader->e_lfanew);

// DEBUG
SHOW_HEX(m_DOSHeader->e_lfanew);
for(int i = m_DOSHeader->e_lfanew - 5; i < m_DOSHeader->e_lfanew + 5; ++i)
{
    if(i == m_DOSHeader->e_lfanew)
        std::cout << "---> ";
    SHOW_HEX(m_image[i]);
}

// check if MZ
if(m_DOSHeader->e_magic != IMAGE_DOS_SIGNATURE)
    throw std::runtime_error("[PEFile] MZ signature not found");

// check if PE00
SHOW_VAR((char)m_NTHeaders->Signature);
if(m_NTHeaders->Signature != IMAGE_NT_SIGNATURE)
    throw std::runtime_error("[PEFile] PE00 signature not found");

DEBUG片段的结果是:

m_DOSHeader->e_lfanew = 0xf0
m_image[i] =  
m_image[i] =  
m_image[i] =  
m_image[i] =  
m_image[i] = P
---> m_image[i] = E
m_image[i] =  
m_image[i] =  
m_image[i] = L
m_image[i] = 
(char)m_NTHeaders->Signature = E
[ERROR] [PEFile] PE00 signature not found

我用pedump.me检查了它,m_DOSHeader-&gt; e_lfanew = 0xf0没问题。如果我必须减少这个偏移以获得实际正确的签名,我该怎么办?

我在64位Windows 8.1上使用VS2013 RC,但我检查过我已经设置了_WIN32。 32位和64位exe文件都会出现此错误。

1 个答案:

答案 0 :(得分:3)

file.open(m_filepath, std::ios::in | std::ios::binary);

如果不以二进制模式打开,则在处理输入时,std :: fstream可以添加或删除其他字符。