diff --git a/AdvLoggerPkg/Application/DecodeUefiLog/DecodeUefiLog.py b/AdvLoggerPkg/Application/DecodeUefiLog/DecodeUefiLog.py index cdc5e7d6f3..19840779e8 100644 --- a/AdvLoggerPkg/Application/DecodeUefiLog/DecodeUefiLog.py +++ b/AdvLoggerPkg/Application/DecodeUefiLog/DecodeUefiLog.py @@ -12,8 +12,7 @@ import copy from win32com.shell import shell - -from UefiVariablesSupportLib import UefiVariable +from edk2toollib.os.uefivariablesupport import UefiVariable class AdvLogParser (): @@ -1003,7 +1002,7 @@ def ReadLogFromUefiInterface(): while rc == 0: VariableName = 'V'+str(Index) - (rc, var, errorstring) = UefiVar.GetUefiVar(VariableName, 'a021bf2b-34ed-4a98-859c-420ef94f3e94') + (rc, var) = UefiVar.GetUefiVar(VariableName, 'a021bf2b-34ed-4a98-859c-420ef94f3e94') if (rc == 0): Index += 1 InFile.write(var) @@ -1060,7 +1059,7 @@ def main(): CountOfLines = len(lines) print(f"{CountOfLines} lines written to {options.OutFilePath}") - except Exception as ex: + except Exception: print("Error processing log output.") traceback.print_exc() @@ -1072,7 +1071,7 @@ def main(): RawFile.close() print("RawFile complete") - except Exception as ex: + except Exception: print("Error processing raw file output.") traceback.print_exc() diff --git a/AdvLoggerPkg/Application/DecodeUefiLog/UefiVariablesSupportLib.py b/AdvLoggerPkg/Application/DecodeUefiLog/UefiVariablesSupportLib.py deleted file mode 100644 index ba63fa458c..0000000000 --- a/AdvLoggerPkg/Application/DecodeUefiLog/UefiVariablesSupportLib.py +++ /dev/null @@ -1,114 +0,0 @@ -# @file -# -# Python lib to support Reading and writing UEFI variables from windows -# -# Modified from original source to not produce error messages for Variable NOT FOUND -# -# Copyright (c), Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent - -import os, sys -from ctypes import * -import logging -import pywintypes -import win32api, win32process, win32security, win32file -import winerror - -kernel32 = windll.kernel32 -EFI_VAR_MAX_BUFFER_SIZE = 1024*1024 - -class UefiVariable(object): - - def __init__(self): - # enable required SeSystemEnvironmentPrivilege privilege - privilege = win32security.LookupPrivilegeValue( None, 'SeSystemEnvironmentPrivilege' ) - token = win32security.OpenProcessToken( win32process.GetCurrentProcess(), win32security.TOKEN_READ|win32security.TOKEN_ADJUST_PRIVILEGES ) - win32security.AdjustTokenPrivileges( token, False, [(privilege, win32security.SE_PRIVILEGE_ENABLED)] ) - win32api.CloseHandle( token ) - - # import firmware variable API - try: - self._GetFirmwareEnvironmentVariable = kernel32.GetFirmwareEnvironmentVariableW - self._GetFirmwareEnvironmentVariable.restype = c_int - self._GetFirmwareEnvironmentVariable.argtypes = [c_wchar_p, c_wchar_p, c_void_p, c_int] - self._SetFirmwareEnvironmentVariable = kernel32.SetFirmwareEnvironmentVariableW - self._SetFirmwareEnvironmentVariable.restype = c_int - self._SetFirmwareEnvironmentVariable.argtypes = [c_wchar_p, c_wchar_p, c_void_p, c_int] - self._SetFirmwareEnvironmentVariableEx = kernel32.SetFirmwareEnvironmentVariableExW - self._SetFirmwareEnvironmentVariableEx.restype = c_int - self._SetFirmwareEnvironmentVariableEx.argtypes = [c_wchar_p, c_wchar_p, c_void_p, c_int, c_int] - except AttributeError as msg: - logging.warn( "G[S]etFirmwareEnvironmentVariableW function doesn't seem to exist" ) - pass - - # - # Helper function to create buffer for var read/write - # - def CreateBuffer(self, init, size=None): - """CreateBuffer(aString) -> character array - CreateBuffer(anInteger) -> character array - CreateBuffer(aString, anInteger) -> character array - """ - if isinstance(init, str): - if size is None: - size = len(init)+1 - buftype = c_char * size - buf = buftype() - buf.value = init - return buf - elif isinstance(init, int): - buftype = c_char * init - buf = buftype() - return buf - raise TypeError(init) - - # - #Function to get variable - # return a tuple of error code and variable data as string - # - def GetUefiVar(self, name, guid ): - err = 0 #success - efi_var = create_string_buffer( EFI_VAR_MAX_BUFFER_SIZE ) - if self._GetFirmwareEnvironmentVariable is not None: - logging.info("calling GetFirmwareEnvironmentVariable( name='%s', GUID='%s' ).." % (name, "{%s}" % guid) ) - length = self._GetFirmwareEnvironmentVariable( name, "{%s}" % guid, efi_var, EFI_VAR_MAX_BUFFER_SIZE ) - if (0 == length) or (efi_var is None): - err = kernel32.GetLastError() - # - # Don't produce an error message for NOT_FOUND - # - if err != 203: # 203 is NOT FOUND - logging.error( 'GetFirmwareEnvironmentVariable[Ex] failed (GetLastError = 0x%x)' % err) - logging.error(WinError()) - return (err, None, WinError(err)) - return (err, efi_var[:length], None) - # - #Function to set variable - # return a tuple of boolean status, errorcode, errorstring (None if not error) - # - def SetUefiVar(self, name, guid, var=None, attrs=None): - var_len = 0 - err = 0 - errorstring = None - if var is None: - var = bytes(0) - else: - var_len = len(var) - success = 0 # Fail - if(attrs == None): - if self._SetFirmwareEnvironmentVariable is not None: - logging.info("Calling SetFirmwareEnvironmentVariable (name='%s', Guid='%s')..." % (name, "{%s}" % guid, )) - success = self._SetFirmwareEnvironmentVariable(name, "{%s}" % guid, var, var_len) - else: - attrs = int(attrs) - if self._SetFirmwareEnvironmentVariableEx is not None: - logging.info(" calling SetFirmwareEnvironmentVariableEx( name='%s', GUID='%s', length=0x%X, attributes=0x%X ).." % (name, "{%s}" % guid, var_len, attrs) ) - success = self._SetFirmwareEnvironmentVariableEx( name, "{%s}" % guid, var, var_len, attrs ) - - if 0 == success: - err = kernel32.GetLastError() - logging.error('SetFirmwareEnvironmentVariable failed (GetLastError = 0x%x)' % err ) - logging.error(WinError()) - errorstring = WinError(err) - return (success,err, errorstring) - diff --git a/MfciPkg/Application/MfciPolicy/MfciPolicy.py b/MfciPkg/Application/MfciPolicy/MfciPolicy.py index 97de7979fb..ac6470eddc 100644 --- a/MfciPkg/Application/MfciPolicy/MfciPolicy.py +++ b/MfciPkg/Application/MfciPolicy/MfciPolicy.py @@ -11,7 +11,7 @@ import logging import argparse import ctypes -from UefiVariableSupport.UefiVariablesSupportLib import UefiVariable +from edk2toollib.os.uefivariablesupport import UefiVariable MFCI_VENDOR_GUID = "EBA1A9D2-BF4D-4736-B680-B36AFB4DD65B" CURRENT_POLICY_BLOB = "CurrentMfciPolicyBlob" @@ -77,7 +77,7 @@ def get_system_info(): UefiVar = UefiVariable() for Variable in MFCI_POLICY_INFO_VARIABLES: - (errorcode, data, errorstring) = UefiVar.GetUefiVar(Variable, MFCI_VENDOR_GUID) + (errorcode, data) = UefiVar.GetUefiVar(Variable, MFCI_VENDOR_GUID) if errorcode != 0: logging.critical(f"Failed to get policy variable {Variable}") else: @@ -91,7 +91,7 @@ def get_system_info(): def get_current_mfci_policy(): UefiVar = UefiVariable() - (errorcode, data, errorstring) = UefiVar.GetUefiVar(CURRENT_MFCI_POLICY, MFCI_VENDOR_GUID) + (errorcode, data) = UefiVar.GetUefiVar(CURRENT_MFCI_POLICY, MFCI_VENDOR_GUID) if errorcode == 0: result = hex(int.from_bytes(data, byteorder="little", signed=False)) logging.info(f" Current MFCI Policy is {result}") @@ -104,17 +104,17 @@ def get_current_mfci_policy(): def delete_current_mfci_policy(): UefiVar = UefiVariable() - (errorcode, data, errorstring) = UefiVar.SetUefiVar(CURRENT_POLICY_BLOB, MFCI_VENDOR_GUID, None, 3) + (errorcode, data) = UefiVar.SetUefiVar(CURRENT_POLICY_BLOB, MFCI_VENDOR_GUID, None, 3) if errorcode == 0: - logging.info(f"Failed to Delete {CURRENT_POLICY_BLOB}\n {errorcode}{errorstring}") + logging.info(f"Failed to Delete {CURRENT_POLICY_BLOB}\n {errorcode}") print(f"Failed to delete {CURRENT_POLICY_BLOB}") else: logging.info(f"{CURRENT_POLICY_BLOB} was deleted") print(f"{CURRENT_POLICY_BLOB} was deleted") - (errorcode, data, errorstring) = UefiVar.SetUefiVar(NEXT_MFCI_POLICY_BLOB, MFCI_VENDOR_GUID, None, 3) + (errorcode, data) = UefiVar.SetUefiVar(NEXT_MFCI_POLICY_BLOB, MFCI_VENDOR_GUID, None, 3) if errorcode == 0: - logging.info(f"Failed to Delete {NEXT_MFCI_POLICY_BLOB}\n {errorcode}{errorstring}") + logging.info(f"Failed to Delete {NEXT_MFCI_POLICY_BLOB}\n {errorcode}") print(f"Failed to delete {NEXT_MFCI_POLICY_BLOB}") else: logging.info(f"{NEXT_MFCI_POLICY_BLOB} was deleted") @@ -128,9 +128,9 @@ def set_next_mfci_policy(policy): var = file.read() UefiVar = UefiVariable() - (errorcode, data, errorstring) = UefiVar.SetUefiVar(NEXT_MFCI_POLICY_BLOB, MFCI_VENDOR_GUID, var, 3) + (errorcode, data) = UefiVar.SetUefiVar(NEXT_MFCI_POLICY_BLOB, MFCI_VENDOR_GUID, var, 3) if errorcode == 0: - logging.info("Next Policy failed: {errorstring}") + logging.info("Next Policy failed: {errorcode}") else: logging.info("Next Policy was set") print(f"{NEXT_MFCI_POLICY_BLOB} was set") @@ -139,7 +139,7 @@ def set_next_mfci_policy(policy): def get_next_mfci_policy(): UefiVar = UefiVariable() - (errorcode, data, errorstring) = UefiVar.GetUefiVar(NEXT_MFCI_POLICY_BLOB, MFCI_VENDOR_GUID) + (errorcode, data) = UefiVar.GetUefiVar(NEXT_MFCI_POLICY_BLOB, MFCI_VENDOR_GUID) if errorcode != 0: logging.info("No Next Mfci Policy Set") print(f"No variable {NEXT_MFCI_POLICY_BLOB} found") diff --git a/MfciPkg/Application/MfciPolicy/UefiVariableSupport/UefiVariablesSupportLib.py b/MfciPkg/Application/MfciPolicy/UefiVariableSupport/UefiVariablesSupportLib.py deleted file mode 100644 index 0197efb844..0000000000 --- a/MfciPkg/Application/MfciPolicy/UefiVariableSupport/UefiVariablesSupportLib.py +++ /dev/null @@ -1,169 +0,0 @@ -# @file -# -# Python lib to support Reading and writing UEFI variables from windows -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent - -from ctypes import ( - windll, - c_wchar_p, - c_void_p, - c_int, - c_char, - create_string_buffer, - WinError, -) -import logging -from win32 import win32api -from win32 import win32process -from win32 import win32security - -kernel32 = windll.kernel32 -EFI_VAR_MAX_BUFFER_SIZE = 1024 * 1024 - - -class UefiVariable(object): - def __init__(self): - # enable required SeSystemEnvironmentPrivilege privilege - privilege = win32security.LookupPrivilegeValue( - None, "SeSystemEnvironmentPrivilege" - ) - token = win32security.OpenProcessToken( - win32process.GetCurrentProcess(), - win32security.TOKEN_READ | win32security.TOKEN_ADJUST_PRIVILEGES, - ) - win32security.AdjustTokenPrivileges( - token, False, [(privilege, win32security.SE_PRIVILEGE_ENABLED)] - ) - win32api.CloseHandle(token) - - # import firmware variable API - try: - self._GetFirmwareEnvironmentVariable = ( - kernel32.GetFirmwareEnvironmentVariableW - ) - self._GetFirmwareEnvironmentVariable.restype = c_int - self._GetFirmwareEnvironmentVariable.argtypes = [ - c_wchar_p, - c_wchar_p, - c_void_p, - c_int, - ] - self._SetFirmwareEnvironmentVariable = ( - kernel32.SetFirmwareEnvironmentVariableW - ) - self._SetFirmwareEnvironmentVariable.restype = c_int - self._SetFirmwareEnvironmentVariable.argtypes = [ - c_wchar_p, - c_wchar_p, - c_void_p, - c_int, - ] - self._SetFirmwareEnvironmentVariableEx = ( - kernel32.SetFirmwareEnvironmentVariableExW - ) - self._SetFirmwareEnvironmentVariableEx.restype = c_int - self._SetFirmwareEnvironmentVariableEx.argtypes = [ - c_wchar_p, - c_wchar_p, - c_void_p, - c_int, - c_int, - ] - except Exception: - logging.warn( - "G[S]etFirmwareEnvironmentVariableW function doesn't seem to exist" - ) - pass - - # - # Helper function to create buffer for var read/write - # - def CreateBuffer(self, init, size=None): - """CreateBuffer(aString) -> character array - CreateBuffer(anInteger) -> character array - CreateBuffer(aString, anInteger) -> character array - """ - if isinstance(init, str): - if size is None: - size = len(init) + 1 - buftype = c_char * size - buf = buftype() - buf.value = init - return buf - elif isinstance(init, int): - buftype = c_char * init - buf = buftype() - return buf - raise TypeError(init) - - # - # Function to get variable - # return a tuple of error code and variable data as string - # - def GetUefiVar(self, name, guid): - # success - err = 0 - efi_var = create_string_buffer(EFI_VAR_MAX_BUFFER_SIZE) - if self._GetFirmwareEnvironmentVariable is not None: - logging.info( - "calling GetFirmwareEnvironmentVariable( name='%s', GUID='%s' ).." - % (name, "{%s}" % guid) - ) - length = self._GetFirmwareEnvironmentVariable( - name, "{%s}" % guid, efi_var, EFI_VAR_MAX_BUFFER_SIZE - ) - if (0 == length) or (efi_var is None): - err = kernel32.GetLastError() - logging.error( - "GetFirmwareEnvironmentVariable[Ex] failed (GetLastError = 0x%x)" % err - ) - logging.error(WinError()) - return (err, None, WinError(err)) - return (err, efi_var[:length], None) - - # - # Function to set variable - # return a tuple of boolean status, error_code, error_string (None if not error) - # - def SetUefiVar(self, name, guid, var=None, attrs=None): - var_len = 0 - err = 0 - error_string = None - if var is None: - var = bytes(0) - else: - var_len = len(var) - success = 0 # Fail - if attrs is None: - if self._SetFirmwareEnvironmentVariable is not None: - logging.info( - "Calling SetFirmwareEnvironmentVariable (name='%s', Guid='%s')..." - % ( - name, - "{%s}" % guid, - ) - ) - success = self._SetFirmwareEnvironmentVariable( - name, "{%s}" % guid, var, var_len - ) - else: - attrs = int(attrs) - if self._SetFirmwareEnvironmentVariableEx is not None: - logging.info( - "Calling SetFirmwareEnvironmentVariableEx( name='%s', GUID='%s', length=0x%X, attributes=0x%X ).." - % (name, "{%s}" % guid, var_len, attrs) - ) - success = self._SetFirmwareEnvironmentVariableEx( - name, "{%s}" % guid, var, var_len, attrs - ) - - if 0 == success: - err = kernel32.GetLastError() - logging.error( - "SetFirmwareEnvironmentVariable failed (GetLastError = 0x%x)" % err - ) - logging.error(WinError()) - error_string = WinError(err) - return (success, err, error_string) diff --git a/UefiTestingPkg/AuditTests/UefiVarLockAudit/Windows/UefiVarAudit.py b/UefiTestingPkg/AuditTests/UefiVarLockAudit/Windows/UefiVarAudit.py index 2507142c93..fb38bd776e 100644 --- a/UefiTestingPkg/AuditTests/UefiVarLockAudit/Windows/UefiVarAudit.py +++ b/UefiTestingPkg/AuditTests/UefiVarLockAudit/Windows/UefiVarAudit.py @@ -8,17 +8,14 @@ ## -import os, sys +import os +import sys import argparse import logging import datetime -import struct -import hashlib -import shutil -import time import xml.etree.ElementTree as ET from xml.etree.ElementTree import Element -from UefiVariablesSupportLib import UefiVariable +from edk2toollib.os.uefivariablesupport import UefiVariable # #main script function @@ -72,13 +69,13 @@ def main(): for var in XmlRoot.findall("Variable"): name = var.get("Name") guid = var.get("Guid") - (ReadStatus, Data, ReadErrorString) = Uefi.GetUefiVar(name, guid) - (WriteSuccess, ErrorCode, WriteErrorString)= Uefi.SetUefiVar(name, guid) + (ReadStatus, Data) = Uefi.GetUefiVar(name, guid) + (WriteSuccess, ErrorCode)= Uefi.SetUefiVar(name, guid) if(WriteSuccess != 0): logging.info("Must Restore Var %s:%s" % (name, guid)) - (RestoreSuccess, RestoreEC, RestoreErrorString) = Uefi.SetUefiVar(name, guid, Data) + (RestoreSuccess, RestoreEC) = Uefi.SetUefiVar(name, guid, Data) if (RestoreSuccess == 0): - logging.critical("Restoring failed for Var %s:%s 0x%X ErrorCode: 0x%X %s" % (name, guid, RestoreSuccess, RestoreEC, RestoreErrorString)) + logging.critical("Restoring failed for Var %s:%s 0x%X ErrorCode: 0x%X %s" % (name, guid, RestoreSuccess, RestoreEC)) #append # #0x0 Success @@ -87,11 +84,7 @@ def main(): rs = Element("ReadStatus") ws = Element("WriteStatus") rs.text = "0x%lX" % (ReadStatus) - if(ReadErrorString is not None): - rs.text = rs.text + " %s" % ReadErrorString ws.text = "0x%lX" % ErrorCode - if(WriteErrorString is not None): - ws.text = ws.text + " %s" % WriteErrorString ele.append(rs) ele.append(ws) var.append(ele) diff --git a/UefiTestingPkg/AuditTests/UefiVarLockAudit/Windows/UefiVariablesSupportLib.py b/UefiTestingPkg/AuditTests/UefiVarLockAudit/Windows/UefiVariablesSupportLib.py deleted file mode 100644 index 9398cbc195..0000000000 --- a/UefiTestingPkg/AuditTests/UefiVarLockAudit/Windows/UefiVariablesSupportLib.py +++ /dev/null @@ -1,92 +0,0 @@ -## -## Python lib to support Reading and writing UEFI variables from windows -## -# -# -# Copyright (C) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -import os, sys -from ctypes import * -import logging -import pywintypes -import win32api, win32process, win32security, win32file -import winerror - -kernel32 = windll.kernel32 -EFI_VAR_MAX_BUFFER_SIZE = 1024*1024 - -class UefiVariable(object): - - def __init__(self): - # enable required SeSystemEnvironmentPrivilege privilege - privilege = win32security.LookupPrivilegeValue( None, 'SeSystemEnvironmentPrivilege' ) - token = win32security.OpenProcessToken( win32process.GetCurrentProcess(), win32security.TOKEN_READ|win32security.TOKEN_ADJUST_PRIVILEGES ) - win32security.AdjustTokenPrivileges( token, False, [(privilege, win32security.SE_PRIVILEGE_ENABLED)] ) - win32api.CloseHandle( token ) - - # get windows firmware variable API - try: - self._GetFirmwareEnvironmentVariable = kernel32.GetFirmwareEnvironmentVariableW - self._GetFirmwareEnvironmentVariable.restype = c_int - self._GetFirmwareEnvironmentVariable.argtypes = [c_wchar_p, c_wchar_p, c_void_p, c_int] - self._SetFirmwareEnvironmentVariable = kernel32.SetFirmwareEnvironmentVariableW - self._SetFirmwareEnvironmentVariable.restype = c_int - self._SetFirmwareEnvironmentVariable.argtypes = [c_wchar_p, c_wchar_p, c_void_p, c_int] - self._SetFirmwareEnvironmentVariableEx = kernel32.SetFirmwareEnvironmentVariableExW - self._SetFirmwareEnvironmentVariableEx.restype = c_int - self._SetFirmwareEnvironmentVariableEx.argtypes = [c_wchar_p, c_wchar_p, c_void_p, c_int, c_int] - except AttributeError: - logging.warn( "Some get/set functions don't't seem to exist" ) - - # - #Function to get variable - # return a tuple of error code and variable data as string - # - def GetUefiVar(self, name, guid ): - err = 0 #success - efi_var = create_string_buffer( EFI_VAR_MAX_BUFFER_SIZE ) - if self._GetFirmwareEnvironmentVariable is not None: - logging.info("calling GetFirmwareEnvironmentVariable( name='%s', GUID='%s' ).." % (name, "{%s}" % guid) ) - length = self._GetFirmwareEnvironmentVariable( name, "{%s}" % guid, efi_var, EFI_VAR_MAX_BUFFER_SIZE ) - if (0 == length) or (efi_var is None): - err = kernel32.GetLastError() - logging.error( 'GetFirmwareEnvironmentVariable[Ex] failed (GetLastError = 0x%x)' % err) - logging.error(WinError()) - return (err, None, WinError(err)) - return (err, efi_var[:length], None) - # - #Function to set variable - # return a tuple of boolean status, errorcode, errorstring (None if not error) - # - def SetUefiVar(self, name, guid, var=None, attrs=None): - var_len = 0 - err = 0 - errorstring = None - if var is None: - var = bytes(0) - else: - var_len = len(var) - if(attrs == None): - if self._SetFirmwareEnvironmentVariable is not None: - logging.info("Calling SetFirmwareEnvironmentVariable (name='%s', Guid='%s')..." % (name, "{%s}" % guid, )) - success = self._SetFirmwareEnvironmentVariable(name, "{%s}" % guid, var, var_len) - else: - if self._SetFirmwareEnvironmentVariableEx is not None: - logging.info(" calling SetFirmwareEnvironmentVariableEx( name='%s', GUID='%s', length=0x%X, attributes=0x%X ).." % (name, "{%s}" % guid, var_len, attrs) ) - success = self._SetFirmwareEnvironmentVariableEx( name, "{%s}" % guid, var, var_len, attrs ) - - if 0 == success: - err = kernel32.GetLastError() - logging.error('SetFirmwareEnvironmentVariable failed (GetLastError = 0x%x)' % err ) - logging.error(WinError()) - errorstring = WinError(err) - return (success,err, errorstring) - - - -#Test code -#UefiVar = UefiVariable() -#(errorcode, data, errorstring) = UefiVar.GetUefiVar('PK', '8BE4DF61-93CA-11D2-AA0D-00E098032B8C') -#(status, errorcode, errorstring) = UefiVar.SetUefiVar('PK','8BE4DF61-93CA-11D2-AA0D-00E098032B8C',None, None) \ No newline at end of file