DxeImageVerificationLib.c 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962
  1. /** @file
  2. Implement image verification services for secure boot service
  3. Caution: This file requires additional review when modified.
  4. This library will have external input - PE/COFF image.
  5. This external input must be validated carefully to avoid security issue like
  6. buffer overflow, integer overflow.
  7. DxeImageVerificationLibImageRead() function will make sure the PE/COFF image content
  8. read is within the image buffer.
  9. DxeImageVerificationHandler(), HashPeImageByType(), HashPeImage() function will accept
  10. untrusted PE/COFF image and validate its data structure within this image buffer before use.
  11. Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.<BR>
  12. (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
  13. SPDX-License-Identifier: BSD-2-Clause-Patent
  14. **/
  15. #include "DxeImageVerificationLib.h"
  16. //
  17. // Caution: This is used by a function which may receive untrusted input.
  18. // These global variables hold PE/COFF image data, and they should be validated before use.
  19. //
  20. EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader;
  21. UINT32 mPeCoffHeaderOffset;
  22. EFI_GUID mCertType;
  23. //
  24. // Information on current PE/COFF image
  25. //
  26. UINTN mImageSize;
  27. UINT8 *mImageBase = NULL;
  28. UINT8 mImageDigest[MAX_DIGEST_SIZE];
  29. UINTN mImageDigestSize;
  30. //
  31. // Notify string for authorization UI.
  32. //
  33. CHAR16 mNotifyString1[MAX_NOTIFY_STRING_LEN] = L"Image verification pass but not found in authorized database!";
  34. CHAR16 mNotifyString2[MAX_NOTIFY_STRING_LEN] = L"Launch this image anyway? (Yes/Defer/No)";
  35. //
  36. // Public Exponent of RSA Key.
  37. //
  38. CONST UINT8 mRsaE[] = { 0x01, 0x00, 0x01 };
  39. //
  40. // OID ASN.1 Value for Hash Algorithms
  41. //
  42. UINT8 mHashOidValue[] = {
  43. 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1
  44. 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224
  45. 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256
  46. 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384
  47. 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512
  48. };
  49. HASH_TABLE mHash[] = {
  50. { L"SHA1", 20, &mHashOidValue[0], 5, Sha1GetContextSize, Sha1Init, Sha1Update, Sha1Final },
  51. { L"SHA224", 28, &mHashOidValue[5], 9, NULL, NULL, NULL, NULL },
  52. { L"SHA256", 32, &mHashOidValue[14], 9, Sha256GetContextSize, Sha256Init, Sha256Update, Sha256Final},
  53. { L"SHA384", 48, &mHashOidValue[23], 9, Sha384GetContextSize, Sha384Init, Sha384Update, Sha384Final},
  54. { L"SHA512", 64, &mHashOidValue[32], 9, Sha512GetContextSize, Sha512Init, Sha512Update, Sha512Final}
  55. };
  56. EFI_STRING mHashTypeStr;
  57. /**
  58. SecureBoot Hook for processing image verification.
  59. @param[in] VariableName Name of Variable to be found.
  60. @param[in] VendorGuid Variable vendor GUID.
  61. @param[in] DataSize Size of Data found. If size is less than the
  62. data, this value contains the required size.
  63. @param[in] Data Data pointer.
  64. **/
  65. VOID
  66. EFIAPI
  67. SecureBootHook (
  68. IN CHAR16 *VariableName,
  69. IN EFI_GUID *VendorGuid,
  70. IN UINTN DataSize,
  71. IN VOID *Data
  72. );
  73. /**
  74. Reads contents of a PE/COFF image in memory buffer.
  75. Caution: This function may receive untrusted input.
  76. PE/COFF image is external input, so this function will make sure the PE/COFF image content
  77. read is within the image buffer.
  78. @param FileHandle Pointer to the file handle to read the PE/COFF image.
  79. @param FileOffset Offset into the PE/COFF image to begin the read operation.
  80. @param ReadSize On input, the size in bytes of the requested read operation.
  81. On output, the number of bytes actually read.
  82. @param Buffer Output buffer that contains the data read from the PE/COFF image.
  83. @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
  84. **/
  85. EFI_STATUS
  86. EFIAPI
  87. DxeImageVerificationLibImageRead (
  88. IN VOID *FileHandle,
  89. IN UINTN FileOffset,
  90. IN OUT UINTN *ReadSize,
  91. OUT VOID *Buffer
  92. )
  93. {
  94. UINTN EndPosition;
  95. if (FileHandle == NULL || ReadSize == NULL || Buffer == NULL) {
  96. return EFI_INVALID_PARAMETER;
  97. }
  98. if (MAX_ADDRESS - FileOffset < *ReadSize) {
  99. return EFI_INVALID_PARAMETER;
  100. }
  101. EndPosition = FileOffset + *ReadSize;
  102. if (EndPosition > mImageSize) {
  103. *ReadSize = (UINT32)(mImageSize - FileOffset);
  104. }
  105. if (FileOffset >= mImageSize) {
  106. *ReadSize = 0;
  107. }
  108. CopyMem (Buffer, (UINT8 *)((UINTN) FileHandle + FileOffset), *ReadSize);
  109. return EFI_SUCCESS;
  110. }
  111. /**
  112. Get the image type.
  113. @param[in] File This is a pointer to the device path of the file that is
  114. being dispatched.
  115. @return UINT32 Image Type
  116. **/
  117. UINT32
  118. GetImageType (
  119. IN CONST EFI_DEVICE_PATH_PROTOCOL *File
  120. )
  121. {
  122. EFI_STATUS Status;
  123. EFI_HANDLE DeviceHandle;
  124. EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
  125. EFI_BLOCK_IO_PROTOCOL *BlockIo;
  126. if (File == NULL) {
  127. return IMAGE_UNKNOWN;
  128. }
  129. //
  130. // First check to see if File is from a Firmware Volume
  131. //
  132. DeviceHandle = NULL;
  133. TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
  134. Status = gBS->LocateDevicePath (
  135. &gEfiFirmwareVolume2ProtocolGuid,
  136. &TempDevicePath,
  137. &DeviceHandle
  138. );
  139. if (!EFI_ERROR (Status)) {
  140. Status = gBS->OpenProtocol (
  141. DeviceHandle,
  142. &gEfiFirmwareVolume2ProtocolGuid,
  143. NULL,
  144. NULL,
  145. NULL,
  146. EFI_OPEN_PROTOCOL_TEST_PROTOCOL
  147. );
  148. if (!EFI_ERROR (Status)) {
  149. return IMAGE_FROM_FV;
  150. }
  151. }
  152. //
  153. // Next check to see if File is from a Block I/O device
  154. //
  155. DeviceHandle = NULL;
  156. TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
  157. Status = gBS->LocateDevicePath (
  158. &gEfiBlockIoProtocolGuid,
  159. &TempDevicePath,
  160. &DeviceHandle
  161. );
  162. if (!EFI_ERROR (Status)) {
  163. BlockIo = NULL;
  164. Status = gBS->OpenProtocol (
  165. DeviceHandle,
  166. &gEfiBlockIoProtocolGuid,
  167. (VOID **) &BlockIo,
  168. NULL,
  169. NULL,
  170. EFI_OPEN_PROTOCOL_GET_PROTOCOL
  171. );
  172. if (!EFI_ERROR (Status) && BlockIo != NULL) {
  173. if (BlockIo->Media != NULL) {
  174. if (BlockIo->Media->RemovableMedia) {
  175. //
  176. // Block I/O is present and specifies the media is removable
  177. //
  178. return IMAGE_FROM_REMOVABLE_MEDIA;
  179. } else {
  180. //
  181. // Block I/O is present and specifies the media is not removable
  182. //
  183. return IMAGE_FROM_FIXED_MEDIA;
  184. }
  185. }
  186. }
  187. }
  188. //
  189. // File is not in a Firmware Volume or on a Block I/O device, so check to see if
  190. // the device path supports the Simple File System Protocol.
  191. //
  192. DeviceHandle = NULL;
  193. TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
  194. Status = gBS->LocateDevicePath (
  195. &gEfiSimpleFileSystemProtocolGuid,
  196. &TempDevicePath,
  197. &DeviceHandle
  198. );
  199. if (!EFI_ERROR (Status)) {
  200. //
  201. // Simple File System is present without Block I/O, so assume media is fixed.
  202. //
  203. return IMAGE_FROM_FIXED_MEDIA;
  204. }
  205. //
  206. // File is not from an FV, Block I/O or Simple File System, so the only options
  207. // left are a PCI Option ROM and a Load File Protocol such as a PXE Boot from a NIC.
  208. //
  209. TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
  210. while (!IsDevicePathEndType (TempDevicePath)) {
  211. switch (DevicePathType (TempDevicePath)) {
  212. case MEDIA_DEVICE_PATH:
  213. if (DevicePathSubType (TempDevicePath) == MEDIA_RELATIVE_OFFSET_RANGE_DP) {
  214. return IMAGE_FROM_OPTION_ROM;
  215. }
  216. break;
  217. case MESSAGING_DEVICE_PATH:
  218. if (DevicePathSubType(TempDevicePath) == MSG_MAC_ADDR_DP) {
  219. return IMAGE_FROM_REMOVABLE_MEDIA;
  220. }
  221. break;
  222. default:
  223. break;
  224. }
  225. TempDevicePath = NextDevicePathNode (TempDevicePath);
  226. }
  227. return IMAGE_UNKNOWN;
  228. }
  229. /**
  230. Calculate hash of Pe/Coff image based on the authenticode image hashing in
  231. PE/COFF Specification 8.0 Appendix A
  232. Caution: This function may receive untrusted input.
  233. PE/COFF image is external input, so this function will validate its data structure
  234. within this image buffer before use.
  235. Notes: PE/COFF image has been checked by BasePeCoffLib PeCoffLoaderGetImageInfo() in
  236. its caller function DxeImageVerificationHandler().
  237. @param[in] HashAlg Hash algorithm type.
  238. @retval TRUE Successfully hash image.
  239. @retval FALSE Fail in hash image.
  240. **/
  241. BOOLEAN
  242. HashPeImage (
  243. IN UINT32 HashAlg
  244. )
  245. {
  246. BOOLEAN Status;
  247. EFI_IMAGE_SECTION_HEADER *Section;
  248. VOID *HashCtx;
  249. UINTN CtxSize;
  250. UINT8 *HashBase;
  251. UINTN HashSize;
  252. UINTN SumOfBytesHashed;
  253. EFI_IMAGE_SECTION_HEADER *SectionHeader;
  254. UINTN Index;
  255. UINTN Pos;
  256. UINT32 CertSize;
  257. UINT32 NumberOfRvaAndSizes;
  258. HashCtx = NULL;
  259. SectionHeader = NULL;
  260. Status = FALSE;
  261. if ((HashAlg >= HASHALG_MAX)) {
  262. return FALSE;
  263. }
  264. //
  265. // Initialize context of hash.
  266. //
  267. ZeroMem (mImageDigest, MAX_DIGEST_SIZE);
  268. switch (HashAlg) {
  269. case HASHALG_SHA1:
  270. mImageDigestSize = SHA1_DIGEST_SIZE;
  271. mCertType = gEfiCertSha1Guid;
  272. break;
  273. case HASHALG_SHA256:
  274. mImageDigestSize = SHA256_DIGEST_SIZE;
  275. mCertType = gEfiCertSha256Guid;
  276. break;
  277. case HASHALG_SHA384:
  278. mImageDigestSize = SHA384_DIGEST_SIZE;
  279. mCertType = gEfiCertSha384Guid;
  280. break;
  281. case HASHALG_SHA512:
  282. mImageDigestSize = SHA512_DIGEST_SIZE;
  283. mCertType = gEfiCertSha512Guid;
  284. break;
  285. default:
  286. return FALSE;
  287. }
  288. mHashTypeStr = mHash[HashAlg].Name;
  289. CtxSize = mHash[HashAlg].GetContextSize();
  290. HashCtx = AllocatePool (CtxSize);
  291. if (HashCtx == NULL) {
  292. return FALSE;
  293. }
  294. // 1. Load the image header into memory.
  295. // 2. Initialize a SHA hash context.
  296. Status = mHash[HashAlg].HashInit(HashCtx);
  297. if (!Status) {
  298. goto Done;
  299. }
  300. //
  301. // Measuring PE/COFF Image Header;
  302. // But CheckSum field and SECURITY data directory (certificate) are excluded
  303. //
  304. //
  305. // 3. Calculate the distance from the base of the image header to the image checksum address.
  306. // 4. Hash the image header from its base to beginning of the image checksum.
  307. //
  308. HashBase = mImageBase;
  309. if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  310. //
  311. // Use PE32 offset.
  312. //
  313. HashSize = (UINTN) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - (UINTN) HashBase;
  314. NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
  315. } else if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
  316. //
  317. // Use PE32+ offset.
  318. //
  319. HashSize = (UINTN) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - (UINTN) HashBase;
  320. NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
  321. } else {
  322. //
  323. // Invalid header magic number.
  324. //
  325. Status = FALSE;
  326. goto Done;
  327. }
  328. Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
  329. if (!Status) {
  330. goto Done;
  331. }
  332. //
  333. // 5. Skip over the image checksum (it occupies a single ULONG).
  334. //
  335. if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
  336. //
  337. // 6. Since there is no Cert Directory in optional header, hash everything
  338. // from the end of the checksum to the end of image header.
  339. //
  340. if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  341. //
  342. // Use PE32 offset.
  343. //
  344. HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
  345. HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase);
  346. } else {
  347. //
  348. // Use PE32+ offset.
  349. //
  350. HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
  351. HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase);
  352. }
  353. if (HashSize != 0) {
  354. Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
  355. if (!Status) {
  356. goto Done;
  357. }
  358. }
  359. } else {
  360. //
  361. // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
  362. //
  363. if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  364. //
  365. // Use PE32 offset.
  366. //
  367. HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
  368. HashSize = (UINTN) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase;
  369. } else {
  370. //
  371. // Use PE32+ offset.
  372. //
  373. HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
  374. HashSize = (UINTN) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase;
  375. }
  376. if (HashSize != 0) {
  377. Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
  378. if (!Status) {
  379. goto Done;
  380. }
  381. }
  382. //
  383. // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
  384. // 9. Hash everything from the end of the Cert Directory to the end of image header.
  385. //
  386. if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  387. //
  388. // Use PE32 offset
  389. //
  390. HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
  391. HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase);
  392. } else {
  393. //
  394. // Use PE32+ offset.
  395. //
  396. HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
  397. HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase);
  398. }
  399. if (HashSize != 0) {
  400. Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
  401. if (!Status) {
  402. goto Done;
  403. }
  404. }
  405. }
  406. //
  407. // 10. Set the SUM_OF_BYTES_HASHED to the size of the header.
  408. //
  409. if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  410. //
  411. // Use PE32 offset.
  412. //
  413. SumOfBytesHashed = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders;
  414. } else {
  415. //
  416. // Use PE32+ offset
  417. //
  418. SumOfBytesHashed = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders;
  419. }
  420. Section = (EFI_IMAGE_SECTION_HEADER *) (
  421. mImageBase +
  422. mPeCoffHeaderOffset +
  423. sizeof (UINT32) +
  424. sizeof (EFI_IMAGE_FILE_HEADER) +
  425. mNtHeader.Pe32->FileHeader.SizeOfOptionalHeader
  426. );
  427. //
  428. // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
  429. // structures in the image. The 'NumberOfSections' field of the image
  430. // header indicates how big the table should be. Do not include any
  431. // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
  432. //
  433. SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * mNtHeader.Pe32->FileHeader.NumberOfSections);
  434. if (SectionHeader == NULL) {
  435. Status = FALSE;
  436. goto Done;
  437. }
  438. //
  439. // 12. Using the 'PointerToRawData' in the referenced section headers as
  440. // a key, arrange the elements in the table in ascending order. In other
  441. // words, sort the section headers according to the disk-file offset of
  442. // the section.
  443. //
  444. for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) {
  445. Pos = Index;
  446. while ((Pos > 0) && (Section->PointerToRawData < SectionHeader[Pos - 1].PointerToRawData)) {
  447. CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof (EFI_IMAGE_SECTION_HEADER));
  448. Pos--;
  449. }
  450. CopyMem (&SectionHeader[Pos], Section, sizeof (EFI_IMAGE_SECTION_HEADER));
  451. Section += 1;
  452. }
  453. //
  454. // 13. Walk through the sorted table, bring the corresponding section
  455. // into memory, and hash the entire section (using the 'SizeOfRawData'
  456. // field in the section header to determine the amount of data to hash).
  457. // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
  458. // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
  459. //
  460. for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) {
  461. Section = &SectionHeader[Index];
  462. if (Section->SizeOfRawData == 0) {
  463. continue;
  464. }
  465. HashBase = mImageBase + Section->PointerToRawData;
  466. HashSize = (UINTN) Section->SizeOfRawData;
  467. Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
  468. if (!Status) {
  469. goto Done;
  470. }
  471. SumOfBytesHashed += HashSize;
  472. }
  473. //
  474. // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
  475. // data in the file that needs to be added to the hash. This data begins
  476. // at file offset SUM_OF_BYTES_HASHED and its length is:
  477. // FileSize - (CertDirectory->Size)
  478. //
  479. if (mImageSize > SumOfBytesHashed) {
  480. HashBase = mImageBase + SumOfBytesHashed;
  481. if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
  482. CertSize = 0;
  483. } else {
  484. if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  485. //
  486. // Use PE32 offset.
  487. //
  488. CertSize = mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
  489. } else {
  490. //
  491. // Use PE32+ offset.
  492. //
  493. CertSize = mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
  494. }
  495. }
  496. if (mImageSize > CertSize + SumOfBytesHashed) {
  497. HashSize = (UINTN) (mImageSize - CertSize - SumOfBytesHashed);
  498. Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
  499. if (!Status) {
  500. goto Done;
  501. }
  502. } else if (mImageSize < CertSize + SumOfBytesHashed) {
  503. Status = FALSE;
  504. goto Done;
  505. }
  506. }
  507. Status = mHash[HashAlg].HashFinal(HashCtx, mImageDigest);
  508. Done:
  509. if (HashCtx != NULL) {
  510. FreePool (HashCtx);
  511. }
  512. if (SectionHeader != NULL) {
  513. FreePool (SectionHeader);
  514. }
  515. return Status;
  516. }
  517. /**
  518. Recognize the Hash algorithm in PE/COFF Authenticode and calculate hash of
  519. Pe/Coff image based on the authenticode image hashing in PE/COFF Specification
  520. 8.0 Appendix A
  521. Caution: This function may receive untrusted input.
  522. PE/COFF image is external input, so this function will validate its data structure
  523. within this image buffer before use.
  524. @param[in] AuthData Pointer to the Authenticode Signature retrieved from signed image.
  525. @param[in] AuthDataSize Size of the Authenticode Signature in bytes.
  526. @retval EFI_UNSUPPORTED Hash algorithm is not supported.
  527. @retval EFI_SUCCESS Hash successfully.
  528. **/
  529. EFI_STATUS
  530. HashPeImageByType (
  531. IN UINT8 *AuthData,
  532. IN UINTN AuthDataSize
  533. )
  534. {
  535. UINT8 Index;
  536. for (Index = 0; Index < HASHALG_MAX; Index++) {
  537. //
  538. // Check the Hash algorithm in PE/COFF Authenticode.
  539. // According to PKCS#7 Definition:
  540. // SignedData ::= SEQUENCE {
  541. // version Version,
  542. // digestAlgorithms DigestAlgorithmIdentifiers,
  543. // contentInfo ContentInfo,
  544. // .... }
  545. // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm in PE/COFF hashing
  546. // This field has the fixed offset (+32) in final Authenticode ASN.1 data.
  547. // Fixed offset (+32) is calculated based on two bytes of length encoding.
  548. //
  549. if ((*(AuthData + 1) & TWO_BYTE_ENCODE) != TWO_BYTE_ENCODE) {
  550. //
  551. // Only support two bytes of Long Form of Length Encoding.
  552. //
  553. continue;
  554. }
  555. if (AuthDataSize < 32 + mHash[Index].OidLength) {
  556. return EFI_UNSUPPORTED;
  557. }
  558. if (CompareMem (AuthData + 32, mHash[Index].OidValue, mHash[Index].OidLength) == 0) {
  559. break;
  560. }
  561. }
  562. if (Index == HASHALG_MAX) {
  563. return EFI_UNSUPPORTED;
  564. }
  565. //
  566. // HASH PE Image based on Hash algorithm in PE/COFF Authenticode.
  567. //
  568. if (!HashPeImage(Index)) {
  569. return EFI_UNSUPPORTED;
  570. }
  571. return EFI_SUCCESS;
  572. }
  573. /**
  574. Returns the size of a given image execution info table in bytes.
  575. This function returns the size, in bytes, of the image execution info table specified by
  576. ImageExeInfoTable. If ImageExeInfoTable is NULL, then 0 is returned.
  577. @param ImageExeInfoTable A pointer to a image execution info table structure.
  578. @retval 0 If ImageExeInfoTable is NULL.
  579. @retval Others The size of a image execution info table in bytes.
  580. **/
  581. UINTN
  582. GetImageExeInfoTableSize (
  583. EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable
  584. )
  585. {
  586. UINTN Index;
  587. EFI_IMAGE_EXECUTION_INFO *ImageExeInfoItem;
  588. UINTN TotalSize;
  589. if (ImageExeInfoTable == NULL) {
  590. return 0;
  591. }
  592. ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoTable + sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE));
  593. TotalSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
  594. for (Index = 0; Index < ImageExeInfoTable->NumberOfImages; Index++) {
  595. TotalSize += ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize);
  596. ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoItem + ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize));
  597. }
  598. return TotalSize;
  599. }
  600. /**
  601. Create an Image Execution Information Table entry and add it to system configuration table.
  602. @param[in] Action Describes the action taken by the firmware regarding this image.
  603. @param[in] Name Input a null-terminated, user-friendly name.
  604. @param[in] DevicePath Input device path pointer.
  605. @param[in] Signature Input signature info in EFI_SIGNATURE_LIST data structure.
  606. @param[in] SignatureSize Size of signature.
  607. **/
  608. VOID
  609. AddImageExeInfo (
  610. IN EFI_IMAGE_EXECUTION_ACTION Action,
  611. IN CHAR16 *Name OPTIONAL,
  612. IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath,
  613. IN EFI_SIGNATURE_LIST *Signature OPTIONAL,
  614. IN UINTN SignatureSize
  615. )
  616. {
  617. EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable;
  618. EFI_IMAGE_EXECUTION_INFO_TABLE *NewImageExeInfoTable;
  619. EFI_IMAGE_EXECUTION_INFO *ImageExeInfoEntry;
  620. UINTN ImageExeInfoTableSize;
  621. UINTN NewImageExeInfoEntrySize;
  622. UINTN NameStringLen;
  623. UINTN DevicePathSize;
  624. CHAR16 *NameStr;
  625. ImageExeInfoTable = NULL;
  626. NewImageExeInfoTable = NULL;
  627. ImageExeInfoEntry = NULL;
  628. NameStringLen = 0;
  629. NameStr = NULL;
  630. if (DevicePath == NULL) {
  631. return ;
  632. }
  633. if (Name != NULL) {
  634. NameStringLen = StrSize (Name);
  635. } else {
  636. NameStringLen = sizeof (CHAR16);
  637. }
  638. EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **) &ImageExeInfoTable);
  639. if (ImageExeInfoTable != NULL) {
  640. //
  641. // The table has been found!
  642. // We must enlarge the table to accommodate the new exe info entry.
  643. //
  644. ImageExeInfoTableSize = GetImageExeInfoTableSize (ImageExeInfoTable);
  645. } else {
  646. //
  647. // Not Found!
  648. // We should create a new table to append to the configuration table.
  649. //
  650. ImageExeInfoTableSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
  651. }
  652. DevicePathSize = GetDevicePathSize (DevicePath);
  653. //
  654. // Signature size can be odd. Pad after signature to ensure next EXECUTION_INFO entry align
  655. //
  656. NewImageExeInfoEntrySize = sizeof (EFI_IMAGE_EXECUTION_INFO) + NameStringLen + DevicePathSize + SignatureSize;
  657. NewImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *) AllocateRuntimePool (ImageExeInfoTableSize + NewImageExeInfoEntrySize);
  658. if (NewImageExeInfoTable == NULL) {
  659. return ;
  660. }
  661. if (ImageExeInfoTable != NULL) {
  662. CopyMem (NewImageExeInfoTable, ImageExeInfoTable, ImageExeInfoTableSize);
  663. } else {
  664. NewImageExeInfoTable->NumberOfImages = 0;
  665. }
  666. NewImageExeInfoTable->NumberOfImages++;
  667. ImageExeInfoEntry = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) NewImageExeInfoTable + ImageExeInfoTableSize);
  668. //
  669. // Update new item's information.
  670. //
  671. WriteUnaligned32 ((UINT32 *) ImageExeInfoEntry, Action);
  672. WriteUnaligned32 ((UINT32 *) ((UINT8 *) ImageExeInfoEntry + sizeof (EFI_IMAGE_EXECUTION_ACTION)), (UINT32) NewImageExeInfoEntrySize);
  673. NameStr = (CHAR16 *)(ImageExeInfoEntry + 1);
  674. if (Name != NULL) {
  675. CopyMem ((UINT8 *) NameStr, Name, NameStringLen);
  676. } else {
  677. ZeroMem ((UINT8 *) NameStr, sizeof (CHAR16));
  678. }
  679. CopyMem (
  680. (UINT8 *) NameStr + NameStringLen,
  681. DevicePath,
  682. DevicePathSize
  683. );
  684. if (Signature != NULL) {
  685. CopyMem (
  686. (UINT8 *) NameStr + NameStringLen + DevicePathSize,
  687. Signature,
  688. SignatureSize
  689. );
  690. }
  691. //
  692. // Update/replace the image execution table.
  693. //
  694. gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *) NewImageExeInfoTable);
  695. //
  696. // Free Old table data!
  697. //
  698. if (ImageExeInfoTable != NULL) {
  699. FreePool (ImageExeInfoTable);
  700. }
  701. }
  702. /**
  703. Check whether the hash of an given X.509 certificate is in forbidden database (DBX).
  704. @param[in] Certificate Pointer to X.509 Certificate that is searched for.
  705. @param[in] CertSize Size of X.509 Certificate.
  706. @param[in] SignatureList Pointer to the Signature List in forbidden database.
  707. @param[in] SignatureListSize Size of Signature List.
  708. @param[out] RevocationTime Return the time that the certificate was revoked.
  709. @return TRUE The certificate hash is found in the forbidden database.
  710. @return FALSE The certificate hash is not found in the forbidden database.
  711. **/
  712. BOOLEAN
  713. IsCertHashFoundInDatabase (
  714. IN UINT8 *Certificate,
  715. IN UINTN CertSize,
  716. IN EFI_SIGNATURE_LIST *SignatureList,
  717. IN UINTN SignatureListSize,
  718. OUT EFI_TIME *RevocationTime
  719. )
  720. {
  721. BOOLEAN IsFound;
  722. BOOLEAN Status;
  723. EFI_SIGNATURE_LIST *DbxList;
  724. UINTN DbxSize;
  725. EFI_SIGNATURE_DATA *CertHash;
  726. UINTN CertHashCount;
  727. UINTN Index;
  728. UINT32 HashAlg;
  729. VOID *HashCtx;
  730. UINT8 CertDigest[MAX_DIGEST_SIZE];
  731. UINT8 *DbxCertHash;
  732. UINTN SiglistHeaderSize;
  733. UINT8 *TBSCert;
  734. UINTN TBSCertSize;
  735. IsFound = FALSE;
  736. DbxList = SignatureList;
  737. DbxSize = SignatureListSize;
  738. HashCtx = NULL;
  739. HashAlg = HASHALG_MAX;
  740. if ((RevocationTime == NULL) || (DbxList == NULL)) {
  741. return FALSE;
  742. }
  743. //
  744. // Retrieve the TBSCertificate from the X.509 Certificate.
  745. //
  746. if (!X509GetTBSCert (Certificate, CertSize, &TBSCert, &TBSCertSize)) {
  747. return FALSE;
  748. }
  749. while ((DbxSize > 0) && (SignatureListSize >= DbxList->SignatureListSize)) {
  750. //
  751. // Determine Hash Algorithm of Certificate in the forbidden database.
  752. //
  753. if (CompareGuid (&DbxList->SignatureType, &gEfiCertX509Sha256Guid)) {
  754. HashAlg = HASHALG_SHA256;
  755. } else if (CompareGuid (&DbxList->SignatureType, &gEfiCertX509Sha384Guid)) {
  756. HashAlg = HASHALG_SHA384;
  757. } else if (CompareGuid (&DbxList->SignatureType, &gEfiCertX509Sha512Guid)) {
  758. HashAlg = HASHALG_SHA512;
  759. } else {
  760. DbxSize -= DbxList->SignatureListSize;
  761. DbxList = (EFI_SIGNATURE_LIST *) ((UINT8 *) DbxList + DbxList->SignatureListSize);
  762. continue;
  763. }
  764. //
  765. // Calculate the hash value of current TBSCertificate for comparision.
  766. //
  767. if (mHash[HashAlg].GetContextSize == NULL) {
  768. goto Done;
  769. }
  770. ZeroMem (CertDigest, MAX_DIGEST_SIZE);
  771. HashCtx = AllocatePool (mHash[HashAlg].GetContextSize ());
  772. if (HashCtx == NULL) {
  773. goto Done;
  774. }
  775. Status = mHash[HashAlg].HashInit (HashCtx);
  776. if (!Status) {
  777. goto Done;
  778. }
  779. Status = mHash[HashAlg].HashUpdate (HashCtx, TBSCert, TBSCertSize);
  780. if (!Status) {
  781. goto Done;
  782. }
  783. Status = mHash[HashAlg].HashFinal (HashCtx, CertDigest);
  784. if (!Status) {
  785. goto Done;
  786. }
  787. SiglistHeaderSize = sizeof (EFI_SIGNATURE_LIST) + DbxList->SignatureHeaderSize;
  788. CertHash = (EFI_SIGNATURE_DATA *) ((UINT8 *) DbxList + SiglistHeaderSize);
  789. CertHashCount = (DbxList->SignatureListSize - SiglistHeaderSize) / DbxList->SignatureSize;
  790. for (Index = 0; Index < CertHashCount; Index++) {
  791. //
  792. // Iterate each Signature Data Node within this CertList for verify.
  793. //
  794. DbxCertHash = CertHash->SignatureData;
  795. if (CompareMem (DbxCertHash, CertDigest, mHash[HashAlg].DigestLength) == 0) {
  796. //
  797. // Hash of Certificate is found in forbidden database.
  798. //
  799. IsFound = TRUE;
  800. //
  801. // Return the revocation time.
  802. //
  803. CopyMem (RevocationTime, (EFI_TIME *)(DbxCertHash + mHash[HashAlg].DigestLength), sizeof (EFI_TIME));
  804. goto Done;
  805. }
  806. CertHash = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertHash + DbxList->SignatureSize);
  807. }
  808. DbxSize -= DbxList->SignatureListSize;
  809. DbxList = (EFI_SIGNATURE_LIST *) ((UINT8 *) DbxList + DbxList->SignatureListSize);
  810. }
  811. Done:
  812. if (HashCtx != NULL) {
  813. FreePool (HashCtx);
  814. }
  815. return IsFound;
  816. }
  817. /**
  818. Check whether signature is in specified database.
  819. @param[in] VariableName Name of database variable that is searched in.
  820. @param[in] Signature Pointer to signature that is searched for.
  821. @param[in] CertType Pointer to hash algorithm.
  822. @param[in] SignatureSize Size of Signature.
  823. @return TRUE Found the signature in the variable database.
  824. @return FALSE Not found the signature in the variable database.
  825. **/
  826. BOOLEAN
  827. IsSignatureFoundInDatabase (
  828. IN CHAR16 *VariableName,
  829. IN UINT8 *Signature,
  830. IN EFI_GUID *CertType,
  831. IN UINTN SignatureSize
  832. )
  833. {
  834. EFI_STATUS Status;
  835. EFI_SIGNATURE_LIST *CertList;
  836. EFI_SIGNATURE_DATA *Cert;
  837. UINTN DataSize;
  838. UINT8 *Data;
  839. UINTN Index;
  840. UINTN CertCount;
  841. BOOLEAN IsFound;
  842. //
  843. // Read signature database variable.
  844. //
  845. IsFound = FALSE;
  846. Data = NULL;
  847. DataSize = 0;
  848. Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL);
  849. if (Status != EFI_BUFFER_TOO_SMALL) {
  850. return FALSE;
  851. }
  852. Data = (UINT8 *) AllocateZeroPool (DataSize);
  853. if (Data == NULL) {
  854. return FALSE;
  855. }
  856. Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, Data);
  857. if (EFI_ERROR (Status)) {
  858. goto Done;
  859. }
  860. //
  861. // Enumerate all signature data in SigDB to check if signature exists for executable.
  862. //
  863. CertList = (EFI_SIGNATURE_LIST *) Data;
  864. while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) {
  865. CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
  866. Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
  867. if ((CertList->SignatureSize == sizeof(EFI_SIGNATURE_DATA) - 1 + SignatureSize) && (CompareGuid(&CertList->SignatureType, CertType))) {
  868. for (Index = 0; Index < CertCount; Index++) {
  869. if (CompareMem (Cert->SignatureData, Signature, SignatureSize) == 0) {
  870. //
  871. // Find the signature in database.
  872. //
  873. IsFound = TRUE;
  874. //
  875. // Entries in UEFI_IMAGE_SECURITY_DATABASE that are used to validate image should be measured
  876. //
  877. if (StrCmp(VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) {
  878. SecureBootHook (VariableName, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, Cert);
  879. }
  880. break;
  881. }
  882. Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
  883. }
  884. if (IsFound) {
  885. break;
  886. }
  887. }
  888. DataSize -= CertList->SignatureListSize;
  889. CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
  890. }
  891. Done:
  892. if (Data != NULL) {
  893. FreePool (Data);
  894. }
  895. return IsFound;
  896. }
  897. /**
  898. Check whether the timestamp is valid by comparing the signing time and the revocation time.
  899. @param SigningTime A pointer to the signing time.
  900. @param RevocationTime A pointer to the revocation time.
  901. @retval TRUE The SigningTime is not later than the RevocationTime.
  902. @retval FALSE The SigningTime is later than the RevocationTime.
  903. **/
  904. BOOLEAN
  905. IsValidSignatureByTimestamp (
  906. IN EFI_TIME *SigningTime,
  907. IN EFI_TIME *RevocationTime
  908. )
  909. {
  910. if (SigningTime->Year != RevocationTime->Year) {
  911. return (BOOLEAN) (SigningTime->Year < RevocationTime->Year);
  912. } else if (SigningTime->Month != RevocationTime->Month) {
  913. return (BOOLEAN) (SigningTime->Month < RevocationTime->Month);
  914. } else if (SigningTime->Day != RevocationTime->Day) {
  915. return (BOOLEAN) (SigningTime->Day < RevocationTime->Day);
  916. } else if (SigningTime->Hour != RevocationTime->Hour) {
  917. return (BOOLEAN) (SigningTime->Hour < RevocationTime->Hour);
  918. } else if (SigningTime->Minute != RevocationTime->Minute) {
  919. return (BOOLEAN) (SigningTime->Minute < RevocationTime->Minute);
  920. }
  921. return (BOOLEAN) (SigningTime->Second <= RevocationTime->Second);
  922. }
  923. /**
  924. Check if the given time value is zero.
  925. @param[in] Time Pointer of a time value.
  926. @retval TRUE The Time is Zero.
  927. @retval FALSE The Time is not Zero.
  928. **/
  929. BOOLEAN
  930. IsTimeZero (
  931. IN EFI_TIME *Time
  932. )
  933. {
  934. if ((Time->Year == 0) && (Time->Month == 0) && (Time->Day == 0) &&
  935. (Time->Hour == 0) && (Time->Minute == 0) && (Time->Second == 0)) {
  936. return TRUE;
  937. }
  938. return FALSE;
  939. }
  940. /**
  941. Check whether the timestamp signature is valid and the signing time is also earlier than
  942. the revocation time.
  943. @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
  944. @param[in] AuthDataSize Size of the Authenticode signature in bytes.
  945. @param[in] RevocationTime The time that the certificate was revoked.
  946. @retval TRUE Timestamp signature is valid and signing time is no later than the
  947. revocation time.
  948. @retval FALSE Timestamp signature is not valid or the signing time is later than the
  949. revocation time.
  950. **/
  951. BOOLEAN
  952. PassTimestampCheck (
  953. IN UINT8 *AuthData,
  954. IN UINTN AuthDataSize,
  955. IN EFI_TIME *RevocationTime
  956. )
  957. {
  958. EFI_STATUS Status;
  959. BOOLEAN VerifyStatus;
  960. EFI_SIGNATURE_LIST *CertList;
  961. EFI_SIGNATURE_DATA *Cert;
  962. UINT8 *DbtData;
  963. UINTN DbtDataSize;
  964. UINT8 *RootCert;
  965. UINTN RootCertSize;
  966. UINTN Index;
  967. UINTN CertCount;
  968. EFI_TIME SigningTime;
  969. //
  970. // Variable Initialization
  971. //
  972. VerifyStatus = FALSE;
  973. DbtData = NULL;
  974. CertList = NULL;
  975. Cert = NULL;
  976. RootCert = NULL;
  977. RootCertSize = 0;
  978. //
  979. // If RevocationTime is zero, the certificate shall be considered to always be revoked.
  980. //
  981. if (IsTimeZero (RevocationTime)) {
  982. return FALSE;
  983. }
  984. //
  985. // RevocationTime is non-zero, the certificate should be considered to be revoked from that time and onwards.
  986. // Using the dbt to get the trusted TSA certificates.
  987. //
  988. DbtDataSize = 0;
  989. Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, NULL, &DbtDataSize, NULL);
  990. if (Status != EFI_BUFFER_TOO_SMALL) {
  991. goto Done;
  992. }
  993. DbtData = (UINT8 *) AllocateZeroPool (DbtDataSize);
  994. if (DbtData == NULL) {
  995. goto Done;
  996. }
  997. Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, NULL, &DbtDataSize, (VOID *) DbtData);
  998. if (EFI_ERROR (Status)) {
  999. goto Done;
  1000. }
  1001. CertList = (EFI_SIGNATURE_LIST *) DbtData;
  1002. while ((DbtDataSize > 0) && (DbtDataSize >= CertList->SignatureListSize)) {
  1003. if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
  1004. Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
  1005. CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
  1006. for (Index = 0; Index < CertCount; Index++) {
  1007. //
  1008. // Iterate each Signature Data Node within this CertList for verify.
  1009. //
  1010. RootCert = Cert->SignatureData;
  1011. RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID);
  1012. //
  1013. // Get the signing time if the timestamp signature is valid.
  1014. //
  1015. if (ImageTimestampVerify (AuthData, AuthDataSize, RootCert, RootCertSize, &SigningTime)) {
  1016. //
  1017. // The signer signature is valid only when the signing time is earlier than revocation time.
  1018. //
  1019. if (IsValidSignatureByTimestamp (&SigningTime, RevocationTime)) {
  1020. VerifyStatus = TRUE;
  1021. goto Done;
  1022. }
  1023. }
  1024. Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
  1025. }
  1026. }
  1027. DbtDataSize -= CertList->SignatureListSize;
  1028. CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
  1029. }
  1030. Done:
  1031. if (DbtData != NULL) {
  1032. FreePool (DbtData);
  1033. }
  1034. return VerifyStatus;
  1035. }
  1036. /**
  1037. Check whether the image signature is forbidden by the forbidden database (dbx).
  1038. The image is forbidden to load if any certificates for signing are revoked before signing time.
  1039. @param[in] AuthData Pointer to the Authenticode signature retrieved from the signed image.
  1040. @param[in] AuthDataSize Size of the Authenticode signature in bytes.
  1041. @retval TRUE Image is forbidden by dbx.
  1042. @retval FALSE Image is not forbidden by dbx.
  1043. **/
  1044. BOOLEAN
  1045. IsForbiddenByDbx (
  1046. IN UINT8 *AuthData,
  1047. IN UINTN AuthDataSize
  1048. )
  1049. {
  1050. EFI_STATUS Status;
  1051. BOOLEAN IsForbidden;
  1052. UINT8 *Data;
  1053. UINTN DataSize;
  1054. EFI_SIGNATURE_LIST *CertList;
  1055. UINTN CertListSize;
  1056. EFI_SIGNATURE_DATA *CertData;
  1057. UINT8 *RootCert;
  1058. UINTN RootCertSize;
  1059. UINTN CertCount;
  1060. UINTN Index;
  1061. UINT8 *CertBuffer;
  1062. UINTN BufferLength;
  1063. UINT8 *TrustedCert;
  1064. UINTN TrustedCertLength;
  1065. UINT8 CertNumber;
  1066. UINT8 *CertPtr;
  1067. UINT8 *Cert;
  1068. UINTN CertSize;
  1069. EFI_TIME RevocationTime;
  1070. //
  1071. // Variable Initialization
  1072. //
  1073. IsForbidden = FALSE;
  1074. Data = NULL;
  1075. CertList = NULL;
  1076. CertData = NULL;
  1077. RootCert = NULL;
  1078. RootCertSize = 0;
  1079. Cert = NULL;
  1080. CertBuffer = NULL;
  1081. BufferLength = 0;
  1082. TrustedCert = NULL;
  1083. TrustedCertLength = 0;
  1084. //
  1085. // The image will not be forbidden if dbx can't be got.
  1086. //
  1087. DataSize = 0;
  1088. Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL);
  1089. if (Status != EFI_BUFFER_TOO_SMALL) {
  1090. return IsForbidden;
  1091. }
  1092. Data = (UINT8 *) AllocateZeroPool (DataSize);
  1093. if (Data == NULL) {
  1094. return IsForbidden;
  1095. }
  1096. Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, (VOID *) Data);
  1097. if (EFI_ERROR (Status)) {
  1098. return IsForbidden;
  1099. }
  1100. //
  1101. // Verify image signature with RAW X509 certificates in DBX database.
  1102. // If passed, the image will be forbidden.
  1103. //
  1104. CertList = (EFI_SIGNATURE_LIST *) Data;
  1105. CertListSize = DataSize;
  1106. while ((CertListSize > 0) && (CertListSize >= CertList->SignatureListSize)) {
  1107. if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
  1108. CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
  1109. CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
  1110. for (Index = 0; Index < CertCount; Index++) {
  1111. //
  1112. // Iterate each Signature Data Node within this CertList for verify.
  1113. //
  1114. RootCert = CertData->SignatureData;
  1115. RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID);
  1116. //
  1117. // Call AuthenticodeVerify library to Verify Authenticode struct.
  1118. //
  1119. IsForbidden = AuthenticodeVerify (
  1120. AuthData,
  1121. AuthDataSize,
  1122. RootCert,
  1123. RootCertSize,
  1124. mImageDigest,
  1125. mImageDigestSize
  1126. );
  1127. if (IsForbidden) {
  1128. DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature is forbidden by DBX.\n"));
  1129. goto Done;
  1130. }
  1131. CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertData + CertList->SignatureSize);
  1132. }
  1133. }
  1134. CertListSize -= CertList->SignatureListSize;
  1135. CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
  1136. }
  1137. //
  1138. // Check X.509 Certificate Hash & Possible Timestamp.
  1139. //
  1140. //
  1141. // Retrieve the certificate stack from AuthData
  1142. // The output CertStack format will be:
  1143. // UINT8 CertNumber;
  1144. // UINT32 Cert1Length;
  1145. // UINT8 Cert1[];
  1146. // UINT32 Cert2Length;
  1147. // UINT8 Cert2[];
  1148. // ...
  1149. // UINT32 CertnLength;
  1150. // UINT8 Certn[];
  1151. //
  1152. Pkcs7GetSigners (AuthData, AuthDataSize, &CertBuffer, &BufferLength, &TrustedCert, &TrustedCertLength);
  1153. if ((BufferLength == 0) || (CertBuffer == NULL)) {
  1154. IsForbidden = TRUE;
  1155. goto Done;
  1156. }
  1157. //
  1158. // Check if any hash of certificates embedded in AuthData is in the forbidden database.
  1159. //
  1160. CertNumber = (UINT8) (*CertBuffer);
  1161. CertPtr = CertBuffer + 1;
  1162. for (Index = 0; Index < CertNumber; Index++) {
  1163. CertSize = (UINTN) ReadUnaligned32 ((UINT32 *)CertPtr);
  1164. Cert = (UINT8 *)CertPtr + sizeof (UINT32);
  1165. //
  1166. // Advance CertPtr to the next cert in image signer's cert list
  1167. //
  1168. CertPtr = CertPtr + sizeof (UINT32) + CertSize;
  1169. if (IsCertHashFoundInDatabase (Cert, CertSize, (EFI_SIGNATURE_LIST *)Data, DataSize, &RevocationTime)) {
  1170. //
  1171. // Check the timestamp signature and signing time to determine if the image can be trusted.
  1172. //
  1173. IsForbidden = TRUE;
  1174. if (PassTimestampCheck (AuthData, AuthDataSize, &RevocationTime)) {
  1175. IsForbidden = FALSE;
  1176. //
  1177. // Pass DBT check. Continue to check other certs in image signer's cert list against DBX, DBT
  1178. //
  1179. continue;
  1180. }
  1181. DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature failed the timestamp check.\n"));
  1182. goto Done;
  1183. }
  1184. }
  1185. Done:
  1186. if (Data != NULL) {
  1187. FreePool (Data);
  1188. }
  1189. Pkcs7FreeSigners (CertBuffer);
  1190. Pkcs7FreeSigners (TrustedCert);
  1191. return IsForbidden;
  1192. }
  1193. /**
  1194. Check whether the image signature can be verified by the trusted certificates in DB database.
  1195. @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
  1196. @param[in] AuthDataSize Size of the Authenticode signature in bytes.
  1197. @retval TRUE Image passed verification using certificate in db.
  1198. @retval FALSE Image didn't pass verification using certificate in db.
  1199. **/
  1200. BOOLEAN
  1201. IsAllowedByDb (
  1202. IN UINT8 *AuthData,
  1203. IN UINTN AuthDataSize
  1204. )
  1205. {
  1206. EFI_STATUS Status;
  1207. BOOLEAN VerifyStatus;
  1208. EFI_SIGNATURE_LIST *CertList;
  1209. EFI_SIGNATURE_DATA *CertData;
  1210. UINTN DataSize;
  1211. UINT8 *Data;
  1212. UINT8 *RootCert;
  1213. UINTN RootCertSize;
  1214. UINTN Index;
  1215. UINTN CertCount;
  1216. UINTN DbxDataSize;
  1217. UINT8 *DbxData;
  1218. EFI_TIME RevocationTime;
  1219. Data = NULL;
  1220. CertList = NULL;
  1221. CertData = NULL;
  1222. RootCert = NULL;
  1223. DbxData = NULL;
  1224. RootCertSize = 0;
  1225. VerifyStatus = FALSE;
  1226. DataSize = 0;
  1227. Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL);
  1228. if (Status == EFI_BUFFER_TOO_SMALL) {
  1229. Data = (UINT8 *) AllocateZeroPool (DataSize);
  1230. if (Data == NULL) {
  1231. return VerifyStatus;
  1232. }
  1233. Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, (VOID *) Data);
  1234. if (EFI_ERROR (Status)) {
  1235. goto Done;
  1236. }
  1237. //
  1238. // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
  1239. //
  1240. CertList = (EFI_SIGNATURE_LIST *) Data;
  1241. while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) {
  1242. if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
  1243. CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
  1244. CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
  1245. for (Index = 0; Index < CertCount; Index++) {
  1246. //
  1247. // Iterate each Signature Data Node within this CertList for verify.
  1248. //
  1249. RootCert = CertData->SignatureData;
  1250. RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID);
  1251. //
  1252. // Call AuthenticodeVerify library to Verify Authenticode struct.
  1253. //
  1254. VerifyStatus = AuthenticodeVerify (
  1255. AuthData,
  1256. AuthDataSize,
  1257. RootCert,
  1258. RootCertSize,
  1259. mImageDigest,
  1260. mImageDigestSize
  1261. );
  1262. if (VerifyStatus) {
  1263. //
  1264. // Here We still need to check if this RootCert's Hash is revoked
  1265. //
  1266. Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DbxDataSize, NULL);
  1267. if (Status == EFI_BUFFER_TOO_SMALL) {
  1268. goto Done;
  1269. }
  1270. DbxData = (UINT8 *) AllocateZeroPool (DbxDataSize);
  1271. if (DbxData == NULL) {
  1272. goto Done;
  1273. }
  1274. Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DbxDataSize, (VOID *) DbxData);
  1275. if (EFI_ERROR (Status)) {
  1276. goto Done;
  1277. }
  1278. if (IsCertHashFoundInDatabase (RootCert, RootCertSize, (EFI_SIGNATURE_LIST *)DbxData, DbxDataSize, &RevocationTime)) {
  1279. //
  1280. // Check the timestamp signature and signing time to determine if the RootCert can be trusted.
  1281. //
  1282. VerifyStatus = PassTimestampCheck (AuthData, AuthDataSize, &RevocationTime);
  1283. if (!VerifyStatus) {
  1284. DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed and signature is accepted by DB, but its root cert failed the timestamp check.\n"));
  1285. }
  1286. }
  1287. goto Done;
  1288. }
  1289. CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertData + CertList->SignatureSize);
  1290. }
  1291. }
  1292. DataSize -= CertList->SignatureListSize;
  1293. CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
  1294. }
  1295. }
  1296. Done:
  1297. if (VerifyStatus) {
  1298. SecureBootHook (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, CertData);
  1299. }
  1300. if (Data != NULL) {
  1301. FreePool (Data);
  1302. }
  1303. if (DbxData != NULL) {
  1304. FreePool (DbxData);
  1305. }
  1306. return VerifyStatus;
  1307. }
  1308. /**
  1309. Provide verification service for signed images, which include both signature validation
  1310. and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
  1311. MSFT Authenticode type signatures are supported.
  1312. In this implementation, only verify external executables when in USER MODE.
  1313. Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
  1314. The image verification policy is:
  1315. If the image is signed,
  1316. At least one valid signature or at least one hash value of the image must match a record
  1317. in the security database "db", and no valid signature nor any hash value of the image may
  1318. be reflected in the security database "dbx".
  1319. Otherwise, the image is not signed,
  1320. The SHA256 hash value of the image must match a record in the security database "db", and
  1321. not be reflected in the security data base "dbx".
  1322. Caution: This function may receive untrusted input.
  1323. PE/COFF image is external input, so this function will validate its data structure
  1324. within this image buffer before use.
  1325. @param[in] AuthenticationStatus
  1326. This is the authentication status returned from the security
  1327. measurement services for the input file.
  1328. @param[in] File This is a pointer to the device path of the file that is
  1329. being dispatched. This will optionally be used for logging.
  1330. @param[in] FileBuffer File buffer matches the input file device path.
  1331. @param[in] FileSize Size of File buffer matches the input file device path.
  1332. @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
  1333. @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
  1334. FileBuffer did authenticate, and the platform policy dictates
  1335. that the DXE Foundation may use the file.
  1336. @retval EFI_SUCCESS The device path specified by NULL device path DevicePath
  1337. and non-NULL FileBuffer did authenticate, and the platform
  1338. policy dictates that the DXE Foundation may execute the image in
  1339. FileBuffer.
  1340. @retval EFI_OUT_RESOURCE Fail to allocate memory.
  1341. @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
  1342. the platform policy dictates that File should be placed
  1343. in the untrusted state. The image has been added to the file
  1344. execution table.
  1345. @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not
  1346. authenticate, and the platform policy dictates that the DXE
  1347. Foundation many not use File.
  1348. **/
  1349. EFI_STATUS
  1350. EFIAPI
  1351. DxeImageVerificationHandler (
  1352. IN UINT32 AuthenticationStatus,
  1353. IN CONST EFI_DEVICE_PATH_PROTOCOL *File,
  1354. IN VOID *FileBuffer,
  1355. IN UINTN FileSize,
  1356. IN BOOLEAN BootPolicy
  1357. )
  1358. {
  1359. EFI_STATUS Status;
  1360. EFI_IMAGE_DOS_HEADER *DosHdr;
  1361. EFI_STATUS VerifyStatus;
  1362. EFI_SIGNATURE_LIST *SignatureList;
  1363. UINTN SignatureListSize;
  1364. EFI_SIGNATURE_DATA *Signature;
  1365. EFI_IMAGE_EXECUTION_ACTION Action;
  1366. WIN_CERTIFICATE *WinCertificate;
  1367. UINT32 Policy;
  1368. UINT8 *SecureBoot;
  1369. PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
  1370. UINT32 NumberOfRvaAndSizes;
  1371. WIN_CERTIFICATE_EFI_PKCS *PkcsCertData;
  1372. WIN_CERTIFICATE_UEFI_GUID *WinCertUefiGuid;
  1373. UINT8 *AuthData;
  1374. UINTN AuthDataSize;
  1375. EFI_IMAGE_DATA_DIRECTORY *SecDataDir;
  1376. UINT32 OffSet;
  1377. CHAR16 *NameStr;
  1378. SignatureList = NULL;
  1379. SignatureListSize = 0;
  1380. WinCertificate = NULL;
  1381. SecDataDir = NULL;
  1382. PkcsCertData = NULL;
  1383. Action = EFI_IMAGE_EXECUTION_AUTH_UNTESTED;
  1384. Status = EFI_ACCESS_DENIED;
  1385. VerifyStatus = EFI_ACCESS_DENIED;
  1386. //
  1387. // Check the image type and get policy setting.
  1388. //
  1389. switch (GetImageType (File)) {
  1390. case IMAGE_FROM_FV:
  1391. Policy = ALWAYS_EXECUTE;
  1392. break;
  1393. case IMAGE_FROM_OPTION_ROM:
  1394. Policy = PcdGet32 (PcdOptionRomImageVerificationPolicy);
  1395. break;
  1396. case IMAGE_FROM_REMOVABLE_MEDIA:
  1397. Policy = PcdGet32 (PcdRemovableMediaImageVerificationPolicy);
  1398. break;
  1399. case IMAGE_FROM_FIXED_MEDIA:
  1400. Policy = PcdGet32 (PcdFixedMediaImageVerificationPolicy);
  1401. break;
  1402. default:
  1403. Policy = DENY_EXECUTE_ON_SECURITY_VIOLATION;
  1404. break;
  1405. }
  1406. //
  1407. // If policy is always/never execute, return directly.
  1408. //
  1409. if (Policy == ALWAYS_EXECUTE) {
  1410. return EFI_SUCCESS;
  1411. } else if (Policy == NEVER_EXECUTE) {
  1412. return EFI_ACCESS_DENIED;
  1413. }
  1414. //
  1415. // The policy QUERY_USER_ON_SECURITY_VIOLATION and ALLOW_EXECUTE_ON_SECURITY_VIOLATION
  1416. // violates the UEFI spec and has been removed.
  1417. //
  1418. ASSERT (Policy != QUERY_USER_ON_SECURITY_VIOLATION && Policy != ALLOW_EXECUTE_ON_SECURITY_VIOLATION);
  1419. if (Policy == QUERY_USER_ON_SECURITY_VIOLATION || Policy == ALLOW_EXECUTE_ON_SECURITY_VIOLATION) {
  1420. CpuDeadLoop ();
  1421. }
  1422. GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME, (VOID**)&SecureBoot, NULL);
  1423. //
  1424. // Skip verification if SecureBoot variable doesn't exist.
  1425. //
  1426. if (SecureBoot == NULL) {
  1427. return EFI_SUCCESS;
  1428. }
  1429. //
  1430. // Skip verification if SecureBoot is disabled but not AuditMode
  1431. //
  1432. if (*SecureBoot == SECURE_BOOT_MODE_DISABLE) {
  1433. FreePool (SecureBoot);
  1434. return EFI_SUCCESS;
  1435. }
  1436. FreePool (SecureBoot);
  1437. //
  1438. // Read the Dos header.
  1439. //
  1440. if (FileBuffer == NULL) {
  1441. return EFI_INVALID_PARAMETER;
  1442. }
  1443. mImageBase = (UINT8 *) FileBuffer;
  1444. mImageSize = FileSize;
  1445. ZeroMem (&ImageContext, sizeof (ImageContext));
  1446. ImageContext.Handle = (VOID *) FileBuffer;
  1447. ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) DxeImageVerificationLibImageRead;
  1448. //
  1449. // Get information about the image being loaded
  1450. //
  1451. Status = PeCoffLoaderGetImageInfo (&ImageContext);
  1452. if (EFI_ERROR (Status)) {
  1453. //
  1454. // The information can't be got from the invalid PeImage
  1455. //
  1456. DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: PeImage invalid. Cannot retrieve image information.\n"));
  1457. goto Done;
  1458. }
  1459. Status = EFI_ACCESS_DENIED;
  1460. DosHdr = (EFI_IMAGE_DOS_HEADER *) mImageBase;
  1461. if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
  1462. //
  1463. // DOS image header is present,
  1464. // so read the PE header after the DOS image header.
  1465. //
  1466. mPeCoffHeaderOffset = DosHdr->e_lfanew;
  1467. } else {
  1468. mPeCoffHeaderOffset = 0;
  1469. }
  1470. //
  1471. // Check PE/COFF image.
  1472. //
  1473. mNtHeader.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) (mImageBase + mPeCoffHeaderOffset);
  1474. if (mNtHeader.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
  1475. //
  1476. // It is not a valid Pe/Coff file.
  1477. //
  1478. DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Not a valid PE/COFF image.\n"));
  1479. goto Done;
  1480. }
  1481. if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  1482. //
  1483. // Use PE32 offset.
  1484. //
  1485. NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
  1486. if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
  1487. SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
  1488. }
  1489. } else {
  1490. //
  1491. // Use PE32+ offset.
  1492. //
  1493. NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
  1494. if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
  1495. SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
  1496. }
  1497. }
  1498. //
  1499. // Start Image Validation.
  1500. //
  1501. if (SecDataDir == NULL || SecDataDir->Size == 0) {
  1502. //
  1503. // This image is not signed. The SHA256 hash value of the image must match a record in the security database "db",
  1504. // and not be reflected in the security data base "dbx".
  1505. //
  1506. if (!HashPeImage (HASHALG_SHA256)) {
  1507. DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Failed to hash this image using %s.\n", mHashTypeStr));
  1508. goto Done;
  1509. }
  1510. if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) {
  1511. //
  1512. // Image Hash is in forbidden database (DBX).
  1513. //
  1514. DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is not signed and %s hash of image is forbidden by DBX.\n", mHashTypeStr));
  1515. goto Done;
  1516. }
  1517. if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) {
  1518. //
  1519. // Image Hash is in allowed database (DB).
  1520. //
  1521. return EFI_SUCCESS;
  1522. }
  1523. //
  1524. // Image Hash is not found in both forbidden and allowed database.
  1525. //
  1526. DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is not signed and %s hash of image is not found in DB/DBX.\n", mHashTypeStr));
  1527. goto Done;
  1528. }
  1529. //
  1530. // Verify the signature of the image, multiple signatures are allowed as per PE/COFF Section 4.7
  1531. // "Attribute Certificate Table".
  1532. // The first certificate starts at offset (SecDataDir->VirtualAddress) from the start of the file.
  1533. //
  1534. for (OffSet = SecDataDir->VirtualAddress;
  1535. OffSet < (SecDataDir->VirtualAddress + SecDataDir->Size);
  1536. OffSet += (WinCertificate->dwLength + ALIGN_SIZE (WinCertificate->dwLength))) {
  1537. WinCertificate = (WIN_CERTIFICATE *) (mImageBase + OffSet);
  1538. if ((SecDataDir->VirtualAddress + SecDataDir->Size - OffSet) <= sizeof (WIN_CERTIFICATE) ||
  1539. (SecDataDir->VirtualAddress + SecDataDir->Size - OffSet) < WinCertificate->dwLength) {
  1540. break;
  1541. }
  1542. //
  1543. // Verify the image's Authenticode signature, only DER-encoded PKCS#7 signed data is supported.
  1544. //
  1545. if (WinCertificate->wCertificateType == WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
  1546. //
  1547. // The certificate is formatted as WIN_CERTIFICATE_EFI_PKCS which is described in the
  1548. // Authenticode specification.
  1549. //
  1550. PkcsCertData = (WIN_CERTIFICATE_EFI_PKCS *) WinCertificate;
  1551. if (PkcsCertData->Hdr.dwLength <= sizeof (PkcsCertData->Hdr)) {
  1552. break;
  1553. }
  1554. AuthData = PkcsCertData->CertData;
  1555. AuthDataSize = PkcsCertData->Hdr.dwLength - sizeof(PkcsCertData->Hdr);
  1556. } else if (WinCertificate->wCertificateType == WIN_CERT_TYPE_EFI_GUID) {
  1557. //
  1558. // The certificate is formatted as WIN_CERTIFICATE_UEFI_GUID which is described in UEFI Spec.
  1559. //
  1560. WinCertUefiGuid = (WIN_CERTIFICATE_UEFI_GUID *) WinCertificate;
  1561. if (WinCertUefiGuid->Hdr.dwLength <= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData)) {
  1562. break;
  1563. }
  1564. if (!CompareGuid (&WinCertUefiGuid->CertType, &gEfiCertPkcs7Guid)) {
  1565. continue;
  1566. }
  1567. AuthData = WinCertUefiGuid->CertData;
  1568. AuthDataSize = WinCertUefiGuid->Hdr.dwLength - OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData);
  1569. } else {
  1570. if (WinCertificate->dwLength < sizeof (WIN_CERTIFICATE)) {
  1571. break;
  1572. }
  1573. continue;
  1574. }
  1575. Status = HashPeImageByType (AuthData, AuthDataSize);
  1576. if (EFI_ERROR (Status)) {
  1577. continue;
  1578. }
  1579. //
  1580. // Check the digital signature against the revoked certificate in forbidden database (dbx).
  1581. //
  1582. if (IsForbiddenByDbx (AuthData, AuthDataSize)) {
  1583. Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED;
  1584. VerifyStatus = EFI_ACCESS_DENIED;
  1585. break;
  1586. }
  1587. //
  1588. // Check the digital signature against the valid certificate in allowed database (db).
  1589. //
  1590. if (EFI_ERROR (VerifyStatus)) {
  1591. if (IsAllowedByDb (AuthData, AuthDataSize)) {
  1592. VerifyStatus = EFI_SUCCESS;
  1593. }
  1594. }
  1595. //
  1596. // Check the image's hash value.
  1597. //
  1598. if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) {
  1599. Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND;
  1600. DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but %s hash of image is found in DBX.\n", mHashTypeStr));
  1601. VerifyStatus = EFI_ACCESS_DENIED;
  1602. break;
  1603. } else if (EFI_ERROR (VerifyStatus)) {
  1604. if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) {
  1605. VerifyStatus = EFI_SUCCESS;
  1606. } else {
  1607. DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature is not allowed by DB and %s hash of image is not found in DB/DBX.\n", mHashTypeStr));
  1608. }
  1609. }
  1610. }
  1611. if (OffSet != (SecDataDir->VirtualAddress + SecDataDir->Size)) {
  1612. //
  1613. // The Size in Certificate Table or the attribute certificate table is corrupted.
  1614. //
  1615. VerifyStatus = EFI_ACCESS_DENIED;
  1616. }
  1617. if (!EFI_ERROR (VerifyStatus)) {
  1618. return EFI_SUCCESS;
  1619. } else {
  1620. Status = EFI_ACCESS_DENIED;
  1621. if (Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED || Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND) {
  1622. //
  1623. // Get image hash value as signature of executable.
  1624. //
  1625. SignatureListSize = sizeof (EFI_SIGNATURE_LIST) + sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize;
  1626. SignatureList = (EFI_SIGNATURE_LIST *) AllocateZeroPool (SignatureListSize);
  1627. if (SignatureList == NULL) {
  1628. Status = EFI_OUT_OF_RESOURCES;
  1629. goto Done;
  1630. }
  1631. SignatureList->SignatureHeaderSize = 0;
  1632. SignatureList->SignatureListSize = (UINT32) SignatureListSize;
  1633. SignatureList->SignatureSize = (UINT32) (sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize);
  1634. CopyMem (&SignatureList->SignatureType, &mCertType, sizeof (EFI_GUID));
  1635. Signature = (EFI_SIGNATURE_DATA *) ((UINT8 *) SignatureList + sizeof (EFI_SIGNATURE_LIST));
  1636. CopyMem (Signature->SignatureData, mImageDigest, mImageDigestSize);
  1637. }
  1638. }
  1639. Done:
  1640. if (Status != EFI_SUCCESS) {
  1641. //
  1642. // Policy decides to defer or reject the image; add its information in image executable information table.
  1643. //
  1644. NameStr = ConvertDevicePathToText (File, FALSE, TRUE);
  1645. AddImageExeInfo (Action, NameStr, File, SignatureList, SignatureListSize);
  1646. if (NameStr != NULL) {
  1647. DEBUG((EFI_D_INFO, "The image doesn't pass verification: %s\n", NameStr));
  1648. FreePool(NameStr);
  1649. }
  1650. Status = EFI_SECURITY_VIOLATION;
  1651. }
  1652. if (SignatureList != NULL) {
  1653. FreePool (SignatureList);
  1654. }
  1655. return Status;
  1656. }
  1657. /**
  1658. On Ready To Boot Services Event notification handler.
  1659. Add the image execution information table if it is not in system configuration table.
  1660. @param[in] Event Event whose notification function is being invoked
  1661. @param[in] Context Pointer to the notification function's context
  1662. **/
  1663. VOID
  1664. EFIAPI
  1665. OnReadyToBoot (
  1666. IN EFI_EVENT Event,
  1667. IN VOID *Context
  1668. )
  1669. {
  1670. EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable;
  1671. UINTN ImageExeInfoTableSize;
  1672. EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **) &ImageExeInfoTable);
  1673. if (ImageExeInfoTable != NULL) {
  1674. return;
  1675. }
  1676. ImageExeInfoTableSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
  1677. ImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *) AllocateRuntimePool (ImageExeInfoTableSize);
  1678. if (ImageExeInfoTable == NULL) {
  1679. return ;
  1680. }
  1681. ImageExeInfoTable->NumberOfImages = 0;
  1682. gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *) ImageExeInfoTable);
  1683. }
  1684. /**
  1685. Register security measurement handler.
  1686. @param ImageHandle ImageHandle of the loaded driver.
  1687. @param SystemTable Pointer to the EFI System Table.
  1688. @retval EFI_SUCCESS The handlers were registered successfully.
  1689. **/
  1690. EFI_STATUS
  1691. EFIAPI
  1692. DxeImageVerificationLibConstructor (
  1693. IN EFI_HANDLE ImageHandle,
  1694. IN EFI_SYSTEM_TABLE *SystemTable
  1695. )
  1696. {
  1697. EFI_EVENT Event;
  1698. //
  1699. // Register the event to publish the image execution table.
  1700. //
  1701. EfiCreateEventReadyToBootEx (
  1702. TPL_CALLBACK,
  1703. OnReadyToBoot,
  1704. NULL,
  1705. &Event
  1706. );
  1707. return RegisterSecurity2Handler (
  1708. DxeImageVerificationHandler,
  1709. EFI_AUTH_OPERATION_VERIFY_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED
  1710. );
  1711. }