SecurityPkg:AuthVariableLib:Implement ECR1707 for Private Auth Variable
[mirror_edk2.git] / SecurityPkg / Library / AuthVariableLib / AuthService.c
1 /** @file
2 Implement authentication services for the authenticated variables.
3
4 Caution: This module requires additional review when modified.
5 This driver will have external input - variable data. It may be input in SMM mode.
6 This external input must be validated carefully to avoid security issue like
7 buffer overflow, integer overflow.
8 Variable attribute should also be checked to avoid authentication bypass.
9 The whole SMM authentication variable design relies on the integrity of flash part and SMM.
10 which is assumed to be protected by platform. All variable code and metadata in flash/SMM Memory
11 may not be modified without authorization. If platform fails to protect these resources,
12 the authentication service provided in this driver will be broken, and the behavior is undefined.
13
14 ProcessVarWithPk(), ProcessVarWithKek() and ProcessVariable() are the function to do
15 variable authentication.
16
17 VerifyTimeBasedPayloadAndUpdate() and VerifyCounterBasedPayload() are sub function to do verification.
18 They will do basic validation for authentication data structure, then call crypto library
19 to verify the signature.
20
21 Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>
22 This program and the accompanying materials
23 are licensed and made available under the terms and conditions of the BSD License
24 which accompanies this distribution. The full text of the license may be found at
25 http://opensource.org/licenses/bsd-license.php
26
27 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
28 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
29
30 **/
31
32 #include "AuthServiceInternal.h"
33
34 //
35 // Public Exponent of RSA Key.
36 //
37 CONST UINT8 mRsaE[] = { 0x01, 0x00, 0x01 };
38
39 CONST UINT8 mSha256OidValue[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01 };
40
41 //
42 // Requirement for different signature type which have been defined in UEFI spec.
43 // These data are used to perform SignatureList format check while setting PK/KEK variable.
44 //
45 EFI_SIGNATURE_ITEM mSupportSigItem[] = {
46 //{SigType, SigHeaderSize, SigDataSize }
47 {EFI_CERT_SHA256_GUID, 0, 32 },
48 {EFI_CERT_RSA2048_GUID, 0, 256 },
49 {EFI_CERT_RSA2048_SHA256_GUID, 0, 256 },
50 {EFI_CERT_SHA1_GUID, 0, 20 },
51 {EFI_CERT_RSA2048_SHA1_GUID, 0, 256 },
52 {EFI_CERT_X509_GUID, 0, ((UINT32) ~0)},
53 {EFI_CERT_SHA224_GUID, 0, 28 },
54 {EFI_CERT_SHA384_GUID, 0, 48 },
55 {EFI_CERT_SHA512_GUID, 0, 64 },
56 {EFI_CERT_X509_SHA256_GUID, 0, 48 },
57 {EFI_CERT_X509_SHA384_GUID, 0, 64 },
58 {EFI_CERT_X509_SHA512_GUID, 0, 80 }
59 };
60
61 /**
62 Finds variable in storage blocks of volatile and non-volatile storage areas.
63
64 This code finds variable in storage blocks of volatile and non-volatile storage areas.
65 If VariableName is an empty string, then we just return the first
66 qualified variable without comparing VariableName and VendorGuid.
67
68 @param[in] VariableName Name of the variable to be found.
69 @param[in] VendorGuid Variable vendor GUID to be found.
70 @param[out] Data Pointer to data address.
71 @param[out] DataSize Pointer to data size.
72
73 @retval EFI_INVALID_PARAMETER If VariableName is not an empty string,
74 while VendorGuid is NULL.
75 @retval EFI_SUCCESS Variable successfully found.
76 @retval EFI_NOT_FOUND Variable not found
77
78 **/
79 EFI_STATUS
80 AuthServiceInternalFindVariable (
81 IN CHAR16 *VariableName,
82 IN EFI_GUID *VendorGuid,
83 OUT VOID **Data,
84 OUT UINTN *DataSize
85 )
86 {
87 EFI_STATUS Status;
88 AUTH_VARIABLE_INFO AuthVariableInfo;
89
90 ZeroMem (&AuthVariableInfo, sizeof (AuthVariableInfo));
91 Status = mAuthVarLibContextIn->FindVariable (
92 VariableName,
93 VendorGuid,
94 &AuthVariableInfo
95 );
96 *Data = AuthVariableInfo.Data;
97 *DataSize = AuthVariableInfo.DataSize;
98 return Status;
99 }
100
101 /**
102 Update the variable region with Variable information.
103
104 @param[in] VariableName Name of variable.
105 @param[in] VendorGuid Guid of variable.
106 @param[in] Data Data pointer.
107 @param[in] DataSize Size of Data.
108 @param[in] Attributes Attribute value of the variable.
109
110 @retval EFI_SUCCESS The update operation is success.
111 @retval EFI_INVALID_PARAMETER Invalid parameter.
112 @retval EFI_WRITE_PROTECTED Variable is write-protected.
113 @retval EFI_OUT_OF_RESOURCES There is not enough resource.
114
115 **/
116 EFI_STATUS
117 AuthServiceInternalUpdateVariable (
118 IN CHAR16 *VariableName,
119 IN EFI_GUID *VendorGuid,
120 IN VOID *Data,
121 IN UINTN DataSize,
122 IN UINT32 Attributes
123 )
124 {
125 AUTH_VARIABLE_INFO AuthVariableInfo;
126
127 ZeroMem (&AuthVariableInfo, sizeof (AuthVariableInfo));
128 AuthVariableInfo.VariableName = VariableName;
129 AuthVariableInfo.VendorGuid = VendorGuid;
130 AuthVariableInfo.Data = Data;
131 AuthVariableInfo.DataSize = DataSize;
132 AuthVariableInfo.Attributes = Attributes;
133
134 return mAuthVarLibContextIn->UpdateVariable (
135 &AuthVariableInfo
136 );
137 }
138
139 /**
140 Update the variable region with Variable information.
141
142 @param[in] VariableName Name of variable.
143 @param[in] VendorGuid Guid of variable.
144 @param[in] Data Data pointer.
145 @param[in] DataSize Size of Data.
146 @param[in] Attributes Attribute value of the variable.
147 @param[in] KeyIndex Index of associated public key.
148 @param[in] MonotonicCount Value of associated monotonic count.
149
150 @retval EFI_SUCCESS The update operation is success.
151 @retval EFI_INVALID_PARAMETER Invalid parameter.
152 @retval EFI_WRITE_PROTECTED Variable is write-protected.
153 @retval EFI_OUT_OF_RESOURCES There is not enough resource.
154
155 **/
156 EFI_STATUS
157 AuthServiceInternalUpdateVariableWithMonotonicCount (
158 IN CHAR16 *VariableName,
159 IN EFI_GUID *VendorGuid,
160 IN VOID *Data,
161 IN UINTN DataSize,
162 IN UINT32 Attributes,
163 IN UINT32 KeyIndex,
164 IN UINT64 MonotonicCount
165 )
166 {
167 AUTH_VARIABLE_INFO AuthVariableInfo;
168
169 ZeroMem (&AuthVariableInfo, sizeof (AuthVariableInfo));
170 AuthVariableInfo.VariableName = VariableName;
171 AuthVariableInfo.VendorGuid = VendorGuid;
172 AuthVariableInfo.Data = Data;
173 AuthVariableInfo.DataSize = DataSize;
174 AuthVariableInfo.Attributes = Attributes;
175 AuthVariableInfo.PubKeyIndex = KeyIndex;
176 AuthVariableInfo.MonotonicCount = MonotonicCount;
177
178 return mAuthVarLibContextIn->UpdateVariable (
179 &AuthVariableInfo
180 );
181 }
182
183 /**
184 Update the variable region with Variable information.
185
186 @param[in] VariableName Name of variable.
187 @param[in] VendorGuid Guid of variable.
188 @param[in] Data Data pointer.
189 @param[in] DataSize Size of Data.
190 @param[in] Attributes Attribute value of the variable.
191 @param[in] TimeStamp Value of associated TimeStamp.
192
193 @retval EFI_SUCCESS The update operation is success.
194 @retval EFI_INVALID_PARAMETER Invalid parameter.
195 @retval EFI_WRITE_PROTECTED Variable is write-protected.
196 @retval EFI_OUT_OF_RESOURCES There is not enough resource.
197
198 **/
199 EFI_STATUS
200 AuthServiceInternalUpdateVariableWithTimeStamp (
201 IN CHAR16 *VariableName,
202 IN EFI_GUID *VendorGuid,
203 IN VOID *Data,
204 IN UINTN DataSize,
205 IN UINT32 Attributes,
206 IN EFI_TIME *TimeStamp
207 )
208 {
209 EFI_STATUS FindStatus;
210 VOID *OrgData;
211 UINTN OrgDataSize;
212 AUTH_VARIABLE_INFO AuthVariableInfo;
213
214 FindStatus = AuthServiceInternalFindVariable (
215 VariableName,
216 VendorGuid,
217 &OrgData,
218 &OrgDataSize
219 );
220
221 //
222 // EFI_VARIABLE_APPEND_WRITE attribute only effects for existing variable
223 //
224 if (!EFI_ERROR (FindStatus) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0)) {
225 if ((CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) &&
226 ((StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) || (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0) ||
227 (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE2) == 0))) ||
228 (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0))) {
229 //
230 // For variables with formatted as EFI_SIGNATURE_LIST, the driver shall not perform an append of
231 // EFI_SIGNATURE_DATA values that are already part of the existing variable value.
232 //
233 FilterSignatureList (
234 OrgData,
235 OrgDataSize,
236 Data,
237 &DataSize
238 );
239 }
240 }
241
242 ZeroMem (&AuthVariableInfo, sizeof (AuthVariableInfo));
243 AuthVariableInfo.VariableName = VariableName;
244 AuthVariableInfo.VendorGuid = VendorGuid;
245 AuthVariableInfo.Data = Data;
246 AuthVariableInfo.DataSize = DataSize;
247 AuthVariableInfo.Attributes = Attributes;
248 AuthVariableInfo.TimeStamp = TimeStamp;
249 return mAuthVarLibContextIn->UpdateVariable (
250 &AuthVariableInfo
251 );
252 }
253
254 /**
255 Determine whether this operation needs a physical present user.
256
257 @param[in] VariableName Name of the Variable.
258 @param[in] VendorGuid GUID of the Variable.
259
260 @retval TRUE This variable is protected, only a physical present user could set this variable.
261 @retval FALSE This variable is not protected.
262
263 **/
264 BOOLEAN
265 NeedPhysicallyPresent(
266 IN CHAR16 *VariableName,
267 IN EFI_GUID *VendorGuid
268 )
269 {
270 if ((CompareGuid (VendorGuid, &gEfiSecureBootEnableDisableGuid) && (StrCmp (VariableName, EFI_SECURE_BOOT_ENABLE_NAME) == 0))
271 || (CompareGuid (VendorGuid, &gEfiCustomModeEnableGuid) && (StrCmp (VariableName, EFI_CUSTOM_MODE_NAME) == 0))) {
272 return TRUE;
273 }
274
275 return FALSE;
276 }
277
278 /**
279 Determine whether the platform is operating in Custom Secure Boot mode.
280
281 @retval TRUE The platform is operating in Custom mode.
282 @retval FALSE The platform is operating in Standard mode.
283
284 **/
285 BOOLEAN
286 InCustomMode (
287 VOID
288 )
289 {
290 EFI_STATUS Status;
291 VOID *Data;
292 UINTN DataSize;
293
294 Status = AuthServiceInternalFindVariable (EFI_CUSTOM_MODE_NAME, &gEfiCustomModeEnableGuid, &Data, &DataSize);
295 if (!EFI_ERROR (Status) && (*(UINT8 *) Data == CUSTOM_SECURE_BOOT_MODE)) {
296 return TRUE;
297 }
298
299 return FALSE;
300 }
301
302 /**
303 Get available public key index.
304
305 @param[in] PubKey Pointer to Public Key data.
306
307 @return Public key index, 0 if no any public key index available.
308
309 **/
310 UINT32
311 GetAvailableKeyIndex (
312 IN UINT8 *PubKey
313 )
314 {
315 EFI_STATUS Status;
316 UINT8 *Data;
317 UINTN DataSize;
318 UINT8 *Ptr;
319 UINT32 Index;
320 BOOLEAN IsFound;
321 EFI_GUID VendorGuid;
322 CHAR16 Name[1];
323 AUTH_VARIABLE_INFO AuthVariableInfo;
324 UINT32 KeyIndex;
325
326 Status = AuthServiceInternalFindVariable (
327 AUTHVAR_KEYDB_NAME,
328 &gEfiAuthenticatedVariableGuid,
329 (VOID **) &Data,
330 &DataSize
331 );
332 if (EFI_ERROR (Status)) {
333 DEBUG ((EFI_D_ERROR, "Get public key database variable failure, Status = %r\n", Status));
334 return 0;
335 }
336
337 if (mPubKeyNumber == mMaxKeyNumber) {
338 Name[0] = 0;
339 AuthVariableInfo.VariableName = Name;
340 ZeroMem (&VendorGuid, sizeof (VendorGuid));
341 AuthVariableInfo.VendorGuid = &VendorGuid;
342 mPubKeyNumber = 0;
343 //
344 // Collect valid key data.
345 //
346 do {
347 Status = mAuthVarLibContextIn->FindNextVariable (AuthVariableInfo.VariableName, AuthVariableInfo.VendorGuid, &AuthVariableInfo);
348 if (!EFI_ERROR (Status)) {
349 if (AuthVariableInfo.PubKeyIndex != 0) {
350 for (Ptr = Data; Ptr < (Data + DataSize); Ptr += sizeof (AUTHVAR_KEY_DB_DATA)) {
351 if (ReadUnaligned32 (&(((AUTHVAR_KEY_DB_DATA *) Ptr)->KeyIndex)) == AuthVariableInfo.PubKeyIndex) {
352 //
353 // Check if the key data has been collected.
354 //
355 for (Index = 0; Index < mPubKeyNumber; Index++) {
356 if (ReadUnaligned32 (&(((AUTHVAR_KEY_DB_DATA *) mPubKeyStore + Index)->KeyIndex)) == AuthVariableInfo.PubKeyIndex) {
357 break;
358 }
359 }
360 if (Index == mPubKeyNumber) {
361 //
362 // New key data.
363 //
364 CopyMem ((AUTHVAR_KEY_DB_DATA *) mPubKeyStore + mPubKeyNumber, Ptr, sizeof (AUTHVAR_KEY_DB_DATA));
365 mPubKeyNumber++;
366 }
367 break;
368 }
369 }
370 }
371 }
372 } while (Status != EFI_NOT_FOUND);
373
374 //
375 // No available space to add new public key.
376 //
377 if (mPubKeyNumber == mMaxKeyNumber) {
378 return 0;
379 }
380 }
381
382 //
383 // Find available public key index.
384 //
385 for (KeyIndex = 1; KeyIndex <= mMaxKeyNumber; KeyIndex++) {
386 IsFound = FALSE;
387 for (Ptr = mPubKeyStore; Ptr < (mPubKeyStore + mPubKeyNumber * sizeof (AUTHVAR_KEY_DB_DATA)); Ptr += sizeof (AUTHVAR_KEY_DB_DATA)) {
388 if (ReadUnaligned32 (&(((AUTHVAR_KEY_DB_DATA *) Ptr)->KeyIndex)) == KeyIndex) {
389 IsFound = TRUE;
390 break;
391 }
392 }
393 if (!IsFound) {
394 break;
395 }
396 }
397
398 return KeyIndex;
399 }
400
401 /**
402 Add public key in store and return its index.
403
404 @param[in] PubKey Input pointer to Public Key data.
405 @param[in] VariableDataEntry The variable data entry.
406
407 @return Index of new added public key.
408
409 **/
410 UINT32
411 AddPubKeyInStore (
412 IN UINT8 *PubKey,
413 IN VARIABLE_ENTRY_CONSISTENCY *VariableDataEntry
414 )
415 {
416 EFI_STATUS Status;
417 UINT32 Index;
418 VARIABLE_ENTRY_CONSISTENCY PublicKeyEntry;
419 UINT32 Attributes;
420 UINT32 KeyIndex;
421
422 if (PubKey == NULL) {
423 return 0;
424 }
425
426 //
427 // Check whether the public key entry does exist.
428 //
429 for (Index = 0; Index < mPubKeyNumber; Index++) {
430 if (CompareMem (((AUTHVAR_KEY_DB_DATA *) mPubKeyStore + Index)->KeyData, PubKey, EFI_CERT_TYPE_RSA2048_SIZE) == 0) {
431 return ReadUnaligned32 (&(((AUTHVAR_KEY_DB_DATA *) mPubKeyStore + Index)->KeyIndex));
432 }
433 }
434
435 KeyIndex = GetAvailableKeyIndex (PubKey);
436 if (KeyIndex == 0) {
437 return 0;
438 }
439
440 //
441 // Check the variable space for both public key and variable data.
442 //
443 PublicKeyEntry.VariableSize = (mPubKeyNumber + 1) * sizeof (AUTHVAR_KEY_DB_DATA);
444 PublicKeyEntry.Guid = &gEfiAuthenticatedVariableGuid;
445 PublicKeyEntry.Name = AUTHVAR_KEYDB_NAME;
446 Attributes = VARIABLE_ATTRIBUTE_NV_BS_RT | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS;
447
448 if (!mAuthVarLibContextIn->CheckRemainingSpaceForConsistency (Attributes, &PublicKeyEntry, VariableDataEntry, NULL)) {
449 //
450 // No enough variable space.
451 //
452 return 0;
453 }
454
455 WriteUnaligned32 (&(((AUTHVAR_KEY_DB_DATA *) mPubKeyStore + mPubKeyNumber)->KeyIndex), KeyIndex);
456 CopyMem (((AUTHVAR_KEY_DB_DATA *) mPubKeyStore + mPubKeyNumber)->KeyData, PubKey, EFI_CERT_TYPE_RSA2048_SIZE);
457 mPubKeyNumber++;
458
459 //
460 // Update public key database variable.
461 //
462 Status = AuthServiceInternalUpdateVariable (
463 AUTHVAR_KEYDB_NAME,
464 &gEfiAuthenticatedVariableGuid,
465 mPubKeyStore,
466 mPubKeyNumber * sizeof (AUTHVAR_KEY_DB_DATA),
467 Attributes
468 );
469 if (EFI_ERROR (Status)) {
470 DEBUG ((EFI_D_ERROR, "Update public key database variable failure, Status = %r\n", Status));
471 return 0;
472 }
473
474 return KeyIndex;
475 }
476
477 /**
478 Verify data payload with AuthInfo in EFI_CERT_TYPE_RSA2048_SHA256_GUID type.
479 Follow the steps in UEFI2.2.
480
481 Caution: This function may receive untrusted input.
482 This function may be invoked in SMM mode, and datasize and data are external input.
483 This function will do basic validation, before parse the data.
484 This function will parse the authentication carefully to avoid security issues, like
485 buffer overflow, integer overflow.
486
487 @param[in] Data Pointer to data with AuthInfo.
488 @param[in] DataSize Size of Data.
489 @param[in] PubKey Public key used for verification.
490
491 @retval EFI_INVALID_PARAMETER Invalid parameter.
492 @retval EFI_SECURITY_VIOLATION If authentication failed.
493 @retval EFI_SUCCESS Authentication successful.
494
495 **/
496 EFI_STATUS
497 VerifyCounterBasedPayload (
498 IN UINT8 *Data,
499 IN UINTN DataSize,
500 IN UINT8 *PubKey
501 )
502 {
503 BOOLEAN Status;
504 EFI_VARIABLE_AUTHENTICATION *CertData;
505 EFI_CERT_BLOCK_RSA_2048_SHA256 *CertBlock;
506 UINT8 Digest[SHA256_DIGEST_SIZE];
507 VOID *Rsa;
508 UINTN PayloadSize;
509
510 PayloadSize = DataSize - AUTHINFO_SIZE;
511 Rsa = NULL;
512 CertData = NULL;
513 CertBlock = NULL;
514
515 if (Data == NULL || PubKey == NULL) {
516 return EFI_INVALID_PARAMETER;
517 }
518
519 CertData = (EFI_VARIABLE_AUTHENTICATION *) Data;
520 CertBlock = (EFI_CERT_BLOCK_RSA_2048_SHA256 *) (CertData->AuthInfo.CertData);
521
522 //
523 // wCertificateType should be WIN_CERT_TYPE_EFI_GUID.
524 // Cert type should be EFI_CERT_TYPE_RSA2048_SHA256_GUID.
525 //
526 if ((CertData->AuthInfo.Hdr.wCertificateType != WIN_CERT_TYPE_EFI_GUID) ||
527 !CompareGuid (&CertData->AuthInfo.CertType, &gEfiCertTypeRsa2048Sha256Guid)) {
528 //
529 // Invalid AuthInfo type, return EFI_SECURITY_VIOLATION.
530 //
531 return EFI_SECURITY_VIOLATION;
532 }
533 //
534 // Hash data payload with SHA256.
535 //
536 ZeroMem (Digest, SHA256_DIGEST_SIZE);
537 Status = Sha256Init (mHashCtx);
538 if (!Status) {
539 goto Done;
540 }
541 Status = Sha256Update (mHashCtx, Data + AUTHINFO_SIZE, PayloadSize);
542 if (!Status) {
543 goto Done;
544 }
545 //
546 // Hash Size.
547 //
548 Status = Sha256Update (mHashCtx, &PayloadSize, sizeof (UINTN));
549 if (!Status) {
550 goto Done;
551 }
552 //
553 // Hash Monotonic Count.
554 //
555 Status = Sha256Update (mHashCtx, &CertData->MonotonicCount, sizeof (UINT64));
556 if (!Status) {
557 goto Done;
558 }
559 Status = Sha256Final (mHashCtx, Digest);
560 if (!Status) {
561 goto Done;
562 }
563 //
564 // Generate & Initialize RSA Context.
565 //
566 Rsa = RsaNew ();
567 ASSERT (Rsa != NULL);
568 //
569 // Set RSA Key Components.
570 // NOTE: Only N and E are needed to be set as RSA public key for signature verification.
571 //
572 Status = RsaSetKey (Rsa, RsaKeyN, PubKey, EFI_CERT_TYPE_RSA2048_SIZE);
573 if (!Status) {
574 goto Done;
575 }
576 Status = RsaSetKey (Rsa, RsaKeyE, mRsaE, sizeof (mRsaE));
577 if (!Status) {
578 goto Done;
579 }
580 //
581 // Verify the signature.
582 //
583 Status = RsaPkcs1Verify (
584 Rsa,
585 Digest,
586 SHA256_DIGEST_SIZE,
587 CertBlock->Signature,
588 EFI_CERT_TYPE_RSA2048_SHA256_SIZE
589 );
590
591 Done:
592 if (Rsa != NULL) {
593 RsaFree (Rsa);
594 }
595 if (Status) {
596 return EFI_SUCCESS;
597 } else {
598 return EFI_SECURITY_VIOLATION;
599 }
600 }
601
602 /**
603 Update platform mode.
604
605 @param[in] Mode SETUP_MODE or USER_MODE.
606
607 @return EFI_INVALID_PARAMETER Invalid parameter.
608 @return EFI_SUCCESS Update platform mode successfully.
609
610 **/
611 EFI_STATUS
612 UpdatePlatformMode (
613 IN UINT32 Mode
614 )
615 {
616 EFI_STATUS Status;
617 VOID *Data;
618 UINTN DataSize;
619 UINT8 SecureBootMode;
620 UINT8 SecureBootEnable;
621 UINTN VariableDataSize;
622
623 Status = AuthServiceInternalFindVariable (
624 EFI_SETUP_MODE_NAME,
625 &gEfiGlobalVariableGuid,
626 &Data,
627 &DataSize
628 );
629 if (EFI_ERROR (Status)) {
630 return Status;
631 }
632
633 //
634 // Update the value of SetupMode variable by a simple mem copy, this could avoid possible
635 // variable storage reclaim at runtime.
636 //
637 mPlatformMode = (UINT8) Mode;
638 CopyMem (Data, &mPlatformMode, sizeof(UINT8));
639
640 if (mAuthVarLibContextIn->AtRuntime ()) {
641 //
642 // SecureBoot Variable indicates whether the platform firmware is operating
643 // in Secure boot mode (1) or not (0), so we should not change SecureBoot
644 // Variable in runtime.
645 //
646 return Status;
647 }
648
649 //
650 // Check "SecureBoot" variable's existence.
651 // If it doesn't exist, firmware has no capability to perform driver signing verification,
652 // then set "SecureBoot" to 0.
653 //
654 Status = AuthServiceInternalFindVariable (
655 EFI_SECURE_BOOT_MODE_NAME,
656 &gEfiGlobalVariableGuid,
657 &Data,
658 &DataSize
659 );
660 //
661 // If "SecureBoot" variable exists, then check "SetupMode" variable update.
662 // If "SetupMode" variable is USER_MODE, "SecureBoot" variable is set to 1.
663 // If "SetupMode" variable is SETUP_MODE, "SecureBoot" variable is set to 0.
664 //
665 if (EFI_ERROR (Status)) {
666 SecureBootMode = SECURE_BOOT_MODE_DISABLE;
667 } else {
668 if (mPlatformMode == USER_MODE) {
669 SecureBootMode = SECURE_BOOT_MODE_ENABLE;
670 } else if (mPlatformMode == SETUP_MODE) {
671 SecureBootMode = SECURE_BOOT_MODE_DISABLE;
672 } else {
673 return EFI_NOT_FOUND;
674 }
675 }
676
677 Status = AuthServiceInternalUpdateVariable (
678 EFI_SECURE_BOOT_MODE_NAME,
679 &gEfiGlobalVariableGuid,
680 &SecureBootMode,
681 sizeof(UINT8),
682 EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS
683 );
684 if (EFI_ERROR (Status)) {
685 return Status;
686 }
687
688 //
689 // Check "SecureBootEnable" variable's existence. It can enable/disable secure boot feature.
690 //
691 Status = AuthServiceInternalFindVariable (
692 EFI_SECURE_BOOT_ENABLE_NAME,
693 &gEfiSecureBootEnableDisableGuid,
694 &Data,
695 &DataSize
696 );
697
698 if (SecureBootMode == SECURE_BOOT_MODE_ENABLE) {
699 //
700 // Create the "SecureBootEnable" variable as secure boot is enabled.
701 //
702 SecureBootEnable = SECURE_BOOT_ENABLE;
703 VariableDataSize = sizeof (SecureBootEnable);
704 } else {
705 //
706 // Delete the "SecureBootEnable" variable if this variable exist as "SecureBoot"
707 // variable is not in secure boot state.
708 //
709 if (EFI_ERROR (Status)) {
710 return EFI_SUCCESS;
711 }
712 SecureBootEnable = SECURE_BOOT_DISABLE;
713 VariableDataSize = 0;
714 }
715
716 Status = AuthServiceInternalUpdateVariable (
717 EFI_SECURE_BOOT_ENABLE_NAME,
718 &gEfiSecureBootEnableDisableGuid,
719 &SecureBootEnable,
720 VariableDataSize,
721 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS
722 );
723 return Status;
724 }
725
726 /**
727 Check input data form to make sure it is a valid EFI_SIGNATURE_LIST for PK/KEK/db/dbx/dbt variable.
728
729 @param[in] VariableName Name of Variable to be check.
730 @param[in] VendorGuid Variable vendor GUID.
731 @param[in] Data Point to the variable data to be checked.
732 @param[in] DataSize Size of Data.
733
734 @return EFI_INVALID_PARAMETER Invalid signature list format.
735 @return EFI_SUCCESS Passed signature list format check successfully.
736
737 **/
738 EFI_STATUS
739 CheckSignatureListFormat(
740 IN CHAR16 *VariableName,
741 IN EFI_GUID *VendorGuid,
742 IN VOID *Data,
743 IN UINTN DataSize
744 )
745 {
746 EFI_SIGNATURE_LIST *SigList;
747 UINTN SigDataSize;
748 UINT32 Index;
749 UINT32 SigCount;
750 BOOLEAN IsPk;
751 VOID *RsaContext;
752 EFI_SIGNATURE_DATA *CertData;
753 UINTN CertLen;
754
755 if (DataSize == 0) {
756 return EFI_SUCCESS;
757 }
758
759 ASSERT (VariableName != NULL && VendorGuid != NULL && Data != NULL);
760
761 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_PLATFORM_KEY_NAME) == 0)){
762 IsPk = TRUE;
763 } else if ((CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0)) ||
764 (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) &&
765 ((StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) || (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0) ||
766 (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE2) == 0)))) {
767 IsPk = FALSE;
768 } else {
769 return EFI_SUCCESS;
770 }
771
772 SigCount = 0;
773 SigList = (EFI_SIGNATURE_LIST *) Data;
774 SigDataSize = DataSize;
775 RsaContext = NULL;
776
777 //
778 // Walk throuth the input signature list and check the data format.
779 // If any signature is incorrectly formed, the whole check will fail.
780 //
781 while ((SigDataSize > 0) && (SigDataSize >= SigList->SignatureListSize)) {
782 for (Index = 0; Index < (sizeof (mSupportSigItem) / sizeof (EFI_SIGNATURE_ITEM)); Index++ ) {
783 if (CompareGuid (&SigList->SignatureType, &mSupportSigItem[Index].SigType)) {
784 //
785 // The value of SignatureSize should always be 16 (size of SignatureOwner
786 // component) add the data length according to signature type.
787 //
788 if (mSupportSigItem[Index].SigDataSize != ((UINT32) ~0) &&
789 (SigList->SignatureSize - sizeof (EFI_GUID)) != mSupportSigItem[Index].SigDataSize) {
790 return EFI_INVALID_PARAMETER;
791 }
792 if (mSupportSigItem[Index].SigHeaderSize != ((UINT32) ~0) &&
793 SigList->SignatureHeaderSize != mSupportSigItem[Index].SigHeaderSize) {
794 return EFI_INVALID_PARAMETER;
795 }
796 break;
797 }
798 }
799
800 if (Index == (sizeof (mSupportSigItem) / sizeof (EFI_SIGNATURE_ITEM))) {
801 //
802 // Undefined signature type.
803 //
804 return EFI_INVALID_PARAMETER;
805 }
806
807 if (CompareGuid (&SigList->SignatureType, &gEfiCertX509Guid)) {
808 //
809 // Try to retrieve the RSA public key from the X.509 certificate.
810 // If this operation fails, it's not a valid certificate.
811 //
812 RsaContext = RsaNew ();
813 if (RsaContext == NULL) {
814 return EFI_INVALID_PARAMETER;
815 }
816 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) SigList + sizeof (EFI_SIGNATURE_LIST) + SigList->SignatureHeaderSize);
817 CertLen = SigList->SignatureSize - sizeof (EFI_GUID);
818 if (!RsaGetPublicKeyFromX509 (CertData->SignatureData, CertLen, &RsaContext)) {
819 RsaFree (RsaContext);
820 return EFI_INVALID_PARAMETER;
821 }
822 RsaFree (RsaContext);
823 }
824
825 if ((SigList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - SigList->SignatureHeaderSize) % SigList->SignatureSize != 0) {
826 return EFI_INVALID_PARAMETER;
827 }
828 SigCount += (SigList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - SigList->SignatureHeaderSize) / SigList->SignatureSize;
829
830 SigDataSize -= SigList->SignatureListSize;
831 SigList = (EFI_SIGNATURE_LIST *) ((UINT8 *) SigList + SigList->SignatureListSize);
832 }
833
834 if (((UINTN) SigList - (UINTN) Data) != DataSize) {
835 return EFI_INVALID_PARAMETER;
836 }
837
838 if (IsPk && SigCount > 1) {
839 return EFI_INVALID_PARAMETER;
840 }
841
842 return EFI_SUCCESS;
843 }
844
845 /**
846 Update "VendorKeys" variable to record the out of band secure boot key modification.
847
848 @return EFI_SUCCESS Variable is updated successfully.
849 @return Others Failed to update variable.
850
851 **/
852 EFI_STATUS
853 VendorKeyIsModified (
854 VOID
855 )
856 {
857 EFI_STATUS Status;
858
859 if (mVendorKeyState == VENDOR_KEYS_MODIFIED) {
860 return EFI_SUCCESS;
861 }
862 mVendorKeyState = VENDOR_KEYS_MODIFIED;
863
864 Status = AuthServiceInternalUpdateVariable (
865 EFI_VENDOR_KEYS_NV_VARIABLE_NAME,
866 &gEfiVendorKeysNvGuid,
867 &mVendorKeyState,
868 sizeof (UINT8),
869 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
870 );
871 if (EFI_ERROR (Status)) {
872 return Status;
873 }
874
875 return AuthServiceInternalUpdateVariable (
876 EFI_VENDOR_KEYS_VARIABLE_NAME,
877 &gEfiGlobalVariableGuid,
878 &mVendorKeyState,
879 sizeof (UINT8),
880 EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS
881 );
882 }
883
884 /**
885 Process variable with platform key for verification.
886
887 Caution: This function may receive untrusted input.
888 This function may be invoked in SMM mode, and datasize and data are external input.
889 This function will do basic validation, before parse the data.
890 This function will parse the authentication carefully to avoid security issues, like
891 buffer overflow, integer overflow.
892 This function will check attribute carefully to avoid authentication bypass.
893
894 @param[in] VariableName Name of Variable to be found.
895 @param[in] VendorGuid Variable vendor GUID.
896 @param[in] Data Data pointer.
897 @param[in] DataSize Size of Data found. If size is less than the
898 data, this value contains the required size.
899 @param[in] Attributes Attribute value of the variable
900 @param[in] IsPk Indicate whether it is to process pk.
901
902 @return EFI_INVALID_PARAMETER Invalid parameter.
903 @return EFI_SECURITY_VIOLATION The variable does NOT pass the validation.
904 check carried out by the firmware.
905 @return EFI_SUCCESS Variable passed validation successfully.
906
907 **/
908 EFI_STATUS
909 ProcessVarWithPk (
910 IN CHAR16 *VariableName,
911 IN EFI_GUID *VendorGuid,
912 IN VOID *Data,
913 IN UINTN DataSize,
914 IN UINT32 Attributes OPTIONAL,
915 IN BOOLEAN IsPk
916 )
917 {
918 EFI_STATUS Status;
919 BOOLEAN Del;
920 UINT8 *Payload;
921 UINTN PayloadSize;
922
923 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0 ||
924 (Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == 0) {
925 //
926 // PK, KEK and db/dbx/dbt should set EFI_VARIABLE_NON_VOLATILE attribute and should be a time-based
927 // authenticated variable.
928 //
929 return EFI_INVALID_PARAMETER;
930 }
931
932 //
933 // Init state of Del. State may change due to secure check
934 //
935 Del = FALSE;
936 if ((InCustomMode() && UserPhysicalPresent()) || (mPlatformMode == SETUP_MODE && !IsPk)) {
937 Payload = (UINT8 *) Data + AUTHINFO2_SIZE (Data);
938 PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
939 if (PayloadSize == 0) {
940 Del = TRUE;
941 }
942
943 Status = CheckSignatureListFormat(VariableName, VendorGuid, Payload, PayloadSize);
944 if (EFI_ERROR (Status)) {
945 return Status;
946 }
947
948 Status = AuthServiceInternalUpdateVariableWithTimeStamp (
949 VariableName,
950 VendorGuid,
951 Payload,
952 PayloadSize,
953 Attributes,
954 &((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->TimeStamp
955 );
956 if (EFI_ERROR(Status)) {
957 return Status;
958 }
959
960 if ((mPlatformMode != SETUP_MODE) || IsPk) {
961 Status = VendorKeyIsModified ();
962 }
963 } else if (mPlatformMode == USER_MODE) {
964 //
965 // Verify against X509 Cert in PK database.
966 //
967 Status = VerifyTimeBasedPayloadAndUpdate (
968 VariableName,
969 VendorGuid,
970 Data,
971 DataSize,
972 Attributes,
973 AuthVarTypePk,
974 &Del
975 );
976 } else {
977 //
978 // Verify against the certificate in data payload.
979 //
980 Status = VerifyTimeBasedPayloadAndUpdate (
981 VariableName,
982 VendorGuid,
983 Data,
984 DataSize,
985 Attributes,
986 AuthVarTypePayload,
987 &Del
988 );
989 }
990
991 if (!EFI_ERROR(Status) && IsPk) {
992 if (mPlatformMode == SETUP_MODE && !Del) {
993 //
994 // If enroll PK in setup mode, need change to user mode.
995 //
996 Status = UpdatePlatformMode (USER_MODE);
997 } else if (mPlatformMode == USER_MODE && Del){
998 //
999 // If delete PK in user mode, need change to setup mode.
1000 //
1001 Status = UpdatePlatformMode (SETUP_MODE);
1002 }
1003 }
1004
1005 return Status;
1006 }
1007
1008 /**
1009 Process variable with key exchange key for verification.
1010
1011 Caution: This function may receive untrusted input.
1012 This function may be invoked in SMM mode, and datasize and data are external input.
1013 This function will do basic validation, before parse the data.
1014 This function will parse the authentication carefully to avoid security issues, like
1015 buffer overflow, integer overflow.
1016 This function will check attribute carefully to avoid authentication bypass.
1017
1018 @param[in] VariableName Name of Variable to be found.
1019 @param[in] VendorGuid Variable vendor GUID.
1020 @param[in] Data Data pointer.
1021 @param[in] DataSize Size of Data found. If size is less than the
1022 data, this value contains the required size.
1023 @param[in] Attributes Attribute value of the variable.
1024
1025 @return EFI_INVALID_PARAMETER Invalid parameter.
1026 @return EFI_SECURITY_VIOLATION The variable does NOT pass the validation
1027 check carried out by the firmware.
1028 @return EFI_SUCCESS Variable pass validation successfully.
1029
1030 **/
1031 EFI_STATUS
1032 ProcessVarWithKek (
1033 IN CHAR16 *VariableName,
1034 IN EFI_GUID *VendorGuid,
1035 IN VOID *Data,
1036 IN UINTN DataSize,
1037 IN UINT32 Attributes OPTIONAL
1038 )
1039 {
1040 EFI_STATUS Status;
1041 UINT8 *Payload;
1042 UINTN PayloadSize;
1043
1044 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0 ||
1045 (Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == 0) {
1046 //
1047 // DB, DBX and DBT should set EFI_VARIABLE_NON_VOLATILE attribute and should be a time-based
1048 // authenticated variable.
1049 //
1050 return EFI_INVALID_PARAMETER;
1051 }
1052
1053 Status = EFI_SUCCESS;
1054 if (mPlatformMode == USER_MODE && !(InCustomMode() && UserPhysicalPresent())) {
1055 //
1056 // Time-based, verify against X509 Cert KEK.
1057 //
1058 return VerifyTimeBasedPayloadAndUpdate (
1059 VariableName,
1060 VendorGuid,
1061 Data,
1062 DataSize,
1063 Attributes,
1064 AuthVarTypeKek,
1065 NULL
1066 );
1067 } else {
1068 //
1069 // If in setup mode or custom secure boot mode, no authentication needed.
1070 //
1071 Payload = (UINT8 *) Data + AUTHINFO2_SIZE (Data);
1072 PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
1073
1074 Status = CheckSignatureListFormat(VariableName, VendorGuid, Payload, PayloadSize);
1075 if (EFI_ERROR (Status)) {
1076 return Status;
1077 }
1078
1079 Status = AuthServiceInternalUpdateVariableWithTimeStamp (
1080 VariableName,
1081 VendorGuid,
1082 Payload,
1083 PayloadSize,
1084 Attributes,
1085 &((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->TimeStamp
1086 );
1087 if (EFI_ERROR (Status)) {
1088 return Status;
1089 }
1090
1091 if (mPlatformMode != SETUP_MODE) {
1092 Status = VendorKeyIsModified ();
1093 }
1094 }
1095
1096 return Status;
1097 }
1098
1099 /**
1100 Check if it is to delete auth variable.
1101
1102 @param[in] OrgAttributes Original attribute value of the variable.
1103 @param[in] Data Data pointer.
1104 @param[in] DataSize Size of Data.
1105 @param[in] Attributes Attribute value of the variable.
1106
1107 @retval TRUE It is to delete auth variable.
1108 @retval FALSE It is not to delete auth variable.
1109
1110 **/
1111 BOOLEAN
1112 IsDeleteAuthVariable (
1113 IN UINT32 OrgAttributes,
1114 IN VOID *Data,
1115 IN UINTN DataSize,
1116 IN UINT32 Attributes
1117 )
1118 {
1119 BOOLEAN Del;
1120 UINTN PayloadSize;
1121
1122 Del = FALSE;
1123
1124 //
1125 // To delete a variable created with the EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
1126 // or the EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute,
1127 // SetVariable must be used with attributes matching the existing variable
1128 // and the DataSize set to the size of the AuthInfo descriptor.
1129 //
1130 if ((Attributes == OrgAttributes) &&
1131 ((Attributes & (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) != 0)) {
1132 if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) {
1133 PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
1134 if (PayloadSize == 0) {
1135 Del = TRUE;
1136 }
1137 } else {
1138 PayloadSize = DataSize - AUTHINFO_SIZE;
1139 if (PayloadSize == 0) {
1140 Del = TRUE;
1141 }
1142 }
1143 }
1144
1145 return Del;
1146 }
1147
1148 /**
1149 Process variable with EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS/EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS set
1150
1151 Caution: This function may receive untrusted input.
1152 This function may be invoked in SMM mode, and datasize and data are external input.
1153 This function will do basic validation, before parse the data.
1154 This function will parse the authentication carefully to avoid security issues, like
1155 buffer overflow, integer overflow.
1156 This function will check attribute carefully to avoid authentication bypass.
1157
1158 @param[in] VariableName Name of the variable.
1159 @param[in] VendorGuid Variable vendor GUID.
1160 @param[in] Data Data pointer.
1161 @param[in] DataSize Size of Data.
1162 @param[in] Attributes Attribute value of the variable.
1163
1164 @return EFI_INVALID_PARAMETER Invalid parameter.
1165 @return EFI_WRITE_PROTECTED Variable is write-protected and needs authentication with
1166 EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS set.
1167 @return EFI_OUT_OF_RESOURCES The Database to save the public key is full.
1168 @return EFI_SECURITY_VIOLATION The variable is with EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
1169 set, but the AuthInfo does NOT pass the validation
1170 check carried out by the firmware.
1171 @return EFI_SUCCESS Variable is not write-protected or pass validation successfully.
1172
1173 **/
1174 EFI_STATUS
1175 ProcessVariable (
1176 IN CHAR16 *VariableName,
1177 IN EFI_GUID *VendorGuid,
1178 IN VOID *Data,
1179 IN UINTN DataSize,
1180 IN UINT32 Attributes
1181 )
1182 {
1183 EFI_STATUS Status;
1184 BOOLEAN IsDeletion;
1185 BOOLEAN IsFirstTime;
1186 UINT8 *PubKey;
1187 EFI_VARIABLE_AUTHENTICATION *CertData;
1188 EFI_CERT_BLOCK_RSA_2048_SHA256 *CertBlock;
1189 UINT32 KeyIndex;
1190 UINT64 MonotonicCount;
1191 VARIABLE_ENTRY_CONSISTENCY VariableDataEntry;
1192 UINT32 Index;
1193 AUTH_VARIABLE_INFO OrgVariableInfo;
1194
1195 KeyIndex = 0;
1196 CertData = NULL;
1197 CertBlock = NULL;
1198 PubKey = NULL;
1199 IsDeletion = FALSE;
1200 Status = EFI_SUCCESS;
1201
1202 ZeroMem (&OrgVariableInfo, sizeof (OrgVariableInfo));
1203 Status = mAuthVarLibContextIn->FindVariable (
1204 VariableName,
1205 VendorGuid,
1206 &OrgVariableInfo
1207 );
1208
1209 if ((!EFI_ERROR (Status)) && IsDeleteAuthVariable (OrgVariableInfo.Attributes, Data, DataSize, Attributes) && UserPhysicalPresent()) {
1210 //
1211 // Allow the delete operation of common authenticated variable at user physical presence.
1212 //
1213 Status = AuthServiceInternalUpdateVariable (
1214 VariableName,
1215 VendorGuid,
1216 NULL,
1217 0,
1218 0
1219 );
1220 if (!EFI_ERROR (Status) && ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0)) {
1221 Status = DeleteCertsFromDb (VariableName, VendorGuid, Attributes);
1222 }
1223
1224 return Status;
1225 }
1226
1227 if (NeedPhysicallyPresent (VariableName, VendorGuid) && !UserPhysicalPresent()) {
1228 //
1229 // This variable is protected, only physical present user could modify its value.
1230 //
1231 return EFI_SECURITY_VIOLATION;
1232 }
1233
1234 //
1235 // A time-based authenticated variable and a count-based authenticated variable
1236 // can't be updated by each other.
1237 //
1238 if (OrgVariableInfo.Data != NULL) {
1239 if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) &&
1240 ((OrgVariableInfo.Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0)) {
1241 return EFI_SECURITY_VIOLATION;
1242 }
1243
1244 if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) &&
1245 ((OrgVariableInfo.Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0)) {
1246 return EFI_SECURITY_VIOLATION;
1247 }
1248 }
1249
1250 //
1251 // Process Time-based Authenticated variable.
1252 //
1253 if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) {
1254 return VerifyTimeBasedPayloadAndUpdate (
1255 VariableName,
1256 VendorGuid,
1257 Data,
1258 DataSize,
1259 Attributes,
1260 AuthVarTypePriv,
1261 NULL
1262 );
1263 }
1264
1265 //
1266 // Determine if first time SetVariable with the EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS.
1267 //
1268 if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) {
1269 //
1270 // Determine current operation type.
1271 //
1272 if (DataSize == AUTHINFO_SIZE) {
1273 IsDeletion = TRUE;
1274 }
1275 //
1276 // Determine whether this is the first time with EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS set.
1277 //
1278 if (OrgVariableInfo.Data == NULL) {
1279 IsFirstTime = TRUE;
1280 } else if ((OrgVariableInfo.Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == 0) {
1281 IsFirstTime = TRUE;
1282 } else {
1283 KeyIndex = OrgVariableInfo.PubKeyIndex;
1284 IsFirstTime = FALSE;
1285 }
1286 } else if ((OrgVariableInfo.Data != NULL) &&
1287 ((OrgVariableInfo.Attributes & (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) != 0)
1288 ) {
1289 //
1290 // If the variable is already write-protected, it always needs authentication before update.
1291 //
1292 return EFI_WRITE_PROTECTED;
1293 } else {
1294 //
1295 // If without EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS, set and attributes collision.
1296 // That means it is not authenticated variable, just update variable as usual.
1297 //
1298 Status = AuthServiceInternalUpdateVariable (VariableName, VendorGuid, Data, DataSize, Attributes);
1299 return Status;
1300 }
1301
1302 //
1303 // Get PubKey and check Monotonic Count value corresponding to the variable.
1304 //
1305 CertData = (EFI_VARIABLE_AUTHENTICATION *) Data;
1306 CertBlock = (EFI_CERT_BLOCK_RSA_2048_SHA256 *) (CertData->AuthInfo.CertData);
1307 PubKey = CertBlock->PublicKey;
1308
1309 //
1310 // Update Monotonic Count value.
1311 //
1312 MonotonicCount = CertData->MonotonicCount;
1313
1314 if (!IsFirstTime) {
1315 //
1316 // 2 cases need to check here
1317 // 1. Internal PubKey variable. PubKeyIndex is always 0
1318 // 2. Other counter-based AuthVariable. Check input PubKey.
1319 //
1320 if (KeyIndex == 0) {
1321 return EFI_SECURITY_VIOLATION;
1322 }
1323 for (Index = 0; Index < mPubKeyNumber; Index++) {
1324 if (ReadUnaligned32 (&(((AUTHVAR_KEY_DB_DATA *) mPubKeyStore + Index)->KeyIndex)) == KeyIndex) {
1325 if (CompareMem (((AUTHVAR_KEY_DB_DATA *) mPubKeyStore + Index)->KeyData, PubKey, EFI_CERT_TYPE_RSA2048_SIZE) == 0) {
1326 break;
1327 } else {
1328 return EFI_SECURITY_VIOLATION;
1329 }
1330 }
1331 }
1332 if (Index == mPubKeyNumber) {
1333 return EFI_SECURITY_VIOLATION;
1334 }
1335
1336 //
1337 // Compare the current monotonic count and ensure that it is greater than the last SetVariable
1338 // operation with the EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS attribute set.
1339 //
1340 if (MonotonicCount <= OrgVariableInfo.MonotonicCount) {
1341 //
1342 // Monotonic count check fail, suspicious replay attack, return EFI_SECURITY_VIOLATION.
1343 //
1344 return EFI_SECURITY_VIOLATION;
1345 }
1346 }
1347 //
1348 // Verify the certificate in Data payload.
1349 //
1350 Status = VerifyCounterBasedPayload (Data, DataSize, PubKey);
1351 if (EFI_ERROR (Status)) {
1352 return Status;
1353 }
1354
1355 //
1356 // Now, the signature has been verified!
1357 //
1358 if (IsFirstTime && !IsDeletion) {
1359 VariableDataEntry.VariableSize = DataSize - AUTHINFO_SIZE;
1360 VariableDataEntry.Guid = VendorGuid;
1361 VariableDataEntry.Name = VariableName;
1362
1363 //
1364 // Update public key database variable if need.
1365 //
1366 KeyIndex = AddPubKeyInStore (PubKey, &VariableDataEntry);
1367 if (KeyIndex == 0) {
1368 return EFI_OUT_OF_RESOURCES;
1369 }
1370 }
1371
1372 //
1373 // Verification pass.
1374 //
1375 return AuthServiceInternalUpdateVariableWithMonotonicCount (VariableName, VendorGuid, (UINT8*)Data + AUTHINFO_SIZE, DataSize - AUTHINFO_SIZE, Attributes, KeyIndex, MonotonicCount);
1376 }
1377
1378 /**
1379 Filter out the duplicated EFI_SIGNATURE_DATA from the new data by comparing to the original data.
1380
1381 @param[in] Data Pointer to original EFI_SIGNATURE_LIST.
1382 @param[in] DataSize Size of Data buffer.
1383 @param[in, out] NewData Pointer to new EFI_SIGNATURE_LIST.
1384 @param[in, out] NewDataSize Size of NewData buffer.
1385
1386 **/
1387 EFI_STATUS
1388 FilterSignatureList (
1389 IN VOID *Data,
1390 IN UINTN DataSize,
1391 IN OUT VOID *NewData,
1392 IN OUT UINTN *NewDataSize
1393 )
1394 {
1395 EFI_SIGNATURE_LIST *CertList;
1396 EFI_SIGNATURE_DATA *Cert;
1397 UINTN CertCount;
1398 EFI_SIGNATURE_LIST *NewCertList;
1399 EFI_SIGNATURE_DATA *NewCert;
1400 UINTN NewCertCount;
1401 UINTN Index;
1402 UINTN Index2;
1403 UINTN Size;
1404 UINT8 *Tail;
1405 UINTN CopiedCount;
1406 UINTN SignatureListSize;
1407 BOOLEAN IsNewCert;
1408 UINT8 *TempData;
1409 UINTN TempDataSize;
1410 EFI_STATUS Status;
1411
1412 if (*NewDataSize == 0) {
1413 return EFI_SUCCESS;
1414 }
1415
1416 TempDataSize = *NewDataSize;
1417 Status = mAuthVarLibContextIn->GetScratchBuffer (&TempDataSize, (VOID **) &TempData);
1418 if (EFI_ERROR (Status)) {
1419 return EFI_OUT_OF_RESOURCES;
1420 }
1421
1422 Tail = TempData;
1423
1424 NewCertList = (EFI_SIGNATURE_LIST *) NewData;
1425 while ((*NewDataSize > 0) && (*NewDataSize >= NewCertList->SignatureListSize)) {
1426 NewCert = (EFI_SIGNATURE_DATA *) ((UINT8 *) NewCertList + sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize);
1427 NewCertCount = (NewCertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - NewCertList->SignatureHeaderSize) / NewCertList->SignatureSize;
1428
1429 CopiedCount = 0;
1430 for (Index = 0; Index < NewCertCount; Index++) {
1431 IsNewCert = TRUE;
1432
1433 Size = DataSize;
1434 CertList = (EFI_SIGNATURE_LIST *) Data;
1435 while ((Size > 0) && (Size >= CertList->SignatureListSize)) {
1436 if (CompareGuid (&CertList->SignatureType, &NewCertList->SignatureType) &&
1437 (CertList->SignatureSize == NewCertList->SignatureSize)) {
1438 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1439 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1440 for (Index2 = 0; Index2 < CertCount; Index2++) {
1441 //
1442 // Iterate each Signature Data in this Signature List.
1443 //
1444 if (CompareMem (NewCert, Cert, CertList->SignatureSize) == 0) {
1445 IsNewCert = FALSE;
1446 break;
1447 }
1448 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
1449 }
1450 }
1451
1452 if (!IsNewCert) {
1453 break;
1454 }
1455 Size -= CertList->SignatureListSize;
1456 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1457 }
1458
1459 if (IsNewCert) {
1460 //
1461 // New EFI_SIGNATURE_DATA, keep it.
1462 //
1463 if (CopiedCount == 0) {
1464 //
1465 // Copy EFI_SIGNATURE_LIST header for only once.
1466 //
1467 CopyMem (Tail, NewCertList, sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize);
1468 Tail = Tail + sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize;
1469 }
1470
1471 CopyMem (Tail, NewCert, NewCertList->SignatureSize);
1472 Tail += NewCertList->SignatureSize;
1473 CopiedCount++;
1474 }
1475
1476 NewCert = (EFI_SIGNATURE_DATA *) ((UINT8 *) NewCert + NewCertList->SignatureSize);
1477 }
1478
1479 //
1480 // Update SignatureListSize in the kept EFI_SIGNATURE_LIST.
1481 //
1482 if (CopiedCount != 0) {
1483 SignatureListSize = sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize + (CopiedCount * NewCertList->SignatureSize);
1484 CertList = (EFI_SIGNATURE_LIST *) (Tail - SignatureListSize);
1485 CertList->SignatureListSize = (UINT32) SignatureListSize;
1486 }
1487
1488 *NewDataSize -= NewCertList->SignatureListSize;
1489 NewCertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) NewCertList + NewCertList->SignatureListSize);
1490 }
1491
1492 TempDataSize = (Tail - (UINT8 *) TempData);
1493
1494 CopyMem (NewData, TempData, TempDataSize);
1495 *NewDataSize = TempDataSize;
1496
1497 return EFI_SUCCESS;
1498 }
1499
1500 /**
1501 Compare two EFI_TIME data.
1502
1503
1504 @param FirstTime A pointer to the first EFI_TIME data.
1505 @param SecondTime A pointer to the second EFI_TIME data.
1506
1507 @retval TRUE The FirstTime is not later than the SecondTime.
1508 @retval FALSE The FirstTime is later than the SecondTime.
1509
1510 **/
1511 BOOLEAN
1512 AuthServiceInternalCompareTimeStamp (
1513 IN EFI_TIME *FirstTime,
1514 IN EFI_TIME *SecondTime
1515 )
1516 {
1517 if (FirstTime->Year != SecondTime->Year) {
1518 return (BOOLEAN) (FirstTime->Year < SecondTime->Year);
1519 } else if (FirstTime->Month != SecondTime->Month) {
1520 return (BOOLEAN) (FirstTime->Month < SecondTime->Month);
1521 } else if (FirstTime->Day != SecondTime->Day) {
1522 return (BOOLEAN) (FirstTime->Day < SecondTime->Day);
1523 } else if (FirstTime->Hour != SecondTime->Hour) {
1524 return (BOOLEAN) (FirstTime->Hour < SecondTime->Hour);
1525 } else if (FirstTime->Minute != SecondTime->Minute) {
1526 return (BOOLEAN) (FirstTime->Minute < SecondTime->Minute);
1527 }
1528
1529 return (BOOLEAN) (FirstTime->Second <= SecondTime->Second);
1530 }
1531
1532 /**
1533 Calculate SHA256 digest of SignerCert CommonName + ToplevelCert tbsCertificate
1534 SignerCert and ToplevelCert are inside the signer certificate chain.
1535
1536 @param[in] SignerCert A pointer to SignerCert data.
1537 @param[in] SignerCertSize Length of SignerCert data.
1538 @param[in] TopLevelCert A pointer to TopLevelCert data.
1539 @param[in] TopLevelCertSize Length of TopLevelCert data.
1540 @param[out] Sha256Digest Sha256 digest calculated.
1541
1542 @return EFI_ABORTED Digest process failed.
1543 @return EFI_SUCCESS SHA256 Digest is succesfully calculated.
1544
1545 **/
1546 EFI_STATUS
1547 CalculatePrivAuthVarSignChainSHA256Digest(
1548 IN UINT8 *SignerCert,
1549 IN UINTN SignerCertSize,
1550 IN UINT8 *TopLevelCert,
1551 IN UINTN TopLevelCertSize,
1552 OUT UINT8 *Sha256Digest
1553 )
1554 {
1555 UINT8 *TbsCert;
1556 UINTN TbsCertSize;
1557 UINT8 CertCommonName[128];
1558 UINTN CertCommonNameSize;
1559 BOOLEAN CryptoStatus;
1560 EFI_STATUS Status;
1561
1562 CertCommonNameSize = sizeof(CertCommonName);
1563
1564 //
1565 // Get SignerCert CommonName
1566 //
1567 Status = X509GetCommonName(SignerCert, SignerCertSize, CertCommonName, &CertCommonNameSize);
1568 if (EFI_ERROR(Status)) {
1569 DEBUG((DEBUG_INFO, "%a Get SignerCert CommonName failed with status %x\n", __FUNCTION__, Status));
1570 return EFI_ABORTED;
1571 }
1572
1573 //
1574 // Get TopLevelCert tbsCertificate
1575 //
1576 if (!X509GetTBSCert(TopLevelCert, TopLevelCertSize, &TbsCert, &TbsCertSize)) {
1577 DEBUG((DEBUG_INFO, "%a Get Top-level Cert tbsCertificate failed!\n", __FUNCTION__));
1578 return EFI_ABORTED;
1579 }
1580
1581 //
1582 // Digest SignerCert CN + TopLevelCert tbsCertificate
1583 //
1584 ZeroMem (Sha256Digest, SHA256_DIGEST_SIZE);
1585 CryptoStatus = Sha256Init (mHashCtx);
1586 if (!CryptoStatus) {
1587 return EFI_ABORTED;
1588 }
1589
1590 //
1591 // '\0' is forced in CertCommonName. No overflow issue
1592 //
1593 CryptoStatus = Sha256Update (mHashCtx, CertCommonName, AsciiStrLen((CHAR8 *)CertCommonName));
1594 if (!CryptoStatus) {
1595 return EFI_ABORTED;
1596 }
1597
1598 CryptoStatus = Sha256Update (mHashCtx, TbsCert, TbsCertSize);
1599 if (!CryptoStatus) {
1600 return EFI_ABORTED;
1601 }
1602
1603 CryptoStatus = Sha256Final (mHashCtx, Sha256Digest);
1604 if (!CryptoStatus) {
1605 return EFI_ABORTED;
1606 }
1607
1608 return EFI_SUCCESS;
1609 }
1610
1611 /**
1612 Find matching signer's certificates for common authenticated variable
1613 by corresponding VariableName and VendorGuid from "certdb" or "certdbv".
1614
1615 The data format of "certdb" or "certdbv":
1616 //
1617 // UINT32 CertDbListSize;
1618 // /// AUTH_CERT_DB_DATA Certs1[];
1619 // /// AUTH_CERT_DB_DATA Certs2[];
1620 // /// ...
1621 // /// AUTH_CERT_DB_DATA Certsn[];
1622 //
1623
1624 @param[in] VariableName Name of authenticated Variable.
1625 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1626 @param[in] Data Pointer to variable "certdb" or "certdbv".
1627 @param[in] DataSize Size of variable "certdb" or "certdbv".
1628 @param[out] CertOffset Offset of matching CertData, from starting of Data.
1629 @param[out] CertDataSize Length of CertData in bytes.
1630 @param[out] CertNodeOffset Offset of matching AUTH_CERT_DB_DATA , from
1631 starting of Data.
1632 @param[out] CertNodeSize Length of AUTH_CERT_DB_DATA in bytes.
1633
1634 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1635 @retval EFI_NOT_FOUND Fail to find matching certs.
1636 @retval EFI_SUCCESS Find matching certs and output parameters.
1637
1638 **/
1639 EFI_STATUS
1640 FindCertsFromDb (
1641 IN CHAR16 *VariableName,
1642 IN EFI_GUID *VendorGuid,
1643 IN UINT8 *Data,
1644 IN UINTN DataSize,
1645 OUT UINT32 *CertOffset, OPTIONAL
1646 OUT UINT32 *CertDataSize, OPTIONAL
1647 OUT UINT32 *CertNodeOffset,OPTIONAL
1648 OUT UINT32 *CertNodeSize OPTIONAL
1649 )
1650 {
1651 UINT32 Offset;
1652 AUTH_CERT_DB_DATA *Ptr;
1653 UINT32 CertSize;
1654 UINT32 NameSize;
1655 UINT32 NodeSize;
1656 UINT32 CertDbListSize;
1657
1658 if ((VariableName == NULL) || (VendorGuid == NULL) || (Data == NULL)) {
1659 return EFI_INVALID_PARAMETER;
1660 }
1661
1662 //
1663 // Check whether DataSize matches recorded CertDbListSize.
1664 //
1665 if (DataSize < sizeof (UINT32)) {
1666 return EFI_INVALID_PARAMETER;
1667 }
1668
1669 CertDbListSize = ReadUnaligned32 ((UINT32 *) Data);
1670
1671 if (CertDbListSize != (UINT32) DataSize) {
1672 return EFI_INVALID_PARAMETER;
1673 }
1674
1675 Offset = sizeof (UINT32);
1676
1677 //
1678 // Get corresponding certificates by VendorGuid and VariableName.
1679 //
1680 while (Offset < (UINT32) DataSize) {
1681 Ptr = (AUTH_CERT_DB_DATA *) (Data + Offset);
1682 //
1683 // Check whether VendorGuid matches.
1684 //
1685 if (CompareGuid (&Ptr->VendorGuid, VendorGuid)) {
1686 NodeSize = ReadUnaligned32 (&Ptr->CertNodeSize);
1687 NameSize = ReadUnaligned32 (&Ptr->NameSize);
1688 CertSize = ReadUnaligned32 (&Ptr->CertDataSize);
1689
1690 if (NodeSize != sizeof (EFI_GUID) + sizeof (UINT32) * 3 + CertSize +
1691 sizeof (CHAR16) * NameSize) {
1692 return EFI_INVALID_PARAMETER;
1693 }
1694
1695 Offset = Offset + sizeof (EFI_GUID) + sizeof (UINT32) * 3;
1696 //
1697 // Check whether VariableName matches.
1698 //
1699 if ((NameSize == StrLen (VariableName)) &&
1700 (CompareMem (Data + Offset, VariableName, NameSize * sizeof (CHAR16)) == 0)) {
1701 Offset = Offset + NameSize * sizeof (CHAR16);
1702
1703 if (CertOffset != NULL) {
1704 *CertOffset = Offset;
1705 }
1706
1707 if (CertDataSize != NULL) {
1708 *CertDataSize = CertSize;
1709 }
1710
1711 if (CertNodeOffset != NULL) {
1712 *CertNodeOffset = (UINT32) ((UINT8 *) Ptr - Data);
1713 }
1714
1715 if (CertNodeSize != NULL) {
1716 *CertNodeSize = NodeSize;
1717 }
1718
1719 return EFI_SUCCESS;
1720 } else {
1721 Offset = Offset + NameSize * sizeof (CHAR16) + CertSize;
1722 }
1723 } else {
1724 NodeSize = ReadUnaligned32 (&Ptr->CertNodeSize);
1725 Offset = Offset + NodeSize;
1726 }
1727 }
1728
1729 return EFI_NOT_FOUND;
1730 }
1731
1732 /**
1733 Retrieve signer's certificates for common authenticated variable
1734 by corresponding VariableName and VendorGuid from "certdb"
1735 or "certdbv" according to authenticated variable attributes.
1736
1737 @param[in] VariableName Name of authenticated Variable.
1738 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1739 @param[in] Attributes Attributes of authenticated variable.
1740 @param[out] CertData Pointer to signer's certificates.
1741 @param[out] CertDataSize Length of CertData in bytes.
1742
1743 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1744 @retval EFI_NOT_FOUND Fail to find "certdb"/"certdbv" or matching certs.
1745 @retval EFI_SUCCESS Get signer's certificates successfully.
1746
1747 **/
1748 EFI_STATUS
1749 GetCertsFromDb (
1750 IN CHAR16 *VariableName,
1751 IN EFI_GUID *VendorGuid,
1752 IN UINT32 Attributes,
1753 OUT UINT8 **CertData,
1754 OUT UINT32 *CertDataSize
1755 )
1756 {
1757 EFI_STATUS Status;
1758 UINT8 *Data;
1759 UINTN DataSize;
1760 UINT32 CertOffset;
1761 CHAR16 *DbName;
1762
1763 if ((VariableName == NULL) || (VendorGuid == NULL) || (CertData == NULL) || (CertDataSize == NULL)) {
1764 return EFI_INVALID_PARAMETER;
1765 }
1766
1767
1768 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
1769 //
1770 // Get variable "certdb".
1771 //
1772 DbName = EFI_CERT_DB_NAME;
1773 } else {
1774 //
1775 // Get variable "certdbv".
1776 //
1777 DbName = EFI_CERT_DB_VOLATILE_NAME;
1778 }
1779
1780 //
1781 // Get variable "certdb" or "certdbv".
1782 //
1783 Status = AuthServiceInternalFindVariable (
1784 DbName,
1785 &gEfiCertDbGuid,
1786 (VOID **) &Data,
1787 &DataSize
1788 );
1789 if (EFI_ERROR (Status)) {
1790 return Status;
1791 }
1792
1793 if ((DataSize == 0) || (Data == NULL)) {
1794 ASSERT (FALSE);
1795 return EFI_NOT_FOUND;
1796 }
1797
1798 Status = FindCertsFromDb (
1799 VariableName,
1800 VendorGuid,
1801 Data,
1802 DataSize,
1803 &CertOffset,
1804 CertDataSize,
1805 NULL,
1806 NULL
1807 );
1808
1809 if (EFI_ERROR (Status)) {
1810 return Status;
1811 }
1812
1813 *CertData = Data + CertOffset;
1814 return EFI_SUCCESS;
1815 }
1816
1817 /**
1818 Delete matching signer's certificates when deleting common authenticated
1819 variable by corresponding VariableName and VendorGuid from "certdb" or
1820 "certdbv" according to authenticated variable attributes.
1821
1822 @param[in] VariableName Name of authenticated Variable.
1823 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1824 @param[in] Attributes Attributes of authenticated variable.
1825
1826 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1827 @retval EFI_NOT_FOUND Fail to find "certdb"/"certdbv" or matching certs.
1828 @retval EFI_OUT_OF_RESOURCES The operation is failed due to lack of resources.
1829 @retval EFI_SUCCESS The operation is completed successfully.
1830
1831 **/
1832 EFI_STATUS
1833 DeleteCertsFromDb (
1834 IN CHAR16 *VariableName,
1835 IN EFI_GUID *VendorGuid,
1836 IN UINT32 Attributes
1837 )
1838 {
1839 EFI_STATUS Status;
1840 UINT8 *Data;
1841 UINTN DataSize;
1842 UINT32 VarAttr;
1843 UINT32 CertNodeOffset;
1844 UINT32 CertNodeSize;
1845 UINT8 *NewCertDb;
1846 UINT32 NewCertDbSize;
1847 CHAR16 *DbName;
1848
1849 if ((VariableName == NULL) || (VendorGuid == NULL)) {
1850 return EFI_INVALID_PARAMETER;
1851 }
1852
1853 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
1854 //
1855 // Get variable "certdb".
1856 //
1857 DbName = EFI_CERT_DB_NAME;
1858 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
1859 } else {
1860 //
1861 // Get variable "certdbv".
1862 //
1863 DbName = EFI_CERT_DB_VOLATILE_NAME;
1864 VarAttr = EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
1865 }
1866
1867 Status = AuthServiceInternalFindVariable (
1868 DbName,
1869 &gEfiCertDbGuid,
1870 (VOID **) &Data,
1871 &DataSize
1872 );
1873
1874 if (EFI_ERROR (Status)) {
1875 return Status;
1876 }
1877
1878 if ((DataSize == 0) || (Data == NULL)) {
1879 ASSERT (FALSE);
1880 return EFI_NOT_FOUND;
1881 }
1882
1883 if (DataSize == sizeof (UINT32)) {
1884 //
1885 // There is no certs in "certdb" or "certdbv".
1886 //
1887 return EFI_SUCCESS;
1888 }
1889
1890 //
1891 // Get corresponding cert node from "certdb" or "certdbv".
1892 //
1893 Status = FindCertsFromDb (
1894 VariableName,
1895 VendorGuid,
1896 Data,
1897 DataSize,
1898 NULL,
1899 NULL,
1900 &CertNodeOffset,
1901 &CertNodeSize
1902 );
1903
1904 if (EFI_ERROR (Status)) {
1905 return Status;
1906 }
1907
1908 if (DataSize < (CertNodeOffset + CertNodeSize)) {
1909 return EFI_NOT_FOUND;
1910 }
1911
1912 //
1913 // Construct new data content of variable "certdb" or "certdbv".
1914 //
1915 NewCertDbSize = (UINT32) DataSize - CertNodeSize;
1916 NewCertDb = (UINT8*) mCertDbStore;
1917
1918 //
1919 // Copy the DB entries before deleting node.
1920 //
1921 CopyMem (NewCertDb, Data, CertNodeOffset);
1922 //
1923 // Update CertDbListSize.
1924 //
1925 CopyMem (NewCertDb, &NewCertDbSize, sizeof (UINT32));
1926 //
1927 // Copy the DB entries after deleting node.
1928 //
1929 if (DataSize > (CertNodeOffset + CertNodeSize)) {
1930 CopyMem (
1931 NewCertDb + CertNodeOffset,
1932 Data + CertNodeOffset + CertNodeSize,
1933 DataSize - CertNodeOffset - CertNodeSize
1934 );
1935 }
1936
1937 //
1938 // Set "certdb" or "certdbv".
1939 //
1940 Status = AuthServiceInternalUpdateVariable (
1941 DbName,
1942 &gEfiCertDbGuid,
1943 NewCertDb,
1944 NewCertDbSize,
1945 VarAttr
1946 );
1947
1948 return Status;
1949 }
1950
1951 /**
1952 Insert signer's certificates for common authenticated variable with VariableName
1953 and VendorGuid in AUTH_CERT_DB_DATA to "certdb" or "certdbv" according to
1954 time based authenticated variable attributes. CertData is the SHA256 digest of
1955 SignerCert CommonName + TopLevelCert tbsCertificate.
1956
1957 @param[in] VariableName Name of authenticated Variable.
1958 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1959 @param[in] Attributes Attributes of authenticated variable.
1960 @param[in] SignerCert Signer certificate data.
1961 @param[in] SignerCertSize Length of signer certificate.
1962 @param[in] TopLevelCert Top-level certificate data.
1963 @param[in] TopLevelCertSize Length of top-level certificate.
1964
1965 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1966 @retval EFI_ACCESS_DENIED An AUTH_CERT_DB_DATA entry with same VariableName
1967 and VendorGuid already exists.
1968 @retval EFI_OUT_OF_RESOURCES The operation is failed due to lack of resources.
1969 @retval EFI_SUCCESS Insert an AUTH_CERT_DB_DATA entry to "certdb" or "certdbv"
1970
1971 **/
1972 EFI_STATUS
1973 InsertCertsToDb (
1974 IN CHAR16 *VariableName,
1975 IN EFI_GUID *VendorGuid,
1976 IN UINT32 Attributes,
1977 IN UINT8 *SignerCert,
1978 IN UINTN SignerCertSize,
1979 IN UINT8 *TopLevelCert,
1980 IN UINTN TopLevelCertSize
1981 )
1982 {
1983 EFI_STATUS Status;
1984 UINT8 *Data;
1985 UINTN DataSize;
1986 UINT32 VarAttr;
1987 UINT8 *NewCertDb;
1988 UINT32 NewCertDbSize;
1989 UINT32 CertNodeSize;
1990 UINT32 NameSize;
1991 UINT32 CertDataSize;
1992 AUTH_CERT_DB_DATA *Ptr;
1993 CHAR16 *DbName;
1994 UINT8 Sha256Digest[SHA256_DIGEST_SIZE];
1995
1996 if ((VariableName == NULL) || (VendorGuid == NULL) || (SignerCert == NULL) ||(TopLevelCert == NULL)) {
1997 return EFI_INVALID_PARAMETER;
1998 }
1999
2000 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
2001 //
2002 // Get variable "certdb".
2003 //
2004 DbName = EFI_CERT_DB_NAME;
2005 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
2006 } else {
2007 //
2008 // Get variable "certdbv".
2009 //
2010 DbName = EFI_CERT_DB_VOLATILE_NAME;
2011 VarAttr = EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
2012 }
2013
2014 //
2015 // Get variable "certdb" or "certdbv".
2016 //
2017 Status = AuthServiceInternalFindVariable (
2018 DbName,
2019 &gEfiCertDbGuid,
2020 (VOID **) &Data,
2021 &DataSize
2022 );
2023 if (EFI_ERROR (Status)) {
2024 return Status;
2025 }
2026
2027 if ((DataSize == 0) || (Data == NULL)) {
2028 ASSERT (FALSE);
2029 return EFI_NOT_FOUND;
2030 }
2031
2032 //
2033 // Find whether matching cert node already exists in "certdb" or "certdbv".
2034 // If yes return error.
2035 //
2036 Status = FindCertsFromDb (
2037 VariableName,
2038 VendorGuid,
2039 Data,
2040 DataSize,
2041 NULL,
2042 NULL,
2043 NULL,
2044 NULL
2045 );
2046
2047 if (!EFI_ERROR (Status)) {
2048 ASSERT (FALSE);
2049 return EFI_ACCESS_DENIED;
2050 }
2051
2052 //
2053 // Construct new data content of variable "certdb" or "certdbv".
2054 //
2055 NameSize = (UINT32) StrLen (VariableName);
2056 CertDataSize = sizeof(Sha256Digest);
2057 CertNodeSize = sizeof (AUTH_CERT_DB_DATA) + (UINT32) CertDataSize + NameSize * sizeof (CHAR16);
2058 NewCertDbSize = (UINT32) DataSize + CertNodeSize;
2059 if (NewCertDbSize > mMaxCertDbSize) {
2060 return EFI_OUT_OF_RESOURCES;
2061 }
2062
2063 Status = CalculatePrivAuthVarSignChainSHA256Digest(
2064 SignerCert,
2065 SignerCertSize,
2066 TopLevelCert,
2067 TopLevelCertSize,
2068 Sha256Digest
2069 );
2070 if (EFI_ERROR (Status)) {
2071 return Status;
2072 }
2073
2074 NewCertDb = (UINT8*) mCertDbStore;
2075
2076 //
2077 // Copy the DB entries before inserting node.
2078 //
2079 CopyMem (NewCertDb, Data, DataSize);
2080 //
2081 // Update CertDbListSize.
2082 //
2083 CopyMem (NewCertDb, &NewCertDbSize, sizeof (UINT32));
2084 //
2085 // Construct new cert node.
2086 //
2087 Ptr = (AUTH_CERT_DB_DATA *) (NewCertDb + DataSize);
2088 CopyGuid (&Ptr->VendorGuid, VendorGuid);
2089 CopyMem (&Ptr->CertNodeSize, &CertNodeSize, sizeof (UINT32));
2090 CopyMem (&Ptr->NameSize, &NameSize, sizeof (UINT32));
2091 CopyMem (&Ptr->CertDataSize, &CertDataSize, sizeof (UINT32));
2092
2093 CopyMem (
2094 (UINT8 *) Ptr + sizeof (AUTH_CERT_DB_DATA),
2095 VariableName,
2096 NameSize * sizeof (CHAR16)
2097 );
2098
2099 CopyMem (
2100 (UINT8 *) Ptr + sizeof (AUTH_CERT_DB_DATA) + NameSize * sizeof (CHAR16),
2101 Sha256Digest,
2102 CertDataSize
2103 );
2104
2105 //
2106 // Set "certdb" or "certdbv".
2107 //
2108 Status = AuthServiceInternalUpdateVariable (
2109 DbName,
2110 &gEfiCertDbGuid,
2111 NewCertDb,
2112 NewCertDbSize,
2113 VarAttr
2114 );
2115
2116 return Status;
2117 }
2118
2119 /**
2120 Clean up signer's certificates for common authenticated variable
2121 by corresponding VariableName and VendorGuid from "certdb".
2122 System may break down during Timebased Variable update & certdb update,
2123 make them inconsistent, this function is called in AuthVariable Init
2124 to ensure consistency.
2125
2126 @retval EFI_NOT_FOUND Fail to find variable "certdb".
2127 @retval EFI_OUT_OF_RESOURCES The operation is failed due to lack of resources.
2128 @retval EFI_SUCCESS The operation is completed successfully.
2129
2130 **/
2131 EFI_STATUS
2132 CleanCertsFromDb (
2133 VOID
2134 )
2135 {
2136 UINT32 Offset;
2137 AUTH_CERT_DB_DATA *Ptr;
2138 UINT32 NameSize;
2139 UINT32 NodeSize;
2140 CHAR16 *VariableName;
2141 EFI_STATUS Status;
2142 BOOLEAN CertCleaned;
2143 UINT8 *Data;
2144 UINTN DataSize;
2145 EFI_GUID AuthVarGuid;
2146 AUTH_VARIABLE_INFO AuthVariableInfo;
2147
2148 Status = EFI_SUCCESS;
2149
2150 //
2151 // Get corresponding certificates by VendorGuid and VariableName.
2152 //
2153 do {
2154 CertCleaned = FALSE;
2155
2156 //
2157 // Get latest variable "certdb"
2158 //
2159 Status = AuthServiceInternalFindVariable (
2160 EFI_CERT_DB_NAME,
2161 &gEfiCertDbGuid,
2162 (VOID **) &Data,
2163 &DataSize
2164 );
2165 if (EFI_ERROR (Status)) {
2166 return Status;
2167 }
2168
2169 if ((DataSize == 0) || (Data == NULL)) {
2170 ASSERT (FALSE);
2171 return EFI_NOT_FOUND;
2172 }
2173
2174 Offset = sizeof (UINT32);
2175
2176 while (Offset < (UINT32) DataSize) {
2177 Ptr = (AUTH_CERT_DB_DATA *) (Data + Offset);
2178 NodeSize = ReadUnaligned32 (&Ptr->CertNodeSize);
2179 NameSize = ReadUnaligned32 (&Ptr->NameSize);
2180
2181 //
2182 // Get VarName tailed with '\0'
2183 //
2184 VariableName = AllocateZeroPool((NameSize + 1) * sizeof(CHAR16));
2185 if (VariableName == NULL) {
2186 return EFI_OUT_OF_RESOURCES;
2187 }
2188 CopyMem (VariableName, (UINT8 *) Ptr + sizeof (AUTH_CERT_DB_DATA), NameSize * sizeof(CHAR16));
2189 //
2190 // Keep VarGuid aligned
2191 //
2192 CopyMem (&AuthVarGuid, &Ptr->VendorGuid, sizeof(EFI_GUID));
2193
2194 //
2195 // Find corresponding time auth variable
2196 //
2197 ZeroMem (&AuthVariableInfo, sizeof (AuthVariableInfo));
2198 Status = mAuthVarLibContextIn->FindVariable (
2199 VariableName,
2200 &AuthVarGuid,
2201 &AuthVariableInfo
2202 );
2203
2204 if (EFI_ERROR(Status) || (AuthVariableInfo.Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == 0) {
2205 Status = DeleteCertsFromDb(
2206 VariableName,
2207 &AuthVarGuid,
2208 AuthVariableInfo.Attributes
2209 );
2210 CertCleaned = TRUE;
2211 DEBUG((EFI_D_INFO, "Recovery!! Cert for Auth Variable %s Guid %g is removed for consistency\n", VariableName, &AuthVarGuid));
2212 FreePool(VariableName);
2213 break;
2214 }
2215
2216 FreePool(VariableName);
2217 Offset = Offset + NodeSize;
2218 }
2219 } while (CertCleaned);
2220
2221 return Status;
2222 }
2223
2224 /**
2225 Process variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS set
2226
2227 Caution: This function may receive untrusted input.
2228 This function may be invoked in SMM mode, and datasize and data are external input.
2229 This function will do basic validation, before parse the data.
2230 This function will parse the authentication carefully to avoid security issues, like
2231 buffer overflow, integer overflow.
2232
2233 @param[in] VariableName Name of Variable to be found.
2234 @param[in] VendorGuid Variable vendor GUID.
2235 @param[in] Data Data pointer.
2236 @param[in] DataSize Size of Data found. If size is less than the
2237 data, this value contains the required size.
2238 @param[in] Attributes Attribute value of the variable.
2239 @param[in] AuthVarType Verify against PK, KEK database, private database or certificate in data payload.
2240 @param[in] OrgTimeStamp Pointer to original time stamp,
2241 original variable is not found if NULL.
2242 @param[out] VarPayloadPtr Pointer to variable payload address.
2243 @param[out] VarPayloadSize Pointer to variable payload size.
2244
2245 @retval EFI_INVALID_PARAMETER Invalid parameter.
2246 @retval EFI_SECURITY_VIOLATION The variable does NOT pass the validation
2247 check carried out by the firmware.
2248 @retval EFI_OUT_OF_RESOURCES Failed to process variable due to lack
2249 of resources.
2250 @retval EFI_SUCCESS Variable pass validation successfully.
2251
2252 **/
2253 EFI_STATUS
2254 VerifyTimeBasedPayload (
2255 IN CHAR16 *VariableName,
2256 IN EFI_GUID *VendorGuid,
2257 IN VOID *Data,
2258 IN UINTN DataSize,
2259 IN UINT32 Attributes,
2260 IN AUTHVAR_TYPE AuthVarType,
2261 IN EFI_TIME *OrgTimeStamp,
2262 OUT UINT8 **VarPayloadPtr,
2263 OUT UINTN *VarPayloadSize
2264 )
2265 {
2266 EFI_VARIABLE_AUTHENTICATION_2 *CertData;
2267 UINT8 *SigData;
2268 UINT32 SigDataSize;
2269 UINT8 *PayloadPtr;
2270 UINTN PayloadSize;
2271 UINT32 Attr;
2272 BOOLEAN VerifyStatus;
2273 EFI_STATUS Status;
2274 EFI_SIGNATURE_LIST *CertList;
2275 EFI_SIGNATURE_DATA *Cert;
2276 UINTN Index;
2277 UINTN CertCount;
2278 UINT32 KekDataSize;
2279 UINT8 *NewData;
2280 UINTN NewDataSize;
2281 UINT8 *Buffer;
2282 UINTN Length;
2283 UINT8 *TopLevelCert;
2284 UINTN TopLevelCertSize;
2285 UINT8 *TrustedCert;
2286 UINTN TrustedCertSize;
2287 UINT8 *SignerCerts;
2288 UINTN CertStackSize;
2289 UINT8 *CertsInCertDb;
2290 UINT32 CertsSizeinDb;
2291 UINT8 Sha256Digest[SHA256_DIGEST_SIZE];
2292
2293 //
2294 // 1. TopLevelCert is the top-level issuer certificate in signature Signer Cert Chain
2295 // 2. TrustedCert is the certificate which firmware trusts. It could be saved in protected
2296 // storage or PK payload on PK init
2297 //
2298 VerifyStatus = FALSE;
2299 CertData = NULL;
2300 NewData = NULL;
2301 Attr = Attributes;
2302 SignerCerts = NULL;
2303 TopLevelCert = NULL;
2304 CertsInCertDb = NULL;
2305
2306 //
2307 // When the attribute EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS is
2308 // set, then the Data buffer shall begin with an instance of a complete (and serialized)
2309 // EFI_VARIABLE_AUTHENTICATION_2 descriptor. The descriptor shall be followed by the new
2310 // variable value and DataSize shall reflect the combined size of the descriptor and the new
2311 // variable value. The authentication descriptor is not part of the variable data and is not
2312 // returned by subsequent calls to GetVariable().
2313 //
2314 CertData = (EFI_VARIABLE_AUTHENTICATION_2 *) Data;
2315
2316 //
2317 // Verify that Pad1, Nanosecond, TimeZone, Daylight and Pad2 components of the
2318 // TimeStamp value are set to zero.
2319 //
2320 if ((CertData->TimeStamp.Pad1 != 0) ||
2321 (CertData->TimeStamp.Nanosecond != 0) ||
2322 (CertData->TimeStamp.TimeZone != 0) ||
2323 (CertData->TimeStamp.Daylight != 0) ||
2324 (CertData->TimeStamp.Pad2 != 0)) {
2325 return EFI_SECURITY_VIOLATION;
2326 }
2327
2328 if ((OrgTimeStamp != NULL) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0)) {
2329 if (AuthServiceInternalCompareTimeStamp (&CertData->TimeStamp, OrgTimeStamp)) {
2330 //
2331 // TimeStamp check fail, suspicious replay attack, return EFI_SECURITY_VIOLATION.
2332 //
2333 return EFI_SECURITY_VIOLATION;
2334 }
2335 }
2336
2337 //
2338 // wCertificateType should be WIN_CERT_TYPE_EFI_GUID.
2339 // Cert type should be EFI_CERT_TYPE_PKCS7_GUID.
2340 //
2341 if ((CertData->AuthInfo.Hdr.wCertificateType != WIN_CERT_TYPE_EFI_GUID) ||
2342 !CompareGuid (&CertData->AuthInfo.CertType, &gEfiCertPkcs7Guid)) {
2343 //
2344 // Invalid AuthInfo type, return EFI_SECURITY_VIOLATION.
2345 //
2346 return EFI_SECURITY_VIOLATION;
2347 }
2348
2349 //
2350 // Find out Pkcs7 SignedData which follows the EFI_VARIABLE_AUTHENTICATION_2 descriptor.
2351 // AuthInfo.Hdr.dwLength is the length of the entire certificate, including the length of the header.
2352 //
2353 SigData = CertData->AuthInfo.CertData;
2354 SigDataSize = CertData->AuthInfo.Hdr.dwLength - (UINT32) (OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData));
2355
2356 //
2357 // SignedData.digestAlgorithms shall contain the digest algorithm used when preparing the
2358 // signature. Only a digest algorithm of SHA-256 is accepted.
2359 //
2360 // According to PKCS#7 Definition:
2361 // SignedData ::= SEQUENCE {
2362 // version Version,
2363 // digestAlgorithms DigestAlgorithmIdentifiers,
2364 // contentInfo ContentInfo,
2365 // .... }
2366 // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm
2367 // in VARIABLE_AUTHENTICATION_2 descriptor.
2368 // This field has the fixed offset (+13) and be calculated based on two bytes of length encoding.
2369 //
2370 if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) {
2371 if (SigDataSize >= (13 + sizeof (mSha256OidValue))) {
2372 if (((*(SigData + 1) & TWO_BYTE_ENCODE) != TWO_BYTE_ENCODE) ||
2373 (CompareMem (SigData + 13, &mSha256OidValue, sizeof (mSha256OidValue)) != 0)) {
2374 return EFI_SECURITY_VIOLATION;
2375 }
2376 }
2377 }
2378
2379 //
2380 // Find out the new data payload which follows Pkcs7 SignedData directly.
2381 //
2382 PayloadPtr = SigData + SigDataSize;
2383 PayloadSize = DataSize - OFFSET_OF_AUTHINFO2_CERT_DATA - (UINTN) SigDataSize;
2384
2385 //
2386 // Construct a serialization buffer of the values of the VariableName, VendorGuid and Attributes
2387 // parameters of the SetVariable() call and the TimeStamp component of the
2388 // EFI_VARIABLE_AUTHENTICATION_2 descriptor followed by the variable's new value
2389 // i.e. (VariableName, VendorGuid, Attributes, TimeStamp, Data)
2390 //
2391 NewDataSize = PayloadSize + sizeof (EFI_TIME) + sizeof (UINT32) +
2392 sizeof (EFI_GUID) + StrSize (VariableName) - sizeof (CHAR16);
2393
2394 //
2395 // Here is to reuse scratch data area(at the end of volatile variable store)
2396 // to reduce SMRAM consumption for SMM variable driver.
2397 // The scratch buffer is enough to hold the serialized data and safe to use,
2398 // because it is only used at here to do verification temporarily first
2399 // and then used in UpdateVariable() for a time based auth variable set.
2400 //
2401 Status = mAuthVarLibContextIn->GetScratchBuffer (&NewDataSize, (VOID **) &NewData);
2402 if (EFI_ERROR (Status)) {
2403 return EFI_OUT_OF_RESOURCES;
2404 }
2405
2406 Buffer = NewData;
2407 Length = StrLen (VariableName) * sizeof (CHAR16);
2408 CopyMem (Buffer, VariableName, Length);
2409 Buffer += Length;
2410
2411 Length = sizeof (EFI_GUID);
2412 CopyMem (Buffer, VendorGuid, Length);
2413 Buffer += Length;
2414
2415 Length = sizeof (UINT32);
2416 CopyMem (Buffer, &Attr, Length);
2417 Buffer += Length;
2418
2419 Length = sizeof (EFI_TIME);
2420 CopyMem (Buffer, &CertData->TimeStamp, Length);
2421 Buffer += Length;
2422
2423 CopyMem (Buffer, PayloadPtr, PayloadSize);
2424
2425 if (AuthVarType == AuthVarTypePk) {
2426 //
2427 // Verify that the signature has been made with the current Platform Key (no chaining for PK).
2428 // First, get signer's certificates from SignedData.
2429 //
2430 VerifyStatus = Pkcs7GetSigners (
2431 SigData,
2432 SigDataSize,
2433 &SignerCerts,
2434 &CertStackSize,
2435 &TopLevelCert,
2436 &TopLevelCertSize
2437 );
2438 if (!VerifyStatus) {
2439 goto Exit;
2440 }
2441
2442 //
2443 // Second, get the current platform key from variable. Check whether it's identical with signer's certificates
2444 // in SignedData. If not, return error immediately.
2445 //
2446 Status = AuthServiceInternalFindVariable (
2447 EFI_PLATFORM_KEY_NAME,
2448 &gEfiGlobalVariableGuid,
2449 &Data,
2450 &DataSize
2451 );
2452 if (EFI_ERROR (Status)) {
2453 VerifyStatus = FALSE;
2454 goto Exit;
2455 }
2456 CertList = (EFI_SIGNATURE_LIST *) Data;
2457 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2458 if ((TopLevelCertSize != (CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1))) ||
2459 (CompareMem (Cert->SignatureData, TopLevelCert, TopLevelCertSize) != 0)) {
2460 VerifyStatus = FALSE;
2461 goto Exit;
2462 }
2463
2464 //
2465 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2466 //
2467 VerifyStatus = Pkcs7Verify (
2468 SigData,
2469 SigDataSize,
2470 TopLevelCert,
2471 TopLevelCertSize,
2472 NewData,
2473 NewDataSize
2474 );
2475
2476 } else if (AuthVarType == AuthVarTypeKek) {
2477
2478 //
2479 // Get KEK database from variable.
2480 //
2481 Status = AuthServiceInternalFindVariable (
2482 EFI_KEY_EXCHANGE_KEY_NAME,
2483 &gEfiGlobalVariableGuid,
2484 &Data,
2485 &DataSize
2486 );
2487 if (EFI_ERROR (Status)) {
2488 return Status;
2489 }
2490
2491 //
2492 // Ready to verify Pkcs7 SignedData. Go through KEK Signature Database to find out X.509 CertList.
2493 //
2494 KekDataSize = (UINT32) DataSize;
2495 CertList = (EFI_SIGNATURE_LIST *) Data;
2496 while ((KekDataSize > 0) && (KekDataSize >= CertList->SignatureListSize)) {
2497 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
2498 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2499 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
2500 for (Index = 0; Index < CertCount; Index++) {
2501 //
2502 // Iterate each Signature Data Node within this CertList for a verify
2503 //
2504 TrustedCert = Cert->SignatureData;
2505 TrustedCertSize = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);
2506
2507 //
2508 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2509 //
2510 VerifyStatus = Pkcs7Verify (
2511 SigData,
2512 SigDataSize,
2513 TrustedCert,
2514 TrustedCertSize,
2515 NewData,
2516 NewDataSize
2517 );
2518 if (VerifyStatus) {
2519 goto Exit;
2520 }
2521 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
2522 }
2523 }
2524 KekDataSize -= CertList->SignatureListSize;
2525 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
2526 }
2527 } else if (AuthVarType == AuthVarTypePriv) {
2528
2529 //
2530 // Process common authenticated variable except PK/KEK/DB/DBX/DBT.
2531 // Get signer's certificates from SignedData.
2532 //
2533 VerifyStatus = Pkcs7GetSigners (
2534 SigData,
2535 SigDataSize,
2536 &SignerCerts,
2537 &CertStackSize,
2538 &TopLevelCert,
2539 &TopLevelCertSize
2540 );
2541 if (!VerifyStatus) {
2542 goto Exit;
2543 }
2544
2545 //
2546 // Get previously stored signer's certificates from certdb or certdbv for existing
2547 // variable. Check whether they are identical with signer's certificates
2548 // in SignedData. If not, return error immediately.
2549 //
2550 if (OrgTimeStamp != NULL) {
2551 VerifyStatus = FALSE;
2552
2553 Status = GetCertsFromDb (VariableName, VendorGuid, Attributes, &CertsInCertDb, &CertsSizeinDb);
2554 if (EFI_ERROR (Status)) {
2555 goto Exit;
2556 }
2557
2558 if (CertsSizeinDb == SHA256_DIGEST_SIZE) {
2559 //
2560 // Check hash of signer cert CommonName + Top-level issuer tbsCertificate against data in CertDb
2561 //
2562 Status = CalculatePrivAuthVarSignChainSHA256Digest(
2563 SignerCerts + sizeof(UINT8) + sizeof(UINT32),
2564 ReadUnaligned32 ((UINT32 *)(SignerCerts + sizeof(UINT8))),
2565 TopLevelCert,
2566 TopLevelCertSize,
2567 Sha256Digest
2568 );
2569 if (EFI_ERROR(Status) || CompareMem (Sha256Digest, CertsInCertDb, CertsSizeinDb) != 0){
2570 goto Exit;
2571 }
2572 } else {
2573 //
2574 // Keep backward compatible with previous solution which saves whole signer certs stack in CertDb
2575 //
2576 if ((CertStackSize != CertsSizeinDb) ||
2577 (CompareMem (SignerCerts, CertsInCertDb, CertsSizeinDb) != 0)) {
2578 goto Exit;
2579 }
2580 }
2581 }
2582
2583 VerifyStatus = Pkcs7Verify (
2584 SigData,
2585 SigDataSize,
2586 TopLevelCert,
2587 TopLevelCertSize,
2588 NewData,
2589 NewDataSize
2590 );
2591 if (!VerifyStatus) {
2592 goto Exit;
2593 }
2594
2595 if ((OrgTimeStamp == NULL) && (PayloadSize != 0)) {
2596 //
2597 // When adding a new common authenticated variable, always save Hash of cn of signer cert + tbsCertificate of Top-level issuer
2598 //
2599 Status = InsertCertsToDb (
2600 VariableName,
2601 VendorGuid,
2602 Attributes,
2603 SignerCerts + sizeof(UINT8) + sizeof(UINT32),
2604 ReadUnaligned32 ((UINT32 *)(SignerCerts + sizeof(UINT8))),
2605 TopLevelCert,
2606 TopLevelCertSize
2607 );
2608 if (EFI_ERROR (Status)) {
2609 VerifyStatus = FALSE;
2610 goto Exit;
2611 }
2612 }
2613 } else if (AuthVarType == AuthVarTypePayload) {
2614 CertList = (EFI_SIGNATURE_LIST *) PayloadPtr;
2615 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2616 TrustedCert = Cert->SignatureData;
2617 TrustedCertSize = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);
2618 //
2619 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2620 //
2621 VerifyStatus = Pkcs7Verify (
2622 SigData,
2623 SigDataSize,
2624 TrustedCert,
2625 TrustedCertSize,
2626 NewData,
2627 NewDataSize
2628 );
2629 } else {
2630 return EFI_SECURITY_VIOLATION;
2631 }
2632
2633 Exit:
2634
2635 if (AuthVarType == AuthVarTypePk || AuthVarType == AuthVarTypePriv) {
2636 Pkcs7FreeSigners (TopLevelCert);
2637 Pkcs7FreeSigners (SignerCerts);
2638 }
2639
2640 if (!VerifyStatus) {
2641 return EFI_SECURITY_VIOLATION;
2642 }
2643
2644 Status = CheckSignatureListFormat(VariableName, VendorGuid, PayloadPtr, PayloadSize);
2645 if (EFI_ERROR (Status)) {
2646 return Status;
2647 }
2648
2649 *VarPayloadPtr = PayloadPtr;
2650 *VarPayloadSize = PayloadSize;
2651
2652 return EFI_SUCCESS;
2653 }
2654
2655 /**
2656 Process variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS set
2657
2658 Caution: This function may receive untrusted input.
2659 This function may be invoked in SMM mode, and datasize and data are external input.
2660 This function will do basic validation, before parse the data.
2661 This function will parse the authentication carefully to avoid security issues, like
2662 buffer overflow, integer overflow.
2663
2664 @param[in] VariableName Name of Variable to be found.
2665 @param[in] VendorGuid Variable vendor GUID.
2666 @param[in] Data Data pointer.
2667 @param[in] DataSize Size of Data found. If size is less than the
2668 data, this value contains the required size.
2669 @param[in] Attributes Attribute value of the variable.
2670 @param[in] AuthVarType Verify against PK, KEK database, private database or certificate in data payload.
2671 @param[out] VarDel Delete the variable or not.
2672
2673 @retval EFI_INVALID_PARAMETER Invalid parameter.
2674 @retval EFI_SECURITY_VIOLATION The variable does NOT pass the validation
2675 check carried out by the firmware.
2676 @retval EFI_OUT_OF_RESOURCES Failed to process variable due to lack
2677 of resources.
2678 @retval EFI_SUCCESS Variable pass validation successfully.
2679
2680 **/
2681 EFI_STATUS
2682 VerifyTimeBasedPayloadAndUpdate (
2683 IN CHAR16 *VariableName,
2684 IN EFI_GUID *VendorGuid,
2685 IN VOID *Data,
2686 IN UINTN DataSize,
2687 IN UINT32 Attributes,
2688 IN AUTHVAR_TYPE AuthVarType,
2689 OUT BOOLEAN *VarDel
2690 )
2691 {
2692 EFI_STATUS Status;
2693 EFI_STATUS FindStatus;
2694 UINT8 *PayloadPtr;
2695 UINTN PayloadSize;
2696 EFI_VARIABLE_AUTHENTICATION_2 *CertData;
2697 AUTH_VARIABLE_INFO OrgVariableInfo;
2698 BOOLEAN IsDel;
2699
2700 ZeroMem (&OrgVariableInfo, sizeof (OrgVariableInfo));
2701 FindStatus = mAuthVarLibContextIn->FindVariable (
2702 VariableName,
2703 VendorGuid,
2704 &OrgVariableInfo
2705 );
2706
2707 Status = VerifyTimeBasedPayload (
2708 VariableName,
2709 VendorGuid,
2710 Data,
2711 DataSize,
2712 Attributes,
2713 AuthVarType,
2714 (!EFI_ERROR (FindStatus)) ? OrgVariableInfo.TimeStamp : NULL,
2715 &PayloadPtr,
2716 &PayloadSize
2717 );
2718 if (EFI_ERROR (Status)) {
2719 return Status;
2720 }
2721
2722 if (!EFI_ERROR(FindStatus)
2723 && (PayloadSize == 0)
2724 && ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0)) {
2725 IsDel = TRUE;
2726 } else {
2727 IsDel = FALSE;
2728 }
2729
2730 CertData = (EFI_VARIABLE_AUTHENTICATION_2 *) Data;
2731
2732 //
2733 // Final step: Update/Append Variable if it pass Pkcs7Verify
2734 //
2735 Status = AuthServiceInternalUpdateVariableWithTimeStamp (
2736 VariableName,
2737 VendorGuid,
2738 PayloadPtr,
2739 PayloadSize,
2740 Attributes,
2741 &CertData->TimeStamp
2742 );
2743
2744 //
2745 // Delete signer's certificates when delete the common authenticated variable.
2746 //
2747 if (IsDel && AuthVarType == AuthVarTypePriv && !EFI_ERROR(Status) ) {
2748 Status = DeleteCertsFromDb (VariableName, VendorGuid, Attributes);
2749 }
2750
2751 if (VarDel != NULL) {
2752 if (IsDel && !EFI_ERROR(Status)) {
2753 *VarDel = TRUE;
2754 } else {
2755 *VarDel = FALSE;
2756 }
2757 }
2758
2759 return Status;
2760 }