]> git.proxmox.com Git - mirror_edk2.git/blob - SecurityPkg/VariableAuthenticated/RuntimeDxe/AuthService.c
Fix a bug that the invalid public key will never be removed from public key database.
[mirror_edk2.git] / SecurityPkg / VariableAuthenticated / RuntimeDxe / AuthService.c
1 /** @file
2 Implement authentication services for the authenticated variable
3 service in UEFI2.2.
4
5 Caution: This module requires additional review when modified.
6 This driver will have external input - variable data. It may be input in SMM mode.
7 This external input must be validated carefully to avoid security issue like
8 buffer overflow, integer overflow.
9 Variable attribute should also be checked to avoid authentication bypass.
10
11 ProcessVarWithPk(), ProcessVarWithKek() and ProcessVariable() are the function to do
12 variable authentication.
13
14 VerifyTimeBasedPayload() and VerifyCounterBasedPayload() are sub function to do verification.
15 They will do basic validation for authentication data structure, then call crypto library
16 to verify the signature.
17
18 Copyright (c) 2009 - 2013, Intel Corporation. All rights reserved.<BR>
19 This program and the accompanying materials
20 are licensed and made available under the terms and conditions of the BSD License
21 which accompanies this distribution. The full text of the license may be found at
22 http://opensource.org/licenses/bsd-license.php
23
24 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
25 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
26
27 **/
28
29 #include "Variable.h"
30 #include "AuthService.h"
31
32 ///
33 /// Global database array for scratch
34 ///
35 UINT8 mPubKeyStore[MAX_KEYDB_SIZE];
36 UINT32 mPubKeyNumber;
37 UINT8 mCertDbStore[MAX_CERTDB_SIZE];
38 UINT32 mPlatformMode;
39 EFI_GUID mSignatureSupport[] = {EFI_CERT_SHA1_GUID, EFI_CERT_SHA256_GUID, EFI_CERT_RSA2048_GUID, EFI_CERT_X509_GUID};
40 //
41 // Public Exponent of RSA Key.
42 //
43 CONST UINT8 mRsaE[] = { 0x01, 0x00, 0x01 };
44 //
45 // Hash context pointer
46 //
47 VOID *mHashCtx = NULL;
48
49 //
50 // Pointer to runtime buffer.
51 // For "Append" operation to an existing variable, a read/modify/write operation
52 // is supported by firmware internally. Reserve runtime buffer to cache previous
53 // variable data in runtime phase because memory allocation is forbidden in virtual mode.
54 //
55 VOID *mStorageArea = NULL;
56
57 //
58 // The serialization of the values of the VariableName, VendorGuid and Attributes
59 // parameters of the SetVariable() call and the TimeStamp component of the
60 // EFI_VARIABLE_AUTHENTICATION_2 descriptor followed by the variable's new value
61 // i.e. (VariableName, VendorGuid, Attributes, TimeStamp, Data)
62 //
63 UINT8 *mSerializationRuntimeBuffer = NULL;
64
65 //
66 // Requirement for different signature type which have been defined in UEFI spec.
67 // These data are used to peform SignatureList format check while setting PK/KEK variable.
68 //
69 EFI_SIGNATURE_ITEM mSupportSigItem[] = {
70 //{SigType, SigHeaderSize, SigDataSize }
71 {EFI_CERT_SHA256_GUID, 0, 32 },
72 {EFI_CERT_RSA2048_GUID, 0, 256 },
73 {EFI_CERT_RSA2048_SHA256_GUID, 0, 256 },
74 {EFI_CERT_SHA1_GUID, 0, 20 },
75 {EFI_CERT_RSA2048_SHA1_GUID, 0, 256 },
76 {EFI_CERT_X509_GUID, 0, ((UINT32) ~0)},
77 {EFI_CERT_SHA224_GUID, 0, 28 },
78 {EFI_CERT_SHA384_GUID, 0, 48 },
79 {EFI_CERT_SHA512_GUID, 0, 64 }
80 };
81
82 /**
83 Determine whether this operation needs a physical present user.
84
85 @param[in] VariableName Name of the Variable.
86 @param[in] VendorGuid GUID of the Variable.
87
88 @retval TRUE This variable is protected, only a physical present user could set this variable.
89 @retval FALSE This variable is not protected.
90
91 **/
92 BOOLEAN
93 NeedPhysicallyPresent(
94 IN CHAR16 *VariableName,
95 IN EFI_GUID *VendorGuid
96 )
97 {
98 if ((CompareGuid (VendorGuid, &gEfiSecureBootEnableDisableGuid) && (StrCmp (VariableName, EFI_SECURE_BOOT_ENABLE_NAME) == 0))
99 || (CompareGuid (VendorGuid, &gEfiCustomModeEnableGuid) && (StrCmp (VariableName, EFI_CUSTOM_MODE_NAME) == 0))) {
100 return TRUE;
101 }
102
103 return FALSE;
104 }
105
106 /**
107 Determine whether the platform is operating in Custom Secure Boot mode.
108
109 @retval TRUE The platform is operating in Custom mode.
110 @retval FALSE The platform is operating in Standard mode.
111
112 **/
113 BOOLEAN
114 InCustomMode (
115 VOID
116 )
117 {
118 VARIABLE_POINTER_TRACK Variable;
119
120 FindVariable (EFI_CUSTOM_MODE_NAME, &gEfiCustomModeEnableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
121 if (Variable.CurrPtr != NULL && *(GetVariableDataPtr (Variable.CurrPtr)) == CUSTOM_SECURE_BOOT_MODE) {
122 return TRUE;
123 }
124
125 return FALSE;
126 }
127
128
129 /**
130 Internal function to delete a Variable given its name and GUID, no authentication
131 required.
132
133 @param[in] VariableName Name of the Variable.
134 @param[in] VendorGuid GUID of the Variable.
135
136 @retval EFI_SUCCESS Variable deleted successfully.
137 @retval Others The driver failded to start the device.
138
139 **/
140 EFI_STATUS
141 DeleteVariable (
142 IN CHAR16 *VariableName,
143 IN EFI_GUID *VendorGuid
144 )
145 {
146 EFI_STATUS Status;
147 VARIABLE_POINTER_TRACK Variable;
148
149 Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
150 if (EFI_ERROR (Status)) {
151 return EFI_SUCCESS;
152 }
153
154 ASSERT (Variable.CurrPtr != NULL);
155 return UpdateVariable (VariableName, VendorGuid, NULL, 0, 0, 0, 0, &Variable, NULL);
156 }
157
158 /**
159 Initializes for authenticated varibale service.
160
161 @retval EFI_SUCCESS Function successfully executed.
162 @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resources.
163
164 **/
165 EFI_STATUS
166 AutenticatedVariableServiceInitialize (
167 VOID
168 )
169 {
170 EFI_STATUS Status;
171 VARIABLE_POINTER_TRACK Variable;
172 VARIABLE_POINTER_TRACK PkVariable;
173 UINT8 VarValue;
174 UINT32 VarAttr;
175 UINT8 *Data;
176 UINTN DataSize;
177 UINTN CtxSize;
178 UINT8 SecureBootMode;
179 UINT8 SecureBootEnable;
180 UINT8 CustomMode;
181 UINT32 ListSize;
182
183 //
184 // Initialize hash context.
185 //
186 CtxSize = Sha256GetContextSize ();
187 mHashCtx = AllocateRuntimePool (CtxSize);
188 if (mHashCtx == NULL) {
189 return EFI_OUT_OF_RESOURCES;
190 }
191
192 //
193 // Reserved runtime buffer for "Append" operation in virtual mode.
194 //
195 mStorageArea = AllocateRuntimePool (PcdGet32 (PcdMaxVariableSize));
196 if (mStorageArea == NULL) {
197 return EFI_OUT_OF_RESOURCES;
198 }
199
200 //
201 // Prepare runtime buffer for serialized data of time-based authenticated
202 // Variable, i.e. (VariableName, VendorGuid, Attributes, TimeStamp, Data).
203 //
204 mSerializationRuntimeBuffer = AllocateRuntimePool (PcdGet32 (PcdMaxVariableSize) + sizeof (EFI_GUID) + sizeof (UINT32) + sizeof (EFI_TIME));
205 if (mSerializationRuntimeBuffer == NULL) {
206 return EFI_OUT_OF_RESOURCES;
207 }
208
209 //
210 // Check "AuthVarKeyDatabase" variable's existence.
211 // If it doesn't exist, create a new one with initial value of 0 and EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS set.
212 //
213 Status = FindVariable (
214 AUTHVAR_KEYDB_NAME,
215 &gEfiAuthenticatedVariableGuid,
216 &Variable,
217 &mVariableModuleGlobal->VariableGlobal,
218 FALSE
219 );
220
221 if (Variable.CurrPtr == NULL) {
222 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS;
223 VarValue = 0;
224 mPubKeyNumber = 0;
225 Status = UpdateVariable (
226 AUTHVAR_KEYDB_NAME,
227 &gEfiAuthenticatedVariableGuid,
228 &VarValue,
229 sizeof(UINT8),
230 VarAttr,
231 0,
232 0,
233 &Variable,
234 NULL
235 );
236 if (EFI_ERROR (Status)) {
237 return Status;
238 }
239 } else {
240 //
241 // Load database in global variable for cache.
242 //
243 DataSize = DataSizeOfVariable (Variable.CurrPtr);
244 Data = GetVariableDataPtr (Variable.CurrPtr);
245 ASSERT ((DataSize != 0) && (Data != NULL));
246 CopyMem (mPubKeyStore, (UINT8 *) Data, DataSize);
247 mPubKeyNumber = (UINT32) (DataSize / EFI_CERT_TYPE_RSA2048_SIZE);
248 }
249
250 FindVariable (EFI_PLATFORM_KEY_NAME, &gEfiGlobalVariableGuid, &PkVariable, &mVariableModuleGlobal->VariableGlobal, FALSE);
251 if (PkVariable.CurrPtr == NULL) {
252 DEBUG ((EFI_D_INFO, "Variable %s does not exist.\n", EFI_PLATFORM_KEY_NAME));
253 } else {
254 DEBUG ((EFI_D_INFO, "Variable %s exists.\n", EFI_PLATFORM_KEY_NAME));
255 }
256
257 //
258 // Create "SetupMode" varable with BS+RT attribute set.
259 //
260 FindVariable (EFI_SETUP_MODE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
261 if (PkVariable.CurrPtr == NULL) {
262 mPlatformMode = SETUP_MODE;
263 } else {
264 mPlatformMode = USER_MODE;
265 }
266 Status = UpdateVariable (
267 EFI_SETUP_MODE_NAME,
268 &gEfiGlobalVariableGuid,
269 &mPlatformMode,
270 sizeof(UINT8),
271 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
272 0,
273 0,
274 &Variable,
275 NULL
276 );
277 if (EFI_ERROR (Status)) {
278 return Status;
279 }
280
281 //
282 // Create "SignatureSupport" varable with BS+RT attribute set.
283 //
284 FindVariable (EFI_SIGNATURE_SUPPORT_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
285 Status = UpdateVariable (
286 EFI_SIGNATURE_SUPPORT_NAME,
287 &gEfiGlobalVariableGuid,
288 mSignatureSupport,
289 sizeof(mSignatureSupport),
290 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
291 0,
292 0,
293 &Variable,
294 NULL
295 );
296 if (EFI_ERROR (Status)) {
297 return Status;
298 }
299
300 //
301 // If "SecureBootEnable" variable exists, then update "SecureBoot" variable.
302 // If "SecureBootEnable" variable is SECURE_BOOT_ENABLE and in USER_MODE, Set "SecureBoot" variable to SECURE_BOOT_MODE_ENABLE.
303 // If "SecureBootEnable" variable is SECURE_BOOT_DISABLE, Set "SecureBoot" variable to SECURE_BOOT_MODE_DISABLE.
304 //
305 SecureBootEnable = SECURE_BOOT_DISABLE;
306 FindVariable (EFI_SECURE_BOOT_ENABLE_NAME, &gEfiSecureBootEnableDisableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
307 if (Variable.CurrPtr != NULL) {
308 SecureBootEnable = *(GetVariableDataPtr (Variable.CurrPtr));
309 } else if (mPlatformMode == USER_MODE) {
310 //
311 // "SecureBootEnable" not exist, initialize it in USER_MODE.
312 //
313 SecureBootEnable = SECURE_BOOT_ENABLE;
314 Status = UpdateVariable (
315 EFI_SECURE_BOOT_ENABLE_NAME,
316 &gEfiSecureBootEnableDisableGuid,
317 &SecureBootEnable,
318 sizeof (UINT8),
319 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
320 0,
321 0,
322 &Variable,
323 NULL
324 );
325 if (EFI_ERROR (Status)) {
326 return Status;
327 }
328 }
329
330 //
331 // Create "SecureBoot" varable with BS+RT attribute set.
332 //
333 if (SecureBootEnable == SECURE_BOOT_ENABLE && mPlatformMode == USER_MODE) {
334 SecureBootMode = SECURE_BOOT_MODE_ENABLE;
335 } else {
336 SecureBootMode = SECURE_BOOT_MODE_DISABLE;
337 }
338 FindVariable (EFI_SECURE_BOOT_MODE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
339 Status = UpdateVariable (
340 EFI_SECURE_BOOT_MODE_NAME,
341 &gEfiGlobalVariableGuid,
342 &SecureBootMode,
343 sizeof (UINT8),
344 EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS,
345 0,
346 0,
347 &Variable,
348 NULL
349 );
350 if (EFI_ERROR (Status)) {
351 return Status;
352 }
353
354 DEBUG ((EFI_D_INFO, "Variable %s is %x\n", EFI_SETUP_MODE_NAME, mPlatformMode));
355 DEBUG ((EFI_D_INFO, "Variable %s is %x\n", EFI_SECURE_BOOT_MODE_NAME, SecureBootMode));
356 DEBUG ((EFI_D_INFO, "Variable %s is %x\n", EFI_SECURE_BOOT_ENABLE_NAME, SecureBootEnable));
357
358 //
359 // Check "CustomMode" variable's existence.
360 //
361 FindVariable (EFI_CUSTOM_MODE_NAME, &gEfiCustomModeEnableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
362 if (Variable.CurrPtr != NULL) {
363 CustomMode = *(GetVariableDataPtr (Variable.CurrPtr));
364 } else {
365 //
366 // "CustomMode" not exist, initialize it in STANDARD_SECURE_BOOT_MODE.
367 //
368 CustomMode = STANDARD_SECURE_BOOT_MODE;
369 Status = UpdateVariable (
370 EFI_CUSTOM_MODE_NAME,
371 &gEfiCustomModeEnableGuid,
372 &CustomMode,
373 sizeof (UINT8),
374 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
375 0,
376 0,
377 &Variable,
378 NULL
379 );
380 if (EFI_ERROR (Status)) {
381 return Status;
382 }
383 }
384
385 DEBUG ((EFI_D_INFO, "Variable %s is %x\n", EFI_CUSTOM_MODE_NAME, CustomMode));
386
387 //
388 // Check "certdb" variable's existence.
389 // If it doesn't exist, then create a new one with
390 // EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS set.
391 //
392 Status = FindVariable (
393 EFI_CERT_DB_NAME,
394 &gEfiCertDbGuid,
395 &Variable,
396 &mVariableModuleGlobal->VariableGlobal,
397 FALSE
398 );
399
400 if (Variable.CurrPtr == NULL) {
401 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
402 ListSize = sizeof (UINT32);
403 Status = UpdateVariable (
404 EFI_CERT_DB_NAME,
405 &gEfiCertDbGuid,
406 &ListSize,
407 sizeof (UINT32),
408 VarAttr,
409 0,
410 0,
411 &Variable,
412 NULL
413 );
414 if (EFI_ERROR (Status)) {
415 return Status;
416 }
417 }
418
419 return Status;
420 }
421
422 /**
423 Add public key in store and return its index.
424
425 @param[in] PubKey Input pointer to Public Key data
426
427 @return Index of new added item
428
429 **/
430 UINT32
431 AddPubKeyInStore (
432 IN UINT8 *PubKey
433 )
434 {
435 EFI_STATUS Status;
436 BOOLEAN IsFound;
437 UINT32 Index;
438 VARIABLE_POINTER_TRACK Variable;
439 UINT8 *Ptr;
440 UINT8 *Data;
441 UINTN DataSize;
442
443 if (PubKey == NULL) {
444 return 0;
445 }
446
447 Status = FindVariable (
448 AUTHVAR_KEYDB_NAME,
449 &gEfiAuthenticatedVariableGuid,
450 &Variable,
451 &mVariableModuleGlobal->VariableGlobal,
452 FALSE
453 );
454 ASSERT_EFI_ERROR (Status);
455 //
456 // Check whether the public key entry does exist.
457 //
458 IsFound = FALSE;
459 for (Ptr = mPubKeyStore, Index = 1; Index <= mPubKeyNumber; Index++) {
460 if (CompareMem (Ptr, PubKey, EFI_CERT_TYPE_RSA2048_SIZE) == 0) {
461 IsFound = TRUE;
462 break;
463 }
464 Ptr += EFI_CERT_TYPE_RSA2048_SIZE;
465 }
466
467 if (!IsFound) {
468 //
469 // Add public key in database.
470 //
471 if (mPubKeyNumber == MAX_KEY_NUM) {
472 //
473 // Public key dadatase is full, try to reclaim invalid key.
474 //
475 if (AtRuntime ()) {
476 //
477 // NV storage can't reclaim at runtime.
478 //
479 return 0;
480 }
481
482 Status = Reclaim (
483 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
484 &mVariableModuleGlobal->NonVolatileLastVariableOffset,
485 FALSE,
486 NULL,
487 TRUE,
488 TRUE
489 );
490 if (EFI_ERROR (Status)) {
491 return 0;
492 }
493
494 Status = FindVariable (
495 AUTHVAR_KEYDB_NAME,
496 &gEfiAuthenticatedVariableGuid,
497 &Variable,
498 &mVariableModuleGlobal->VariableGlobal,
499 FALSE
500 );
501 ASSERT_EFI_ERROR (Status);
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] NewData Pointer to new EFI_SIGNATURE_LIST to be appended.
1322 @param[in] NewDataSize Size of NewData buffer.
1323
1324 @return Size of the merged buffer.
1325
1326 **/
1327 UINTN
1328 AppendSignatureList (
1329 IN OUT VOID *Data,
1330 IN UINTN DataSize,
1331 IN VOID *NewData,
1332 IN UINTN NewDataSize
1333 )
1334 {
1335 EFI_SIGNATURE_LIST *CertList;
1336 EFI_SIGNATURE_DATA *Cert;
1337 UINTN CertCount;
1338 EFI_SIGNATURE_LIST *NewCertList;
1339 EFI_SIGNATURE_DATA *NewCert;
1340 UINTN NewCertCount;
1341 UINTN Index;
1342 UINTN Index2;
1343 UINTN Size;
1344 UINT8 *Tail;
1345 UINTN CopiedCount;
1346 UINTN SignatureListSize;
1347 BOOLEAN IsNewCert;
1348
1349 Tail = (UINT8 *) Data + DataSize;
1350
1351 NewCertList = (EFI_SIGNATURE_LIST *) NewData;
1352 while ((NewDataSize > 0) && (NewDataSize >= NewCertList->SignatureListSize)) {
1353 NewCert = (EFI_SIGNATURE_DATA *) ((UINT8 *) NewCertList + sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize);
1354 NewCertCount = (NewCertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - NewCertList->SignatureHeaderSize) / NewCertList->SignatureSize;
1355
1356 CopiedCount = 0;
1357 for (Index = 0; Index < NewCertCount; Index++) {
1358 IsNewCert = TRUE;
1359
1360 Size = DataSize;
1361 CertList = (EFI_SIGNATURE_LIST *) Data;
1362 while ((Size > 0) && (Size >= CertList->SignatureListSize)) {
1363 if (CompareGuid (&CertList->SignatureType, &NewCertList->SignatureType) &&
1364 (CertList->SignatureSize == NewCertList->SignatureSize)) {
1365 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1366 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1367 for (Index2 = 0; Index2 < CertCount; Index2++) {
1368 //
1369 // Iterate each Signature Data in this Signature List.
1370 //
1371 if (CompareMem (NewCert, Cert, CertList->SignatureSize) == 0) {
1372 IsNewCert = FALSE;
1373 break;
1374 }
1375 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
1376 }
1377 }
1378
1379 if (!IsNewCert) {
1380 break;
1381 }
1382 Size -= CertList->SignatureListSize;
1383 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1384 }
1385
1386 if (IsNewCert) {
1387 //
1388 // New EFI_SIGNATURE_DATA, append it.
1389 //
1390 if (CopiedCount == 0) {
1391 //
1392 // Copy EFI_SIGNATURE_LIST header for only once.
1393 //
1394 CopyMem (Tail, NewCertList, sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize);
1395 Tail = Tail + sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize;
1396 }
1397
1398 CopyMem (Tail, NewCert, NewCertList->SignatureSize);
1399 Tail += NewCertList->SignatureSize;
1400 CopiedCount++;
1401 }
1402
1403 NewCert = (EFI_SIGNATURE_DATA *) ((UINT8 *) NewCert + NewCertList->SignatureSize);
1404 }
1405
1406 //
1407 // Update SignatureListSize in newly appended EFI_SIGNATURE_LIST.
1408 //
1409 if (CopiedCount != 0) {
1410 SignatureListSize = sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize + (CopiedCount * NewCertList->SignatureSize);
1411 CertList = (EFI_SIGNATURE_LIST *) (Tail - SignatureListSize);
1412 CertList->SignatureListSize = (UINT32) SignatureListSize;
1413 }
1414
1415 NewDataSize -= NewCertList->SignatureListSize;
1416 NewCertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) NewCertList + NewCertList->SignatureListSize);
1417 }
1418
1419 return (Tail - (UINT8 *) Data);
1420 }
1421
1422 /**
1423 Compare two EFI_TIME data.
1424
1425
1426 @param FirstTime A pointer to the first EFI_TIME data.
1427 @param SecondTime A pointer to the second EFI_TIME data.
1428
1429 @retval TRUE The FirstTime is not later than the SecondTime.
1430 @retval FALSE The FirstTime is later than the SecondTime.
1431
1432 **/
1433 BOOLEAN
1434 CompareTimeStamp (
1435 IN EFI_TIME *FirstTime,
1436 IN EFI_TIME *SecondTime
1437 )
1438 {
1439 if (FirstTime->Year != SecondTime->Year) {
1440 return (BOOLEAN) (FirstTime->Year < SecondTime->Year);
1441 } else if (FirstTime->Month != SecondTime->Month) {
1442 return (BOOLEAN) (FirstTime->Month < SecondTime->Month);
1443 } else if (FirstTime->Day != SecondTime->Day) {
1444 return (BOOLEAN) (FirstTime->Day < SecondTime->Day);
1445 } else if (FirstTime->Hour != SecondTime->Hour) {
1446 return (BOOLEAN) (FirstTime->Hour < SecondTime->Hour);
1447 } else if (FirstTime->Minute != SecondTime->Minute) {
1448 return (BOOLEAN) (FirstTime->Minute < SecondTime->Minute);
1449 }
1450
1451 return (BOOLEAN) (FirstTime->Second <= SecondTime->Second);
1452 }
1453
1454 /**
1455 Find matching signer's certificates for common authenticated variable
1456 by corresponding VariableName and VendorGuid from "certdb".
1457
1458 The data format of "certdb":
1459 //
1460 // UINT32 CertDbListSize;
1461 // /// AUTH_CERT_DB_DATA Certs1[];
1462 // /// AUTH_CERT_DB_DATA Certs2[];
1463 // /// ...
1464 // /// AUTH_CERT_DB_DATA Certsn[];
1465 //
1466
1467 @param[in] VariableName Name of authenticated Variable.
1468 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1469 @param[in] Data Pointer to variable "certdb".
1470 @param[in] DataSize Size of variable "certdb".
1471 @param[out] CertOffset Offset of matching CertData, from starting of Data.
1472 @param[out] CertDataSize Length of CertData in bytes.
1473 @param[out] CertNodeOffset Offset of matching AUTH_CERT_DB_DATA , from
1474 starting of Data.
1475 @param[out] CertNodeSize Length of AUTH_CERT_DB_DATA in bytes.
1476
1477 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1478 @retval EFI_NOT_FOUND Fail to find matching certs.
1479 @retval EFI_SUCCESS Find matching certs and output parameters.
1480
1481 **/
1482 EFI_STATUS
1483 FindCertsFromDb (
1484 IN CHAR16 *VariableName,
1485 IN EFI_GUID *VendorGuid,
1486 IN UINT8 *Data,
1487 IN UINTN DataSize,
1488 OUT UINT32 *CertOffset, OPTIONAL
1489 OUT UINT32 *CertDataSize, OPTIONAL
1490 OUT UINT32 *CertNodeOffset,OPTIONAL
1491 OUT UINT32 *CertNodeSize OPTIONAL
1492 )
1493 {
1494 UINT32 Offset;
1495 AUTH_CERT_DB_DATA *Ptr;
1496 UINT32 CertSize;
1497 UINT32 NameSize;
1498 UINT32 NodeSize;
1499 UINT32 CertDbListSize;
1500
1501 if ((VariableName == NULL) || (VendorGuid == NULL) || (Data == NULL)) {
1502 return EFI_INVALID_PARAMETER;
1503 }
1504
1505 //
1506 // Check whether DataSize matches recorded CertDbListSize.
1507 //
1508 if (DataSize < sizeof (UINT32)) {
1509 return EFI_INVALID_PARAMETER;
1510 }
1511
1512 CertDbListSize = ReadUnaligned32 ((UINT32 *) Data);
1513
1514 if (CertDbListSize != (UINT32) DataSize) {
1515 return EFI_INVALID_PARAMETER;
1516 }
1517
1518 Offset = sizeof (UINT32);
1519
1520 //
1521 // Get corresponding certificates by VendorGuid and VariableName.
1522 //
1523 while (Offset < (UINT32) DataSize) {
1524 Ptr = (AUTH_CERT_DB_DATA *) (Data + Offset);
1525 //
1526 // Check whether VendorGuid matches.
1527 //
1528 if (CompareGuid (&Ptr->VendorGuid, VendorGuid)) {
1529 NodeSize = ReadUnaligned32 (&Ptr->CertNodeSize);
1530 NameSize = ReadUnaligned32 (&Ptr->NameSize);
1531 CertSize = ReadUnaligned32 (&Ptr->CertDataSize);
1532
1533 if (NodeSize != sizeof (EFI_GUID) + sizeof (UINT32) * 3 + CertSize +
1534 sizeof (CHAR16) * NameSize) {
1535 return EFI_INVALID_PARAMETER;
1536 }
1537
1538 Offset = Offset + sizeof (EFI_GUID) + sizeof (UINT32) * 3;
1539 //
1540 // Check whether VariableName matches.
1541 //
1542 if ((NameSize == StrLen (VariableName)) &&
1543 (CompareMem (Data + Offset, VariableName, NameSize * sizeof (CHAR16)) == 0)) {
1544 Offset = Offset + NameSize * sizeof (CHAR16);
1545
1546 if (CertOffset != NULL) {
1547 *CertOffset = Offset;
1548 }
1549
1550 if (CertDataSize != NULL) {
1551 *CertDataSize = CertSize;
1552 }
1553
1554 if (CertNodeOffset != NULL) {
1555 *CertNodeOffset = (UINT32) ((UINT8 *) Ptr - Data);
1556 }
1557
1558 if (CertNodeSize != NULL) {
1559 *CertNodeSize = NodeSize;
1560 }
1561
1562 return EFI_SUCCESS;
1563 } else {
1564 Offset = Offset + NameSize * sizeof (CHAR16) + CertSize;
1565 }
1566 } else {
1567 NodeSize = ReadUnaligned32 (&Ptr->CertNodeSize);
1568 Offset = Offset + NodeSize;
1569 }
1570 }
1571
1572 return EFI_NOT_FOUND;
1573 }
1574
1575 /**
1576 Retrieve signer's certificates for common authenticated variable
1577 by corresponding VariableName and VendorGuid from "certdb".
1578
1579 @param[in] VariableName Name of authenticated Variable.
1580 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1581 @param[out] CertData Pointer to signer's certificates.
1582 @param[out] CertDataSize Length of CertData in bytes.
1583
1584 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1585 @retval EFI_NOT_FOUND Fail to find "certdb" or matching certs.
1586 @retval EFI_SUCCESS Get signer's certificates successfully.
1587
1588 **/
1589 EFI_STATUS
1590 GetCertsFromDb (
1591 IN CHAR16 *VariableName,
1592 IN EFI_GUID *VendorGuid,
1593 OUT UINT8 **CertData,
1594 OUT UINT32 *CertDataSize
1595 )
1596 {
1597 VARIABLE_POINTER_TRACK CertDbVariable;
1598 EFI_STATUS Status;
1599 UINT8 *Data;
1600 UINTN DataSize;
1601 UINT32 CertOffset;
1602
1603 if ((VariableName == NULL) || (VendorGuid == NULL) || (CertData == NULL) || (CertDataSize == NULL)) {
1604 return EFI_INVALID_PARAMETER;
1605 }
1606
1607 //
1608 // Get variable "certdb".
1609 //
1610 Status = FindVariable (
1611 EFI_CERT_DB_NAME,
1612 &gEfiCertDbGuid,
1613 &CertDbVariable,
1614 &mVariableModuleGlobal->VariableGlobal,
1615 FALSE
1616 );
1617 if (EFI_ERROR (Status)) {
1618 return Status;
1619 }
1620
1621 DataSize = DataSizeOfVariable (CertDbVariable.CurrPtr);
1622 Data = GetVariableDataPtr (CertDbVariable.CurrPtr);
1623 if ((DataSize == 0) || (Data == NULL)) {
1624 ASSERT (FALSE);
1625 return EFI_NOT_FOUND;
1626 }
1627
1628 Status = FindCertsFromDb (
1629 VariableName,
1630 VendorGuid,
1631 Data,
1632 DataSize,
1633 &CertOffset,
1634 CertDataSize,
1635 NULL,
1636 NULL
1637 );
1638
1639 if (EFI_ERROR (Status)) {
1640 return Status;
1641 }
1642
1643 *CertData = Data + CertOffset;
1644 return EFI_SUCCESS;
1645 }
1646
1647 /**
1648 Delete matching signer's certificates when deleting common authenticated
1649 variable by corresponding VariableName and VendorGuid from "certdb".
1650
1651 @param[in] VariableName Name of authenticated Variable.
1652 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1653
1654 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1655 @retval EFI_NOT_FOUND Fail to find "certdb" or matching certs.
1656 @retval EFI_OUT_OF_RESOURCES The operation is failed due to lack of resources.
1657 @retval EFI_SUCCESS The operation is completed successfully.
1658
1659 **/
1660 EFI_STATUS
1661 DeleteCertsFromDb (
1662 IN CHAR16 *VariableName,
1663 IN EFI_GUID *VendorGuid
1664 )
1665 {
1666 VARIABLE_POINTER_TRACK CertDbVariable;
1667 EFI_STATUS Status;
1668 UINT8 *Data;
1669 UINTN DataSize;
1670 UINT32 VarAttr;
1671 UINT32 CertNodeOffset;
1672 UINT32 CertNodeSize;
1673 UINT8 *NewCertDb;
1674 UINT32 NewCertDbSize;
1675
1676 if ((VariableName == NULL) || (VendorGuid == NULL)) {
1677 return EFI_INVALID_PARAMETER;
1678 }
1679
1680 //
1681 // Get variable "certdb".
1682 //
1683 Status = FindVariable (
1684 EFI_CERT_DB_NAME,
1685 &gEfiCertDbGuid,
1686 &CertDbVariable,
1687 &mVariableModuleGlobal->VariableGlobal,
1688 FALSE
1689 );
1690 if (EFI_ERROR (Status)) {
1691 return Status;
1692 }
1693
1694 DataSize = DataSizeOfVariable (CertDbVariable.CurrPtr);
1695 Data = GetVariableDataPtr (CertDbVariable.CurrPtr);
1696 if ((DataSize == 0) || (Data == NULL)) {
1697 ASSERT (FALSE);
1698 return EFI_NOT_FOUND;
1699 }
1700
1701 if (DataSize == sizeof (UINT32)) {
1702 //
1703 // There is no certs in certdb.
1704 //
1705 return EFI_SUCCESS;
1706 }
1707
1708 //
1709 // Get corresponding cert node from certdb.
1710 //
1711 Status = FindCertsFromDb (
1712 VariableName,
1713 VendorGuid,
1714 Data,
1715 DataSize,
1716 NULL,
1717 NULL,
1718 &CertNodeOffset,
1719 &CertNodeSize
1720 );
1721
1722 if (EFI_ERROR (Status)) {
1723 return Status;
1724 }
1725
1726 if (DataSize < (CertNodeOffset + CertNodeSize)) {
1727 return EFI_NOT_FOUND;
1728 }
1729
1730 //
1731 // Construct new data content of variable "certdb".
1732 //
1733 NewCertDbSize = (UINT32) DataSize - CertNodeSize;
1734 NewCertDb = (UINT8*) mCertDbStore;
1735
1736 //
1737 // Copy the DB entries before deleting node.
1738 //
1739 CopyMem (NewCertDb, Data, CertNodeOffset);
1740 //
1741 // Update CertDbListSize.
1742 //
1743 CopyMem (NewCertDb, &NewCertDbSize, sizeof (UINT32));
1744 //
1745 // Copy the DB entries after deleting node.
1746 //
1747 if (DataSize > (CertNodeOffset + CertNodeSize)) {
1748 CopyMem (
1749 NewCertDb + CertNodeOffset,
1750 Data + CertNodeOffset + CertNodeSize,
1751 DataSize - CertNodeOffset - CertNodeSize
1752 );
1753 }
1754
1755 //
1756 // Set "certdb".
1757 //
1758 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
1759 Status = UpdateVariable (
1760 EFI_CERT_DB_NAME,
1761 &gEfiCertDbGuid,
1762 NewCertDb,
1763 NewCertDbSize,
1764 VarAttr,
1765 0,
1766 0,
1767 &CertDbVariable,
1768 NULL
1769 );
1770
1771 return Status;
1772 }
1773
1774 /**
1775 Insert signer's certificates for common authenticated variable with VariableName
1776 and VendorGuid in AUTH_CERT_DB_DATA to "certdb".
1777
1778 @param[in] VariableName Name of authenticated Variable.
1779 @param[in] VendorGuid Vendor GUID of authenticated Variable.
1780 @param[in] CertData Pointer to signer's certificates.
1781 @param[in] CertDataSize Length of CertData in bytes.
1782
1783 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
1784 @retval EFI_ACCESS_DENIED An AUTH_CERT_DB_DATA entry with same VariableName
1785 and VendorGuid already exists.
1786 @retval EFI_OUT_OF_RESOURCES The operation is failed due to lack of resources.
1787 @retval EFI_SUCCESS Insert an AUTH_CERT_DB_DATA entry to "certdb"
1788
1789 **/
1790 EFI_STATUS
1791 InsertCertsToDb (
1792 IN CHAR16 *VariableName,
1793 IN EFI_GUID *VendorGuid,
1794 IN UINT8 *CertData,
1795 IN UINTN CertDataSize
1796 )
1797 {
1798 VARIABLE_POINTER_TRACK CertDbVariable;
1799 EFI_STATUS Status;
1800 UINT8 *Data;
1801 UINTN DataSize;
1802 UINT32 VarAttr;
1803 UINT8 *NewCertDb;
1804 UINT32 NewCertDbSize;
1805 UINT32 CertNodeSize;
1806 UINT32 NameSize;
1807 AUTH_CERT_DB_DATA *Ptr;
1808
1809 if ((VariableName == NULL) || (VendorGuid == NULL) || (CertData == NULL)) {
1810 return EFI_INVALID_PARAMETER;
1811 }
1812
1813 //
1814 // Get variable "certdb".
1815 //
1816 Status = FindVariable (
1817 EFI_CERT_DB_NAME,
1818 &gEfiCertDbGuid,
1819 &CertDbVariable,
1820 &mVariableModuleGlobal->VariableGlobal,
1821 FALSE
1822 );
1823 if (EFI_ERROR (Status)) {
1824 return Status;
1825 }
1826
1827 DataSize = DataSizeOfVariable (CertDbVariable.CurrPtr);
1828 Data = GetVariableDataPtr (CertDbVariable.CurrPtr);
1829 if ((DataSize == 0) || (Data == NULL)) {
1830 ASSERT (FALSE);
1831 return EFI_NOT_FOUND;
1832 }
1833
1834 //
1835 // Find whether matching cert node already exists in "certdb".
1836 // If yes return error.
1837 //
1838 Status = FindCertsFromDb (
1839 VariableName,
1840 VendorGuid,
1841 Data,
1842 DataSize,
1843 NULL,
1844 NULL,
1845 NULL,
1846 NULL
1847 );
1848
1849 if (!EFI_ERROR (Status)) {
1850 ASSERT (FALSE);
1851 return EFI_ACCESS_DENIED;
1852 }
1853
1854 //
1855 // Construct new data content of variable "certdb".
1856 //
1857 NameSize = (UINT32) StrLen (VariableName);
1858 CertNodeSize = sizeof (AUTH_CERT_DB_DATA) + (UINT32) CertDataSize + NameSize * sizeof (CHAR16);
1859 NewCertDbSize = (UINT32) DataSize + CertNodeSize;
1860 if (NewCertDbSize > MAX_CERTDB_SIZE) {
1861 return EFI_OUT_OF_RESOURCES;
1862 }
1863 NewCertDb = (UINT8*) mCertDbStore;
1864
1865 //
1866 // Copy the DB entries before deleting node.
1867 //
1868 CopyMem (NewCertDb, Data, DataSize);
1869 //
1870 // Update CertDbListSize.
1871 //
1872 CopyMem (NewCertDb, &NewCertDbSize, sizeof (UINT32));
1873 //
1874 // Construct new cert node.
1875 //
1876 Ptr = (AUTH_CERT_DB_DATA *) (NewCertDb + DataSize);
1877 CopyGuid (&Ptr->VendorGuid, VendorGuid);
1878 CopyMem (&Ptr->CertNodeSize, &CertNodeSize, sizeof (UINT32));
1879 CopyMem (&Ptr->NameSize, &NameSize, sizeof (UINT32));
1880 CopyMem (&Ptr->CertDataSize, &CertDataSize, sizeof (UINT32));
1881
1882 CopyMem (
1883 (UINT8 *) Ptr + sizeof (AUTH_CERT_DB_DATA),
1884 VariableName,
1885 NameSize * sizeof (CHAR16)
1886 );
1887
1888 CopyMem (
1889 (UINT8 *) Ptr + sizeof (AUTH_CERT_DB_DATA) + NameSize * sizeof (CHAR16),
1890 CertData,
1891 CertDataSize
1892 );
1893
1894 //
1895 // Set "certdb".
1896 //
1897 VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
1898 Status = UpdateVariable (
1899 EFI_CERT_DB_NAME,
1900 &gEfiCertDbGuid,
1901 NewCertDb,
1902 NewCertDbSize,
1903 VarAttr,
1904 0,
1905 0,
1906 &CertDbVariable,
1907 NULL
1908 );
1909
1910 return Status;
1911 }
1912
1913 /**
1914 Process variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS set
1915
1916 Caution: This function may receive untrusted input.
1917 This function may be invoked in SMM mode, and datasize and data are external input.
1918 This function will do basic validation, before parse the data.
1919 This function will parse the authentication carefully to avoid security issues, like
1920 buffer overflow, integer overflow.
1921
1922 @param[in] VariableName Name of Variable to be found.
1923 @param[in] VendorGuid Variable vendor GUID.
1924 @param[in] Data Data pointer.
1925 @param[in] DataSize Size of Data found. If size is less than the
1926 data, this value contains the required size.
1927 @param[in] Variable The variable information which is used to keep track of variable usage.
1928 @param[in] Attributes Attribute value of the variable.
1929 @param[in] AuthVarType Verify against PK, KEK database, private database or certificate in data payload.
1930 @param[out] VarDel Delete the variable or not.
1931
1932 @retval EFI_INVALID_PARAMETER Invalid parameter.
1933 @retval EFI_SECURITY_VIOLATION The variable does NOT pass the validation
1934 check carried out by the firmware.
1935 @retval EFI_OUT_OF_RESOURCES Failed to process variable due to lack
1936 of resources.
1937 @retval EFI_SUCCESS Variable pass validation successfully.
1938
1939 **/
1940 EFI_STATUS
1941 VerifyTimeBasedPayload (
1942 IN CHAR16 *VariableName,
1943 IN EFI_GUID *VendorGuid,
1944 IN VOID *Data,
1945 IN UINTN DataSize,
1946 IN VARIABLE_POINTER_TRACK *Variable,
1947 IN UINT32 Attributes,
1948 IN AUTHVAR_TYPE AuthVarType,
1949 OUT BOOLEAN *VarDel
1950 )
1951 {
1952 UINT8 *RootCert;
1953 UINT8 *SigData;
1954 UINT8 *PayloadPtr;
1955 UINTN RootCertSize;
1956 UINTN Index;
1957 UINTN CertCount;
1958 UINTN PayloadSize;
1959 UINT32 Attr;
1960 UINT32 SigDataSize;
1961 UINT32 KekDataSize;
1962 BOOLEAN VerifyStatus;
1963 EFI_STATUS Status;
1964 EFI_SIGNATURE_LIST *CertList;
1965 EFI_SIGNATURE_DATA *Cert;
1966 VARIABLE_POINTER_TRACK KekVariable;
1967 EFI_VARIABLE_AUTHENTICATION_2 *CertData;
1968 UINT8 *NewData;
1969 UINTN NewDataSize;
1970 VARIABLE_POINTER_TRACK PkVariable;
1971 UINT8 *Buffer;
1972 UINTN Length;
1973 UINT8 *SignerCerts;
1974 UINT8 *WrapSigData;
1975 UINTN CertStackSize;
1976 UINT8 *CertsInCertDb;
1977 UINT32 CertsSizeinDb;
1978
1979 VerifyStatus = FALSE;
1980 CertData = NULL;
1981 NewData = NULL;
1982 Attr = Attributes;
1983 WrapSigData = NULL;
1984 SignerCerts = NULL;
1985 RootCert = NULL;
1986
1987 //
1988 // When the attribute EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS is
1989 // set, then the Data buffer shall begin with an instance of a complete (and serialized)
1990 // EFI_VARIABLE_AUTHENTICATION_2 descriptor. The descriptor shall be followed by the new
1991 // variable value and DataSize shall reflect the combined size of the descriptor and the new
1992 // variable value. The authentication descriptor is not part of the variable data and is not
1993 // returned by subsequent calls to GetVariable().
1994 //
1995 CertData = (EFI_VARIABLE_AUTHENTICATION_2 *) Data;
1996
1997 //
1998 // Verify that Pad1, Nanosecond, TimeZone, Daylight and Pad2 components of the
1999 // TimeStamp value are set to zero.
2000 //
2001 if ((CertData->TimeStamp.Pad1 != 0) ||
2002 (CertData->TimeStamp.Nanosecond != 0) ||
2003 (CertData->TimeStamp.TimeZone != 0) ||
2004 (CertData->TimeStamp.Daylight != 0) ||
2005 (CertData->TimeStamp.Pad2 != 0)) {
2006 return EFI_SECURITY_VIOLATION;
2007 }
2008
2009 if ((Variable->CurrPtr != NULL) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0)) {
2010 if (CompareTimeStamp (&CertData->TimeStamp, &Variable->CurrPtr->TimeStamp)) {
2011 //
2012 // TimeStamp check fail, suspicious replay attack, return EFI_SECURITY_VIOLATION.
2013 //
2014 return EFI_SECURITY_VIOLATION;
2015 }
2016 }
2017
2018 //
2019 // wCertificateType should be WIN_CERT_TYPE_EFI_GUID.
2020 // Cert type should be EFI_CERT_TYPE_PKCS7_GUID.
2021 //
2022 if ((CertData->AuthInfo.Hdr.wCertificateType != WIN_CERT_TYPE_EFI_GUID) ||
2023 !CompareGuid (&CertData->AuthInfo.CertType, &gEfiCertPkcs7Guid)) {
2024 //
2025 // Invalid AuthInfo type, return EFI_SECURITY_VIOLATION.
2026 //
2027 return EFI_SECURITY_VIOLATION;
2028 }
2029
2030 //
2031 // Find out Pkcs7 SignedData which follows the EFI_VARIABLE_AUTHENTICATION_2 descriptor.
2032 // AuthInfo.Hdr.dwLength is the length of the entire certificate, including the length of the header.
2033 //
2034 SigData = CertData->AuthInfo.CertData;
2035 SigDataSize = CertData->AuthInfo.Hdr.dwLength - (UINT32) (OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData));
2036
2037 //
2038 // Find out the new data payload which follows Pkcs7 SignedData directly.
2039 //
2040 PayloadPtr = SigData + SigDataSize;
2041 PayloadSize = DataSize - OFFSET_OF_AUTHINFO2_CERT_DATA - (UINTN) SigDataSize;
2042
2043 //
2044 // Construct a buffer to fill with (VariableName, VendorGuid, Attributes, TimeStamp, Data).
2045 //
2046 NewDataSize = PayloadSize + sizeof (EFI_TIME) + sizeof (UINT32) +
2047 sizeof (EFI_GUID) + StrSize (VariableName) - sizeof (CHAR16);
2048 NewData = mSerializationRuntimeBuffer;
2049
2050 Buffer = NewData;
2051 Length = StrLen (VariableName) * sizeof (CHAR16);
2052 CopyMem (Buffer, VariableName, Length);
2053 Buffer += Length;
2054
2055 Length = sizeof (EFI_GUID);
2056 CopyMem (Buffer, VendorGuid, Length);
2057 Buffer += Length;
2058
2059 Length = sizeof (UINT32);
2060 CopyMem (Buffer, &Attr, Length);
2061 Buffer += Length;
2062
2063 Length = sizeof (EFI_TIME);
2064 CopyMem (Buffer, &CertData->TimeStamp, Length);
2065 Buffer += Length;
2066
2067 CopyMem (Buffer, PayloadPtr, PayloadSize);
2068
2069 if (AuthVarType == AuthVarTypePk) {
2070 //
2071 // Get platform key from variable.
2072 //
2073 Status = FindVariable (
2074 EFI_PLATFORM_KEY_NAME,
2075 &gEfiGlobalVariableGuid,
2076 &PkVariable,
2077 &mVariableModuleGlobal->VariableGlobal,
2078 FALSE
2079 );
2080 if (EFI_ERROR (Status)) {
2081 return Status;
2082 }
2083
2084 CertList = (EFI_SIGNATURE_LIST *) GetVariableDataPtr (PkVariable.CurrPtr);
2085 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2086 RootCert = Cert->SignatureData;
2087 RootCertSize = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);
2088
2089
2090 //
2091 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2092 //
2093 VerifyStatus = Pkcs7Verify (
2094 SigData,
2095 SigDataSize,
2096 RootCert,
2097 RootCertSize,
2098 NewData,
2099 NewDataSize
2100 );
2101
2102 } else if (AuthVarType == AuthVarTypeKek) {
2103
2104 //
2105 // Get KEK database from variable.
2106 //
2107 Status = FindVariable (
2108 EFI_KEY_EXCHANGE_KEY_NAME,
2109 &gEfiGlobalVariableGuid,
2110 &KekVariable,
2111 &mVariableModuleGlobal->VariableGlobal,
2112 FALSE
2113 );
2114 if (EFI_ERROR (Status)) {
2115 return Status;
2116 }
2117
2118 //
2119 // Ready to verify Pkcs7 SignedData. Go through KEK Signature Database to find out X.509 CertList.
2120 //
2121 KekDataSize = KekVariable.CurrPtr->DataSize;
2122 CertList = (EFI_SIGNATURE_LIST *) GetVariableDataPtr (KekVariable.CurrPtr);
2123 while ((KekDataSize > 0) && (KekDataSize >= CertList->SignatureListSize)) {
2124 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
2125 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2126 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
2127 for (Index = 0; Index < CertCount; Index++) {
2128 //
2129 // Iterate each Signature Data Node within this CertList for a verify
2130 //
2131 RootCert = Cert->SignatureData;
2132 RootCertSize = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);
2133
2134 //
2135 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2136 //
2137 VerifyStatus = Pkcs7Verify (
2138 SigData,
2139 SigDataSize,
2140 RootCert,
2141 RootCertSize,
2142 NewData,
2143 NewDataSize
2144 );
2145 if (VerifyStatus) {
2146 goto Exit;
2147 }
2148 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
2149 }
2150 }
2151 KekDataSize -= CertList->SignatureListSize;
2152 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
2153 }
2154 } else if (AuthVarType == AuthVarTypePriv) {
2155
2156 //
2157 // Process common authenticated variable except PK/KEK/DB/DBX.
2158 // Get signer's certificates from SignedData.
2159 //
2160 VerifyStatus = Pkcs7GetSigners (
2161 SigData,
2162 SigDataSize,
2163 &SignerCerts,
2164 &CertStackSize,
2165 &RootCert,
2166 &RootCertSize
2167 );
2168 if (!VerifyStatus) {
2169 goto Exit;
2170 }
2171
2172 //
2173 // Get previously stored signer's certificates from certdb for existing
2174 // variable. Check whether they are identical with signer's certificates
2175 // in SignedData. If not, return error immediately.
2176 //
2177 if ((Variable->CurrPtr != NULL)) {
2178 VerifyStatus = FALSE;
2179
2180 Status = GetCertsFromDb (VariableName, VendorGuid, &CertsInCertDb, &CertsSizeinDb);
2181 if (EFI_ERROR (Status)) {
2182 goto Exit;
2183 }
2184
2185 if ((CertStackSize != CertsSizeinDb) ||
2186 (CompareMem (SignerCerts, CertsInCertDb, CertsSizeinDb) != 0)) {
2187 goto Exit;
2188 }
2189 }
2190
2191 VerifyStatus = Pkcs7Verify (
2192 SigData,
2193 SigDataSize,
2194 RootCert,
2195 RootCertSize,
2196 NewData,
2197 NewDataSize
2198 );
2199 if (!VerifyStatus) {
2200 goto Exit;
2201 }
2202
2203 //
2204 // Delete signer's certificates when delete the common authenticated variable.
2205 //
2206 if ((PayloadSize == 0) && (Variable->CurrPtr != NULL) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0)) {
2207 Status = DeleteCertsFromDb (VariableName, VendorGuid);
2208 if (EFI_ERROR (Status)) {
2209 VerifyStatus = FALSE;
2210 goto Exit;
2211 }
2212 } else if (Variable->CurrPtr == NULL && PayloadSize != 0) {
2213 //
2214 // Insert signer's certificates when adding a new common authenticated variable.
2215 //
2216 Status = InsertCertsToDb (VariableName, VendorGuid, SignerCerts, CertStackSize);
2217 if (EFI_ERROR (Status)) {
2218 VerifyStatus = FALSE;
2219 goto Exit;
2220 }
2221 }
2222 } else if (AuthVarType == AuthVarTypePayload) {
2223 CertList = (EFI_SIGNATURE_LIST *) PayloadPtr;
2224 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
2225 RootCert = Cert->SignatureData;
2226 RootCertSize = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);
2227
2228 // Verify Pkcs7 SignedData via Pkcs7Verify library.
2229 //
2230 VerifyStatus = Pkcs7Verify (
2231 SigData,
2232 SigDataSize,
2233 RootCert,
2234 RootCertSize,
2235 NewData,
2236 NewDataSize
2237 );
2238 } else {
2239 return EFI_SECURITY_VIOLATION;
2240 }
2241
2242 Exit:
2243
2244 if (AuthVarType == AuthVarTypePriv) {
2245 Pkcs7FreeSigners (RootCert);
2246 Pkcs7FreeSigners (SignerCerts);
2247 }
2248
2249 if (!VerifyStatus) {
2250 return EFI_SECURITY_VIOLATION;
2251 }
2252
2253 Status = CheckSignatureListFormat(VariableName, VendorGuid, PayloadPtr, PayloadSize);
2254 if (EFI_ERROR (Status)) {
2255 return Status;
2256 }
2257
2258 if ((PayloadSize == 0) && (VarDel != NULL)) {
2259 *VarDel = TRUE;
2260 }
2261
2262 //
2263 // Final step: Update/Append Variable if it pass Pkcs7Verify
2264 //
2265 return UpdateVariable (
2266 VariableName,
2267 VendorGuid,
2268 PayloadPtr,
2269 PayloadSize,
2270 Attributes,
2271 0,
2272 0,
2273 Variable,
2274 &CertData->TimeStamp
2275 );
2276 }
2277