Posted to tcl by apn at Sat Sep 06 16:04:23 GMT 2014view pretty

/*
 * If we are opening a Windows PE executable with an attached metakit
 * then we must check for the presence of an Authenticode certificate
 * and reduce the length of our mapped region accordingly
 */

static DWORD
AuthenticodeOffset(LPBYTE pData, DWORD cbData)
{
    if (pData[0] == 'M' && pData[1] == 'Z')              /* IMAGE_DOS_SIGNATURE */
    {
        LPBYTE pNT = pData + *(LONG *)(pData + 0x3c);    /* e_lfanew */
        if (pNT[0] == 'P' && pNT[1] == 'E' && pNT[2] == 0 && pNT[3] == 0)
        {                                                /* IMAGE_NT_SIGNATURE */
            DWORD dwCheckSum = 0, dwDirectories = 0;
            LPBYTE pOpt = pNT + 0x18;                    /* OptionalHeader */
            LPDWORD pCertDir = NULL;
            if (pOpt[0] == 0x0b && pOpt[1] == 0x01) {    /* IMAGE_NT_OPTIONAL_HDR_MAGIC */
                dwCheckSum = *(DWORD *)(pOpt + 0x40);    /* Checksum */
                dwDirectories = *(DWORD *)(pOpt + 0x5c); /* NumberOfRvaAndSizes */
                if (dwDirectories > 4) {                 /* DataDirectory[] */
                    pCertDir = (DWORD *)(pOpt + 0x60 + (4 * 8));
                }
            } else {
                dwCheckSum = *(DWORD *)(pOpt + 0x40);    /* Checksum */
                dwDirectories = *(DWORD *)(pOpt + 0x6c); /* NumberOfRvaAndSizes */
                if (dwDirectories > 4) {                 /* DataDirectory[] */
                    pCertDir = (DWORD *)(pOpt + 0x70 + (4 * 8));
                }
            }

            if (pCertDir && pCertDir[1] > 0) {
                int n = 0;
                cbData = pCertDir[0];
                /* need to eliminate any zero padding - up to 8 bytes */
                while (pData[cbData - 16] != 0x80 && pData[cbData-1] == 0 && n < 16) {
                    --cbData, ++n;
                }
            }
        }
    }
    return cbData;
}
#endif /* WIN32 */