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

  1. /*
  2. * If we are opening a Windows PE executable with an attached metakit
  3. * then we must check for the presence of an Authenticode certificate
  4. * and reduce the length of our mapped region accordingly
  5. */
  6.  
  7. static DWORD
  8. AuthenticodeOffset(LPBYTE pData, DWORD cbData)
  9. {
  10. if (pData[0] == 'M' && pData[1] == 'Z') /* IMAGE_DOS_SIGNATURE */
  11. {
  12. LPBYTE pNT = pData + *(LONG *)(pData + 0x3c); /* e_lfanew */
  13. if (pNT[0] == 'P' && pNT[1] == 'E' && pNT[2] == 0 && pNT[3] == 0)
  14. { /* IMAGE_NT_SIGNATURE */
  15. DWORD dwCheckSum = 0, dwDirectories = 0;
  16. LPBYTE pOpt = pNT + 0x18; /* OptionalHeader */
  17. LPDWORD pCertDir = NULL;
  18. if (pOpt[0] == 0x0b && pOpt[1] == 0x01) { /* IMAGE_NT_OPTIONAL_HDR_MAGIC */
  19. dwCheckSum = *(DWORD *)(pOpt + 0x40); /* Checksum */
  20. dwDirectories = *(DWORD *)(pOpt + 0x5c); /* NumberOfRvaAndSizes */
  21. if (dwDirectories > 4) { /* DataDirectory[] */
  22. pCertDir = (DWORD *)(pOpt + 0x60 + (4 * 8));
  23. }
  24. } else {
  25. dwCheckSum = *(DWORD *)(pOpt + 0x40); /* Checksum */
  26. dwDirectories = *(DWORD *)(pOpt + 0x6c); /* NumberOfRvaAndSizes */
  27. if (dwDirectories > 4) { /* DataDirectory[] */
  28. pCertDir = (DWORD *)(pOpt + 0x70 + (4 * 8));
  29. }
  30. }
  31.  
  32. if (pCertDir && pCertDir[1] > 0) {
  33. int n = 0;
  34. cbData = pCertDir[0];
  35. /* need to eliminate any zero padding - up to 8 bytes */
  36. while (pData[cbData - 16] != 0x80 && pData[cbData-1] == 0 && n < 16) {
  37. --cbData, ++n;
  38. }
  39. }
  40. }
  41. }
  42. return cbData;
  43. }
  44. #endif /* WIN32 */
  45.