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