X-Git-Url: https://git.proxmox.com/?p=mirror_edk2.git;a=blobdiff_plain;f=SecurityPkg%2FVariableAuthenticated%2FRuntimeDxe%2FVariable.c;h=ce4f6e813ef833b800ac3223b8f6459cd6746bd0;hp=df8b30a63e5f004c56de81495773bd1f3b2d0acf;hb=5767f22fca7c337cdc113e14b411c1fd0ea7bd53;hpb=648f98d15b5811ff9cf649bda8b762d50b735798 diff --git a/SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c b/SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c index df8b30a63e..ce4f6e813e 100644 --- a/SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c +++ b/SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c @@ -1,14 +1,28 @@ /** @file - The common variable operation routines shared by DXE_RINTIME variable + The common variable operation routines shared by DXE_RUNTIME variable module and DXE_SMM variable module. -Copyright (c) 2009 - 2011, Intel Corporation. All rights reserved.
-This program and the accompanying materials -are licensed and made available under the terms and conditions of the BSD License -which accompanies this distribution. The full text of the license may be found at + Caution: This module requires additional review when modified. + This driver will have external input - variable data. They may be input in SMM mode. + This external input must be validated carefully to avoid security issue like + buffer overflow, integer overflow. + + VariableServiceGetNextVariableName () and VariableServiceQueryVariableInfo() are external API. + They need check input parameter. + + VariableServiceGetVariable() and VariableServiceSetVariable() are external API + to receive datasize and data buffer. The size should be checked carefully. + + VariableServiceSetVariable() should also check authenticate data to avoid buffer overflow, + integer overflow. It should also check attribute to avoid authentication bypass. + +Copyright (c) 2009 - 2013, Intel Corporation. All rights reserved.
+This program and the accompanying materials +are licensed and made available under the terms and conditions of the BSD License +which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php -THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ @@ -30,13 +44,13 @@ VARIABLE_INFO_ENTRY *gVariableInfo = NULL; /** - Routine used to track statistical information about variable usage. + Routine used to track statistical information about variable usage. The data is stored in the EFI system table so it can be accessed later. - VariableInfo.efi can dump out the table. Only Boot Services variable + VariableInfo.efi can dump out the table. Only Boot Services variable accesses are tracked by this code. The PcdVariableCollectStatistics - build flag controls if this feature is enabled. + build flag controls if this feature is enabled. - A read that hits in the cache will have Read and Cache true for + A read that hits in the cache will have Read and Cache true for the transaction. Data is allocated by this routine, but never freed. @@ -84,7 +98,7 @@ UpdateVariableInfo ( gVariableInfo->Volatile = Volatile; } - + for (Entry = gVariableInfo; Entry != NULL; Entry = Entry->Next) { if (CompareGuid (VendorGuid, &Entry->VendorGuid)) { if (StrCmp (VariableName, Entry->Name) == 0) { @@ -230,14 +244,14 @@ UpdateVariableStore ( if ((DataPtr + DataSize) >= ((UINTN) ((UINT8 *) VolatileBase + VolatileBase->Size))) { return EFI_INVALID_PARAMETER; } - + // // If Volatile Variable just do a simple mem copy. - // + // CopyMem ((UINT8 *)(UINTN)DataPtr, Buffer, DataSize); return EFI_SUCCESS; } - + // // If we are here we are dealing with Non-Volatile Variables. // @@ -412,7 +426,7 @@ GetVariableDataPtr ( ) { UINTN Value; - + // // Be careful about pad size for alignment. // @@ -483,7 +497,7 @@ GetStartPointer ( @param VarStoreHeader Pointer to the Variable Store Header. - @return Pointer to the end of the variable storage area. + @return Pointer to the end of the variable storage area. **/ VARIABLE_HEADER * @@ -497,20 +511,157 @@ GetEndPointer ( return (VARIABLE_HEADER *) HEADER_ALIGN ((UINTN) VarStoreHeader + VarStoreHeader->Size); } +/** + + Check the PubKeyIndex is a valid key or not. + + This function will iterate the NV storage to see if this PubKeyIndex is still referenced + by any valid count-based auth variabe. + + @param[in] PubKeyIndex Index of the public key in public key store. + + @retval TRUE The PubKeyIndex is still in use. + @retval FALSE The PubKeyIndex is not referenced by any count-based auth variabe. + +**/ +BOOLEAN +IsValidPubKeyIndex ( + IN UINT32 PubKeyIndex + ) +{ + VARIABLE_HEADER *Variable; + + if (PubKeyIndex > mPubKeyNumber) { + return FALSE; + } + + Variable = GetStartPointer (mNvVariableCache); + + while (IsValidVariableHeader (Variable)) { + if ((Variable->State == VAR_ADDED || Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) && + Variable->PubKeyIndex == PubKeyIndex) { + return TRUE; + } + Variable = GetNextVariablePtr (Variable); + } + + return FALSE; +} /** - Variable store garbage collection and reclaim operation. + Get the number of valid public key in PubKeyStore. + + @param[in] PubKeyNumber Number of the public key in public key store. + + @return Number of valid public key in PubKeyStore. + +**/ +UINT32 +GetValidPubKeyNumber ( + IN UINT32 PubKeyNumber + ) +{ + UINT32 PubKeyIndex; + UINT32 Counter; + + Counter = 0; + + for (PubKeyIndex = 1; PubKeyIndex <= PubKeyNumber; PubKeyIndex++) { + if (IsValidPubKeyIndex (PubKeyIndex)) { + Counter++; + } + } + + return Counter; +} + +/** + + Filter the useless key in public key store. + + This function will find out all valid public keys in public key database, save them in new allocated + buffer NewPubKeyStore, and give the new PubKeyIndex. The caller is responsible for freeing buffer + NewPubKeyIndex and NewPubKeyStore with FreePool(). + + @param[in] PubKeyStore Point to the public key database. + @param[in] PubKeyNumber Number of the public key in PubKeyStore. + @param[out] NewPubKeyIndex Point to an array of new PubKeyIndex corresponds to NewPubKeyStore. + @param[out] NewPubKeyStore Saved all valid public keys in PubKeyStore. + @param[out] NewPubKeySize Buffer size of the NewPubKeyStore. + + @retval EFI_SUCCESS Trim operation is complete successfully. + @retval EFI_OUT_OF_RESOURCES No enough memory resources, or no useless key in PubKeyStore. + +**/ +EFI_STATUS +PubKeyStoreFilter ( + IN UINT8 *PubKeyStore, + IN UINT32 PubKeyNumber, + OUT UINT32 **NewPubKeyIndex, + OUT UINT8 **NewPubKeyStore, + OUT UINT32 *NewPubKeySize + ) +{ + UINT32 PubKeyIndex; + UINT32 CopiedKey; + UINT32 NewPubKeyNumber; + + NewPubKeyNumber = GetValidPubKeyNumber (PubKeyNumber); + if (NewPubKeyNumber == PubKeyNumber) { + return EFI_OUT_OF_RESOURCES; + } + + if (NewPubKeyNumber != 0) { + *NewPubKeySize = NewPubKeyNumber * EFI_CERT_TYPE_RSA2048_SIZE; + } else { + *NewPubKeySize = sizeof (UINT8); + } + + *NewPubKeyStore = AllocatePool (*NewPubKeySize); + if (*NewPubKeyStore == NULL) { + return EFI_OUT_OF_RESOURCES; + } - @param VariableBase Base address of variable store. - @param LastVariableOffset Offset of last variable. - @param IsVolatile The variable store is volatile or not; - if it is non-volatile, need FTW. - @param UpdatingVariable Pointer to updating variable. + *NewPubKeyIndex = AllocateZeroPool ((PubKeyNumber + 1) * sizeof (UINT32)); + if (*NewPubKeyIndex == NULL) { + FreePool (*NewPubKeyStore); + return EFI_OUT_OF_RESOURCES; + } + + CopiedKey = 0; + for (PubKeyIndex = 1; PubKeyIndex <= PubKeyNumber; PubKeyIndex++) { + if (IsValidPubKeyIndex (PubKeyIndex)) { + CopyMem ( + *NewPubKeyStore + CopiedKey * EFI_CERT_TYPE_RSA2048_SIZE, + PubKeyStore + (PubKeyIndex - 1) * EFI_CERT_TYPE_RSA2048_SIZE, + EFI_CERT_TYPE_RSA2048_SIZE + ); + (*NewPubKeyIndex)[PubKeyIndex] = ++CopiedKey; + } + } + return EFI_SUCCESS; +} + +/** + + Variable store garbage collection and reclaim operation. - @return EFI_OUT_OF_RESOURCES - @return EFI_SUCCESS - @return Others + If ReclaimPubKeyStore is FALSE, reclaim variable space by deleting the obsoleted varaibles. + If ReclaimPubKeyStore is TRUE, reclaim invalid key in public key database and update the PubKeyIndex + for all the count-based authenticate variable in NV storage. + + @param[in] VariableBase Base address of variable store. + @param[out] LastVariableOffset Offset of last variable. + @param[in] IsVolatile The variable store is volatile or not; + if it is non-volatile, need FTW. + @param[in, out] UpdatingPtrTrack Pointer to updating variable pointer track structure. + @param[in] ReclaimPubKeyStore Reclaim for public key database or not. + @param[in] ReclaimAnyway If TRUE, do reclaim anyway. + + @return EFI_OUT_OF_RESOURCES No enough memory resources. + @return EFI_SUCCESS Reclaim operation has finished successfully. + @return Others Unexpect error happened during reclaim operation. **/ EFI_STATUS @@ -518,7 +669,9 @@ Reclaim ( IN EFI_PHYSICAL_ADDRESS VariableBase, OUT UINTN *LastVariableOffset, IN BOOLEAN IsVolatile, - IN VARIABLE_HEADER *UpdatingVariable + IN OUT VARIABLE_POINTER_TRACK *UpdatingPtrTrack, + IN BOOLEAN ReclaimPubKeyStore, + IN BOOLEAN ReclaimAnyway ) { VARIABLE_HEADER *Variable; @@ -539,16 +692,30 @@ Reclaim ( EFI_STATUS Status; CHAR16 *VariableNamePtr; CHAR16 *UpdatingVariableNamePtr; + UINTN CommonVariableTotalSize; + UINTN HwErrVariableTotalSize; + UINT32 *NewPubKeyIndex; + UINT8 *NewPubKeyStore; + UINT32 NewPubKeySize; + VARIABLE_HEADER *PubKeyHeader; + BOOLEAN NeedDoReclaim; + VARIABLE_HEADER *UpdatingVariable; + + UpdatingVariable = NULL; + if (UpdatingPtrTrack != NULL) { + UpdatingVariable = UpdatingPtrTrack->CurrPtr; + } + NeedDoReclaim = FALSE; VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) VariableBase); - // - // Recalculate the total size of Common/HwErr type variables in non-volatile area. - // - if (!IsVolatile) { - mVariableModuleGlobal->CommonVariableTotalSize = 0; - mVariableModuleGlobal->HwErrVariableTotalSize = 0; - } + CommonVariableTotalSize = 0; + HwErrVariableTotalSize = 0; + NewPubKeyIndex = NULL; + NewPubKeyStore = NULL; + NewPubKeySize = 0; + PubKeyHeader = NULL; + // // Start Pointers for the variable. // @@ -557,20 +724,27 @@ Reclaim ( while (IsValidVariableHeader (Variable)) { NextVariable = GetNextVariablePtr (Variable); - if (Variable->State == VAR_ADDED || + if (Variable->State == VAR_ADDED || Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED) ) { VariableSize = (UINTN) NextVariable - (UINTN) Variable; MaximumBufferSize += VariableSize; + } else { + NeedDoReclaim = TRUE; } Variable = NextVariable; } + if (!ReclaimAnyway && !NeedDoReclaim) { + DEBUG ((EFI_D_INFO, "Variable driver: no DELETED variable found, so no variable space could be reclaimed.\n")); + return EFI_SUCCESS; + } + + // + // Reserve the 1 Bytes with Oxff to identify the + // end of the variable buffer. // - // Reserve the 1 Bytes with Oxff to identify the - // end of the variable buffer. - // MaximumBufferSize += 1; ValidBuffer = AllocatePool (MaximumBufferSize); if (ValidBuffer == NULL) { @@ -585,105 +759,166 @@ Reclaim ( CopyMem (ValidBuffer, VariableStoreHeader, sizeof (VARIABLE_STORE_HEADER)); CurrPtr = (UINT8 *) GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer); - // - // Reinstall all ADDED variables as long as they are not identical to Updating Variable. - // - Variable = GetStartPointer (VariableStoreHeader); - while (IsValidVariableHeader (Variable)) { - NextVariable = GetNextVariablePtr (Variable); - if (Variable->State == VAR_ADDED) { - if (UpdatingVariable != NULL) { - if (UpdatingVariable == Variable) { - Variable = NextVariable; - continue; - } - - VariableNameSize = NameSizeOfVariable(Variable); - UpdatingVariableNameSize = NameSizeOfVariable(UpdatingVariable); + if (ReclaimPubKeyStore) { + // + // Trim the PubKeyStore and get new PubKeyIndex. + // + Status = PubKeyStoreFilter ( + mPubKeyStore, + mPubKeyNumber, + &NewPubKeyIndex, + &NewPubKeyStore, + &NewPubKeySize + ); + if (EFI_ERROR (Status)) { + FreePool (ValidBuffer); + return Status; + } - VariableNamePtr = GetVariableNamePtr (Variable); - UpdatingVariableNamePtr = GetVariableNamePtr (UpdatingVariable); - if (CompareGuid (&Variable->VendorGuid, &UpdatingVariable->VendorGuid) && - VariableNameSize == UpdatingVariableNameSize && - CompareMem (VariableNamePtr, UpdatingVariableNamePtr, VariableNameSize) == 0 ) { + // + // Refresh the PubKeyIndex for all valid variables (ADDED and IN_DELETED_TRANSITION). + // + Variable = GetStartPointer (mNvVariableCache); + while (IsValidVariableHeader (Variable)) { + NextVariable = GetNextVariablePtr (Variable); + if (Variable->State == VAR_ADDED || Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { + if ((StrCmp (GetVariableNamePtr (Variable), AUTHVAR_KEYDB_NAME) == 0) && + (CompareGuid (&Variable->VendorGuid, &gEfiAuthenticatedVariableGuid))) { + // + // Skip the public key database, it will be reinstalled later. + // + PubKeyHeader = Variable; Variable = NextVariable; continue; } + + VariableSize = (UINTN) NextVariable - (UINTN) Variable; + CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize); + ((VARIABLE_HEADER*) CurrPtr)->PubKeyIndex = NewPubKeyIndex[Variable->PubKeyIndex]; + CurrPtr += VariableSize; + if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { + HwErrVariableTotalSize += VariableSize; + } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { + CommonVariableTotalSize += VariableSize; + } } - VariableSize = (UINTN) NextVariable - (UINTN) Variable; - CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize); - CurrPtr += VariableSize; - if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { - mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize; - } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { - mVariableModuleGlobal->CommonVariableTotalSize += VariableSize; - } + Variable = NextVariable; } - Variable = NextVariable; - } - // - // Reinstall the variable being updated if it is not NULL. - // - if (UpdatingVariable != NULL) { - VariableSize = (UINTN)(GetNextVariablePtr (UpdatingVariable)) - (UINTN)UpdatingVariable; - CopyMem (CurrPtr, (UINT8 *) UpdatingVariable, VariableSize); - CurrPtr += VariableSize; - if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { - mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize; - } else if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { - mVariableModuleGlobal->CommonVariableTotalSize += VariableSize; - } - } + // + // Reinstall the new public key database. + // + ASSERT (PubKeyHeader != NULL); + CopyMem (CurrPtr, (UINT8*) PubKeyHeader, sizeof (VARIABLE_HEADER)); + Variable = (VARIABLE_HEADER*) CurrPtr; + Variable->DataSize = NewPubKeySize; + StrCpy (GetVariableNamePtr (Variable), GetVariableNamePtr (PubKeyHeader)); + CopyMem (GetVariableDataPtr (Variable), NewPubKeyStore, NewPubKeySize); + CurrPtr = (UINT8*) GetNextVariablePtr (Variable); + CommonVariableTotalSize += (UINTN) CurrPtr - (UINTN) Variable; + } else { + // + // Reinstall all ADDED variables as long as they are not identical to Updating Variable. + // + Variable = GetStartPointer (VariableStoreHeader); + while (IsValidVariableHeader (Variable)) { + NextVariable = GetNextVariablePtr (Variable); + if (Variable->State == VAR_ADDED) { + if (UpdatingVariable != NULL) { + if (UpdatingVariable == Variable) { + Variable = NextVariable; + continue; + } - // - // Reinstall all in delete transition variables. - // - Variable = GetStartPointer (VariableStoreHeader); - while (IsValidVariableHeader (Variable)) { - NextVariable = GetNextVariablePtr (Variable); - if (Variable != UpdatingVariable && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { - - // - // Buffer has cached all ADDED variable. - // Per IN_DELETED variable, we have to guarantee that - // no ADDED one in previous buffer. - // - - FoundAdded = FALSE; - AddedVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer); - while (IsValidVariableHeader (AddedVariable)) { - NextAddedVariable = GetNextVariablePtr (AddedVariable); - NameSize = NameSizeOfVariable (AddedVariable); - if (CompareGuid (&AddedVariable->VendorGuid, &Variable->VendorGuid) && - NameSize == NameSizeOfVariable (Variable) - ) { - Point0 = (VOID *) GetVariableNamePtr (AddedVariable); - Point1 = (VOID *) GetVariableNamePtr (Variable); - if (CompareMem (Point0, Point1, NameSizeOfVariable (AddedVariable)) == 0) { - FoundAdded = TRUE; - break; + VariableNameSize = NameSizeOfVariable(Variable); + UpdatingVariableNameSize = NameSizeOfVariable(UpdatingVariable); + + VariableNamePtr = GetVariableNamePtr (Variable); + UpdatingVariableNamePtr = GetVariableNamePtr (UpdatingVariable); + if (CompareGuid (&Variable->VendorGuid, &UpdatingVariable->VendorGuid) && + VariableNameSize == UpdatingVariableNameSize && + CompareMem (VariableNamePtr, UpdatingVariableNamePtr, VariableNameSize) == 0 ) { + Variable = NextVariable; + continue; } } - AddedVariable = NextAddedVariable; - } - if (!FoundAdded) { - // - // Promote VAR_IN_DELETED_TRANSITION to VAR_ADDED. - // VariableSize = (UINTN) NextVariable - (UINTN) Variable; CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize); - ((VARIABLE_HEADER *) CurrPtr)->State = VAR_ADDED; CurrPtr += VariableSize; if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { - mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize; + HwErrVariableTotalSize += VariableSize; } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { - mVariableModuleGlobal->CommonVariableTotalSize += VariableSize; + CommonVariableTotalSize += VariableSize; } } + Variable = NextVariable; } - Variable = NextVariable; + // + // Reinstall the variable being updated if it is not NULL. + // + if (UpdatingVariable != NULL) { + VariableSize = (UINTN)(GetNextVariablePtr (UpdatingVariable)) - (UINTN)UpdatingVariable; + CopyMem (CurrPtr, (UINT8 *) UpdatingVariable, VariableSize); + UpdatingPtrTrack->CurrPtr = (VARIABLE_HEADER *)((UINTN)UpdatingPtrTrack->StartPtr + ((UINTN)CurrPtr - (UINTN)GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer))); + UpdatingPtrTrack->InDeletedTransitionPtr = NULL; + CurrPtr += VariableSize; + if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { + HwErrVariableTotalSize += VariableSize; + } else if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { + CommonVariableTotalSize += VariableSize; + } + } + + // + // Reinstall all in delete transition variables. + // + Variable = GetStartPointer (VariableStoreHeader); + while (IsValidVariableHeader (Variable)) { + NextVariable = GetNextVariablePtr (Variable); + if (Variable != UpdatingVariable && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { + + // + // Buffer has cached all ADDED variable. + // Per IN_DELETED variable, we have to guarantee that + // no ADDED one in previous buffer. + // + + FoundAdded = FALSE; + AddedVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer); + while (IsValidVariableHeader (AddedVariable)) { + NextAddedVariable = GetNextVariablePtr (AddedVariable); + NameSize = NameSizeOfVariable (AddedVariable); + if (CompareGuid (&AddedVariable->VendorGuid, &Variable->VendorGuid) && + NameSize == NameSizeOfVariable (Variable) + ) { + Point0 = (VOID *) GetVariableNamePtr (AddedVariable); + Point1 = (VOID *) GetVariableNamePtr (Variable); + if (CompareMem (Point0, Point1, NameSize) == 0) { + FoundAdded = TRUE; + break; + } + } + AddedVariable = NextAddedVariable; + } + if (!FoundAdded) { + // + // Promote VAR_IN_DELETED_TRANSITION to VAR_ADDED. + // + VariableSize = (UINTN) NextVariable - (UINTN) Variable; + CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize); + ((VARIABLE_HEADER *) CurrPtr)->State = VAR_ADDED; + CurrPtr += VariableSize; + if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { + HwErrVariableTotalSize += VariableSize; + } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { + CommonVariableTotalSize += VariableSize; + } + } + } + + Variable = NextVariable; + } } if (IsVolatile) { @@ -706,15 +941,106 @@ Reclaim ( } if (!EFI_ERROR (Status)) { *LastVariableOffset = (UINTN) (CurrPtr - (UINT8 *) ValidBuffer); + if (!IsVolatile) { + mVariableModuleGlobal->HwErrVariableTotalSize = HwErrVariableTotalSize; + mVariableModuleGlobal->CommonVariableTotalSize = CommonVariableTotalSize; + } } else { - *LastVariableOffset = 0; + NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase); + while (IsValidVariableHeader (NextVariable)) { + VariableSize = NextVariable->NameSize + NextVariable->DataSize + sizeof (VARIABLE_HEADER); + if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { + mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VariableSize); + } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { + mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VariableSize); + } + + NextVariable = GetNextVariablePtr (NextVariable); + } + *LastVariableOffset = (UINTN) NextVariable - (UINTN) VariableBase; + } + + if (NewPubKeyStore != NULL) { + FreePool (NewPubKeyStore); } + if (NewPubKeyIndex != NULL) { + FreePool (NewPubKeyIndex); + } + FreePool (ValidBuffer); return Status; } +/** + Find the variable in the specified variable store. + + @param[in] VariableName Name of the variable to be found + @param[in] VendorGuid Vendor GUID to be found. + @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute + check at runtime when searching variable. + @param[in, out] PtrTrack Variable Track Pointer structure that contains Variable Information. + + @retval EFI_SUCCESS Variable found successfully + @retval EFI_NOT_FOUND Variable not found +**/ +EFI_STATUS +FindVariableEx ( + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + IN BOOLEAN IgnoreRtCheck, + IN OUT VARIABLE_POINTER_TRACK *PtrTrack + ) +{ + VARIABLE_HEADER *InDeletedVariable; + VOID *Point; + + PtrTrack->InDeletedTransitionPtr = NULL; + + // + // Find the variable by walk through HOB, volatile and non-volatile variable store. + // + InDeletedVariable = NULL; + + for ( PtrTrack->CurrPtr = PtrTrack->StartPtr + ; (PtrTrack->CurrPtr < PtrTrack->EndPtr) && IsValidVariableHeader (PtrTrack->CurrPtr) + ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr) + ) { + if (PtrTrack->CurrPtr->State == VAR_ADDED || + PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED) + ) { + if (IgnoreRtCheck || !AtRuntime () || ((PtrTrack->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) { + if (VariableName[0] == 0) { + if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { + InDeletedVariable = PtrTrack->CurrPtr; + } else { + PtrTrack->InDeletedTransitionPtr = InDeletedVariable; + return EFI_SUCCESS; + } + } else { + if (CompareGuid (VendorGuid, &PtrTrack->CurrPtr->VendorGuid)) { + Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr); + + ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr) != 0); + if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr)) == 0) { + if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { + InDeletedVariable = PtrTrack->CurrPtr; + } else { + PtrTrack->InDeletedTransitionPtr = InDeletedVariable; + return EFI_SUCCESS; + } + } + } + } + } + } + } + + PtrTrack->CurrPtr = InDeletedVariable; + return (PtrTrack->CurrPtr == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS; +} + /** Finds variable in storage blocks of volatile and non-volatile storage areas. @@ -722,15 +1048,19 @@ Reclaim ( This code finds variable in storage blocks of volatile and non-volatile storage areas. If VariableName is an empty string, then we just return the first qualified variable without comparing VariableName and VendorGuid. - Otherwise, VariableName and VendorGuid are compared. + If IgnoreRtCheck is TRUE, then we ignore the EFI_VARIABLE_RUNTIME_ACCESS attribute check + at runtime when searching existing variable, only VariableName and VendorGuid are compared. + Otherwise, variables without EFI_VARIABLE_RUNTIME_ACCESS are not visible at runtime. - @param VariableName Name of the variable to be found. - @param VendorGuid Vendor GUID to be found. - @param PtrTrack VARIABLE_POINTER_TRACK structure for output, + @param[in] VariableName Name of the variable to be found. + @param[in] VendorGuid Vendor GUID to be found. + @param[out] PtrTrack VARIABLE_POINTER_TRACK structure for output, including the range searched and the target position. - @param Global Pointer to VARIABLE_GLOBAL structure, including + @param[in] Global Pointer to VARIABLE_GLOBAL structure, including base of volatile variable storage area, base of NV variable storage area, and a lock. + @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute + check at runtime when searching variable. @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while VendorGuid is NULL. @@ -743,92 +1073,44 @@ FindVariable ( IN CHAR16 *VariableName, IN EFI_GUID *VendorGuid, OUT VARIABLE_POINTER_TRACK *PtrTrack, - IN VARIABLE_GLOBAL *Global + IN VARIABLE_GLOBAL *Global, + IN BOOLEAN IgnoreRtCheck ) { - VARIABLE_HEADER *Variable[2]; - VARIABLE_HEADER *InDeletedVariable; - VARIABLE_STORE_HEADER *VariableStoreHeader[2]; - UINTN InDeletedStorageIndex; - UINTN Index; - VOID *Point; + EFI_STATUS Status; + VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax]; + VARIABLE_STORE_TYPE Type; + + if (VariableName[0] != 0 && VendorGuid == NULL) { + return EFI_INVALID_PARAMETER; + } // - // 0: Volatile, 1: Non-Volatile. + // 0: Volatile, 1: HOB, 2: Non-Volatile. // The index and attributes mapping must be kept in this order as RuntimeServiceGetNextVariableName // make use of this mapping to implement search algorithm. // - VariableStoreHeader[0] = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase); - VariableStoreHeader[1] = mNvVariableCache; + VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) Global->VolatileVariableBase; + VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) Global->HobVariableBase; + VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache; // - // Start Pointers for the variable. - // Actual Data Pointer where data can be written. + // Find the variable by walk through HOB, volatile and non-volatile variable store. // - Variable[0] = GetStartPointer (VariableStoreHeader[0]); - Variable[1] = GetStartPointer (VariableStoreHeader[1]); - - if (VariableName[0] != 0 && VendorGuid == NULL) { - return EFI_INVALID_PARAMETER; - } + for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) { + if (VariableStoreHeader[Type] == NULL) { + continue; + } - // - // Find the variable by walk through volatile and then non-volatile variable store. - // - InDeletedVariable = NULL; - InDeletedStorageIndex = 0; - for (Index = 0; Index < 2; Index++) { - while ((Variable[Index] < GetEndPointer (VariableStoreHeader[Index])) && IsValidVariableHeader (Variable[Index])) { - if (Variable[Index]->State == VAR_ADDED || - Variable[Index]->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED) - ) { - if (!AtRuntime () || ((Variable[Index]->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) { - if (VariableName[0] == 0) { - if (Variable[Index]->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { - InDeletedVariable = Variable[Index]; - InDeletedStorageIndex = Index; - } else { - PtrTrack->StartPtr = GetStartPointer (VariableStoreHeader[Index]); - PtrTrack->EndPtr = GetEndPointer (VariableStoreHeader[Index]); - PtrTrack->CurrPtr = Variable[Index]; - PtrTrack->Volatile = (BOOLEAN)(Index == 0); - - return EFI_SUCCESS; - } - } else { - if (CompareGuid (VendorGuid, &Variable[Index]->VendorGuid)) { - Point = (VOID *) GetVariableNamePtr (Variable[Index]); - - ASSERT (NameSizeOfVariable (Variable[Index]) != 0); - if (CompareMem (VariableName, Point, NameSizeOfVariable (Variable[Index])) == 0) { - if (Variable[Index]->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { - InDeletedVariable = Variable[Index]; - InDeletedStorageIndex = Index; - } else { - PtrTrack->StartPtr = GetStartPointer (VariableStoreHeader[Index]); - PtrTrack->EndPtr = GetEndPointer (VariableStoreHeader[Index]); - PtrTrack->CurrPtr = Variable[Index]; - PtrTrack->Volatile = (BOOLEAN)(Index == 0); - - return EFI_SUCCESS; - } - } - } - } - } - } + PtrTrack->StartPtr = GetStartPointer (VariableStoreHeader[Type]); + PtrTrack->EndPtr = GetEndPointer (VariableStoreHeader[Type]); + PtrTrack->Volatile = (BOOLEAN) (Type == VariableStoreTypeVolatile); - Variable[Index] = GetNextVariablePtr (Variable[Index]); - } - if (InDeletedVariable != NULL) { - PtrTrack->StartPtr = GetStartPointer (VariableStoreHeader[InDeletedStorageIndex]); - PtrTrack->EndPtr = GetEndPointer (VariableStoreHeader[InDeletedStorageIndex]); - PtrTrack->CurrPtr = InDeletedVariable; - PtrTrack->Volatile = (BOOLEAN)(InDeletedStorageIndex == 0); - return EFI_SUCCESS; + Status = FindVariableEx (VariableName, VendorGuid, IgnoreRtCheck, PtrTrack); + if (!EFI_ERROR (Status)) { + return Status; } } - PtrTrack->CurrPtr = NULL; return EFI_NOT_FOUND; } @@ -863,7 +1145,7 @@ GetIndexFromSupportedLangCodes( IN CHAR8 *SupportedLang, IN CHAR8 *Lang, IN BOOLEAN Iso639Language - ) + ) { UINTN Index; UINTN CompareLength; @@ -898,8 +1180,8 @@ GetIndexFromSupportedLangCodes( // Determine the length of the next language code in SupportedLang // for (CompareLength = 0; SupportedLang[CompareLength] != '\0' && SupportedLang[CompareLength] != ';'; CompareLength++); - - if ((CompareLength == LanguageLength) && + + if ((CompareLength == LanguageLength) && (AsciiStrnCmp (Lang, SupportedLang, CompareLength) == 0)) { // // Successfully find the index of Lang string in SupportedLang string. @@ -960,7 +1242,7 @@ GetLangFromSupportedLangCodes ( CompareLength = ISO_639_2_ENTRY_SIZE; mVariableModuleGlobal->Lang[CompareLength] = '\0'; return CopyMem (mVariableModuleGlobal->Lang, SupportedLang + Index * CompareLength, CompareLength); - + } else { while (TRUE) { // @@ -997,10 +1279,10 @@ GetLangFromSupportedLangCodes ( } /** - Returns a pointer to an allocated buffer that contains the best matching language - from a set of supported languages. - - This function supports both ISO 639-2 and RFC 4646 language codes, but language + Returns a pointer to an allocated buffer that contains the best matching language + from a set of supported languages. + + This function supports both ISO 639-2 and RFC 4646 language codes, but language code types may not be mixed in a single call to this function. This function supports a variable argument list that allows the caller to pass in a prioritized list of language codes to test against all the language codes in SupportedLanguages. @@ -1008,37 +1290,37 @@ GetLangFromSupportedLangCodes ( If SupportedLanguages is NULL, then ASSERT(). @param[in] SupportedLanguages A pointer to a Null-terminated ASCII string that - contains a set of language codes in the format + contains a set of language codes in the format specified by Iso639Language. @param[in] Iso639Language If TRUE, then all language codes are assumed to be in ISO 639-2 format. If FALSE, then all language codes are assumed to be in RFC 4646 language format - @param[in] ... A variable argument list that contains pointers to + @param[in] ... A variable argument list that contains pointers to Null-terminated ASCII strings that contain one or more language codes in the format specified by Iso639Language. The first language code from each of these language code lists is used to determine if it is an exact or - close match to any of the language codes in + close match to any of the language codes in SupportedLanguages. Close matches only apply to RFC 4646 language codes, and the matching algorithm from RFC 4647 - is used to determine if a close match is present. If + is used to determine if a close match is present. If an exact or close match is found, then the matching language code from SupportedLanguages is returned. If no matches are found, then the next variable argument - parameter is evaluated. The variable argument list + parameter is evaluated. The variable argument list is terminated by a NULL. @retval NULL The best matching language could not be found in SupportedLanguages. - @retval NULL There are not enough resources available to return the best matching + @retval NULL There are not enough resources available to return the best matching language. - @retval Other A pointer to a Null-terminated ASCII string that is the best matching + @retval Other A pointer to a Null-terminated ASCII string that is the best matching language in SupportedLanguages. **/ CHAR8 * EFIAPI VariableGetBestLanguage ( - IN CONST CHAR8 *SupportedLanguages, + IN CONST CHAR8 *SupportedLanguages, IN BOOLEAN Iso639Language, ... ) @@ -1115,7 +1397,7 @@ VariableGetBestLanguage ( LanguageLength = 0; } else { // - // If RFC 4646 mode, then trim Language from the right to the next '-' character + // If RFC 4646 mode, then trim Language from the right to the next '-' character // for (LanguageLength--; LanguageLength > 0 && Language[LanguageLength] != '-'; LanguageLength--); } @@ -1124,7 +1406,7 @@ VariableGetBestLanguage ( VA_END (Args); // - // No matches were found + // No matches were found // return NULL; } @@ -1145,7 +1427,7 @@ VariableGetBestLanguage ( **/ VOID -AutoUpdateLangVariable( +AutoUpdateLangVariable ( IN CHAR16 *VariableName, IN VOID *Data, IN UINTN DataSize @@ -1189,7 +1471,7 @@ AutoUpdateLangVariable( ASSERT (mVariableModuleGlobal->PlatformLangCodes != NULL); // - // PlatformLang holds a single language from PlatformLangCodes, + // PlatformLang holds a single language from PlatformLangCodes, // so the size of PlatformLangCodes is enough for the PlatformLang. // if (mVariableModuleGlobal->PlatformLang != NULL) { @@ -1219,14 +1501,14 @@ AutoUpdateLangVariable( ASSERT (mVariableModuleGlobal->LangCodes != NULL); } - if (SetLanguageCodes + if (SetLanguageCodes && (mVariableModuleGlobal->PlatformLangCodes != NULL) && (mVariableModuleGlobal->LangCodes != NULL)) { // // Update Lang if PlatformLang is already set // Update PlatformLang if Lang is already set // - Status = FindVariable (L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, (VARIABLE_GLOBAL *) mVariableModuleGlobal); + Status = FindVariable (L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE); if (!EFI_ERROR (Status)) { // // Update Lang @@ -1235,7 +1517,7 @@ AutoUpdateLangVariable( Data = GetVariableDataPtr (Variable.CurrPtr); DataSize = Variable.CurrPtr->DataSize; } else { - Status = FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, (VARIABLE_GLOBAL *) mVariableModuleGlobal); + Status = FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE); if (!EFI_ERROR (Status)) { // // Update PlatformLang @@ -1251,7 +1533,7 @@ AutoUpdateLangVariable( } } } - + // // According to UEFI spec, "Lang" and "PlatformLang" is NV|BS|RT attributions. // @@ -1280,7 +1562,7 @@ AutoUpdateLangVariable( // // Successfully convert PlatformLang to Lang, and set the BestLang value into Lang variable simultaneously. // - FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, (VARIABLE_GLOBAL *)mVariableModuleGlobal); + FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE); Status = UpdateVariable (L"Lang", &gEfiGlobalVariableGuid, BestLang, ISO_639_2_ENTRY_SIZE + 1, Attributes, 0, 0, &Variable, NULL); @@ -1314,9 +1596,9 @@ AutoUpdateLangVariable( // // Successfully convert Lang to PlatformLang, and set the BestPlatformLang value into PlatformLang variable simultaneously. // - FindVariable (L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, (VARIABLE_GLOBAL *)mVariableModuleGlobal); + FindVariable (L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE); - Status = UpdateVariable (L"PlatformLang", &gEfiGlobalVariableGuid, BestPlatformLang, + Status = UpdateVariable (L"PlatformLang", &gEfiGlobalVariableGuid, BestPlatformLang, AsciiStrSize (BestPlatformLang), Attributes, 0, 0, &Variable, NULL); DEBUG ((EFI_D_INFO, "Variable Driver Auto Update Lang, Lang:%a, PlatformLang:%a\n", BestLang, BestPlatformLang)); @@ -1337,9 +1619,9 @@ AutoUpdateLangVariable( @param[in] Attributes Attributes of the variable. @param[in] KeyIndex Index of associated public key. @param[in] MonotonicCount Value of associated monotonic count. - @param[in] CacheVariable The variable information which is used to keep track of variable usage. + @param[in, out] CacheVariable The variable information which is used to keep track of variable usage. @param[in] TimeStamp Value of associated TimeStamp. - + @retval EFI_SUCCESS The update operation is success. @retval EFI_OUT_OF_RESOURCES Variable region is full, can not write other data into this region. @@ -1353,7 +1635,7 @@ UpdateVariable ( IN UINT32 Attributes OPTIONAL, IN UINT32 KeyIndex OPTIONAL, IN UINT64 MonotonicCount OPTIONAL, - IN VARIABLE_POINTER_TRACK *CacheVariable, + IN OUT VARIABLE_POINTER_TRACK *CacheVariable, IN EFI_TIME *TimeStamp OPTIONAL ) { @@ -1369,7 +1651,6 @@ UpdateVariable ( BOOLEAN Volatile; EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb; UINT8 State; - BOOLEAN Reclaimed; VARIABLE_POINTER_TRACK *Variable; VARIABLE_POINTER_TRACK NvVariable; VARIABLE_STORE_HEADER *VariableStoreHeader; @@ -1405,15 +1686,19 @@ UpdateVariable ( // Now let Variable points to the same variable in Flash area. // VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase); - Variable = &NvVariable; + Variable = &NvVariable; Variable->StartPtr = GetStartPointer (VariableStoreHeader); Variable->EndPtr = GetEndPointer (VariableStoreHeader); Variable->CurrPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->CurrPtr - (UINTN)CacheVariable->StartPtr)); + if (CacheVariable->InDeletedTransitionPtr != NULL) { + Variable->InDeletedTransitionPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->InDeletedTransitionPtr - (UINTN)CacheVariable->StartPtr)); + } else { + Variable->InDeletedTransitionPtr = NULL; + } Variable->Volatile = FALSE; - } + } Fvb = mVariableModuleGlobal->FvbInstance; - Reclaimed = FALSE; // // Tricky part: Use scratch data area at the end of volatile variable store @@ -1427,10 +1712,10 @@ UpdateVariable ( // // Update/Delete existing variable. // - if (AtRuntime ()) { + if (AtRuntime ()) { // - // If AtRuntime and the variable is Volatile and Runtime Access, - // the volatile is ReadOnly, and SetVariable should be aborted and + // If AtRuntime and the variable is Volatile and Runtime Access, + // the volatile is ReadOnly, and SetVariable should be aborted and // return EFI_WRITE_PROTECTED. // if (Variable->Volatile) { @@ -1442,36 +1727,71 @@ UpdateVariable ( // if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) { Status = EFI_INVALID_PARAMETER; - goto Done; + goto Done; + } + + // + // Only variable that have RT attributes can be updated/deleted in Runtime. + // + if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) { + Status = EFI_INVALID_PARAMETER; + goto Done; } } // // Setting a data variable with no access, or zero DataSize attributes // causes it to be deleted. - // When the EFI_VARIABLE_APPEND_WRITE attribute is set, DataSize of zero will - // not delete the variable. + // When the EFI_VARIABLE_APPEND_WRITE attribute is set, DataSize of zero will + // not delete the variable. // - if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0))|| ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0)) { - State = Variable->CurrPtr->State; - State &= VAR_DELETED; - - Status = UpdateVariableStore ( - &mVariableModuleGlobal->VariableGlobal, - Variable->Volatile, + if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0))|| ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0)) { + if (Variable->InDeletedTransitionPtr != NULL) { + // + // Both ADDED and IN_DELETED_TRANSITION variable are present, + // set IN_DELETED_TRANSITION one to DELETED state first. + // + State = Variable->InDeletedTransitionPtr->State; + State &= VAR_DELETED; + Status = UpdateVariableStore ( + &mVariableModuleGlobal->VariableGlobal, + Variable->Volatile, + FALSE, + Fvb, + (UINTN) &Variable->InDeletedTransitionPtr->State, + sizeof (UINT8), + &State + ); + if (!EFI_ERROR (Status)) { + if (!Variable->Volatile) { + ASSERT (CacheVariable->InDeletedTransitionPtr != NULL); + CacheVariable->InDeletedTransitionPtr->State = State; + } + } else { + goto Done; + } + } + + State = Variable->CurrPtr->State; + State &= VAR_DELETED; + + Status = UpdateVariableStore ( + &mVariableModuleGlobal->VariableGlobal, + Variable->Volatile, FALSE, Fvb, (UINTN) &Variable->CurrPtr->State, sizeof (UINT8), &State - ); + ); if (!EFI_ERROR (Status)) { UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE); if (!Variable->Volatile) { CacheVariable->CurrPtr->State = State; + FlushHobVariableToFlash (VariableName, VendorGuid); } } - goto Done; + goto Done; } // // If the variable is marked valid, and the same data has been passed in, @@ -1479,8 +1799,11 @@ UpdateVariable ( // if (DataSizeOfVariable (Variable->CurrPtr) == DataSize && (CompareMem (Data, GetVariableDataPtr (Variable->CurrPtr), DataSize) == 0) && - ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0)) { - + ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && + (TimeStamp == NULL)) { + // + // Variable content unchanged and no need to update timestamp, just return. + // UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE); Status = EFI_SUCCESS; goto Done; @@ -1491,10 +1814,40 @@ UpdateVariable ( // EFI_VARIABLE_APPEND_WRITE attribute only effects for existing variable // if ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) { - - BufSize = Variable->CurrPtr->DataSize + DataSize; - RevBufSize = MIN (PcdGet32 (PcdMaxAppendVariableSize), ScratchDataSize); - + // + // Cache the previous variable data into StorageArea. + // + DataOffset = sizeof (VARIABLE_HEADER) + Variable->CurrPtr->NameSize + GET_PAD_SIZE (Variable->CurrPtr->NameSize); + CopyMem (mStorageArea, (UINT8*)((UINTN) Variable->CurrPtr + DataOffset), Variable->CurrPtr->DataSize); + + if ((CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) && + ((StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) || (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0))) || + (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0))) { + // + // For variables with formatted as EFI_SIGNATURE_LIST, the driver shall not perform an append of + // EFI_SIGNATURE_DATA values that are already part of the existing variable value. + // + BufSize = AppendSignatureList (mStorageArea, Variable->CurrPtr->DataSize, Data, DataSize); + if (BufSize == Variable->CurrPtr->DataSize) { + if ((TimeStamp == NULL) || CompareTimeStamp (TimeStamp, &Variable->CurrPtr->TimeStamp)) { + // + // New EFI_SIGNATURE_DATA is not found and timestamp is not later + // than current timestamp, return EFI_SUCCESS directly. + // + UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE); + Status = EFI_SUCCESS; + goto Done; + } + } + } else { + // + // For other Variables, append the new data to the end of previous data. + // + CopyMem ((UINT8*)((UINTN) mStorageArea + Variable->CurrPtr->DataSize), Data, DataSize); + BufSize = Variable->CurrPtr->DataSize + DataSize; + } + + RevBufSize = MIN (PcdGet32 (PcdMaxVariableSize), ScratchDataSize); if (BufSize > RevBufSize) { // // If variable size (previous + current) is bigger than reserved buffer in runtime, @@ -1502,19 +1855,7 @@ UpdateVariable ( // return EFI_OUT_OF_RESOURCES; } - - SetMem (mStorageArea, PcdGet32 (PcdMaxAppendVariableSize), 0xff); - // - // Cache the previous variable data into StorageArea. - // - DataOffset = sizeof (VARIABLE_HEADER) + Variable->CurrPtr->NameSize + GET_PAD_SIZE (Variable->CurrPtr->NameSize); - CopyMem (mStorageArea, (UINT8*)((UINTN)Variable->CurrPtr + DataOffset), Variable->CurrPtr->DataSize); - - // - // Append the new data to the end of previous data. - // - CopyMem ((UINT8*)((UINTN)mStorageArea + Variable->CurrPtr->DataSize), Data, DataSize); - + // // Override Data and DataSize which are used for combined data area including previous and new data. // @@ -1536,36 +1877,33 @@ UpdateVariable ( (UINTN) &Variable->CurrPtr->State, sizeof (UINT8), &State - ); + ); if (EFI_ERROR (Status)) { - goto Done; - } + goto Done; + } if (!Variable->Volatile) { CacheVariable->CurrPtr->State = State; } - } + } } else { // // Not found existing variable. Create a new variable. - // - // - // EFI_VARIABLE_APPEND_WRITE attribute only set for existing variable - // - if ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) { - Status = EFI_INVALID_PARAMETER; + + if ((DataSize == 0) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0)) { + Status = EFI_SUCCESS; goto Done; } - + // // Make sure we are trying to create a new variable. - // Setting a data variable with zero DataSize or no access attributes means to delete it. + // Setting a data variable with zero DataSize or no access attributes means to delete it. // if (DataSize == 0 || (Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0) { Status = EFI_NOT_FOUND; goto Done; } - + // // Only variable have NV|RT attribute can be created in Runtime. // @@ -1573,7 +1911,7 @@ UpdateVariable ( (((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) || ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0))) { Status = EFI_INVALID_PARAMETER; goto Done; - } + } } // @@ -1589,30 +1927,32 @@ UpdateVariable ( NextVariable->Reserved = 0; NextVariable->PubKeyIndex = KeyIndex; NextVariable->MonotonicCount = MonotonicCount; - SetMem (&NextVariable->TimeStamp, sizeof (EFI_TIME), 0); + ZeroMem (&NextVariable->TimeStamp, sizeof (EFI_TIME)); - if (((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && - ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0)) { - CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME)); - } else if ( - ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) && - ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0)) { + if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) && + (TimeStamp != NULL)) { + if ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) { + CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME)); + } else { // // In the case when the EFI_VARIABLE_APPEND_WRITE attribute is set, only // when the new TimeStamp value is later than the current timestamp associated // with the variable, we need associate the new timestamp with the updated value. // - if (CompareTimeStamp (&Variable->CurrPtr->TimeStamp, TimeStamp)) { - CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME)); + if (Variable->CurrPtr != NULL) { + if (CompareTimeStamp (&Variable->CurrPtr->TimeStamp, TimeStamp)) { + CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME)); + } } + } } // - // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned + // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned // Attributes bitmask parameter of a GetVariable() call. // NextVariable->Attributes = Attributes & (~EFI_VARIABLE_APPEND_WRITE); - + VarNameOffset = sizeof (VARIABLE_HEADER); VarNameSize = StrSize (VariableName); CopyMem ( @@ -1646,9 +1986,9 @@ UpdateVariable ( // Volatile = FALSE; NonVolatileVarableStoreSize = ((VARIABLE_STORE_HEADER *)(UINTN)(mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase))->Size; - if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) + if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize))) - || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0) + || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0) && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) { if (AtRuntime ()) { Status = EFI_OUT_OF_RESOURCES; @@ -1657,27 +1997,36 @@ UpdateVariable ( // // Perform garbage collection & reclaim operation. // - Status = Reclaim (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase, - &mVariableModuleGlobal->NonVolatileLastVariableOffset, FALSE, Variable->CurrPtr); + Status = Reclaim ( + mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase, + &mVariableModuleGlobal->NonVolatileLastVariableOffset, + FALSE, + Variable, + FALSE, + FALSE + ); if (EFI_ERROR (Status)) { goto Done; } // // If still no enough space, return out of resources. // - if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) + if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize))) - || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0) + || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0) && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) { Status = EFI_OUT_OF_RESOURCES; goto Done; } - Reclaimed = TRUE; + if (Variable->CurrPtr != NULL) { + CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr)); + CacheVariable->InDeletedTransitionPtr = NULL; + } } // // Four steps // 1. Write variable header - // 2. Set variable state to header valid + // 2. Set variable state to header valid // 3. Write variable data // 4. Set variable state to valid // @@ -1764,7 +2113,7 @@ UpdateVariable ( } else { // // Create a volatile variable. - // + // Volatile = TRUE; if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) > @@ -1772,8 +2121,14 @@ UpdateVariable ( // // Perform garbage collection & reclaim operation. // - Status = Reclaim (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase, - &mVariableModuleGlobal->VolatileLastVariableOffset, TRUE, Variable->CurrPtr); + Status = Reclaim ( + mVariableModuleGlobal->VariableGlobal.VolatileVariableBase, + &mVariableModuleGlobal->VolatileLastVariableOffset, + TRUE, + Variable, + FALSE, + FALSE + ); if (EFI_ERROR (Status)) { goto Done; } @@ -1786,7 +2141,10 @@ UpdateVariable ( Status = EFI_OUT_OF_RESOURCES; goto Done; } - Reclaimed = TRUE; + if (Variable->CurrPtr != NULL) { + CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr)); + CacheVariable->InDeletedTransitionPtr = NULL; + } } NextVariable->State = VAR_ADDED; @@ -1810,7 +2168,33 @@ UpdateVariable ( // // Mark the old variable as deleted. // - if (!Reclaimed && !EFI_ERROR (Status) && Variable->CurrPtr != NULL) { + if (!EFI_ERROR (Status) && Variable->CurrPtr != NULL) { + if (Variable->InDeletedTransitionPtr != NULL) { + // + // Both ADDED and IN_DELETED_TRANSITION old variable are present, + // set IN_DELETED_TRANSITION one to DELETED state first. + // + State = Variable->InDeletedTransitionPtr->State; + State &= VAR_DELETED; + Status = UpdateVariableStore ( + &mVariableModuleGlobal->VariableGlobal, + Variable->Volatile, + FALSE, + Fvb, + (UINTN) &Variable->InDeletedTransitionPtr->State, + sizeof (UINT8), + &State + ); + if (!EFI_ERROR (Status)) { + if (!Variable->Volatile) { + ASSERT (CacheVariable->InDeletedTransitionPtr != NULL); + CacheVariable->InDeletedTransitionPtr->State = State; + } + } else { + goto Done; + } + } + State = Variable->CurrPtr->State; State &= VAR_DELETED; @@ -1823,30 +2207,121 @@ UpdateVariable ( sizeof (UINT8), &State ); - if (!EFI_ERROR (Status) && !Variable->Volatile) { + if (!EFI_ERROR (Status) && !Variable->Volatile) { CacheVariable->CurrPtr->State = State; } } if (!EFI_ERROR (Status)) { UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE); + if (!Volatile) { + FlushHobVariableToFlash (VariableName, VendorGuid); + } } Done: return Status; } +/** + Check if a Unicode character is a hexadecimal character. + + This function checks if a Unicode character is a + hexadecimal character. The valid hexadecimal character is + L'0' to L'9', L'a' to L'f', or L'A' to L'F'. + + + @param Char The character to check against. + + @retval TRUE If the Char is a hexadecmial character. + @retval FALSE If the Char is not a hexadecmial character. + +**/ +BOOLEAN +EFIAPI +IsHexaDecimalDigitCharacter ( + IN CHAR16 Char + ) +{ + return (BOOLEAN) ((Char >= L'0' && Char <= L'9') || (Char >= L'A' && Char <= L'F') || (Char >= L'a' && Char <= L'f')); +} + +/** + + This code checks if variable is hardware error record variable or not. + + According to UEFI spec, hardware error record variable should use the EFI_HARDWARE_ERROR_VARIABLE VendorGuid + and have the L"HwErrRec####" name convention, #### is a printed hex value and no 0x or h is included in the hex value. + + @param VariableName Pointer to variable name. + @param VendorGuid Variable Vendor Guid. + + @retval TRUE Variable is hardware error record variable. + @retval FALSE Variable is not hardware error record variable. + +**/ +BOOLEAN +EFIAPI +IsHwErrRecVariable ( + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid + ) +{ + if (!CompareGuid (VendorGuid, &gEfiHardwareErrorVariableGuid) || + (StrLen (VariableName) != StrLen (L"HwErrRec####")) || + (StrnCmp(VariableName, L"HwErrRec", StrLen (L"HwErrRec")) != 0) || + !IsHexaDecimalDigitCharacter (VariableName[0x8]) || + !IsHexaDecimalDigitCharacter (VariableName[0x9]) || + !IsHexaDecimalDigitCharacter (VariableName[0xA]) || + !IsHexaDecimalDigitCharacter (VariableName[0xB])) { + return FALSE; + } + + return TRUE; +} + +/** + This code checks if variable should be treated as read-only variable. + + @param[in] VariableName Name of the Variable. + @param[in] VendorGuid GUID of the Variable. + + @retval TRUE This variable is read-only variable. + @retval FALSE This variable is NOT read-only variable. + +**/ +BOOLEAN +IsReadOnlyVariable ( + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid + ) +{ + if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid)) { + if ((StrCmp (VariableName, EFI_SETUP_MODE_NAME) == 0) || + (StrCmp (VariableName, EFI_SIGNATURE_SUPPORT_NAME) == 0) || + (StrCmp (VariableName, EFI_SECURE_BOOT_MODE_NAME) == 0)) { + return TRUE; + } + } + + return FALSE; +} + /** This code finds variable in storage blocks (Volatile or Non-Volatile). + Caution: This function may receive untrusted input. + This function may be invoked in SMM mode, and datasize is external input. + This function will do basic validation, before parse the data. + @param VariableName Name of Variable to be found. @param VendorGuid Variable vendor GUID. @param Attributes Attribute value of the variable found. @param DataSize Size of Data found. If size is less than the data, this value contains the required size. @param Data Data pointer. - + @return EFI_INVALID_PARAMETER Invalid parameter. @return EFI_SUCCESS Find the specified variable. @return EFI_NOT_FOUND Not found. @@ -1872,8 +2347,8 @@ VariableServiceGetVariable ( } AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock); - - Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal); + + Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE); if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) { goto Done; } @@ -1897,7 +2372,7 @@ VariableServiceGetVariable ( *DataSize = VarDataSize; UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE); - + Status = EFI_SUCCESS; goto Done; } else { @@ -1917,6 +2392,9 @@ Done: This code Finds the Next available variable. + Caution: This function may receive untrusted input. + This function may be invoked in SMM mode. This function will do basic validation, before parse the data. + @param VariableNameSize Size of the variable name. @param VariableName Pointer to variable name. @param VendorGuid Variable Vendor Guid. @@ -1935,9 +2413,13 @@ VariableServiceGetNextVariableName ( IN OUT EFI_GUID *VendorGuid ) { + VARIABLE_STORE_TYPE Type; VARIABLE_POINTER_TRACK Variable; + VARIABLE_POINTER_TRACK VariableInHob; + VARIABLE_POINTER_TRACK VariablePtrTrack; UINTN VarNameSize; EFI_STATUS Status; + VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax]; if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) { return EFI_INVALID_PARAMETER; @@ -1945,7 +2427,7 @@ VariableServiceGetNextVariableName ( AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock); - Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal); + Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE); if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) { goto Done; } @@ -1957,45 +2439,105 @@ VariableServiceGetNextVariableName ( Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); } + // + // 0: Volatile, 1: HOB, 2: Non-Volatile. + // The index and attributes mapping must be kept in this order as FindVariable + // makes use of this mapping to implement search algorithm. + // + VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase; + VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase; + VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache; + while (TRUE) { // - // If both volatile and non-volatile variable store are parsed, - // return not found. + // Switch from Volatile to HOB, to Non-Volatile. // - if (Variable.CurrPtr >= Variable.EndPtr || Variable.CurrPtr == NULL) { - Variable.Volatile = (BOOLEAN) (Variable.Volatile ^ ((BOOLEAN) 0x1)); - if (!Variable.Volatile) { - Variable.StartPtr = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase); - Variable.EndPtr = GetEndPointer ((VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase)); - } else { + while ((Variable.CurrPtr >= Variable.EndPtr) || + (Variable.CurrPtr == NULL) || + !IsValidVariableHeader (Variable.CurrPtr) + ) { + // + // Find current storage index + // + for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) { + if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) { + break; + } + } + ASSERT (Type < VariableStoreTypeMax); + // + // Switch to next storage + // + for (Type++; Type < VariableStoreTypeMax; Type++) { + if (VariableStoreHeader[Type] != NULL) { + break; + } + } + // + // Capture the case that + // 1. current storage is the last one, or + // 2. no further storage + // + if (Type == VariableStoreTypeMax) { Status = EFI_NOT_FOUND; goto Done; } - - Variable.CurrPtr = Variable.StartPtr; - if (!IsValidVariableHeader (Variable.CurrPtr)) { - continue; - } + Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]); + Variable.EndPtr = GetEndPointer (VariableStoreHeader[Type]); + Variable.CurrPtr = Variable.StartPtr; } + // // Variable is found // - if (IsValidVariableHeader (Variable.CurrPtr) && Variable.CurrPtr->State == VAR_ADDED) { - if ((AtRuntime () && ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) == 0) { + if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { + if (!AtRuntime () || ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) { + if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { + // + // If it is a IN_DELETED_TRANSITION variable, + // and there is also a same ADDED one at the same time, + // don't return it. + // + VariablePtrTrack.StartPtr = Variable.StartPtr; + VariablePtrTrack.EndPtr = Variable.EndPtr; + Status = FindVariableEx ( + GetVariableNamePtr (Variable.CurrPtr), + &Variable.CurrPtr->VendorGuid, + FALSE, + &VariablePtrTrack + ); + if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) { + Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); + continue; + } + } + + // + // Don't return NV variable when HOB overrides it + // + if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) && + (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv])) + ) { + VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]); + VariableInHob.EndPtr = GetEndPointer (VariableStoreHeader[VariableStoreTypeHob]); + Status = FindVariableEx ( + GetVariableNamePtr (Variable.CurrPtr), + &Variable.CurrPtr->VendorGuid, + FALSE, + &VariableInHob + ); + if (!EFI_ERROR (Status)) { + Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); + continue; + } + } + VarNameSize = NameSizeOfVariable (Variable.CurrPtr); ASSERT (VarNameSize != 0); if (VarNameSize <= *VariableNameSize) { - CopyMem ( - VariableName, - GetVariableNamePtr (Variable.CurrPtr), - VarNameSize - ); - CopyMem ( - VendorGuid, - &Variable.CurrPtr->VendorGuid, - sizeof (EFI_GUID) - ); + CopyMem (VariableName, GetVariableNamePtr (Variable.CurrPtr), VarNameSize); + CopyMem (VendorGuid, &Variable.CurrPtr->VendorGuid, sizeof (EFI_GUID)); Status = EFI_SUCCESS; } else { Status = EFI_BUFFER_TOO_SMALL; @@ -2018,6 +2560,13 @@ Done: This code sets variable in storage blocks (Volatile or Non-Volatile). + Caution: This function may receive untrusted input. + This function may be invoked in SMM mode, and datasize and data are external input. + This function will do basic validation, before parse the data. + This function will parse the authentication carefully to avoid security issues, like + buffer overflow, integer overflow. + This function will check attribute carefully to avoid authentication bypass. + @param VariableName Name of Variable to be found. @param VendorGuid Variable vendor GUID. @param Attributes Attribute value of the variable found @@ -2053,12 +2602,23 @@ VariableServiceSetVariable ( // if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) { return EFI_INVALID_PARAMETER; - } + } + + if (IsReadOnlyVariable (VariableName, VendorGuid)) { + return EFI_WRITE_PROTECTED; + } if (DataSize != 0 && Data == NULL) { return EFI_INVALID_PARAMETER; } + // + // Check for reserverd bit in variable attribute. + // + if ((Attributes & (~EFI_VARIABLE_ATTRIBUTES_MASK)) != 0) { + return EFI_INVALID_PARAMETER; + } + // // Make sure if runtime bit is set, boot service bit is set also. // @@ -2067,25 +2627,36 @@ VariableServiceSetVariable ( } // - // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute + // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute // cannot be set both. // - if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) \ + if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) && ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) { return EFI_INVALID_PARAMETER; - } + } if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) { if (DataSize < AUTHINFO_SIZE) { // - // Try to write Authencated Variable without AuthInfo. + // Try to write Authenticated Variable without AuthInfo. // return EFI_SECURITY_VIOLATION; - } - PayloadSize = DataSize - AUTHINFO_SIZE; + } + PayloadSize = DataSize - AUTHINFO_SIZE; + } else if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) { + // + // Sanity check for EFI_VARIABLE_AUTHENTICATION_2 descriptor. + // + if (DataSize < OFFSET_OF_AUTHINFO2_CERT_DATA || + ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength > DataSize - (OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo)) || + ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength < OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData)) { + return EFI_SECURITY_VIOLATION; + } + PayloadSize = DataSize - AUTHINFO2_SIZE (Data); } else { - PayloadSize = DataSize; + PayloadSize = DataSize; } + // // The size of the VariableName, including the Unicode Null in bytes plus // the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize) @@ -2096,10 +2667,7 @@ VariableServiceSetVariable ( (sizeof (VARIABLE_HEADER) + StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize))) { return EFI_INVALID_PARAMETER; } - // - // According to UEFI spec, HARDWARE_ERROR_RECORD variable name convention should be L"HwErrRecXXXX". - // - if (StrnCmp(VariableName, L"HwErrRec", StrLen(L"HwErrRec")) != 0) { + if (!IsHwErrRecVariable(VariableName, VendorGuid)) { return EFI_INVALID_PARAMETER; } } else { @@ -2110,8 +2678,18 @@ VariableServiceSetVariable ( if ((PayloadSize > PcdGet32 (PcdMaxVariableSize)) || (sizeof (VARIABLE_HEADER) + StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxVariableSize))) { return EFI_INVALID_PARAMETER; - } - } + } + } + + if (AtRuntime ()) { + // + // HwErrRecSupport Global Variable identifies the level of hardware error record persistence + // support implemented by the platform. This variable is only modified by firmware and is read-only to the OS. + // + if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, L"HwErrRecSupport") == 0)) { + return EFI_WRITE_PROTECTED; + } + } AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock); @@ -2124,7 +2702,7 @@ VariableServiceSetVariable ( // Parse non-volatile variable data and get last variable offset. // NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point); - while ((NextVariable < GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point)) + while ((NextVariable < GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point)) && IsValidVariableHeader (NextVariable)) { NextVariable = GetNextVariablePtr (NextVariable); } @@ -2134,8 +2712,13 @@ VariableServiceSetVariable ( // // Check whether the input variable is already existed. // - FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal); - + Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, TRUE); + if (!EFI_ERROR (Status)) { + if (((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) && AtRuntime ()) { + return EFI_WRITE_PROTECTED; + } + } + // // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang. // @@ -2147,8 +2730,12 @@ VariableServiceSetVariable ( Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, TRUE); } else if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0)) { Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, FALSE); - } else if (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) && ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == 0)) { - Status = ProcessVarWithKek (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes); + } else if (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) && + ((StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) || (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0))) { + Status = ProcessVarWithPk (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes, FALSE); + if (EFI_ERROR (Status)) { + Status = ProcessVarWithKek (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes); + } } else { Status = ProcessVariable (VariableName, VendorGuid, Data, DataSize, &Variable, Attributes); } @@ -2163,6 +2750,9 @@ VariableServiceSetVariable ( This code returns information about the EFI variables. + Caution: This function may receive untrusted input. + This function may be invoked in SMM mode. This function will do basic validation, before parse the data. + @param Attributes Attributes bitmask to specify the type of variables on which to return information. @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available @@ -2204,7 +2794,7 @@ VariableServiceQueryVariableInfo ( // // Make sure the Attributes combination is supported by the platform. // - return EFI_UNSUPPORTED; + return EFI_UNSUPPORTED; } else if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) { // // Make sure if runtime bit is set, boot service bit is set also. @@ -2323,7 +2913,10 @@ VariableServiceQueryVariableInfo ( /** This function reclaims variable storage if free size is below the threshold. - + + Caution: This function may be invoked at SMM mode. + Care must be taken to make sure not security issue. + **/ VOID ReclaimForOS( @@ -2335,7 +2928,7 @@ ReclaimForOS( UINTN RemainingCommonVariableSpace; UINTN RemainingHwErrVariableSpace; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; CommonVariableSpace = ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase)))->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32(PcdHwErrStorageSize); //Allowable max size of common variable storage space @@ -2346,18 +2939,109 @@ ReclaimForOS( // Check if the free area is blow a threshold. // if ((RemainingCommonVariableSpace < PcdGet32 (PcdMaxVariableSize)) - || ((PcdGet32 (PcdHwErrStorageSize) != 0) && + || ((PcdGet32 (PcdHwErrStorageSize) != 0) && (RemainingHwErrVariableSpace < PcdGet32 (PcdMaxHardwareErrorVariableSize)))){ Status = Reclaim ( mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase, &mVariableModuleGlobal->NonVolatileLastVariableOffset, FALSE, - NULL + NULL, + FALSE, + FALSE ); ASSERT_EFI_ERROR (Status); } } +/** + Flush the HOB variable to flash. + + @param[in] VariableName Name of variable has been updated or deleted. + @param[in] VendorGuid Guid of variable has been updated or deleted. + +**/ +VOID +FlushHobVariableToFlash ( + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid + ) +{ + EFI_STATUS Status; + VARIABLE_STORE_HEADER *VariableStoreHeader; + VARIABLE_HEADER *Variable; + VOID *VariableData; + BOOLEAN ErrorFlag; + + ErrorFlag = FALSE; + + // + // Flush the HOB variable to flash. + // + if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) { + VariableStoreHeader = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase; + // + // Set HobVariableBase to 0, it can avoid SetVariable to call back. + // + mVariableModuleGlobal->VariableGlobal.HobVariableBase = 0; + for ( Variable = GetStartPointer (VariableStoreHeader) + ; (Variable < GetEndPointer (VariableStoreHeader) && IsValidVariableHeader (Variable)) + ; Variable = GetNextVariablePtr (Variable) + ) { + if (Variable->State != VAR_ADDED) { + // + // The HOB variable has been set to DELETED state in local. + // + continue; + } + ASSERT ((Variable->Attributes & EFI_VARIABLE_NON_VOLATILE) != 0); + if (VendorGuid == NULL || VariableName == NULL || + !CompareGuid (VendorGuid, &Variable->VendorGuid) || + StrCmp (VariableName, GetVariableNamePtr (Variable)) != 0) { + VariableData = GetVariableDataPtr (Variable); + Status = VariableServiceSetVariable ( + GetVariableNamePtr (Variable), + &Variable->VendorGuid, + Variable->Attributes, + Variable->DataSize, + VariableData + ); + DEBUG ((EFI_D_INFO, "Variable driver flush the HOB variable to flash: %g %s %r\n", &Variable->VendorGuid, GetVariableNamePtr (Variable), Status)); + } else { + // + // The updated or deleted variable is matched with the HOB variable. + // Don't break here because we will try to set other HOB variables + // since this variable could be set successfully. + // + Status = EFI_SUCCESS; + } + if (!EFI_ERROR (Status)) { + // + // If set variable successful, or the updated or deleted variable is matched with the HOB variable, + // set the HOB variable to DELETED state in local. + // + DEBUG ((EFI_D_INFO, "Variable driver set the HOB variable to DELETED state in local: %g %s\n", &Variable->VendorGuid, GetVariableNamePtr (Variable))); + Variable->State &= VAR_DELETED; + } else { + ErrorFlag = TRUE; + } + } + if (ErrorFlag) { + // + // We still have HOB variable(s) not flushed in flash. + // + mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStoreHeader; + } else { + // + // All HOB variables have been flushed in flash. + // + DEBUG ((EFI_D_INFO, "Variable driver: all HOB variables have been flushed in flash.\n")); + if (!AtRuntime ()) { + FreePool ((VOID *) VariableStoreHeader); + } + } + } + +} /** Initializes variable write service after FVB was ready. @@ -2376,16 +3060,14 @@ VariableWriteServiceInitialize ( UINTN Index; UINT8 Data; EFI_PHYSICAL_ADDRESS VariableStoreBase; - UINT64 VariableStoreLength; VariableStoreBase = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase; VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase; - VariableStoreLength = VariableStoreHeader->Size; - + // // Check if the free area is really free. // - for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < VariableStoreLength; Index++) { + for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < VariableStoreHeader->Size; Index++) { Data = ((UINT8 *) mNvVariableCache)[Index]; if (Data != 0xff) { // @@ -2395,7 +3077,9 @@ VariableWriteServiceInitialize ( mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase, &mVariableModuleGlobal->NonVolatileLastVariableOffset, FALSE, - NULL + NULL, + FALSE, + TRUE ); if (EFI_ERROR (Status)) { return Status; @@ -2404,6 +3088,8 @@ VariableWriteServiceInitialize ( } } + FlushHobVariableToFlash (NULL, NULL); + // // Authenticated variable initialize. // @@ -2434,6 +3120,7 @@ VariableCommonInitialize ( UINT64 VariableStoreLength; UINTN ScratchSize; UINTN VariableSize; + EFI_HOB_GUID_TYPE *GuidHob; // // Allocate runtime memory for variable driver global structure. @@ -2448,11 +3135,28 @@ VariableCommonInitialize ( // // Note that in EdkII variable driver implementation, Hardware Error Record type variable // is stored with common variable in the same NV region. So the platform integrator should - // ensure that the value of PcdHwErrStorageSize is less than or equal to the value of + // ensure that the value of PcdHwErrStorageSize is less than or equal to the value of // PcdFlashNvStorageVariableSize. // ASSERT (PcdGet32 (PcdHwErrStorageSize) <= PcdGet32 (PcdFlashNvStorageVariableSize)); + // + // Get HOB variable store. + // + GuidHob = GetFirstGuidHob (&gEfiAuthenticatedVariableGuid); + if (GuidHob != NULL) { + VariableStoreHeader = GET_GUID_HOB_DATA (GuidHob); + VariableStoreLength = (UINT64) (GuidHob->Header.HobLength - sizeof (EFI_HOB_GUID_TYPE)); + if (GetVariableStoreStatus (VariableStoreHeader) == EfiValid) { + mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) AllocateRuntimeCopyPool ((UINTN) VariableStoreLength, (VOID *) VariableStoreHeader); + if (mVariableModuleGlobal->VariableGlobal.HobVariableBase == 0) { + return EFI_OUT_OF_RESOURCES; + } + } else { + DEBUG ((EFI_D_ERROR, "HOB Variable Store header is corrupted!\n")); + } + } + // // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data. // @@ -2480,13 +3184,24 @@ VariableCommonInitialize ( VolatileVariableStore->Reserved1 = 0; // - // Get non-volatile varaible store. + // Get non-volatile variable store. // TempVariableStoreHeader = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64); if (TempVariableStoreHeader == 0) { TempVariableStoreHeader = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase); } + + // + // Check if the Firmware Volume is not corrupted + // + if ((((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader))->Signature != EFI_FVH_SIGNATURE) || + (!CompareGuid (&gEfiSystemNvDataFvGuid, &((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader))->FileSystemGuid))) { + Status = EFI_VOLUME_CORRUPTED; + DEBUG ((EFI_D_ERROR, "Firmware Volume for Variable Store is corrupted\n")); + goto Done; + } + VariableStoreBase = TempVariableStoreHeader + \ (((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader)) -> HeaderLength); VariableStoreLength = (UINT64) PcdGet32 (PcdFlashNvStorageVariableSize) - \ @@ -2498,9 +3213,9 @@ VariableCommonInitialize ( Status = EFI_VOLUME_CORRUPTED; DEBUG((EFI_D_INFO, "Variable Store header is corrupted\n")); goto Done; - } + } ASSERT(VariableStoreHeader->Size == VariableStoreLength); - + // // Parse non-volatile variable data and get last variable offset. // @@ -2517,7 +3232,7 @@ VariableCommonInitialize ( } mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) VariableStoreBase; - + // // Allocate runtime memory used for a memory copy of the FLASH region. // Keep the memory and the FLASH in sync as updates occur @@ -2563,7 +3278,7 @@ GetFvbInfoByAddress ( EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb; EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; EFI_FVB_ATTRIBUTES_2 Attributes; - + // // Get all FVB handles. // @@ -2588,9 +3303,9 @@ GetFvbInfoByAddress ( // Status = Fvb->GetAttributes (Fvb, &Attributes); if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) { - continue; + continue; } - + // // Compare the address and select the right one. // @@ -2616,7 +3331,7 @@ GetFvbInfoByAddress ( if (Fvb == NULL) { Status = EFI_NOT_FOUND; } - - return Status; + + return Status; }