]> git.proxmox.com Git - mirror_edk2.git/blobdiff - SecurityPkg/VariableAuthenticated/RuntimeDxe/AuthService.c
UEFI 2.4 X509 Certificate Hash and RFC3161 Timestamp Verification support for Secure...
[mirror_edk2.git] / SecurityPkg / VariableAuthenticated / RuntimeDxe / AuthService.c
index 09c58db985928a44c5351a70c9b5fd9e4b243847..3f0698e606eb8a81b4962b8d960b4c2313910a7b 100644 (file)
@@ -7,6 +7,10 @@
   This external input must be validated carefully to avoid security issue like\r
   buffer overflow, integer overflow.\r
   Variable attribute should also be checked to avoid authentication bypass.\r
+     The whole SMM authentication variable design relies on the integrity of flash part and SMM.\r
+  which is assumed to be protected by platform.  All variable code and metadata in flash/SMM Memory\r
+  may not be modified without authorization. If platform fails to protect these resources,\r
+  the authentication service provided in this driver will be broken, and the behavior is undefined.\r
 \r
   ProcessVarWithPk(), ProcessVarWithKek() and ProcessVariable() are the function to do\r
   variable authentication.\r
@@ -15,7 +19,7 @@
   They will do basic validation for authentication data structure, then call crypto library\r
   to verify the signature.\r
 \r
-Copyright (c) 2009 - 2012, Intel Corporation. All rights reserved.<BR>\r
+Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.<BR>\r
 This program and the accompanying materials\r
 are licensed and made available under the terms and conditions of the BSD License\r
 which accompanies this distribution.  The full text of the license may be found at\r
@@ -32,9 +36,15 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 ///\r
 /// Global database array for scratch\r
 ///\r
-UINT8    mPubKeyStore[MAX_KEYDB_SIZE];\r
+UINT8    *mPubKeyStore;\r
 UINT32   mPubKeyNumber;\r
+UINT32   mMaxKeyNumber;\r
+UINT32   mMaxKeyDbSize;\r
+UINT8    *mCertDbStore;\r
+UINT32   mMaxCertDbSize;\r
 UINT32   mPlatformMode;\r
+UINT8    mVendorKeyState;\r
+\r
 EFI_GUID mSignatureSupport[] = {EFI_CERT_SHA1_GUID, EFI_CERT_SHA256_GUID, EFI_CERT_RSA2048_GUID, EFI_CERT_X509_GUID};\r
 //\r
 // Public Exponent of RSA Key.\r
@@ -45,14 +55,6 @@ CONST UINT8 mRsaE[] = { 0x01, 0x00, 0x01 };
 //\r
 VOID  *mHashCtx = NULL;\r
 \r
-//\r
-// Pointer to runtime buffer.\r
-// For "Append" operation to an existing variable, a read/modify/write operation\r
-// is supported by firmware internally. Reserve runtime buffer to cache previous\r
-// variable data in runtime phase because memory allocation is forbidden in virtual mode.\r
-//\r
-VOID  *mStorageArea = NULL;\r
-\r
 //\r
 // The serialization of the values of the VariableName, VendorGuid and Attributes\r
 // parameters of the SetVariable() call and the TimeStamp component of the\r
@@ -75,7 +77,10 @@ EFI_SIGNATURE_ITEM mSupportSigItem[] = {
   {EFI_CERT_X509_GUID,            0,               ((UINT32) ~0)},\r
   {EFI_CERT_SHA224_GUID,          0,               28           },\r
   {EFI_CERT_SHA384_GUID,          0,               48           },\r
-  {EFI_CERT_SHA512_GUID,          0,               64           }\r
+  {EFI_CERT_SHA512_GUID,          0,               64           },\r
+  {EFI_CERT_X509_SHA256_GUID,     0,               48           },\r
+  {EFI_CERT_X509_SHA384_GUID,     0,               64           },\r
+  {EFI_CERT_X509_SHA512_GUID,     0,               80           }\r
 };\r
 \r
 /**\r
@@ -86,7 +91,7 @@ EFI_SIGNATURE_ITEM mSupportSigItem[] = {
 \r
   @retval TRUE      This variable is protected, only a physical present user could set this variable.\r
   @retval FALSE     This variable is not protected.\r
-  \r
+\r
 **/\r
 BOOLEAN\r
 NeedPhysicallyPresent(\r
@@ -98,7 +103,7 @@ NeedPhysicallyPresent(
     || (CompareGuid (VendorGuid, &gEfiCustomModeEnableGuid) && (StrCmp (VariableName, EFI_CUSTOM_MODE_NAME) == 0))) {\r
     return TRUE;\r
   }\r
-  \r
+\r
   return FALSE;\r
 }\r
 \r
@@ -120,7 +125,7 @@ InCustomMode (
   if (Variable.CurrPtr != NULL && *(GetVariableDataPtr (Variable.CurrPtr)) == CUSTOM_SECURE_BOOT_MODE) {\r
     return TRUE;\r
   }\r
-  \r
+\r
   return FALSE;\r
 }\r
 \r
@@ -189,10 +194,21 @@ AutenticatedVariableServiceInitialize (
   }\r
 \r
   //\r
-  // Reserved runtime buffer for "Append" operation in virtual mode.\r
+  // Reserve runtime buffer for public key database. The size excludes variable header and name size.\r
   //\r
-  mStorageArea  = AllocateRuntimePool (PcdGet32 (PcdMaxVariableSize));\r
-  if (mStorageArea == NULL) {\r
+  mMaxKeyDbSize = PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER) - sizeof (AUTHVAR_KEYDB_NAME);\r
+  mMaxKeyNumber = mMaxKeyDbSize / EFI_CERT_TYPE_RSA2048_SIZE;\r
+  mPubKeyStore  = AllocateRuntimePool (mMaxKeyDbSize);\r
+  if (mPubKeyStore == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  //\r
+  // Reserve runtime buffer for certificate database. The size excludes variable header and name size.\r
+  //\r
+  mMaxCertDbSize = PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER) - sizeof (EFI_CERT_DB_NAME);\r
+  mCertDbStore   = AllocateRuntimePool (mMaxCertDbSize);\r
+  if (mCertDbStore == NULL) {\r
     return EFI_OUT_OF_RESOURCES;\r
   }\r
 \r
@@ -242,6 +258,10 @@ AutenticatedVariableServiceInitialize (
     DataSize  = DataSizeOfVariable (Variable.CurrPtr);\r
     Data      = GetVariableDataPtr (Variable.CurrPtr);\r
     ASSERT ((DataSize != 0) && (Data != NULL));\r
+    //\r
+    // "AuthVarKeyDatabase" is an internal variable. Its DataSize is always ensured not to exceed mPubKeyStore buffer size(See definition before)\r
+    //  Therefore, there is no memory overflow in underlying CopyMem.\r
+    //\r
     CopyMem (mPubKeyStore, (UINT8 *) Data, DataSize);\r
     mPubKeyNumber = (UINT32) (DataSize / EFI_CERT_TYPE_RSA2048_SIZE);\r
   }\r
@@ -252,9 +272,9 @@ AutenticatedVariableServiceInitialize (
   } else {\r
     DEBUG ((EFI_D_INFO, "Variable %s exists.\n", EFI_PLATFORM_KEY_NAME));\r
   }\r
-  \r
+\r
   //\r
-  // Create "SetupMode" varable with BS+RT attribute set.\r
+  // Create "SetupMode" variable with BS+RT attribute set.\r
   //\r
   FindVariable (EFI_SETUP_MODE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
   if (PkVariable.CurrPtr == NULL) {\r
@@ -276,9 +296,9 @@ AutenticatedVariableServiceInitialize (
   if (EFI_ERROR (Status)) {\r
     return Status;\r
   }\r
-  \r
+\r
   //\r
-  // Create "SignatureSupport" varable with BS+RT attribute set.\r
+  // Create "SignatureSupport" variable with BS+RT attribute set.\r
   //\r
   FindVariable (EFI_SIGNATURE_SUPPORT_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
   Status  = UpdateVariable (\r
@@ -327,7 +347,7 @@ AutenticatedVariableServiceInitialize (
   }\r
 \r
   //\r
-  // Create "SecureBoot" varable with BS+RT attribute set.\r
+  // Create "SecureBoot" variable with BS+RT attribute set.\r
   //\r
   if (SecureBootEnable == SECURE_BOOT_ENABLE && mPlatformMode == USER_MODE) {\r
     SecureBootMode = SECURE_BOOT_MODE_ENABLE;\r
@@ -355,37 +375,30 @@ AutenticatedVariableServiceInitialize (
   DEBUG ((EFI_D_INFO, "Variable %s is %x\n", EFI_SECURE_BOOT_ENABLE_NAME, SecureBootEnable));\r
 \r
   //\r
-  // Check "CustomMode" variable's existence.\r
+  // Initialize "CustomMode" in STANDARD_SECURE_BOOT_MODE state.\r
   //\r
   FindVariable (EFI_CUSTOM_MODE_NAME, &gEfiCustomModeEnableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
-  if (Variable.CurrPtr != NULL) {\r
-    CustomMode = *(GetVariableDataPtr (Variable.CurrPtr));\r
-  } else {\r
-    //\r
-    // "CustomMode" not exist, initialize it in STANDARD_SECURE_BOOT_MODE.\r
-    //\r
-    CustomMode = STANDARD_SECURE_BOOT_MODE;\r
-    Status = UpdateVariable (\r
-               EFI_CUSTOM_MODE_NAME,\r
-               &gEfiCustomModeEnableGuid,\r
-               &CustomMode,\r
-               sizeof (UINT8),\r
-               EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,\r
-               0,\r
-               0,\r
-               &Variable,\r
-               NULL\r
-               );\r
-    if (EFI_ERROR (Status)) {\r
-      return Status;\r
-    }\r
+  CustomMode = STANDARD_SECURE_BOOT_MODE;\r
+  Status = UpdateVariable (\r
+             EFI_CUSTOM_MODE_NAME,\r
+             &gEfiCustomModeEnableGuid,\r
+             &CustomMode,\r
+             sizeof (UINT8),\r
+             EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,\r
+             0,\r
+             0,\r
+             &Variable,\r
+             NULL\r
+             );\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
   }\r
-  \r
+\r
   DEBUG ((EFI_D_INFO, "Variable %s is %x\n", EFI_CUSTOM_MODE_NAME, CustomMode));\r
 \r
   //\r
   // Check "certdb" variable's existence.\r
-  // If it doesn't exist, then create a new one with \r
+  // If it doesn't exist, then create a new one with\r
   // EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS set.\r
   //\r
   Status = FindVariable (\r
@@ -398,7 +411,7 @@ AutenticatedVariableServiceInitialize (
 \r
   if (Variable.CurrPtr == NULL) {\r
     VarAttr  = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;\r
-    ListSize = 0;\r
+    ListSize = sizeof (UINT32);\r
     Status   = UpdateVariable (\r
                  EFI_CERT_DB_NAME,\r
                  &gEfiCertDbGuid,\r
@@ -410,8 +423,58 @@ AutenticatedVariableServiceInitialize (
                  &Variable,\r
                  NULL\r
                  );\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Check "VendorKeysNv" variable's existence and create "VendorKeys" variable accordingly.\r
+  //\r
+  FindVariable (EFI_VENDOR_KEYS_NV_VARIABLE_NAME, &gEfiVendorKeysNvGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
+  if (Variable.CurrPtr != NULL) {\r
+    mVendorKeyState = *(GetVariableDataPtr (Variable.CurrPtr));\r
+  } else {\r
+    //\r
+    // "VendorKeysNv" not exist, initialize it in VENDOR_KEYS_VALID state.\r
+    //\r
+    mVendorKeyState = VENDOR_KEYS_VALID;\r
+    Status = UpdateVariable (\r
+               EFI_VENDOR_KEYS_NV_VARIABLE_NAME,\r
+               &gEfiVendorKeysNvGuid,\r
+               &mVendorKeyState,\r
+               sizeof (UINT8),\r
+               EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS,\r
+               0,\r
+               0,\r
+               &Variable,\r
+               NULL\r
+               );\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Create "VendorKeys" variable with BS+RT attribute set.\r
+  //\r
+  FindVariable (EFI_VENDOR_KEYS_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
+  Status = UpdateVariable (\r
+             EFI_VENDOR_KEYS_VARIABLE_NAME,\r
+             &gEfiGlobalVariableGuid,\r
+             &mVendorKeyState,\r
+             sizeof (UINT8),\r
+             EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS,\r
+             0,\r
+             0,\r
+             &Variable,\r
+             NULL\r
+             );\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
 \r
-  }  \r
+  DEBUG ((EFI_D_INFO, "Variable %s is %x\n", EFI_VENDOR_KEYS_VARIABLE_NAME, mVendorKeyState));\r
 \r
   return Status;\r
 }\r
@@ -420,20 +483,26 @@ AutenticatedVariableServiceInitialize (
   Add public key in store and return its index.\r
 \r
   @param[in]  PubKey                  Input pointer to Public Key data\r
+  @param[in]  VariableDataEntry       The variable data entry\r
 \r
   @return                             Index of new added item\r
 \r
 **/\r
 UINT32\r
 AddPubKeyInStore (\r
-  IN  UINT8               *PubKey\r
+  IN  UINT8                        *PubKey,\r
+  IN  VARIABLE_ENTRY_CONSISTENCY   *VariableDataEntry\r
   )\r
 {\r
-  EFI_STATUS              Status;\r
-  BOOLEAN                 IsFound;\r
-  UINT32                  Index;\r
-  VARIABLE_POINTER_TRACK  Variable;\r
-  UINT8                   *Ptr;\r
+  EFI_STATUS                       Status;\r
+  BOOLEAN                          IsFound;\r
+  UINT32                           Index;\r
+  VARIABLE_POINTER_TRACK           Variable;\r
+  UINT8                            *Ptr;\r
+  UINT8                            *Data;\r
+  UINTN                            DataSize;\r
+  VARIABLE_ENTRY_CONSISTENCY       PublicKeyEntry;\r
+  UINT32                           Attributes;\r
 \r
   if (PubKey == NULL) {\r
     return 0;\r
@@ -446,7 +515,11 @@ AddPubKeyInStore (
              &mVariableModuleGlobal->VariableGlobal,\r
              FALSE\r
              );\r
-  ASSERT_EFI_ERROR (Status);\r
+  if (EFI_ERROR (Status)) {\r
+    DEBUG ((EFI_D_ERROR, "Get public key database variable failure, Status = %r\n", Status));\r
+    return 0;\r
+  }\r
+\r
   //\r
   // Check whether the public key entry does exist.\r
   //\r
@@ -463,9 +536,68 @@ AddPubKeyInStore (
     //\r
     // Add public key in database.\r
     //\r
-    if (mPubKeyNumber == MAX_KEY_NUM) {\r
+    if (mPubKeyNumber == mMaxKeyNumber) {\r
+      //\r
+      // Public key dadatase is full, try to reclaim invalid key.\r
+      //\r
+      if (AtRuntime ()) {\r
+        //\r
+        // NV storage can't reclaim at runtime.\r
+        //\r
+        return 0;\r
+      }\r
+\r
+      Status = Reclaim (\r
+                 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,\r
+                 &mVariableModuleGlobal->NonVolatileLastVariableOffset,\r
+                 FALSE,\r
+                 NULL,\r
+                 NULL,\r
+                 0,\r
+                 TRUE\r
+                 );\r
+      if (EFI_ERROR (Status)) {\r
+        return 0;\r
+      }\r
+\r
+      Status = FindVariable (\r
+                 AUTHVAR_KEYDB_NAME,\r
+                 &gEfiAuthenticatedVariableGuid,\r
+                 &Variable,\r
+                 &mVariableModuleGlobal->VariableGlobal,\r
+                 FALSE\r
+                 );\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((EFI_D_ERROR, "Get public key database variable failure, Status = %r\n", Status));\r
+        return 0;\r
+      }\r
+\r
+      DataSize  = DataSizeOfVariable (Variable.CurrPtr);\r
+      Data      = GetVariableDataPtr (Variable.CurrPtr);\r
+      ASSERT ((DataSize != 0) && (Data != NULL));\r
+      //\r
+      // "AuthVarKeyDatabase" is an internal used variable. Its DataSize is always ensured not to exceed mPubKeyStore buffer size(See definition before)\r
+      //  Therefore, there is no memory overflow in underlying CopyMem.\r
+      //\r
+      CopyMem (mPubKeyStore, (UINT8 *) Data, DataSize);\r
+      mPubKeyNumber = (UINT32) (DataSize / EFI_CERT_TYPE_RSA2048_SIZE);\r
+\r
+      if (mPubKeyNumber == mMaxKeyNumber) {\r
+        return 0;\r
+      }\r
+    }\r
+\r
+    //\r
+    // Check the variable space for both public key and variable data.\r
+    //\r
+    PublicKeyEntry.VariableSize = (mPubKeyNumber + 1) * EFI_CERT_TYPE_RSA2048_SIZE;\r
+    PublicKeyEntry.Guid         = &gEfiAuthenticatedVariableGuid;\r
+    PublicKeyEntry.Name         = AUTHVAR_KEYDB_NAME;\r
+    Attributes = VARIABLE_ATTRIBUTE_NV_BS_RT | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS;\r
+\r
+    if (!CheckRemainingSpaceForConsistency (Attributes, &PublicKeyEntry, VariableDataEntry, NULL)) {\r
       //\r
-      // Notes: Database is full, need enhancement here, currently just return 0.\r
+      // No enough variable space.\r
       //\r
       return 0;\r
     }\r
@@ -480,13 +612,16 @@ AddPubKeyInStore (
                &gEfiAuthenticatedVariableGuid,\r
                mPubKeyStore,\r
                mPubKeyNumber * EFI_CERT_TYPE_RSA2048_SIZE,\r
-               EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS,\r
+               Attributes,\r
                0,\r
                0,\r
                &Variable,\r
                NULL\r
                );\r
-    ASSERT_EFI_ERROR (Status);\r
+    if (EFI_ERROR (Status)) {\r
+      DEBUG ((EFI_D_ERROR, "Update public key database variable failure, Status = %r\n", Status));\r
+      return 0;\r
+    }\r
   }\r
 \r
   return Index;\r
@@ -523,7 +658,9 @@ VerifyCounterBasedPayload (
   EFI_CERT_BLOCK_RSA_2048_SHA256  *CertBlock;\r
   UINT8                           Digest[SHA256_DIGEST_SIZE];\r
   VOID                            *Rsa;\r
+  UINTN                           PayloadSize;\r
 \r
+  PayloadSize = DataSize - AUTHINFO_SIZE;\r
   Rsa         = NULL;\r
   CertData    = NULL;\r
   CertBlock   = NULL;\r
@@ -555,7 +692,14 @@ VerifyCounterBasedPayload (
   if (!Status) {\r
     goto Done;\r
   }\r
-  Status  = Sha256Update (mHashCtx, Data + AUTHINFO_SIZE, (UINTN) (DataSize - AUTHINFO_SIZE));\r
+  Status  = Sha256Update (mHashCtx, Data + AUTHINFO_SIZE, PayloadSize);\r
+  if (!Status) {\r
+    goto Done;\r
+  }\r
+  //\r
+  // Hash Size.\r
+  //\r
+  Status  = Sha256Update (mHashCtx, &PayloadSize, sizeof (UINTN));\r
   if (!Status) {\r
     goto Done;\r
   }\r
@@ -625,7 +769,6 @@ UpdatePlatformMode (
 {\r
   EFI_STATUS              Status;\r
   VARIABLE_POINTER_TRACK  Variable;\r
-  UINT32                  VarAttr;\r
   UINT8                   SecureBootMode;\r
   UINT8                   SecureBootEnable;\r
   UINTN                   VariableDataSize;\r
@@ -686,13 +829,12 @@ UpdatePlatformMode (
     }\r
   }\r
 \r
-  VarAttr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS;\r
   Status  = UpdateVariable (\r
               EFI_SECURE_BOOT_MODE_NAME,\r
               &gEfiGlobalVariableGuid,\r
               &SecureBootMode,\r
               sizeof(UINT8),\r
-              VarAttr,\r
+              EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS,\r
               0,\r
               0,\r
               &Variable,\r
@@ -746,7 +888,7 @@ UpdatePlatformMode (
 }\r
 \r
 /**\r
-  Check input data form to make sure it is a valid EFI_SIGNATURE_LIST for PK/KEK/db/dbx variable.\r
+  Check input data form to make sure it is a valid EFI_SIGNATURE_LIST for PK/KEK/db/dbx/dbt variable.\r
 \r
   @param[in]  VariableName                Name of Variable to be check.\r
   @param[in]  VendorGuid                  Variable vendor GUID.\r
@@ -755,7 +897,7 @@ UpdatePlatformMode (
 \r
   @return EFI_INVALID_PARAMETER           Invalid signature list format.\r
   @return EFI_SUCCESS                     Passed signature list format check successfully.\r
-  \r
+\r
 **/\r
 EFI_STATUS\r
 CheckSignatureListFormat(\r
@@ -782,9 +924,10 @@ CheckSignatureListFormat(
 \r
   if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_PLATFORM_KEY_NAME) == 0)){\r
     IsPk = TRUE;\r
-  } else if ((CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0) ||\r
-             (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) && \r
-              (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0 || StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0))){\r
+  } else if ((CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0)) ||\r
+             (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) &&\r
+             ((StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) || (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0) ||\r
+              (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE2) == 0)))) {\r
     IsPk = FALSE;\r
   } else {\r
     return EFI_SUCCESS;\r
@@ -803,10 +946,10 @@ CheckSignatureListFormat(
     for (Index = 0; Index < (sizeof (mSupportSigItem) / sizeof (EFI_SIGNATURE_ITEM)); Index++ ) {\r
       if (CompareGuid (&SigList->SignatureType, &mSupportSigItem[Index].SigType)) {\r
         //\r
-        // The value of SignatureSize should always be 16 (size of SignatureOwner \r
+        // The value of SignatureSize should always be 16 (size of SignatureOwner\r
         // component) add the data length according to signature type.\r
         //\r
-        if (mSupportSigItem[Index].SigDataSize != ((UINT32) ~0) && \r
+        if (mSupportSigItem[Index].SigDataSize != ((UINT32) ~0) &&\r
           (SigList->SignatureSize - sizeof (EFI_GUID)) != mSupportSigItem[Index].SigDataSize) {\r
           return EFI_INVALID_PARAMETER;\r
         }\r
@@ -847,7 +990,7 @@ CheckSignatureListFormat(
       return EFI_INVALID_PARAMETER;\r
     }\r
     SigCount += (SigList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - SigList->SignatureHeaderSize) / SigList->SignatureSize;\r
-    \r
+\r
     SigDataSize -= SigList->SignatureListSize;\r
     SigList = (EFI_SIGNATURE_LIST *) ((UINT8 *) SigList + SigList->SignatureListSize);\r
   }\r
@@ -863,6 +1006,56 @@ CheckSignatureListFormat(
   return EFI_SUCCESS;\r
 }\r
 \r
+/**\r
+  Update "VendorKeys" variable to record the out of band secure boot key modification.\r
+\r
+  @return EFI_SUCCESS           Variable is updated successfully.\r
+  @return Others                Failed to update variable.\r
+\r
+**/\r
+EFI_STATUS\r
+VendorKeyIsModified (\r
+  VOID\r
+  )\r
+{\r
+  EFI_STATUS              Status;\r
+  VARIABLE_POINTER_TRACK  Variable;\r
+\r
+  if (mVendorKeyState == VENDOR_KEYS_MODIFIED) {\r
+    return EFI_SUCCESS;\r
+  }\r
+  mVendorKeyState = VENDOR_KEYS_MODIFIED;\r
+\r
+  FindVariable (EFI_VENDOR_KEYS_NV_VARIABLE_NAME, &gEfiVendorKeysNvGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
+  Status = UpdateVariable (\r
+             EFI_VENDOR_KEYS_NV_VARIABLE_NAME,\r
+             &gEfiVendorKeysNvGuid,\r
+             &mVendorKeyState,\r
+             sizeof (UINT8),\r
+             EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS,\r
+             0,\r
+             0,\r
+             &Variable,\r
+             NULL\r
+             );\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  FindVariable (EFI_VENDOR_KEYS_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
+  return UpdateVariable (\r
+           EFI_VENDOR_KEYS_VARIABLE_NAME,\r
+           &gEfiGlobalVariableGuid,\r
+           &mVendorKeyState,\r
+           sizeof (UINT8),\r
+           EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS,\r
+           0,\r
+           0,\r
+           &Variable,\r
+           NULL\r
+           );\r
+}\r
+\r
 /**\r
   Process variable with platform key for verification.\r
 \r
@@ -904,10 +1097,10 @@ ProcessVarWithPk (
   UINT8                       *Payload;\r
   UINTN                       PayloadSize;\r
 \r
-  if ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0 || \r
+  if ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0 ||\r
       (Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == 0) {\r
     //\r
-    // PK, KEK and db/dbx should set EFI_VARIABLE_NON_VOLATILE attribute and should be a time-based\r
+    // PK, KEK and db/dbx/dbt should set EFI_VARIABLE_NON_VOLATILE attribute and should be a time-based\r
     // authenticated variable.\r
     //\r
     return EFI_INVALID_PARAMETER;\r
@@ -937,6 +1130,13 @@ ProcessVarWithPk (
                Variable,\r
                &((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->TimeStamp\r
                );\r
+    if (EFI_ERROR(Status)) {\r
+      return Status;\r
+    }\r
+\r
+    if ((mPlatformMode != SETUP_MODE) || IsPk) {\r
+      Status = VendorKeyIsModified ();\r
+    }\r
   } else if (mPlatformMode == USER_MODE) {\r
     //\r
     // Verify against X509 Cert in PK database.\r
@@ -1025,7 +1225,7 @@ ProcessVarWithKek (
   if ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0 ||\r
       (Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == 0) {\r
     //\r
-    // DB and DBX should set EFI_VARIABLE_NON_VOLATILE attribute and should be a time-based\r
+    // DB, DBX and DBT should set EFI_VARIABLE_NON_VOLATILE attribute and should be a time-based\r
     // authenticated variable.\r
     //\r
     return EFI_INVALID_PARAMETER;\r
@@ -1057,7 +1257,7 @@ ProcessVarWithKek (
     if (EFI_ERROR (Status)) {\r
       return Status;\r
     }\r
-    \r
+\r
     Status = UpdateVariable (\r
                VariableName,\r
                VendorGuid,\r
@@ -1069,6 +1269,13 @@ ProcessVarWithKek (
                Variable,\r
                &((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->TimeStamp\r
                );\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+\r
+    if (mPlatformMode != SETUP_MODE) {\r
+      Status = VendorKeyIsModified ();\r
+    }\r
   }\r
 \r
   return Status;\r
@@ -1096,6 +1303,7 @@ ProcessVarWithKek (
   @return EFI_INVALID_PARAMETER           Invalid parameter.\r
   @return EFI_WRITE_PROTECTED             Variable is write-protected and needs authentication with\r
                                           EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS set.\r
+  @return EFI_OUT_OF_RESOURCES            The Database to save the public key is full.\r
   @return EFI_SECURITY_VIOLATION          The variable is with EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS\r
                                           set, but the AuthInfo does NOT pass the validation\r
                                           check carried out by the firmware.\r
@@ -1120,6 +1328,7 @@ ProcessVariable (
   EFI_CERT_BLOCK_RSA_2048_SHA256  *CertBlock;\r
   UINT32                          KeyIndex;\r
   UINT64                          MonotonicCount;\r
+  VARIABLE_ENTRY_CONSISTENCY      VariableDataEntry;\r
 \r
   KeyIndex    = 0;\r
   CertData    = NULL;\r
@@ -1133,7 +1342,23 @@ ProcessVariable (
     //\r
     return EFI_SECURITY_VIOLATION;\r
   }\r
-  \r
+\r
+  //\r
+  // A time-based authenticated variable and a count-based authenticated variable\r
+  // can't be updated by each other.\r
+  //\r
+  if (Variable->CurrPtr != NULL) {\r
+    if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) &&\r
+        ((Variable->CurrPtr->Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0)) {\r
+      return EFI_SECURITY_VIOLATION;\r
+    }\r
+\r
+    if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) &&\r
+        ((Variable->CurrPtr->Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0)) {\r
+      return EFI_SECURITY_VIOLATION;\r
+    }\r
+  }\r
+\r
   //\r
   // Process Time-based Authenticated variable.\r
   //\r
@@ -1171,7 +1396,7 @@ ProcessVariable (
       KeyIndex   = Variable->CurrPtr->PubKeyIndex;\r
       IsFirstTime = FALSE;\r
     }\r
-  } else if ((Variable->CurrPtr != NULL) && \r
+  } else if ((Variable->CurrPtr != NULL) &&\r
              ((Variable->CurrPtr->Attributes & (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) != 0)\r
             ) {\r
     //\r
@@ -1201,9 +1426,11 @@ ProcessVariable (
 \r
   if (!IsFirstTime) {\r
     //\r
-    // Check input PubKey.\r
+    // 2 cases need to check here\r
+    //   1. Internal PubKey variable. PubKeyIndex is always 0\r
+    //   2. Other counter-based AuthVariable. Check input PubKey.\r
     //\r
-    if (CompareMem (PubKey, mPubKeyStore + (KeyIndex - 1) * EFI_CERT_TYPE_RSA2048_SIZE, EFI_CERT_TYPE_RSA2048_SIZE) != 0) {\r
+    if (KeyIndex == 0 || CompareMem (PubKey, mPubKeyStore + (KeyIndex - 1) * EFI_CERT_TYPE_RSA2048_SIZE, EFI_CERT_TYPE_RSA2048_SIZE) != 0) {\r
       return EFI_SECURITY_VIOLATION;\r
     }\r
     //\r
@@ -1229,12 +1456,16 @@ ProcessVariable (
   // Now, the signature has been verified!\r
   //\r
   if (IsFirstTime && !IsDeletion) {\r
+    VariableDataEntry.VariableSize = DataSize - AUTHINFO_SIZE;\r
+    VariableDataEntry.Guid         = VendorGuid;\r
+    VariableDataEntry.Name         = VariableName;\r
+\r
     //\r
     // Update public key database variable if need.\r
     //\r
-    KeyIndex = AddPubKeyInStore (PubKey);\r
+    KeyIndex = AddPubKeyInStore (PubKey, &VariableDataEntry);\r
     if (KeyIndex == 0) {\r
-      return EFI_SECURITY_VIOLATION;\r
+      return EFI_OUT_OF_RESOURCES;\r
     }\r
   }\r
 \r
@@ -1249,20 +1480,24 @@ ProcessVariable (
   will be appended to the original EFI_SIGNATURE_LIST, duplicate EFI_SIGNATURE_DATA\r
   will be ignored.\r
 \r
-  @param[in, out]  Data            Pointer to original EFI_SIGNATURE_LIST.\r
-  @param[in]       DataSize        Size of Data buffer.\r
-  @param[in]       NewData         Pointer to new EFI_SIGNATURE_LIST to be appended.\r
-  @param[in]       NewDataSize     Size of NewData buffer.\r
+  @param[in, out]  Data              Pointer to original EFI_SIGNATURE_LIST.\r
+  @param[in]       DataSize          Size of Data buffer.\r
+  @param[in]       FreeBufSize       Size of free data buffer\r
+  @param[in]       NewData           Pointer to new EFI_SIGNATURE_LIST to be appended.\r
+  @param[in]       NewDataSize       Size of NewData buffer.\r
+  @param[out]      MergedBufSize     Size of the merged buffer\r
 \r
-  @return Size of the merged buffer.\r
+  @return EFI_BUFFER_TOO_SMALL if input Data buffer overflowed\r
 \r
 **/\r
-UINTN\r
+EFI_STATUS\r
 AppendSignatureList (\r
   IN  OUT VOID            *Data,\r
   IN  UINTN               DataSize,\r
+  IN  UINTN               FreeBufSize,\r
   IN  VOID                *NewData,\r
-  IN  UINTN               NewDataSize\r
+  IN  UINTN               NewDataSize,\r
+  OUT UINTN               *MergedBufSize\r
   )\r
 {\r
   EFI_SIGNATURE_LIST  *CertList;\r
@@ -1321,15 +1556,25 @@ AppendSignatureList (
         // New EFI_SIGNATURE_DATA, append it.\r
         //\r
         if (CopiedCount == 0) {\r
+          if (FreeBufSize < sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize) {\r
+            return EFI_BUFFER_TOO_SMALL;\r
+          }\r
+\r
           //\r
           // Copy EFI_SIGNATURE_LIST header for only once.\r
           //\r
+\r
           CopyMem (Tail, NewCertList, sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize);\r
           Tail = Tail + sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize;\r
+          FreeBufSize -= sizeof (EFI_SIGNATURE_LIST) + NewCertList->SignatureHeaderSize;\r
         }\r
 \r
+        if (FreeBufSize < NewCertList->SignatureSize) {\r
+          return EFI_BUFFER_TOO_SMALL;\r
+        }\r
         CopyMem (Tail, NewCert, NewCertList->SignatureSize);\r
         Tail += NewCertList->SignatureSize;\r
+        FreeBufSize -= NewCertList->SignatureSize;\r
         CopiedCount++;\r
       }\r
 \r
@@ -1349,7 +1594,8 @@ AppendSignatureList (
     NewCertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) NewCertList + NewCertList->SignatureListSize);\r
   }\r
 \r
-  return (Tail - (UINT8 *) Data);\r
+  *MergedBufSize = (Tail - (UINT8 *) Data);\r
+  return EFI_SUCCESS;\r
 }\r
 \r
 /**\r
@@ -1378,7 +1624,7 @@ CompareTimeStamp (
   } else if (FirstTime->Hour != SecondTime->Hour) {\r
     return (BOOLEAN) (FirstTime->Hour < SecondTime->Hour);\r
   } else if (FirstTime->Minute != SecondTime->Minute) {\r
-    return (BOOLEAN) (FirstTime->Minute < FirstTime->Minute);\r
+    return (BOOLEAN) (FirstTime->Minute < SecondTime->Minute);\r
   }\r
 \r
   return (BOOLEAN) (FirstTime->Second <= SecondTime->Second);\r
@@ -1472,7 +1718,7 @@ FindCertsFromDb (
       //\r
       // Check whether VariableName matches.\r
       //\r
-      if ((NameSize == StrLen (VariableName)) && \r
+      if ((NameSize == StrLen (VariableName)) &&\r
           (CompareMem (Data + Offset, VariableName, NameSize * sizeof (CHAR16)) == 0)) {\r
         Offset = Offset + NameSize * sizeof (CHAR16);\r
 \r
@@ -1481,7 +1727,7 @@ FindCertsFromDb (
         }\r
 \r
         if (CertDataSize != NULL) {\r
-          *CertDataSize = CertSize;        \r
+          *CertDataSize = CertSize;\r
         }\r
 \r
         if (CertNodeOffset != NULL) {\r
@@ -1502,7 +1748,7 @@ FindCertsFromDb (
     }\r
   }\r
 \r
-  return EFI_NOT_FOUND;  \r
+  return EFI_NOT_FOUND;\r
 }\r
 \r
 /**\r
@@ -1536,7 +1782,7 @@ GetCertsFromDb (
   if ((VariableName == NULL) || (VendorGuid == NULL) || (CertData == NULL) || (CertDataSize == NULL)) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
-  \r
+\r
   //\r
   // Get variable "certdb".\r
   //\r
@@ -1546,7 +1792,7 @@ GetCertsFromDb (
              &CertDbVariable,\r
              &mVariableModuleGlobal->VariableGlobal,\r
              FALSE\r
-             );      \r
+             );\r
   if (EFI_ERROR (Status)) {\r
     return Status;\r
   }\r
@@ -1609,7 +1855,7 @@ DeleteCertsFromDb (
   if ((VariableName == NULL) || (VendorGuid == NULL)) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
-  \r
+\r
   //\r
   // Get variable "certdb".\r
   //\r
@@ -1619,7 +1865,7 @@ DeleteCertsFromDb (
              &CertDbVariable,\r
              &mVariableModuleGlobal->VariableGlobal,\r
              FALSE\r
-             );      \r
+             );\r
   if (EFI_ERROR (Status)) {\r
     return Status;\r
   }\r
@@ -1664,10 +1910,7 @@ DeleteCertsFromDb (
   // Construct new data content of variable "certdb".\r
   //\r
   NewCertDbSize = (UINT32) DataSize - CertNodeSize;\r
-  NewCertDb     = AllocateZeroPool (NewCertDbSize);\r
-  if (NewCertDb == NULL) {\r
-    return EFI_OUT_OF_RESOURCES;\r
-  }\r
+  NewCertDb     = (UINT8*) mCertDbStore;\r
 \r
   //\r
   // Copy the DB entries before deleting node.\r
@@ -1690,8 +1933,8 @@ DeleteCertsFromDb (
 \r
   //\r
   // Set "certdb".\r
-  // \r
-  VarAttr  = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;  \r
+  //\r
+  VarAttr  = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;\r
   Status   = UpdateVariable (\r
                EFI_CERT_DB_NAME,\r
                &gEfiCertDbGuid,\r
@@ -1704,7 +1947,6 @@ DeleteCertsFromDb (
                NULL\r
                );\r
 \r
-  FreePool (NewCertDb);\r
   return Status;\r
 }\r
 \r
@@ -1746,7 +1988,7 @@ InsertCertsToDb (
   if ((VariableName == NULL) || (VendorGuid == NULL) || (CertData == NULL)) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
-  \r
+\r
   //\r
   // Get variable "certdb".\r
   //\r
@@ -1756,7 +1998,7 @@ InsertCertsToDb (
              &CertDbVariable,\r
              &mVariableModuleGlobal->VariableGlobal,\r
              FALSE\r
-             );      \r
+             );\r
   if (EFI_ERROR (Status)) {\r
     return Status;\r
   }\r
@@ -1792,12 +2034,12 @@ InsertCertsToDb (
   // Construct new data content of variable "certdb".\r
   //\r
   NameSize      = (UINT32) StrLen (VariableName);\r
-  CertNodeSize  = sizeof (AUTH_CERT_DB_DATA) + (UINT32) CertDataSize + NameSize * sizeof (CHAR16); \r
-  NewCertDbSize = (UINT32) DataSize + CertNodeSize;                  \r
-  NewCertDb     = AllocateZeroPool (NewCertDbSize);\r
-  if (NewCertDb == NULL) {\r
+  CertNodeSize  = sizeof (AUTH_CERT_DB_DATA) + (UINT32) CertDataSize + NameSize * sizeof (CHAR16);\r
+  NewCertDbSize = (UINT32) DataSize + CertNodeSize;\r
+  if (NewCertDbSize > mMaxCertDbSize) {\r
     return EFI_OUT_OF_RESOURCES;\r
   }\r
+  NewCertDb     = (UINT8*) mCertDbStore;\r
 \r
   //\r
   // Copy the DB entries before deleting node.\r
@@ -1815,7 +2057,7 @@ InsertCertsToDb (
   CopyMem (&Ptr->CertNodeSize, &CertNodeSize, sizeof (UINT32));\r
   CopyMem (&Ptr->NameSize, &NameSize, sizeof (UINT32));\r
   CopyMem (&Ptr->CertDataSize, &CertDataSize, sizeof (UINT32));\r
-  \r
+\r
   CopyMem (\r
     (UINT8 *) Ptr + sizeof (AUTH_CERT_DB_DATA),\r
     VariableName,\r
@@ -1827,11 +2069,11 @@ InsertCertsToDb (
     CertData,\r
     CertDataSize\r
     );\r
-  \r
+\r
   //\r
   // Set "certdb".\r
-  // \r
-  VarAttr  = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;  \r
+  //\r
+  VarAttr  = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;\r
   Status   = UpdateVariable (\r
                EFI_CERT_DB_NAME,\r
                &gEfiCertDbGuid,\r
@@ -1844,7 +2086,6 @@ InsertCertsToDb (
                NULL\r
                );\r
 \r
-  FreePool (NewCertDb);\r
   return Status;\r
 }\r
 \r
@@ -1921,6 +2162,7 @@ VerifyTimeBasedPayload (
   WrapSigData            = NULL;\r
   SignerCerts            = NULL;\r
   RootCert               = NULL;\r
+  CertsInCertDb          = NULL;\r
 \r
   //\r
   // When the attribute EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS is\r
@@ -2006,7 +2248,24 @@ VerifyTimeBasedPayload (
 \r
   if (AuthVarType == AuthVarTypePk) {\r
     //\r
-    // Get platform key from variable.\r
+    // Verify that the signature has been made with the current Platform Key (no chaining for PK).\r
+    // First, get signer's certificates from SignedData.\r
+    //\r
+    VerifyStatus = Pkcs7GetSigners (\r
+                     SigData,\r
+                     SigDataSize,\r
+                     &SignerCerts,\r
+                     &CertStackSize,\r
+                     &RootCert,\r
+                     &RootCertSize\r
+                     );\r
+    if (!VerifyStatus) {\r
+      goto Exit;\r
+    }\r
+\r
+    //\r
+    // Second, get the current platform key from variable. Check whether it's identical with signer's certificates\r
+    // in SignedData. If not, return error immediately.\r
     //\r
     Status = FindVariable (\r
                EFI_PLATFORM_KEY_NAME,\r
@@ -2016,14 +2275,16 @@ VerifyTimeBasedPayload (
                FALSE\r
                );\r
     if (EFI_ERROR (Status)) {\r
-      return Status;\r
+      VerifyStatus = FALSE;\r
+      goto Exit;\r
     }\r
-\r
     CertList = (EFI_SIGNATURE_LIST *) GetVariableDataPtr (PkVariable.CurrPtr);\r
     Cert     = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);\r
-    RootCert      = Cert->SignatureData;\r
-    RootCertSize  = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);\r
-\r
+    if ((RootCertSize != (CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1))) ||\r
+        (CompareMem (Cert->SignatureData, RootCert, RootCertSize) != 0)) {\r
+      VerifyStatus = FALSE;\r
+      goto Exit;\r
+    }\r
 \r
     //\r
     // Verify Pkcs7 SignedData via Pkcs7Verify library.\r
@@ -2092,7 +2353,7 @@ VerifyTimeBasedPayload (
   } else if (AuthVarType == AuthVarTypePriv) {\r
 \r
     //\r
-    // Process common authenticated variable except PK/KEK/DB/DBX.\r
+    // Process common authenticated variable except PK/KEK/DB/DBX/DBT.\r
     // Get signer's certificates from SignedData.\r
     //\r
     VerifyStatus = Pkcs7GetSigners (\r
@@ -2119,7 +2380,7 @@ VerifyTimeBasedPayload (
       if (EFI_ERROR (Status)) {\r
         goto Exit;\r
       }\r
-    \r
+\r
       if ((CertStackSize != CertsSizeinDb) ||\r
           (CompareMem (SignerCerts, CertsInCertDb, CertsSizeinDb) != 0)) {\r
         goto Exit;\r
@@ -2141,13 +2402,13 @@ VerifyTimeBasedPayload (
     //\r
     // Delete signer's certificates when delete the common authenticated variable.\r
     //\r
-    if ((PayloadSize == 0) && (Variable->CurrPtr != NULL)) {\r
+    if ((PayloadSize == 0) && (Variable->CurrPtr != NULL) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0)) {\r
       Status = DeleteCertsFromDb (VariableName, VendorGuid);\r
       if (EFI_ERROR (Status)) {\r
         VerifyStatus = FALSE;\r
         goto Exit;\r
       }\r
-    } else if (Variable->CurrPtr == NULL) {\r
+    } else if (Variable->CurrPtr == NULL && PayloadSize != 0) {\r
       //\r
       // Insert signer's certificates when adding a new common authenticated variable.\r
       //\r
@@ -2162,7 +2423,7 @@ VerifyTimeBasedPayload (
     Cert     = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);\r
     RootCert      = Cert->SignatureData;\r
     RootCertSize  = CertList->SignatureSize - (sizeof (EFI_SIGNATURE_DATA) - 1);\r
-    \r
+\r
     // Verify Pkcs7 SignedData via Pkcs7Verify library.\r
     //\r
     VerifyStatus = Pkcs7Verify (\r
@@ -2179,7 +2440,7 @@ VerifyTimeBasedPayload (
 \r
 Exit:\r
 \r
-  if (AuthVarType == AuthVarTypePriv) {\r
+  if (AuthVarType == AuthVarTypePk || AuthVarType == AuthVarTypePriv) {\r
     Pkcs7FreeSigners (RootCert);\r
     Pkcs7FreeSigners (SignerCerts);\r
   }\r
@@ -2212,4 +2473,3 @@ Exit:
            &CertData->TimeStamp\r
            );\r
 }\r
-\r