]> git.proxmox.com Git - mirror_edk2.git/blob - SecurityPkg/VariableAuthenticated/RuntimeDxe/AuthService.c
1. Fix TOCTOU issue in VariableSmm, FtwSmm, FpdtSmm, SmmCorePerformance SMM handler...
[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 (MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize)));
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 if (EFI_ERROR (Status)) {
449 return 0;
450 }
451
452 //
453 // Check whether the public key entry does exist.
454 //
455 IsFound = FALSE;
456 for (Ptr = mPubKeyStore, Index = 1; Index <= mPubKeyNumber; Index++) {
457 if (CompareMem (Ptr, PubKey, EFI_CERT_TYPE_RSA2048_SIZE) == 0) {
458 IsFound = TRUE;
459 break;
460 }
461 Ptr += EFI_CERT_TYPE_RSA2048_SIZE;
462 }
463
464 if (!IsFound) {
465 //
466 // Add public key in database.
467 //
468 if (mPubKeyNumber == MAX_KEY_NUM) {
469 //
470 // Public key dadatase is full, try to reclaim invalid key.
471 //
472 if (AtRuntime ()) {
473 //
474 // NV storage can't reclaim at runtime.
475 //
476 return 0;
477 }
478
479 Status = Reclaim (
480 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
481 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
482 FALSE,
483 NULL,
484 TRUE,
485 TRUE
486 );
487 if (EFI_ERROR (Status)) {
488 return 0;
489 }
490
491 Status = FindVariable (
492 AUTHVAR_KEYDB_NAME,
493 &gEfiAuthenticatedVariableGuid,
494 &Variable,
495 &mVariableModuleGlobal->VariableGlobal,
496 FALSE
497 );
498 ASSERT_EFI_ERROR (Status);
499 if (EFI_ERROR (Status)) {
500 return 0;
501 }
502
503 DataSize = DataSizeOfVariable (Variable.CurrPtr);
504 Data = GetVariableDataPtr (Variable.CurrPtr);
505 ASSERT ((DataSize != 0) && (Data != NULL));
506 CopyMem (mPubKeyStore, (UINT8 *) Data, DataSize);
507 mPubKeyNumber = (UINT32) (DataSize / EFI_CERT_TYPE_RSA2048_SIZE);
508
509 if (mPubKeyNumber == MAX_KEY_NUM) {
510 return 0;
511 }
512 }
513
514 CopyMem (mPubKeyStore + mPubKeyNumber * EFI_CERT_TYPE_RSA2048_SIZE, PubKey, EFI_CERT_TYPE_RSA2048_SIZE);
515 Index = ++mPubKeyNumber;
516 //
517 // Update public key database variable.
518 //
519 Status = UpdateVariable (
520 AUTHVAR_KEYDB_NAME,
521 &gEfiAuthenticatedVariableGuid,
522 mPubKeyStore,
523 mPubKeyNumber * EFI_CERT_TYPE_RSA2048_SIZE,
524 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS,
525 0,
526 0,
527 &Variable,
528 NULL
529 );
530 ASSERT_EFI_ERROR (Status);
531 }
532
533 return Index;
534 }
535
536 /**
537 Verify data payload with AuthInfo in EFI_CERT_TYPE_RSA2048_SHA256_GUID type.
538 Follow the steps in UEFI2.2.
539
540 Caution: This function may receive untrusted input.
541 This function may be invoked in SMM mode, and datasize and data are external input.
542 This function will do basic validation, before parse the data.
543 This function will parse the authentication carefully to avoid security issues, like
544 buffer overflow, integer overflow.
545
546 @param[in] Data Pointer to data with AuthInfo.
547 @param[in] DataSize Size of Data.
548 @param[in] PubKey Public key used for verification.
549
550 @retval EFI_INVALID_PARAMETER Invalid parameter.
551 @retval EFI_SECURITY_VIOLATION If authentication failed.
552 @retval EFI_SUCCESS Authentication successful.
553
554 **/
555 EFI_STATUS
556 VerifyCounterBasedPayload (
557 IN UINT8 *Data,
558 IN UINTN DataSize,
559 IN UINT8 *PubKey
560 )
561 {
562 BOOLEAN Status;
563 EFI_VARIABLE_AUTHENTICATION *CertData;
564 EFI_CERT_BLOCK_RSA_2048_SHA256 *CertBlock;
565 UINT8 Digest[SHA256_DIGEST_SIZE];
566 VOID *Rsa;
567 UINTN PayloadSize;
568
569 PayloadSize = DataSize - AUTHINFO_SIZE;
570 Rsa = NULL;
571 CertData = NULL;
572 CertBlock = NULL;
573
574 if (Data == NULL || PubKey == NULL) {
575 return EFI_INVALID_PARAMETER;
576 }
577
578 CertData = (EFI_VARIABLE_AUTHENTICATION *) Data;
579 CertBlock = (EFI_CERT_BLOCK_RSA_2048_SHA256 *) (CertData->AuthInfo.CertData);
580
581 //
582 // wCertificateType should be WIN_CERT_TYPE_EFI_GUID.
583 // Cert type should be EFI_CERT_TYPE_RSA2048_SHA256_GUID.
584 //
585 if ((CertData->AuthInfo.Hdr.wCertificateType != WIN_CERT_TYPE_EFI_GUID) ||
586 !CompareGuid (&CertData->AuthInfo.CertType, &gEfiCertTypeRsa2048Sha256Guid)
587 ) {
588 //
589 // Invalid AuthInfo type, return EFI_SECURITY_VIOLATION.
590 //
591 return EFI_SECURITY_VIOLATION;
592 }
593 //
594 // Hash data payload with SHA256.
595 //
596 ZeroMem (Digest, SHA256_DIGEST_SIZE);
597 Status = Sha256Init (mHashCtx);
598 if (!Status) {
599 goto Done;
600 }
601 Status = Sha256Update (mHashCtx, Data + AUTHINFO_SIZE, PayloadSize);
602 if (!Status) {
603 goto Done;
604 }
605 //
606 // Hash Size.
607 //
608 Status = Sha256Update (mHashCtx, &PayloadSize, sizeof (UINTN));
609 if (!Status) {
610 goto Done;
611 }
612 //
613 // Hash Monotonic Count.
614 //
615 Status = Sha256Update (mHashCtx, &CertData->MonotonicCount, sizeof (UINT64));
616 if (!Status) {
617 goto Done;
618 }
619 Status = Sha256Final (mHashCtx, Digest);
620 if (!Status) {
621 goto Done;
622 }
623 //
624 // Generate & Initialize RSA Context.
625 //
626 Rsa = RsaNew ();
627 ASSERT (Rsa != NULL);
628 //
629 // Set RSA Key Components.
630 // NOTE: Only N and E are needed to be set as RSA public key for signature verification.
631 //
632 Status = RsaSetKey (Rsa, RsaKeyN, PubKey, EFI_CERT_TYPE_RSA2048_SIZE);
633 if (!Status) {
634 goto Done;
635 }
636 Status = RsaSetKey (Rsa, RsaKeyE, mRsaE, sizeof (mRsaE));
637 if (!Status) {
638 goto Done;
639 }
640 //
641 // Verify the signature.
642 //
643 Status = RsaPkcs1Verify (
644 Rsa,
645 Digest,
646 SHA256_DIGEST_SIZE,
647 CertBlock->Signature,
648 EFI_CERT_TYPE_RSA2048_SHA256_SIZE
649 );
650
651 Done:
652 if (Rsa != NULL) {
653 RsaFree (Rsa);
654 }
655 if (Status) {
656 return EFI_SUCCESS;
657 } else {
658 return EFI_SECURITY_VIOLATION;
659 }
660 }
661
662 /**
663 Update platform mode.
664
665 @param[in] Mode SETUP_MODE or USER_MODE.
666
667 @return EFI_INVALID_PARAMETER Invalid parameter.
668 @return EFI_SUCCESS Update platform mode successfully.
669
670 **/
671 EFI_STATUS
672 UpdatePlatformMode (
673 IN UINT32 Mode
674 )
675 {
676 EFI_STATUS Status;
677 VARIABLE_POINTER_TRACK Variable;
678 UINT32 VarAttr;
679 UINT8 SecureBootMode;
680 UINT8 SecureBootEnable;
681 UINTN VariableDataSize;
682
683 Status = FindVariable (
684 EFI_SETUP_MODE_NAME,
685 &gEfiGlobalVariableGuid,
686 &Variable,
687 &mVariableModuleGlobal->VariableGlobal,
688 FALSE
689 );
690 if (EFI_ERROR (Status)) {
691 return Status;
692 }
693
694 //
695 // Update the value of SetupMode variable by a simple mem copy, this could avoid possible
696 // variable storage reclaim at runtime.
697 //
698 mPlatformMode = (UINT8) Mode;
699 CopyMem (GetVariableDataPtr (Variable.CurrPtr), &mPlatformMode, sizeof(UINT8));
700
701 if (AtRuntime ()) {
702 //
703 // SecureBoot Variable indicates whether the platform firmware is operating
704 // in Secure boot mode (1) or not (0), so we should not change SecureBoot
705 // Variable in runtime.
706 //
707 return Status;
708 }
709
710 //
711 // Check "SecureBoot" variable's existence.
712 // If it doesn't exist, firmware has no capability to perform driver signing verification,
713 // then set "SecureBoot" to 0.
714 //
715 Status = FindVariable (
716 EFI_SECURE_BOOT_MODE_NAME,
717 &gEfiGlobalVariableGuid,
718 &Variable,
719 &mVariableModuleGlobal->VariableGlobal,
720 FALSE
721 );
722 //
723 // If "SecureBoot" variable exists, then check "SetupMode" variable update.
724 // If "SetupMode" variable is USER_MODE, "SecureBoot" variable is set to 1.
725 // If "SetupMode" variable is SETUP_MODE, "SecureBoot" variable is set to 0.
726 //
727 if (Variable.CurrPtr == NULL) {
728 SecureBootMode = SECURE_BOOT_MODE_DISABLE;
729 } else {
730 if (mPlatformMode == USER_MODE) {
731 SecureBootMode = SECURE_BOOT_MODE_ENABLE;
732 } else if (mPlatformMode == SETUP_MODE) {
733 SecureBootMode = SECURE_BOOT_MODE_DISABLE;
734 } else {
735 return EFI_NOT_FOUND;
736 }
737 }
738
739 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS;
740 Status = UpdateVariable (
741 EFI_SECURE_BOOT_MODE_NAME,
742 &gEfiGlobalVariableGuid,
743 &SecureBootMode,
744 sizeof(UINT8),
745 VarAttr,
746 0,
747 0,
748 &Variable,
749 NULL
750 );
751 if (EFI_ERROR (Status)) {
752 return Status;
753 }
754
755 //
756 // Check "SecureBootEnable" variable's existence. It can enable/disable secure boot feature.
757 //
758 Status = FindVariable (
759 EFI_SECURE_BOOT_ENABLE_NAME,
760 &gEfiSecureBootEnableDisableGuid,
761 &Variable,
762 &mVariableModuleGlobal->VariableGlobal,
763 FALSE
764 );
765
766 if (SecureBootMode == SECURE_BOOT_MODE_ENABLE) {
767 //
768 // Create the "SecureBootEnable" variable as secure boot is enabled.
769 //
770 SecureBootEnable = SECURE_BOOT_ENABLE;
771 VariableDataSize = sizeof (SecureBootEnable);
772 } else {
773 //
774 // Delete the "SecureBootEnable" variable if this variable exist as "SecureBoot"
775 // variable is not in secure boot state.
776 //
777 if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
778 return EFI_SUCCESS;
779 }
780 SecureBootEnable = SECURE_BOOT_DISABLE;
781 VariableDataSize = 0;
782 }
783
784 Status = UpdateVariable (
785 EFI_SECURE_BOOT_ENABLE_NAME,
786 &gEfiSecureBootEnableDisableGuid,
787 &SecureBootEnable,
788 VariableDataSize,
789 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
790 0,
791 0,
792 &Variable,
793 NULL
794 );
795 return Status;
796 }
797
798 /**
799 Check input data form to make sure it is a valid EFI_SIGNATURE_LIST for PK/KEK/db/dbx variable.
800
801 @param[in] VariableName Name of Variable to be check.
802 @param[in] VendorGuid Variable vendor GUID.
803 @param[in] Data Point to the variable data to be checked.
804 @param[in] DataSize Size of Data.
805
806 @return EFI_INVALID_PARAMETER Invalid signature list format.
807 @return EFI_SUCCESS Passed signature list format check successfully.
808
809 **/
810 EFI_STATUS
811 CheckSignatureListFormat(
812 IN CHAR16 *VariableName,
813 IN EFI_GUID *VendorGuid,
814 IN VOID *Data,
815 IN UINTN DataSize
816 )
817 {
818 EFI_SIGNATURE_LIST *SigList;
819 UINTN SigDataSize;
820 UINT32 Index;
821 UINT32 SigCount;
822 BOOLEAN IsPk;
823 VOID *RsaContext;
824 EFI_SIGNATURE_DATA *CertData;
825 UINTN CertLen;
826
827 if (DataSize == 0) {
828 return EFI_SUCCESS;
829 }
830
831 ASSERT (VariableName != NULL && VendorGuid != NULL && Data != NULL);
832
833 if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_PLATFORM_KEY_NAME) == 0)){
834 IsPk = TRUE;
835 } else if ((CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0) ||
836 (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) &&
837 (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0 || StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0))){
838 IsPk = FALSE;
839 } else {
840 return EFI_SUCCESS;
841 }
842
843 SigCount = 0;
844 SigList = (EFI_SIGNATURE_LIST *) Data;
845 SigDataSize = DataSize;
846 RsaContext = NULL;
847
848 //
849 // Walk throuth the input signature list and check the data format.
850 // If any signature is incorrectly formed, the whole check will fail.
851 //
852 while ((SigDataSize > 0) && (SigDataSize >= SigList->SignatureListSize)) {
853 for (Index = 0; Index < (sizeof (mSupportSigItem) / sizeof (EFI_SIGNATURE_ITEM)); Index++ ) {
854 if (CompareGuid (&SigList->SignatureType, &mSupportSigItem[Index].SigType)) {
855 //
856 // The value of SignatureSize should always be 16 (size of SignatureOwner
857 // component) add the data length according to signature type.
858 //
859 if (mSupportSigItem[Index].SigDataSize != ((UINT32) ~0) &&
860 (SigList->SignatureSize - sizeof (EFI_GUID)) != mSupportSigItem[Index].SigDataSize) {
861 return EFI_INVALID_PARAMETER;
862 }
863 if (mSupportSigItem[Index].SigHeaderSize != ((UINTN) ~0) &&
864 SigList->SignatureHeaderSize != mSupportSigItem[Index].SigHeaderSize) {
865 return EFI_INVALID_PARAMETER;
866 }
867 break;
868 }
869 }
870
871 if (Index == (sizeof (mSupportSigItem) / sizeof (EFI_SIGNATURE_ITEM))) {
872 //
873 // Undefined signature type.
874 //
875 return EFI_INVALID_PARAMETER;
876 }
877
878 if (CompareGuid (&SigList->SignatureType, &gEfiCertX509Guid)) {
879 //
880 // Try to retrieve the RSA public key from the X.509 certificate.
881 // If this operation fails, it's not a valid certificate.
882 //
883 RsaContext = RsaNew ();
884 if (RsaContext == NULL) {
885 return EFI_INVALID_PARAMETER;
886 }
887 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) SigList + sizeof (EFI_SIGNATURE_LIST) + SigList->SignatureHeaderSize);
888 CertLen = SigList->SignatureSize - sizeof (EFI_GUID);
889 if (!RsaGetPublicKeyFromX509 (CertData->SignatureData, CertLen, &RsaContext)) {
890 RsaFree (RsaContext);
891 return EFI_INVALID_PARAMETER;
892 }
893 RsaFree (RsaContext);
894 }
895
896 if ((SigList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - SigList->SignatureHeaderSize) % SigList->SignatureSize != 0) {
897 return EFI_INVALID_PARAMETER;
898 }
899 SigCount += (SigList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - SigList->SignatureHeaderSize) / SigList->SignatureSize;
900
901 SigDataSize -= SigList->SignatureListSize;
902 SigList = (EFI_SIGNATURE_LIST *) ((UINT8 *) SigList + SigList->SignatureListSize);
903 }
904
905 if (((UINTN) SigList - (UINTN) Data) != DataSize) {
906 return EFI_INVALID_PARAMETER;
907 }
908
909 if (IsPk && SigCount > 1) {
910 return EFI_INVALID_PARAMETER;
911 }
912
913 return EFI_SUCCESS;
914 }
915
916 /**
917 Process variable with platform key for verification.
918
919 Caution: This function may receive untrusted input.
920 This function may be invoked in SMM mode, and datasize and data are external input.
921 This function will do basic validation, before parse the data.
922 This function will parse the authentication carefully to avoid security issues, like
923 buffer overflow, integer overflow.
924 This function will check attribute carefully to avoid authentication bypass.
925
926 @param[in] VariableName Name of Variable to be found.
927 @param[in] VendorGuid Variable vendor GUID.
928 @param[in] Data Data pointer.
929 @param[in] DataSize Size of Data found. If size is less than the
930 data, this value contains the required size.
931 @param[in] Variable The variable information which is used to keep track of variable usage.
932 @param[in] Attributes Attribute value of the variable
933 @param[in] IsPk Indicate whether it is to process pk.
934
935 @return EFI_INVALID_PARAMETER Invalid parameter.
936 @return EFI_SECURITY_VIOLATION The variable does NOT pass the validation.
937 check carried out by the firmware.
938 @return EFI_SUCCESS Variable passed validation successfully.
939
940 **/
941 EFI_STATUS
942 ProcessVarWithPk (
943 IN CHAR16 *VariableName,
944 IN EFI_GUID *VendorGuid,
945 IN VOID *Data,
946 IN UINTN DataSize,
947 IN VARIABLE_POINTER_TRACK *Variable,
948 IN UINT32 Attributes OPTIONAL,
949 IN BOOLEAN IsPk
950 )
951 {
952 EFI_STATUS Status;
953 BOOLEAN Del;
954 UINT8 *Payload;
955 UINTN PayloadSize;
956
957 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0 ||
958 (Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == 0) {
959 //
960 // PK, KEK and db/dbx should set EFI_VARIABLE_NON_VOLATILE attribute and should be a time-based
961 // authenticated variable.
962 //
963 return EFI_INVALID_PARAMETER;
964 }
965
966 Del = FALSE;
967 if ((InCustomMode() && UserPhysicalPresent()) || (mPlatformMode == SETUP_MODE && !IsPk)) {
968 Payload = (UINT8 *) Data + AUTHINFO2_SIZE (Data);
969 PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
970 if (PayloadSize == 0) {
971 Del = TRUE;
972 }
973
974 Status = CheckSignatureListFormat(VariableName, VendorGuid, Payload, PayloadSize);
975 if (EFI_ERROR (Status)) {
976 return Status;
977 }
978
979 Status = UpdateVariable (
980 VariableName,
981 VendorGuid,
982 Payload,
983 PayloadSize,
984 Attributes,
985 0,
986 0,
987 Variable,
988 &((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->TimeStamp
989 );
990 } else if (mPlatformMode == USER_MODE) {
991 //
992 // Verify against X509 Cert in PK database.
993 //
994 Status = VerifyTimeBasedPayload (
995 VariableName,
996 VendorGuid,
997 Data,
998 DataSize,
999 Variable,
1000 Attributes,
1001 AuthVarTypePk,
1002 &Del
1003 );
1004 } else {
1005 //
1006 // Verify against the certificate in data payload.
1007 //
1008 Status = VerifyTimeBasedPayload (
1009 VariableName,
1010 VendorGuid,
1011 Data,
1012 DataSize,
1013 Variable,
1014 Attributes,
1015 AuthVarTypePayload,
1016 &Del
1017 );
1018 }
1019
1020 if (!EFI_ERROR(Status) && IsPk) {
1021 if (mPlatformMode == SETUP_MODE && !Del) {
1022 //
1023 // If enroll PK in setup mode, need change to user mode.
1024 //
1025 Status = UpdatePlatformMode (USER_MODE);
1026 } else if (mPlatformMode == USER_MODE && Del){
1027 //
1028 // If delete PK in user mode, need change to setup mode.
1029 //
1030 Status = UpdatePlatformMode (SETUP_MODE);
1031 }
1032 }
1033
1034 return Status;
1035 }
1036
1037 /**
1038 Process variable with key exchange key for verification.
1039
1040 Caution: This function may receive untrusted input.
1041 This function may be invoked in SMM mode, and datasize and data are external input.
1042 This function will do basic validation, before parse the data.
1043 This function will parse the authentication carefully to avoid security issues, like
1044 buffer overflow, integer overflow.
1045 This function will check attribute carefully to avoid authentication bypass.
1046
1047 @param[in] VariableName Name of Variable to be found.
1048 @param[in] VendorGuid Variable vendor GUID.
1049 @param[in] Data Data pointer.
1050 @param[in] DataSize Size of Data found. If size is less than the
1051 data, this value contains the required size.
1052 @param[in] Variable The variable information which is used to keep track of variable usage.
1053 @param[in] Attributes Attribute value of the variable.
1054
1055 @return EFI_INVALID_PARAMETER Invalid parameter.
1056 @return EFI_SECURITY_VIOLATION The variable does NOT pass the validation
1057 check carried out by the firmware.
1058 @return EFI_SUCCESS Variable pass validation successfully.
1059
1060 **/
1061 EFI_STATUS
1062 ProcessVarWithKek (
1063 IN CHAR16 *VariableName,
1064 IN EFI_GUID *VendorGuid,
1065 IN VOID *Data,
1066 IN UINTN DataSize,
1067 IN VARIABLE_POINTER_TRACK *Variable,
1068 IN UINT32 Attributes OPTIONAL
1069 )
1070 {
1071 EFI_STATUS Status;
1072 UINT8 *Payload;
1073 UINTN PayloadSize;
1074
1075 if ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0 ||
1076 (Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == 0) {
1077 //
1078 // DB and DBX should set EFI_VARIABLE_NON_VOLATILE attribute and should be a time-based
1079 // authenticated variable.
1080 //
1081 return EFI_INVALID_PARAMETER;
1082 }
1083
1084 Status = EFI_SUCCESS;
1085 if (mPlatformMode == USER_MODE && !(InCustomMode() && UserPhysicalPresent())) {
1086 //
1087 // Time-based, verify against X509 Cert KEK.
1088 //
1089 return VerifyTimeBasedPayload (
1090 VariableName,
1091 VendorGuid,
1092 Data,
1093 DataSize,
1094 Variable,
1095 Attributes,
1096 AuthVarTypeKek,
1097 NULL
1098 );
1099 } else {
1100 //
1101 // If in setup mode or custom secure boot mode, no authentication needed.
1102 //
1103 Payload = (UINT8 *) Data + AUTHINFO2_SIZE (Data);
1104 PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
1105
1106 Status = CheckSignatureListFormat(VariableName, VendorGuid, Payload, PayloadSize);
1107 if (EFI_ERROR (Status)) {
1108 return Status;
1109 }
1110
1111 Status = UpdateVariable (
1112 VariableName,
1113 VendorGuid,
1114 Payload,
1115 PayloadSize,
1116 Attributes,
1117 0,
1118 0,
1119 Variable,
1120 &((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->TimeStamp
1121 );
1122 }
1123
1124 return Status;
1125 }
1126
1127 /**
1128 Process variable with EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS/EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS set
1129
1130 Caution: This function may receive untrusted input.
1131 This function may be invoked in SMM mode, and datasize and data are external input.
1132 This function will do basic validation, before parse the data.
1133 This function will parse the authentication carefully to avoid security issues, like
1134 buffer overflow, integer overflow.
1135 This function will check attribute carefully to avoid authentication bypass.
1136
1137 @param[in] VariableName Name of Variable to be found.
1138 @param[in] VendorGuid Variable vendor GUID.
1139
1140 @param[in] Data Data pointer.
1141 @param[in] DataSize Size of Data found. If size is less than the
1142 data, this value contains the required size.
1143 @param[in] Variable The variable information which is used to keep track of variable usage.
1144 @param[in] Attributes Attribute value of the variable.
1145
1146 @return EFI_INVALID_PARAMETER Invalid parameter.
1147 @return EFI_WRITE_PROTECTED Variable is write-protected and needs authentication with
1148 EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS set.
1149 @return EFI_OUT_OF_RESOURCES The Database to save the public key is full.
1150 @return EFI_SECURITY_VIOLATION The variable is with EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
1151 set, but the AuthInfo does NOT pass the validation
1152 check carried out by the firmware.
1153 @return EFI_SUCCESS Variable is not write-protected or pass validation successfully.
1154
1155 **/
1156 EFI_STATUS
1157 ProcessVariable (
1158 IN CHAR16 *VariableName,
1159 IN EFI_GUID *VendorGuid,
1160 IN VOID *Data,
1161 IN UINTN DataSize,
1162 IN VARIABLE_POINTER_TRACK *Variable,
1163 IN UINT32 Attributes
1164 )
1165 {
1166 EFI_STATUS Status;
1167 BOOLEAN IsDeletion;
1168 BOOLEAN IsFirstTime;
1169 UINT8 *PubKey;
1170 EFI_VARIABLE_AUTHENTICATION *CertData;
1171 EFI_CERT_BLOCK_RSA_2048_SHA256 *CertBlock;
1172 UINT32 KeyIndex;
1173 UINT64 MonotonicCount;
1174
1175 KeyIndex = 0;
1176 CertData = NULL;
1177 CertBlock = NULL;
1178 PubKey = NULL;
1179 IsDeletion = FALSE;
1180
1181 if (NeedPhysicallyPresent(VariableName, VendorGuid) && !UserPhysicalPresent()) {
1182 //
1183 // This variable is protected, only physical present user could modify its value.
1184 //
1185 return EFI_SECURITY_VIOLATION;
1186 }
1187
1188 //
1189 // A time-based authenticated variable and a count-based authenticated variable
1190 // can't be updated by each other.
1191 //
1192 if (Variable->CurrPtr != NULL) {
1193 if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) &&
1194 ((Variable->CurrPtr->Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0)) {
1195 return EFI_SECURITY_VIOLATION;
1196 }
1197
1198 if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) &&
1199 ((Variable->CurrPtr->Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0)) {
1200 return EFI_SECURITY_VIOLATION;
1201 }
1202 }
1203
1204 //
1205 // Process Time-based Authenticated variable.
1206 //
1207 if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) {
1208 return VerifyTimeBasedPayload (
1209 VariableName,
1210 VendorGuid,
1211 Data,
1212 DataSize,
1213 Variable,
1214 Attributes,
1215 AuthVarTypePriv,
1216 NULL
1217 );
1218 }
1219
1220 //
1221 // Determine if first time SetVariable with the EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS.
1222 //
1223 if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) {
1224 //
1225 // Determine current operation type.
1226 //
1227 if (DataSize == AUTHINFO_SIZE) {
1228 IsDeletion = TRUE;
1229 }
1230 //
1231 // Determine whether this is the first time with EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS set.
1232 //
1233 if (Variable->CurrPtr == NULL) {
1234 IsFirstTime = TRUE;
1235 } else if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == 0) {
1236 IsFirstTime = TRUE;
1237 } else {
1238 KeyIndex = Variable->CurrPtr->PubKeyIndex;
1239 IsFirstTime = FALSE;
1240 }
1241 } else if ((Variable->CurrPtr != NULL) &&
1242 ((Variable->CurrPtr->Attributes & (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) != 0)
1243 ) {
1244 //
1245 // If the variable is already write-protected, it always needs authentication before update.
1246 //
1247 return EFI_WRITE_PROTECTED;
1248 } else {
1249 //
1250 // If without EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS, set and attributes collision.
1251 // That means it is not authenticated variable, just update variable as usual.
1252 //
1253 Status = UpdateVariable (VariableName, VendorGuid, Data, DataSize, Attributes, 0, 0, Variable, NULL);
1254 return Status;
1255 }
1256
1257 //
1258 // Get PubKey and check Monotonic Count value corresponding to the variable.
1259 //
1260 CertData = (EFI_VARIABLE_AUTHENTICATION *) Data;
1261 CertBlock = (EFI_CERT_BLOCK_RSA_2048_SHA256 *) (CertData->AuthInfo.CertData);
1262 PubKey = CertBlock->PublicKey;
1263
1264 //
1265 // Update Monotonic Count value.
1266 //
1267 MonotonicCount = CertData->MonotonicCount;
1268
1269 if (!IsFirstTime) {
1270 //
1271 // Check input PubKey.
1272 //
1273 if (CompareMem (PubKey, mPubKeyStore + (KeyIndex - 1) * EFI_CERT_TYPE_RSA2048_SIZE, EFI_CERT_TYPE_RSA2048_SIZE) != 0) {
1274 return EFI_SECURITY_VIOLATION;
1275 }
1276 //
1277 // Compare the current monotonic count and ensure that it is greater than the last SetVariable
1278 // operation with the EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS attribute set.
1279 //
1280 if (CertData->MonotonicCount <= Variable->CurrPtr->MonotonicCount) {
1281 //
1282 // Monotonic count check fail, suspicious replay attack, return EFI_SECURITY_VIOLATION.
1283 //
1284 return EFI_SECURITY_VIOLATION;
1285 }
1286 }
1287 //
1288 // Verify the certificate in Data payload.
1289 //
1290 Status = VerifyCounterBasedPayload (Data, DataSize, PubKey);
1291 if (EFI_ERROR (Status)) {
1292 return Status;
1293 }
1294
1295 //
1296 // Now, the signature has been verified!
1297 //
1298 if (IsFirstTime && !IsDeletion) {
1299 //
1300 // Update public key database variable if need.
1301 //
1302 KeyIndex = AddPubKeyInStore (PubKey);
1303 if (KeyIndex == 0) {
1304 return EFI_OUT_OF_RESOURCES;
1305 }
1306 }
1307
1308 //
1309 // Verification pass.
1310 //
1311 return UpdateVariable (VariableName, VendorGuid, (UINT8*)Data + AUTHINFO_SIZE, DataSize - AUTHINFO_SIZE, Attributes, KeyIndex, MonotonicCount, Variable, NULL);
1312 }
1313
1314 /**
1315 Merge two buffers which formatted as EFI_SIGNATURE_LIST. Only the new EFI_SIGNATURE_DATA
1316 will be appended to the original EFI_SIGNATURE_LIST, duplicate EFI_SIGNATURE_DATA
1317 will be ignored.
1318
1319 @param[in, out] Data Pointer to original EFI_SIGNATURE_LIST.
1320 @param[in] DataSize Size of Data buffer.
1321 @param[in] FreeBufSize Size of free data buffer
1322 @param[in] NewData Pointer to new EFI_SIGNATURE_LIST to be appended.
1323 @param[in] NewDataSize Size of NewData buffer.
1324 @param[out] MergedBufSize Size of the merged buffer
1325
1326 @return EFI_BUFFER_TOO_SMALL if input Data buffer overflowed
1327
1328 **/
1329 EFI_STATUS
1330 AppendSignatureList (
1331 IN OUT VOID *Data,
1332 IN UINTN DataSize,
1333 IN UINTN FreeBufSize,
1334 IN VOID *NewData,
1335 IN UINTN NewDataSize,
1336 OUT UINTN *MergedBufSize
1337 )
1338 {
1339 EFI_SIGNATURE_LIST *CertList;
1340 EFI_SIGNATURE_DATA *Cert;
1341 UINTN CertCount;
1342 EFI_SIGNATURE_LIST *NewCertList;
1343 EFI_SIGNATURE_DATA *NewCert;
1344 UINTN NewCertCount;
1345 UINTN Index;
1346 UINTN Index2;
1347 UINTN Size;
1348 UINT8 *Tail;
1349 UINTN CopiedCount;
1350 UINTN SignatureListSize;
1351 BOOLEAN IsNewCert;
1352
1353 Tail = (UINT8 *) Data + DataSize;
1354
1355 NewCertList = (EFI_SIGNATURE_LIST *) NewData;
1356 while ((NewDataSize > 0) && (NewDataSize >= NewCertList->SignatureListSize)) {
1357 NewCert = (EFI_SIGNATURE_DATA *) ((UINT8 *) NewCertList + sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize);
1358 NewCertCount = (NewCertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - NewCertList->SignatureHeaderSize) / NewCertList->SignatureSize;
1359
1360 CopiedCount = 0;
1361 for (Index = 0; Index < NewCertCount; Index++) {
1362 IsNewCert = TRUE;
1363
1364 Size = DataSize;
1365 CertList = (EFI_SIGNATURE_LIST *) Data;
1366 while ((Size > 0) && (Size >= CertList->SignatureListSize)) {
1367 if (CompareGuid (&CertList->SignatureType, &NewCertList->SignatureType) &&
1368 (CertList->SignatureSize == NewCertList->SignatureSize)) {
1369 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1370 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1371 for (Index2 = 0; Index2 < CertCount; Index2++) {
1372 //
1373 // Iterate each Signature Data in this Signature List.
1374 //
1375 if (CompareMem (NewCert, Cert, CertList->SignatureSize) == 0) {
1376 IsNewCert = FALSE;
1377 break;
1378 }
1379 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
1380 }
1381 }
1382
1383 if (!IsNewCert) {
1384 break;
1385 }
1386 Size -= CertList->SignatureListSize;
1387 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1388 }
1389
1390 if (IsNewCert) {
1391 //
1392 // New EFI_SIGNATURE_DATA, append it.
1393 //
1394 if (CopiedCount == 0) {
1395 if (FreeBufSize < sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize) {
1396 return EFI_BUFFER_TOO_SMALL;
1397 }
1398
1399 //
1400 // Copy EFI_SIGNATURE_LIST header for only once.
1401 //
1402
1403 CopyMem (Tail, NewCertList, sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize);
1404 Tail = Tail + sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize;
1405 FreeBufSize -= sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize;
1406 }
1407
1408 if (FreeBufSize < NewCertList->SignatureSize) {
1409 return EFI_BUFFER_TOO_SMALL;
1410 }
1411 CopyMem (Tail, NewCert, NewCertList->SignatureSize);
1412 Tail += NewCertList->SignatureSize;
1413 FreeBufSize -= NewCertList->SignatureSize;
1414 CopiedCount++;
1415 }
1416
1417 NewCert = (EFI_SIGNATURE_DATA *) ((UINT8 *) NewCert + NewCertList->SignatureSize);
1418 }
1419
1420 //
1421 // Update SignatureListSize in newly appended EFI_SIGNATURE_LIST.
1422 //
1423 if (CopiedCount != 0) {
1424 SignatureListSize = sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize + (CopiedCount * NewCertList->SignatureSize);
1425 CertList = (EFI_SIGNATURE_LIST *) (Tail - SignatureListSize);
1426 CertList->SignatureListSize = (UINT32) SignatureListSize;
1427 }
1428
1429 NewDataSize -= NewCertList->SignatureListSize;
1430 NewCertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) NewCertList + NewCertList->SignatureListSize);
1431 }
1432
1433 *MergedBufSize = (Tail - (UINT8 *) Data);
1434 return EFI_SUCCESS;
1435 }
1436
1437 /**
1438 Compare two EFI_TIME data.
1439
1440
1441 @param FirstTime A pointer to the first EFI_TIME data.
1442 @param SecondTime A pointer to the second EFI_TIME data.
1443
1444 @retval TRUE The FirstTime is not later than the SecondTime.
1445 @retval FALSE The FirstTime is later than the SecondTime.
1446
1447 **/
1448 BOOLEAN
1449 CompareTimeStamp (
1450 IN EFI_TIME *FirstTime,
1451 IN EFI_TIME *SecondTime
1452 )
1453 {
1454 if (FirstTime->Year != SecondTime->Year) {
1455 return (BOOLEAN) (FirstTime->Year < SecondTime->Year);
1456 } else if (FirstTime->Month != SecondTime->Month) {
1457 return (BOOLEAN) (FirstTime->Month < SecondTime->Month);
1458 } else if (FirstTime->Day != SecondTime->Day) {
1459 return (BOOLEAN) (FirstTime->Day < SecondTime->Day);
1460 } else if (FirstTime->Hour != SecondTime->Hour) {
1461 return (BOOLEAN) (FirstTime->Hour < SecondTime->Hour);
1462 } else if (FirstTime->Minute != SecondTime->Minute) {
1463 return (BOOLEAN) (FirstTime->Minute < SecondTime->Minute);
1464 }
1465
1466 return (BOOLEAN) (FirstTime->Second <= SecondTime->Second);
1467 }
1468
1469 /**
1470 Find matching signer's certificates for common authenticated variable
1471 by corresponding VariableName and VendorGuid from "certdb".
1472
1473 The data format of "certdb":
1474 //
1475 // UINT32 CertDbListSize;
1476 // /// AUTH_CERT_DB_DATA Certs1[];
1477 // /// AUTH_CERT_DB_DATA Certs2[];
1478 // /// ...
1479 // /// AUTH_CERT_DB_DATA Certsn[];
1480 //
1481
1482 @param[in] VariableName Name of authenticated Variable.
1483 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1484 @param[in] Data Pointer to variable "certdb".
1485 @param[in] DataSize Size of variable "certdb".
1486 @param[out] CertOffset Offset of matching CertData, from starting of Data.
1487 @param[out] CertDataSize Length of CertData in bytes.
1488 @param[out] CertNodeOffset Offset of matching AUTH_CERT_DB_DATA , from
1489 starting of Data.
1490 @param[out] CertNodeSize Length of AUTH_CERT_DB_DATA in bytes.
1491
1492 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1493 @retval EFI_NOT_FOUND Fail to find matching certs.
1494 @retval EFI_SUCCESS Find matching certs and output parameters.
1495
1496 **/
1497 EFI_STATUS
1498 FindCertsFromDb (
1499 IN CHAR16 *VariableName,
1500 IN EFI_GUID *VendorGuid,
1501 IN UINT8 *Data,
1502 IN UINTN DataSize,
1503 OUT UINT32 *CertOffset, OPTIONAL
1504 OUT UINT32 *CertDataSize, OPTIONAL
1505 OUT UINT32 *CertNodeOffset,OPTIONAL
1506 OUT UINT32 *CertNodeSize OPTIONAL
1507 )
1508 {
1509 UINT32 Offset;
1510 AUTH_CERT_DB_DATA *Ptr;
1511 UINT32 CertSize;
1512 UINT32 NameSize;
1513 UINT32 NodeSize;
1514 UINT32 CertDbListSize;
1515
1516 if ((VariableName == NULL) || (VendorGuid == NULL) || (Data == NULL)) {
1517 return EFI_INVALID_PARAMETER;
1518 }
1519
1520 //
1521 // Check whether DataSize matches recorded CertDbListSize.
1522 //
1523 if (DataSize < sizeof (UINT32)) {
1524 return EFI_INVALID_PARAMETER;
1525 }
1526
1527 CertDbListSize = ReadUnaligned32 ((UINT32 *) Data);
1528
1529 if (CertDbListSize != (UINT32) DataSize) {
1530 return EFI_INVALID_PARAMETER;
1531 }
1532
1533 Offset = sizeof (UINT32);
1534
1535 //
1536 // Get corresponding certificates by VendorGuid and VariableName.
1537 //
1538 while (Offset < (UINT32) DataSize) {
1539 Ptr = (AUTH_CERT_DB_DATA *) (Data + Offset);
1540 //
1541 // Check whether VendorGuid matches.
1542 //
1543 if (CompareGuid (&Ptr->VendorGuid, VendorGuid)) {
1544 NodeSize = ReadUnaligned32 (&Ptr->CertNodeSize);
1545 NameSize = ReadUnaligned32 (&Ptr->NameSize);
1546 CertSize = ReadUnaligned32 (&Ptr->CertDataSize);
1547
1548 if (NodeSize != sizeof (EFI_GUID) + sizeof (UINT32) * 3 + CertSize +
1549 sizeof (CHAR16) * NameSize) {
1550 return EFI_INVALID_PARAMETER;
1551 }
1552
1553 Offset = Offset + sizeof (EFI_GUID) + sizeof (UINT32) * 3;
1554 //
1555 // Check whether VariableName matches.
1556 //
1557 if ((NameSize == StrLen (VariableName)) &&
1558 (CompareMem (Data + Offset, VariableName, NameSize * sizeof (CHAR16)) == 0)) {
1559 Offset = Offset + NameSize * sizeof (CHAR16);
1560
1561 if (CertOffset != NULL) {
1562 *CertOffset = Offset;
1563 }
1564
1565 if (CertDataSize != NULL) {
1566 *CertDataSize = CertSize;
1567 }
1568
1569 if (CertNodeOffset != NULL) {
1570 *CertNodeOffset = (UINT32) ((UINT8 *) Ptr - Data);
1571 }
1572
1573 if (CertNodeSize != NULL) {
1574 *CertNodeSize = NodeSize;
1575 }
1576
1577 return EFI_SUCCESS;
1578 } else {
1579 Offset = Offset + NameSize * sizeof (CHAR16) + CertSize;
1580 }
1581 } else {
1582 NodeSize = ReadUnaligned32 (&Ptr->CertNodeSize);
1583 Offset = Offset + NodeSize;
1584 }
1585 }
1586
1587 return EFI_NOT_FOUND;
1588 }
1589
1590 /**
1591 Retrieve signer's certificates for common authenticated variable
1592 by corresponding VariableName and VendorGuid from "certdb".
1593
1594 @param[in] VariableName Name of authenticated Variable.
1595 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1596 @param[out] CertData Pointer to signer's certificates.
1597 @param[out] CertDataSize Length of CertData in bytes.
1598
1599 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1600 @retval EFI_NOT_FOUND Fail to find "certdb" or matching certs.
1601 @retval EFI_SUCCESS Get signer's certificates successfully.
1602
1603 **/
1604 EFI_STATUS
1605 GetCertsFromDb (
1606 IN CHAR16 *VariableName,
1607 IN EFI_GUID *VendorGuid,
1608 OUT UINT8 **CertData,
1609 OUT UINT32 *CertDataSize
1610 )
1611 {
1612 VARIABLE_POINTER_TRACK CertDbVariable;
1613 EFI_STATUS Status;
1614 UINT8 *Data;
1615 UINTN DataSize;
1616 UINT32 CertOffset;
1617
1618 if ((VariableName == NULL) || (VendorGuid == NULL) || (CertData == NULL) || (CertDataSize == NULL)) {
1619 return EFI_INVALID_PARAMETER;
1620 }
1621
1622 //
1623 // Get variable "certdb".
1624 //
1625 Status = FindVariable (
1626 EFI_CERT_DB_NAME,
1627 &gEfiCertDbGuid,
1628 &CertDbVariable,
1629 &mVariableModuleGlobal->VariableGlobal,
1630 FALSE
1631 );
1632 if (EFI_ERROR (Status)) {
1633 return Status;
1634 }
1635
1636 DataSize = DataSizeOfVariable (CertDbVariable.CurrPtr);
1637 Data = GetVariableDataPtr (CertDbVariable.CurrPtr);
1638 if ((DataSize == 0) || (Data == NULL)) {
1639 ASSERT (FALSE);
1640 return EFI_NOT_FOUND;
1641 }
1642
1643 Status = FindCertsFromDb (
1644 VariableName,
1645 VendorGuid,
1646 Data,
1647 DataSize,
1648 &CertOffset,
1649 CertDataSize,
1650 NULL,
1651 NULL
1652 );
1653
1654 if (EFI_ERROR (Status)) {
1655 return Status;
1656 }
1657
1658 *CertData = Data + CertOffset;
1659 return EFI_SUCCESS;
1660 }
1661
1662 /**
1663 Delete matching signer's certificates when deleting common authenticated
1664 variable by corresponding VariableName and VendorGuid from "certdb".
1665
1666 @param[in] VariableName Name of authenticated Variable.
1667 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1668
1669 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1670 @retval EFI_NOT_FOUND Fail to find "certdb" or matching certs.
1671 @retval EFI_OUT_OF_RESOURCES The operation is failed due to lack of resources.
1672 @retval EFI_SUCCESS The operation is completed successfully.
1673
1674 **/
1675 EFI_STATUS
1676 DeleteCertsFromDb (
1677 IN CHAR16 *VariableName,
1678 IN EFI_GUID *VendorGuid
1679 )
1680 {
1681 VARIABLE_POINTER_TRACK CertDbVariable;
1682 EFI_STATUS Status;
1683 UINT8 *Data;
1684 UINTN DataSize;
1685 UINT32 VarAttr;
1686 UINT32 CertNodeOffset;
1687 UINT32 CertNodeSize;
1688 UINT8 *NewCertDb;
1689 UINT32 NewCertDbSize;
1690
1691 if ((VariableName == NULL) || (VendorGuid == NULL)) {
1692 return EFI_INVALID_PARAMETER;
1693 }
1694
1695 //
1696 // Get variable "certdb".
1697 //
1698 Status = FindVariable (
1699 EFI_CERT_DB_NAME,
1700 &gEfiCertDbGuid,
1701 &CertDbVariable,
1702 &mVariableModuleGlobal->VariableGlobal,
1703 FALSE
1704 );
1705 if (EFI_ERROR (Status)) {
1706 return Status;
1707 }
1708
1709 DataSize = DataSizeOfVariable (CertDbVariable.CurrPtr);
1710 Data = GetVariableDataPtr (CertDbVariable.CurrPtr);
1711 if ((DataSize == 0) || (Data == NULL)) {
1712 ASSERT (FALSE);
1713 return EFI_NOT_FOUND;
1714 }
1715
1716 if (DataSize == sizeof (UINT32)) {
1717 //
1718 // There is no certs in certdb.
1719 //
1720 return EFI_SUCCESS;
1721 }
1722
1723 //
1724 // Get corresponding cert node from certdb.
1725 //
1726 Status = FindCertsFromDb (
1727 VariableName,
1728 VendorGuid,
1729 Data,
1730 DataSize,
1731 NULL,
1732 NULL,
1733 &CertNodeOffset,
1734 &CertNodeSize
1735 );
1736
1737 if (EFI_ERROR (Status)) {
1738 return Status;
1739 }
1740
1741 if (DataSize < (CertNodeOffset + CertNodeSize)) {
1742 return EFI_NOT_FOUND;
1743 }
1744
1745 //
1746 // Construct new data content of variable "certdb".
1747 //
1748 NewCertDbSize = (UINT32) DataSize - CertNodeSize;
1749 NewCertDb = (UINT8*) mCertDbStore;
1750
1751 //
1752 // Copy the DB entries before deleting node.
1753 //
1754 CopyMem (NewCertDb, Data, CertNodeOffset);
1755 //
1756 // Update CertDbListSize.
1757 //
1758 CopyMem (NewCertDb, &NewCertDbSize, sizeof (UINT32));
1759 //
1760 // Copy the DB entries after deleting node.
1761 //
1762 if (DataSize > (CertNodeOffset + CertNodeSize)) {
1763 CopyMem (
1764 NewCertDb + CertNodeOffset,
1765 Data + CertNodeOffset + CertNodeSize,
1766 DataSize - CertNodeOffset - CertNodeSize
1767 );
1768 }
1769
1770 //
1771 // Set "certdb".
1772 //
1773 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
1774 Status = UpdateVariable (
1775 EFI_CERT_DB_NAME,
1776 &gEfiCertDbGuid,
1777 NewCertDb,
1778 NewCertDbSize,
1779 VarAttr,
1780 0,
1781 0,
1782 &CertDbVariable,
1783 NULL
1784 );
1785
1786 return Status;
1787 }
1788
1789 /**
1790 Insert signer's certificates for common authenticated variable with VariableName
1791 and VendorGuid in AUTH_CERT_DB_DATA to "certdb".
1792
1793 @param[in] VariableName Name of authenticated Variable.
1794 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1795 @param[in] CertData Pointer to signer's certificates.
1796 @param[in] CertDataSize Length of CertData in bytes.
1797
1798 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1799 @retval EFI_ACCESS_DENIED An AUTH_CERT_DB_DATA entry with same VariableName
1800 and VendorGuid already exists.
1801 @retval EFI_OUT_OF_RESOURCES The operation is failed due to lack of resources.
1802 @retval EFI_SUCCESS Insert an AUTH_CERT_DB_DATA entry to "certdb"
1803
1804 **/
1805 EFI_STATUS
1806 InsertCertsToDb (
1807 IN CHAR16 *VariableName,
1808 IN EFI_GUID *VendorGuid,
1809 IN UINT8 *CertData,
1810 IN UINTN CertDataSize
1811 )
1812 {
1813 VARIABLE_POINTER_TRACK CertDbVariable;
1814 EFI_STATUS Status;
1815 UINT8 *Data;
1816 UINTN DataSize;
1817 UINT32 VarAttr;
1818 UINT8 *NewCertDb;
1819 UINT32 NewCertDbSize;
1820 UINT32 CertNodeSize;
1821 UINT32 NameSize;
1822 AUTH_CERT_DB_DATA *Ptr;
1823
1824 if ((VariableName == NULL) || (VendorGuid == NULL) || (CertData == NULL)) {
1825 return EFI_INVALID_PARAMETER;
1826 }
1827
1828 //
1829 // Get variable "certdb".
1830 //
1831 Status = FindVariable (
1832 EFI_CERT_DB_NAME,
1833 &gEfiCertDbGuid,
1834 &CertDbVariable,
1835 &mVariableModuleGlobal->VariableGlobal,
1836 FALSE
1837 );
1838 if (EFI_ERROR (Status)) {
1839 return Status;
1840 }
1841
1842 DataSize = DataSizeOfVariable (CertDbVariable.CurrPtr);
1843 Data = GetVariableDataPtr (CertDbVariable.CurrPtr);
1844 if ((DataSize == 0) || (Data == NULL)) {
1845 ASSERT (FALSE);
1846 return EFI_NOT_FOUND;
1847 }
1848
1849 //
1850 // Find whether matching cert node already exists in "certdb".
1851 // If yes return error.
1852 //
1853 Status = FindCertsFromDb (
1854 VariableName,
1855 VendorGuid,
1856 Data,
1857 DataSize,
1858 NULL,
1859 NULL,
1860 NULL,
1861 NULL
1862 );
1863
1864 if (!EFI_ERROR (Status)) {
1865 ASSERT (FALSE);
1866 return EFI_ACCESS_DENIED;
1867 }
1868
1869 //
1870 // Construct new data content of variable "certdb".
1871 //
1872 NameSize = (UINT32) StrLen (VariableName);
1873 CertNodeSize = sizeof (AUTH_CERT_DB_DATA) + (UINT32) CertDataSize + NameSize * sizeof (CHAR16);
1874 NewCertDbSize = (UINT32) DataSize + CertNodeSize;
1875 if (NewCertDbSize > MAX_CERTDB_SIZE) {
1876 return EFI_OUT_OF_RESOURCES;
1877 }
1878 NewCertDb = (UINT8*) mCertDbStore;
1879
1880 //
1881 // Copy the DB entries before deleting node.
1882 //
1883 CopyMem (NewCertDb, Data, DataSize);
1884 //
1885 // Update CertDbListSize.
1886 //
1887 CopyMem (NewCertDb, &NewCertDbSize, sizeof (UINT32));
1888 //
1889 // Construct new cert node.
1890 //
1891 Ptr = (AUTH_CERT_DB_DATA *) (NewCertDb + DataSize);
1892 CopyGuid (&Ptr->VendorGuid, VendorGuid);
1893 CopyMem (&Ptr->CertNodeSize, &CertNodeSize, sizeof (UINT32));
1894 CopyMem (&Ptr->NameSize, &NameSize, sizeof (UINT32));
1895 CopyMem (&Ptr->CertDataSize, &CertDataSize, sizeof (UINT32));
1896
1897 CopyMem (
1898 (UINT8 *) Ptr + sizeof (AUTH_CERT_DB_DATA),
1899 VariableName,
1900 NameSize * sizeof (CHAR16)
1901 );
1902
1903 CopyMem (
1904 (UINT8 *) Ptr + sizeof (AUTH_CERT_DB_DATA) + NameSize * sizeof (CHAR16),
1905 CertData,
1906 CertDataSize
1907 );
1908
1909 //
1910 // Set "certdb".
1911 //
1912 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
1913 Status = UpdateVariable (
1914 EFI_CERT_DB_NAME,
1915 &gEfiCertDbGuid,
1916 NewCertDb,
1917 NewCertDbSize,
1918 VarAttr,
1919 0,
1920 0,
1921 &CertDbVariable,
1922 NULL
1923 );
1924
1925 return Status;
1926 }
1927
1928 /**
1929 Process variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS set
1930
1931 Caution: This function may receive untrusted input.
1932 This function may be invoked in SMM mode, and datasize and data are external input.
1933 This function will do basic validation, before parse the data.
1934 This function will parse the authentication carefully to avoid security issues, like
1935 buffer overflow, integer overflow.
1936
1937 @param[in] VariableName Name of Variable to be found.
1938 @param[in] VendorGuid Variable vendor GUID.
1939 @param[in] Data Data pointer.
1940 @param[in] DataSize Size of Data found. If size is less than the
1941 data, this value contains the required size.
1942 @param[in] Variable The variable information which is used to keep track of variable usage.
1943 @param[in] Attributes Attribute value of the variable.
1944 @param[in] AuthVarType Verify against PK, KEK database, private database or certificate in data payload.
1945 @param[out] VarDel Delete the variable or not.
1946
1947 @retval EFI_INVALID_PARAMETER Invalid parameter.
1948 @retval EFI_SECURITY_VIOLATION The variable does NOT pass the validation
1949 check carried out by the firmware.
1950 @retval EFI_OUT_OF_RESOURCES Failed to process variable due to lack
1951 of resources.
1952 @retval EFI_SUCCESS Variable pass validation successfully.
1953
1954 **/
1955 EFI_STATUS
1956 VerifyTimeBasedPayload (
1957 IN CHAR16 *VariableName,
1958 IN EFI_GUID *VendorGuid,
1959 IN VOID *Data,
1960 IN UINTN DataSize,
1961 IN VARIABLE_POINTER_TRACK *Variable,
1962 IN UINT32 Attributes,
1963 IN AUTHVAR_TYPE AuthVarType,
1964 OUT BOOLEAN *VarDel
1965 )
1966 {
1967 UINT8 *RootCert;
1968 UINT8 *SigData;
1969 UINT8 *PayloadPtr;
1970 UINTN RootCertSize;
1971 UINTN Index;
1972 UINTN CertCount;
1973 UINTN PayloadSize;
1974 UINT32 Attr;
1975 UINT32 SigDataSize;
1976 UINT32 KekDataSize;
1977 BOOLEAN VerifyStatus;
1978 EFI_STATUS Status;
1979 EFI_SIGNATURE_LIST *CertList;
1980 EFI_SIGNATURE_DATA *Cert;
1981 VARIABLE_POINTER_TRACK KekVariable;
1982 EFI_VARIABLE_AUTHENTICATION_2 *CertData;
1983 UINT8 *NewData;
1984 UINTN NewDataSize;
1985 VARIABLE_POINTER_TRACK PkVariable;
1986 UINT8 *Buffer;
1987 UINTN Length;
1988 UINT8 *SignerCerts;
1989 UINT8 *WrapSigData;
1990 UINTN CertStackSize;
1991 UINT8 *CertsInCertDb;
1992 UINT32 CertsSizeinDb;
1993
1994 VerifyStatus = FALSE;
1995 CertData = NULL;
1996 NewData = NULL;
1997 Attr = Attributes;
1998 WrapSigData = NULL;
1999 SignerCerts = NULL;
2000 RootCert = NULL;
2001
2002 //
2003 // When the attribute EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS is
2004 // set, then the Data buffer shall begin with an instance of a complete (and serialized)
2005 // EFI_VARIABLE_AUTHENTICATION_2 descriptor. The descriptor shall be followed by the new
2006 // variable value and DataSize shall reflect the combined size of the descriptor and the new
2007 // variable value. The authentication descriptor is not part of the variable data and is not
2008 // returned by subsequent calls to GetVariable().
2009 //
2010 CertData = (EFI_VARIABLE_AUTHENTICATION_2 *) Data;
2011
2012 //
2013 // Verify that Pad1, Nanosecond, TimeZone, Daylight and Pad2 components of the
2014 // TimeStamp value are set to zero.
2015 //
2016 if ((CertData->TimeStamp.Pad1 != 0) ||
2017 (CertData->TimeStamp.Nanosecond != 0) ||
2018 (CertData->TimeStamp.TimeZone != 0) ||
2019 (CertData->TimeStamp.Daylight != 0) ||
2020 (CertData->TimeStamp.Pad2 != 0)) {
2021 return EFI_SECURITY_VIOLATION;
2022 }
2023
2024 if ((Variable->CurrPtr != NULL) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0)) {
2025 if (CompareTimeStamp (&CertData->TimeStamp, &Variable->CurrPtr->TimeStamp)) {
2026 //
2027 // TimeStamp check fail, suspicious replay attack, return EFI_SECURITY_VIOLATION.
2028 //
2029 return EFI_SECURITY_VIOLATION;
2030 }
2031 }
2032
2033 //
2034 // wCertificateType should be WIN_CERT_TYPE_EFI_GUID.
2035 // Cert type should be EFI_CERT_TYPE_PKCS7_GUID.
2036 //
2037 if ((CertData->AuthInfo.Hdr.wCertificateType != WIN_CERT_TYPE_EFI_GUID) ||
2038 !CompareGuid (&CertData->AuthInfo.CertType, &gEfiCertPkcs7Guid)) {
2039 //
2040 // Invalid AuthInfo type, return EFI_SECURITY_VIOLATION.
2041 //
2042 return EFI_SECURITY_VIOLATION;
2043 }
2044
2045 //
2046 // Find out Pkcs7 SignedData which follows the EFI_VARIABLE_AUTHENTICATION_2 descriptor.
2047 // AuthInfo.Hdr.dwLength is the length of the entire certificate, including the length of the header.
2048 //
2049 SigData = CertData->AuthInfo.CertData;
2050 SigDataSize = CertData->AuthInfo.Hdr.dwLength - (UINT32) (OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData));
2051
2052 //
2053 // Find out the new data payload which follows Pkcs7 SignedData directly.
2054 //
2055 PayloadPtr = SigData + SigDataSize;
2056 PayloadSize = DataSize - OFFSET_OF_AUTHINFO2_CERT_DATA - (UINTN) SigDataSize;
2057
2058 //
2059 // Construct a buffer to fill with (VariableName, VendorGuid, Attributes, TimeStamp, Data).
2060 //
2061 NewDataSize = PayloadSize + sizeof (EFI_TIME) + sizeof (UINT32) +
2062 sizeof (EFI_GUID) + StrSize (VariableName) - sizeof (CHAR16);
2063 NewData = mSerializationRuntimeBuffer;
2064
2065 Buffer = NewData;
2066 Length = StrLen (VariableName) * sizeof (CHAR16);
2067 CopyMem (Buffer, VariableName, Length);
2068 Buffer += Length;
2069
2070 Length = sizeof (EFI_GUID);
2071 CopyMem (Buffer, VendorGuid, Length);
2072 Buffer += Length;
2073
2074 Length = sizeof (UINT32);
2075 CopyMem (Buffer, &Attr, Length);
2076 Buffer += Length;
2077
2078 Length = sizeof (EFI_TIME);
2079 CopyMem (Buffer, &CertData->TimeStamp, Length);
2080 Buffer += Length;
2081
2082 CopyMem (Buffer, PayloadPtr, PayloadSize);
2083
2084 if (AuthVarType == AuthVarTypePk) {
2085 //
2086 // Get platform key from variable.
2087 //
2088 Status = FindVariable (
2089 EFI_PLATFORM_KEY_NAME,
2090 &gEfiGlobalVariableGuid,
2091 &PkVariable,
2092 &mVariableModuleGlobal->VariableGlobal,
2093 FALSE
2094 );
2095 if (EFI_ERROR (Status)) {
2096 return Status;
2097 }
2098
2099 CertList = (EFI_SIGNATURE_LIST *) GetVariableDataPtr (PkVariable.CurrPtr);
2100 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2101 RootCert = Cert->SignatureData;
2102 RootCertSize = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);
2103
2104
2105 //
2106 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2107 //
2108 VerifyStatus = Pkcs7Verify (
2109 SigData,
2110 SigDataSize,
2111 RootCert,
2112 RootCertSize,
2113 NewData,
2114 NewDataSize
2115 );
2116
2117 } else if (AuthVarType == AuthVarTypeKek) {
2118
2119 //
2120 // Get KEK database from variable.
2121 //
2122 Status = FindVariable (
2123 EFI_KEY_EXCHANGE_KEY_NAME,
2124 &gEfiGlobalVariableGuid,
2125 &KekVariable,
2126 &mVariableModuleGlobal->VariableGlobal,
2127 FALSE
2128 );
2129 if (EFI_ERROR (Status)) {
2130 return Status;
2131 }
2132
2133 //
2134 // Ready to verify Pkcs7 SignedData. Go through KEK Signature Database to find out X.509 CertList.
2135 //
2136 KekDataSize = KekVariable.CurrPtr->DataSize;
2137 CertList = (EFI_SIGNATURE_LIST *) GetVariableDataPtr (KekVariable.CurrPtr);
2138 while ((KekDataSize > 0) && (KekDataSize >= CertList->SignatureListSize)) {
2139 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
2140 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2141 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
2142 for (Index = 0; Index < CertCount; Index++) {
2143 //
2144 // Iterate each Signature Data Node within this CertList for a verify
2145 //
2146 RootCert = Cert->SignatureData;
2147 RootCertSize = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);
2148
2149 //
2150 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2151 //
2152 VerifyStatus = Pkcs7Verify (
2153 SigData,
2154 SigDataSize,
2155 RootCert,
2156 RootCertSize,
2157 NewData,
2158 NewDataSize
2159 );
2160 if (VerifyStatus) {
2161 goto Exit;
2162 }
2163 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
2164 }
2165 }
2166 KekDataSize -= CertList->SignatureListSize;
2167 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
2168 }
2169 } else if (AuthVarType == AuthVarTypePriv) {
2170
2171 //
2172 // Process common authenticated variable except PK/KEK/DB/DBX.
2173 // Get signer's certificates from SignedData.
2174 //
2175 VerifyStatus = Pkcs7GetSigners (
2176 SigData,
2177 SigDataSize,
2178 &SignerCerts,
2179 &CertStackSize,
2180 &RootCert,
2181 &RootCertSize
2182 );
2183 if (!VerifyStatus) {
2184 goto Exit;
2185 }
2186
2187 //
2188 // Get previously stored signer's certificates from certdb for existing
2189 // variable. Check whether they are identical with signer's certificates
2190 // in SignedData. If not, return error immediately.
2191 //
2192 if ((Variable->CurrPtr != NULL)) {
2193 VerifyStatus = FALSE;
2194
2195 Status = GetCertsFromDb (VariableName, VendorGuid, &CertsInCertDb, &CertsSizeinDb);
2196 if (EFI_ERROR (Status)) {
2197 goto Exit;
2198 }
2199
2200 if ((CertStackSize != CertsSizeinDb) ||
2201 (CompareMem (SignerCerts, CertsInCertDb, CertsSizeinDb) != 0)) {
2202 goto Exit;
2203 }
2204 }
2205
2206 VerifyStatus = Pkcs7Verify (
2207 SigData,
2208 SigDataSize,
2209 RootCert,
2210 RootCertSize,
2211 NewData,
2212 NewDataSize
2213 );
2214 if (!VerifyStatus) {
2215 goto Exit;
2216 }
2217
2218 //
2219 // Delete signer's certificates when delete the common authenticated variable.
2220 //
2221 if ((PayloadSize == 0) && (Variable->CurrPtr != NULL) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0)) {
2222 Status = DeleteCertsFromDb (VariableName, VendorGuid);
2223 if (EFI_ERROR (Status)) {
2224 VerifyStatus = FALSE;
2225 goto Exit;
2226 }
2227 } else if (Variable->CurrPtr == NULL && PayloadSize != 0) {
2228 //
2229 // Insert signer's certificates when adding a new common authenticated variable.
2230 //
2231 Status = InsertCertsToDb (VariableName, VendorGuid, SignerCerts, CertStackSize);
2232 if (EFI_ERROR (Status)) {
2233 VerifyStatus = FALSE;
2234 goto Exit;
2235 }
2236 }
2237 } else if (AuthVarType == AuthVarTypePayload) {
2238 CertList = (EFI_SIGNATURE_LIST *) PayloadPtr;
2239 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2240 RootCert = Cert->SignatureData;
2241 RootCertSize = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);
2242
2243 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2244 //
2245 VerifyStatus = Pkcs7Verify (
2246 SigData,
2247 SigDataSize,
2248 RootCert,
2249 RootCertSize,
2250 NewData,
2251 NewDataSize
2252 );
2253 } else {
2254 return EFI_SECURITY_VIOLATION;
2255 }
2256
2257 Exit:
2258
2259 if (AuthVarType == AuthVarTypePriv) {
2260 Pkcs7FreeSigners (RootCert);
2261 Pkcs7FreeSigners (SignerCerts);
2262 }
2263
2264 if (!VerifyStatus) {
2265 return EFI_SECURITY_VIOLATION;
2266 }
2267
2268 Status = CheckSignatureListFormat(VariableName, VendorGuid, PayloadPtr, PayloadSize);
2269 if (EFI_ERROR (Status)) {
2270 return Status;
2271 }
2272
2273 if ((PayloadSize == 0) && (VarDel != NULL)) {
2274 *VarDel = TRUE;
2275 }
2276
2277 //
2278 // Final step: Update/Append Variable if it pass Pkcs7Verify
2279 //
2280 return UpdateVariable (
2281 VariableName,
2282 VendorGuid,
2283 PayloadPtr,
2284 PayloadSize,
2285 Attributes,
2286 0,
2287 0,
2288 Variable,
2289 &CertData->TimeStamp
2290 );
2291 }
2292