如何获取已签名的Windows可执行文件的签名段的长度

时间:2011-02-16 03:55:06

标签: windows winapi cryptography code-signing

我的程序与原始exe末尾的一些其他数据相结合。该程序将在运行程序时将其他数据提取到磁盘。

但是,在签署组合的可执行程序后,我的程序无法获得附加数据的正确偏移量。

我比较了签名的exe和原始的exe,签名信息附加在exe的末尾。所以我正在寻找一个Win32 API来从签名程序中获取签名段的长度。之后,我的程序可以找到组合数据的正确偏移量,然后正确提取它们。

有人能给我一个提示吗?

2 个答案:

答案 0 :(得分:1)

我找到了一个名为PEDump的工具(由Matt Pietrek为他的书编写),其中包含源代码,用于演示如何获取签名信息的大小。

以下是为了我的目的从PEDump中提取的代码,

// MakePtr is a macro that allows you to easily add to values (including
// pointers) together without dealing with C's pointer arithmetic.  It
// essentially treats the last two parameters as DWORDs.  The first
// parameter is used to typecast the result to the appropriate pointer type.
#define MakePtr( cast, ptr, addValue ) (cast)( (DWORD)(ptr) + (DWORD)(addValue))

// Names of the data directory elements that are defined
const char *ImageDirectoryNames[] = {
    "EXPORT", "IMPORT", "RESOURCE", "EXCEPTION", "SECURITY", "BASERELOC",
    "DEBUG", "COPYRIGHT", "GLOBALPTR", "TLS", "LOAD_CONFIG",
    "BOUND_IMPORT", "IAT",  // These two entries added for NT 3.51
    "DELAY_IMPORT" };       // This entry added in NT 5

#define NUMBER_IMAGE_DIRECTORY_ENTRYS \
    (sizeof(ImageDirectoryNames)/sizeof(char *))
        HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(getProgramFile()));
        HANDLE hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
        if ( hFileMapping == 0 )
        {
            printf("%s", "Couldn't open file mapping with CreateFileMapping()\n");
        } else {
            LPVOID lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
            if ( lpFileBase == 0 )
            {
                printf("%s", "Couldn't map view of file with MapViewOfFile()\n");
            } else {
                PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)lpFileBase;
                PIMAGE_FILE_HEADER pImgFileHdr = (PIMAGE_FILE_HEADER)lpFileBase;
                // it's EXE file
                if ( dosHeader->e_magic == IMAGE_DOS_SIGNATURE )
                {
                    PIMAGE_NT_HEADERS pNTHeader;
                    DWORD base = (DWORD)dosHeader;

                    pNTHeader = MakePtr( PIMAGE_NT_HEADERS, dosHeader, dosHeader->e_lfanew );

                    PIMAGE_OPTIONAL_HEADER optionalHeader = (PIMAGE_OPTIONAL_HEADER)&pNTHeader->OptionalHeader;
                    for ( int i=0; i < optionalHeader->NumberOfRvaAndSizes; i++)
                    {
                        // DataDirectory[4] represents security directory
                        if ( 4 == i ) {
                            signingLength = optionalHeader->DataDirectory[i].Size;
                            break;
                        }
                    }
                }
                UnmapViewOfFile(lpFileBase);
            }
            CloseHandle(hFileMapping);
        }

答案 1 :(得分:0)

在数据前后放置一条长签名行,然后只搜索预期偏移处的那些行。