]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
MdeModulePkg Variable: Abstract GetHobVariableStore function
[mirror_edk2.git] / MdeModulePkg / Universal / Variable / RuntimeDxe / VariableSmm.c
index 8d949c396513e147c29de21ad75e0cc72e8564f7..e495d971a08b1d8df69fddf05d92c9e80d9e40fd 100644 (file)
@@ -1,25 +1,39 @@
 /** @file\r
-\r
-  The sample implementation for SMM variable protocol. And this driver \r
-  implements  an SMI handler to communicate with the DXE runtime driver \r
+  The sample implementation for SMM variable protocol. And this driver\r
+  implements an SMI handler to communicate with the DXE runtime driver\r
   to provide variable services.\r
 \r
-Copyright (c) 2010 - 2011, 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
-http://opensource.org/licenses/bsd-license.php                                            \r
+  Caution: This module requires additional review when modified.\r
+  This driver will have external input - variable data and communicate buffer in SMM mode.\r
+  This external input must be validated carefully to avoid security issue like\r
+  buffer overflow, integer overflow.\r
+\r
+  SmmVariableHandler() will receive untrusted input and do basic validation.\r
+\r
+  Each sub function VariableServiceGetVariable(), VariableServiceGetNextVariableName(),\r
+  VariableServiceSetVariable(), VariableServiceQueryVariableInfo(), ReclaimForOS(),\r
+  SmmVariableGetStatistics() should also do validation based on its own knowledge.\r
 \r
-THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
-WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.  \r
+Copyright (c) 2010 - 2016, 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
+http://opensource.org/licenses/bsd-license.php\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
 \r
 **/\r
+\r
 #include <Protocol/SmmVariable.h>\r
 #include <Protocol/SmmFirmwareVolumeBlock.h>\r
 #include <Protocol/SmmFaultTolerantWrite.h>\r
+#include <Protocol/SmmEndOfDxe.h>\r
+#include <Protocol/SmmVarCheck.h>\r
+\r
 #include <Library/SmmServicesTableLib.h>\r
+#include <Library/SmmMemLib.h>\r
 \r
-#include <Guid/VariableFormat.h>\r
 #include <Guid/SmmVariableCommon.h>\r
 #include "Variable.h"\r
 \r
@@ -27,19 +41,87 @@ extern VARIABLE_INFO_ENTRY                           *gVariableInfo;
 EFI_HANDLE                                           mSmmVariableHandle      = NULL;\r
 EFI_HANDLE                                           mVariableHandle         = NULL;\r
 BOOLEAN                                              mAtRuntime              = FALSE;\r
-EFI_GUID                                             mZeroGuid               = {0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0}};\r
-  \r
+UINT8                                                *mVariableBufferPayload = NULL;\r
+UINTN                                                mVariableBufferPayloadSize;\r
+extern BOOLEAN                                       mEndOfDxe;\r
+extern VAR_CHECK_REQUEST_SOURCE                      mRequestSource;\r
+\r
+/**\r
+  SecureBoot Hook for SetVariable.\r
+\r
+  @param[in] VariableName                 Name of Variable to be found.\r
+  @param[in] VendorGuid                   Variable vendor GUID.\r
+\r
+**/\r
+VOID\r
+EFIAPI\r
+SecureBootHook (\r
+  IN CHAR16                                 *VariableName,\r
+  IN EFI_GUID                               *VendorGuid\r
+  )\r
+{\r
+  return ;\r
+}\r
+\r
+/**\r
+\r
+  This code sets variable in storage blocks (Volatile or Non-Volatile).\r
+\r
+  @param VariableName                     Name of Variable to be found.\r
+  @param VendorGuid                       Variable vendor GUID.\r
+  @param Attributes                       Attribute value of the variable found\r
+  @param DataSize                         Size of Data found. If size is less than the\r
+                                          data, this value contains the required size.\r
+  @param Data                             Data pointer.\r
+\r
+  @return EFI_INVALID_PARAMETER           Invalid parameter.\r
+  @return EFI_SUCCESS                     Set successfully.\r
+  @return EFI_OUT_OF_RESOURCES            Resource not enough to set variable.\r
+  @return EFI_NOT_FOUND                   Not found.\r
+  @return EFI_WRITE_PROTECTED             Variable is read-only.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+SmmVariableSetVariable (\r
+  IN CHAR16                  *VariableName,\r
+  IN EFI_GUID                *VendorGuid,\r
+  IN UINT32                  Attributes,\r
+  IN UINTN                   DataSize,\r
+  IN VOID                    *Data\r
+  )\r
+{\r
+  EFI_STATUS                 Status;\r
+\r
+  //\r
+  // Disable write protection when the calling SetVariable() through EFI_SMM_VARIABLE_PROTOCOL.\r
+  //\r
+  mRequestSource = VarCheckFromTrusted;\r
+  Status         = VariableServiceSetVariable (\r
+                     VariableName,\r
+                     VendorGuid,\r
+                     Attributes,\r
+                     DataSize,\r
+                     Data\r
+                     );\r
+  mRequestSource = VarCheckFromUntrusted;\r
+  return Status;\r
+}\r
+\r
 EFI_SMM_VARIABLE_PROTOCOL      gSmmVariable = {\r
   VariableServiceGetVariable,\r
   VariableServiceGetNextVariableName,\r
-  VariableServiceSetVariable,\r
+  SmmVariableSetVariable,\r
   VariableServiceQueryVariableInfo\r
 };\r
 \r
+EDKII_SMM_VAR_CHECK_PROTOCOL mSmmVarCheck = { VarCheckRegisterSetVariableCheckHandler,\r
+                                              VarCheckVariablePropertySet,\r
+                                              VarCheckVariablePropertyGet };\r
 \r
 /**\r
   Return TRUE if ExitBootServices () has been called.\r
-  \r
+\r
   @retval TRUE If ExitBootServices () has been called.\r
 **/\r
 BOOLEAN\r
@@ -53,8 +135,8 @@ AtRuntime (
 /**\r
   Initializes a basic mutual exclusion lock.\r
 \r
-  This function initializes a basic mutual exclusion lock to the released state \r
-  and returns the lock.  Each lock provides mutual exclusion access at its task \r
+  This function initializes a basic mutual exclusion lock to the released state\r
+  and returns the lock.  Each lock provides mutual exclusion access at its task\r
   priority level.  Since there is no preemption or multiprocessor support in EFI,\r
   acquiring the lock only consists of raising to the locks TPL.\r
   If Lock is NULL, then ASSERT().\r
@@ -117,7 +199,7 @@ ReleaseLockOnlyAtBootTime (
 }\r
 \r
 /**\r
-  Retrive the SMM Fault Tolerent Write protocol interface.\r
+  Retrieve the SMM Fault Tolerent Write protocol interface.\r
 \r
   @param[out] FtwProtocol       The interface of SMM Ftw protocol\r
 \r
@@ -137,8 +219,8 @@ GetFtwProtocol (
   // Locate Smm Fault Tolerent Write protocol\r
   //\r
   Status = gSmst->SmmLocateProtocol (\r
-                    &gEfiSmmFaultTolerantWriteProtocolGuid, \r
-                    NULL, \r
+                    &gEfiSmmFaultTolerantWriteProtocolGuid,\r
+                    NULL,\r
                     FtwProtocol\r
                     );\r
   return Status;\r
@@ -146,7 +228,7 @@ GetFtwProtocol (
 \r
 \r
 /**\r
-  Retrive the SMM FVB protocol interface by HANDLE.\r
+  Retrieve the SMM FVB protocol interface by HANDLE.\r
 \r
   @param[in]  FvBlockHandle     The handle of SMM FVB protocol that provides services for\r
                                 reading, writing, and erasing the target block.\r
@@ -176,7 +258,7 @@ GetFvbByHandle (
 \r
 /**\r
   Function returns an array of handles that support the SMM FVB protocol\r
-  in a buffer allocated from pool. \r
+  in a buffer allocated from pool.\r
 \r
   @param[out]  NumberHandles    The number of handles returned in Buffer.\r
   @param[out]  Buffer           A pointer to the buffer to return the requested\r
@@ -232,6 +314,8 @@ GetFvbCountAndBuffer (
   *NumberHandles = BufferSize / sizeof(EFI_HANDLE);\r
   if (EFI_ERROR(Status)) {\r
     *NumberHandles = 0;\r
+    FreePool (*Buffer);\r
+    *Buffer = NULL;\r
   }\r
 \r
   return Status;\r
@@ -241,17 +325,21 @@ GetFvbCountAndBuffer (
 /**\r
   Get the variable statistics information from the information buffer pointed by gVariableInfo.\r
 \r
-  @param[in, out]  InfoEntry   A pointer to the buffer of variable information entry.\r
-                               On input, point to the variable information returned last time. if \r
-                               InfoEntry->VendorGuid is zero, return the first information.\r
-                               On output, point to the next variable information.\r
-  @param[in, out]  InfoSize    On input, the size of the variable information buffer.\r
-                               On output, the returned variable information size.\r
+  Caution: This function may be invoked at SMM runtime.\r
+  InfoEntry and InfoSize are external input. Care must be taken to make sure not security issue at runtime.\r
 \r
-  @retval EFI_SUCCESS          The variable information is found and returned successfully.\r
-  @retval EFI_UNSUPPORTED      No variable inoformation exists in variable driver. The \r
-                               PcdVariableCollectStatistics should be set TRUE to support it.\r
-  @retval EFI_BUFFER_TOO_SMALL The buffer is too small to hold the next variable information.\r
+  @param[in, out]  InfoEntry    A pointer to the buffer of variable information entry.\r
+                                On input, point to the variable information returned last time. if\r
+                                InfoEntry->VendorGuid is zero, return the first information.\r
+                                On output, point to the next variable information.\r
+  @param[in, out]  InfoSize     On input, the size of the variable information buffer.\r
+                                On output, the returned variable information size.\r
+\r
+  @retval EFI_SUCCESS           The variable information is found and returned successfully.\r
+  @retval EFI_UNSUPPORTED       No variable inoformation exists in variable driver. The\r
+                                PcdVariableCollectStatistics should be set TRUE to support it.\r
+  @retval EFI_BUFFER_TOO_SMALL  The buffer is too small to hold the next variable information.\r
+  @retval EFI_INVALID_PARAMETER Input parameter is invalid.\r
 \r
 **/\r
 EFI_STATUS\r
@@ -261,29 +349,43 @@ SmmVariableGetStatistics (
   )\r
 {\r
   VARIABLE_INFO_ENTRY                                  *VariableInfo;\r
-  UINTN                                                NameLength;\r
+  UINTN                                                NameSize;\r
   UINTN                                                StatisticsInfoSize;\r
   CHAR16                                               *InfoName;\r
\r
-  ASSERT (InfoEntry != NULL);\r
-  VariableInfo = gVariableInfo; \r
+  UINTN                                                InfoNameMaxSize;\r
+  EFI_GUID                                             VendorGuid;\r
+\r
+  if (InfoEntry == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  VariableInfo = gVariableInfo;\r
   if (VariableInfo == NULL) {\r
     return EFI_UNSUPPORTED;\r
   }\r
 \r
-  StatisticsInfoSize = sizeof (VARIABLE_INFO_ENTRY) + StrSize (VariableInfo->Name);\r
-  if (*InfoSize < sizeof (VARIABLE_INFO_ENTRY)) {\r
+  StatisticsInfoSize = sizeof (VARIABLE_INFO_ENTRY);\r
+  if (*InfoSize < StatisticsInfoSize) {\r
     *InfoSize = StatisticsInfoSize;\r
     return EFI_BUFFER_TOO_SMALL;\r
   }\r
   InfoName = (CHAR16 *)(InfoEntry + 1);\r
+  InfoNameMaxSize = (*InfoSize - sizeof (VARIABLE_INFO_ENTRY));\r
+\r
+  CopyGuid (&VendorGuid, &InfoEntry->VendorGuid);\r
 \r
-  if (CompareGuid (&InfoEntry->VendorGuid, &mZeroGuid)) {\r
+  if (IsZeroGuid (&VendorGuid)) {\r
     //\r
     // Return the first variable info\r
     //\r
+    NameSize = StrSize (VariableInfo->Name);\r
+    StatisticsInfoSize = sizeof (VARIABLE_INFO_ENTRY) + NameSize;\r
+    if (*InfoSize < StatisticsInfoSize) {\r
+      *InfoSize = StatisticsInfoSize;\r
+      return EFI_BUFFER_TOO_SMALL;\r
+    }\r
     CopyMem (InfoEntry, VariableInfo, sizeof (VARIABLE_INFO_ENTRY));\r
-    CopyMem (InfoName, VariableInfo->Name, StrSize (VariableInfo->Name));\r
+    CopyMem (InfoName, VariableInfo->Name, NameSize);\r
     *InfoSize = StatisticsInfoSize;\r
     return EFI_SUCCESS;\r
   }\r
@@ -292,10 +394,10 @@ SmmVariableGetStatistics (
   // Get the next variable info\r
   //\r
   while (VariableInfo != NULL) {\r
-    if (CompareGuid (&VariableInfo->VendorGuid, &InfoEntry->VendorGuid)) {\r
-      NameLength = StrSize (VariableInfo->Name);\r
-      if (NameLength == StrSize (InfoName)) {\r
-        if (CompareMem (VariableInfo->Name, InfoName, NameLength) == 0) {\r
+    if (CompareGuid (&VariableInfo->VendorGuid, &VendorGuid)) {\r
+      NameSize = StrSize (VariableInfo->Name);\r
+      if (NameSize <= InfoNameMaxSize) {\r
+        if (CompareMem (VariableInfo->Name, InfoName, NameSize) == 0) {\r
           //\r
           // Find the match one\r
           //\r
@@ -306,7 +408,7 @@ SmmVariableGetStatistics (
     }\r
     VariableInfo = VariableInfo->Next;\r
   };\r
-    \r
+\r
   if (VariableInfo == NULL) {\r
     *InfoSize = 0;\r
     return EFI_SUCCESS;\r
@@ -315,16 +417,17 @@ SmmVariableGetStatistics (
   //\r
   // Output the new variable info\r
   //\r
-  StatisticsInfoSize = sizeof (VARIABLE_INFO_ENTRY) + StrSize (VariableInfo->Name);\r
+  NameSize = StrSize (VariableInfo->Name);\r
+  StatisticsInfoSize = sizeof (VARIABLE_INFO_ENTRY) + NameSize;\r
   if (*InfoSize < StatisticsInfoSize) {\r
     *InfoSize = StatisticsInfoSize;\r
     return EFI_BUFFER_TOO_SMALL;\r
   }\r
 \r
   CopyMem (InfoEntry, VariableInfo, sizeof (VARIABLE_INFO_ENTRY));\r
-  CopyMem (InfoName, VariableInfo->Name, StrSize (VariableInfo->Name));\r
+  CopyMem (InfoName, VariableInfo->Name, NameSize);\r
   *InfoSize = StatisticsInfoSize;\r
-  \r
+\r
   return EFI_SUCCESS;\r
 }\r
 \r
@@ -334,6 +437,12 @@ SmmVariableGetStatistics (
 \r
   This SMI handler provides services for the variable wrapper driver.\r
 \r
+  Caution: This function may receive untrusted input.\r
+  This variable data and communicate buffer are external input, so this function will do basic validation.\r
+  Each sub function VariableServiceGetVariable(), VariableServiceGetNextVariableName(),\r
+  VariableServiceSetVariable(), VariableServiceQueryVariableInfo(), ReclaimForOS(),\r
+  SmmVariableGetStatistics() should also do validation based on its own knowledge.\r
+\r
   @param[in]     DispatchHandle  The unique handle assigned to this handler by SmiHandlerRegister().\r
   @param[in]     RegisterContext Points to an optional handler context which was specified when the\r
                                  handler was registered.\r
@@ -341,11 +450,11 @@ SmmVariableGetStatistics (
                                  be conveyed from a non-SMM environment into an SMM environment.\r
   @param[in, out] CommBufferSize The size of the CommBuffer.\r
 \r
-  @retval EFI_SUCCESS                         The interrupt was handled and quiesced. No other handlers \r
+  @retval EFI_SUCCESS                         The interrupt was handled and quiesced. No other handlers\r
                                               should still be called.\r
-  @retval EFI_WARN_INTERRUPT_SOURCE_QUIESCED  The interrupt has been quiesced but other handlers should \r
+  @retval EFI_WARN_INTERRUPT_SOURCE_QUIESCED  The interrupt has been quiesced but other handlers should\r
                                               still be called.\r
-  @retval EFI_WARN_INTERRUPT_SOURCE_PENDING   The interrupt is still pending and other handlers should still \r
+  @retval EFI_WARN_INTERRUPT_SOURCE_PENDING   The interrupt is still pending and other handlers should still\r
                                               be called.\r
   @retval EFI_INTERRUPT_PENDING               The interrupt could not be quiesced.\r
 **/\r
@@ -363,15 +472,79 @@ SmmVariableHandler (
   SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE         *SmmVariableHeader;\r
   SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME  *GetNextVariableName;\r
   SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO     *QueryVariableInfo;\r
+  SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE        *GetPayloadSize;\r
   VARIABLE_INFO_ENTRY                              *VariableInfo;\r
+  SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE           *VariableToLock;\r
+  SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY *CommVariableProperty;\r
   UINTN                                            InfoSize;\r
+  UINTN                                            NameBufferSize;\r
+  UINTN                                            CommBufferPayloadSize;\r
+  UINTN                                            TempCommBufferSize;\r
+\r
+  //\r
+  // If input is invalid, stop processing this SMI\r
+  //\r
+  if (CommBuffer == NULL || CommBufferSize == NULL) {\r
+    return EFI_SUCCESS;\r
+  }\r
+\r
+  TempCommBufferSize = *CommBufferSize;\r
+\r
+  if (TempCommBufferSize < SMM_VARIABLE_COMMUNICATE_HEADER_SIZE) {\r
+    DEBUG ((EFI_D_ERROR, "SmmVariableHandler: SMM communication buffer size invalid!\n"));\r
+    return EFI_SUCCESS;\r
+  }\r
+  CommBufferPayloadSize = TempCommBufferSize - SMM_VARIABLE_COMMUNICATE_HEADER_SIZE;\r
+  if (CommBufferPayloadSize > mVariableBufferPayloadSize) {\r
+    DEBUG ((EFI_D_ERROR, "SmmVariableHandler: SMM communication buffer payload size invalid!\n"));\r
+    return EFI_SUCCESS;\r
+  }\r
 \r
-  ASSERT (CommBuffer != NULL);\r
+  if (!SmmIsBufferOutsideSmmValid ((UINTN)CommBuffer, TempCommBufferSize)) {\r
+    DEBUG ((EFI_D_ERROR, "SmmVariableHandler: SMM communication buffer in SMRAM or overflow!\n"));\r
+    return EFI_SUCCESS;\r
+  }\r
 \r
   SmmVariableFunctionHeader = (SMM_VARIABLE_COMMUNICATE_HEADER *)CommBuffer;\r
   switch (SmmVariableFunctionHeader->Function) {\r
     case SMM_VARIABLE_FUNCTION_GET_VARIABLE:\r
-      SmmVariableHeader = (SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE *) SmmVariableFunctionHeader->Data;     \r
+      if (CommBufferPayloadSize < OFFSET_OF(SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name)) {\r
+        DEBUG ((EFI_D_ERROR, "GetVariable: SMM communication buffer size invalid!\n"));\r
+        return EFI_SUCCESS;\r
+      }\r
+      //\r
+      // Copy the input communicate buffer payload to pre-allocated SMM variable buffer payload.\r
+      //\r
+      CopyMem (mVariableBufferPayload, SmmVariableFunctionHeader->Data, CommBufferPayloadSize);\r
+      SmmVariableHeader = (SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE *) mVariableBufferPayload;\r
+      if (((UINTN)(~0) - SmmVariableHeader->DataSize < OFFSET_OF(SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name)) ||\r
+         ((UINTN)(~0) - SmmVariableHeader->NameSize < OFFSET_OF(SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name) + SmmVariableHeader->DataSize)) {\r
+        //\r
+        // Prevent InfoSize overflow happen\r
+        //\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto EXIT;\r
+      }\r
+      InfoSize = OFFSET_OF(SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name)\r
+                 + SmmVariableHeader->DataSize + SmmVariableHeader->NameSize;\r
+\r
+      //\r
+      // SMRAM range check already covered before\r
+      //\r
+      if (InfoSize > CommBufferPayloadSize) {\r
+        DEBUG ((EFI_D_ERROR, "GetVariable: Data size exceed communication buffer size limit!\n"));\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto EXIT;\r
+      }\r
+\r
+      if (SmmVariableHeader->NameSize < sizeof (CHAR16) || SmmVariableHeader->Name[SmmVariableHeader->NameSize/sizeof (CHAR16) - 1] != L'\0') {\r
+        //\r
+        // Make sure VariableName is A Null-terminated string.\r
+        //\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto EXIT;\r
+      }\r
+\r
       Status = VariableServiceGetVariable (\r
                  SmmVariableHeader->Name,\r
                  &SmmVariableHeader->Guid,\r
@@ -379,19 +552,93 @@ SmmVariableHandler (
                  &SmmVariableHeader->DataSize,\r
                  (UINT8 *)SmmVariableHeader->Name + SmmVariableHeader->NameSize\r
                  );\r
+      CopyMem (SmmVariableFunctionHeader->Data, mVariableBufferPayload, CommBufferPayloadSize);\r
       break;\r
-      \r
+\r
     case SMM_VARIABLE_FUNCTION_GET_NEXT_VARIABLE_NAME:\r
-      GetNextVariableName = (SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME *) SmmVariableFunctionHeader->Data;\r
+      if (CommBufferPayloadSize < OFFSET_OF(SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME, Name)) {\r
+        DEBUG ((EFI_D_ERROR, "GetNextVariableName: SMM communication buffer size invalid!\n"));\r
+        return EFI_SUCCESS;\r
+      }\r
+      //\r
+      // Copy the input communicate buffer payload to pre-allocated SMM variable buffer payload.\r
+      //\r
+      CopyMem (mVariableBufferPayload, SmmVariableFunctionHeader->Data, CommBufferPayloadSize);\r
+      GetNextVariableName = (SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME *) mVariableBufferPayload;\r
+      if ((UINTN)(~0) - GetNextVariableName->NameSize < OFFSET_OF(SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME, Name)) {\r
+        //\r
+        // Prevent InfoSize overflow happen\r
+        //\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto EXIT;\r
+      }\r
+      InfoSize = OFFSET_OF(SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME, Name) + GetNextVariableName->NameSize;\r
+\r
+      //\r
+      // SMRAM range check already covered before\r
+      //\r
+      if (InfoSize > CommBufferPayloadSize) {\r
+        DEBUG ((EFI_D_ERROR, "GetNextVariableName: Data size exceed communication buffer size limit!\n"));\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto EXIT;\r
+      }\r
+\r
+      NameBufferSize = CommBufferPayloadSize - OFFSET_OF(SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME, Name);\r
+      if (NameBufferSize < sizeof (CHAR16) || GetNextVariableName->Name[NameBufferSize/sizeof (CHAR16) - 1] != L'\0') {\r
+        //\r
+        // Make sure input VariableName is A Null-terminated string.\r
+        //\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto EXIT;\r
+      }\r
+\r
       Status = VariableServiceGetNextVariableName (\r
                  &GetNextVariableName->NameSize,\r
                  GetNextVariableName->Name,\r
                  &GetNextVariableName->Guid\r
                  );\r
+      CopyMem (SmmVariableFunctionHeader->Data, mVariableBufferPayload, CommBufferPayloadSize);\r
       break;\r
-      \r
+\r
     case SMM_VARIABLE_FUNCTION_SET_VARIABLE:\r
-      SmmVariableHeader = (SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE *) SmmVariableFunctionHeader->Data;\r
+      if (CommBufferPayloadSize < OFFSET_OF(SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name)) {\r
+        DEBUG ((EFI_D_ERROR, "SetVariable: SMM communication buffer size invalid!\n"));\r
+        return EFI_SUCCESS;\r
+      }\r
+      //\r
+      // Copy the input communicate buffer payload to pre-allocated SMM variable buffer payload.\r
+      //\r
+      CopyMem (mVariableBufferPayload, SmmVariableFunctionHeader->Data, CommBufferPayloadSize);\r
+      SmmVariableHeader = (SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE *) mVariableBufferPayload;\r
+      if (((UINTN)(~0) - SmmVariableHeader->DataSize < OFFSET_OF(SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name)) ||\r
+         ((UINTN)(~0) - SmmVariableHeader->NameSize < OFFSET_OF(SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name) + SmmVariableHeader->DataSize)) {\r
+        //\r
+        // Prevent InfoSize overflow happen\r
+        //\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto EXIT;\r
+      }\r
+      InfoSize = OFFSET_OF(SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name)\r
+                 + SmmVariableHeader->DataSize + SmmVariableHeader->NameSize;\r
+\r
+      //\r
+      // SMRAM range check already covered before\r
+      // Data buffer should not contain SMM range\r
+      //\r
+      if (InfoSize > CommBufferPayloadSize) {\r
+        DEBUG ((EFI_D_ERROR, "SetVariable: Data size exceed communication buffer size limit!\n"));\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto EXIT;\r
+      }\r
+\r
+      if (SmmVariableHeader->NameSize < sizeof (CHAR16) || SmmVariableHeader->Name[SmmVariableHeader->NameSize/sizeof (CHAR16) - 1] != L'\0') {\r
+        //\r
+        // Make sure VariableName is A Null-terminated string.\r
+        //\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto EXIT;\r
+      }\r
+\r
       Status = VariableServiceSetVariable (\r
                  SmmVariableHeader->Name,\r
                  &SmmVariableHeader->Guid,\r
@@ -400,9 +647,14 @@ SmmVariableHandler (
                  (UINT8 *)SmmVariableHeader->Name + SmmVariableHeader->NameSize\r
                  );\r
       break;\r
-      \r
+\r
     case SMM_VARIABLE_FUNCTION_QUERY_VARIABLE_INFO:\r
+      if (CommBufferPayloadSize < sizeof (SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO)) {\r
+        DEBUG ((EFI_D_ERROR, "QueryVariableInfo: SMM communication buffer size invalid!\n"));\r
+        return EFI_SUCCESS;\r
+      }\r
       QueryVariableInfo = (SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO *) SmmVariableFunctionHeader->Data;\r
+\r
       Status = VariableServiceQueryVariableInfo (\r
                  QueryVariableInfo->Attributes,\r
                  &QueryVariableInfo->MaximumVariableStorageSize,\r
@@ -411,11 +663,34 @@ SmmVariableHandler (
                  );\r
       break;\r
 \r
+    case SMM_VARIABLE_FUNCTION_GET_PAYLOAD_SIZE:\r
+      if (CommBufferPayloadSize < sizeof (SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE)) {\r
+        DEBUG ((EFI_D_ERROR, "GetPayloadSize: SMM communication buffer size invalid!\n"));\r
+        return EFI_SUCCESS;\r
+      }\r
+      GetPayloadSize = (SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE *) SmmVariableFunctionHeader->Data;\r
+      GetPayloadSize->VariablePayloadSize = mVariableBufferPayloadSize;\r
+      Status = EFI_SUCCESS;\r
+      break;\r
+\r
     case SMM_VARIABLE_FUNCTION_READY_TO_BOOT:\r
+      if (AtRuntime()) {\r
+        Status = EFI_UNSUPPORTED;\r
+        break;\r
+      }\r
+      if (!mEndOfDxe) {\r
+        MorLockInitAtEndOfDxe ();\r
+        mEndOfDxe = TRUE;\r
+        VarCheckLibInitializeAtEndOfDxe (NULL);\r
+        //\r
+        // The initialization for variable quota.\r
+        //\r
+        InitializeVariableQuota ();\r
+      }\r
       ReclaimForOS ();\r
       Status = EFI_SUCCESS;\r
       break;\r
-  \r
+\r
     case SMM_VARIABLE_FUNCTION_EXIT_BOOT_SERVICE:\r
       mAtRuntime = TRUE;\r
       Status = EFI_SUCCESS;\r
@@ -423,35 +698,147 @@ SmmVariableHandler (
 \r
     case SMM_VARIABLE_FUNCTION_GET_STATISTICS:\r
       VariableInfo = (VARIABLE_INFO_ENTRY *) SmmVariableFunctionHeader->Data;\r
-      InfoSize = *CommBufferSize - OFFSET_OF (SMM_VARIABLE_COMMUNICATE_HEADER, Data);\r
+      InfoSize = TempCommBufferSize - SMM_VARIABLE_COMMUNICATE_HEADER_SIZE;\r
+\r
+      //\r
+      // Do not need to check SmmVariableFunctionHeader->Data in SMRAM here.\r
+      // It is covered by previous CommBuffer check\r
+      //\r
+\r
+      //\r
+      // Do not need to check CommBufferSize buffer as it should point to SMRAM\r
+      // that was used by SMM core to cache CommSize from SmmCommunication protocol.\r
+      //\r
+\r
       Status = SmmVariableGetStatistics (VariableInfo, &InfoSize);\r
-      *CommBufferSize = InfoSize + OFFSET_OF (SMM_VARIABLE_COMMUNICATE_HEADER, Data);\r
+      *CommBufferSize = InfoSize + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE;\r
+      break;\r
+\r
+    case SMM_VARIABLE_FUNCTION_LOCK_VARIABLE:\r
+      if (mEndOfDxe) {\r
+        Status = EFI_ACCESS_DENIED;\r
+      } else {\r
+        VariableToLock = (SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE *) SmmVariableFunctionHeader->Data;\r
+        Status = VariableLockRequestToLock (\r
+                   NULL,\r
+                   VariableToLock->Name,\r
+                   &VariableToLock->Guid\r
+                   );\r
+      }\r
+      break;\r
+    case SMM_VARIABLE_FUNCTION_VAR_CHECK_VARIABLE_PROPERTY_SET:\r
+      if (mEndOfDxe) {\r
+        Status = EFI_ACCESS_DENIED;\r
+      } else {\r
+        CommVariableProperty = (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY *) SmmVariableFunctionHeader->Data;\r
+        Status = VarCheckVariablePropertySet (\r
+                   CommVariableProperty->Name,\r
+                   &CommVariableProperty->Guid,\r
+                   &CommVariableProperty->VariableProperty\r
+                   );\r
+      }\r
+      break;\r
+    case SMM_VARIABLE_FUNCTION_VAR_CHECK_VARIABLE_PROPERTY_GET:\r
+      if (CommBufferPayloadSize < OFFSET_OF (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY, Name)) {\r
+        DEBUG ((EFI_D_ERROR, "VarCheckVariablePropertyGet: SMM communication buffer size invalid!\n"));\r
+        return EFI_SUCCESS;\r
+      }\r
+      //\r
+      // Copy the input communicate buffer payload to pre-allocated SMM variable buffer payload.\r
+      //\r
+      CopyMem (mVariableBufferPayload, SmmVariableFunctionHeader->Data, CommBufferPayloadSize);\r
+      CommVariableProperty = (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY *) mVariableBufferPayload;\r
+      if ((UINTN) (~0) - CommVariableProperty->NameSize < OFFSET_OF (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY, Name)) {\r
+        //\r
+        // Prevent InfoSize overflow happen\r
+        //\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto EXIT;\r
+      }\r
+      InfoSize = OFFSET_OF (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY, Name) + CommVariableProperty->NameSize;\r
+\r
+      //\r
+      // SMRAM range check already covered before\r
+      //\r
+      if (InfoSize > CommBufferPayloadSize) {\r
+        DEBUG ((EFI_D_ERROR, "VarCheckVariablePropertyGet: Data size exceed communication buffer size limit!\n"));\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto EXIT;\r
+      }\r
+\r
+      if (CommVariableProperty->NameSize < sizeof (CHAR16) || CommVariableProperty->Name[CommVariableProperty->NameSize/sizeof (CHAR16) - 1] != L'\0') {\r
+        //\r
+        // Make sure VariableName is A Null-terminated string.\r
+        //\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto EXIT;\r
+      }\r
+\r
+      Status = VarCheckVariablePropertyGet (\r
+                 CommVariableProperty->Name,\r
+                 &CommVariableProperty->Guid,\r
+                 &CommVariableProperty->VariableProperty\r
+                 );\r
+      CopyMem (SmmVariableFunctionHeader->Data, mVariableBufferPayload, CommBufferPayloadSize);\r
       break;\r
 \r
     default:\r
-      ASSERT (FALSE);\r
       Status = EFI_UNSUPPORTED;\r
   }\r
 \r
+EXIT:\r
+\r
   SmmVariableFunctionHeader->ReturnStatus = Status;\r
 \r
   return EFI_SUCCESS;\r
 }\r
 \r
+/**\r
+  SMM END_OF_DXE protocol notification event handler.\r
+\r
+  @param  Protocol   Points to the protocol's unique identifier\r
+  @param  Interface  Points to the interface instance\r
+  @param  Handle     The handle on which the interface was installed\r
+\r
+  @retval EFI_SUCCESS   SmmEndOfDxeCallback runs successfully\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+SmmEndOfDxeCallback (\r
+  IN CONST EFI_GUID                       *Protocol,\r
+  IN VOID                                 *Interface,\r
+  IN EFI_HANDLE                           Handle\r
+  )\r
+{\r
+  DEBUG ((EFI_D_INFO, "[Variable]SMM_END_OF_DXE is signaled\n"));\r
+  MorLockInitAtEndOfDxe ();\r
+  mEndOfDxe = TRUE;\r
+  VarCheckLibInitializeAtEndOfDxe (NULL);\r
+  //\r
+  // The initialization for variable quota.\r
+  //\r
+  InitializeVariableQuota ();\r
+  if (PcdGetBool (PcdReclaimVariableSpaceAtEndOfDxe)) {\r
+    ReclaimForOS ();\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
 \r
 /**\r
   SMM Fault Tolerant Write protocol notification event handler.\r
 \r
-  Non-Volatile variable write may needs FTW protocol to reclaim when \r
+  Non-Volatile variable write may needs FTW protocol to reclaim when\r
   writting variable.\r
-  \r
+\r
   @param  Protocol   Points to the protocol's unique identifier\r
   @param  Interface  Points to the interface instance\r
   @param  Handle     The handle on which the interface was installed\r
 \r
   @retval EFI_SUCCESS   SmmEventCallback runs successfully\r
   @retval EFI_NOT_FOUND The Fvb protocol for variable is not found.\r
-  \r
+\r
  **/\r
 EFI_STATUS\r
 EFIAPI\r
@@ -465,7 +852,8 @@ SmmFtwNotificationEvent (
   EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *FvbProtocol;\r
   EFI_SMM_FAULT_TOLERANT_WRITE_PROTOCOL   *FtwProtocol;\r
   EFI_PHYSICAL_ADDRESS                    NvStorageVariableBase;\r
-  \r
+  UINTN                                   FtwMaxBlockSize;\r
+\r
   if (mVariableModuleGlobal->FvbInstance != NULL) {\r
     return EFI_SUCCESS;\r
   }\r
@@ -478,6 +866,11 @@ SmmFtwNotificationEvent (
     return Status;\r
   }\r
 \r
+  Status = FtwProtocol->GetMaxBlockSize (FtwProtocol, &FtwMaxBlockSize);\r
+  if (!EFI_ERROR (Status)) {\r
+    ASSERT (PcdGet32 (PcdFlashNvStorageVariableSize) <= FtwMaxBlockSize);\r
+  }\r
+\r
   //\r
   // Find the proper FVB protocol for variable.\r
   //\r
@@ -491,10 +884,12 @@ SmmFtwNotificationEvent (
   }\r
 \r
   mVariableModuleGlobal->FvbInstance = FvbProtocol;\r
-  \r
+\r
   Status = VariableWriteServiceInitialize ();\r
-  ASSERT_EFI_ERROR (Status);\r
\r
+  if (EFI_ERROR (Status)) {\r
+    DEBUG ((DEBUG_ERROR, "Variable write service initialization failed. Status = %r\n", Status));\r
+  }\r
+\r
   //\r
   // Notify the variable wrapper driver the variable write service is ready\r
   //\r
@@ -505,20 +900,20 @@ SmmFtwNotificationEvent (
                   NULL\r
                   );\r
   ASSERT_EFI_ERROR (Status);\r
-  \r
+\r
   return EFI_SUCCESS;\r
 }\r
 \r
 \r
 /**\r
   Variable Driver main entry point. The Variable driver places the 4 EFI\r
-  runtime services in the EFI System Table and installs arch protocols \r
+  runtime services in the EFI System Table and installs arch protocols\r
   for variable read and write services being available. It also registers\r
   a notification function for an EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE event.\r
 \r
-  @param[in] ImageHandle    The firmware allocated handle for the EFI image.  \r
+  @param[in] ImageHandle    The firmware allocated handle for the EFI image.\r
   @param[in] SystemTable    A pointer to the EFI System Table.\r
-  \r
+\r
   @retval EFI_SUCCESS       Variable service successfully initialized.\r
 \r
 **/\r
@@ -532,7 +927,8 @@ VariableServiceInitialize (
   EFI_STATUS                              Status;\r
   EFI_HANDLE                              VariableHandle;\r
   VOID                                    *SmmFtwRegistration;\r
-  \r
+  VOID                                    *SmmEndOfDxeRegistration;\r
+\r
   //\r
   // Variable initialize.\r
   //\r
@@ -551,13 +947,31 @@ VariableServiceInitialize (
                     );\r
   ASSERT_EFI_ERROR (Status);\r
 \r
+  Status = gSmst->SmmInstallProtocolInterface (\r
+                    &VariableHandle,\r
+                    &gEdkiiSmmVarCheckProtocolGuid,\r
+                    EFI_NATIVE_INTERFACE,\r
+                    &mSmmVarCheck\r
+                    );\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  mVariableBufferPayloadSize = GetMaxVariableSize () +\r
+                               OFFSET_OF (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY, Name) - GetVariableHeaderSize ();\r
+\r
+  Status = gSmst->SmmAllocatePool (\r
+                    EfiRuntimeServicesData,\r
+                    mVariableBufferPayloadSize,\r
+                    (VOID **)&mVariableBufferPayload\r
+                    );\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
   ///\r
   /// Register SMM variable SMI handler\r
   ///\r
   VariableHandle = NULL;\r
   Status = gSmst->SmiHandlerRegister (SmmVariableHandler, &gEfiSmmVariableProtocolGuid, &VariableHandle);\r
   ASSERT_EFI_ERROR (Status);\r
-  \r
+\r
   //\r
   // Notify the variable wrapper driver the variable service is ready\r
   //\r
@@ -568,10 +982,20 @@ VariableServiceInitialize (
                                         &gSmmVariable\r
                                         );\r
   ASSERT_EFI_ERROR (Status);\r
\r
+\r
+  //\r
+  // Register EFI_SMM_END_OF_DXE_PROTOCOL_GUID notify function.\r
+  //\r
+  Status = gSmst->SmmRegisterProtocolNotify (\r
+                    &gEfiSmmEndOfDxeProtocolGuid,\r
+                    SmmEndOfDxeCallback,\r
+                    &SmmEndOfDxeRegistration\r
+                    );\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
   //\r
   // Register FtwNotificationEvent () notify function.\r
-  // \r
+  //\r
   Status = gSmst->SmmRegisterProtocolNotify (\r
                     &gEfiSmmFaultTolerantWriteProtocolGuid,\r
                     SmmFtwNotificationEvent,\r
@@ -580,7 +1004,7 @@ VariableServiceInitialize (
   ASSERT_EFI_ERROR (Status);\r
 \r
   SmmFtwNotificationEvent (NULL, NULL, NULL);\r
-  \r
+\r
   return EFI_SUCCESS;\r
 }\r
 \r