]> git.proxmox.com Git - mirror_edk2.git/blob - SecurityPkg/Library/AuthVariableLib/AuthService.c
SecurityPkg/AuthVariableLib: fix GCC build error
[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 CHAR8 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 (
1594 mHashCtx,
1595 CertCommonName,
1596 AsciiStrLen (CertCommonName)
1597 );
1598 if (!CryptoStatus) {
1599 return EFI_ABORTED;
1600 }
1601
1602 CryptoStatus = Sha256Update (mHashCtx, TbsCert, TbsCertSize);
1603 if (!CryptoStatus) {
1604 return EFI_ABORTED;
1605 }
1606
1607 CryptoStatus = Sha256Final (mHashCtx, Sha256Digest);
1608 if (!CryptoStatus) {
1609 return EFI_ABORTED;
1610 }
1611
1612 return EFI_SUCCESS;
1613 }
1614
1615 /**
1616 Find matching signer's certificates for common authenticated variable
1617 by corresponding VariableName and VendorGuid from "certdb" or "certdbv".
1618
1619 The data format of "certdb" or "certdbv":
1620 //
1621 // UINT32 CertDbListSize;
1622 // /// AUTH_CERT_DB_DATA Certs1[];
1623 // /// AUTH_CERT_DB_DATA Certs2[];
1624 // /// ...
1625 // /// AUTH_CERT_DB_DATA Certsn[];
1626 //
1627
1628 @param[in] VariableName Name of authenticated Variable.
1629 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1630 @param[in] Data Pointer to variable "certdb" or "certdbv".
1631 @param[in] DataSize Size of variable "certdb" or "certdbv".
1632 @param[out] CertOffset Offset of matching CertData, from starting of Data.
1633 @param[out] CertDataSize Length of CertData in bytes.
1634 @param[out] CertNodeOffset Offset of matching AUTH_CERT_DB_DATA , from
1635 starting of Data.
1636 @param[out] CertNodeSize Length of AUTH_CERT_DB_DATA in bytes.
1637
1638 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1639 @retval EFI_NOT_FOUND Fail to find matching certs.
1640 @retval EFI_SUCCESS Find matching certs and output parameters.
1641
1642 **/
1643 EFI_STATUS
1644 FindCertsFromDb (
1645 IN CHAR16 *VariableName,
1646 IN EFI_GUID *VendorGuid,
1647 IN UINT8 *Data,
1648 IN UINTN DataSize,
1649 OUT UINT32 *CertOffset, OPTIONAL
1650 OUT UINT32 *CertDataSize, OPTIONAL
1651 OUT UINT32 *CertNodeOffset,OPTIONAL
1652 OUT UINT32 *CertNodeSize OPTIONAL
1653 )
1654 {
1655 UINT32 Offset;
1656 AUTH_CERT_DB_DATA *Ptr;
1657 UINT32 CertSize;
1658 UINT32 NameSize;
1659 UINT32 NodeSize;
1660 UINT32 CertDbListSize;
1661
1662 if ((VariableName == NULL) || (VendorGuid == NULL) || (Data == NULL)) {
1663 return EFI_INVALID_PARAMETER;
1664 }
1665
1666 //
1667 // Check whether DataSize matches recorded CertDbListSize.
1668 //
1669 if (DataSize < sizeof (UINT32)) {
1670 return EFI_INVALID_PARAMETER;
1671 }
1672
1673 CertDbListSize = ReadUnaligned32 ((UINT32 *) Data);
1674
1675 if (CertDbListSize != (UINT32) DataSize) {
1676 return EFI_INVALID_PARAMETER;
1677 }
1678
1679 Offset = sizeof (UINT32);
1680
1681 //
1682 // Get corresponding certificates by VendorGuid and VariableName.
1683 //
1684 while (Offset < (UINT32) DataSize) {
1685 Ptr = (AUTH_CERT_DB_DATA *) (Data + Offset);
1686 //
1687 // Check whether VendorGuid matches.
1688 //
1689 if (CompareGuid (&Ptr->VendorGuid, VendorGuid)) {
1690 NodeSize = ReadUnaligned32 (&Ptr->CertNodeSize);
1691 NameSize = ReadUnaligned32 (&Ptr->NameSize);
1692 CertSize = ReadUnaligned32 (&Ptr->CertDataSize);
1693
1694 if (NodeSize != sizeof (EFI_GUID) + sizeof (UINT32) * 3 + CertSize +
1695 sizeof (CHAR16) * NameSize) {
1696 return EFI_INVALID_PARAMETER;
1697 }
1698
1699 Offset = Offset + sizeof (EFI_GUID) + sizeof (UINT32) * 3;
1700 //
1701 // Check whether VariableName matches.
1702 //
1703 if ((NameSize == StrLen (VariableName)) &&
1704 (CompareMem (Data + Offset, VariableName, NameSize * sizeof (CHAR16)) == 0)) {
1705 Offset = Offset + NameSize * sizeof (CHAR16);
1706
1707 if (CertOffset != NULL) {
1708 *CertOffset = Offset;
1709 }
1710
1711 if (CertDataSize != NULL) {
1712 *CertDataSize = CertSize;
1713 }
1714
1715 if (CertNodeOffset != NULL) {
1716 *CertNodeOffset = (UINT32) ((UINT8 *) Ptr - Data);
1717 }
1718
1719 if (CertNodeSize != NULL) {
1720 *CertNodeSize = NodeSize;
1721 }
1722
1723 return EFI_SUCCESS;
1724 } else {
1725 Offset = Offset + NameSize * sizeof (CHAR16) + CertSize;
1726 }
1727 } else {
1728 NodeSize = ReadUnaligned32 (&Ptr->CertNodeSize);
1729 Offset = Offset + NodeSize;
1730 }
1731 }
1732
1733 return EFI_NOT_FOUND;
1734 }
1735
1736 /**
1737 Retrieve signer's certificates for common authenticated variable
1738 by corresponding VariableName and VendorGuid from "certdb"
1739 or "certdbv" according to authenticated variable attributes.
1740
1741 @param[in] VariableName Name of authenticated Variable.
1742 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1743 @param[in] Attributes Attributes of authenticated variable.
1744 @param[out] CertData Pointer to signer's certificates.
1745 @param[out] CertDataSize Length of CertData in bytes.
1746
1747 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1748 @retval EFI_NOT_FOUND Fail to find "certdb"/"certdbv" or matching certs.
1749 @retval EFI_SUCCESS Get signer's certificates successfully.
1750
1751 **/
1752 EFI_STATUS
1753 GetCertsFromDb (
1754 IN CHAR16 *VariableName,
1755 IN EFI_GUID *VendorGuid,
1756 IN UINT32 Attributes,
1757 OUT UINT8 **CertData,
1758 OUT UINT32 *CertDataSize
1759 )
1760 {
1761 EFI_STATUS Status;
1762 UINT8 *Data;
1763 UINTN DataSize;
1764 UINT32 CertOffset;
1765 CHAR16 *DbName;
1766
1767 if ((VariableName == NULL) || (VendorGuid == NULL) || (CertData == NULL) || (CertDataSize == NULL)) {
1768 return EFI_INVALID_PARAMETER;
1769 }
1770
1771
1772 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
1773 //
1774 // Get variable "certdb".
1775 //
1776 DbName = EFI_CERT_DB_NAME;
1777 } else {
1778 //
1779 // Get variable "certdbv".
1780 //
1781 DbName = EFI_CERT_DB_VOLATILE_NAME;
1782 }
1783
1784 //
1785 // Get variable "certdb" or "certdbv".
1786 //
1787 Status = AuthServiceInternalFindVariable (
1788 DbName,
1789 &gEfiCertDbGuid,
1790 (VOID **) &Data,
1791 &DataSize
1792 );
1793 if (EFI_ERROR (Status)) {
1794 return Status;
1795 }
1796
1797 if ((DataSize == 0) || (Data == NULL)) {
1798 ASSERT (FALSE);
1799 return EFI_NOT_FOUND;
1800 }
1801
1802 Status = FindCertsFromDb (
1803 VariableName,
1804 VendorGuid,
1805 Data,
1806 DataSize,
1807 &CertOffset,
1808 CertDataSize,
1809 NULL,
1810 NULL
1811 );
1812
1813 if (EFI_ERROR (Status)) {
1814 return Status;
1815 }
1816
1817 *CertData = Data + CertOffset;
1818 return EFI_SUCCESS;
1819 }
1820
1821 /**
1822 Delete matching signer's certificates when deleting common authenticated
1823 variable by corresponding VariableName and VendorGuid from "certdb" or
1824 "certdbv" according to authenticated variable attributes.
1825
1826 @param[in] VariableName Name of authenticated Variable.
1827 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1828 @param[in] Attributes Attributes of authenticated variable.
1829
1830 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1831 @retval EFI_NOT_FOUND Fail to find "certdb"/"certdbv" or matching certs.
1832 @retval EFI_OUT_OF_RESOURCES The operation is failed due to lack of resources.
1833 @retval EFI_SUCCESS The operation is completed successfully.
1834
1835 **/
1836 EFI_STATUS
1837 DeleteCertsFromDb (
1838 IN CHAR16 *VariableName,
1839 IN EFI_GUID *VendorGuid,
1840 IN UINT32 Attributes
1841 )
1842 {
1843 EFI_STATUS Status;
1844 UINT8 *Data;
1845 UINTN DataSize;
1846 UINT32 VarAttr;
1847 UINT32 CertNodeOffset;
1848 UINT32 CertNodeSize;
1849 UINT8 *NewCertDb;
1850 UINT32 NewCertDbSize;
1851 CHAR16 *DbName;
1852
1853 if ((VariableName == NULL) || (VendorGuid == NULL)) {
1854 return EFI_INVALID_PARAMETER;
1855 }
1856
1857 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
1858 //
1859 // Get variable "certdb".
1860 //
1861 DbName = EFI_CERT_DB_NAME;
1862 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
1863 } else {
1864 //
1865 // Get variable "certdbv".
1866 //
1867 DbName = EFI_CERT_DB_VOLATILE_NAME;
1868 VarAttr = EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
1869 }
1870
1871 Status = AuthServiceInternalFindVariable (
1872 DbName,
1873 &gEfiCertDbGuid,
1874 (VOID **) &Data,
1875 &DataSize
1876 );
1877
1878 if (EFI_ERROR (Status)) {
1879 return Status;
1880 }
1881
1882 if ((DataSize == 0) || (Data == NULL)) {
1883 ASSERT (FALSE);
1884 return EFI_NOT_FOUND;
1885 }
1886
1887 if (DataSize == sizeof (UINT32)) {
1888 //
1889 // There is no certs in "certdb" or "certdbv".
1890 //
1891 return EFI_SUCCESS;
1892 }
1893
1894 //
1895 // Get corresponding cert node from "certdb" or "certdbv".
1896 //
1897 Status = FindCertsFromDb (
1898 VariableName,
1899 VendorGuid,
1900 Data,
1901 DataSize,
1902 NULL,
1903 NULL,
1904 &CertNodeOffset,
1905 &CertNodeSize
1906 );
1907
1908 if (EFI_ERROR (Status)) {
1909 return Status;
1910 }
1911
1912 if (DataSize < (CertNodeOffset + CertNodeSize)) {
1913 return EFI_NOT_FOUND;
1914 }
1915
1916 //
1917 // Construct new data content of variable "certdb" or "certdbv".
1918 //
1919 NewCertDbSize = (UINT32) DataSize - CertNodeSize;
1920 NewCertDb = (UINT8*) mCertDbStore;
1921
1922 //
1923 // Copy the DB entries before deleting node.
1924 //
1925 CopyMem (NewCertDb, Data, CertNodeOffset);
1926 //
1927 // Update CertDbListSize.
1928 //
1929 CopyMem (NewCertDb, &NewCertDbSize, sizeof (UINT32));
1930 //
1931 // Copy the DB entries after deleting node.
1932 //
1933 if (DataSize > (CertNodeOffset + CertNodeSize)) {
1934 CopyMem (
1935 NewCertDb + CertNodeOffset,
1936 Data + CertNodeOffset + CertNodeSize,
1937 DataSize - CertNodeOffset - CertNodeSize
1938 );
1939 }
1940
1941 //
1942 // Set "certdb" or "certdbv".
1943 //
1944 Status = AuthServiceInternalUpdateVariable (
1945 DbName,
1946 &gEfiCertDbGuid,
1947 NewCertDb,
1948 NewCertDbSize,
1949 VarAttr
1950 );
1951
1952 return Status;
1953 }
1954
1955 /**
1956 Insert signer's certificates for common authenticated variable with VariableName
1957 and VendorGuid in AUTH_CERT_DB_DATA to "certdb" or "certdbv" according to
1958 time based authenticated variable attributes. CertData is the SHA256 digest of
1959 SignerCert CommonName + TopLevelCert tbsCertificate.
1960
1961 @param[in] VariableName Name of authenticated Variable.
1962 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1963 @param[in] Attributes Attributes of authenticated variable.
1964 @param[in] SignerCert Signer certificate data.
1965 @param[in] SignerCertSize Length of signer certificate.
1966 @param[in] TopLevelCert Top-level certificate data.
1967 @param[in] TopLevelCertSize Length of top-level certificate.
1968
1969 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1970 @retval EFI_ACCESS_DENIED An AUTH_CERT_DB_DATA entry with same VariableName
1971 and VendorGuid already exists.
1972 @retval EFI_OUT_OF_RESOURCES The operation is failed due to lack of resources.
1973 @retval EFI_SUCCESS Insert an AUTH_CERT_DB_DATA entry to "certdb" or "certdbv"
1974
1975 **/
1976 EFI_STATUS
1977 InsertCertsToDb (
1978 IN CHAR16 *VariableName,
1979 IN EFI_GUID *VendorGuid,
1980 IN UINT32 Attributes,
1981 IN UINT8 *SignerCert,
1982 IN UINTN SignerCertSize,
1983 IN UINT8 *TopLevelCert,
1984 IN UINTN TopLevelCertSize
1985 )
1986 {
1987 EFI_STATUS Status;
1988 UINT8 *Data;
1989 UINTN DataSize;
1990 UINT32 VarAttr;
1991 UINT8 *NewCertDb;
1992 UINT32 NewCertDbSize;
1993 UINT32 CertNodeSize;
1994 UINT32 NameSize;
1995 UINT32 CertDataSize;
1996 AUTH_CERT_DB_DATA *Ptr;
1997 CHAR16 *DbName;
1998 UINT8 Sha256Digest[SHA256_DIGEST_SIZE];
1999
2000 if ((VariableName == NULL) || (VendorGuid == NULL) || (SignerCert == NULL) ||(TopLevelCert == NULL)) {
2001 return EFI_INVALID_PARAMETER;
2002 }
2003
2004 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
2005 //
2006 // Get variable "certdb".
2007 //
2008 DbName = EFI_CERT_DB_NAME;
2009 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
2010 } else {
2011 //
2012 // Get variable "certdbv".
2013 //
2014 DbName = EFI_CERT_DB_VOLATILE_NAME;
2015 VarAttr = EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
2016 }
2017
2018 //
2019 // Get variable "certdb" or "certdbv".
2020 //
2021 Status = AuthServiceInternalFindVariable (
2022 DbName,
2023 &gEfiCertDbGuid,
2024 (VOID **) &Data,
2025 &DataSize
2026 );
2027 if (EFI_ERROR (Status)) {
2028 return Status;
2029 }
2030
2031 if ((DataSize == 0) || (Data == NULL)) {
2032 ASSERT (FALSE);
2033 return EFI_NOT_FOUND;
2034 }
2035
2036 //
2037 // Find whether matching cert node already exists in "certdb" or "certdbv".
2038 // If yes return error.
2039 //
2040 Status = FindCertsFromDb (
2041 VariableName,
2042 VendorGuid,
2043 Data,
2044 DataSize,
2045 NULL,
2046 NULL,
2047 NULL,
2048 NULL
2049 );
2050
2051 if (!EFI_ERROR (Status)) {
2052 ASSERT (FALSE);
2053 return EFI_ACCESS_DENIED;
2054 }
2055
2056 //
2057 // Construct new data content of variable "certdb" or "certdbv".
2058 //
2059 NameSize = (UINT32) StrLen (VariableName);
2060 CertDataSize = sizeof(Sha256Digest);
2061 CertNodeSize = sizeof (AUTH_CERT_DB_DATA) + (UINT32) CertDataSize + NameSize * sizeof (CHAR16);
2062 NewCertDbSize = (UINT32) DataSize + CertNodeSize;
2063 if (NewCertDbSize > mMaxCertDbSize) {
2064 return EFI_OUT_OF_RESOURCES;
2065 }
2066
2067 Status = CalculatePrivAuthVarSignChainSHA256Digest(
2068 SignerCert,
2069 SignerCertSize,
2070 TopLevelCert,
2071 TopLevelCertSize,
2072 Sha256Digest
2073 );
2074 if (EFI_ERROR (Status)) {
2075 return Status;
2076 }
2077
2078 NewCertDb = (UINT8*) mCertDbStore;
2079
2080 //
2081 // Copy the DB entries before inserting node.
2082 //
2083 CopyMem (NewCertDb, Data, DataSize);
2084 //
2085 // Update CertDbListSize.
2086 //
2087 CopyMem (NewCertDb, &NewCertDbSize, sizeof (UINT32));
2088 //
2089 // Construct new cert node.
2090 //
2091 Ptr = (AUTH_CERT_DB_DATA *) (NewCertDb + DataSize);
2092 CopyGuid (&Ptr->VendorGuid, VendorGuid);
2093 CopyMem (&Ptr->CertNodeSize, &CertNodeSize, sizeof (UINT32));
2094 CopyMem (&Ptr->NameSize, &NameSize, sizeof (UINT32));
2095 CopyMem (&Ptr->CertDataSize, &CertDataSize, sizeof (UINT32));
2096
2097 CopyMem (
2098 (UINT8 *) Ptr + sizeof (AUTH_CERT_DB_DATA),
2099 VariableName,
2100 NameSize * sizeof (CHAR16)
2101 );
2102
2103 CopyMem (
2104 (UINT8 *) Ptr + sizeof (AUTH_CERT_DB_DATA) + NameSize * sizeof (CHAR16),
2105 Sha256Digest,
2106 CertDataSize
2107 );
2108
2109 //
2110 // Set "certdb" or "certdbv".
2111 //
2112 Status = AuthServiceInternalUpdateVariable (
2113 DbName,
2114 &gEfiCertDbGuid,
2115 NewCertDb,
2116 NewCertDbSize,
2117 VarAttr
2118 );
2119
2120 return Status;
2121 }
2122
2123 /**
2124 Clean up signer's certificates for common authenticated variable
2125 by corresponding VariableName and VendorGuid from "certdb".
2126 System may break down during Timebased Variable update & certdb update,
2127 make them inconsistent, this function is called in AuthVariable Init
2128 to ensure consistency.
2129
2130 @retval EFI_NOT_FOUND Fail to find variable "certdb".
2131 @retval EFI_OUT_OF_RESOURCES The operation is failed due to lack of resources.
2132 @retval EFI_SUCCESS The operation is completed successfully.
2133
2134 **/
2135 EFI_STATUS
2136 CleanCertsFromDb (
2137 VOID
2138 )
2139 {
2140 UINT32 Offset;
2141 AUTH_CERT_DB_DATA *Ptr;
2142 UINT32 NameSize;
2143 UINT32 NodeSize;
2144 CHAR16 *VariableName;
2145 EFI_STATUS Status;
2146 BOOLEAN CertCleaned;
2147 UINT8 *Data;
2148 UINTN DataSize;
2149 EFI_GUID AuthVarGuid;
2150 AUTH_VARIABLE_INFO AuthVariableInfo;
2151
2152 Status = EFI_SUCCESS;
2153
2154 //
2155 // Get corresponding certificates by VendorGuid and VariableName.
2156 //
2157 do {
2158 CertCleaned = FALSE;
2159
2160 //
2161 // Get latest variable "certdb"
2162 //
2163 Status = AuthServiceInternalFindVariable (
2164 EFI_CERT_DB_NAME,
2165 &gEfiCertDbGuid,
2166 (VOID **) &Data,
2167 &DataSize
2168 );
2169 if (EFI_ERROR (Status)) {
2170 return Status;
2171 }
2172
2173 if ((DataSize == 0) || (Data == NULL)) {
2174 ASSERT (FALSE);
2175 return EFI_NOT_FOUND;
2176 }
2177
2178 Offset = sizeof (UINT32);
2179
2180 while (Offset < (UINT32) DataSize) {
2181 Ptr = (AUTH_CERT_DB_DATA *) (Data + Offset);
2182 NodeSize = ReadUnaligned32 (&Ptr->CertNodeSize);
2183 NameSize = ReadUnaligned32 (&Ptr->NameSize);
2184
2185 //
2186 // Get VarName tailed with '\0'
2187 //
2188 VariableName = AllocateZeroPool((NameSize + 1) * sizeof(CHAR16));
2189 if (VariableName == NULL) {
2190 return EFI_OUT_OF_RESOURCES;
2191 }
2192 CopyMem (VariableName, (UINT8 *) Ptr + sizeof (AUTH_CERT_DB_DATA), NameSize * sizeof(CHAR16));
2193 //
2194 // Keep VarGuid aligned
2195 //
2196 CopyMem (&AuthVarGuid, &Ptr->VendorGuid, sizeof(EFI_GUID));
2197
2198 //
2199 // Find corresponding time auth variable
2200 //
2201 ZeroMem (&AuthVariableInfo, sizeof (AuthVariableInfo));
2202 Status = mAuthVarLibContextIn->FindVariable (
2203 VariableName,
2204 &AuthVarGuid,
2205 &AuthVariableInfo
2206 );
2207
2208 if (EFI_ERROR(Status) || (AuthVariableInfo.Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == 0) {
2209 Status = DeleteCertsFromDb(
2210 VariableName,
2211 &AuthVarGuid,
2212 AuthVariableInfo.Attributes
2213 );
2214 CertCleaned = TRUE;
2215 DEBUG((EFI_D_INFO, "Recovery!! Cert for Auth Variable %s Guid %g is removed for consistency\n", VariableName, &AuthVarGuid));
2216 FreePool(VariableName);
2217 break;
2218 }
2219
2220 FreePool(VariableName);
2221 Offset = Offset + NodeSize;
2222 }
2223 } while (CertCleaned);
2224
2225 return Status;
2226 }
2227
2228 /**
2229 Process variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS set
2230
2231 Caution: This function may receive untrusted input.
2232 This function may be invoked in SMM mode, and datasize and data are external input.
2233 This function will do basic validation, before parse the data.
2234 This function will parse the authentication carefully to avoid security issues, like
2235 buffer overflow, integer overflow.
2236
2237 @param[in] VariableName Name of Variable to be found.
2238 @param[in] VendorGuid Variable vendor GUID.
2239 @param[in] Data Data pointer.
2240 @param[in] DataSize Size of Data found. If size is less than the
2241 data, this value contains the required size.
2242 @param[in] Attributes Attribute value of the variable.
2243 @param[in] AuthVarType Verify against PK, KEK database, private database or certificate in data payload.
2244 @param[in] OrgTimeStamp Pointer to original time stamp,
2245 original variable is not found if NULL.
2246 @param[out] VarPayloadPtr Pointer to variable payload address.
2247 @param[out] VarPayloadSize Pointer to variable payload size.
2248
2249 @retval EFI_INVALID_PARAMETER Invalid parameter.
2250 @retval EFI_SECURITY_VIOLATION The variable does NOT pass the validation
2251 check carried out by the firmware.
2252 @retval EFI_OUT_OF_RESOURCES Failed to process variable due to lack
2253 of resources.
2254 @retval EFI_SUCCESS Variable pass validation successfully.
2255
2256 **/
2257 EFI_STATUS
2258 VerifyTimeBasedPayload (
2259 IN CHAR16 *VariableName,
2260 IN EFI_GUID *VendorGuid,
2261 IN VOID *Data,
2262 IN UINTN DataSize,
2263 IN UINT32 Attributes,
2264 IN AUTHVAR_TYPE AuthVarType,
2265 IN EFI_TIME *OrgTimeStamp,
2266 OUT UINT8 **VarPayloadPtr,
2267 OUT UINTN *VarPayloadSize
2268 )
2269 {
2270 EFI_VARIABLE_AUTHENTICATION_2 *CertData;
2271 UINT8 *SigData;
2272 UINT32 SigDataSize;
2273 UINT8 *PayloadPtr;
2274 UINTN PayloadSize;
2275 UINT32 Attr;
2276 BOOLEAN VerifyStatus;
2277 EFI_STATUS Status;
2278 EFI_SIGNATURE_LIST *CertList;
2279 EFI_SIGNATURE_DATA *Cert;
2280 UINTN Index;
2281 UINTN CertCount;
2282 UINT32 KekDataSize;
2283 UINT8 *NewData;
2284 UINTN NewDataSize;
2285 UINT8 *Buffer;
2286 UINTN Length;
2287 UINT8 *TopLevelCert;
2288 UINTN TopLevelCertSize;
2289 UINT8 *TrustedCert;
2290 UINTN TrustedCertSize;
2291 UINT8 *SignerCerts;
2292 UINTN CertStackSize;
2293 UINT8 *CertsInCertDb;
2294 UINT32 CertsSizeinDb;
2295 UINT8 Sha256Digest[SHA256_DIGEST_SIZE];
2296
2297 //
2298 // 1. TopLevelCert is the top-level issuer certificate in signature Signer Cert Chain
2299 // 2. TrustedCert is the certificate which firmware trusts. It could be saved in protected
2300 // storage or PK payload on PK init
2301 //
2302 VerifyStatus = FALSE;
2303 CertData = NULL;
2304 NewData = NULL;
2305 Attr = Attributes;
2306 SignerCerts = NULL;
2307 TopLevelCert = NULL;
2308 CertsInCertDb = NULL;
2309
2310 //
2311 // When the attribute EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS is
2312 // set, then the Data buffer shall begin with an instance of a complete (and serialized)
2313 // EFI_VARIABLE_AUTHENTICATION_2 descriptor. The descriptor shall be followed by the new
2314 // variable value and DataSize shall reflect the combined size of the descriptor and the new
2315 // variable value. The authentication descriptor is not part of the variable data and is not
2316 // returned by subsequent calls to GetVariable().
2317 //
2318 CertData = (EFI_VARIABLE_AUTHENTICATION_2 *) Data;
2319
2320 //
2321 // Verify that Pad1, Nanosecond, TimeZone, Daylight and Pad2 components of the
2322 // TimeStamp value are set to zero.
2323 //
2324 if ((CertData->TimeStamp.Pad1 != 0) ||
2325 (CertData->TimeStamp.Nanosecond != 0) ||
2326 (CertData->TimeStamp.TimeZone != 0) ||
2327 (CertData->TimeStamp.Daylight != 0) ||
2328 (CertData->TimeStamp.Pad2 != 0)) {
2329 return EFI_SECURITY_VIOLATION;
2330 }
2331
2332 if ((OrgTimeStamp != NULL) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0)) {
2333 if (AuthServiceInternalCompareTimeStamp (&CertData->TimeStamp, OrgTimeStamp)) {
2334 //
2335 // TimeStamp check fail, suspicious replay attack, return EFI_SECURITY_VIOLATION.
2336 //
2337 return EFI_SECURITY_VIOLATION;
2338 }
2339 }
2340
2341 //
2342 // wCertificateType should be WIN_CERT_TYPE_EFI_GUID.
2343 // Cert type should be EFI_CERT_TYPE_PKCS7_GUID.
2344 //
2345 if ((CertData->AuthInfo.Hdr.wCertificateType != WIN_CERT_TYPE_EFI_GUID) ||
2346 !CompareGuid (&CertData->AuthInfo.CertType, &gEfiCertPkcs7Guid)) {
2347 //
2348 // Invalid AuthInfo type, return EFI_SECURITY_VIOLATION.
2349 //
2350 return EFI_SECURITY_VIOLATION;
2351 }
2352
2353 //
2354 // Find out Pkcs7 SignedData which follows the EFI_VARIABLE_AUTHENTICATION_2 descriptor.
2355 // AuthInfo.Hdr.dwLength is the length of the entire certificate, including the length of the header.
2356 //
2357 SigData = CertData->AuthInfo.CertData;
2358 SigDataSize = CertData->AuthInfo.Hdr.dwLength - (UINT32) (OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData));
2359
2360 //
2361 // SignedData.digestAlgorithms shall contain the digest algorithm used when preparing the
2362 // signature. Only a digest algorithm of SHA-256 is accepted.
2363 //
2364 // According to PKCS#7 Definition:
2365 // SignedData ::= SEQUENCE {
2366 // version Version,
2367 // digestAlgorithms DigestAlgorithmIdentifiers,
2368 // contentInfo ContentInfo,
2369 // .... }
2370 // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm
2371 // in VARIABLE_AUTHENTICATION_2 descriptor.
2372 // This field has the fixed offset (+13) and be calculated based on two bytes of length encoding.
2373 //
2374 if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) {
2375 if (SigDataSize >= (13 + sizeof (mSha256OidValue))) {
2376 if (((*(SigData + 1) & TWO_BYTE_ENCODE) != TWO_BYTE_ENCODE) ||
2377 (CompareMem (SigData + 13, &mSha256OidValue, sizeof (mSha256OidValue)) != 0)) {
2378 return EFI_SECURITY_VIOLATION;
2379 }
2380 }
2381 }
2382
2383 //
2384 // Find out the new data payload which follows Pkcs7 SignedData directly.
2385 //
2386 PayloadPtr = SigData + SigDataSize;
2387 PayloadSize = DataSize - OFFSET_OF_AUTHINFO2_CERT_DATA - (UINTN) SigDataSize;
2388
2389 //
2390 // Construct a serialization buffer of the values of the VariableName, VendorGuid and Attributes
2391 // parameters of the SetVariable() call and the TimeStamp component of the
2392 // EFI_VARIABLE_AUTHENTICATION_2 descriptor followed by the variable's new value
2393 // i.e. (VariableName, VendorGuid, Attributes, TimeStamp, Data)
2394 //
2395 NewDataSize = PayloadSize + sizeof (EFI_TIME) + sizeof (UINT32) +
2396 sizeof (EFI_GUID) + StrSize (VariableName) - sizeof (CHAR16);
2397
2398 //
2399 // Here is to reuse scratch data area(at the end of volatile variable store)
2400 // to reduce SMRAM consumption for SMM variable driver.
2401 // The scratch buffer is enough to hold the serialized data and safe to use,
2402 // because it is only used at here to do verification temporarily first
2403 // and then used in UpdateVariable() for a time based auth variable set.
2404 //
2405 Status = mAuthVarLibContextIn->GetScratchBuffer (&NewDataSize, (VOID **) &NewData);
2406 if (EFI_ERROR (Status)) {
2407 return EFI_OUT_OF_RESOURCES;
2408 }
2409
2410 Buffer = NewData;
2411 Length = StrLen (VariableName) * sizeof (CHAR16);
2412 CopyMem (Buffer, VariableName, Length);
2413 Buffer += Length;
2414
2415 Length = sizeof (EFI_GUID);
2416 CopyMem (Buffer, VendorGuid, Length);
2417 Buffer += Length;
2418
2419 Length = sizeof (UINT32);
2420 CopyMem (Buffer, &Attr, Length);
2421 Buffer += Length;
2422
2423 Length = sizeof (EFI_TIME);
2424 CopyMem (Buffer, &CertData->TimeStamp, Length);
2425 Buffer += Length;
2426
2427 CopyMem (Buffer, PayloadPtr, PayloadSize);
2428
2429 if (AuthVarType == AuthVarTypePk) {
2430 //
2431 // Verify that the signature has been made with the current Platform Key (no chaining for PK).
2432 // First, get signer's certificates from SignedData.
2433 //
2434 VerifyStatus = Pkcs7GetSigners (
2435 SigData,
2436 SigDataSize,
2437 &SignerCerts,
2438 &CertStackSize,
2439 &TopLevelCert,
2440 &TopLevelCertSize
2441 );
2442 if (!VerifyStatus) {
2443 goto Exit;
2444 }
2445
2446 //
2447 // Second, get the current platform key from variable. Check whether it's identical with signer's certificates
2448 // in SignedData. If not, return error immediately.
2449 //
2450 Status = AuthServiceInternalFindVariable (
2451 EFI_PLATFORM_KEY_NAME,
2452 &gEfiGlobalVariableGuid,
2453 &Data,
2454 &DataSize
2455 );
2456 if (EFI_ERROR (Status)) {
2457 VerifyStatus = FALSE;
2458 goto Exit;
2459 }
2460 CertList = (EFI_SIGNATURE_LIST *) Data;
2461 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2462 if ((TopLevelCertSize != (CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1))) ||
2463 (CompareMem (Cert->SignatureData, TopLevelCert, TopLevelCertSize) != 0)) {
2464 VerifyStatus = FALSE;
2465 goto Exit;
2466 }
2467
2468 //
2469 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2470 //
2471 VerifyStatus = Pkcs7Verify (
2472 SigData,
2473 SigDataSize,
2474 TopLevelCert,
2475 TopLevelCertSize,
2476 NewData,
2477 NewDataSize
2478 );
2479
2480 } else if (AuthVarType == AuthVarTypeKek) {
2481
2482 //
2483 // Get KEK database from variable.
2484 //
2485 Status = AuthServiceInternalFindVariable (
2486 EFI_KEY_EXCHANGE_KEY_NAME,
2487 &gEfiGlobalVariableGuid,
2488 &Data,
2489 &DataSize
2490 );
2491 if (EFI_ERROR (Status)) {
2492 return Status;
2493 }
2494
2495 //
2496 // Ready to verify Pkcs7 SignedData. Go through KEK Signature Database to find out X.509 CertList.
2497 //
2498 KekDataSize = (UINT32) DataSize;
2499 CertList = (EFI_SIGNATURE_LIST *) Data;
2500 while ((KekDataSize > 0) && (KekDataSize >= CertList->SignatureListSize)) {
2501 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
2502 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2503 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
2504 for (Index = 0; Index < CertCount; Index++) {
2505 //
2506 // Iterate each Signature Data Node within this CertList for a verify
2507 //
2508 TrustedCert = Cert->SignatureData;
2509 TrustedCertSize = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);
2510
2511 //
2512 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2513 //
2514 VerifyStatus = Pkcs7Verify (
2515 SigData,
2516 SigDataSize,
2517 TrustedCert,
2518 TrustedCertSize,
2519 NewData,
2520 NewDataSize
2521 );
2522 if (VerifyStatus) {
2523 goto Exit;
2524 }
2525 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
2526 }
2527 }
2528 KekDataSize -= CertList->SignatureListSize;
2529 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
2530 }
2531 } else if (AuthVarType == AuthVarTypePriv) {
2532
2533 //
2534 // Process common authenticated variable except PK/KEK/DB/DBX/DBT.
2535 // Get signer's certificates from SignedData.
2536 //
2537 VerifyStatus = Pkcs7GetSigners (
2538 SigData,
2539 SigDataSize,
2540 &SignerCerts,
2541 &CertStackSize,
2542 &TopLevelCert,
2543 &TopLevelCertSize
2544 );
2545 if (!VerifyStatus) {
2546 goto Exit;
2547 }
2548
2549 //
2550 // Get previously stored signer's certificates from certdb or certdbv for existing
2551 // variable. Check whether they are identical with signer's certificates
2552 // in SignedData. If not, return error immediately.
2553 //
2554 if (OrgTimeStamp != NULL) {
2555 VerifyStatus = FALSE;
2556
2557 Status = GetCertsFromDb (VariableName, VendorGuid, Attributes, &CertsInCertDb, &CertsSizeinDb);
2558 if (EFI_ERROR (Status)) {
2559 goto Exit;
2560 }
2561
2562 if (CertsSizeinDb == SHA256_DIGEST_SIZE) {
2563 //
2564 // Check hash of signer cert CommonName + Top-level issuer tbsCertificate against data in CertDb
2565 //
2566 Status = CalculatePrivAuthVarSignChainSHA256Digest(
2567 SignerCerts + sizeof(UINT8) + sizeof(UINT32),
2568 ReadUnaligned32 ((UINT32 *)(SignerCerts + sizeof(UINT8))),
2569 TopLevelCert,
2570 TopLevelCertSize,
2571 Sha256Digest
2572 );
2573 if (EFI_ERROR(Status) || CompareMem (Sha256Digest, CertsInCertDb, CertsSizeinDb) != 0){
2574 goto Exit;
2575 }
2576 } else {
2577 //
2578 // Keep backward compatible with previous solution which saves whole signer certs stack in CertDb
2579 //
2580 if ((CertStackSize != CertsSizeinDb) ||
2581 (CompareMem (SignerCerts, CertsInCertDb, CertsSizeinDb) != 0)) {
2582 goto Exit;
2583 }
2584 }
2585 }
2586
2587 VerifyStatus = Pkcs7Verify (
2588 SigData,
2589 SigDataSize,
2590 TopLevelCert,
2591 TopLevelCertSize,
2592 NewData,
2593 NewDataSize
2594 );
2595 if (!VerifyStatus) {
2596 goto Exit;
2597 }
2598
2599 if ((OrgTimeStamp == NULL) && (PayloadSize != 0)) {
2600 //
2601 // When adding a new common authenticated variable, always save Hash of cn of signer cert + tbsCertificate of Top-level issuer
2602 //
2603 Status = InsertCertsToDb (
2604 VariableName,
2605 VendorGuid,
2606 Attributes,
2607 SignerCerts + sizeof(UINT8) + sizeof(UINT32),
2608 ReadUnaligned32 ((UINT32 *)(SignerCerts + sizeof(UINT8))),
2609 TopLevelCert,
2610 TopLevelCertSize
2611 );
2612 if (EFI_ERROR (Status)) {
2613 VerifyStatus = FALSE;
2614 goto Exit;
2615 }
2616 }
2617 } else if (AuthVarType == AuthVarTypePayload) {
2618 CertList = (EFI_SIGNATURE_LIST *) PayloadPtr;
2619 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2620 TrustedCert = Cert->SignatureData;
2621 TrustedCertSize = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);
2622 //
2623 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2624 //
2625 VerifyStatus = Pkcs7Verify (
2626 SigData,
2627 SigDataSize,
2628 TrustedCert,
2629 TrustedCertSize,
2630 NewData,
2631 NewDataSize
2632 );
2633 } else {
2634 return EFI_SECURITY_VIOLATION;
2635 }
2636
2637 Exit:
2638
2639 if (AuthVarType == AuthVarTypePk || AuthVarType == AuthVarTypePriv) {
2640 Pkcs7FreeSigners (TopLevelCert);
2641 Pkcs7FreeSigners (SignerCerts);
2642 }
2643
2644 if (!VerifyStatus) {
2645 return EFI_SECURITY_VIOLATION;
2646 }
2647
2648 Status = CheckSignatureListFormat(VariableName, VendorGuid, PayloadPtr, PayloadSize);
2649 if (EFI_ERROR (Status)) {
2650 return Status;
2651 }
2652
2653 *VarPayloadPtr = PayloadPtr;
2654 *VarPayloadSize = PayloadSize;
2655
2656 return EFI_SUCCESS;
2657 }
2658
2659 /**
2660 Process variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS set
2661
2662 Caution: This function may receive untrusted input.
2663 This function may be invoked in SMM mode, and datasize and data are external input.
2664 This function will do basic validation, before parse the data.
2665 This function will parse the authentication carefully to avoid security issues, like
2666 buffer overflow, integer overflow.
2667
2668 @param[in] VariableName Name of Variable to be found.
2669 @param[in] VendorGuid Variable vendor GUID.
2670 @param[in] Data Data pointer.
2671 @param[in] DataSize Size of Data found. If size is less than the
2672 data, this value contains the required size.
2673 @param[in] Attributes Attribute value of the variable.
2674 @param[in] AuthVarType Verify against PK, KEK database, private database or certificate in data payload.
2675 @param[out] VarDel Delete the variable or not.
2676
2677 @retval EFI_INVALID_PARAMETER Invalid parameter.
2678 @retval EFI_SECURITY_VIOLATION The variable does NOT pass the validation
2679 check carried out by the firmware.
2680 @retval EFI_OUT_OF_RESOURCES Failed to process variable due to lack
2681 of resources.
2682 @retval EFI_SUCCESS Variable pass validation successfully.
2683
2684 **/
2685 EFI_STATUS
2686 VerifyTimeBasedPayloadAndUpdate (
2687 IN CHAR16 *VariableName,
2688 IN EFI_GUID *VendorGuid,
2689 IN VOID *Data,
2690 IN UINTN DataSize,
2691 IN UINT32 Attributes,
2692 IN AUTHVAR_TYPE AuthVarType,
2693 OUT BOOLEAN *VarDel
2694 )
2695 {
2696 EFI_STATUS Status;
2697 EFI_STATUS FindStatus;
2698 UINT8 *PayloadPtr;
2699 UINTN PayloadSize;
2700 EFI_VARIABLE_AUTHENTICATION_2 *CertData;
2701 AUTH_VARIABLE_INFO OrgVariableInfo;
2702 BOOLEAN IsDel;
2703
2704 ZeroMem (&OrgVariableInfo, sizeof (OrgVariableInfo));
2705 FindStatus = mAuthVarLibContextIn->FindVariable (
2706 VariableName,
2707 VendorGuid,
2708 &OrgVariableInfo
2709 );
2710
2711 Status = VerifyTimeBasedPayload (
2712 VariableName,
2713 VendorGuid,
2714 Data,
2715 DataSize,
2716 Attributes,
2717 AuthVarType,
2718 (!EFI_ERROR (FindStatus)) ? OrgVariableInfo.TimeStamp : NULL,
2719 &PayloadPtr,
2720 &PayloadSize
2721 );
2722 if (EFI_ERROR (Status)) {
2723 return Status;
2724 }
2725
2726 if (!EFI_ERROR(FindStatus)
2727 && (PayloadSize == 0)
2728 && ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0)) {
2729 IsDel = TRUE;
2730 } else {
2731 IsDel = FALSE;
2732 }
2733
2734 CertData = (EFI_VARIABLE_AUTHENTICATION_2 *) Data;
2735
2736 //
2737 // Final step: Update/Append Variable if it pass Pkcs7Verify
2738 //
2739 Status = AuthServiceInternalUpdateVariableWithTimeStamp (
2740 VariableName,
2741 VendorGuid,
2742 PayloadPtr,
2743 PayloadSize,
2744 Attributes,
2745 &CertData->TimeStamp
2746 );
2747
2748 //
2749 // Delete signer's certificates when delete the common authenticated variable.
2750 //
2751 if (IsDel && AuthVarType == AuthVarTypePriv && !EFI_ERROR(Status) ) {
2752 Status = DeleteCertsFromDb (VariableName, VendorGuid, Attributes);
2753 }
2754
2755 if (VarDel != NULL) {
2756 if (IsDel && !EFI_ERROR(Status)) {
2757 *VarDel = TRUE;
2758 } else {
2759 *VarDel = FALSE;
2760 }
2761 }
2762
2763 return Status;
2764 }