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