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