]> git.proxmox.com Git - mirror_edk2.git/blob - OvmfPkg/SecureBootConfigDxe/SecureBootConfigImpl.c
OvmfPkg/SecureBootConfigDxe: Avoid illegal access
[mirror_edk2.git] / OvmfPkg / SecureBootConfigDxe / SecureBootConfigImpl.c
1 /** @file
2 HII Config Access protocol implementation of SecureBoot configuration module.
3
4 Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
9
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12
13 **/
14
15 #include "SecureBootConfigImpl.h"
16
17 CHAR16 mSecureBootStorageName[] = L"SECUREBOOT_CONFIGURATION";
18
19 SECUREBOOT_CONFIG_PRIVATE_DATA mSecureBootConfigPrivateDateTemplate = {
20 SECUREBOOT_CONFIG_PRIVATE_DATA_SIGNATURE,
21 {
22 SecureBootExtractConfig,
23 SecureBootRouteConfig,
24 SecureBootCallback
25 }
26 };
27
28 HII_VENDOR_DEVICE_PATH mSecureBootHiiVendorDevicePath = {
29 {
30 {
31 HARDWARE_DEVICE_PATH,
32 HW_VENDOR_DP,
33 {
34 (UINT8) (sizeof (VENDOR_DEVICE_PATH)),
35 (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8)
36 }
37 },
38 SECUREBOOT_CONFIG_FORM_SET_GUID
39 },
40 {
41 END_DEVICE_PATH_TYPE,
42 END_ENTIRE_DEVICE_PATH_SUBTYPE,
43 {
44 (UINT8) (END_DEVICE_PATH_LENGTH),
45 (UINT8) ((END_DEVICE_PATH_LENGTH) >> 8)
46 }
47 }
48 };
49
50
51 //
52 // OID ASN.1 Value for Hash Algorithms
53 //
54 UINT8 mHashOidValue[] = {
55 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, // OBJ_md5
56 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1
57 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224
58 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256
59 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384
60 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512
61 };
62
63 HASH_TABLE mHash[] = {
64 { L"SHA1", 20, &mHashOidValue[8], 5, Sha1GetContextSize, Sha1Init, Sha1Update, Sha1Final },
65 { L"SHA224", 28, &mHashOidValue[13], 9, NULL, NULL, NULL, NULL },
66 { L"SHA256", 32, &mHashOidValue[22], 9, Sha256GetContextSize,Sha256Init, Sha256Update, Sha256Final},
67 { L"SHA384", 48, &mHashOidValue[31], 9, NULL, NULL, NULL, NULL },
68 { L"SHA512", 64, &mHashOidValue[40], 9, NULL, NULL, NULL, NULL }
69 };
70
71 //
72 // Variable Definitions
73 //
74 UINT32 mPeCoffHeaderOffset = 0;
75 WIN_CERTIFICATE *mCertificate = NULL;
76 IMAGE_TYPE mImageType;
77 UINT8 *mImageBase = NULL;
78 UINTN mImageSize = 0;
79 UINT8 mImageDigest[MAX_DIGEST_SIZE];
80 UINTN mImageDigestSize;
81 EFI_GUID mCertType;
82 EFI_IMAGE_SECURITY_DATA_DIRECTORY *mSecDataDir = NULL;
83 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader;
84
85 //
86 // Possible DER-encoded certificate file suffixes, end with NULL pointer.
87 //
88 CHAR16* mDerEncodedSuffix[] = {
89 L".cer",
90 L".der",
91 L".crt",
92 NULL
93 };
94 CHAR16* mSupportX509Suffix = L"*.cer/der/crt";
95
96 /**
97 This code checks if the FileSuffix is one of the possible DER-encoded certificate suffix.
98
99 @param[in] FileSuffix The suffix of the input certificate file
100
101 @retval TRUE It's a DER-encoded certificate.
102 @retval FALSE It's NOT a DER-encoded certificate.
103
104 **/
105 BOOLEAN
106 IsDerEncodeCertificate (
107 IN CONST CHAR16 *FileSuffix
108 )
109 {
110 UINTN Index;
111 for (Index = 0; mDerEncodedSuffix[Index] != NULL; Index++) {
112 if (StrCmp (FileSuffix, mDerEncodedSuffix[Index]) == 0) {
113 return TRUE;
114 }
115 }
116 return FALSE;
117 }
118
119 /**
120 Set Secure Boot option into variable space.
121
122 @param[in] VarValue The option of Secure Boot.
123
124 @retval EFI_SUCCESS The operation is finished successfully.
125 @retval Others Other errors as indicated.
126
127 **/
128 EFI_STATUS
129 SaveSecureBootVariable (
130 IN UINT8 VarValue
131 )
132 {
133 EFI_STATUS Status;
134
135 Status = gRT->SetVariable (
136 EFI_SECURE_BOOT_ENABLE_NAME,
137 &gEfiSecureBootEnableDisableGuid,
138 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
139 sizeof (UINT8),
140 &VarValue
141 );
142 return Status;
143 }
144
145 /**
146 Create a time based data payload by concatenating the EFI_VARIABLE_AUTHENTICATION_2
147 descriptor with the input data. NO authentication is required in this function.
148
149 @param[in, out] DataSize On input, the size of Data buffer in bytes.
150 On output, the size of data returned in Data
151 buffer in bytes.
152 @param[in, out] Data On input, Pointer to data buffer to be wrapped or
153 pointer to NULL to wrap an empty payload.
154 On output, Pointer to the new payload date buffer allocated from pool,
155 it's caller's responsibility to free the memory when finish using it.
156
157 @retval EFI_SUCCESS Create time based payload successfully.
158 @retval EFI_OUT_OF_RESOURCES There are not enough memory resourses to create time based payload.
159 @retval EFI_INVALID_PARAMETER The parameter is invalid.
160 @retval Others Unexpected error happens.
161
162 **/
163 EFI_STATUS
164 CreateTimeBasedPayload (
165 IN OUT UINTN *DataSize,
166 IN OUT UINT8 **Data
167 )
168 {
169 EFI_STATUS Status;
170 UINT8 *NewData;
171 UINT8 *Payload;
172 UINTN PayloadSize;
173 EFI_VARIABLE_AUTHENTICATION_2 *DescriptorData;
174 UINTN DescriptorSize;
175 EFI_TIME Time;
176
177 if (Data == NULL || DataSize == NULL) {
178 return EFI_INVALID_PARAMETER;
179 }
180
181 //
182 // In Setup mode or Custom mode, the variable does not need to be signed but the
183 // parameters to the SetVariable() call still need to be prepared as authenticated
184 // variable. So we create EFI_VARIABLE_AUTHENTICATED_2 descriptor without certificate
185 // data in it.
186 //
187 Payload = *Data;
188 PayloadSize = *DataSize;
189
190 DescriptorSize = OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo) + OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData);
191 NewData = (UINT8*) AllocateZeroPool (DescriptorSize + PayloadSize);
192 if (NewData == NULL) {
193 return EFI_OUT_OF_RESOURCES;
194 }
195
196 if ((Payload != NULL) && (PayloadSize != 0)) {
197 CopyMem (NewData + DescriptorSize, Payload, PayloadSize);
198 }
199
200 DescriptorData = (EFI_VARIABLE_AUTHENTICATION_2 *) (NewData);
201
202 ZeroMem (&Time, sizeof (EFI_TIME));
203 Status = gRT->GetTime (&Time, NULL);
204 if (EFI_ERROR (Status)) {
205 FreePool(NewData);
206 return Status;
207 }
208 Time.Pad1 = 0;
209 Time.Nanosecond = 0;
210 Time.TimeZone = 0;
211 Time.Daylight = 0;
212 Time.Pad2 = 0;
213 CopyMem (&DescriptorData->TimeStamp, &Time, sizeof (EFI_TIME));
214
215 DescriptorData->AuthInfo.Hdr.dwLength = OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData);
216 DescriptorData->AuthInfo.Hdr.wRevision = 0x0200;
217 DescriptorData->AuthInfo.Hdr.wCertificateType = WIN_CERT_TYPE_EFI_GUID;
218 CopyGuid (&DescriptorData->AuthInfo.CertType, &gEfiCertPkcs7Guid);
219
220 if (Payload != NULL) {
221 FreePool(Payload);
222 }
223
224 *DataSize = DescriptorSize + PayloadSize;
225 *Data = NewData;
226 return EFI_SUCCESS;
227 }
228
229 /**
230 Internal helper function to delete a Variable given its name and GUID, NO authentication
231 required.
232
233 @param[in] VariableName Name of the Variable.
234 @param[in] VendorGuid GUID of the Variable.
235
236 @retval EFI_SUCCESS Variable deleted successfully.
237 @retval Others The driver failed to start the device.
238
239 **/
240 EFI_STATUS
241 DeleteVariable (
242 IN CHAR16 *VariableName,
243 IN EFI_GUID *VendorGuid
244 )
245 {
246 EFI_STATUS Status;
247 VOID* Variable;
248 UINT8 *Data;
249 UINTN DataSize;
250 UINT32 Attr;
251
252 GetVariable2 (VariableName, VendorGuid, &Variable, NULL);
253 if (Variable == NULL) {
254 return EFI_SUCCESS;
255 }
256
257 Data = NULL;
258 DataSize = 0;
259 Attr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS
260 | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
261
262 Status = CreateTimeBasedPayload (&DataSize, &Data);
263 if (EFI_ERROR (Status)) {
264 DEBUG ((EFI_D_ERROR, "Fail to create time-based data payload: %r", Status));
265 return Status;
266 }
267
268 Status = gRT->SetVariable (
269 VariableName,
270 VendorGuid,
271 Attr,
272 DataSize,
273 Data
274 );
275 if (Data != NULL) {
276 FreePool (Data);
277 }
278 return Status;
279 }
280
281 /**
282 Generate the PK signature list from the X509 Certificate storing file (.cer)
283
284 @param[in] X509File FileHandle of X509 Certificate storing file.
285 @param[out] PkCert Point to the data buffer to store the signature list.
286
287 @return EFI_UNSUPPORTED Unsupported Key Length.
288 @return EFI_OUT_OF_RESOURCES There are not enough memory resourses to form the signature list.
289
290 **/
291 EFI_STATUS
292 CreatePkX509SignatureList (
293 IN EFI_FILE_HANDLE X509File,
294 OUT EFI_SIGNATURE_LIST **PkCert
295 )
296 {
297 EFI_STATUS Status;
298 UINT8 *X509Data;
299 UINTN X509DataSize;
300 EFI_SIGNATURE_DATA *PkCertData;
301
302 X509Data = NULL;
303 PkCertData = NULL;
304 X509DataSize = 0;
305
306 Status = ReadFileContent (X509File, (VOID**) &X509Data, &X509DataSize, 0);
307 if (EFI_ERROR (Status)) {
308 goto ON_EXIT;
309 }
310 ASSERT (X509Data != NULL);
311
312 //
313 // Allocate space for PK certificate list and initialize it.
314 // Create PK database entry with SignatureHeaderSize equals 0.
315 //
316 *PkCert = (EFI_SIGNATURE_LIST*) AllocateZeroPool (
317 sizeof(EFI_SIGNATURE_LIST) + sizeof(EFI_SIGNATURE_DATA) - 1
318 + X509DataSize
319 );
320 if (*PkCert == NULL) {
321 Status = EFI_OUT_OF_RESOURCES;
322 goto ON_EXIT;
323 }
324
325 (*PkCert)->SignatureListSize = (UINT32) (sizeof(EFI_SIGNATURE_LIST)
326 + sizeof(EFI_SIGNATURE_DATA) - 1
327 + X509DataSize);
328 (*PkCert)->SignatureSize = (UINT32) (sizeof(EFI_SIGNATURE_DATA) - 1 + X509DataSize);
329 (*PkCert)->SignatureHeaderSize = 0;
330 CopyGuid (&(*PkCert)->SignatureType, &gEfiCertX509Guid);
331 PkCertData = (EFI_SIGNATURE_DATA*) ((UINTN)(*PkCert)
332 + sizeof(EFI_SIGNATURE_LIST)
333 + (*PkCert)->SignatureHeaderSize);
334 CopyGuid (&PkCertData->SignatureOwner, &gEfiGlobalVariableGuid);
335 //
336 // Fill the PK database with PKpub data from X509 certificate file.
337 //
338 CopyMem (&(PkCertData->SignatureData[0]), X509Data, X509DataSize);
339
340 ON_EXIT:
341
342 if (X509Data != NULL) {
343 FreePool (X509Data);
344 }
345
346 if (EFI_ERROR(Status) && *PkCert != NULL) {
347 FreePool (*PkCert);
348 *PkCert = NULL;
349 }
350
351 return Status;
352 }
353
354 /**
355 Enroll new PK into the System without original PK's authentication.
356
357 The SignatureOwner GUID will be the same with PK's vendorguid.
358
359 @param[in] PrivateData The module's private data.
360
361 @retval EFI_SUCCESS New PK enrolled successfully.
362 @retval EFI_INVALID_PARAMETER The parameter is invalid.
363 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
364
365 **/
366 EFI_STATUS
367 EnrollPlatformKey (
368 IN SECUREBOOT_CONFIG_PRIVATE_DATA* Private
369 )
370 {
371 EFI_STATUS Status;
372 UINT32 Attr;
373 UINTN DataSize;
374 EFI_SIGNATURE_LIST *PkCert;
375 UINT16* FilePostFix;
376 UINTN NameLength;
377
378 if (Private->FileContext->FileName == NULL) {
379 return EFI_INVALID_PARAMETER;
380 }
381
382 PkCert = NULL;
383
384 //
385 // Parse the file's postfix. Only support DER encoded X.509 certificate files.
386 //
387 NameLength = StrLen (Private->FileContext->FileName);
388 if (NameLength <= 4) {
389 return EFI_INVALID_PARAMETER;
390 }
391 FilePostFix = Private->FileContext->FileName + NameLength - 4;
392 if (!IsDerEncodeCertificate(FilePostFix)) {
393 DEBUG ((EFI_D_ERROR, "Unsupported file type, only DER encoded certificate (%s) is supported.", mSupportX509Suffix));
394 return EFI_INVALID_PARAMETER;
395 }
396 DEBUG ((EFI_D_INFO, "FileName= %s\n", Private->FileContext->FileName));
397 DEBUG ((EFI_D_INFO, "FilePostFix = %s\n", FilePostFix));
398
399 //
400 // Prase the selected PK file and generature PK certificate list.
401 //
402 Status = CreatePkX509SignatureList (
403 Private->FileContext->FHandle,
404 &PkCert
405 );
406 if (EFI_ERROR (Status)) {
407 goto ON_EXIT;
408 }
409 ASSERT (PkCert != NULL);
410
411 //
412 // Set Platform Key variable.
413 //
414 Attr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS
415 | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
416 DataSize = PkCert->SignatureListSize;
417 Status = CreateTimeBasedPayload (&DataSize, (UINT8**) &PkCert);
418 if (EFI_ERROR (Status)) {
419 DEBUG ((EFI_D_ERROR, "Fail to create time-based data payload: %r", Status));
420 goto ON_EXIT;
421 }
422
423 Status = gRT->SetVariable(
424 EFI_PLATFORM_KEY_NAME,
425 &gEfiGlobalVariableGuid,
426 Attr,
427 DataSize,
428 PkCert
429 );
430 if (EFI_ERROR (Status)) {
431 if (Status == EFI_OUT_OF_RESOURCES) {
432 DEBUG ((EFI_D_ERROR, "Enroll PK failed with out of resource.\n"));
433 }
434 goto ON_EXIT;
435 }
436
437 ON_EXIT:
438
439 if (PkCert != NULL) {
440 FreePool(PkCert);
441 }
442
443 if (Private->FileContext->FHandle != NULL) {
444 CloseFile (Private->FileContext->FHandle);
445 Private->FileContext->FHandle = NULL;
446 }
447
448 return Status;
449 }
450
451 /**
452 Remove the PK variable.
453
454 @retval EFI_SUCCESS Delete PK successfully.
455 @retval Others Could not allow to delete PK.
456
457 **/
458 EFI_STATUS
459 DeletePlatformKey (
460 VOID
461 )
462 {
463 EFI_STATUS Status;
464
465 Status = DeleteVariable (
466 EFI_PLATFORM_KEY_NAME,
467 &gEfiGlobalVariableGuid
468 );
469 return Status;
470 }
471
472 /**
473 Enroll a new KEK item from public key storing file (*.pbk).
474
475 @param[in] PrivateData The module's private data.
476
477 @retval EFI_SUCCESS New KEK enrolled successfully.
478 @retval EFI_INVALID_PARAMETER The parameter is invalid.
479 @retval EFI_UNSUPPORTED Unsupported command.
480 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
481
482 **/
483 EFI_STATUS
484 EnrollRsa2048ToKek (
485 IN SECUREBOOT_CONFIG_PRIVATE_DATA *Private
486 )
487 {
488 EFI_STATUS Status;
489 UINT32 Attr;
490 UINTN DataSize;
491 EFI_SIGNATURE_LIST *KekSigList;
492 UINTN KeyBlobSize;
493 UINT8 *KeyBlob;
494 CPL_KEY_INFO *KeyInfo;
495 EFI_SIGNATURE_DATA *KEKSigData;
496 UINTN KekSigListSize;
497 UINT8 *KeyBuffer;
498 UINTN KeyLenInBytes;
499
500 Attr = 0;
501 DataSize = 0;
502 KeyBuffer = NULL;
503 KeyBlobSize = 0;
504 KeyBlob = NULL;
505 KeyInfo = NULL;
506 KEKSigData = NULL;
507 KekSigList = NULL;
508 KekSigListSize = 0;
509
510 //
511 // Form the KeKpub certificate list into EFI_SIGNATURE_LIST type.
512 // First, We have to parse out public key data from the pbk key file.
513 //
514 Status = ReadFileContent (
515 Private->FileContext->FHandle,
516 (VOID**) &KeyBlob,
517 &KeyBlobSize,
518 0
519 );
520 if (EFI_ERROR (Status)) {
521 goto ON_EXIT;
522 }
523 ASSERT (KeyBlob != NULL);
524 KeyInfo = (CPL_KEY_INFO *) KeyBlob;
525 if (KeyInfo->KeyLengthInBits / 8 != WIN_CERT_UEFI_RSA2048_SIZE) {
526 DEBUG ((DEBUG_ERROR, "Unsupported key length, Only RSA2048 is supported.\n"));
527 Status = EFI_UNSUPPORTED;
528 goto ON_EXIT;
529 }
530
531 //
532 // Convert the Public key to fix octet string format represented in RSA PKCS#1.
533 //
534 KeyLenInBytes = KeyInfo->KeyLengthInBits / 8;
535 KeyBuffer = AllocateZeroPool (KeyLenInBytes);
536 if (KeyBuffer == NULL) {
537 Status = EFI_OUT_OF_RESOURCES;
538 goto ON_EXIT;
539 }
540 Int2OctStr (
541 (UINTN*) (KeyBlob + sizeof (CPL_KEY_INFO)),
542 KeyLenInBytes / sizeof (UINTN),
543 KeyBuffer,
544 KeyLenInBytes
545 );
546 CopyMem(KeyBlob + sizeof(CPL_KEY_INFO), KeyBuffer, KeyLenInBytes);
547
548 //
549 // Form an new EFI_SIGNATURE_LIST.
550 //
551 KekSigListSize = sizeof(EFI_SIGNATURE_LIST)
552 + sizeof(EFI_SIGNATURE_DATA) - 1
553 + WIN_CERT_UEFI_RSA2048_SIZE;
554
555 KekSigList = (EFI_SIGNATURE_LIST*) AllocateZeroPool (KekSigListSize);
556 if (KekSigList == NULL) {
557 Status = EFI_OUT_OF_RESOURCES;
558 goto ON_EXIT;
559 }
560
561 KekSigList->SignatureListSize = sizeof(EFI_SIGNATURE_LIST)
562 + sizeof(EFI_SIGNATURE_DATA) - 1
563 + WIN_CERT_UEFI_RSA2048_SIZE;
564 KekSigList->SignatureHeaderSize = 0;
565 KekSigList->SignatureSize = sizeof(EFI_SIGNATURE_DATA) - 1 + WIN_CERT_UEFI_RSA2048_SIZE;
566 CopyGuid (&KekSigList->SignatureType, &gEfiCertRsa2048Guid);
567
568 KEKSigData = (EFI_SIGNATURE_DATA*)((UINT8*)KekSigList + sizeof(EFI_SIGNATURE_LIST));
569 CopyGuid (&KEKSigData->SignatureOwner, Private->SignatureGUID);
570 CopyMem (
571 KEKSigData->SignatureData,
572 KeyBlob + sizeof(CPL_KEY_INFO),
573 WIN_CERT_UEFI_RSA2048_SIZE
574 );
575
576 //
577 // Check if KEK entry has been already existed.
578 // If true, use EFI_VARIABLE_APPEND_WRITE attribute to append the
579 // new KEK to original variable.
580 //
581 Attr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS
582 | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
583 Status = CreateTimeBasedPayload (&KekSigListSize, (UINT8**) &KekSigList);
584 if (EFI_ERROR (Status)) {
585 DEBUG ((EFI_D_ERROR, "Fail to create time-based data payload: %r", Status));
586 goto ON_EXIT;
587 }
588
589 Status = gRT->GetVariable(
590 EFI_KEY_EXCHANGE_KEY_NAME,
591 &gEfiGlobalVariableGuid,
592 NULL,
593 &DataSize,
594 NULL
595 );
596 if (Status == EFI_BUFFER_TOO_SMALL) {
597 Attr |= EFI_VARIABLE_APPEND_WRITE;
598 } else if (Status != EFI_NOT_FOUND) {
599 goto ON_EXIT;
600 }
601
602 //
603 // Done. Now we have formed the correct KEKpub database item, just set it into variable storage,
604 //
605 Status = gRT->SetVariable(
606 EFI_KEY_EXCHANGE_KEY_NAME,
607 &gEfiGlobalVariableGuid,
608 Attr,
609 KekSigListSize,
610 KekSigList
611 );
612 if (EFI_ERROR (Status)) {
613 goto ON_EXIT;
614 }
615
616 ON_EXIT:
617
618 CloseFile (Private->FileContext->FHandle);
619 Private->FileContext->FHandle = NULL;
620 Private->FileContext->FileName = NULL;
621
622 if (Private->SignatureGUID != NULL) {
623 FreePool (Private->SignatureGUID);
624 Private->SignatureGUID = NULL;
625 }
626
627 if (KeyBlob != NULL) {
628 FreePool (KeyBlob);
629 }
630 if (KeyBuffer != NULL) {
631 FreePool (KeyBuffer);
632 }
633 if (KekSigList != NULL) {
634 FreePool (KekSigList);
635 }
636
637 return Status;
638 }
639
640 /**
641 Enroll a new KEK item from X509 certificate file.
642
643 @param[in] PrivateData The module's private data.
644
645 @retval EFI_SUCCESS New X509 is enrolled successfully.
646 @retval EFI_INVALID_PARAMETER The parameter is invalid.
647 @retval EFI_UNSUPPORTED Unsupported command.
648 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
649
650 **/
651 EFI_STATUS
652 EnrollX509ToKek (
653 IN SECUREBOOT_CONFIG_PRIVATE_DATA *Private
654 )
655 {
656 EFI_STATUS Status;
657 UINTN X509DataSize;
658 VOID *X509Data;
659 EFI_SIGNATURE_DATA *KEKSigData;
660 EFI_SIGNATURE_LIST *KekSigList;
661 UINTN DataSize;
662 UINTN KekSigListSize;
663 UINT32 Attr;
664
665 X509Data = NULL;
666 X509DataSize = 0;
667 KekSigList = NULL;
668 KekSigListSize = 0;
669 DataSize = 0;
670 KEKSigData = NULL;
671
672 Status = ReadFileContent (
673 Private->FileContext->FHandle,
674 &X509Data,
675 &X509DataSize,
676 0
677 );
678 if (EFI_ERROR (Status)) {
679 goto ON_EXIT;
680 }
681 ASSERT (X509Data != NULL);
682
683 KekSigListSize = sizeof(EFI_SIGNATURE_LIST) + sizeof(EFI_SIGNATURE_DATA) - 1 + X509DataSize;
684 KekSigList = (EFI_SIGNATURE_LIST*) AllocateZeroPool (KekSigListSize);
685 if (KekSigList == NULL) {
686 Status = EFI_OUT_OF_RESOURCES;
687 goto ON_EXIT;
688 }
689
690 //
691 // Fill Certificate Database parameters.
692 //
693 KekSigList->SignatureListSize = (UINT32) KekSigListSize;
694 KekSigList->SignatureHeaderSize = 0;
695 KekSigList->SignatureSize = (UINT32) (sizeof(EFI_SIGNATURE_DATA) - 1 + X509DataSize);
696 CopyGuid (&KekSigList->SignatureType, &gEfiCertX509Guid);
697
698 KEKSigData = (EFI_SIGNATURE_DATA*) ((UINT8*) KekSigList + sizeof (EFI_SIGNATURE_LIST));
699 CopyGuid (&KEKSigData->SignatureOwner, Private->SignatureGUID);
700 CopyMem (KEKSigData->SignatureData, X509Data, X509DataSize);
701
702 //
703 // Check if KEK been already existed.
704 // If true, use EFI_VARIABLE_APPEND_WRITE attribute to append the
705 // new kek to original variable
706 //
707 Attr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS
708 | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
709 Status = CreateTimeBasedPayload (&KekSigListSize, (UINT8**) &KekSigList);
710 if (EFI_ERROR (Status)) {
711 DEBUG ((EFI_D_ERROR, "Fail to create time-based data payload: %r", Status));
712 goto ON_EXIT;
713 }
714
715 Status = gRT->GetVariable(
716 EFI_KEY_EXCHANGE_KEY_NAME,
717 &gEfiGlobalVariableGuid,
718 NULL,
719 &DataSize,
720 NULL
721 );
722 if (Status == EFI_BUFFER_TOO_SMALL) {
723 Attr |= EFI_VARIABLE_APPEND_WRITE;
724 } else if (Status != EFI_NOT_FOUND) {
725 goto ON_EXIT;
726 }
727
728 Status = gRT->SetVariable(
729 EFI_KEY_EXCHANGE_KEY_NAME,
730 &gEfiGlobalVariableGuid,
731 Attr,
732 KekSigListSize,
733 KekSigList
734 );
735 if (EFI_ERROR (Status)) {
736 goto ON_EXIT;
737 }
738
739 ON_EXIT:
740
741 CloseFile (Private->FileContext->FHandle);
742 Private->FileContext->FileName = NULL;
743 Private->FileContext->FHandle = NULL;
744
745 if (Private->SignatureGUID != NULL) {
746 FreePool (Private->SignatureGUID);
747 Private->SignatureGUID = NULL;
748 }
749
750 if (KekSigList != NULL) {
751 FreePool (KekSigList);
752 }
753
754 return Status;
755 }
756
757 /**
758 Enroll new KEK into the System without PK's authentication.
759 The SignatureOwner GUID will be Private->SignatureGUID.
760
761 @param[in] PrivateData The module's private data.
762
763 @retval EFI_SUCCESS New KEK enrolled successful.
764 @retval EFI_INVALID_PARAMETER The parameter is invalid.
765 @retval others Fail to enroll KEK data.
766
767 **/
768 EFI_STATUS
769 EnrollKeyExchangeKey (
770 IN SECUREBOOT_CONFIG_PRIVATE_DATA *Private
771 )
772 {
773 UINT16* FilePostFix;
774 UINTN NameLength;
775
776 if ((Private->FileContext->FileName == NULL) || (Private->SignatureGUID == NULL)) {
777 return EFI_INVALID_PARAMETER;
778 }
779
780 //
781 // Parse the file's postfix. Supports DER-encoded X509 certificate,
782 // and .pbk as RSA public key file.
783 //
784 NameLength = StrLen (Private->FileContext->FileName);
785 if (NameLength <= 4) {
786 return EFI_INVALID_PARAMETER;
787 }
788 FilePostFix = Private->FileContext->FileName + NameLength - 4;
789 if (IsDerEncodeCertificate(FilePostFix)) {
790 return EnrollX509ToKek (Private);
791 } else if (CompareMem (FilePostFix, L".pbk",4) == 0) {
792 return EnrollRsa2048ToKek (Private);
793 } else {
794 return EFI_INVALID_PARAMETER;
795 }
796 }
797
798 /**
799 Enroll a new X509 certificate into Signature Database (DB or DBX) without
800 KEK's authentication.
801
802 @param[in] PrivateData The module's private data.
803 @param[in] VariableName Variable name of signature database, must be
804 EFI_IMAGE_SECURITY_DATABASE or EFI_IMAGE_SECURITY_DATABASE1.
805
806 @retval EFI_SUCCESS New X509 is enrolled successfully.
807 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
808
809 **/
810 EFI_STATUS
811 EnrollX509toSigDB (
812 IN SECUREBOOT_CONFIG_PRIVATE_DATA *Private,
813 IN CHAR16 *VariableName
814 )
815 {
816 EFI_STATUS Status;
817 UINTN X509DataSize;
818 VOID *X509Data;
819 EFI_SIGNATURE_LIST *SigDBCert;
820 EFI_SIGNATURE_DATA *SigDBCertData;
821 VOID *Data;
822 UINTN DataSize;
823 UINTN SigDBSize;
824 UINT32 Attr;
825
826 X509DataSize = 0;
827 SigDBSize = 0;
828 DataSize = 0;
829 X509Data = NULL;
830 SigDBCert = NULL;
831 SigDBCertData = NULL;
832 Data = NULL;
833
834 Status = ReadFileContent (
835 Private->FileContext->FHandle,
836 &X509Data,
837 &X509DataSize,
838 0
839 );
840 if (EFI_ERROR (Status)) {
841 goto ON_EXIT;
842 }
843 ASSERT (X509Data != NULL);
844
845 SigDBSize = sizeof(EFI_SIGNATURE_LIST) + sizeof(EFI_SIGNATURE_DATA) - 1 + X509DataSize;
846
847 Data = AllocateZeroPool (SigDBSize);
848 if (Data == NULL) {
849 Status = EFI_OUT_OF_RESOURCES;
850 goto ON_EXIT;
851 }
852
853 //
854 // Fill Certificate Database parameters.
855 //
856 SigDBCert = (EFI_SIGNATURE_LIST*) Data;
857 SigDBCert->SignatureListSize = (UINT32) SigDBSize;
858 SigDBCert->SignatureHeaderSize = 0;
859 SigDBCert->SignatureSize = (UINT32) (sizeof(EFI_SIGNATURE_DATA) - 1 + X509DataSize);
860 CopyGuid (&SigDBCert->SignatureType, &gEfiCertX509Guid);
861
862 SigDBCertData = (EFI_SIGNATURE_DATA*) ((UINT8* ) SigDBCert + sizeof (EFI_SIGNATURE_LIST));
863 CopyGuid (&SigDBCertData->SignatureOwner, Private->SignatureGUID);
864 CopyMem ((UINT8* ) (SigDBCertData->SignatureData), X509Data, X509DataSize);
865
866 //
867 // Check if signature database entry has been already existed.
868 // If true, use EFI_VARIABLE_APPEND_WRITE attribute to append the
869 // new signature data to original variable
870 //
871 Attr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS
872 | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
873 Status = CreateTimeBasedPayload (&SigDBSize, (UINT8**) &Data);
874 if (EFI_ERROR (Status)) {
875 DEBUG ((EFI_D_ERROR, "Fail to create time-based data payload: %r", Status));
876 goto ON_EXIT;
877 }
878
879 Status = gRT->GetVariable(
880 VariableName,
881 &gEfiImageSecurityDatabaseGuid,
882 NULL,
883 &DataSize,
884 NULL
885 );
886 if (Status == EFI_BUFFER_TOO_SMALL) {
887 Attr |= EFI_VARIABLE_APPEND_WRITE;
888 } else if (Status != EFI_NOT_FOUND) {
889 goto ON_EXIT;
890 }
891
892 Status = gRT->SetVariable(
893 VariableName,
894 &gEfiImageSecurityDatabaseGuid,
895 Attr,
896 SigDBSize,
897 Data
898 );
899 if (EFI_ERROR (Status)) {
900 goto ON_EXIT;
901 }
902
903 ON_EXIT:
904
905 CloseFile (Private->FileContext->FHandle);
906 Private->FileContext->FileName = NULL;
907 Private->FileContext->FHandle = NULL;
908
909 if (Private->SignatureGUID != NULL) {
910 FreePool (Private->SignatureGUID);
911 Private->SignatureGUID = NULL;
912 }
913
914 if (Data != NULL) {
915 FreePool (Data);
916 }
917
918 if (X509Data != NULL) {
919 FreePool (X509Data);
920 }
921
922 return Status;
923 }
924
925 /**
926 Load PE/COFF image information into internal buffer and check its validity.
927
928 @retval EFI_SUCCESS Successful
929 @retval EFI_UNSUPPORTED Invalid PE/COFF file
930 @retval EFI_ABORTED Serious error occurs, like file I/O error etc.
931
932 **/
933 EFI_STATUS
934 LoadPeImage (
935 VOID
936 )
937 {
938 EFI_IMAGE_DOS_HEADER *DosHdr;
939 EFI_IMAGE_NT_HEADERS32 *NtHeader32;
940 EFI_IMAGE_NT_HEADERS64 *NtHeader64;
941
942 NtHeader32 = NULL;
943 NtHeader64 = NULL;
944 //
945 // Read the Dos header
946 //
947 DosHdr = (EFI_IMAGE_DOS_HEADER*)(mImageBase);
948 if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE)
949 {
950 //
951 // DOS image header is present,
952 // So read the PE header after the DOS image header
953 //
954 mPeCoffHeaderOffset = DosHdr->e_lfanew;
955 }
956 else
957 {
958 mPeCoffHeaderOffset = 0;
959 }
960
961 //
962 // Read PE header and check the signature validity and machine compatibility
963 //
964 NtHeader32 = (EFI_IMAGE_NT_HEADERS32*) (mImageBase + mPeCoffHeaderOffset);
965 if (NtHeader32->Signature != EFI_IMAGE_NT_SIGNATURE)
966 {
967 return EFI_UNSUPPORTED;
968 }
969
970 mNtHeader.Pe32 = NtHeader32;
971
972 //
973 // Check the architecture field of PE header and get the Certificate Data Directory data
974 // Note the size of FileHeader field is constant for both IA32 and X64 arch
975 //
976 if ((NtHeader32->FileHeader.Machine == EFI_IMAGE_MACHINE_IA32)
977 || (NtHeader32->FileHeader.Machine == EFI_IMAGE_MACHINE_EBC)) {
978 //
979 // IA-32 Architecture
980 //
981 mImageType = ImageType_IA32;
982 mSecDataDir = (EFI_IMAGE_SECURITY_DATA_DIRECTORY*) &(NtHeader32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]);
983 }
984 else if ((NtHeader32->FileHeader.Machine == EFI_IMAGE_MACHINE_IA64)
985 || (NtHeader32->FileHeader.Machine == EFI_IMAGE_MACHINE_X64)) {
986 //
987 // 64-bits Architecture
988 //
989 mImageType = ImageType_X64;
990 NtHeader64 = (EFI_IMAGE_NT_HEADERS64 *) (mImageBase + mPeCoffHeaderOffset);
991 mSecDataDir = (EFI_IMAGE_SECURITY_DATA_DIRECTORY*) &(NtHeader64->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]);
992 } else {
993 return EFI_UNSUPPORTED;
994 }
995
996 return EFI_SUCCESS;
997 }
998
999 /**
1000 Calculate hash of Pe/Coff image based on the authenticode image hashing in
1001 PE/COFF Specification 8.0 Appendix A
1002
1003 @param[in] HashAlg Hash algorithm type.
1004
1005 @retval TRUE Successfully hash image.
1006 @retval FALSE Fail in hash image.
1007
1008 **/
1009 BOOLEAN
1010 HashPeImage (
1011 IN UINT32 HashAlg
1012 )
1013 {
1014 BOOLEAN Status;
1015 UINT16 Magic;
1016 EFI_IMAGE_SECTION_HEADER *Section;
1017 VOID *HashCtx;
1018 UINTN CtxSize;
1019 UINT8 *HashBase;
1020 UINTN HashSize;
1021 UINTN SumOfBytesHashed;
1022 EFI_IMAGE_SECTION_HEADER *SectionHeader;
1023 UINTN Index;
1024 UINTN Pos;
1025
1026 HashCtx = NULL;
1027 SectionHeader = NULL;
1028 Status = FALSE;
1029
1030 if ((HashAlg != HASHALG_SHA1) && (HashAlg != HASHALG_SHA256)) {
1031 return FALSE;
1032 }
1033
1034 //
1035 // Initialize context of hash.
1036 //
1037 ZeroMem (mImageDigest, MAX_DIGEST_SIZE);
1038
1039 if (HashAlg == HASHALG_SHA1) {
1040 mImageDigestSize = SHA1_DIGEST_SIZE;
1041 mCertType = gEfiCertSha1Guid;
1042 } else if (HashAlg == HASHALG_SHA256) {
1043 mImageDigestSize = SHA256_DIGEST_SIZE;
1044 mCertType = gEfiCertSha256Guid;
1045 }
1046
1047 CtxSize = mHash[HashAlg].GetContextSize();
1048
1049 HashCtx = AllocatePool (CtxSize);
1050 ASSERT (HashCtx != NULL);
1051
1052 // 1. Load the image header into memory.
1053
1054 // 2. Initialize a SHA hash context.
1055 Status = mHash[HashAlg].HashInit(HashCtx);
1056 if (!Status) {
1057 goto Done;
1058 }
1059 //
1060 // Measuring PE/COFF Image Header;
1061 // But CheckSum field and SECURITY data directory (certificate) are excluded
1062 //
1063 if (mNtHeader.Pe32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 && mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1064 //
1065 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
1066 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
1067 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
1068 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
1069 //
1070 Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
1071 } else {
1072 //
1073 // Get the magic value from the PE/COFF Optional Header
1074 //
1075 Magic = mNtHeader.Pe32->OptionalHeader.Magic;
1076 }
1077
1078 //
1079 // 3. Calculate the distance from the base of the image header to the image checksum address.
1080 // 4. Hash the image header from its base to beginning of the image checksum.
1081 //
1082 HashBase = mImageBase;
1083 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1084 //
1085 // Use PE32 offset.
1086 //
1087 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - HashBase);
1088 } else {
1089 //
1090 // Use PE32+ offset.
1091 //
1092 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
1093 }
1094
1095 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
1096 if (!Status) {
1097 goto Done;
1098 }
1099 //
1100 // 5. Skip over the image checksum (it occupies a single ULONG).
1101 // 6. Get the address of the beginning of the Cert Directory.
1102 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
1103 //
1104 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1105 //
1106 // Use PE32 offset.
1107 //
1108 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
1109 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
1110 } else {
1111 //
1112 // Use PE32+ offset.
1113 //
1114 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
1115 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
1116 }
1117
1118 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
1119 if (!Status) {
1120 goto Done;
1121 }
1122 //
1123 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
1124 // 9. Hash everything from the end of the Cert Directory to the end of image header.
1125 //
1126 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1127 //
1128 // Use PE32 offset
1129 //
1130 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
1131 HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]) - mImageBase);
1132 } else {
1133 //
1134 // Use PE32+ offset.
1135 //
1136 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
1137 HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]) - mImageBase);
1138 }
1139
1140 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
1141 if (!Status) {
1142 goto Done;
1143 }
1144 //
1145 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header.
1146 //
1147 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1148 //
1149 // Use PE32 offset.
1150 //
1151 SumOfBytesHashed = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders;
1152 } else {
1153 //
1154 // Use PE32+ offset
1155 //
1156 SumOfBytesHashed = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders;
1157 }
1158
1159 //
1160 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
1161 // structures in the image. The 'NumberOfSections' field of the image
1162 // header indicates how big the table should be. Do not include any
1163 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
1164 //
1165 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * mNtHeader.Pe32->FileHeader.NumberOfSections);
1166 ASSERT (SectionHeader != NULL);
1167 //
1168 // 12. Using the 'PointerToRawData' in the referenced section headers as
1169 // a key, arrange the elements in the table in ascending order. In other
1170 // words, sort the section headers according to the disk-file offset of
1171 // the section.
1172 //
1173 Section = (EFI_IMAGE_SECTION_HEADER *) (
1174 mImageBase +
1175 mPeCoffHeaderOffset +
1176 sizeof (UINT32) +
1177 sizeof (EFI_IMAGE_FILE_HEADER) +
1178 mNtHeader.Pe32->FileHeader.SizeOfOptionalHeader
1179 );
1180 for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) {
1181 Pos = Index;
1182 while ((Pos > 0) && (Section->PointerToRawData < SectionHeader[Pos - 1].PointerToRawData)) {
1183 CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof (EFI_IMAGE_SECTION_HEADER));
1184 Pos--;
1185 }
1186 CopyMem (&SectionHeader[Pos], Section, sizeof (EFI_IMAGE_SECTION_HEADER));
1187 Section += 1;
1188 }
1189
1190 //
1191 // 13. Walk through the sorted table, bring the corresponding section
1192 // into memory, and hash the entire section (using the 'SizeOfRawData'
1193 // field in the section header to determine the amount of data to hash).
1194 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
1195 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
1196 //
1197 for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) {
1198 Section = &SectionHeader[Index];
1199 if (Section->SizeOfRawData == 0) {
1200 continue;
1201 }
1202 HashBase = mImageBase + Section->PointerToRawData;
1203 HashSize = (UINTN) Section->SizeOfRawData;
1204
1205 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
1206 if (!Status) {
1207 goto Done;
1208 }
1209
1210 SumOfBytesHashed += HashSize;
1211 }
1212
1213 //
1214 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
1215 // data in the file that needs to be added to the hash. This data begins
1216 // at file offset SUM_OF_BYTES_HASHED and its length is:
1217 // FileSize - (CertDirectory->Size)
1218 //
1219 if (mImageSize > SumOfBytesHashed) {
1220 HashBase = mImageBase + SumOfBytesHashed;
1221 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1222 //
1223 // Use PE32 offset.
1224 //
1225 HashSize = (UINTN)(
1226 mImageSize -
1227 mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size -
1228 SumOfBytesHashed);
1229 } else {
1230 //
1231 // Use PE32+ offset.
1232 //
1233 HashSize = (UINTN)(
1234 mImageSize -
1235 mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size -
1236 SumOfBytesHashed);
1237 }
1238
1239 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
1240 if (!Status) {
1241 goto Done;
1242 }
1243 }
1244
1245 Status = mHash[HashAlg].HashFinal(HashCtx, mImageDigest);
1246
1247 Done:
1248 if (HashCtx != NULL) {
1249 FreePool (HashCtx);
1250 }
1251 if (SectionHeader != NULL) {
1252 FreePool (SectionHeader);
1253 }
1254 return Status;
1255 }
1256
1257 /**
1258 Recognize the Hash algorithm in PE/COFF Authenticode and caculate hash of
1259 Pe/Coff image based on the authenticated image hashing in PE/COFF Specification
1260 8.0 Appendix A
1261
1262 @retval EFI_UNSUPPORTED Hash algorithm is not supported.
1263 @retval EFI_SUCCESS Hash successfully.
1264
1265 **/
1266 EFI_STATUS
1267 HashPeImageByType (
1268 VOID
1269 )
1270 {
1271 UINT8 Index;
1272 WIN_CERTIFICATE_EFI_PKCS *PkcsCertData;
1273
1274 PkcsCertData = (WIN_CERTIFICATE_EFI_PKCS *) (mImageBase + mSecDataDir->Offset);
1275
1276 for (Index = 0; Index < HASHALG_MAX; Index++) {
1277 //
1278 // Check the Hash algorithm in PE/COFF Authenticode.
1279 // According to PKCS#7 Definition:
1280 // SignedData ::= SEQUENCE {
1281 // version Version,
1282 // digestAlgorithms DigestAlgorithmIdentifiers,
1283 // contentInfo ContentInfo,
1284 // .... }
1285 // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm in PE/COFF hashing
1286 // This field has the fixed offset (+32) in final Authenticode ASN.1 data.
1287 // Fixed offset (+32) is calculated based on two bytes of length encoding.
1288 //
1289 if ((*(PkcsCertData->CertData + 1) & TWO_BYTE_ENCODE) != TWO_BYTE_ENCODE) {
1290 //
1291 // Only support two bytes of Long Form of Length Encoding.
1292 //
1293 continue;
1294 }
1295
1296 //
1297 if (CompareMem (PkcsCertData->CertData + 32, mHash[Index].OidValue, mHash[Index].OidLength) == 0) {
1298 break;
1299 }
1300 }
1301
1302 if (Index == HASHALG_MAX) {
1303 return EFI_UNSUPPORTED;
1304 }
1305
1306 //
1307 // HASH PE Image based on Hash algorithm in PE/COFF Authenticode.
1308 //
1309 if (!HashPeImage(Index)) {
1310 return EFI_UNSUPPORTED;
1311 }
1312
1313 return EFI_SUCCESS;
1314 }
1315
1316 /**
1317 Enroll a new executable's signature into Signature Database.
1318
1319 @param[in] PrivateData The module's private data.
1320 @param[in] VariableName Variable name of signature database, must be
1321 EFI_IMAGE_SECURITY_DATABASE or EFI_IMAGE_SECURITY_DATABASE1.
1322
1323 @retval EFI_SUCCESS New signature is enrolled successfully.
1324 @retval EFI_INVALID_PARAMETER The parameter is invalid.
1325 @retval EFI_UNSUPPORTED Unsupported command.
1326 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
1327
1328 **/
1329 EFI_STATUS
1330 EnrollImageSignatureToSigDB (
1331 IN SECUREBOOT_CONFIG_PRIVATE_DATA *Private,
1332 IN CHAR16 *VariableName
1333 )
1334 {
1335 EFI_STATUS Status;
1336 EFI_SIGNATURE_LIST *SigDBCert;
1337 EFI_SIGNATURE_DATA *SigDBCertData;
1338 VOID *Data;
1339 UINTN DataSize;
1340 UINTN SigDBSize;
1341 UINT32 Attr;
1342 WIN_CERTIFICATE_UEFI_GUID *GuidCertData;
1343
1344 Data = NULL;
1345 GuidCertData = NULL;
1346
1347 //
1348 // Form the SigDB certificate list.
1349 // Format the data item into EFI_SIGNATURE_LIST type.
1350 //
1351 // We need to parse executable's signature data from specified signed executable file.
1352 // In current implementation, we simply trust the pass-in signed executable file.
1353 // In reality, it's OS's responsibility to verify the signed executable file.
1354 //
1355
1356 //
1357 // Read the whole file content
1358 //
1359 Status = ReadFileContent(
1360 Private->FileContext->FHandle,
1361 (VOID **) &mImageBase,
1362 &mImageSize,
1363 0
1364 );
1365 if (EFI_ERROR (Status)) {
1366 goto ON_EXIT;
1367 }
1368 ASSERT (mImageBase != NULL);
1369
1370 Status = LoadPeImage ();
1371 if (EFI_ERROR (Status)) {
1372 goto ON_EXIT;
1373 }
1374
1375 if (mSecDataDir->SizeOfCert == 0) {
1376 if (!HashPeImage (HASHALG_SHA256)) {
1377 Status = EFI_SECURITY_VIOLATION;
1378 goto ON_EXIT;
1379 }
1380 } else {
1381
1382 //
1383 // Read the certificate data
1384 //
1385 mCertificate = (WIN_CERTIFICATE *)(mImageBase + mSecDataDir->Offset);
1386
1387 if (mCertificate->wCertificateType == WIN_CERT_TYPE_EFI_GUID) {
1388 GuidCertData = (WIN_CERTIFICATE_UEFI_GUID*) mCertificate;
1389 if (CompareMem (&GuidCertData->CertType, &gEfiCertTypeRsa2048Sha256Guid, sizeof(EFI_GUID)) != 0) {
1390 Status = EFI_ABORTED;
1391 goto ON_EXIT;
1392 }
1393
1394 if (!HashPeImage (HASHALG_SHA256)) {
1395 Status = EFI_ABORTED;
1396 goto ON_EXIT;;
1397 }
1398
1399 } else if (mCertificate->wCertificateType == WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
1400
1401 Status = HashPeImageByType ();
1402 if (EFI_ERROR (Status)) {
1403 goto ON_EXIT;;
1404 }
1405 } else {
1406 Status = EFI_ABORTED;
1407 goto ON_EXIT;
1408 }
1409 }
1410
1411 //
1412 // Create a new SigDB entry.
1413 //
1414 SigDBSize = sizeof(EFI_SIGNATURE_LIST)
1415 + sizeof(EFI_SIGNATURE_DATA) - 1
1416 + (UINT32) mImageDigestSize;
1417
1418 Data = (UINT8*) AllocateZeroPool (SigDBSize);
1419 if (Data == NULL) {
1420 Status = EFI_OUT_OF_RESOURCES;
1421 goto ON_EXIT;
1422 }
1423
1424 //
1425 // Adjust the Certificate Database parameters.
1426 //
1427 SigDBCert = (EFI_SIGNATURE_LIST*) Data;
1428 SigDBCert->SignatureListSize = (UINT32) SigDBSize;
1429 SigDBCert->SignatureHeaderSize = 0;
1430 SigDBCert->SignatureSize = sizeof(EFI_SIGNATURE_DATA) - 1 + (UINT32) mImageDigestSize;
1431 CopyGuid (&SigDBCert->SignatureType, &mCertType);
1432
1433 SigDBCertData = (EFI_SIGNATURE_DATA*)((UINT8*)SigDBCert + sizeof(EFI_SIGNATURE_LIST));
1434 CopyGuid (&SigDBCertData->SignatureOwner, Private->SignatureGUID);
1435 CopyMem (SigDBCertData->SignatureData, mImageDigest, mImageDigestSize);
1436
1437 Attr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS
1438 | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
1439 Status = CreateTimeBasedPayload (&SigDBSize, (UINT8**) &Data);
1440 if (EFI_ERROR (Status)) {
1441 DEBUG ((EFI_D_ERROR, "Fail to create time-based data payload: %r", Status));
1442 goto ON_EXIT;
1443 }
1444
1445 //
1446 // Check if SigDB variable has been already existed.
1447 // If true, use EFI_VARIABLE_APPEND_WRITE attribute to append the
1448 // new signature data to original variable
1449 //
1450 DataSize = 0;
1451 Status = gRT->GetVariable(
1452 VariableName,
1453 &gEfiImageSecurityDatabaseGuid,
1454 NULL,
1455 &DataSize,
1456 NULL
1457 );
1458 if (Status == EFI_BUFFER_TOO_SMALL) {
1459 Attr |= EFI_VARIABLE_APPEND_WRITE;
1460 } else if (Status != EFI_NOT_FOUND) {
1461 goto ON_EXIT;
1462 }
1463
1464 //
1465 // Enroll the variable.
1466 //
1467 Status = gRT->SetVariable(
1468 VariableName,
1469 &gEfiImageSecurityDatabaseGuid,
1470 Attr,
1471 SigDBSize,
1472 Data
1473 );
1474 if (EFI_ERROR (Status)) {
1475 goto ON_EXIT;
1476 }
1477
1478 ON_EXIT:
1479
1480 CloseFile (Private->FileContext->FHandle);
1481 Private->FileContext->FHandle = NULL;
1482 Private->FileContext->FileName = NULL;
1483
1484 if (Private->SignatureGUID != NULL) {
1485 FreePool (Private->SignatureGUID);
1486 Private->SignatureGUID = NULL;
1487 }
1488
1489 if (Data != NULL) {
1490 FreePool (Data);
1491 }
1492
1493 if (mImageBase != NULL) {
1494 FreePool (mImageBase);
1495 mImageBase = NULL;
1496 }
1497
1498 return Status;
1499 }
1500
1501 /**
1502 Enroll signature into DB/DBX without KEK's authentication.
1503 The SignatureOwner GUID will be Private->SignatureGUID.
1504
1505 @param[in] PrivateData The module's private data.
1506 @param[in] VariableName Variable name of signature database, must be
1507 EFI_IMAGE_SECURITY_DATABASE or EFI_IMAGE_SECURITY_DATABASE1.
1508
1509 @retval EFI_SUCCESS New signature enrolled successfully.
1510 @retval EFI_INVALID_PARAMETER The parameter is invalid.
1511 @retval others Fail to enroll signature data.
1512
1513 **/
1514 EFI_STATUS
1515 EnrollSignatureDatabase (
1516 IN SECUREBOOT_CONFIG_PRIVATE_DATA *Private,
1517 IN CHAR16 *VariableName
1518 )
1519 {
1520 UINT16* FilePostFix;
1521 UINTN NameLength;
1522
1523 if ((Private->FileContext->FileName == NULL) || (Private->FileContext->FHandle == NULL) || (Private->SignatureGUID == NULL)) {
1524 return EFI_INVALID_PARAMETER;
1525 }
1526
1527 //
1528 // Parse the file's postfix.
1529 //
1530 NameLength = StrLen (Private->FileContext->FileName);
1531 if (NameLength <= 4) {
1532 return EFI_INVALID_PARAMETER;
1533 }
1534 FilePostFix = Private->FileContext->FileName + NameLength - 4;
1535 if (IsDerEncodeCertificate(FilePostFix)) {
1536 //
1537 // Supports DER-encoded X509 certificate.
1538 //
1539 return EnrollX509toSigDB (Private, VariableName);
1540 }
1541
1542 return EnrollImageSignatureToSigDB (Private, VariableName);
1543 }
1544
1545 /**
1546 List all signatures in specified signature database (e.g. KEK/DB/DBX)
1547 by GUID in the page for user to select and delete as needed.
1548
1549 @param[in] PrivateData Module's private data.
1550 @param[in] VariableName The variable name of the vendor's signature database.
1551 @param[in] VendorGuid A unique identifier for the vendor.
1552 @param[in] LabelNumber Label number to insert opcodes.
1553 @param[in] FormId Form ID of current page.
1554 @param[in] QuestionIdBase Base question id of the signature list.
1555
1556 @retval EFI_SUCCESS Success to update the signature list page
1557 @retval EFI_OUT_OF_RESOURCES Unable to allocate required resources.
1558
1559 **/
1560 EFI_STATUS
1561 UpdateDeletePage (
1562 IN SECUREBOOT_CONFIG_PRIVATE_DATA *PrivateData,
1563 IN CHAR16 *VariableName,
1564 IN EFI_GUID *VendorGuid,
1565 IN UINT16 LabelNumber,
1566 IN EFI_FORM_ID FormId,
1567 IN EFI_QUESTION_ID QuestionIdBase
1568 )
1569 {
1570 EFI_STATUS Status;
1571 UINT32 Index;
1572 UINTN CertCount;
1573 UINTN GuidIndex;
1574 VOID *StartOpCodeHandle;
1575 VOID *EndOpCodeHandle;
1576 EFI_IFR_GUID_LABEL *StartLabel;
1577 EFI_IFR_GUID_LABEL *EndLabel;
1578 UINTN DataSize;
1579 UINT8 *Data;
1580 EFI_SIGNATURE_LIST *CertList;
1581 EFI_SIGNATURE_DATA *Cert;
1582 UINT32 ItemDataSize;
1583 CHAR16 *GuidStr;
1584 EFI_STRING_ID GuidID;
1585 EFI_STRING_ID Help;
1586
1587 Data = NULL;
1588 CertList = NULL;
1589 Cert = NULL;
1590 GuidStr = NULL;
1591 StartOpCodeHandle = NULL;
1592 EndOpCodeHandle = NULL;
1593
1594 //
1595 // Initialize the container for dynamic opcodes.
1596 //
1597 StartOpCodeHandle = HiiAllocateOpCodeHandle ();
1598 if (StartOpCodeHandle == NULL) {
1599 Status = EFI_OUT_OF_RESOURCES;
1600 goto ON_EXIT;
1601 }
1602
1603 EndOpCodeHandle = HiiAllocateOpCodeHandle ();
1604 if (EndOpCodeHandle == NULL) {
1605 Status = EFI_OUT_OF_RESOURCES;
1606 goto ON_EXIT;
1607 }
1608
1609 //
1610 // Create Hii Extend Label OpCode.
1611 //
1612 StartLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (
1613 StartOpCodeHandle,
1614 &gEfiIfrTianoGuid,
1615 NULL,
1616 sizeof (EFI_IFR_GUID_LABEL)
1617 );
1618 StartLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
1619 StartLabel->Number = LabelNumber;
1620
1621 EndLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (
1622 EndOpCodeHandle,
1623 &gEfiIfrTianoGuid,
1624 NULL,
1625 sizeof (EFI_IFR_GUID_LABEL)
1626 );
1627 EndLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
1628 EndLabel->Number = LABEL_END;
1629
1630 //
1631 // Read Variable.
1632 //
1633 DataSize = 0;
1634 Status = gRT->GetVariable (VariableName, VendorGuid, NULL, &DataSize, Data);
1635 if (EFI_ERROR (Status) && Status != EFI_BUFFER_TOO_SMALL) {
1636 goto ON_EXIT;
1637 }
1638
1639 Data = (UINT8 *) AllocateZeroPool (DataSize);
1640 if (Data == NULL) {
1641 Status = EFI_OUT_OF_RESOURCES;
1642 goto ON_EXIT;
1643 }
1644
1645 Status = gRT->GetVariable (VariableName, VendorGuid, NULL, &DataSize, Data);
1646 if (EFI_ERROR (Status)) {
1647 goto ON_EXIT;
1648 }
1649
1650 GuidStr = AllocateZeroPool (100);
1651 if (GuidStr == NULL) {
1652 Status = EFI_OUT_OF_RESOURCES;
1653 goto ON_EXIT;
1654 }
1655
1656 //
1657 // Enumerate all KEK pub data.
1658 //
1659 ItemDataSize = (UINT32) DataSize;
1660 CertList = (EFI_SIGNATURE_LIST *) Data;
1661 GuidIndex = 0;
1662
1663 while ((ItemDataSize > 0) && (ItemDataSize >= CertList->SignatureListSize)) {
1664
1665 if (CompareGuid (&CertList->SignatureType, &gEfiCertRsa2048Guid)) {
1666 Help = STRING_TOKEN (STR_CERT_TYPE_RSA2048_SHA256_GUID);
1667 } else if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
1668 Help = STRING_TOKEN (STR_CERT_TYPE_PCKS7_GUID);
1669 } else if (CompareGuid (&CertList->SignatureType, &gEfiCertSha1Guid)) {
1670 Help = STRING_TOKEN (STR_CERT_TYPE_SHA1_GUID);
1671 } else if (CompareGuid (&CertList->SignatureType, &gEfiCertSha256Guid)) {
1672 Help = STRING_TOKEN (STR_CERT_TYPE_SHA256_GUID);
1673 } else {
1674 //
1675 // The signature type is not supported in current implementation.
1676 //
1677 continue;
1678 }
1679
1680 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1681 for (Index = 0; Index < CertCount; Index++) {
1682 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList
1683 + sizeof (EFI_SIGNATURE_LIST)
1684 + CertList->SignatureHeaderSize
1685 + Index * CertList->SignatureSize);
1686 //
1687 // Display GUID and help
1688 //
1689 GuidToString (&Cert->SignatureOwner, GuidStr, 100);
1690 GuidID = HiiSetString (PrivateData->HiiHandle, 0, GuidStr, NULL);
1691 HiiCreateCheckBoxOpCode (
1692 StartOpCodeHandle,
1693 (EFI_QUESTION_ID) (QuestionIdBase + GuidIndex++),
1694 0,
1695 0,
1696 GuidID,
1697 Help,
1698 EFI_IFR_FLAG_CALLBACK,
1699 0,
1700 NULL
1701 );
1702 }
1703
1704 ItemDataSize -= CertList->SignatureListSize;
1705 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1706 }
1707
1708 ON_EXIT:
1709 HiiUpdateForm (
1710 PrivateData->HiiHandle,
1711 &gSecureBootConfigFormSetGuid,
1712 FormId,
1713 StartOpCodeHandle,
1714 EndOpCodeHandle
1715 );
1716
1717 if (StartOpCodeHandle != NULL) {
1718 HiiFreeOpCodeHandle (StartOpCodeHandle);
1719 }
1720
1721 if (EndOpCodeHandle != NULL) {
1722 HiiFreeOpCodeHandle (EndOpCodeHandle);
1723 }
1724
1725 if (Data != NULL) {
1726 FreePool (Data);
1727 }
1728
1729 if (GuidStr != NULL) {
1730 FreePool (GuidStr);
1731 }
1732
1733 return EFI_SUCCESS;
1734 }
1735
1736 /**
1737 Delete a KEK entry from KEK database.
1738
1739 @param[in] PrivateData Module's private data.
1740 @param[in] QuestionId Question id of the KEK item to delete.
1741
1742 @retval EFI_SUCCESS Delete kek item successfully.
1743 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
1744
1745 **/
1746 EFI_STATUS
1747 DeleteKeyExchangeKey (
1748 IN SECUREBOOT_CONFIG_PRIVATE_DATA *PrivateData,
1749 IN EFI_QUESTION_ID QuestionId
1750 )
1751 {
1752 EFI_STATUS Status;
1753 UINTN DataSize;
1754 UINT8 *Data;
1755 UINT8 *OldData;
1756 UINT32 Attr;
1757 UINT32 Index;
1758 EFI_SIGNATURE_LIST *CertList;
1759 EFI_SIGNATURE_LIST *NewCertList;
1760 EFI_SIGNATURE_DATA *Cert;
1761 UINTN CertCount;
1762 UINT32 Offset;
1763 BOOLEAN IsKEKItemFound;
1764 UINT32 KekDataSize;
1765 UINTN DeleteKekIndex;
1766 UINTN GuidIndex;
1767
1768 Data = NULL;
1769 OldData = NULL;
1770 CertList = NULL;
1771 Cert = NULL;
1772 Attr = 0;
1773 DeleteKekIndex = QuestionId - OPTION_DEL_KEK_QUESTION_ID;
1774
1775 //
1776 // Get original KEK variable.
1777 //
1778 DataSize = 0;
1779 Status = gRT->GetVariable (EFI_KEY_EXCHANGE_KEY_NAME, &gEfiGlobalVariableGuid, NULL, &DataSize, NULL);
1780 if (EFI_ERROR(Status) && Status != EFI_BUFFER_TOO_SMALL) {
1781 goto ON_EXIT;
1782 }
1783
1784 OldData = (UINT8*)AllocateZeroPool(DataSize);
1785 if (OldData == NULL) {
1786 Status = EFI_OUT_OF_RESOURCES;
1787 goto ON_EXIT;
1788 }
1789
1790 Status = gRT->GetVariable (EFI_KEY_EXCHANGE_KEY_NAME, &gEfiGlobalVariableGuid, &Attr, &DataSize, OldData);
1791 if (EFI_ERROR(Status)) {
1792 goto ON_EXIT;
1793 }
1794
1795 //
1796 // Allocate space for new variable.
1797 //
1798 Data = (UINT8*) AllocateZeroPool (DataSize);
1799 if (Data == NULL) {
1800 Status = EFI_OUT_OF_RESOURCES;
1801 goto ON_EXIT;
1802 }
1803
1804 //
1805 // Enumerate all KEK pub data and erasing the target item.
1806 //
1807 IsKEKItemFound = FALSE;
1808 KekDataSize = (UINT32) DataSize;
1809 CertList = (EFI_SIGNATURE_LIST *) OldData;
1810 Offset = 0;
1811 GuidIndex = 0;
1812 while ((KekDataSize > 0) && (KekDataSize >= CertList->SignatureListSize)) {
1813 if (CompareGuid (&CertList->SignatureType, &gEfiCertRsa2048Guid) ||
1814 CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
1815 CopyMem (Data + Offset, CertList, (sizeof(EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize));
1816 NewCertList = (EFI_SIGNATURE_LIST *)(Data + Offset);
1817 Offset += (sizeof(EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1818 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1819 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1820 for (Index = 0; Index < CertCount; Index++) {
1821 if (GuidIndex == DeleteKekIndex ) {
1822 //
1823 // Find it! Skip it!
1824 //
1825 NewCertList->SignatureListSize -= CertList->SignatureSize;
1826 IsKEKItemFound = TRUE;
1827 } else {
1828 //
1829 // This item doesn't match. Copy it to the Data buffer.
1830 //
1831 CopyMem (Data + Offset, Cert, CertList->SignatureSize);
1832 Offset += CertList->SignatureSize;
1833 }
1834 GuidIndex++;
1835 Cert = (EFI_SIGNATURE_DATA *) ((UINT8*) Cert + CertList->SignatureSize);
1836 }
1837 } else {
1838 //
1839 // This List doesn't match. Copy it to the Data buffer.
1840 //
1841 CopyMem (Data + Offset, CertList, CertList->SignatureListSize);
1842 Offset += CertList->SignatureListSize;
1843 }
1844
1845 KekDataSize -= CertList->SignatureListSize;
1846 CertList = (EFI_SIGNATURE_LIST*) ((UINT8*) CertList + CertList->SignatureListSize);
1847 }
1848
1849 if (!IsKEKItemFound) {
1850 //
1851 // Doesn't find the Kek Item!
1852 //
1853 Status = EFI_NOT_FOUND;
1854 goto ON_EXIT;
1855 }
1856
1857 //
1858 // Delete the Signature header if there is no signature in the list.
1859 //
1860 KekDataSize = Offset;
1861 CertList = (EFI_SIGNATURE_LIST*) Data;
1862 Offset = 0;
1863 ZeroMem (OldData, KekDataSize);
1864 while ((KekDataSize > 0) && (KekDataSize >= CertList->SignatureListSize)) {
1865 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1866 DEBUG ((DEBUG_ERROR, " CertCount = %x\n", CertCount));
1867 if (CertCount != 0) {
1868 CopyMem (OldData + Offset, CertList, CertList->SignatureListSize);
1869 Offset += CertList->SignatureListSize;
1870 }
1871 KekDataSize -= CertList->SignatureListSize;
1872 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1873 }
1874
1875 DataSize = Offset;
1876 if ((Attr & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) {
1877 Status = CreateTimeBasedPayload (&DataSize, &OldData);
1878 if (EFI_ERROR (Status)) {
1879 DEBUG ((EFI_D_ERROR, "Fail to create time-based data payload: %r", Status));
1880 goto ON_EXIT;
1881 }
1882 }
1883
1884 Status = gRT->SetVariable(
1885 EFI_KEY_EXCHANGE_KEY_NAME,
1886 &gEfiGlobalVariableGuid,
1887 Attr,
1888 DataSize,
1889 OldData
1890 );
1891 if (EFI_ERROR (Status)) {
1892 DEBUG ((DEBUG_ERROR, "Failed to set variable, Status = %r\n", Status));
1893 goto ON_EXIT;
1894 }
1895
1896 ON_EXIT:
1897 if (Data != NULL) {
1898 FreePool(Data);
1899 }
1900
1901 if (OldData != NULL) {
1902 FreePool(OldData);
1903 }
1904
1905 return UpdateDeletePage (
1906 PrivateData,
1907 EFI_KEY_EXCHANGE_KEY_NAME,
1908 &gEfiGlobalVariableGuid,
1909 LABEL_KEK_DELETE,
1910 FORMID_DELETE_KEK_FORM,
1911 OPTION_DEL_KEK_QUESTION_ID
1912 );
1913 }
1914
1915 /**
1916 Delete a signature entry from siganture database.
1917
1918 @param[in] PrivateData Module's private data.
1919 @param[in] VariableName The variable name of the vendor's signature database.
1920 @param[in] VendorGuid A unique identifier for the vendor.
1921 @param[in] LabelNumber Label number to insert opcodes.
1922 @param[in] FormId Form ID of current page.
1923 @param[in] QuestionIdBase Base question id of the signature list.
1924 @param[in] DeleteIndex Signature index to delete.
1925
1926 @retval EFI_SUCCESS Delete siganture successfully.
1927 @retval EFI_NOT_FOUND Can't find the signature item,
1928 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
1929 **/
1930 EFI_STATUS
1931 DeleteSignature (
1932 IN SECUREBOOT_CONFIG_PRIVATE_DATA *PrivateData,
1933 IN CHAR16 *VariableName,
1934 IN EFI_GUID *VendorGuid,
1935 IN UINT16 LabelNumber,
1936 IN EFI_FORM_ID FormId,
1937 IN EFI_QUESTION_ID QuestionIdBase,
1938 IN UINTN DeleteIndex
1939 )
1940 {
1941 EFI_STATUS Status;
1942 UINTN DataSize;
1943 UINT8 *Data;
1944 UINT8 *OldData;
1945 UINT32 Attr;
1946 UINT32 Index;
1947 EFI_SIGNATURE_LIST *CertList;
1948 EFI_SIGNATURE_LIST *NewCertList;
1949 EFI_SIGNATURE_DATA *Cert;
1950 UINTN CertCount;
1951 UINT32 Offset;
1952 BOOLEAN IsItemFound;
1953 UINT32 ItemDataSize;
1954 UINTN GuidIndex;
1955
1956 Data = NULL;
1957 OldData = NULL;
1958 CertList = NULL;
1959 Cert = NULL;
1960 Attr = 0;
1961
1962 //
1963 // Get original signature list data.
1964 //
1965 DataSize = 0;
1966 Status = gRT->GetVariable (VariableName, VendorGuid, NULL, &DataSize, NULL);
1967 if (EFI_ERROR (Status) && Status != EFI_BUFFER_TOO_SMALL) {
1968 goto ON_EXIT;
1969 }
1970
1971 OldData = (UINT8 *) AllocateZeroPool (DataSize);
1972 if (OldData == NULL) {
1973 Status = EFI_OUT_OF_RESOURCES;
1974 goto ON_EXIT;
1975 }
1976
1977 Status = gRT->GetVariable (VariableName, VendorGuid, &Attr, &DataSize, OldData);
1978 if (EFI_ERROR(Status)) {
1979 goto ON_EXIT;
1980 }
1981
1982 //
1983 // Allocate space for new variable.
1984 //
1985 Data = (UINT8*) AllocateZeroPool (DataSize);
1986 if (Data == NULL) {
1987 Status = EFI_OUT_OF_RESOURCES;
1988 goto ON_EXIT;
1989 }
1990
1991 //
1992 // Enumerate all signature data and erasing the target item.
1993 //
1994 IsItemFound = FALSE;
1995 ItemDataSize = (UINT32) DataSize;
1996 CertList = (EFI_SIGNATURE_LIST *) OldData;
1997 Offset = 0;
1998 GuidIndex = 0;
1999 while ((ItemDataSize > 0) && (ItemDataSize >= CertList->SignatureListSize)) {
2000 if (CompareGuid (&CertList->SignatureType, &gEfiCertRsa2048Guid) ||
2001 CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid) ||
2002 CompareGuid (&CertList->SignatureType, &gEfiCertSha1Guid) ||
2003 CompareGuid (&CertList->SignatureType, &gEfiCertSha256Guid)
2004 ) {
2005 //
2006 // Copy EFI_SIGNATURE_LIST header then calculate the signature count in this list.
2007 //
2008 CopyMem (Data + Offset, CertList, (sizeof(EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize));
2009 NewCertList = (EFI_SIGNATURE_LIST*) (Data + Offset);
2010 Offset += (sizeof(EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2011 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2012 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
2013 for (Index = 0; Index < CertCount; Index++) {
2014 if (GuidIndex == DeleteIndex) {
2015 //
2016 // Find it! Skip it!
2017 //
2018 NewCertList->SignatureListSize -= CertList->SignatureSize;
2019 IsItemFound = TRUE;
2020 } else {
2021 //
2022 // This item doesn't match. Copy it to the Data buffer.
2023 //
2024 CopyMem (Data + Offset, (UINT8*)(Cert), CertList->SignatureSize);
2025 Offset += CertList->SignatureSize;
2026 }
2027 GuidIndex++;
2028 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
2029 }
2030 } else {
2031 //
2032 // This List doesn't match. Just copy it to the Data buffer.
2033 //
2034 CopyMem (Data + Offset, (UINT8*)(CertList), CertList->SignatureListSize);
2035 Offset += CertList->SignatureListSize;
2036 }
2037
2038 ItemDataSize -= CertList->SignatureListSize;
2039 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
2040 }
2041
2042 if (!IsItemFound) {
2043 //
2044 // Doesn't find the signature Item!
2045 //
2046 Status = EFI_NOT_FOUND;
2047 goto ON_EXIT;
2048 }
2049
2050 //
2051 // Delete the EFI_SIGNATURE_LIST header if there is no signature in the list.
2052 //
2053 ItemDataSize = Offset;
2054 CertList = (EFI_SIGNATURE_LIST *) Data;
2055 Offset = 0;
2056 ZeroMem (OldData, ItemDataSize);
2057 while ((ItemDataSize > 0) && (ItemDataSize >= CertList->SignatureListSize)) {
2058 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
2059 DEBUG ((DEBUG_ERROR, " CertCount = %x\n", CertCount));
2060 if (CertCount != 0) {
2061 CopyMem (OldData + Offset, (UINT8*)(CertList), CertList->SignatureListSize);
2062 Offset += CertList->SignatureListSize;
2063 }
2064 ItemDataSize -= CertList->SignatureListSize;
2065 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
2066 }
2067
2068 DataSize = Offset;
2069 if ((Attr & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) {
2070 Status = CreateTimeBasedPayload (&DataSize, &OldData);
2071 if (EFI_ERROR (Status)) {
2072 DEBUG ((EFI_D_ERROR, "Fail to create time-based data payload: %r", Status));
2073 goto ON_EXIT;
2074 }
2075 }
2076
2077 Status = gRT->SetVariable(
2078 VariableName,
2079 VendorGuid,
2080 Attr,
2081 DataSize,
2082 OldData
2083 );
2084 if (EFI_ERROR (Status)) {
2085 DEBUG ((DEBUG_ERROR, "Failed to set variable, Status = %r\n", Status));
2086 goto ON_EXIT;
2087 }
2088
2089 ON_EXIT:
2090 if (Data != NULL) {
2091 FreePool(Data);
2092 }
2093
2094 if (OldData != NULL) {
2095 FreePool(OldData);
2096 }
2097
2098 return UpdateDeletePage (
2099 PrivateData,
2100 VariableName,
2101 VendorGuid,
2102 LabelNumber,
2103 FormId,
2104 QuestionIdBase
2105 );
2106 }
2107
2108 /**
2109 This function extracts configuration from variable.
2110
2111 @param[in, out] ConfigData Point to SecureBoot configuration private data.
2112
2113 **/
2114 VOID
2115 SecureBootExtractConfigFromVariable (
2116 IN OUT SECUREBOOT_CONFIGURATION *ConfigData
2117 )
2118 {
2119 UINT8 *SecureBootEnable;
2120 UINT8 *SetupMode;
2121 UINT8 *SecureBoot;
2122 UINT8 *SecureBootMode;
2123
2124 SecureBootEnable = NULL;
2125 SetupMode = NULL;
2126 SecureBoot = NULL;
2127 SecureBootMode = NULL;
2128
2129 //
2130 // If the SecureBootEnable Variable doesn't exist, hide the SecureBoot Enable/Disable
2131 // Checkbox.
2132 //
2133 GetVariable2 (EFI_SECURE_BOOT_ENABLE_NAME, &gEfiSecureBootEnableDisableGuid, (VOID**)&SecureBootEnable, NULL);
2134 if (SecureBootEnable == NULL) {
2135 ConfigData->HideSecureBoot = TRUE;
2136 } else {
2137 ConfigData->HideSecureBoot = FALSE;
2138 }
2139
2140 //
2141 // If it is Physical Presence User, set the PhysicalPresent to true.
2142 //
2143 if (UserPhysicalPresent()) {
2144 ConfigData->PhysicalPresent = TRUE;
2145 } else {
2146 ConfigData->PhysicalPresent = FALSE;
2147 }
2148
2149 //
2150 // If there is no PK then the Delete Pk button will be gray.
2151 //
2152 GetVariable2 (EFI_SETUP_MODE_NAME, &gEfiGlobalVariableGuid, (VOID**)&SetupMode, NULL);
2153 if (SetupMode == NULL || (*SetupMode) == SETUP_MODE) {
2154 ConfigData->HasPk = FALSE;
2155 } else {
2156 ConfigData->HasPk = TRUE;
2157 }
2158
2159 //
2160 // If the value of SecureBoot variable is 1, the platform is operating in secure boot mode.
2161 //
2162 GetVariable2 (EFI_SECURE_BOOT_MODE_NAME, &gEfiGlobalVariableGuid, (VOID**)&SecureBoot, NULL);
2163 if (SecureBoot != NULL && *SecureBoot == SECURE_BOOT_MODE_ENABLE) {
2164 ConfigData->SecureBootState = TRUE;
2165 } else {
2166 ConfigData->SecureBootState = FALSE;
2167 }
2168
2169 //
2170 // Get the SecureBootMode from CustomMode variable.
2171 //
2172 GetVariable2 (EFI_CUSTOM_MODE_NAME, &gEfiCustomModeEnableGuid, (VOID**)&SecureBootMode, NULL);
2173 if (SecureBootMode == NULL) {
2174 ConfigData->SecureBootMode = STANDARD_SECURE_BOOT_MODE;
2175 } else {
2176 ConfigData->SecureBootMode = *(SecureBootMode);
2177 }
2178
2179 }
2180
2181 /**
2182 This function allows a caller to extract the current configuration for one
2183 or more named elements from the target driver.
2184
2185 @param[in] This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
2186 @param[in] Request A null-terminated Unicode string in
2187 <ConfigRequest> format.
2188 @param[out] Progress On return, points to a character in the Request
2189 string. Points to the string's null terminator if
2190 request was successful. Points to the most recent
2191 '&' before the first failing name/value pair (or
2192 the beginning of the string if the failure is in
2193 the first name/value pair) if the request was not
2194 successful.
2195 @param[out] Results A null-terminated Unicode string in
2196 <ConfigAltResp> format which has all values filled
2197 in for the names in the Request string. String to
2198 be allocated by the called function.
2199
2200 @retval EFI_SUCCESS The Results is filled with the requested values.
2201 @retval EFI_OUT_OF_RESOURCES Not enough memory to store the results.
2202 @retval EFI_INVALID_PARAMETER Request is illegal syntax, or unknown name.
2203 @retval EFI_NOT_FOUND Routing data doesn't match any storage in this
2204 driver.
2205
2206 **/
2207 EFI_STATUS
2208 EFIAPI
2209 SecureBootExtractConfig (
2210 IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
2211 IN CONST EFI_STRING Request,
2212 OUT EFI_STRING *Progress,
2213 OUT EFI_STRING *Results
2214 )
2215 {
2216 EFI_STATUS Status;
2217 UINTN BufferSize;
2218 UINTN Size;
2219 SECUREBOOT_CONFIGURATION Configuration;
2220 EFI_STRING ConfigRequest;
2221 EFI_STRING ConfigRequestHdr;
2222 SECUREBOOT_CONFIG_PRIVATE_DATA *PrivateData;
2223 BOOLEAN AllocatedRequest;
2224
2225 if (Progress == NULL || Results == NULL) {
2226 return EFI_INVALID_PARAMETER;
2227 }
2228
2229 AllocatedRequest = FALSE;
2230 ConfigRequestHdr = NULL;
2231 ConfigRequest = NULL;
2232 Size = 0;
2233
2234 ZeroMem (&Configuration, sizeof (Configuration));
2235 PrivateData = SECUREBOOT_CONFIG_PRIVATE_FROM_THIS (This);
2236 *Progress = Request;
2237
2238 if ((Request != NULL) && !HiiIsConfigHdrMatch (Request, &gSecureBootConfigFormSetGuid, mSecureBootStorageName)) {
2239 return EFI_NOT_FOUND;
2240 }
2241
2242 //
2243 // Get Configuration from Variable.
2244 //
2245 SecureBootExtractConfigFromVariable (&Configuration);
2246
2247 BufferSize = sizeof (SECUREBOOT_CONFIGURATION);
2248 ConfigRequest = Request;
2249 if ((Request == NULL) || (StrStr (Request, L"OFFSET") == NULL)) {
2250 //
2251 // Request is set to NULL or OFFSET is NULL, construct full request string.
2252 //
2253 // Allocate and fill a buffer large enough to hold the <ConfigHdr> template
2254 // followed by "&OFFSET=0&WIDTH=WWWWWWWWWWWWWWWW" followed by a Null-terminator
2255 //
2256 ConfigRequestHdr = HiiConstructConfigHdr (&gSecureBootConfigFormSetGuid, mSecureBootStorageName, PrivateData->DriverHandle);
2257 Size = (StrLen (ConfigRequestHdr) + 32 + 1) * sizeof (CHAR16);
2258 ConfigRequest = AllocateZeroPool (Size);
2259 ASSERT (ConfigRequest != NULL);
2260 AllocatedRequest = TRUE;
2261 UnicodeSPrint (ConfigRequest, Size, L"%s&OFFSET=0&WIDTH=%016LX", ConfigRequestHdr, (UINT64)BufferSize);
2262 FreePool (ConfigRequestHdr);
2263 ConfigRequestHdr = NULL;
2264 }
2265
2266 Status = gHiiConfigRouting->BlockToConfig (
2267 gHiiConfigRouting,
2268 ConfigRequest,
2269 (UINT8 *) &Configuration,
2270 BufferSize,
2271 Results,
2272 Progress
2273 );
2274
2275 //
2276 // Free the allocated config request string.
2277 //
2278 if (AllocatedRequest) {
2279 FreePool (ConfigRequest);
2280 }
2281
2282 //
2283 // Set Progress string to the original request string.
2284 //
2285 if (Request == NULL) {
2286 *Progress = NULL;
2287 } else if (StrStr (Request, L"OFFSET") == NULL) {
2288 *Progress = Request + StrLen (Request);
2289 }
2290
2291 return Status;
2292 }
2293
2294 /**
2295 This function processes the results of changes in configuration.
2296
2297 @param[in] This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
2298 @param[in] Configuration A null-terminated Unicode string in <ConfigResp>
2299 format.
2300 @param[out] Progress A pointer to a string filled in with the offset of
2301 the most recent '&' before the first failing
2302 name/value pair (or the beginning of the string if
2303 the failure is in the first name/value pair) or
2304 the terminating NULL if all was successful.
2305
2306 @retval EFI_SUCCESS The Results is processed successfully.
2307 @retval EFI_INVALID_PARAMETER Configuration is NULL.
2308 @retval EFI_NOT_FOUND Routing data doesn't match any storage in this
2309 driver.
2310
2311 **/
2312 EFI_STATUS
2313 EFIAPI
2314 SecureBootRouteConfig (
2315 IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
2316 IN CONST EFI_STRING Configuration,
2317 OUT EFI_STRING *Progress
2318 )
2319 {
2320 if (Configuration == NULL || Progress == NULL) {
2321 return EFI_INVALID_PARAMETER;
2322 }
2323
2324 *Progress = Configuration;
2325 if (!HiiIsConfigHdrMatch (Configuration, &gSecureBootConfigFormSetGuid, mSecureBootStorageName)) {
2326 return EFI_NOT_FOUND;
2327 }
2328
2329 *Progress = Configuration + StrLen (Configuration);
2330 return EFI_SUCCESS;
2331 }
2332
2333 /**
2334 This function is called to provide results data to the driver.
2335
2336 @param[in] This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
2337 @param[in] Action Specifies the type of action taken by the browser.
2338 @param[in] QuestionId A unique value which is sent to the original
2339 exporting driver so that it can identify the type
2340 of data to expect.
2341 @param[in] Type The type of value for the question.
2342 @param[in] Value A pointer to the data being sent to the original
2343 exporting driver.
2344 @param[out] ActionRequest On return, points to the action requested by the
2345 callback function.
2346
2347 @retval EFI_SUCCESS The callback successfully handled the action.
2348 @retval EFI_OUT_OF_RESOURCES Not enough storage is available to hold the
2349 variable and its data.
2350 @retval EFI_DEVICE_ERROR The variable could not be saved.
2351 @retval EFI_UNSUPPORTED The specified Action is not supported by the
2352 callback.
2353
2354 **/
2355 EFI_STATUS
2356 EFIAPI
2357 SecureBootCallback (
2358 IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
2359 IN EFI_BROWSER_ACTION Action,
2360 IN EFI_QUESTION_ID QuestionId,
2361 IN UINT8 Type,
2362 IN EFI_IFR_TYPE_VALUE *Value,
2363 OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest
2364 )
2365 {
2366 EFI_INPUT_KEY Key;
2367 EFI_STATUS Status;
2368 SECUREBOOT_CONFIG_PRIVATE_DATA *Private;
2369 UINTN BufferSize;
2370 SECUREBOOT_CONFIGURATION *IfrNvData;
2371 UINT16 LabelId;
2372 UINT8 *SecureBootEnable;
2373 CHAR16 PromptString[100];
2374
2375 SecureBootEnable = NULL;
2376
2377 if ((This == NULL) || (Value == NULL) || (ActionRequest == NULL)) {
2378 return EFI_INVALID_PARAMETER;
2379 }
2380
2381 if ((Action != EFI_BROWSER_ACTION_CHANGED) && (Action != EFI_BROWSER_ACTION_CHANGING)) {
2382 return EFI_UNSUPPORTED;
2383 }
2384
2385 Private = SECUREBOOT_CONFIG_PRIVATE_FROM_THIS (This);
2386
2387 //
2388 // Retrieve uncommitted data from Browser
2389 //
2390 BufferSize = sizeof (SECUREBOOT_CONFIGURATION);
2391 IfrNvData = AllocateZeroPool (BufferSize);
2392 if (IfrNvData == NULL) {
2393 return EFI_OUT_OF_RESOURCES;
2394 }
2395
2396 Status = EFI_SUCCESS;
2397
2398 HiiGetBrowserData (NULL, NULL, BufferSize, (UINT8 *) IfrNvData);
2399
2400 if (Action == EFI_BROWSER_ACTION_CHANGING) {
2401
2402 switch (QuestionId) {
2403 case KEY_SECURE_BOOT_ENABLE:
2404 GetVariable2 (EFI_SECURE_BOOT_ENABLE_NAME, &gEfiSecureBootEnableDisableGuid, (VOID**)&SecureBootEnable, NULL);
2405 if (NULL != SecureBootEnable) {
2406 if (EFI_ERROR (SaveSecureBootVariable (Value->u8))) {
2407 CreatePopUp (
2408 EFI_LIGHTGRAY | EFI_BACKGROUND_BLUE,
2409 &Key,
2410 L"Only Physical Presence User could disable secure boot!",
2411 NULL
2412 );
2413 Status = EFI_UNSUPPORTED;
2414 }
2415 *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_APPLY;
2416 }
2417 break;
2418
2419 case KEY_SECURE_BOOT_OPTION:
2420 FreeMenu (&DirectoryMenu);
2421 FreeMenu (&FsOptionMenu);
2422 break;
2423
2424 case KEY_SECURE_BOOT_KEK_OPTION:
2425 case KEY_SECURE_BOOT_DB_OPTION:
2426 case KEY_SECURE_BOOT_DBX_OPTION:
2427 //
2428 // Clear Signature GUID.
2429 //
2430 ZeroMem (IfrNvData->SignatureGuid, sizeof (IfrNvData->SignatureGuid));
2431 if (Private->SignatureGUID == NULL) {
2432 Private->SignatureGUID = (EFI_GUID *) AllocateZeroPool (sizeof (EFI_GUID));
2433 if (Private->SignatureGUID == NULL) {
2434 return EFI_OUT_OF_RESOURCES;
2435 }
2436 }
2437
2438 if (QuestionId == KEY_SECURE_BOOT_DB_OPTION) {
2439 LabelId = SECUREBOOT_ENROLL_SIGNATURE_TO_DB;
2440 } else if (QuestionId == KEY_SECURE_BOOT_DBX_OPTION) {
2441 LabelId = SECUREBOOT_ENROLL_SIGNATURE_TO_DBX;
2442 } else {
2443 LabelId = FORMID_ENROLL_KEK_FORM;
2444 }
2445
2446 //
2447 // Refresh selected file.
2448 //
2449 CleanUpPage (LabelId, Private);
2450 break;
2451
2452 case SECUREBOOT_ADD_PK_FILE_FORM_ID:
2453 case FORMID_ENROLL_KEK_FORM:
2454 case SECUREBOOT_ENROLL_SIGNATURE_TO_DB:
2455 case SECUREBOOT_ENROLL_SIGNATURE_TO_DBX:
2456 if (QuestionId == SECUREBOOT_ADD_PK_FILE_FORM_ID) {
2457 Private->FeCurrentState = FileExplorerStateEnrollPkFile;
2458 } else if (QuestionId == FORMID_ENROLL_KEK_FORM) {
2459 Private->FeCurrentState = FileExplorerStateEnrollKekFile;
2460 } else if (QuestionId == SECUREBOOT_ENROLL_SIGNATURE_TO_DB) {
2461 Private->FeCurrentState = FileExplorerStateEnrollSignatureFileToDb;
2462 } else {
2463 Private->FeCurrentState = FileExplorerStateEnrollSignatureFileToDbx;
2464 }
2465
2466 Private->FeDisplayContext = FileExplorerDisplayUnknown;
2467 CleanUpPage (FORM_FILE_EXPLORER_ID, Private);
2468 UpdateFileExplorer (Private, 0);
2469 break;
2470
2471 case KEY_SECURE_BOOT_DELETE_PK:
2472 if (Value->u8) {
2473 Status = DeletePlatformKey ();
2474 *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_APPLY;
2475 }
2476 break;
2477
2478 case KEY_DELETE_KEK:
2479 UpdateDeletePage (
2480 Private,
2481 EFI_KEY_EXCHANGE_KEY_NAME,
2482 &gEfiGlobalVariableGuid,
2483 LABEL_KEK_DELETE,
2484 FORMID_DELETE_KEK_FORM,
2485 OPTION_DEL_KEK_QUESTION_ID
2486 );
2487 break;
2488
2489 case SECUREBOOT_DELETE_SIGNATURE_FROM_DB:
2490 UpdateDeletePage (
2491 Private,
2492 EFI_IMAGE_SECURITY_DATABASE,
2493 &gEfiImageSecurityDatabaseGuid,
2494 LABEL_DB_DELETE,
2495 SECUREBOOT_DELETE_SIGNATURE_FROM_DB,
2496 OPTION_DEL_DB_QUESTION_ID
2497 );
2498 break;
2499
2500 case SECUREBOOT_DELETE_SIGNATURE_FROM_DBX:
2501 UpdateDeletePage (
2502 Private,
2503 EFI_IMAGE_SECURITY_DATABASE1,
2504 &gEfiImageSecurityDatabaseGuid,
2505 LABEL_DBX_DELETE,
2506 SECUREBOOT_DELETE_SIGNATURE_FROM_DBX,
2507 OPTION_DEL_DBX_QUESTION_ID
2508 );
2509
2510 break;
2511
2512 case KEY_VALUE_SAVE_AND_EXIT_KEK:
2513 Status = EnrollKeyExchangeKey (Private);
2514 break;
2515
2516 case KEY_VALUE_SAVE_AND_EXIT_DB:
2517 Status = EnrollSignatureDatabase (Private, EFI_IMAGE_SECURITY_DATABASE);
2518 break;
2519
2520 case KEY_VALUE_SAVE_AND_EXIT_DBX:
2521 Status = EnrollSignatureDatabase (Private, EFI_IMAGE_SECURITY_DATABASE1);
2522 break;
2523
2524 default:
2525 if (QuestionId >= FILE_OPTION_OFFSET) {
2526 UpdateFileExplorer (Private, QuestionId);
2527 } else if ((QuestionId >= OPTION_DEL_KEK_QUESTION_ID) &&
2528 (QuestionId < (OPTION_DEL_KEK_QUESTION_ID + OPTION_CONFIG_RANGE))) {
2529 DeleteKeyExchangeKey (Private, QuestionId);
2530 } else if ((QuestionId >= OPTION_DEL_DB_QUESTION_ID) &&
2531 (QuestionId < (OPTION_DEL_DB_QUESTION_ID + OPTION_CONFIG_RANGE))) {
2532 DeleteSignature (
2533 Private,
2534 EFI_IMAGE_SECURITY_DATABASE,
2535 &gEfiImageSecurityDatabaseGuid,
2536 LABEL_DB_DELETE,
2537 SECUREBOOT_DELETE_SIGNATURE_FROM_DB,
2538 OPTION_DEL_DB_QUESTION_ID,
2539 QuestionId - OPTION_DEL_DB_QUESTION_ID
2540 );
2541 } else if ((QuestionId >= OPTION_DEL_DBX_QUESTION_ID) &&
2542 (QuestionId < (OPTION_DEL_DBX_QUESTION_ID + OPTION_CONFIG_RANGE))) {
2543 DeleteSignature (
2544 Private,
2545 EFI_IMAGE_SECURITY_DATABASE1,
2546 &gEfiImageSecurityDatabaseGuid,
2547 LABEL_DBX_DELETE,
2548 SECUREBOOT_DELETE_SIGNATURE_FROM_DBX,
2549 OPTION_DEL_DBX_QUESTION_ID,
2550 QuestionId - OPTION_DEL_DBX_QUESTION_ID
2551 );
2552 }
2553 break;
2554 }
2555 } else if (Action == EFI_BROWSER_ACTION_CHANGED) {
2556 switch (QuestionId) {
2557 case KEY_SECURE_BOOT_ENABLE:
2558 *ActionRequest = EFI_BROWSER_ACTION_REQUEST_SUBMIT;
2559 break;
2560 case KEY_VALUE_SAVE_AND_EXIT_PK:
2561 Status = EnrollPlatformKey (Private);
2562 UnicodeSPrint (
2563 PromptString,
2564 sizeof (PromptString),
2565 L"Only DER encoded certificate file (%s) is supported.",
2566 mSupportX509Suffix
2567 );
2568 if (EFI_ERROR (Status)) {
2569 CreatePopUp (
2570 EFI_LIGHTGRAY | EFI_BACKGROUND_BLUE,
2571 &Key,
2572 L"ERROR: Unsupported file type!",
2573 PromptString,
2574 NULL
2575 );
2576 } else {
2577 *ActionRequest = EFI_BROWSER_ACTION_REQUEST_SUBMIT;
2578 }
2579 break;
2580
2581 case KEY_VALUE_NO_SAVE_AND_EXIT_PK:
2582 case KEY_VALUE_NO_SAVE_AND_EXIT_KEK:
2583 case KEY_VALUE_NO_SAVE_AND_EXIT_DB:
2584 case KEY_VALUE_NO_SAVE_AND_EXIT_DBX:
2585 if (Private->FileContext->FHandle != NULL) {
2586 CloseFile (Private->FileContext->FHandle);
2587 Private->FileContext->FHandle = NULL;
2588 Private->FileContext->FileName = NULL;
2589 }
2590
2591 if (Private->SignatureGUID != NULL) {
2592 FreePool (Private->SignatureGUID);
2593 Private->SignatureGUID = NULL;
2594 }
2595 *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT;
2596 break;
2597
2598 case KEY_SECURE_BOOT_MODE:
2599 GetVariable2 (EFI_CUSTOM_MODE_NAME, &gEfiCustomModeEnableGuid, (VOID**)&SecureBootEnable, NULL);
2600 if (NULL != SecureBootEnable) {
2601 Status = gRT->SetVariable (
2602 EFI_CUSTOM_MODE_NAME,
2603 &gEfiCustomModeEnableGuid,
2604 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
2605 sizeof (UINT8),
2606 &Value->u8
2607 );
2608 *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_APPLY;
2609 IfrNvData->SecureBootMode = Value->u8;
2610 }
2611 break;
2612
2613 case KEY_SECURE_BOOT_KEK_GUID:
2614 case KEY_SECURE_BOOT_SIGNATURE_GUID_DB:
2615 case KEY_SECURE_BOOT_SIGNATURE_GUID_DBX:
2616 ASSERT (Private->SignatureGUID != NULL);
2617 Status = StringToGuid (
2618 IfrNvData->SignatureGuid,
2619 StrLen (IfrNvData->SignatureGuid),
2620 Private->SignatureGUID
2621 );
2622 if (EFI_ERROR (Status)) {
2623 break;
2624 }
2625
2626 *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_APPLY;
2627 break;
2628
2629 case KEY_SECURE_BOOT_DELETE_PK:
2630 if (Value->u8) {
2631 *ActionRequest = EFI_BROWSER_ACTION_REQUEST_SUBMIT;
2632 }
2633 break;
2634 }
2635 }
2636
2637 if (!EFI_ERROR (Status)) {
2638 BufferSize = sizeof (SECUREBOOT_CONFIGURATION);
2639 HiiSetBrowserData (NULL, NULL, BufferSize, (UINT8*) IfrNvData, NULL);
2640 }
2641 FreePool (IfrNvData);
2642
2643 return EFI_SUCCESS;
2644 }
2645
2646 /**
2647 This function publish the SecureBoot configuration Form.
2648
2649 @param[in, out] PrivateData Points to SecureBoot configuration private data.
2650
2651 @retval EFI_SUCCESS HII Form is installed successfully.
2652 @retval EFI_OUT_OF_RESOURCES Not enough resource for HII Form installation.
2653 @retval Others Other errors as indicated.
2654
2655 **/
2656 EFI_STATUS
2657 InstallSecureBootConfigForm (
2658 IN OUT SECUREBOOT_CONFIG_PRIVATE_DATA *PrivateData
2659 )
2660 {
2661 EFI_STATUS Status;
2662 EFI_HII_HANDLE HiiHandle;
2663 EFI_HANDLE DriverHandle;
2664 EFI_HII_CONFIG_ACCESS_PROTOCOL *ConfigAccess;
2665
2666 DriverHandle = NULL;
2667 ConfigAccess = &PrivateData->ConfigAccess;
2668 Status = gBS->InstallMultipleProtocolInterfaces (
2669 &DriverHandle,
2670 &gEfiDevicePathProtocolGuid,
2671 &mSecureBootHiiVendorDevicePath,
2672 &gEfiHiiConfigAccessProtocolGuid,
2673 ConfigAccess,
2674 NULL
2675 );
2676 if (EFI_ERROR (Status)) {
2677 return Status;
2678 }
2679
2680 PrivateData->DriverHandle = DriverHandle;
2681
2682 //
2683 // Publish the HII package list
2684 //
2685 HiiHandle = HiiAddPackages (
2686 &gSecureBootConfigFormSetGuid,
2687 DriverHandle,
2688 SecureBootConfigDxeStrings,
2689 SecureBootConfigBin,
2690 NULL
2691 );
2692 if (HiiHandle == NULL) {
2693 gBS->UninstallMultipleProtocolInterfaces (
2694 DriverHandle,
2695 &gEfiDevicePathProtocolGuid,
2696 &mSecureBootHiiVendorDevicePath,
2697 &gEfiHiiConfigAccessProtocolGuid,
2698 ConfigAccess,
2699 NULL
2700 );
2701 return EFI_OUT_OF_RESOURCES;
2702 }
2703
2704 PrivateData->HiiHandle = HiiHandle;
2705
2706 PrivateData->FileContext = AllocateZeroPool (sizeof (SECUREBOOT_FILE_CONTEXT));
2707 PrivateData->MenuEntry = AllocateZeroPool (sizeof (SECUREBOOT_MENU_ENTRY));
2708
2709 if (PrivateData->FileContext == NULL || PrivateData->MenuEntry == NULL) {
2710 UninstallSecureBootConfigForm (PrivateData);
2711 return EFI_OUT_OF_RESOURCES;
2712 }
2713
2714 PrivateData->FeCurrentState = FileExplorerStateInActive;
2715 PrivateData->FeDisplayContext = FileExplorerDisplayUnknown;
2716
2717 InitializeListHead (&FsOptionMenu.Head);
2718 InitializeListHead (&DirectoryMenu.Head);
2719
2720 //
2721 // Init OpCode Handle and Allocate space for creation of Buffer
2722 //
2723 mStartOpCodeHandle = HiiAllocateOpCodeHandle ();
2724 if (mStartOpCodeHandle == NULL) {
2725 UninstallSecureBootConfigForm (PrivateData);
2726 return EFI_OUT_OF_RESOURCES;
2727 }
2728
2729 mEndOpCodeHandle = HiiAllocateOpCodeHandle ();
2730 if (mEndOpCodeHandle == NULL) {
2731 UninstallSecureBootConfigForm (PrivateData);
2732 return EFI_OUT_OF_RESOURCES;
2733 }
2734
2735 //
2736 // Create Hii Extend Label OpCode as the start opcode
2737 //
2738 mStartLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (
2739 mStartOpCodeHandle,
2740 &gEfiIfrTianoGuid,
2741 NULL,
2742 sizeof (EFI_IFR_GUID_LABEL)
2743 );
2744 mStartLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
2745
2746 //
2747 // Create Hii Extend Label OpCode as the end opcode
2748 //
2749 mEndLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (
2750 mEndOpCodeHandle,
2751 &gEfiIfrTianoGuid,
2752 NULL,
2753 sizeof (EFI_IFR_GUID_LABEL)
2754 );
2755 mEndLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
2756 mEndLabel->Number = LABEL_END;
2757
2758 return EFI_SUCCESS;
2759 }
2760
2761 /**
2762 This function removes SecureBoot configuration Form.
2763
2764 @param[in, out] PrivateData Points to SecureBoot configuration private data.
2765
2766 **/
2767 VOID
2768 UninstallSecureBootConfigForm (
2769 IN OUT SECUREBOOT_CONFIG_PRIVATE_DATA *PrivateData
2770 )
2771 {
2772 //
2773 // Uninstall HII package list
2774 //
2775 if (PrivateData->HiiHandle != NULL) {
2776 HiiRemovePackages (PrivateData->HiiHandle);
2777 PrivateData->HiiHandle = NULL;
2778 }
2779
2780 //
2781 // Uninstall HII Config Access Protocol
2782 //
2783 if (PrivateData->DriverHandle != NULL) {
2784 gBS->UninstallMultipleProtocolInterfaces (
2785 PrivateData->DriverHandle,
2786 &gEfiDevicePathProtocolGuid,
2787 &mSecureBootHiiVendorDevicePath,
2788 &gEfiHiiConfigAccessProtocolGuid,
2789 &PrivateData->ConfigAccess,
2790 NULL
2791 );
2792 PrivateData->DriverHandle = NULL;
2793 }
2794
2795 if (PrivateData->SignatureGUID != NULL) {
2796 FreePool (PrivateData->SignatureGUID);
2797 }
2798
2799 if (PrivateData->MenuEntry != NULL) {
2800 FreePool (PrivateData->MenuEntry);
2801 }
2802
2803 if (PrivateData->FileContext != NULL) {
2804 FreePool (PrivateData->FileContext);
2805 }
2806
2807 FreePool (PrivateData);
2808
2809 FreeMenu (&DirectoryMenu);
2810 FreeMenu (&FsOptionMenu);
2811
2812 if (mStartOpCodeHandle != NULL) {
2813 HiiFreeOpCodeHandle (mStartOpCodeHandle);
2814 }
2815
2816 if (mEndOpCodeHandle != NULL) {
2817 HiiFreeOpCodeHandle (mEndOpCodeHandle);
2818 }
2819 }