]> git.proxmox.com Git - mirror_edk2.git/blob - SecurityPkg/VariableAuthenticated/RuntimeDxe/AuthService.c
1. Set the secure boot state to Standard Mode when user leaving secure boot setup...
[mirror_edk2.git] / SecurityPkg / VariableAuthenticated / RuntimeDxe / AuthService.c
1 /** @file
2 Implement authentication services for the authenticated variable
3 service in UEFI2.2.
4
5 Caution: This module requires additional review when modified.
6 This driver will have external input - variable data. It may be input in SMM mode.
7 This external input must be validated carefully to avoid security issue like
8 buffer overflow, integer overflow.
9 Variable attribute should also be checked to avoid authentication bypass.
10
11 ProcessVarWithPk(), ProcessVarWithKek() and ProcessVariable() are the function to do
12 variable authentication.
13
14 VerifyTimeBasedPayload() and VerifyCounterBasedPayload() are sub function to do verification.
15 They will do basic validation for authentication data structure, then call crypto library
16 to verify the signature.
17
18 Copyright (c) 2009 - 2013, Intel Corporation. All rights reserved.<BR>
19 This program and the accompanying materials
20 are licensed and made available under the terms and conditions of the BSD License
21 which accompanies this distribution. The full text of the license may be found at
22 http://opensource.org/licenses/bsd-license.php
23
24 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
25 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
26
27 **/
28
29 #include "Variable.h"
30 #include "AuthService.h"
31
32 ///
33 /// Global database array for scratch
34 ///
35 UINT8 mPubKeyStore[MAX_KEYDB_SIZE];
36 UINT32 mPubKeyNumber;
37 UINT8 mCertDbStore[MAX_CERTDB_SIZE];
38 UINT32 mPlatformMode;
39 EFI_GUID mSignatureSupport[] = {EFI_CERT_SHA1_GUID, EFI_CERT_SHA256_GUID, EFI_CERT_RSA2048_GUID, EFI_CERT_X509_GUID};
40 //
41 // Public Exponent of RSA Key.
42 //
43 CONST UINT8 mRsaE[] = { 0x01, 0x00, 0x01 };
44 //
45 // Hash context pointer
46 //
47 VOID *mHashCtx = NULL;
48
49 //
50 // Pointer to runtime buffer.
51 // For "Append" operation to an existing variable, a read/modify/write operation
52 // is supported by firmware internally. Reserve runtime buffer to cache previous
53 // variable data in runtime phase because memory allocation is forbidden in virtual mode.
54 //
55 VOID *mStorageArea = NULL;
56
57 //
58 // The serialization of the values of the VariableName, VendorGuid and Attributes
59 // parameters of the SetVariable() call and the TimeStamp component of the
60 // EFI_VARIABLE_AUTHENTICATION_2 descriptor followed by the variable's new value
61 // i.e. (VariableName, VendorGuid, Attributes, TimeStamp, Data)
62 //
63 UINT8 *mSerializationRuntimeBuffer = NULL;
64
65 //
66 // Requirement for different signature type which have been defined in UEFI spec.
67 // These data are used to peform SignatureList format check while setting PK/KEK variable.
68 //
69 EFI_SIGNATURE_ITEM mSupportSigItem[] = {
70 //{SigType, SigHeaderSize, SigDataSize }
71 {EFI_CERT_SHA256_GUID, 0, 32 },
72 {EFI_CERT_RSA2048_GUID, 0, 256 },
73 {EFI_CERT_RSA2048_SHA256_GUID, 0, 256 },
74 {EFI_CERT_SHA1_GUID, 0, 20 },
75 {EFI_CERT_RSA2048_SHA1_GUID, 0, 256 },
76 {EFI_CERT_X509_GUID, 0, ((UINT32) ~0)},
77 {EFI_CERT_SHA224_GUID, 0, 28 },
78 {EFI_CERT_SHA384_GUID, 0, 48 },
79 {EFI_CERT_SHA512_GUID, 0, 64 }
80 };
81
82 /**
83 Determine whether this operation needs a physical present user.
84
85 @param[in] VariableName Name of the Variable.
86 @param[in] VendorGuid GUID of the Variable.
87
88 @retval TRUE This variable is protected, only a physical present user could set this variable.
89 @retval FALSE This variable is not protected.
90
91 **/
92 BOOLEAN
93 NeedPhysicallyPresent(
94 IN CHAR16 *VariableName,
95 IN EFI_GUID *VendorGuid
96 )
97 {
98 if ((CompareGuid (VendorGuid, &gEfiSecureBootEnableDisableGuid) && (StrCmp (VariableName, EFI_SECURE_BOOT_ENABLE_NAME) == 0))
99 || (CompareGuid (VendorGuid, &gEfiCustomModeEnableGuid) && (StrCmp (VariableName, EFI_CUSTOM_MODE_NAME) == 0))) {
100 return TRUE;
101 }
102
103 return FALSE;
104 }
105
106 /**
107 Determine whether the platform is operating in Custom Secure Boot mode.
108
109 @retval TRUE The platform is operating in Custom mode.
110 @retval FALSE The platform is operating in Standard mode.
111
112 **/
113 BOOLEAN
114 InCustomMode (
115 VOID
116 )
117 {
118 VARIABLE_POINTER_TRACK Variable;
119
120 FindVariable (EFI_CUSTOM_MODE_NAME, &gEfiCustomModeEnableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
121 if (Variable.CurrPtr != NULL && *(GetVariableDataPtr (Variable.CurrPtr)) == CUSTOM_SECURE_BOOT_MODE) {
122 return TRUE;
123 }
124
125 return FALSE;
126 }
127
128
129 /**
130 Internal function to delete a Variable given its name and GUID, no authentication
131 required.
132
133 @param[in] VariableName Name of the Variable.
134 @param[in] VendorGuid GUID of the Variable.
135
136 @retval EFI_SUCCESS Variable deleted successfully.
137 @retval Others The driver failded to start the device.
138
139 **/
140 EFI_STATUS
141 DeleteVariable (
142 IN CHAR16 *VariableName,
143 IN EFI_GUID *VendorGuid
144 )
145 {
146 EFI_STATUS Status;
147 VARIABLE_POINTER_TRACK Variable;
148
149 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
150 if (EFI_ERROR (Status)) {
151 return EFI_SUCCESS;
152 }
153
154 ASSERT (Variable.CurrPtr != NULL);
155 return UpdateVariable (VariableName, VendorGuid, NULL, 0, 0, 0, 0, &Variable, NULL);
156 }
157
158 /**
159 Initializes for authenticated varibale service.
160
161 @retval EFI_SUCCESS Function successfully executed.
162 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resources.
163
164 **/
165 EFI_STATUS
166 AutenticatedVariableServiceInitialize (
167 VOID
168 )
169 {
170 EFI_STATUS Status;
171 VARIABLE_POINTER_TRACK Variable;
172 VARIABLE_POINTER_TRACK PkVariable;
173 UINT8 VarValue;
174 UINT32 VarAttr;
175 UINT8 *Data;
176 UINTN DataSize;
177 UINTN CtxSize;
178 UINT8 SecureBootMode;
179 UINT8 SecureBootEnable;
180 UINT8 CustomMode;
181 UINT32 ListSize;
182
183 //
184 // Initialize hash context.
185 //
186 CtxSize = Sha256GetContextSize ();
187 mHashCtx = AllocateRuntimePool (CtxSize);
188 if (mHashCtx == NULL) {
189 return EFI_OUT_OF_RESOURCES;
190 }
191
192 //
193 // Reserved runtime buffer for "Append" operation in virtual mode.
194 //
195 mStorageArea = AllocateRuntimePool (PcdGet32 (PcdMaxVariableSize));
196 if (mStorageArea == NULL) {
197 return EFI_OUT_OF_RESOURCES;
198 }
199
200 //
201 // Prepare runtime buffer for serialized data of time-based authenticated
202 // Variable, i.e. (VariableName, VendorGuid, Attributes, TimeStamp, Data).
203 //
204 mSerializationRuntimeBuffer = AllocateRuntimePool (PcdGet32 (PcdMaxVariableSize) + sizeof (EFI_GUID) + sizeof (UINT32) + sizeof (EFI_TIME));
205 if (mSerializationRuntimeBuffer == NULL) {
206 return EFI_OUT_OF_RESOURCES;
207 }
208
209 //
210 // Check "AuthVarKeyDatabase" variable's existence.
211 // If it doesn't exist, create a new one with initial value of 0 and EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS set.
212 //
213 Status = FindVariable (
214 AUTHVAR_KEYDB_NAME,
215 &gEfiAuthenticatedVariableGuid,
216 &Variable,
217 &mVariableModuleGlobal->VariableGlobal,
218 FALSE
219 );
220
221 if (Variable.CurrPtr == NULL) {
222 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS;
223 VarValue = 0;
224 mPubKeyNumber = 0;
225 Status = UpdateVariable (
226 AUTHVAR_KEYDB_NAME,
227 &gEfiAuthenticatedVariableGuid,
228 &VarValue,
229 sizeof(UINT8),
230 VarAttr,
231 0,
232 0,
233 &Variable,
234 NULL
235 );
236 if (EFI_ERROR (Status)) {
237 return Status;
238 }
239 } else {
240 //
241 // Load database in global variable for cache.
242 //
243 DataSize = DataSizeOfVariable (Variable.CurrPtr);
244 Data = GetVariableDataPtr (Variable.CurrPtr);
245 ASSERT ((DataSize != 0) && (Data != NULL));
246 CopyMem (mPubKeyStore, (UINT8 *) Data, DataSize);
247 mPubKeyNumber = (UINT32) (DataSize / EFI_CERT_TYPE_RSA2048_SIZE);
248 }
249
250 FindVariable (EFI_PLATFORM_KEY_NAME, &gEfiGlobalVariableGuid, &PkVariable, &mVariableModuleGlobal->VariableGlobal, FALSE);
251 if (PkVariable.CurrPtr == NULL) {
252 DEBUG ((EFI_D_INFO, "Variable %s does not exist.\n", EFI_PLATFORM_KEY_NAME));
253 } else {
254 DEBUG ((EFI_D_INFO, "Variable %s exists.\n", EFI_PLATFORM_KEY_NAME));
255 }
256
257 //
258 // Create "SetupMode" varable with BS+RT attribute set.
259 //
260 FindVariable (EFI_SETUP_MODE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
261 if (PkVariable.CurrPtr == NULL) {
262 mPlatformMode = SETUP_MODE;
263 } else {
264 mPlatformMode = USER_MODE;
265 }
266 Status = UpdateVariable (
267 EFI_SETUP_MODE_NAME,
268 &gEfiGlobalVariableGuid,
269 &mPlatformMode,
270 sizeof(UINT8),
271 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
272 0,
273 0,
274 &Variable,
275 NULL
276 );
277 if (EFI_ERROR (Status)) {
278 return Status;
279 }
280
281 //
282 // Create "SignatureSupport" varable with BS+RT attribute set.
283 //
284 FindVariable (EFI_SIGNATURE_SUPPORT_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
285 Status = UpdateVariable (
286 EFI_SIGNATURE_SUPPORT_NAME,
287 &gEfiGlobalVariableGuid,
288 mSignatureSupport,
289 sizeof(mSignatureSupport),
290 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
291 0,
292 0,
293 &Variable,
294 NULL
295 );
296 if (EFI_ERROR (Status)) {
297 return Status;
298 }
299
300 //
301 // If "SecureBootEnable" variable exists, then update "SecureBoot" variable.
302 // If "SecureBootEnable" variable is SECURE_BOOT_ENABLE and in USER_MODE, Set "SecureBoot" variable to SECURE_BOOT_MODE_ENABLE.
303 // If "SecureBootEnable" variable is SECURE_BOOT_DISABLE, Set "SecureBoot" variable to SECURE_BOOT_MODE_DISABLE.
304 //
305 SecureBootEnable = SECURE_BOOT_DISABLE;
306 FindVariable (EFI_SECURE_BOOT_ENABLE_NAME, &gEfiSecureBootEnableDisableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
307 if (Variable.CurrPtr != NULL) {
308 SecureBootEnable = *(GetVariableDataPtr (Variable.CurrPtr));
309 } else if (mPlatformMode == USER_MODE) {
310 //
311 // "SecureBootEnable" not exist, initialize it in USER_MODE.
312 //
313 SecureBootEnable = SECURE_BOOT_ENABLE;
314 Status = UpdateVariable (
315 EFI_SECURE_BOOT_ENABLE_NAME,
316 &gEfiSecureBootEnableDisableGuid,
317 &SecureBootEnable,
318 sizeof (UINT8),
319 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
320 0,
321 0,
322 &Variable,
323 NULL
324 );
325 if (EFI_ERROR (Status)) {
326 return Status;
327 }
328 }
329
330 //
331 // Create "SecureBoot" varable with BS+RT attribute set.
332 //
333 if (SecureBootEnable == SECURE_BOOT_ENABLE && mPlatformMode == USER_MODE) {
334 SecureBootMode = SECURE_BOOT_MODE_ENABLE;
335 } else {
336 SecureBootMode = SECURE_BOOT_MODE_DISABLE;
337 }
338 FindVariable (EFI_SECURE_BOOT_MODE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
339 Status = UpdateVariable (
340 EFI_SECURE_BOOT_MODE_NAME,
341 &gEfiGlobalVariableGuid,
342 &SecureBootMode,
343 sizeof (UINT8),
344 EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS,
345 0,
346 0,
347 &Variable,
348 NULL
349 );
350 if (EFI_ERROR (Status)) {
351 return Status;
352 }
353
354 DEBUG ((EFI_D_INFO, "Variable %s is %x\n", EFI_SETUP_MODE_NAME, mPlatformMode));
355 DEBUG ((EFI_D_INFO, "Variable %s is %x\n", EFI_SECURE_BOOT_MODE_NAME, SecureBootMode));
356 DEBUG ((EFI_D_INFO, "Variable %s is %x\n", EFI_SECURE_BOOT_ENABLE_NAME, SecureBootEnable));
357
358 //
359 // Initialize "CustomMode" in STANDARD_SECURE_BOOT_MODE state.
360 //
361 FindVariable (EFI_CUSTOM_MODE_NAME, &gEfiCustomModeEnableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
362 CustomMode = STANDARD_SECURE_BOOT_MODE;
363 Status = UpdateVariable (
364 EFI_CUSTOM_MODE_NAME,
365 &gEfiCustomModeEnableGuid,
366 &CustomMode,
367 sizeof (UINT8),
368 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
369 0,
370 0,
371 &Variable,
372 NULL
373 );
374 if (EFI_ERROR (Status)) {
375 return Status;
376 }
377
378 DEBUG ((EFI_D_INFO, "Variable %s is %x\n", EFI_CUSTOM_MODE_NAME, CustomMode));
379
380 //
381 // Check "certdb" variable's existence.
382 // If it doesn't exist, then create a new one with
383 // EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS set.
384 //
385 Status = FindVariable (
386 EFI_CERT_DB_NAME,
387 &gEfiCertDbGuid,
388 &Variable,
389 &mVariableModuleGlobal->VariableGlobal,
390 FALSE
391 );
392
393 if (Variable.CurrPtr == NULL) {
394 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
395 ListSize = sizeof (UINT32);
396 Status = UpdateVariable (
397 EFI_CERT_DB_NAME,
398 &gEfiCertDbGuid,
399 &ListSize,
400 sizeof (UINT32),
401 VarAttr,
402 0,
403 0,
404 &Variable,
405 NULL
406 );
407 if (EFI_ERROR (Status)) {
408 return Status;
409 }
410 }
411
412 return Status;
413 }
414
415 /**
416 Add public key in store and return its index.
417
418 @param[in] PubKey Input pointer to Public Key data
419
420 @return Index of new added item
421
422 **/
423 UINT32
424 AddPubKeyInStore (
425 IN UINT8 *PubKey
426 )
427 {
428 EFI_STATUS Status;
429 BOOLEAN IsFound;
430 UINT32 Index;
431 VARIABLE_POINTER_TRACK Variable;
432 UINT8 *Ptr;
433 UINT8 *Data;
434 UINTN DataSize;
435
436 if (PubKey == NULL) {
437 return 0;
438 }
439
440 Status = FindVariable (
441 AUTHVAR_KEYDB_NAME,
442 &gEfiAuthenticatedVariableGuid,
443 &Variable,
444 &mVariableModuleGlobal->VariableGlobal,
445 FALSE
446 );
447 ASSERT_EFI_ERROR (Status);
448 //
449 // Check whether the public key entry does exist.
450 //
451 IsFound = FALSE;
452 for (Ptr = mPubKeyStore, Index = 1; Index <= mPubKeyNumber; Index++) {
453 if (CompareMem (Ptr, PubKey, EFI_CERT_TYPE_RSA2048_SIZE) == 0) {
454 IsFound = TRUE;
455 break;
456 }
457 Ptr += EFI_CERT_TYPE_RSA2048_SIZE;
458 }
459
460 if (!IsFound) {
461 //
462 // Add public key in database.
463 //
464 if (mPubKeyNumber == MAX_KEY_NUM) {
465 //
466 // Public key dadatase is full, try to reclaim invalid key.
467 //
468 if (AtRuntime ()) {
469 //
470 // NV storage can't reclaim at runtime.
471 //
472 return 0;
473 }
474
475 Status = Reclaim (
476 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
477 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
478 FALSE,
479 NULL,
480 TRUE,
481 TRUE
482 );
483 if (EFI_ERROR (Status)) {
484 return 0;
485 }
486
487 Status = FindVariable (
488 AUTHVAR_KEYDB_NAME,
489 &gEfiAuthenticatedVariableGuid,
490 &Variable,
491 &mVariableModuleGlobal->VariableGlobal,
492 FALSE
493 );
494 ASSERT_EFI_ERROR (Status);
495
496 DataSize = DataSizeOfVariable (Variable.CurrPtr);
497 Data = GetVariableDataPtr (Variable.CurrPtr);
498 ASSERT ((DataSize != 0) && (Data != NULL));
499 CopyMem (mPubKeyStore, (UINT8 *) Data, DataSize);
500 mPubKeyNumber = (UINT32) (DataSize / EFI_CERT_TYPE_RSA2048_SIZE);
501
502 if (mPubKeyNumber == MAX_KEY_NUM) {
503 return 0;
504 }
505 }
506
507 CopyMem (mPubKeyStore + mPubKeyNumber * EFI_CERT_TYPE_RSA2048_SIZE, PubKey, EFI_CERT_TYPE_RSA2048_SIZE);
508 Index = ++mPubKeyNumber;
509 //
510 // Update public key database variable.
511 //
512 Status = UpdateVariable (
513 AUTHVAR_KEYDB_NAME,
514 &gEfiAuthenticatedVariableGuid,
515 mPubKeyStore,
516 mPubKeyNumber * EFI_CERT_TYPE_RSA2048_SIZE,
517 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS,
518 0,
519 0,
520 &Variable,
521 NULL
522 );
523 ASSERT_EFI_ERROR (Status);
524 }
525
526 return Index;
527 }
528
529 /**
530 Verify data payload with AuthInfo in EFI_CERT_TYPE_RSA2048_SHA256_GUID type.
531 Follow the steps in UEFI2.2.
532
533 Caution: This function may receive untrusted input.
534 This function may be invoked in SMM mode, and datasize and data are external input.
535 This function will do basic validation, before parse the data.
536 This function will parse the authentication carefully to avoid security issues, like
537 buffer overflow, integer overflow.
538
539 @param[in] Data Pointer to data with AuthInfo.
540 @param[in] DataSize Size of Data.
541 @param[in] PubKey Public key used for verification.
542
543 @retval EFI_INVALID_PARAMETER Invalid parameter.
544 @retval EFI_SECURITY_VIOLATION If authentication failed.
545 @retval EFI_SUCCESS Authentication successful.
546
547 **/
548 EFI_STATUS
549 VerifyCounterBasedPayload (
550 IN UINT8 *Data,
551 IN UINTN DataSize,
552 IN UINT8 *PubKey
553 )
554 {
555 BOOLEAN Status;
556 EFI_VARIABLE_AUTHENTICATION *CertData;
557 EFI_CERT_BLOCK_RSA_2048_SHA256 *CertBlock;
558 UINT8 Digest[SHA256_DIGEST_SIZE];
559 VOID *Rsa;
560 UINTN PayloadSize;
561
562 PayloadSize = DataSize - AUTHINFO_SIZE;
563 Rsa = NULL;
564 CertData = NULL;
565 CertBlock = NULL;
566
567 if (Data == NULL || PubKey == NULL) {
568 return EFI_INVALID_PARAMETER;
569 }
570
571 CertData = (EFI_VARIABLE_AUTHENTICATION *) Data;
572 CertBlock = (EFI_CERT_BLOCK_RSA_2048_SHA256 *) (CertData->AuthInfo.CertData);
573
574 //
575 // wCertificateType should be WIN_CERT_TYPE_EFI_GUID.
576 // Cert type should be EFI_CERT_TYPE_RSA2048_SHA256_GUID.
577 //
578 if ((CertData->AuthInfo.Hdr.wCertificateType != WIN_CERT_TYPE_EFI_GUID) ||
579 !CompareGuid (&CertData->AuthInfo.CertType, &gEfiCertTypeRsa2048Sha256Guid)
580 ) {
581 //
582 // Invalid AuthInfo type, return EFI_SECURITY_VIOLATION.
583 //
584 return EFI_SECURITY_VIOLATION;
585 }
586 //
587 // Hash data payload with SHA256.
588 //
589 ZeroMem (Digest, SHA256_DIGEST_SIZE);
590 Status = Sha256Init (mHashCtx);
591 if (!Status) {
592 goto Done;
593 }
594 Status = Sha256Update (mHashCtx, Data + AUTHINFO_SIZE, PayloadSize);
595 if (!Status) {
596 goto Done;
597 }
598 //
599 // Hash Size.
600 //
601 Status = Sha256Update (mHashCtx, &PayloadSize, sizeof (UINTN));
602 if (!Status) {
603 goto Done;
604 }
605 //
606 // Hash Monotonic Count.
607 //
608 Status = Sha256Update (mHashCtx, &CertData->MonotonicCount, sizeof (UINT64));
609 if (!Status) {
610 goto Done;
611 }
612 Status = Sha256Final (mHashCtx, Digest);
613 if (!Status) {
614 goto Done;
615 }
616 //
617 // Generate & Initialize RSA Context.
618 //
619 Rsa = RsaNew ();
620 ASSERT (Rsa != NULL);
621 //
622 // Set RSA Key Components.
623 // NOTE: Only N and E are needed to be set as RSA public key for signature verification.
624 //
625 Status = RsaSetKey (Rsa, RsaKeyN, PubKey, EFI_CERT_TYPE_RSA2048_SIZE);
626 if (!Status) {
627 goto Done;
628 }
629 Status = RsaSetKey (Rsa, RsaKeyE, mRsaE, sizeof (mRsaE));
630 if (!Status) {
631 goto Done;
632 }
633 //
634 // Verify the signature.
635 //
636 Status = RsaPkcs1Verify (
637 Rsa,
638 Digest,
639 SHA256_DIGEST_SIZE,
640 CertBlock->Signature,
641 EFI_CERT_TYPE_RSA2048_SHA256_SIZE
642 );
643
644 Done:
645 if (Rsa != NULL) {
646 RsaFree (Rsa);
647 }
648 if (Status) {
649 return EFI_SUCCESS;
650 } else {
651 return EFI_SECURITY_VIOLATION;
652 }
653 }
654
655 /**
656 Update platform mode.
657
658 @param[in] Mode SETUP_MODE or USER_MODE.
659
660 @return EFI_INVALID_PARAMETER Invalid parameter.
661 @return EFI_SUCCESS Update platform mode successfully.
662
663 **/
664 EFI_STATUS
665 UpdatePlatformMode (
666 IN UINT32 Mode
667 )
668 {
669 EFI_STATUS Status;
670 VARIABLE_POINTER_TRACK Variable;
671 UINT32 VarAttr;
672 UINT8 SecureBootMode;
673 UINT8 SecureBootEnable;
674 UINTN VariableDataSize;
675
676 Status = FindVariable (
677 EFI_SETUP_MODE_NAME,
678 &gEfiGlobalVariableGuid,
679 &Variable,
680 &mVariableModuleGlobal->VariableGlobal,
681 FALSE
682 );
683 if (EFI_ERROR (Status)) {
684 return Status;
685 }
686
687 //
688 // Update the value of SetupMode variable by a simple mem copy, this could avoid possible
689 // variable storage reclaim at runtime.
690 //
691 mPlatformMode = (UINT8) Mode;
692 CopyMem (GetVariableDataPtr (Variable.CurrPtr), &mPlatformMode, sizeof(UINT8));
693
694 if (AtRuntime ()) {
695 //
696 // SecureBoot Variable indicates whether the platform firmware is operating
697 // in Secure boot mode (1) or not (0), so we should not change SecureBoot
698 // Variable in runtime.
699 //
700 return Status;
701 }
702
703 //
704 // Check "SecureBoot" variable's existence.
705 // If it doesn't exist, firmware has no capability to perform driver signing verification,
706 // then set "SecureBoot" to 0.
707 //
708 Status = FindVariable (
709 EFI_SECURE_BOOT_MODE_NAME,
710 &gEfiGlobalVariableGuid,
711 &Variable,
712 &mVariableModuleGlobal->VariableGlobal,
713 FALSE
714 );
715 //
716 // If "SecureBoot" variable exists, then check "SetupMode" variable update.
717 // If "SetupMode" variable is USER_MODE, "SecureBoot" variable is set to 1.
718 // If "SetupMode" variable is SETUP_MODE, "SecureBoot" variable is set to 0.
719 //
720 if (Variable.CurrPtr == NULL) {
721 SecureBootMode = SECURE_BOOT_MODE_DISABLE;
722 } else {
723 if (mPlatformMode == USER_MODE) {
724 SecureBootMode = SECURE_BOOT_MODE_ENABLE;
725 } else if (mPlatformMode == SETUP_MODE) {
726 SecureBootMode = SECURE_BOOT_MODE_DISABLE;
727 } else {
728 return EFI_NOT_FOUND;
729 }
730 }
731
732 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS;
733 Status = UpdateVariable (
734 EFI_SECURE_BOOT_MODE_NAME,
735 &gEfiGlobalVariableGuid,
736 &SecureBootMode,
737 sizeof(UINT8),
738 VarAttr,
739 0,
740 0,
741 &Variable,
742 NULL
743 );
744 if (EFI_ERROR (Status)) {
745 return Status;
746 }
747
748 //
749 // Check "SecureBootEnable" variable's existence. It can enable/disable secure boot feature.
750 //
751 Status = FindVariable (
752 EFI_SECURE_BOOT_ENABLE_NAME,
753 &gEfiSecureBootEnableDisableGuid,
754 &Variable,
755 &mVariableModuleGlobal->VariableGlobal,
756 FALSE
757 );
758
759 if (SecureBootMode == SECURE_BOOT_MODE_ENABLE) {
760 //
761 // Create the "SecureBootEnable" variable as secure boot is enabled.
762 //
763 SecureBootEnable = SECURE_BOOT_ENABLE;
764 VariableDataSize = sizeof (SecureBootEnable);
765 } else {
766 //
767 // Delete the "SecureBootEnable" variable if this variable exist as "SecureBoot"
768 // variable is not in secure boot state.
769 //
770 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
771 return EFI_SUCCESS;
772 }
773 SecureBootEnable = SECURE_BOOT_DISABLE;
774 VariableDataSize = 0;
775 }
776
777 Status = UpdateVariable (
778 EFI_SECURE_BOOT_ENABLE_NAME,
779 &gEfiSecureBootEnableDisableGuid,
780 &SecureBootEnable,
781 VariableDataSize,
782 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
783 0,
784 0,
785 &Variable,
786 NULL
787 );
788 return Status;
789 }
790
791 /**
792 Check input data form to make sure it is a valid EFI_SIGNATURE_LIST for PK/KEK/db/dbx variable.
793
794 @param[in] VariableName Name of Variable to be check.
795 @param[in] VendorGuid Variable vendor GUID.
796 @param[in] Data Point to the variable data to be checked.
797 @param[in] DataSize Size of Data.
798
799 @return EFI_INVALID_PARAMETER Invalid signature list format.
800 @return EFI_SUCCESS Passed signature list format check successfully.
801
802 **/
803 EFI_STATUS
804 CheckSignatureListFormat(
805 IN CHAR16 *VariableName,
806 IN EFI_GUID *VendorGuid,
807 IN VOID *Data,
808 IN UINTN DataSize
809 )
810 {
811 EFI_SIGNATURE_LIST *SigList;
812 UINTN SigDataSize;
813 UINT32 Index;
814 UINT32 SigCount;
815 BOOLEAN IsPk;
816 VOID *RsaContext;
817 EFI_SIGNATURE_DATA *CertData;
818 UINTN CertLen;
819
820 if (DataSize == 0) {
821 return EFI_SUCCESS;
822 }
823
824 ASSERT (VariableName != NULL && VendorGuid != NULL && Data != NULL);
825
826 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_PLATFORM_KEY_NAME) == 0)){
827 IsPk = TRUE;
828 } else if ((CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0) ||
829 (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) &&
830 (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0 || StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0))){
831 IsPk = FALSE;
832 } else {
833 return EFI_SUCCESS;
834 }
835
836 SigCount = 0;
837 SigList = (EFI_SIGNATURE_LIST *) Data;
838 SigDataSize = DataSize;
839 RsaContext = NULL;
840
841 //
842 // Walk throuth the input signature list and check the data format.
843 // If any signature is incorrectly formed, the whole check will fail.
844 //
845 while ((SigDataSize > 0) && (SigDataSize >= SigList->SignatureListSize)) {
846 for (Index = 0; Index < (sizeof (mSupportSigItem) / sizeof (EFI_SIGNATURE_ITEM)); Index++ ) {
847 if (CompareGuid (&SigList->SignatureType, &mSupportSigItem[Index].SigType)) {
848 //
849 // The value of SignatureSize should always be 16 (size of SignatureOwner
850 // component) add the data length according to signature type.
851 //
852 if (mSupportSigItem[Index].SigDataSize != ((UINT32) ~0) &&
853 (SigList->SignatureSize - sizeof (EFI_GUID)) != mSupportSigItem[Index].SigDataSize) {
854 return EFI_INVALID_PARAMETER;
855 }
856 if (mSupportSigItem[Index].SigHeaderSize != ((UINTN) ~0) &&
857 SigList->SignatureHeaderSize != mSupportSigItem[Index].SigHeaderSize) {
858 return EFI_INVALID_PARAMETER;
859 }
860 break;
861 }
862 }
863
864 if (Index == (sizeof (mSupportSigItem) / sizeof (EFI_SIGNATURE_ITEM))) {
865 //
866 // Undefined signature type.
867 //
868 return EFI_INVALID_PARAMETER;
869 }
870
871 if (CompareGuid (&SigList->SignatureType, &gEfiCertX509Guid)) {
872 //
873 // Try to retrieve the RSA public key from the X.509 certificate.
874 // If this operation fails, it's not a valid certificate.
875 //
876 RsaContext = RsaNew ();
877 if (RsaContext == NULL) {
878 return EFI_INVALID_PARAMETER;
879 }
880 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) SigList + sizeof (EFI_SIGNATURE_LIST) + SigList->SignatureHeaderSize);
881 CertLen = SigList->SignatureSize - sizeof (EFI_GUID);
882 if (!RsaGetPublicKeyFromX509 (CertData->SignatureData, CertLen, &RsaContext)) {
883 RsaFree (RsaContext);
884 return EFI_INVALID_PARAMETER;
885 }
886 RsaFree (RsaContext);
887 }
888
889 if ((SigList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - SigList->SignatureHeaderSize) % SigList->SignatureSize != 0) {
890 return EFI_INVALID_PARAMETER;
891 }
892 SigCount += (SigList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - SigList->SignatureHeaderSize) / SigList->SignatureSize;
893
894 SigDataSize -= SigList->SignatureListSize;
895 SigList = (EFI_SIGNATURE_LIST *) ((UINT8 *) SigList + SigList->SignatureListSize);
896 }
897
898 if (((UINTN) SigList - (UINTN) Data) != DataSize) {
899 return EFI_INVALID_PARAMETER;
900 }
901
902 if (IsPk && SigCount > 1) {
903 return EFI_INVALID_PARAMETER;
904 }
905
906 return EFI_SUCCESS;
907 }
908
909 /**
910 Process variable with platform key for verification.
911
912 Caution: This function may receive untrusted input.
913 This function may be invoked in SMM mode, and datasize and data are external input.
914 This function will do basic validation, before parse the data.
915 This function will parse the authentication carefully to avoid security issues, like
916 buffer overflow, integer overflow.
917 This function will check attribute carefully to avoid authentication bypass.
918
919 @param[in] VariableName Name of Variable to be found.
920 @param[in] VendorGuid Variable vendor GUID.
921 @param[in] Data Data pointer.
922 @param[in] DataSize Size of Data found. If size is less than the
923 data, this value contains the required size.
924 @param[in] Variable The variable information which is used to keep track of variable usage.
925 @param[in] Attributes Attribute value of the variable
926 @param[in] IsPk Indicate whether it is to process pk.
927
928 @return EFI_INVALID_PARAMETER Invalid parameter.
929 @return EFI_SECURITY_VIOLATION The variable does NOT pass the validation.
930 check carried out by the firmware.
931 @return EFI_SUCCESS Variable passed validation successfully.
932
933 **/
934 EFI_STATUS
935 ProcessVarWithPk (
936 IN CHAR16 *VariableName,
937 IN EFI_GUID *VendorGuid,
938 IN VOID *Data,
939 IN UINTN DataSize,
940 IN VARIABLE_POINTER_TRACK *Variable,
941 IN UINT32 Attributes OPTIONAL,
942 IN BOOLEAN IsPk
943 )
944 {
945 EFI_STATUS Status;
946 BOOLEAN Del;
947 UINT8 *Payload;
948 UINTN PayloadSize;
949
950 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0 ||
951 (Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == 0) {
952 //
953 // PK, KEK and db/dbx should set EFI_VARIABLE_NON_VOLATILE attribute and should be a time-based
954 // authenticated variable.
955 //
956 return EFI_INVALID_PARAMETER;
957 }
958
959 Del = FALSE;
960 if ((InCustomMode() && UserPhysicalPresent()) || (mPlatformMode == SETUP_MODE && !IsPk)) {
961 Payload = (UINT8 *) Data + AUTHINFO2_SIZE (Data);
962 PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
963 if (PayloadSize == 0) {
964 Del = TRUE;
965 }
966
967 Status = CheckSignatureListFormat(VariableName, VendorGuid, Payload, PayloadSize);
968 if (EFI_ERROR (Status)) {
969 return Status;
970 }
971
972 Status = UpdateVariable (
973 VariableName,
974 VendorGuid,
975 Payload,
976 PayloadSize,
977 Attributes,
978 0,
979 0,
980 Variable,
981 &((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->TimeStamp
982 );
983 } else if (mPlatformMode == USER_MODE) {
984 //
985 // Verify against X509 Cert in PK database.
986 //
987 Status = VerifyTimeBasedPayload (
988 VariableName,
989 VendorGuid,
990 Data,
991 DataSize,
992 Variable,
993 Attributes,
994 AuthVarTypePk,
995 &Del
996 );
997 } else {
998 //
999 // Verify against the certificate in data payload.
1000 //
1001 Status = VerifyTimeBasedPayload (
1002 VariableName,
1003 VendorGuid,
1004 Data,
1005 DataSize,
1006 Variable,
1007 Attributes,
1008 AuthVarTypePayload,
1009 &Del
1010 );
1011 }
1012
1013 if (!EFI_ERROR(Status) && IsPk) {
1014 if (mPlatformMode == SETUP_MODE && !Del) {
1015 //
1016 // If enroll PK in setup mode, need change to user mode.
1017 //
1018 Status = UpdatePlatformMode (USER_MODE);
1019 } else if (mPlatformMode == USER_MODE && Del){
1020 //
1021 // If delete PK in user mode, need change to setup mode.
1022 //
1023 Status = UpdatePlatformMode (SETUP_MODE);
1024 }
1025 }
1026
1027 return Status;
1028 }
1029
1030 /**
1031 Process variable with key exchange key for verification.
1032
1033 Caution: This function may receive untrusted input.
1034 This function may be invoked in SMM mode, and datasize and data are external input.
1035 This function will do basic validation, before parse the data.
1036 This function will parse the authentication carefully to avoid security issues, like
1037 buffer overflow, integer overflow.
1038 This function will check attribute carefully to avoid authentication bypass.
1039
1040 @param[in] VariableName Name of Variable to be found.
1041 @param[in] VendorGuid Variable vendor GUID.
1042 @param[in] Data Data pointer.
1043 @param[in] DataSize Size of Data found. If size is less than the
1044 data, this value contains the required size.
1045 @param[in] Variable The variable information which is used to keep track of variable usage.
1046 @param[in] Attributes Attribute value of the variable.
1047
1048 @return EFI_INVALID_PARAMETER Invalid parameter.
1049 @return EFI_SECURITY_VIOLATION The variable does NOT pass the validation
1050 check carried out by the firmware.
1051 @return EFI_SUCCESS Variable pass validation successfully.
1052
1053 **/
1054 EFI_STATUS
1055 ProcessVarWithKek (
1056 IN CHAR16 *VariableName,
1057 IN EFI_GUID *VendorGuid,
1058 IN VOID *Data,
1059 IN UINTN DataSize,
1060 IN VARIABLE_POINTER_TRACK *Variable,
1061 IN UINT32 Attributes OPTIONAL
1062 )
1063 {
1064 EFI_STATUS Status;
1065 UINT8 *Payload;
1066 UINTN PayloadSize;
1067
1068 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0 ||
1069 (Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == 0) {
1070 //
1071 // DB and DBX should set EFI_VARIABLE_NON_VOLATILE attribute and should be a time-based
1072 // authenticated variable.
1073 //
1074 return EFI_INVALID_PARAMETER;
1075 }
1076
1077 Status = EFI_SUCCESS;
1078 if (mPlatformMode == USER_MODE && !(InCustomMode() && UserPhysicalPresent())) {
1079 //
1080 // Time-based, verify against X509 Cert KEK.
1081 //
1082 return VerifyTimeBasedPayload (
1083 VariableName,
1084 VendorGuid,
1085 Data,
1086 DataSize,
1087 Variable,
1088 Attributes,
1089 AuthVarTypeKek,
1090 NULL
1091 );
1092 } else {
1093 //
1094 // If in setup mode or custom secure boot mode, no authentication needed.
1095 //
1096 Payload = (UINT8 *) Data + AUTHINFO2_SIZE (Data);
1097 PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
1098
1099 Status = CheckSignatureListFormat(VariableName, VendorGuid, Payload, PayloadSize);
1100 if (EFI_ERROR (Status)) {
1101 return Status;
1102 }
1103
1104 Status = UpdateVariable (
1105 VariableName,
1106 VendorGuid,
1107 Payload,
1108 PayloadSize,
1109 Attributes,
1110 0,
1111 0,
1112 Variable,
1113 &((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->TimeStamp
1114 );
1115 }
1116
1117 return Status;
1118 }
1119
1120 /**
1121 Process variable with EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS/EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS set
1122
1123 Caution: This function may receive untrusted input.
1124 This function may be invoked in SMM mode, and datasize and data are external input.
1125 This function will do basic validation, before parse the data.
1126 This function will parse the authentication carefully to avoid security issues, like
1127 buffer overflow, integer overflow.
1128 This function will check attribute carefully to avoid authentication bypass.
1129
1130 @param[in] VariableName Name of Variable to be found.
1131 @param[in] VendorGuid Variable vendor GUID.
1132
1133 @param[in] Data Data pointer.
1134 @param[in] DataSize Size of Data found. If size is less than the
1135 data, this value contains the required size.
1136 @param[in] Variable The variable information which is used to keep track of variable usage.
1137 @param[in] Attributes Attribute value of the variable.
1138
1139 @return EFI_INVALID_PARAMETER Invalid parameter.
1140 @return EFI_WRITE_PROTECTED Variable is write-protected and needs authentication with
1141 EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS set.
1142 @return EFI_OUT_OF_RESOURCES The Database to save the public key is full.
1143 @return EFI_SECURITY_VIOLATION The variable is with EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
1144 set, but the AuthInfo does NOT pass the validation
1145 check carried out by the firmware.
1146 @return EFI_SUCCESS Variable is not write-protected or pass validation successfully.
1147
1148 **/
1149 EFI_STATUS
1150 ProcessVariable (
1151 IN CHAR16 *VariableName,
1152 IN EFI_GUID *VendorGuid,
1153 IN VOID *Data,
1154 IN UINTN DataSize,
1155 IN VARIABLE_POINTER_TRACK *Variable,
1156 IN UINT32 Attributes
1157 )
1158 {
1159 EFI_STATUS Status;
1160 BOOLEAN IsDeletion;
1161 BOOLEAN IsFirstTime;
1162 UINT8 *PubKey;
1163 EFI_VARIABLE_AUTHENTICATION *CertData;
1164 EFI_CERT_BLOCK_RSA_2048_SHA256 *CertBlock;
1165 UINT32 KeyIndex;
1166 UINT64 MonotonicCount;
1167
1168 KeyIndex = 0;
1169 CertData = NULL;
1170 CertBlock = NULL;
1171 PubKey = NULL;
1172 IsDeletion = FALSE;
1173
1174 if (NeedPhysicallyPresent(VariableName, VendorGuid) && !UserPhysicalPresent()) {
1175 //
1176 // This variable is protected, only physical present user could modify its value.
1177 //
1178 return EFI_SECURITY_VIOLATION;
1179 }
1180
1181 //
1182 // A time-based authenticated variable and a count-based authenticated variable
1183 // can't be updated by each other.
1184 //
1185 if (Variable->CurrPtr != NULL) {
1186 if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) &&
1187 ((Variable->CurrPtr->Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0)) {
1188 return EFI_SECURITY_VIOLATION;
1189 }
1190
1191 if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) &&
1192 ((Variable->CurrPtr->Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0)) {
1193 return EFI_SECURITY_VIOLATION;
1194 }
1195 }
1196
1197 //
1198 // Process Time-based Authenticated variable.
1199 //
1200 if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) {
1201 return VerifyTimeBasedPayload (
1202 VariableName,
1203 VendorGuid,
1204 Data,
1205 DataSize,
1206 Variable,
1207 Attributes,
1208 AuthVarTypePriv,
1209 NULL
1210 );
1211 }
1212
1213 //
1214 // Determine if first time SetVariable with the EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS.
1215 //
1216 if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) {
1217 //
1218 // Determine current operation type.
1219 //
1220 if (DataSize == AUTHINFO_SIZE) {
1221 IsDeletion = TRUE;
1222 }
1223 //
1224 // Determine whether this is the first time with EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS set.
1225 //
1226 if (Variable->CurrPtr == NULL) {
1227 IsFirstTime = TRUE;
1228 } else if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == 0) {
1229 IsFirstTime = TRUE;
1230 } else {
1231 KeyIndex = Variable->CurrPtr->PubKeyIndex;
1232 IsFirstTime = FALSE;
1233 }
1234 } else if ((Variable->CurrPtr != NULL) &&
1235 ((Variable->CurrPtr->Attributes & (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) != 0)
1236 ) {
1237 //
1238 // If the variable is already write-protected, it always needs authentication before update.
1239 //
1240 return EFI_WRITE_PROTECTED;
1241 } else {
1242 //
1243 // If without EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS, set and attributes collision.
1244 // That means it is not authenticated variable, just update variable as usual.
1245 //
1246 Status = UpdateVariable (VariableName, VendorGuid, Data, DataSize, Attributes, 0, 0, Variable, NULL);
1247 return Status;
1248 }
1249
1250 //
1251 // Get PubKey and check Monotonic Count value corresponding to the variable.
1252 //
1253 CertData = (EFI_VARIABLE_AUTHENTICATION *) Data;
1254 CertBlock = (EFI_CERT_BLOCK_RSA_2048_SHA256 *) (CertData->AuthInfo.CertData);
1255 PubKey = CertBlock->PublicKey;
1256
1257 //
1258 // Update Monotonic Count value.
1259 //
1260 MonotonicCount = CertData->MonotonicCount;
1261
1262 if (!IsFirstTime) {
1263 //
1264 // Check input PubKey.
1265 //
1266 if (CompareMem (PubKey, mPubKeyStore + (KeyIndex - 1) * EFI_CERT_TYPE_RSA2048_SIZE, EFI_CERT_TYPE_RSA2048_SIZE) != 0) {
1267 return EFI_SECURITY_VIOLATION;
1268 }
1269 //
1270 // Compare the current monotonic count and ensure that it is greater than the last SetVariable
1271 // operation with the EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS attribute set.
1272 //
1273 if (CertData->MonotonicCount <= Variable->CurrPtr->MonotonicCount) {
1274 //
1275 // Monotonic count check fail, suspicious replay attack, return EFI_SECURITY_VIOLATION.
1276 //
1277 return EFI_SECURITY_VIOLATION;
1278 }
1279 }
1280 //
1281 // Verify the certificate in Data payload.
1282 //
1283 Status = VerifyCounterBasedPayload (Data, DataSize, PubKey);
1284 if (EFI_ERROR (Status)) {
1285 return Status;
1286 }
1287
1288 //
1289 // Now, the signature has been verified!
1290 //
1291 if (IsFirstTime && !IsDeletion) {
1292 //
1293 // Update public key database variable if need.
1294 //
1295 KeyIndex = AddPubKeyInStore (PubKey);
1296 if (KeyIndex == 0) {
1297 return EFI_OUT_OF_RESOURCES;
1298 }
1299 }
1300
1301 //
1302 // Verification pass.
1303 //
1304 return UpdateVariable (VariableName, VendorGuid, (UINT8*)Data + AUTHINFO_SIZE, DataSize - AUTHINFO_SIZE, Attributes, KeyIndex, MonotonicCount, Variable, NULL);
1305 }
1306
1307 /**
1308 Merge two buffers which formatted as EFI_SIGNATURE_LIST. Only the new EFI_SIGNATURE_DATA
1309 will be appended to the original EFI_SIGNATURE_LIST, duplicate EFI_SIGNATURE_DATA
1310 will be ignored.
1311
1312 @param[in, out] Data Pointer to original EFI_SIGNATURE_LIST.
1313 @param[in] DataSize Size of Data buffer.
1314 @param[in] NewData Pointer to new EFI_SIGNATURE_LIST to be appended.
1315 @param[in] NewDataSize Size of NewData buffer.
1316
1317 @return Size of the merged buffer.
1318
1319 **/
1320 UINTN
1321 AppendSignatureList (
1322 IN OUT VOID *Data,
1323 IN UINTN DataSize,
1324 IN VOID *NewData,
1325 IN UINTN NewDataSize
1326 )
1327 {
1328 EFI_SIGNATURE_LIST *CertList;
1329 EFI_SIGNATURE_DATA *Cert;
1330 UINTN CertCount;
1331 EFI_SIGNATURE_LIST *NewCertList;
1332 EFI_SIGNATURE_DATA *NewCert;
1333 UINTN NewCertCount;
1334 UINTN Index;
1335 UINTN Index2;
1336 UINTN Size;
1337 UINT8 *Tail;
1338 UINTN CopiedCount;
1339 UINTN SignatureListSize;
1340 BOOLEAN IsNewCert;
1341
1342 Tail = (UINT8 *) Data + DataSize;
1343
1344 NewCertList = (EFI_SIGNATURE_LIST *) NewData;
1345 while ((NewDataSize > 0) && (NewDataSize >= NewCertList->SignatureListSize)) {
1346 NewCert = (EFI_SIGNATURE_DATA *) ((UINT8 *) NewCertList + sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize);
1347 NewCertCount = (NewCertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - NewCertList->SignatureHeaderSize) / NewCertList->SignatureSize;
1348
1349 CopiedCount = 0;
1350 for (Index = 0; Index < NewCertCount; Index++) {
1351 IsNewCert = TRUE;
1352
1353 Size = DataSize;
1354 CertList = (EFI_SIGNATURE_LIST *) Data;
1355 while ((Size > 0) && (Size >= CertList->SignatureListSize)) {
1356 if (CompareGuid (&CertList->SignatureType, &NewCertList->SignatureType) &&
1357 (CertList->SignatureSize == NewCertList->SignatureSize)) {
1358 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1359 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1360 for (Index2 = 0; Index2 < CertCount; Index2++) {
1361 //
1362 // Iterate each Signature Data in this Signature List.
1363 //
1364 if (CompareMem (NewCert, Cert, CertList->SignatureSize) == 0) {
1365 IsNewCert = FALSE;
1366 break;
1367 }
1368 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
1369 }
1370 }
1371
1372 if (!IsNewCert) {
1373 break;
1374 }
1375 Size -= CertList->SignatureListSize;
1376 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1377 }
1378
1379 if (IsNewCert) {
1380 //
1381 // New EFI_SIGNATURE_DATA, append it.
1382 //
1383 if (CopiedCount == 0) {
1384 //
1385 // Copy EFI_SIGNATURE_LIST header for only once.
1386 //
1387 CopyMem (Tail, NewCertList, sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize);
1388 Tail = Tail + sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize;
1389 }
1390
1391 CopyMem (Tail, NewCert, NewCertList->SignatureSize);
1392 Tail += NewCertList->SignatureSize;
1393 CopiedCount++;
1394 }
1395
1396 NewCert = (EFI_SIGNATURE_DATA *) ((UINT8 *) NewCert + NewCertList->SignatureSize);
1397 }
1398
1399 //
1400 // Update SignatureListSize in newly appended EFI_SIGNATURE_LIST.
1401 //
1402 if (CopiedCount != 0) {
1403 SignatureListSize = sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize + (CopiedCount * NewCertList->SignatureSize);
1404 CertList = (EFI_SIGNATURE_LIST *) (Tail - SignatureListSize);
1405 CertList->SignatureListSize = (UINT32) SignatureListSize;
1406 }
1407
1408 NewDataSize -= NewCertList->SignatureListSize;
1409 NewCertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) NewCertList + NewCertList->SignatureListSize);
1410 }
1411
1412 return (Tail - (UINT8 *) Data);
1413 }
1414
1415 /**
1416 Compare two EFI_TIME data.
1417
1418
1419 @param FirstTime A pointer to the first EFI_TIME data.
1420 @param SecondTime A pointer to the second EFI_TIME data.
1421
1422 @retval TRUE The FirstTime is not later than the SecondTime.
1423 @retval FALSE The FirstTime is later than the SecondTime.
1424
1425 **/
1426 BOOLEAN
1427 CompareTimeStamp (
1428 IN EFI_TIME *FirstTime,
1429 IN EFI_TIME *SecondTime
1430 )
1431 {
1432 if (FirstTime->Year != SecondTime->Year) {
1433 return (BOOLEAN) (FirstTime->Year < SecondTime->Year);
1434 } else if (FirstTime->Month != SecondTime->Month) {
1435 return (BOOLEAN) (FirstTime->Month < SecondTime->Month);
1436 } else if (FirstTime->Day != SecondTime->Day) {
1437 return (BOOLEAN) (FirstTime->Day < SecondTime->Day);
1438 } else if (FirstTime->Hour != SecondTime->Hour) {
1439 return (BOOLEAN) (FirstTime->Hour < SecondTime->Hour);
1440 } else if (FirstTime->Minute != SecondTime->Minute) {
1441 return (BOOLEAN) (FirstTime->Minute < SecondTime->Minute);
1442 }
1443
1444 return (BOOLEAN) (FirstTime->Second <= SecondTime->Second);
1445 }
1446
1447 /**
1448 Find matching signer's certificates for common authenticated variable
1449 by corresponding VariableName and VendorGuid from "certdb".
1450
1451 The data format of "certdb":
1452 //
1453 // UINT32 CertDbListSize;
1454 // /// AUTH_CERT_DB_DATA Certs1[];
1455 // /// AUTH_CERT_DB_DATA Certs2[];
1456 // /// ...
1457 // /// AUTH_CERT_DB_DATA Certsn[];
1458 //
1459
1460 @param[in] VariableName Name of authenticated Variable.
1461 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1462 @param[in] Data Pointer to variable "certdb".
1463 @param[in] DataSize Size of variable "certdb".
1464 @param[out] CertOffset Offset of matching CertData, from starting of Data.
1465 @param[out] CertDataSize Length of CertData in bytes.
1466 @param[out] CertNodeOffset Offset of matching AUTH_CERT_DB_DATA , from
1467 starting of Data.
1468 @param[out] CertNodeSize Length of AUTH_CERT_DB_DATA in bytes.
1469
1470 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1471 @retval EFI_NOT_FOUND Fail to find matching certs.
1472 @retval EFI_SUCCESS Find matching certs and output parameters.
1473
1474 **/
1475 EFI_STATUS
1476 FindCertsFromDb (
1477 IN CHAR16 *VariableName,
1478 IN EFI_GUID *VendorGuid,
1479 IN UINT8 *Data,
1480 IN UINTN DataSize,
1481 OUT UINT32 *CertOffset, OPTIONAL
1482 OUT UINT32 *CertDataSize, OPTIONAL
1483 OUT UINT32 *CertNodeOffset,OPTIONAL
1484 OUT UINT32 *CertNodeSize OPTIONAL
1485 )
1486 {
1487 UINT32 Offset;
1488 AUTH_CERT_DB_DATA *Ptr;
1489 UINT32 CertSize;
1490 UINT32 NameSize;
1491 UINT32 NodeSize;
1492 UINT32 CertDbListSize;
1493
1494 if ((VariableName == NULL) || (VendorGuid == NULL) || (Data == NULL)) {
1495 return EFI_INVALID_PARAMETER;
1496 }
1497
1498 //
1499 // Check whether DataSize matches recorded CertDbListSize.
1500 //
1501 if (DataSize < sizeof (UINT32)) {
1502 return EFI_INVALID_PARAMETER;
1503 }
1504
1505 CertDbListSize = ReadUnaligned32 ((UINT32 *) Data);
1506
1507 if (CertDbListSize != (UINT32) DataSize) {
1508 return EFI_INVALID_PARAMETER;
1509 }
1510
1511 Offset = sizeof (UINT32);
1512
1513 //
1514 // Get corresponding certificates by VendorGuid and VariableName.
1515 //
1516 while (Offset < (UINT32) DataSize) {
1517 Ptr = (AUTH_CERT_DB_DATA *) (Data + Offset);
1518 //
1519 // Check whether VendorGuid matches.
1520 //
1521 if (CompareGuid (&Ptr->VendorGuid, VendorGuid)) {
1522 NodeSize = ReadUnaligned32 (&Ptr->CertNodeSize);
1523 NameSize = ReadUnaligned32 (&Ptr->NameSize);
1524 CertSize = ReadUnaligned32 (&Ptr->CertDataSize);
1525
1526 if (NodeSize != sizeof (EFI_GUID) + sizeof (UINT32) * 3 + CertSize +
1527 sizeof (CHAR16) * NameSize) {
1528 return EFI_INVALID_PARAMETER;
1529 }
1530
1531 Offset = Offset + sizeof (EFI_GUID) + sizeof (UINT32) * 3;
1532 //
1533 // Check whether VariableName matches.
1534 //
1535 if ((NameSize == StrLen (VariableName)) &&
1536 (CompareMem (Data + Offset, VariableName, NameSize * sizeof (CHAR16)) == 0)) {
1537 Offset = Offset + NameSize * sizeof (CHAR16);
1538
1539 if (CertOffset != NULL) {
1540 *CertOffset = Offset;
1541 }
1542
1543 if (CertDataSize != NULL) {
1544 *CertDataSize = CertSize;
1545 }
1546
1547 if (CertNodeOffset != NULL) {
1548 *CertNodeOffset = (UINT32) ((UINT8 *) Ptr - Data);
1549 }
1550
1551 if (CertNodeSize != NULL) {
1552 *CertNodeSize = NodeSize;
1553 }
1554
1555 return EFI_SUCCESS;
1556 } else {
1557 Offset = Offset + NameSize * sizeof (CHAR16) + CertSize;
1558 }
1559 } else {
1560 NodeSize = ReadUnaligned32 (&Ptr->CertNodeSize);
1561 Offset = Offset + NodeSize;
1562 }
1563 }
1564
1565 return EFI_NOT_FOUND;
1566 }
1567
1568 /**
1569 Retrieve signer's certificates for common authenticated variable
1570 by corresponding VariableName and VendorGuid from "certdb".
1571
1572 @param[in] VariableName Name of authenticated Variable.
1573 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1574 @param[out] CertData Pointer to signer's certificates.
1575 @param[out] CertDataSize Length of CertData in bytes.
1576
1577 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1578 @retval EFI_NOT_FOUND Fail to find "certdb" or matching certs.
1579 @retval EFI_SUCCESS Get signer's certificates successfully.
1580
1581 **/
1582 EFI_STATUS
1583 GetCertsFromDb (
1584 IN CHAR16 *VariableName,
1585 IN EFI_GUID *VendorGuid,
1586 OUT UINT8 **CertData,
1587 OUT UINT32 *CertDataSize
1588 )
1589 {
1590 VARIABLE_POINTER_TRACK CertDbVariable;
1591 EFI_STATUS Status;
1592 UINT8 *Data;
1593 UINTN DataSize;
1594 UINT32 CertOffset;
1595
1596 if ((VariableName == NULL) || (VendorGuid == NULL) || (CertData == NULL) || (CertDataSize == NULL)) {
1597 return EFI_INVALID_PARAMETER;
1598 }
1599
1600 //
1601 // Get variable "certdb".
1602 //
1603 Status = FindVariable (
1604 EFI_CERT_DB_NAME,
1605 &gEfiCertDbGuid,
1606 &CertDbVariable,
1607 &mVariableModuleGlobal->VariableGlobal,
1608 FALSE
1609 );
1610 if (EFI_ERROR (Status)) {
1611 return Status;
1612 }
1613
1614 DataSize = DataSizeOfVariable (CertDbVariable.CurrPtr);
1615 Data = GetVariableDataPtr (CertDbVariable.CurrPtr);
1616 if ((DataSize == 0) || (Data == NULL)) {
1617 ASSERT (FALSE);
1618 return EFI_NOT_FOUND;
1619 }
1620
1621 Status = FindCertsFromDb (
1622 VariableName,
1623 VendorGuid,
1624 Data,
1625 DataSize,
1626 &CertOffset,
1627 CertDataSize,
1628 NULL,
1629 NULL
1630 );
1631
1632 if (EFI_ERROR (Status)) {
1633 return Status;
1634 }
1635
1636 *CertData = Data + CertOffset;
1637 return EFI_SUCCESS;
1638 }
1639
1640 /**
1641 Delete matching signer's certificates when deleting common authenticated
1642 variable by corresponding VariableName and VendorGuid from "certdb".
1643
1644 @param[in] VariableName Name of authenticated Variable.
1645 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1646
1647 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1648 @retval EFI_NOT_FOUND Fail to find "certdb" or matching certs.
1649 @retval EFI_OUT_OF_RESOURCES The operation is failed due to lack of resources.
1650 @retval EFI_SUCCESS The operation is completed successfully.
1651
1652 **/
1653 EFI_STATUS
1654 DeleteCertsFromDb (
1655 IN CHAR16 *VariableName,
1656 IN EFI_GUID *VendorGuid
1657 )
1658 {
1659 VARIABLE_POINTER_TRACK CertDbVariable;
1660 EFI_STATUS Status;
1661 UINT8 *Data;
1662 UINTN DataSize;
1663 UINT32 VarAttr;
1664 UINT32 CertNodeOffset;
1665 UINT32 CertNodeSize;
1666 UINT8 *NewCertDb;
1667 UINT32 NewCertDbSize;
1668
1669 if ((VariableName == NULL) || (VendorGuid == NULL)) {
1670 return EFI_INVALID_PARAMETER;
1671 }
1672
1673 //
1674 // Get variable "certdb".
1675 //
1676 Status = FindVariable (
1677 EFI_CERT_DB_NAME,
1678 &gEfiCertDbGuid,
1679 &CertDbVariable,
1680 &mVariableModuleGlobal->VariableGlobal,
1681 FALSE
1682 );
1683 if (EFI_ERROR (Status)) {
1684 return Status;
1685 }
1686
1687 DataSize = DataSizeOfVariable (CertDbVariable.CurrPtr);
1688 Data = GetVariableDataPtr (CertDbVariable.CurrPtr);
1689 if ((DataSize == 0) || (Data == NULL)) {
1690 ASSERT (FALSE);
1691 return EFI_NOT_FOUND;
1692 }
1693
1694 if (DataSize == sizeof (UINT32)) {
1695 //
1696 // There is no certs in certdb.
1697 //
1698 return EFI_SUCCESS;
1699 }
1700
1701 //
1702 // Get corresponding cert node from certdb.
1703 //
1704 Status = FindCertsFromDb (
1705 VariableName,
1706 VendorGuid,
1707 Data,
1708 DataSize,
1709 NULL,
1710 NULL,
1711 &CertNodeOffset,
1712 &CertNodeSize
1713 );
1714
1715 if (EFI_ERROR (Status)) {
1716 return Status;
1717 }
1718
1719 if (DataSize < (CertNodeOffset + CertNodeSize)) {
1720 return EFI_NOT_FOUND;
1721 }
1722
1723 //
1724 // Construct new data content of variable "certdb".
1725 //
1726 NewCertDbSize = (UINT32) DataSize - CertNodeSize;
1727 NewCertDb = (UINT8*) mCertDbStore;
1728
1729 //
1730 // Copy the DB entries before deleting node.
1731 //
1732 CopyMem (NewCertDb, Data, CertNodeOffset);
1733 //
1734 // Update CertDbListSize.
1735 //
1736 CopyMem (NewCertDb, &NewCertDbSize, sizeof (UINT32));
1737 //
1738 // Copy the DB entries after deleting node.
1739 //
1740 if (DataSize > (CertNodeOffset + CertNodeSize)) {
1741 CopyMem (
1742 NewCertDb + CertNodeOffset,
1743 Data + CertNodeOffset + CertNodeSize,
1744 DataSize - CertNodeOffset - CertNodeSize
1745 );
1746 }
1747
1748 //
1749 // Set "certdb".
1750 //
1751 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
1752 Status = UpdateVariable (
1753 EFI_CERT_DB_NAME,
1754 &gEfiCertDbGuid,
1755 NewCertDb,
1756 NewCertDbSize,
1757 VarAttr,
1758 0,
1759 0,
1760 &CertDbVariable,
1761 NULL
1762 );
1763
1764 return Status;
1765 }
1766
1767 /**
1768 Insert signer's certificates for common authenticated variable with VariableName
1769 and VendorGuid in AUTH_CERT_DB_DATA to "certdb".
1770
1771 @param[in] VariableName Name of authenticated Variable.
1772 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1773 @param[in] CertData Pointer to signer's certificates.
1774 @param[in] CertDataSize Length of CertData in bytes.
1775
1776 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1777 @retval EFI_ACCESS_DENIED An AUTH_CERT_DB_DATA entry with same VariableName
1778 and VendorGuid already exists.
1779 @retval EFI_OUT_OF_RESOURCES The operation is failed due to lack of resources.
1780 @retval EFI_SUCCESS Insert an AUTH_CERT_DB_DATA entry to "certdb"
1781
1782 **/
1783 EFI_STATUS
1784 InsertCertsToDb (
1785 IN CHAR16 *VariableName,
1786 IN EFI_GUID *VendorGuid,
1787 IN UINT8 *CertData,
1788 IN UINTN CertDataSize
1789 )
1790 {
1791 VARIABLE_POINTER_TRACK CertDbVariable;
1792 EFI_STATUS Status;
1793 UINT8 *Data;
1794 UINTN DataSize;
1795 UINT32 VarAttr;
1796 UINT8 *NewCertDb;
1797 UINT32 NewCertDbSize;
1798 UINT32 CertNodeSize;
1799 UINT32 NameSize;
1800 AUTH_CERT_DB_DATA *Ptr;
1801
1802 if ((VariableName == NULL) || (VendorGuid == NULL) || (CertData == NULL)) {
1803 return EFI_INVALID_PARAMETER;
1804 }
1805
1806 //
1807 // Get variable "certdb".
1808 //
1809 Status = FindVariable (
1810 EFI_CERT_DB_NAME,
1811 &gEfiCertDbGuid,
1812 &CertDbVariable,
1813 &mVariableModuleGlobal->VariableGlobal,
1814 FALSE
1815 );
1816 if (EFI_ERROR (Status)) {
1817 return Status;
1818 }
1819
1820 DataSize = DataSizeOfVariable (CertDbVariable.CurrPtr);
1821 Data = GetVariableDataPtr (CertDbVariable.CurrPtr);
1822 if ((DataSize == 0) || (Data == NULL)) {
1823 ASSERT (FALSE);
1824 return EFI_NOT_FOUND;
1825 }
1826
1827 //
1828 // Find whether matching cert node already exists in "certdb".
1829 // If yes return error.
1830 //
1831 Status = FindCertsFromDb (
1832 VariableName,
1833 VendorGuid,
1834 Data,
1835 DataSize,
1836 NULL,
1837 NULL,
1838 NULL,
1839 NULL
1840 );
1841
1842 if (!EFI_ERROR (Status)) {
1843 ASSERT (FALSE);
1844 return EFI_ACCESS_DENIED;
1845 }
1846
1847 //
1848 // Construct new data content of variable "certdb".
1849 //
1850 NameSize = (UINT32) StrLen (VariableName);
1851 CertNodeSize = sizeof (AUTH_CERT_DB_DATA) + (UINT32) CertDataSize + NameSize * sizeof (CHAR16);
1852 NewCertDbSize = (UINT32) DataSize + CertNodeSize;
1853 if (NewCertDbSize > MAX_CERTDB_SIZE) {
1854 return EFI_OUT_OF_RESOURCES;
1855 }
1856 NewCertDb = (UINT8*) mCertDbStore;
1857
1858 //
1859 // Copy the DB entries before deleting node.
1860 //
1861 CopyMem (NewCertDb, Data, DataSize);
1862 //
1863 // Update CertDbListSize.
1864 //
1865 CopyMem (NewCertDb, &NewCertDbSize, sizeof (UINT32));
1866 //
1867 // Construct new cert node.
1868 //
1869 Ptr = (AUTH_CERT_DB_DATA *) (NewCertDb + DataSize);
1870 CopyGuid (&Ptr->VendorGuid, VendorGuid);
1871 CopyMem (&Ptr->CertNodeSize, &CertNodeSize, sizeof (UINT32));
1872 CopyMem (&Ptr->NameSize, &NameSize, sizeof (UINT32));
1873 CopyMem (&Ptr->CertDataSize, &CertDataSize, sizeof (UINT32));
1874
1875 CopyMem (
1876 (UINT8 *) Ptr + sizeof (AUTH_CERT_DB_DATA),
1877 VariableName,
1878 NameSize * sizeof (CHAR16)
1879 );
1880
1881 CopyMem (
1882 (UINT8 *) Ptr + sizeof (AUTH_CERT_DB_DATA) + NameSize * sizeof (CHAR16),
1883 CertData,
1884 CertDataSize
1885 );
1886
1887 //
1888 // Set "certdb".
1889 //
1890 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
1891 Status = UpdateVariable (
1892 EFI_CERT_DB_NAME,
1893 &gEfiCertDbGuid,
1894 NewCertDb,
1895 NewCertDbSize,
1896 VarAttr,
1897 0,
1898 0,
1899 &CertDbVariable,
1900 NULL
1901 );
1902
1903 return Status;
1904 }
1905
1906 /**
1907 Process variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS set
1908
1909 Caution: This function may receive untrusted input.
1910 This function may be invoked in SMM mode, and datasize and data are external input.
1911 This function will do basic validation, before parse the data.
1912 This function will parse the authentication carefully to avoid security issues, like
1913 buffer overflow, integer overflow.
1914
1915 @param[in] VariableName Name of Variable to be found.
1916 @param[in] VendorGuid Variable vendor GUID.
1917 @param[in] Data Data pointer.
1918 @param[in] DataSize Size of Data found. If size is less than the
1919 data, this value contains the required size.
1920 @param[in] Variable The variable information which is used to keep track of variable usage.
1921 @param[in] Attributes Attribute value of the variable.
1922 @param[in] AuthVarType Verify against PK, KEK database, private database or certificate in data payload.
1923 @param[out] VarDel Delete the variable or not.
1924
1925 @retval EFI_INVALID_PARAMETER Invalid parameter.
1926 @retval EFI_SECURITY_VIOLATION The variable does NOT pass the validation
1927 check carried out by the firmware.
1928 @retval EFI_OUT_OF_RESOURCES Failed to process variable due to lack
1929 of resources.
1930 @retval EFI_SUCCESS Variable pass validation successfully.
1931
1932 **/
1933 EFI_STATUS
1934 VerifyTimeBasedPayload (
1935 IN CHAR16 *VariableName,
1936 IN EFI_GUID *VendorGuid,
1937 IN VOID *Data,
1938 IN UINTN DataSize,
1939 IN VARIABLE_POINTER_TRACK *Variable,
1940 IN UINT32 Attributes,
1941 IN AUTHVAR_TYPE AuthVarType,
1942 OUT BOOLEAN *VarDel
1943 )
1944 {
1945 UINT8 *RootCert;
1946 UINT8 *SigData;
1947 UINT8 *PayloadPtr;
1948 UINTN RootCertSize;
1949 UINTN Index;
1950 UINTN CertCount;
1951 UINTN PayloadSize;
1952 UINT32 Attr;
1953 UINT32 SigDataSize;
1954 UINT32 KekDataSize;
1955 BOOLEAN VerifyStatus;
1956 EFI_STATUS Status;
1957 EFI_SIGNATURE_LIST *CertList;
1958 EFI_SIGNATURE_DATA *Cert;
1959 VARIABLE_POINTER_TRACK KekVariable;
1960 EFI_VARIABLE_AUTHENTICATION_2 *CertData;
1961 UINT8 *NewData;
1962 UINTN NewDataSize;
1963 VARIABLE_POINTER_TRACK PkVariable;
1964 UINT8 *Buffer;
1965 UINTN Length;
1966 UINT8 *SignerCerts;
1967 UINT8 *WrapSigData;
1968 UINTN CertStackSize;
1969 UINT8 *CertsInCertDb;
1970 UINT32 CertsSizeinDb;
1971
1972 VerifyStatus = FALSE;
1973 CertData = NULL;
1974 NewData = NULL;
1975 Attr = Attributes;
1976 WrapSigData = NULL;
1977 SignerCerts = NULL;
1978 RootCert = NULL;
1979
1980 //
1981 // When the attribute EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS is
1982 // set, then the Data buffer shall begin with an instance of a complete (and serialized)
1983 // EFI_VARIABLE_AUTHENTICATION_2 descriptor. The descriptor shall be followed by the new
1984 // variable value and DataSize shall reflect the combined size of the descriptor and the new
1985 // variable value. The authentication descriptor is not part of the variable data and is not
1986 // returned by subsequent calls to GetVariable().
1987 //
1988 CertData = (EFI_VARIABLE_AUTHENTICATION_2 *) Data;
1989
1990 //
1991 // Verify that Pad1, Nanosecond, TimeZone, Daylight and Pad2 components of the
1992 // TimeStamp value are set to zero.
1993 //
1994 if ((CertData->TimeStamp.Pad1 != 0) ||
1995 (CertData->TimeStamp.Nanosecond != 0) ||
1996 (CertData->TimeStamp.TimeZone != 0) ||
1997 (CertData->TimeStamp.Daylight != 0) ||
1998 (CertData->TimeStamp.Pad2 != 0)) {
1999 return EFI_SECURITY_VIOLATION;
2000 }
2001
2002 if ((Variable->CurrPtr != NULL) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0)) {
2003 if (CompareTimeStamp (&CertData->TimeStamp, &Variable->CurrPtr->TimeStamp)) {
2004 //
2005 // TimeStamp check fail, suspicious replay attack, return EFI_SECURITY_VIOLATION.
2006 //
2007 return EFI_SECURITY_VIOLATION;
2008 }
2009 }
2010
2011 //
2012 // wCertificateType should be WIN_CERT_TYPE_EFI_GUID.
2013 // Cert type should be EFI_CERT_TYPE_PKCS7_GUID.
2014 //
2015 if ((CertData->AuthInfo.Hdr.wCertificateType != WIN_CERT_TYPE_EFI_GUID) ||
2016 !CompareGuid (&CertData->AuthInfo.CertType, &gEfiCertPkcs7Guid)) {
2017 //
2018 // Invalid AuthInfo type, return EFI_SECURITY_VIOLATION.
2019 //
2020 return EFI_SECURITY_VIOLATION;
2021 }
2022
2023 //
2024 // Find out Pkcs7 SignedData which follows the EFI_VARIABLE_AUTHENTICATION_2 descriptor.
2025 // AuthInfo.Hdr.dwLength is the length of the entire certificate, including the length of the header.
2026 //
2027 SigData = CertData->AuthInfo.CertData;
2028 SigDataSize = CertData->AuthInfo.Hdr.dwLength - (UINT32) (OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData));
2029
2030 //
2031 // Find out the new data payload which follows Pkcs7 SignedData directly.
2032 //
2033 PayloadPtr = SigData + SigDataSize;
2034 PayloadSize = DataSize - OFFSET_OF_AUTHINFO2_CERT_DATA - (UINTN) SigDataSize;
2035
2036 //
2037 // Construct a buffer to fill with (VariableName, VendorGuid, Attributes, TimeStamp, Data).
2038 //
2039 NewDataSize = PayloadSize + sizeof (EFI_TIME) + sizeof (UINT32) +
2040 sizeof (EFI_GUID) + StrSize (VariableName) - sizeof (CHAR16);
2041 NewData = mSerializationRuntimeBuffer;
2042
2043 Buffer = NewData;
2044 Length = StrLen (VariableName) * sizeof (CHAR16);
2045 CopyMem (Buffer, VariableName, Length);
2046 Buffer += Length;
2047
2048 Length = sizeof (EFI_GUID);
2049 CopyMem (Buffer, VendorGuid, Length);
2050 Buffer += Length;
2051
2052 Length = sizeof (UINT32);
2053 CopyMem (Buffer, &Attr, Length);
2054 Buffer += Length;
2055
2056 Length = sizeof (EFI_TIME);
2057 CopyMem (Buffer, &CertData->TimeStamp, Length);
2058 Buffer += Length;
2059
2060 CopyMem (Buffer, PayloadPtr, PayloadSize);
2061
2062 if (AuthVarType == AuthVarTypePk) {
2063 //
2064 // Get platform key from variable.
2065 //
2066 Status = FindVariable (
2067 EFI_PLATFORM_KEY_NAME,
2068 &gEfiGlobalVariableGuid,
2069 &PkVariable,
2070 &mVariableModuleGlobal->VariableGlobal,
2071 FALSE
2072 );
2073 if (EFI_ERROR (Status)) {
2074 return Status;
2075 }
2076
2077 CertList = (EFI_SIGNATURE_LIST *) GetVariableDataPtr (PkVariable.CurrPtr);
2078 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2079 RootCert = Cert->SignatureData;
2080 RootCertSize = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);
2081
2082
2083 //
2084 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2085 //
2086 VerifyStatus = Pkcs7Verify (
2087 SigData,
2088 SigDataSize,
2089 RootCert,
2090 RootCertSize,
2091 NewData,
2092 NewDataSize
2093 );
2094
2095 } else if (AuthVarType == AuthVarTypeKek) {
2096
2097 //
2098 // Get KEK database from variable.
2099 //
2100 Status = FindVariable (
2101 EFI_KEY_EXCHANGE_KEY_NAME,
2102 &gEfiGlobalVariableGuid,
2103 &KekVariable,
2104 &mVariableModuleGlobal->VariableGlobal,
2105 FALSE
2106 );
2107 if (EFI_ERROR (Status)) {
2108 return Status;
2109 }
2110
2111 //
2112 // Ready to verify Pkcs7 SignedData. Go through KEK Signature Database to find out X.509 CertList.
2113 //
2114 KekDataSize = KekVariable.CurrPtr->DataSize;
2115 CertList = (EFI_SIGNATURE_LIST *) GetVariableDataPtr (KekVariable.CurrPtr);
2116 while ((KekDataSize > 0) && (KekDataSize >= CertList->SignatureListSize)) {
2117 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
2118 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2119 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
2120 for (Index = 0; Index < CertCount; Index++) {
2121 //
2122 // Iterate each Signature Data Node within this CertList for a verify
2123 //
2124 RootCert = Cert->SignatureData;
2125 RootCertSize = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);
2126
2127 //
2128 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2129 //
2130 VerifyStatus = Pkcs7Verify (
2131 SigData,
2132 SigDataSize,
2133 RootCert,
2134 RootCertSize,
2135 NewData,
2136 NewDataSize
2137 );
2138 if (VerifyStatus) {
2139 goto Exit;
2140 }
2141 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
2142 }
2143 }
2144 KekDataSize -= CertList->SignatureListSize;
2145 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
2146 }
2147 } else if (AuthVarType == AuthVarTypePriv) {
2148
2149 //
2150 // Process common authenticated variable except PK/KEK/DB/DBX.
2151 // Get signer's certificates from SignedData.
2152 //
2153 VerifyStatus = Pkcs7GetSigners (
2154 SigData,
2155 SigDataSize,
2156 &SignerCerts,
2157 &CertStackSize,
2158 &RootCert,
2159 &RootCertSize
2160 );
2161 if (!VerifyStatus) {
2162 goto Exit;
2163 }
2164
2165 //
2166 // Get previously stored signer's certificates from certdb for existing
2167 // variable. Check whether they are identical with signer's certificates
2168 // in SignedData. If not, return error immediately.
2169 //
2170 if ((Variable->CurrPtr != NULL)) {
2171 VerifyStatus = FALSE;
2172
2173 Status = GetCertsFromDb (VariableName, VendorGuid, &CertsInCertDb, &CertsSizeinDb);
2174 if (EFI_ERROR (Status)) {
2175 goto Exit;
2176 }
2177
2178 if ((CertStackSize != CertsSizeinDb) ||
2179 (CompareMem (SignerCerts, CertsInCertDb, CertsSizeinDb) != 0)) {
2180 goto Exit;
2181 }
2182 }
2183
2184 VerifyStatus = Pkcs7Verify (
2185 SigData,
2186 SigDataSize,
2187 RootCert,
2188 RootCertSize,
2189 NewData,
2190 NewDataSize
2191 );
2192 if (!VerifyStatus) {
2193 goto Exit;
2194 }
2195
2196 //
2197 // Delete signer's certificates when delete the common authenticated variable.
2198 //
2199 if ((PayloadSize == 0) && (Variable->CurrPtr != NULL) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0)) {
2200 Status = DeleteCertsFromDb (VariableName, VendorGuid);
2201 if (EFI_ERROR (Status)) {
2202 VerifyStatus = FALSE;
2203 goto Exit;
2204 }
2205 } else if (Variable->CurrPtr == NULL && PayloadSize != 0) {
2206 //
2207 // Insert signer's certificates when adding a new common authenticated variable.
2208 //
2209 Status = InsertCertsToDb (VariableName, VendorGuid, SignerCerts, CertStackSize);
2210 if (EFI_ERROR (Status)) {
2211 VerifyStatus = FALSE;
2212 goto Exit;
2213 }
2214 }
2215 } else if (AuthVarType == AuthVarTypePayload) {
2216 CertList = (EFI_SIGNATURE_LIST *) PayloadPtr;
2217 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2218 RootCert = Cert->SignatureData;
2219 RootCertSize = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);
2220
2221 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2222 //
2223 VerifyStatus = Pkcs7Verify (
2224 SigData,
2225 SigDataSize,
2226 RootCert,
2227 RootCertSize,
2228 NewData,
2229 NewDataSize
2230 );
2231 } else {
2232 return EFI_SECURITY_VIOLATION;
2233 }
2234
2235 Exit:
2236
2237 if (AuthVarType == AuthVarTypePriv) {
2238 Pkcs7FreeSigners (RootCert);
2239 Pkcs7FreeSigners (SignerCerts);
2240 }
2241
2242 if (!VerifyStatus) {
2243 return EFI_SECURITY_VIOLATION;
2244 }
2245
2246 Status = CheckSignatureListFormat(VariableName, VendorGuid, PayloadPtr, PayloadSize);
2247 if (EFI_ERROR (Status)) {
2248 return Status;
2249 }
2250
2251 if ((PayloadSize == 0) && (VarDel != NULL)) {
2252 *VarDel = TRUE;
2253 }
2254
2255 //
2256 // Final step: Update/Append Variable if it pass Pkcs7Verify
2257 //
2258 return UpdateVariable (
2259 VariableName,
2260 VendorGuid,
2261 PayloadPtr,
2262 PayloadSize,
2263 Attributes,
2264 0,
2265 0,
2266 Variable,
2267 &CertData->TimeStamp
2268 );
2269 }
2270