diff --git a/SetupDataPkg/Tools/ConfigEditor.py b/SetupDataPkg/Tools/ConfigEditor.py index cdb7b470..300f250b 100644 --- a/SetupDataPkg/Tools/ConfigEditor.py +++ b/SetupDataPkg/Tools/ConfigEditor.py @@ -8,6 +8,7 @@ import os import sys import base64 +import datetime from pathlib import Path sys.dont_write_bytecode = True @@ -16,7 +17,6 @@ import tkinter.ttk as ttk # noqa: E402 import tkinter.messagebox as messagebox # noqa: E402 import tkinter.filedialog as filedialog # noqa: E402 -from SettingSupport.SettingsXMLLib import SettingsXMLLib # noqa: E402 from GenNCCfgData import CGenNCCfgData # noqa: E402 from CommonUtility import ( # noqa: E402 bytes_to_value, @@ -917,6 +917,44 @@ def save_delta_file(self, full=False): csv_path, self.cfg_data_list[file_id].org_cfg_data_bin, new_data, full ) + def create_settings_xml(self, filename, version, lsv, settingslist): + + with open(filename, "w") as f: + f.write('\n') + f.write('\n') + f.write(' Dfci Testcase Libraries\n') + f.write(' ') + + print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), end='', file=f) + + f.write('\n') + f.write(' ') + print(version, end='', file=f) + f.write('\n') + f.write(' ') + print(lsv, end='', file=f) + f.write('\n') + f.write(' \n') + + # + # The settings list is a list of a list. The lowest level list is really a tuple of + # setting id and value + # + for setting in settingslist: + f.write(' \n') + f.write(' ') + print(setting[0], end='', file=f) + f.write('\n') + f.write(' ') + print(setting[1], end='', file=f) + f.write('\n') + f.write(' \n') + + f.write(' \n') + f.write('\n') + + return True + def save_to_svd(self, full): path = self.get_save_file_name("svd") if not path: @@ -951,8 +989,7 @@ def save_to_svd(self, full): (name_array[index], b64data.decode("utf-8")) ) - set_lib = SettingsXMLLib() - set_lib.create_settings_xml( + self.create_settings_xml( filename=temp_file, version=1, lsv=1, settingslist=settings ) diff --git a/SetupDataPkg/Tools/GenNCCfgData.py b/SetupDataPkg/Tools/GenNCCfgData.py index f6ebfb5b..8f220a9f 100644 --- a/SetupDataPkg/Tools/GenNCCfgData.py +++ b/SetupDataPkg/Tools/GenNCCfgData.py @@ -11,7 +11,8 @@ from collections import OrderedDict import base64 -from SettingSupport.DFCI_SupportLib import DFCI_SupportLib # noqa: E402 +import xml.etree.ElementTree as ET + from CommonUtility import bytes_to_value from VariableList import ( Schema, @@ -228,6 +229,43 @@ def get_var_list_for_instance(self, var_list): break return actual_var_list + def iterate_each_setting(self, resultfile, handler): + xmlstring = "" + found = False + a = open(resultfile, "r") + + # find the start of the xml string and then copy all lines to xmlstring variable + for line in a.readlines(): + if found: + xmlstring += line + else: + if line.lstrip().startswith(" Version") - - if ( - (self.MfgOffset >= self.ProductOffset) - or (self.ProductOffset >= self.SerialOffset) - or (self.SerialOffset >= self.TrustedCertOffset) - ): - raise Exception("Invalid Offset Structure") - - Temp = fs.tell() - if Temp != self.MfgOffset: - raise Exception("Invalid Mfg Offset") - self.Manufacturer = fs.read( - self.ProductOffset - self.MfgOffset - 1 - ).decode() - Temp = struct.unpack("=B", fs.read(1))[0] - if Temp != 0: - raise Exception("Invalid NULL in Mfg") - - Temp = fs.tell() - if Temp != self.ProductOffset: - raise Exception("Invalid Product Offset") - self.ProductName = fs.read( - self.SerialOffset - self.ProductOffset - 1 - ).decode() - Temp = struct.unpack("=B", fs.read(1))[0] - if Temp != 0: - raise Exception("Invalid NULL in ProductName") - - Temp = fs.tell() - if Temp != self.SerialOffset: - raise Exception("Invalid SerialOffset Offset") - self.SerialNumber = fs.read( - self.TrustedCertOffset - self.SerialOffset - 1 - ).decode() - Temp = struct.unpack("=B", fs.read(1))[0] - if Temp != 0: - raise Exception("Invalid NULL in SerialNumber") - - if self.TrustedCertSize != 0: - Temp = fs.tell() - if Temp != self.TrustedCertOffset: - raise Exception("Invalid TrustedCertOffset Offset") - else: - raise Exception("Invalid header version") - - if (end - fs.tell()) < self.TrustedCertSize: - raise Exception("Invalid file stream size (Trusted Cert Size)") - - if self.TrustedCertSize > 0: - self.TrustedCert = memoryview(fs.read(self.TrustedCertSize)) - - if (end - fs.tell()) > 0: - if self.TrustedCertSize > 0: - self.TestSignature = WinCert.Factory(fs) - - if (end - fs.tell()) > 0: - self.Signature = WinCert.Factory(fs) - - # - # Method to Print CertProvisioningApplyVariable to stdout - # - def Print(self): - print("CertProvisioningVariable") - print(" HeaderSignature: %s" % self.HeaderSignature) - print(" HeaderVersion: 0x%X" % self.HeaderVersion) - print( - " Identity: 0x%X (%s)" - % (self.Identity, self.IDENTITY_MAP[self.Identity]) - ) - print(" SessionId: 0x%X" % self.SessionId) - if self.HeaderVersion == self.VERSION_V1: - print(" SN Target: %d" % self.SNTarget) - elif self.HeaderVersion == self.VERSION_V2: - print(" Version: %s" % self.Version) - print(" Lsv: %s" % self.Lsv) - print(" Manufacturer: %s" % self.Manufacturer) - print(" Product Name: %s" % self.ProductName) - print(" SerialNumber: %s" % self.SerialNumber) - else: - raise Exception("Invalid header version") - - print(" TrustedCertSize: 0x%X" % self.TrustedCertSize) - print(" TrustedCert: ") - if self.TrustedCert is not None: - ndbl = self.TrustedCert.tolist() - PrintByteList(ndbl) - - if (self.TrustedCertSize > 0) and (self.TestSignature is not None): - print(" TestSignature: ") - self.TestSignature.Print() - - if self.Signature is not None: - print(" Signature: ") - self.Signature.Print() - - def Write(self, fs): - fs.write(self.HeaderSignature.encode("utf-8")) - fs.write(struct.pack("=B", self.HeaderVersion)) - fs.write(struct.pack("=B", self.Identity)) - if self.HeaderVersion == self.VERSION_V1: - fs.write(struct.pack("=Q", self.SNTarget)) - fs.write(struct.pack("=I", self.SessionId)) - fs.write(struct.pack("=H", self.TrustedCertSize)) - elif self.HeaderVersion == self.VERSION_V2: - fs.write(struct.pack("=B", 0)) - fs.write(struct.pack("=B", 0)) - fs.write(struct.pack("=I", self.SessionId)) - fs.write(struct.pack("=H", self.MfgOffset)) - self.ProductOffset = self.MfgOffset + len(self.Manufacturer) + 1 - self.SerialOffset = self.ProductOffset + len(self.ProductName) + 1 - self.TrustedCertOffset = self.SerialOffset + len(self.SerialNumber) + 1 - fs.write(struct.pack("=H", self.ProductOffset)) - fs.write(struct.pack("=H", self.SerialOffset)) - fs.write(struct.pack("=H", self.TrustedCertSize)) - fs.write(struct.pack("=H", self.TrustedCertOffset)) - fs.write(struct.pack("=H", 0)) # Alignment UINT16 - fs.write(struct.pack("=I", self.Version)) - fs.write(struct.pack("=I", self.Lsv)) - fs.write(self.Manufacturer.encode("utf-8")) - fs.write(struct.pack("=B", 0)) # NULL Terminator - fs.write(self.ProductName.encode("utf-8")) - fs.write(struct.pack("=B", 0)) # NULL Terminator - fs.write(self.SerialNumber.encode("utf-8")) - fs.write(struct.pack("=B", 0)) # NULL Terminator - - else: - raise Exception("Invalid header version") - - if self.TrustedCertSize != 0: - fs.write(self.TrustedCert) - if self.TestSignature is not None: - self.TestSignature.Write(fs) - if self.Signature is not None: - self.Signature.Write(fs) - - def VerifyComplete(self): - if self.TrustedCertSize > 0: - if not self.TestSignature: - return False - if not self.Signature: - return False - - return True - - def GetCertType(self): - return self.IDENTITY_MAP[self.Identity] - - def WriteCert(self, fs): - if self.TrustedCertSize != 0: - fs.write(self.TrustedCert) - - -## -## SEM Cert Provision Result Variable Data -## -class CertProvisioningResultVariable(object): - - STATIC_STRUCT_SIZE = 18 - HEADER_SIG_VALUE = "MSPR" - VERSION = 1 - - def __init__(self, filestream=None): - if filestream is None: - self.HeaderSignature = self.HEADER_SIG_VALUE - self.HeaderVersion = self.VERSION - self.Status = 0 - self.Identity = 0 - self.SessionId = 0 - else: - self.PopulateFromFileStream(filestream) - - # - # Method to un-serialize from a filestream - # - def PopulateFromFileStream(self, fs): - if fs is None: - raise Exception("Invalid File stream") - - # only populate from file stream those parts that are complete in the file stream - offset = fs.tell() - fs.seek(0, 2) - end = fs.tell() - fs.seek(offset) - - # size of the static header data - if (end - offset) < self.STATIC_STRUCT_SIZE: - raise Exception("Invalid file stream size") - - self.HeaderSignature = fs.read(4).decode() - if self.HeaderSignature != self.HEADER_SIG_VALUE: - raise Exception("Incorrect Header Signature") - self.HeaderVersion = struct.unpack("=B", fs.read(1))[0] - if self.HeaderVersion != self.VERSION: - raise Exception("Incorrect Header Version") - self.Identity = struct.unpack("=B", fs.read(1))[0] - self.SessionId = struct.unpack("=I", fs.read(4))[0] - self.Status = struct.unpack("=Q", fs.read(8))[0] - - # - # Method to Print SEM var to stdout - # - def Print(self): - print("CertProvisioningResultVariable") - print(" HeaderSignature: %s" % self.HeaderSignature) - print(" HeaderVersion: 0x%X" % self.HeaderVersion) - print( - " Identity: 0x%X (%s)" - % (self.Identity, CertProvisioningApplyVariable.IDENTITY_MAP[self.Identity]) - ) - print(" SessionId: 0x%X" % self.SessionId) - print( - " Status: %s (0x%X)" - % (UefiStatusCode().Convert64BitToString(self.Status), self.Status) - ) - - def Write(self, fs): - fs.write(self.HeaderSignature.encode("utf-8")) - fs.write(struct.pack("=B", self.HeaderVersion)) - fs.write(struct.pack("=B", self.Identity)) - fs.write(struct.pack("=I", self.SessionId)) - fs.write(struct.pack("=Q", self.Status)) diff --git a/SetupDataPkg/Tools/SettingSupport/Data/PermissionPacketVariable.py b/SetupDataPkg/Tools/SettingSupport/Data/PermissionPacketVariable.py deleted file mode 100644 index 3fdd99f0..00000000 --- a/SetupDataPkg/Tools/SettingSupport/Data/PermissionPacketVariable.py +++ /dev/null @@ -1,356 +0,0 @@ -# @file -# -# Script to support the binary format of a Permission variable -# -# Copyright (c), Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent - -## -## Data Structure support for Permission Packet Provisioning Variable -## -## - -import struct -import xml.dom.minidom -from edk2toollib.uefi.wincert import WinCert -from edk2toollib.uefi.status_codes import UefiStatusCode -from edk2toollib.utility_functions import PrintByteList - - -## -## SEM Permission Apply Variable Data -## -class PermissionApplyVariable(object): - STATIC_STRUCT_SIZE_V1 = 22 - STATIC_STRUCT_SIZE_V2 = 22 - HEADER_SIG_VALUE = "MPPA" - VERSION_V1 = 1 - VERSION_V2 = 2 - - def __init__(self, filestream=None, HdrVersion=1): - if HdrVersion != self.VERSION_V1 and HdrVersion != self.VERSION_V2: - raise Exception("Invalid version specified") - - # Common members - self.HeaderSignature = None - self.HeaderVersion = 0 - self.Payload = None - # private XML structure - self._XmlTree = None - self.Signature = None - self.SessionId = 0 - self.PayloadSize = 0 - self.Rsvd1 = 0 - self.Rsvd2 = 0 - self.Rsvd3 = 0 - - # V1 unique members - self.SNTarget = 0 - - # V2 unique members - self.Manufacturer = None - self.ProductName = None - self.SerialNumber = None - self.MfgOffset = self.STATIC_STRUCT_SIZE_V2 - self.ProductOffset = 0 - self.SerialOffset = 0 - self.PayloadOffset = 0 - - if filestream is None: - self.HeaderSignature = self.HEADER_SIG_VALUE - self.HeaderVersion = HdrVersion - else: - self.PopulateFromFileStream(filestream) - - # - # Method to un-serialize from a filestream - # - def PopulateFromFileStream(self, fs): - if fs is None: - raise Exception("Invalid File stream") - - # only populate from file stream those parts that are complete in the file stream - offset = fs.tell() - fs.seek(0, 2) - end = fs.tell() - fs.seek(offset) - - # minimum size of the static header data - if (end - offset) < self.STATIC_STRUCT_SIZE_V1: - raise Exception("Invalid file stream size") - - self.HeaderSignature = fs.read(4).decode() - if self.HeaderSignature != self.HEADER_SIG_VALUE: - print(" HeaderSignature: %s" % self.HeaderSignature) - raise Exception("Incorrect Header Signature") - self.HeaderVersion = struct.unpack("=B", fs.read(1))[0] - self.Rsvd1 = struct.unpack("=B", fs.read(1))[0] - self.Rsvd2 = struct.unpack("=B", fs.read(1))[0] - self.Rsvd3 = struct.unpack("=B", fs.read(1))[0] - if (self.Rsvd1 != 0) or (self.Rsvd2 != 0) or (self.Rsvd3 != 0): - raise Exception("Reserved bytes must be zero") - - self.Payload = None - - if self.HeaderVersion == self.VERSION_V1: - self.SNTarget = struct.unpack("=Q", fs.read(8))[0] - self.SessionId = struct.unpack("=I", fs.read(4))[0] - self.PayloadSize = struct.unpack("=H", fs.read(2))[0] - - elif self.HeaderVersion == self.VERSION_V2: - # minimum size of the static header data - if (end - offset) < self.STATIC_STRUCT_SIZE_V2: - raise Exception("Invalid V2 file stream size") - self.SessionId = struct.unpack("=I", fs.read(4))[0] - self.MfgOffset = struct.unpack("=H", fs.read(2))[0] - self.ProductOffset = struct.unpack("=H", fs.read(2))[0] - self.SerialOffset = struct.unpack("=H", fs.read(2))[0] - self.PayloadSize = struct.unpack("=H", fs.read(2))[0] - self.PayloadOffset = struct.unpack("=H", fs.read(2))[0] - - if ( - (self.MfgOffset >= self.ProductOffset) - or (self.ProductOffset >= self.SerialOffset) - or (self.SerialOffset >= self.PayloadOffset) - ): - raise Exception("Invalid Offset Structure") - - if end - fs.tell() < self.PayloadOffset: - raise Exception("Packet too small for SmBiosString") - - Temp = fs.tell() - if Temp != self.MfgOffset: - raise Exception("Invalid Mfg Offset") - self.Manufacturer = fs.read( - self.ProductOffset - self.MfgOffset - 1 - ).decode() - Temp = struct.unpack("=B", fs.read(1))[0] - if Temp != 0: - raise Exception("Invalid NULL in Mfg") - - Temp = fs.tell() - if Temp != self.ProductOffset: - raise Exception("Invalid Product Offset") - self.ProductName = fs.read( - self.SerialOffset - self.ProductOffset - 1 - ).decode() - Temp = struct.unpack("=B", fs.read(1))[0] - if Temp != 0: - raise Exception("Invalid NULL in ProductName") - - Temp = fs.tell() - if Temp != self.SerialOffset: - raise Exception("Invalid SerialOffset Offset") - self.SerialNumber = fs.read( - self.PayloadOffset - self.SerialOffset - 1 - ).decode() - Temp = struct.unpack("=B", fs.read(1))[0] - if Temp != 0: - raise Exception("Invalid NULL in ProductName") - else: - raise Exception("Invalid header version") - - if (end - fs.tell()) < self.PayloadSize: - raise Exception("Invalid file stream size (PayloadSize)") - - self.Payload = fs.read(self.PayloadSize).decode() - self._XmlTree = xml.dom.minidom.parseString(self.Payload) - - if (end - fs.tell()) > 0: - self.Signature = WinCert.Factory(fs) - - def AddXmlPayload(self, xmlstring): - if self.Payload: - raise Exception( - "Can't Add an XML payload to an object already containing payload" - ) - - self.Payload = xmlstring - self._XmlTree = xml.dom.minidom.parseString(self.Payload) - self.PayloadSize = len(xmlstring) - - # - # Method to Print PermissionApplyVariable to stdout - # - def Print(self, ShowRawXmlAsBytes=False): - print("PermissionApplyVariable") - print(" HeaderSignature: %s" % self.HeaderSignature) - print(" HeaderVersion: 0x%X" % self.HeaderVersion) - print(" SessionId: 0x%X" % self.SessionId) - print(" PayloadSize: 0x%X" % self.PayloadSize) - if self.HeaderVersion == self.VERSION_V1: - print(" SN Target: %d" % self.SNTarget) - elif self.HeaderVersion == self.VERSION_V2: - print(" Manufacturer: %s" % self.Manufacturer) - print(" Product Name: %s" % self.ProductName) - print(" SerialNumber: %s" % self.SerialNumber) - else: - raise Exception("Invalid header version") - - if self._XmlTree is not None: - print("%s" % self._XmlTree.toprettyxml()) - else: - print("XML TREE DOESN'T EXIST") - - if ShowRawXmlAsBytes and (self.Payload is not None): - print(" Payload Bytes: ") - ndbl = list(bytearray(self.Payload.encode())) - print(type(ndbl)) - PrintByteList(ndbl) - - if self.Signature is not None: - self.Signature.Print() - - def Write(self, fs): - fs.write(self.HeaderSignature.encode("utf-8")) - fs.write(struct.pack("=B", self.HeaderVersion)) - fs.write(struct.pack("=B", self.Rsvd1)) - fs.write(struct.pack("=B", self.Rsvd2)) - fs.write(struct.pack("=B", self.Rsvd3)) - - if self.HeaderVersion == self.VERSION_V1: - fs.write(struct.pack("=Q", self.SNTarget)) - fs.write(struct.pack("=I", self.SessionId)) - fs.write(struct.pack("=H", self.PayloadSize)) - elif self.HeaderVersion == self.VERSION_V2: - fs.write(struct.pack("=I", self.SessionId)) - fs.write(struct.pack("=H", self.MfgOffset)) - self.ProductOffset = self.MfgOffset + len(self.Manufacturer) + 1 - self.SerialOffset = self.ProductOffset + len(self.ProductName) + 1 - self.PayloadOffset = self.SerialOffset + len(self.SerialNumber) + 1 - fs.write(struct.pack("=H", self.ProductOffset)) - fs.write(struct.pack("=H", self.SerialOffset)) - fs.write(struct.pack("=H", self.PayloadSize)) - fs.write(struct.pack("=H", self.PayloadOffset)) - fs.write(self.Manufacturer.encode("utf-8")) - fs.write(struct.pack("=B", 0)) # NULL Terminator - fs.write(self.ProductName.encode("utf-8")) - fs.write(struct.pack("=B", 0)) # NULL Terminator - fs.write(self.SerialNumber.encode("utf-8")) - fs.write(struct.pack("=B", 0)) # NULL Terminator - else: - raise Exception("Invalid header version") - - fs.write(self.Payload.encode("utf-8")) - if self.Signature is not None: - self.Signature.Write(fs) - - -## -## SEM Permission Result Variable Data -## -class PermissionResultVariable(object): - STATIC_STRUCT_SIZE = 20 - STATIC_STRUCT_SIZE_V2 = 22 - HEADER_SIG_VALUE = "MPPR" - VERSION_V1 = 1 - VERSION_V2 = 2 - - def __init__(self, filestream=None, HdrVersion=1): - if ( - HdrVersion != PermissionResultVariable.VERSION_V1 - and HdrVersion != PermissionResultVariable.VERSION_V2 - ): - raise Exception("Invalid version specified") - - self.Payload = None - self.PayloadSize = 0 - # private xml structure - self._XmlTree = None - - if filestream is None: - self.HeaderSignature = PermissionResultVariable.HEADER_SIG_VALUE - self.HeaderVersion = HdrVersion - self.Status = 0 - self.SessionId = 0 - else: - self.PopulateFromFileStream(filestream) - - # - # Method to un-serialize from a filestream - # - def PopulateFromFileStream(self, fs): - if fs is None: - raise Exception("Invalid File stream") - - # only populate from file stream those parts that are complete in the file stream - offset = fs.tell() - fs.seek(0, 2) - end = fs.tell() - fs.seek(offset) - - # size of the static header data - if (end - offset) < PermissionResultVariable.STATIC_STRUCT_SIZE: - raise Exception("Invalid file stream size") - - self.HeaderSignature = fs.read(4).decode() - if self.HeaderSignature != PermissionResultVariable.HEADER_SIG_VALUE: - print(" HeaderSignature: %s" % self.HeaderSignature) - raise Exception("Incorrect Header Signature") - self.HeaderVersion = struct.unpack("=B", fs.read(1))[0] - if ( - self.HeaderVersion != PermissionResultVariable.VERSION_V1 - and self.HeaderVersion != PermissionResultVariable.VERSION_V2 - ): - raise Exception("Incorrect Header Version") - # skip three bytes ahead to avoid the rsvd bytes - fs.seek(3, 1) - self.Status = struct.unpack("=Q", fs.read(8))[0] - self.SessionId = struct.unpack("=I", fs.read(4))[0] - if self.HeaderVersion == PermissionResultVariable.VERSION_V2: - # size of the static header data - if (end - offset) < PermissionResultVariable.STATIC_STRUCT_SIZE_V2: - raise Exception("Invalid file stream size") - self.PayloadSize = struct.unpack("=H", fs.read(2))[0] - self.Payload = None - self._XmlTree = None - - if (end - fs.tell()) < self.PayloadSize: - raise Exception( - "Invalid file stream size (Payload). %d" % self.PayloadSize - ) - - # is it possible to have 0 sized - if self.PayloadSize > 0: - self.Payload = fs.read(self.PayloadSize) - self.Payload = self.Payload.decode("utf-8") - # remove ending NULL if there. this only happens in some cases - self.Payload = self.Payload.rstrip("\x00") - self._XmlTree = xml.dom.minidom.parseString(self.Payload) - - # - # Method to Print SEM var to stdout - # - def Print(self, ShowRawXmlAsBytes=False): - print("PermissionResultVariable") - print(" HeaderSignature: %s" % self.HeaderSignature) - print(" HeaderVersion: 0x%X" % self.HeaderVersion) - print( - " Status: %s (0x%X)" - % (UefiStatusCode().Convert64BitToString(self.Status), self.Status) - ) - print(" SessionId: 0x%X" % self.SessionId) - - if self.HeaderVersion == PermissionResultVariable.VERSION_V2: - print(" Payload Size: 0x%X" % self.PayloadSize) - if self._XmlTree is not None: - print("%s" % self._XmlTree.toprettyxml()) - else: - print("XML TREE DOESN'T EXIST") - - if ShowRawXmlAsBytes and (self.Payload is not None): - print(" Payload Bytes: ") - ndbl = memoryview(self.Payload).tolist() - PrintByteList(ndbl) - - def Write(self, fs): - raise Exception("Unsupported/Unnecessary function") - - """fs.write(self.HeaderSignature.encode('utf-8') - fs.write(struct.pack("=B", self.HeaderVersion)) - fs.write(struct.pack("=B", self.Identity)) - fs.write(struct.pack("=H", self.NewDataSize)) - fs.write(self.NewDataBuffer) - if(self.Signature != None): - self.Signature.Write(fs) - """ diff --git a/SetupDataPkg/Tools/SettingSupport/Data/SecureSettingVariable.py b/SetupDataPkg/Tools/SettingSupport/Data/SecureSettingVariable.py deleted file mode 100644 index e68a03cc..00000000 --- a/SetupDataPkg/Tools/SettingSupport/Data/SecureSettingVariable.py +++ /dev/null @@ -1,391 +0,0 @@ -# @file -# -# Script to support the binary form of the setting variable -# -# Copyright (c), Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent - -## -## Data Structure support for SEM Setting Apply/Result Variable -## -## - -import struct -import xml.dom.minidom -from edk2toollib.uefi.wincert import WinCert -from edk2toollib.uefi.status_codes import UefiStatusCode -from edk2toollib.utility_functions import PrintByteList - - -## -## SEM Secure Settings Apply Variable Data -## -class SecureSettingsApplyVariable(object): - - STATIC_STRUCT_SIZE_V1 = 22 - STATIC_STRUCT_SIZE_V2 = 22 - HEADER_SIG_VALUE = "MSSA" - VERSION_V1 = 1 - VERSION_V2 = 2 - - def __init__(self, filestream=None, HdrVersion=1): - if HdrVersion != self.VERSION_V1 and HdrVersion != self.VERSION_V2: - raise Exception("Invalid version specified") - - print("Processing Version %s" % HdrVersion) - # Common members - self.HeaderSignature = None - self.HeaderVersion = 0 - self.Rsvd1 = 0 - self.Rsvd2 = 0 - self.Rsvd3 = 0 - self.SessionId = 0 - self.PayloadSize = 0 - self.Payload = None - # private XML structure - self._XmlTree = None - self.Signature = None - - # V1 unique members - self.SNTarget = 0 - - # V2 unique members - self.Manufacturer = None - self.ProductName = None - self.SerialNumber = None - self.MfgOffset = self.STATIC_STRUCT_SIZE_V2 - self.ProductOffset = 0 - self.SerialOffset = 0 - self.PayloadOffset = 0 - - if filestream is None: - self.HeaderSignature = self.HEADER_SIG_VALUE - self.HeaderVersion = HdrVersion - else: - self.PopulateFromFileStream(filestream) - - # - # Method to un-serialize from a filestream - # - def PopulateFromFileStream(self, fs): - if fs is None: - raise Exception("Invalid File stream") - - # only populate from file stream those parts that are complete in the file stream - offset = fs.tell() - fs.seek(0, 2) - end = fs.tell() - fs.seek(offset) - - # minimum size of the static header data - if (end - offset) < self.STATIC_STRUCT_SIZE_V1: - raise Exception("Invalid file stream size") - - self.HeaderSignature = fs.read(4).decode() - if self.HeaderSignature != self.HEADER_SIG_VALUE: - raise Exception("Incorrect Header Signature") - self.HeaderVersion = struct.unpack("=B", fs.read(1))[0] - self.rsvd1 = struct.unpack("=B", fs.read(1))[0] - self.rsvd2 = struct.unpack("=B", fs.read(1))[0] - self.rsvd3 = struct.unpack("=B", fs.read(1))[0] - - if self.HeaderVersion == self.VERSION_V1: - self.SNTarget = struct.unpack("=Q", fs.read(8))[0] - self.SessionId = struct.unpack("=I", fs.read(4))[0] - self.PayloadSize = struct.unpack("=H", fs.read(2))[0] - - elif self.HeaderVersion == self.VERSION_V2: - # minimum size for v2 data - if (end - offset) < self.STATIC_STRUCT_SIZE_V2: - raise Exception("Invalid V2 file stream size") - self.SessionId = struct.unpack("=I", fs.read(4))[0] - self.MfgOffset = struct.unpack("=H", fs.read(2))[0] - self.ProductOffset = struct.unpack("=H", fs.read(2))[0] - self.SerialOffset = struct.unpack("=H", fs.read(2))[0] - self.PayloadSize = struct.unpack("=H", fs.read(2))[0] - self.PayloadOffset = struct.unpack("=H", fs.read(2))[0] - - if end - fs.tell() < self.PayloadOffset: - raise Exception("Packet too small for SmBiosString") - - if ( - (self.MfgOffset >= self.ProductOffset) - or (self.ProductOffset >= self.SerialOffset) - or (self.SerialOffset >= self.PayloadOffset) - ): - raise Exception("Invalid Offset Structure") - - Temp = fs.tell() - if Temp != self.MfgOffset: - raise Exception("Invalid Mfg Offset") - self.Manufacturer = fs.read( - self.ProductOffset - self.MfgOffset - 1 - ).decode() - Temp = struct.unpack("=B", fs.read(1))[0] - if Temp != 0: - raise Exception("Invalid NULL in Mfg") - - Temp = fs.tell() - if Temp != self.ProductOffset: - raise Exception("Invalid Product Offset") - self.ProductName = fs.read( - self.SerialOffset - self.ProductOffset - 1 - ).decode() - Temp = struct.unpack("=B", fs.read(1))[0] - if Temp != 0: - raise Exception("Invalid NULL in ProductName") - - Temp = fs.tell() - if Temp != self.SerialOffset: - raise Exception("Invalid SerialOffset Offset") - self.SerialNumber = fs.read( - self.PayloadOffset - self.SerialOffset - 1 - ).decode() - Temp = struct.unpack("=B", fs.read(1))[0] - if Temp != 0: - raise Exception("Invalid NULL in SerialNumber") - else: - raise Exception("Invalid header version") - - self.Payload = None - self._PayloadXml = None - self.Signature = None - - if (end - fs.tell()) < self.PayloadSize: - raise Exception("Invalid file stream size (payload size incorrect)") - - self.Payload = fs.read(self.PayloadSize).decode("utf-8") - prep = self.Payload - prep = prep.rstrip("\x00") - self._PayloadXml = xml.dom.minidom.parseString(prep) - - if (end - fs.tell()) > 0: - self.Signature = WinCert.Factory(fs) - - def AddXmlPayload(self, xmlstring): - if self.Payload: - raise Exception( - "Can't Add an XML payload to an object already containing payload" - ) - # get rid of extra whitespace and new line chars. This changes newline to blank which i don't like but better - # than before. If replace with '' then xml attributes are messed up - xml_clean = " ".join(xmlstring.split()) - self.Payload = xml_clean - self._PayloadXml = xml.dom.minidom.parseString(xml_clean) - self.PayloadSize = len(xml_clean) - - # - # Method to Print SecureSettingsApplyVariable to stdout - # - def Print(self, ShowRawXmlAsBytes=False): - print("SecureSettingsApplyVariable") - print(" HeaderSignature: %s" % self.HeaderSignature) - print(" HeaderVersion: 0x%X" % self.HeaderVersion) - print(" SessionId: 0x%X" % self.SessionId) - print(" Payload Size: 0x%X" % self.PayloadSize) - if self.HeaderVersion == self.VERSION_V1: - print(" SN Target: %d" % self.SNTarget) - elif self.HeaderVersion == self.VERSION_V2: - print(" Manufacturer: %s" % self.Manufacturer) - print(" Product Name: %s" % self.ProductName) - print(" SerialNumber: %s" % self.SerialNumber) - else: - raise Exception("Invalid header version") - - if self._PayloadXml is not None: - print("%s" % self._PayloadXml.toprettyxml()) - else: - print("XML TREE DOESN'T EXIST") - - if ShowRawXmlAsBytes and (self.Payload is not None): - print(" Payload Bytes: ") - ndbl = list(bytearray(self.Payload.encode())) - print(type(ndbl)) - PrintByteList(ndbl) - - if self.Signature is not None: - self.Signature.Print() - - def Write(self, fs): - fs.write(self.HeaderSignature.encode("utf-8")) - fs.write(struct.pack("=B", self.HeaderVersion)) - fs.write(struct.pack("=B", self.Rsvd1)) - fs.write(struct.pack("=B", self.Rsvd2)) - fs.write(struct.pack("=B", self.Rsvd3)) - - if self.HeaderVersion == self.VERSION_V1: - fs.write(struct.pack("=Q", self.SNTarget)) - fs.write(struct.pack("=I", self.SessionId)) - fs.write(struct.pack("=H", self.PayloadSize)) - elif self.HeaderVersion == self.VERSION_V2: - fs.write(struct.pack("=I", self.SessionId)) - fs.write(struct.pack("=H", self.MfgOffset)) - self.ProductOffset = self.MfgOffset + len(self.Manufacturer) + 1 - self.SerialOffset = self.ProductOffset + len(self.ProductName) + 1 - self.PayloadOffset = self.SerialOffset + len(self.SerialNumber) + 1 - fs.write(struct.pack("=H", self.ProductOffset)) - fs.write(struct.pack("=H", self.SerialOffset)) - fs.write(struct.pack("=H", self.PayloadSize)) - fs.write(struct.pack("=H", self.PayloadOffset)) - fs.write(self.Manufacturer.encode("utf-8")) - fs.write(struct.pack("=B", 0)) # NULL Terminator - fs.write(self.ProductName.encode("utf-8")) - fs.write(struct.pack("=B", 0)) # NULL Terminator - fs.write(self.SerialNumber.encode("utf-8")) - fs.write(struct.pack("=B", 0)) # NULL Terminator - else: - raise Exception("Invalid header version") - - fs.write(self.Payload.encode("utf-8")) - if self.Signature is not None: - self.Signature.Write(fs) - - -## -## SEM Secure Settings Result Variable Data -## -class SecureSettingsResultVariable(object): - - STATIC_STRUCT_SIZE = 22 - HEADER_SIG_VALUE = "MSSR" - VERSION = 1 - - def __init__(self, filestream=None): - if filestream is None: - self.HeaderSignature = SecureSettingsResultVariable.HEADER_SIG_VALUE - self.HeaderVersion = SecureSettingsResultVariable.VERSION - self.Status = 0 - self.SessionId = 0 - self.PayloadSize = 0 - self.Payload = None - # private xml structure - self._XmlTree = None - else: - self._XmlTree = None - self.PopulateFromFileStream(filestream) - - # - # Method to un-serialize from a filestream - # - def PopulateFromFileStream(self, fs): - if fs is None: - raise Exception("Invalid File stream") - - # only populate from file stream those parts that are complete in the file stream - offset = fs.tell() - fs.seek(0, 2) - end = fs.tell() - fs.seek(offset) - - # size of the static header data - if (end - offset) < SecureSettingsResultVariable.STATIC_STRUCT_SIZE: - raise Exception("Invalid file stream size") - - self.HeaderSignature = str(fs.read(4)) - self.HeaderVersion = struct.unpack("=B", fs.read(1))[0] - # skip three bytes ahead to avoid the rsvd bytes - fs.seek(3, 1) - self.Status = struct.unpack("=Q", fs.read(8))[0] - self.SessionId = struct.unpack("=I", fs.read(4))[0] - self.PayloadSize = struct.unpack("=H", fs.read(2))[0] - self.Payload = None - self._XmlTree = None - - if (end - fs.tell()) < self.PayloadSize: - raise Exception( - "Invalid file stream size (Payload). %d" % self.PayloadSize - ) - - # is it possible to have 0 sized - if self.PayloadSize > 0: - self.Payload = fs.read(self.PayloadSize) - self.Payload = self.Payload.decode("utf-8") - # remove ending NULL if there. this only happens in some cases - self.Payload = self.Payload.rstrip("\x00") - self._XmlTree = xml.dom.minidom.parseString(self.Payload) - - # - # Method to Print SEM var results to stdout - # - def Print(self, ShowRawXmlAsBytes=False): - print("SecureSettingResultVariable") - print(" HeaderSignature: %s" % self.HeaderSignature) - print(" HeaderVersion: 0x%X" % self.HeaderVersion) - print(" SessionId: 0x%X" % (self.SessionId)) - print( - " Status: %s (0x%X)" - % (UefiStatusCode().Convert64BitToString(self.Status), self.Status) - ) - print(" Payload Size: 0x%X" % self.PayloadSize) - if self._XmlTree is not None: - print("%s" % self._XmlTree.toprettyxml()) - else: - print("XML TREE DOESN'T EXIST") - - if ShowRawXmlAsBytes and (self.Payload is not None): - print(" Payload Bytes: ") - ndbl = list(bytearray(self.Payload.encode())) - print(type(ndbl)) - PrintByteList(ndbl) - - def Write(self, fs): - raise Exception("Unsupported/Unnecessary function") - - """fs.write(self.HeaderSignature.encode('utf-8')) - fs.write(struct.pack("=B", self.HeaderVersion)) - fs.write(struct.pack("=B", self.Identity)) - fs.write(struct.pack("=H", self.NewDataSize)) - fs.write(self.NewDataBuffer) - if(self.Signature != None): - self.Signature.Write(fs) - """ - - -## -## SEM Secure Settings Current Variable Data -## -class SecureSettingsCurrentVariable(object): - - STATIC_STRUCT_SIZE = 0 - - def __init__(self, filestream=None): - self._Payload = None - # private xml structure - self._XmlTree = None - if filestream is not None: - self.PopulateFromFileStream(filestream) - - # - # Method to un-serialize from a filestream - # - def PopulateFromFileStream(self, fs): - if fs is None: - raise Exception("Invalid File stream") - - # only populate from file stream those parts that are complete in the file stream - offset = fs.tell() - fs.seek(0, 2) - end = fs.tell() - fs.seek(offset) - - # no data - if (end - offset) < 1: - raise Exception("Invalid file stream size. No data") - self._Payload = fs.read() - self._Payload = self._Payload.rstrip("\x00") - self._XmlTree = xml.dom.minidom.parseString(self._Payload) - - # - # Method to Print SEM var to stdout - # - def Print(self): - print("Current Settings XML") - if self._XmlTree is not None: - print("%s" % self._XmlTree.toprettyxml()) - else: - print("XML TREE DOESN'T EXIST") - - def Write(self, fs): - if self._Payload is None: - raise Exception("No payload to write") - fs.write(self._Payload) diff --git a/SetupDataPkg/Tools/SettingSupport/DependencyLib.py b/SetupDataPkg/Tools/SettingSupport/DependencyLib.py deleted file mode 100644 index 36b5a3ab..00000000 --- a/SetupDataPkg/Tools/SettingSupport/DependencyLib.py +++ /dev/null @@ -1,32 +0,0 @@ -# @file -# -# Dependency Lib - Limited functionality to for a robot testcase to depend on a successful -# completion of a previous testcase. -# -# Copyright (c), Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -from robot.libraries.BuiltIn import BuiltIn - - -class DependencyLib(object): - ROBOT_LISTENER_API_VERSION = 2 - ROBOT_LIBRARY_SCOPE = "GLOBAL" - - def __init__(self): - self.ROBOT_LIBRARY_LISTENER = self - self.test_status = {} - - def require_test_case(self, name): - key = name.lower() - if (key not in self.test_status): - BuiltIn().fail("required test case can't be found: '%s'" % name) - - if (self.test_status[key] != "PASS"): - BuiltIn().fail("required test case failed: '%s'" % name) - - return True - - def _end_test(self, name, attrs): - self.test_status[name.lower()] = attrs["status"] diff --git a/SetupDataPkg/Tools/SettingSupport/GenerateCertProvisionData.py b/SetupDataPkg/Tools/SettingSupport/GenerateCertProvisionData.py deleted file mode 100644 index f43ff7f0..00000000 --- a/SetupDataPkg/Tools/SettingSupport/GenerateCertProvisionData.py +++ /dev/null @@ -1,757 +0,0 @@ -# @file -# -# Script to Generate a Device Firmware Configuration Interface Provision Blob -# -# Copyright (c), Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -## -## Script to Generate a Device Firmware Configuration Interface Provision Blob -## This tool takes in a CER file in binary encoding, packages it in a -## DFCI_SIGNER_PROVISION_APPLY_VAR structure, signs it with the -## requested key, and then attaches the signature data in WIN_CERTIFICATE_UEFI_GUID format. -## -## This binary file can then be written to variable store: -## GUID: gDfciAuthProvisionVarNamespace -## NAME: DFCI_IDENTITY_APPLY_VAR_NAME L"DfciIdentityApply" -## -## THIS IS FOR UNIT TEST -## -## General process: -## Phase 1: Create payload file by combining relevant info -## Phase 2: Sign it using signtool -## Phase 3: Parse signature into WIN_CERT and package to create final output -## - -import os -import sys -import argparse -import logging -import datetime -import shutil -import time -import random -import hashlib - -# get script path -sp = os.path.dirname(os.path.realpath(sys.argv[0])) - -# setup python path for build modules -sys.path.append(sp) - -from DFCI_SupportLib import DFCI_SupportLib # noqa: E402 -from Data.CertProvisioningVariable import CertProvisioningApplyVariable # noqa: E402 -from Data.CertProvisioningVariable import CertProvisioningResultVariable # noqa: E402 -from edk2toollib.uefi.wincert import WinCertUefiGuid # noqa: E402 -from edk2toollib.utility_functions import DetachedSignWithSignTool # noqa: E402 - -# PKCS7 Signed Data OID -gOid = "1.2.840.113549.1.7.2" -gPath2SignTool = None - - -def PrintSEM(filepath): - if filepath and os.path.isfile(filepath): - s = open(filepath, "rb") - SEM = CertProvisioningApplyVariable(s) - s.close() - - # now print it out. - SEM.Print() - - -def ExtractCert(filepath): - if filepath and os.path.isfile(filepath): - s = open(filepath, "rb") - SEM = CertProvisioningApplyVariable(s) - s.close() - - # now write the certificate out. - (certtype, a, b) = SEM.GetCertType().partition(" ") - - cert_filename = os.path.basename(filepath) + "_" + certtype + ".cer" - s = open(cert_filename, "wb") - SEM.WriteCert(s) - s.close() - s = open(cert_filename, "rb") - m = hashlib.new("sha1", s.read()) - s.close() - - # return the sha1 (Thumbprint) of the certificate. - return m.digest().hex() - - -def PrintSEMCurrent(filepath): - if filepath and os.path.isfile(filepath): - out_file_name = os.path.basename(filepath) + "_Current" + ".xml" - a = DFCI_SupportLib() - a.extract_payload_from_current(filepath, out_file_name) - - -def PrintSEMResults(filepath): - if filepath and os.path.isfile(filepath): - s = open(filepath, "rb") - SEM = CertProvisioningResultVariable(s) - s.close() - - # now print it out. - SEM.Print() - - -def SignSEMProvisionData(options): - global gPath2SignTool - if gPath2SignTool is None: - a = DFCI_SupportLib() - gPath2SignTool = a.get_signtool_path() - - logging.critical("Signing Started") - logging.critical(options.SigningInputFile) - logging.critical(options.SigningOutputFile) - logging.critical(options.SigningPfxFile) - - return DetachedSignWithSignTool( - gPath2SignTool, - options.SigningInputFile, - options.SigningOutputFile, - options.SigningPfxFile, - options.SigningPfxPw, - gOid, - ) - - -def TestSignSemTrustedCert(options): - global gPath2SignTool - if gPath2SignTool is None: - a = DFCI_SupportLib() - gPath2SignTool = a.get_signtool_path() - - logging.critical("Signing Started") - logging.critical(gPath2SignTool) - logging.critical(options.CertFilePath) - logging.critical(options.Signing2AOutputFile) - logging.critical(options.Signing2APfxFile) - - return DetachedSignWithSignTool( - gPath2SignTool, - options.CertFilePath, - options.Signing2AOutputFile, - options.Signing2APfxFile, - options.Signing2APfxPw, - gOid, - ) - - -def is_32bit_number(s): - try: - float(s) - if s < 4294967296: - return True - else: - return False - except ValueError: - return False - - -# -# main script function -# -def main(): - parser = argparse.ArgumentParser(description="Create SEM Provisioning Cert") - - # Output debug log - parser.add_argument( - "-l", - dest="OutputLog", - help="Create an output log file: ie -l out.txt", - default=None, - ) - parser.add_argument( - "-p", dest="PrintFile", help="Print File as Provisioning Blob", default=None - ) - parser.add_argument( - "-pr", - dest="PrintResultsFile", - help="Print Result File as Identity Blob", - default=None, - ) - parser.add_argument( - "-pc", - dest="PrintCurrentFile", - help="Print Current File as {basename}_Current.xml", - default=None, - ) - parser.add_argument( - "-xc", - dest="ExtractCertFile", - help="Extract the certificate to {basename}_{certtype}.cer", - default=None, - ) - parser.add_argument( - "--dirty", - action="store_true", - dest="dirty", - help="Leave around the temp files after finished", - default=False, - ) - - Step1Group = parser.add_argument_group( - title="Step1", description="Signed Data Prep. Build data structure." - ) - Step1Group.add_argument( - "--Step1Enable", - dest="Step1Enable", - help="Do Step 1 - Signed Data Prep", - default=False, - action="store_true", - ) - Step1Group.add_argument( - "--Identity", - dest="Identity", - help="Identity (Owner=1, User=2, User1=3, User2=4, Ztc=5). Default is Owner", - default=1, - ) - Step1Group.add_argument( - "--SnTarget", - dest="SnTarget", - help="Target to only a device with given Serial Number in decimal. Zero means all devices", - default=0, - ) - Step1Group.add_argument( - "--CertFilePath", - dest="CertFilePath", - help="Path to binary DER Cert", - default=None, - ) - Step1Group.add_argument( - "--PrepResultFile", - dest="PrepResultFile", - help="Optional File for output from Step1. Required if not doing step2 or step2A", - default=None, - ) - Step1Group.add_argument( - "--HdrVersion", - dest="HdrVersion", - help="Specify packet version", - default=CertProvisioningApplyVariable.VERSION_V1, - ) - Step1Group.add_argument( - "--SMBIOSMfg", - dest="SMBIOSMfg", - help="Specify SMBIOS Manufacturer", - default=None, - ) - Step1Group.add_argument( - "--SMBIOSProd", - dest="SMBIOSProd", - help="Specify SMBIOS Product Name", - default=None, - ) - Step1Group.add_argument( - "--SMBIOSSerial", - dest="SMBIOSSerial", - help="Specify SMBIOS Serial Number", - default=None, - ) - Step1Group.add_argument( - "--Version", dest="Version", help="Specify Identity version", default=0 - ) - Step1Group.add_argument( - "--Lsv", dest="Lsv", help="Specify the lowest supported version", default=0 - ) - - Step2AGroup = parser.add_argument_group( - title="Step2A", description="Test Signature Generation Step." - ) - Step2AGroup.add_argument( - "--Step2AEnable", - dest="Step2AEnable", - help="Do Step 2A - Local Signing for Test Signature", - default=False, - action="store_true", - ) - # need to add arguments here for signing. - Step2AGroup.add_argument( - "--Signing2AResultFile", - dest="Signing2AResultFile", - help="Optional File for output from Step2A. Required if not doing step2B", - default=None, - ) - Step2AGroup.add_argument( - "--Signing2APfxFile", - dest="Signing2APfxFile", - help="Path to PFX file for signing Test Signature ", - default=None, - ) - Step2AGroup.add_argument( - "--Signing2APfxPw", - dest="Signing2APfxPw", - help="Optional Password for PFX file for signing Test Signature", - default=None, - ) - - Step2BGroup = parser.add_argument_group( - title="Step2B", description="Package Cert Provision With Test Signature." - ) - Step2BGroup.add_argument( - "--Step2BEnable", - dest="Step2BEnable", - help="Do Step 2B - Package Test Signature with Cert Provision Data", - default=False, - action="store_true", - ) - Step2BGroup.add_argument( - "--TestSignatureInputFile", - dest="TestSignatureInputFile", - help="Detached Signature file for Test Signature", - default=None, - ) - Step2BGroup.add_argument( - "--CertProvisionBlobInputFile", - dest="CertProvisionBlobAfterStep1File", - help="Step1 Output File to use as Input to combine with Test Signature", - default=None, - ) - Step2BGroup.add_argument( - "--Prep2BResultFile", - dest="Prep2BResultFile", - help="Optional File for output from Step2B. Required if not doing step2", - default=None, - ) - - Step2Group = parser.add_argument_group( - title="Step2", description="Signature Generation Step." - ) - Step2Group.add_argument( - "--Step2Enable", - dest="Step2Enable", - help="Do Step 2 - Local Signing", - default=False, - action="store_true", - ) - # need to add arguments here for signing. - Step2Group.add_argument( - "--SigningInputFile", - dest="SigningInputFile", - help="Optional File for intput for Step2. Required if not doing step1", - default=None, - ) - Step2Group.add_argument( - "--SigningResultFile", - dest="SigningResultFile", - help="Optional File for output from Step2. Required if not doing step3", - default=None, - ) - Step2Group.add_argument( - "--SigningPfxFile", - dest="SigningPfxFile", - help="Path to PFX file for signing", - default=None, - ) - Step2Group.add_argument( - "--SigningPfxPw", - dest="SigningPfxPw", - help="Optional Password for PFX file for signing", - default=None, - ) - - Step3Group = parser.add_argument_group( - title="Step3", description="Final Provisioning Var Construction." - ) - Step3Group.add_argument( - "--Step3Enable", - dest="Step3Enable", - help="Do Step 3 - Final Provisioning Var Construction", - default=False, - action="store_true", - ) - Step3Group.add_argument( - "--FinalizeInputFile", - dest="FinalizeInputFile", - help="Optional if doing Step2. Generally Step1 Output or Step2 input. ", - default=None, - ) - Step3Group.add_argument( - "--FinalizeInputDetachedSignatureFile", - dest="FinalizeInputDetachedSignatureFile", - help="Signtool Detached Signature File. Optional if doing Step2", - default=None, - ) - Step3Group.add_argument( - "--FinalizeResultFile", - dest="FinalizeResultFile", - help="File for output from Step3. Complete SEM Provisioning Var File.", - default=None, - ) - - # Turn on debug level logging - parser.add_argument( - "--debug", - action="store_true", - dest="debug", - help="turn on debug logging level for file log", - default=False, - ) - options = parser.parse_args() - - # setup file based logging if outputReport specified - if options.OutputLog: - if len(options.OutputLog) < 2: - logging.critical("the output log file parameter is invalid") - return -2 - else: - # setup file based logging - file_logger = logging.FileHandler(filename=options.OutputLog, mode="w") - if options.debug: - file_logger.setLevel(logging.DEBUG) - else: - file_logger.setLevel(logging.INFO) - - file_logger.setFormatter(formatter) - logging.getLogger("").addHandler(file_logger) - - logging.info( - "Log Started: " - + datetime.datetime.strftime(datetime.datetime.now(), "%A, %B %d, %Y %I:%M%p") - ) - - # Step 1 Prep - if options.Step1Enable: - logging.debug("Step 1 Enabled") - if (not options.CertFilePath) or (not os.path.isfile(options.CertFilePath)): - logging.critical("Not CertFilePath. That means we are un-enrolling") - - if (not options.Step2Enable) and (not options.Step2AEnable): - # must have output file - if not options.PrepResultFile: - logging.critical( - "Since Step2A/2 is not enabled there must be a PrepResultFile for the result" - ) - return -3 - - if options.PrepResultFile: - logging.debug("Step 1 Result will be written to: " + options.PrepResultFile) - - if options.SigningInputFile: - logging.critical( - "Since Step1 is enabled an Input File for Step2 is not allowed" - ) - return -11 - - # Step 2A Test Signature Generation - if options.Step2AEnable: - logging.debug("Step 2A Enabled") - if (not options.CertFilePath) or (not os.path.isfile(options.CertFilePath)): - logging.debug("Not CertFilePath. That means we are un-enrolling") - logging.critical("Step 2A should not be enabled if un-enrolling") - return -847 - - if not options.Signing2APfxFile: - logging.critical( - "Since Step2A is enabled you must supply a path to a PFX file for test signing" - ) - return -848 - - if not options.Step2BEnable: - # must have output file - if not options.Signing2AResultFile: - logging.critical( - "Since Step2B is not enabled there must be a Signing2AResultFile for the result" - ) - return -5 - - if options.Signing2AResultFile: - logging.debug( - "Step2A Result will be written to: " + options.Signing2AResultFile - ) - - # Step2B Combine Step1 and Step2A into Single File in prep for Step2 - if options.Step2BEnable: - logging.debug("Step 2B Enabled") - if not options.Step2AEnable: - # must have Test Signature Input File - if (not options.TestSignatureInputFile) or ( - not os.path.isfile(options.TestSignatureInputFile) - ): - logging.critical( - "Step2B Must have an Test Signature Input File when 2A is not enabled" - ) - return -8487 - else: - # Step 2A enabled - if options.TestSignatureInputFile: - logging.critical( - "Step2B can not have a Test Signature Input File when 2A is enabled" - ) - return -8489 - - if not options.Step1Enable: - # must have Step1s data file - if (not options.CertProvisionBlobAfterStep1File) or ( - not os.path.isfile(options.CertProvisionBlobAfterStep1File) - ): - logging.critical( - "Step2B must have a Cert Provision Blob when Step 1 is not enabled" - ) - return -8490 - - if not options.Step2Enable: - # must have an output file - if not options.Prep2BResultFile: - logging.critical( - "Step2B must have an output file (Prep2BResultFile) when Step2 is not enabled" - ) - return -8491 - - # Step 2 signing - if options.Step2Enable: - logging.debug("Step 2 Enabled") - if not options.SigningPfxFile: - logging.critical( - "Since Step2 is enabled you must supply a path to a PFX file for signing" - ) - return -10 - - if (not options.Step1Enable) and ( - (not options.SigningInputFile) - or (not os.path.isfile(options.SigningInputFile)) - ): - logging.critical( - "For Step2 you must do Step1 or have a valid SigningInputFile" - ) - return -4 - - if not options.Step3Enable: - # must have output file - if not options.SigningResultFile: - logging.critical( - "Since Step3 is not enabled there must be a SigningResultFile for the result" - ) - return -5 - if options.SigningResultFile: - logging.debug( - "Step2 Result will be written to: " + options.SigningResultFile - ) - - if options.FinalizeInputDetachedSignatureFile: - logging.critical( - "Since Step2 is enabled an Input Detached signature file for Step3 is not allowed" - ) - return -13 - - if options.FinalizeInputFile: - logging.critical( - "Since Step2 is enabled an Input file for Step3 is not allowed" - ) - return -14 - - # Step 3 Finalize - if options.Step3Enable: - logging.debug("Step 3 Enabled") - - if (not options.Step2Enable) and (options.Step1Enable): - logging.critical("Can't have only Step1 and 3 Enabled") - return -12 - - if (not options.Step2Enable) and ( - (not options.FinalizeInputFile) - or (not os.path.isfile(options.FinalizeInputFile)) - or (not options.FinalizeInputDetachedSignatureFile) - or (not os.path.isfile(options.FinalizeInputDetachedSignatureFile)) - ): - logging.critical( - "For Step3 you must do Step2 or have a valid FinalizeInputFile and FinalizeInputDetachedSignatureFile" - ) - return -6 - - # must have an output file - if not options.FinalizeResultFile: - logging.critical("For Step3 you must have a FinalizeResultFile") - return -7 - else: - logging.debug( - "Step3 Result will be written to: " + options.FinalizeResultFile - ) - - tempdir = "_temp_" + str(time.time()) - logging.critical("Temp directory is: " + os.path.join(os.getcwd(), tempdir)) - os.makedirs(tempdir) - - # STEP 1 - Prep Var - if options.Step1Enable: - logging.critical("Step1 Started") - Step1OutFile = os.path.join(tempdir, "Step1Out.bin") - SEM = CertProvisioningApplyVariable(None, int(options.HdrVersion)) - SEM.Identity = int(options.Identity) - - if int(options.HdrVersion) == CertProvisioningApplyVariable.VERSION_V1: - SEM.SNTarget = int(options.SnTarget) - elif int(options.HdrVersion) == CertProvisioningApplyVariable.VERSION_V2: - if options.SMBIOSMfg is None: - SEM.Manufacturer = "OEMSH" - else: - SEM.Manufacturer = options.SMBIOSMfg - - if options.SMBIOSProd is None: - SEM.ProductName = "OEMSH Product" - else: - SEM.ProductName = options.SMBIOSProd - - if options.SMBIOSSerial is None: - SEM.SerialNumber = "789789789" - else: - SEM.SerialNumber = options.SMBIOSSerial - - if is_32bit_number(options.Version): - SEM.Version = options.Version - - if is_32bit_number(options.Lsv): - SEM.Lsv = options.Lsv - else: - logging.critical("Invalid Header Version specified") - return -31 - - if options.CertFilePath is not None: - a = open(options.CertFilePath, "rb") - SEM.TrustedCert = a.read() - a.close() - SEM.TrustedCertSize = os.path.getsize(options.CertFilePath) - - of = open(Step1OutFile, "wb") - SEM.Write(of) - of.close() - - # if user requested a step1 output file copy the temp file - if options.PrepResultFile: - shutil.copy(Step1OutFile, options.PrepResultFile) - - # setup input for Step2 - options.SigningInputFile = Step1OutFile - # setup input for Step2B - options.CertProvisionBlobAfterStep1File = Step1OutFile - - # STEP 2A - Local Test Signature of Cert - if options.Step2AEnable: - logging.critical("Step2A Started") - Step2AFileToSign = os.path.join(tempdir, "Step2AIn.bin") - Step2AOutFile = os.path.join(tempdir, "Step2AOut.bin") - shutil.copy(options.CertFilePath, Step2AFileToSign) - options.Signing2AOutputFile = Step2AOutFile - ret = TestSignSemTrustedCert(options) - if ret != 0: - logging.critical("TestSignSemTrustedCert (Step2A) Failed: " + str(ret)) - return ret - - if options.Signing2AResultFile: - shutil.copy(Step2AOutFile, options.Signing2AResultFile) - - # setup for step 2B - options.TestSignatureInputFile = Step2AOutFile - - # STEP 2B - Combine Cert Provision blob with Test signature - if options.Step2BEnable: - logging.critical("Step2B Started") - Step2BOutFile = os.path.join(tempdir, "Step2BOut.bin") - fi = open(options.CertProvisionBlobAfterStep1File, "rb") - SEM = CertProvisioningApplyVariable(fi) - fi.close() - SEM.TestSignature = WinCertUefiGuid() - TestDetached = open(options.TestSignatureInputFile, "rb") - SEM.TestSignature.AddCertData(TestDetached) - TestDetached.close() - SemOut = open(Step2BOutFile, "wb") - SEM.Write(SemOut) - SemOut.close() - - if options.Prep2BResultFile: - shutil.copy(Step2BOutFile, options.Prep2BResultFile) - - # Setup for Step2 - options.SigningInputFile = Step2BOutFile - - # STEP 2 - Local sign - if options.Step2Enable: - logging.critical("Step2 Started") - # copy SigningInputFile into temp dir - FileToSign = os.path.join(tempdir, "Step2In.bin") - shutil.copy(options.SigningInputFile, FileToSign) - options.SigningInputFile = FileToSign - options.SigningOutputFile = os.path.join(tempdir, "Step2Signature.bin") - - # do local signature - ret = SignSEMProvisionData(options) - if ret != 0: - logging.critical("SignSEMProvisionData (Step2) Failed: " + str(ret)) - return ret - - if options.SigningResultFile: - shutil.copy(options.SigningOutputFile, options.SigningResultFile) - - # setup input for Step3 - options.FinalizeInputFile = options.SigningInputFile - options.FinalizeInputDetachedSignatureFile = options.SigningOutputFile - - # STEP 3 - Write Signature Structure and complete the KeyManifest - if options.Step3Enable: - logging.critical("Step3 Started") - sstep1file = open(options.FinalizeInputFile, "rb") - SEM = CertProvisioningApplyVariable(sstep1file) - sstep1file.close() - SEM.SessionId = random.randint(0, 4294967295) # generate a random session id - SEM.Signature = WinCertUefiGuid() - detached = open(options.FinalizeInputDetachedSignatureFile, "rb") - SEM.Signature.AddCertData(detached) - detached.close() - - if not options.FinalizeResultFile: - options.FinalizeResultFile = os.path.join(tempdir, "Step3Out.bin") - - of = open(options.FinalizeResultFile, "wb") - SEM.Write(of) - of.close() - - if not SEM.VerifyComplete(): - logging.critical("SEM Package Not complete") - return -84 - - # - # Function to print SEM - # - if (options.PrintFile) and (os.path.isfile(options.PrintFile)): - PrintSEM(options.PrintFile) - - if (options.PrintResultsFile) and (os.path.isfile(options.PrintResultsFile)): - PrintSEMResults(options.PrintResultsFile) - - if (options.PrintCurrentFile) and (os.path.isfile(options.PrintCurrentFile)): - PrintSEMCurrent(options.PrintCurrentFile) - - if (options.ExtractCertFile) and (os.path.isfile(options.ExtractCertFile)): - Thumbprint = ExtractCert(options.ExtractCertFile) - logging.critical(f"Extracted cert with thumbprint {Thumbprint}") - - # clean up if user didn't request to leave around - if not options.dirty: - shutil.rmtree(tempdir) - - return 0 - - -if __name__ == "__main__": - # setup main console as logger - logger = logging.getLogger("") - logger.setLevel(logging.DEBUG) - formatter = logging.Formatter("%(levelname)s - %(message)s") - console = logging.StreamHandler() - console.setLevel(logging.CRITICAL) - console.setFormatter(formatter) - logger.addHandler(console) - - # call main worker function - retcode = main() - - if retcode != 0: - logging.critical("Failed. Return Code: %i" % retcode) - # end logging - logging.shutdown() - sys.exit(retcode) diff --git a/SetupDataPkg/Tools/SettingSupport/GeneratePermissionPacketData.py b/SetupDataPkg/Tools/SettingSupport/GeneratePermissionPacketData.py deleted file mode 100644 index 1bc98665..00000000 --- a/SetupDataPkg/Tools/SettingSupport/GeneratePermissionPacketData.py +++ /dev/null @@ -1,501 +0,0 @@ -# @file -# -# Script to Generate a Device Firmware Configuration Interface Permission Provision Blob -# -# Copyright (c), Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -## -## Script to Generate a Device Firmware Configuration Interface Permission Provision Blob -## This tool takes in a XML file in PermissionPacket format, packages it in a -## DFCI_PERMISSION_POLICY_APPLY_VAR structure, signs it with the -## requested key, and then attaches the signature data in WIN_CERTIFICATE_UEFI_GUID format. -## -## This binary file can then be written to variable store: -## GUID: gDfciPermissionManagerVarNamespace -## NAME: DFCI_PERMISSION_POLICY_APPLY_VAR_NAME L"DfciPermissionApply" -## -## THIS IS FOR UNIT TEST -## -## General process: -## Phase 1: Create payload file by combining relevant info -## Phase 2: Sign it using signtool -## Phase 3: Parse signature into WIN_CERT and package to create final output -## - -import os -import sys -import argparse -import logging -import datetime -import shutil -import time -import random - -# get script path -sp = os.path.dirname(os.path.realpath(sys.argv[0])) - -# setup python path for build modules -sys.path.append(sp) - -from DFCI_SupportLib import DFCI_SupportLib # noqa: E402 -from edk2toollib.uefi.wincert import WinCertUefiGuid # noqa: E402 -from edk2toollib.utility_functions import DetachedSignWithSignTool # noqa: E402 -from Data.PermissionPacketVariable import PermissionApplyVariable # noqa: E402 -from Data.PermissionPacketVariable import PermissionResultVariable # noqa: E402 - - -# PKCS7 Signed Data OID -gOid = "1.2.840.113549.1.7.2" -gPath2SignTool = None - - -def PrintSEM(filepath): - if filepath and os.path.isfile(filepath): - s = open(filepath, "rb") - SEM = PermissionApplyVariable(s) - s.close() - - # now print it out. - SEM.Print() - - -def PrintSEMResults(filepath): - if filepath and os.path.isfile(filepath): - s = open(filepath, "rb") - SEM = PermissionResultVariable(s) - s.close() - - # now print it out. - SEM.Print() - - -def PrintSEMCurrent(filepath): - if filepath and os.path.isfile(filepath): - out_file_name = os.path.basename(filepath) + "_Current" + ".xml" - a = DFCI_SupportLib() - a.extract_payload_from_current(filepath, out_file_name) - - -def SignSEMData(options): - global gPath2SignTool - if gPath2SignTool is None: - a = DFCI_SupportLib() - gPath2SignTool = a.get_signtool_path() - - return DetachedSignWithSignTool( - gPath2SignTool, - options.SigningInputFile, - options.SigningOutputFile, - options.SigningPfxFile, - options.SigningPfxPw, - gOid, - ) - - -# -# main script function -# -def main(): - parser = argparse.ArgumentParser( - description="Create SEM Permission Packet Variable" - ) - - # Output debug log - parser.add_argument( - "-l", - dest="OutputLog", - help="Create an output log file: ie -l out.txt", - default=None, - ) - parser.add_argument( - "-p", dest="PrintFile", help="Print File as Permission Blob", default=None - ) - parser.add_argument( - "-pr", - dest="PrintResultsFile", - help="Print Result File as Permission Blob", - default=None, - ) - parser.add_argument( - "-pc", - dest="PrintCurrentFile", - help="Print Current File to {basename}_Current.xml", - default=None, - ) - parser.add_argument( - "--dirty", - action="store_true", - dest="dirty", - help="Leave around the temp files after finished", - default=False, - ) - - Step1Group = parser.add_argument_group( - title="Step1", description="Signed Data Prep. Build data structure." - ) - Step1Group.add_argument( - "--Step1Enable", - dest="Step1Enable", - help="Do Step 1 - Signed Data Prep", - default=False, - action="store_true", - ) - Step1Group.add_argument( - "--SnTarget", - dest="SnTarget", - help="Target to only a device with given Serial Number in decimal. Zero means all devices", - default=0, - ) - Step1Group.add_argument( - "--XmlFilePath", - dest="XmlFilePath", - help="Path to Xml Permission Packet File", - default=None, - ) - Step1Group.add_argument( - "--PrepResultFile", - dest="PrepResultFile", - help="Optional File for output from Step1. Required if not doing step2", - default=None, - ) - Step1Group.add_argument( - "--HdrVersion", - dest="HdrVersion", - help="Specify packet version", - default=PermissionApplyVariable.VERSION_V1, - ) - Step1Group.add_argument( - "--SMBIOSMfg", - dest="SMBIOSMfg", - help="Specify SMBIOS Manufacturer", - default=None, - ) - Step1Group.add_argument( - "--SMBIOSProd", - dest="SMBIOSProd", - help="Specify SMBIOS Product Name", - default=None, - ) - Step1Group.add_argument( - "--SMBIOSSerial", - dest="SMBIOSSerial", - help="Specify SMBIOS Serial Number", - default=None, - ) - - Step2Group = parser.add_argument_group( - title="Step2", description="Signature Generation Step." - ) - Step2Group.add_argument( - "--Step2Enable", - dest="Step2Enable", - help="Do Step 2 - Local Signing", - default=False, - action="store_true", - ) - # need to add arguments here for signing. signtool path and parameters - Step2Group.add_argument( - "--SigningInputFile", - dest="SigningInputFile", - help="Optional File for intput for Step2. Required if not doing step1", - default=None, - ) - Step2Group.add_argument( - "--SigningResultFile", - dest="SigningResultFile", - help="Optional File for output from Step2. Required if not doing step3", - default=None, - ) - Step2Group.add_argument( - "--SigningPfxFile", - dest="SigningPfxFile", - help="Path to PFX file for signing", - default=None, - ) - Step2Group.add_argument( - "--SigningPfxPw", - dest="SigningPfxPw", - help="Optional Password for PFX file for signing", - default=None, - ) - - Step3Group = parser.add_argument_group( - title="Step3", description="Final Var Construction." - ) - Step3Group.add_argument( - "--Step3Enable", - dest="Step3Enable", - help="Do Step 3 - Final Provisioning Var Construction", - default=False, - action="store_true", - ) - Step3Group.add_argument( - "--FinalizeInputFile", - dest="FinalizeInputFile", - help="Optional if doing Step2. Generally Step1 Output or Step2 input. ", - default=None, - ) - Step3Group.add_argument( - "--FinalizeInputDetachedSignatureFile", - dest="FinalizeInputDetachedSignatureFile", - help="Signtool Detached Signature File. Optional if doing Step2", - default=None, - ) - Step3Group.add_argument( - "--FinalizeResultFile", - dest="FinalizeResultFile", - help="File for output from Step3. Complete SEM Provisioning Var File.", - default=None, - ) - - # Turn on debug level logging - parser.add_argument( - "--debug", - action="store_true", - dest="debug", - help="turn on debug logging level for file log", - default=False, - ) - options = parser.parse_args() - - # setup file based logging if outputReport specified - if options.OutputLog: - if len(options.OutputLog) < 2: - logging.critical("the output log file parameter is invalid") - return -2 - else: - # setup file based logging - file_logger = logging.FileHandler(filename=options.OutputLog, mode="w") - if options.debug: - file_logger.setLevel(logging.DEBUG) - else: - file_logger.setLevel(logging.INFO) - - file_logger.setFormatter(formatter) - logging.getLogger("").addHandler(file_logger) - - logging.info( - "Log Started: " - + datetime.datetime.strftime(datetime.datetime.now(), "%A, %B %d, %Y %I:%M%p") - ) - - # Step 1 Prep - if options.Step1Enable: - logging.debug("Step 1 Enabled") - if (not options.XmlFilePath) or (not os.path.isfile(options.XmlFilePath)): - logging.critical("For Step1 there must be a valid XML Permission file") - return -2 - - if not options.Step2Enable: - # must have output file - if not options.PrepResultFile: - logging.critical( - "Since Step2 is not enabled there must be a PrepResultFile for the result" - ) - return -3 - - if options.PrepResultFile: - logging.debug("Step 1 Result will be written to: " + options.PrepResultFile) - - if options.SigningInputFile: - logging.critical( - "Since Step1 is enabled an Input File for Step2 is not allowed" - ) - return -11 - - # Step 2 signing - if options.Step2Enable: - logging.debug("Step 2 Enabled") - if not options.SigningPfxFile: - logging.critical( - "Since Step2 is enabled you must supply a path to a PFX file for signing" - ) - return -10 - - if (not options.Step1Enable) and ( - (not options.SigningInputFile) - or (not os.path.isfile(options.SigningInputFile)) - ): - logging.critical( - "For Step2 you must do Step1 or have a valid SigningInputFile" - ) - return -4 - - if not options.Step3Enable: - # must have output file - if not options.SigningResultFile: - logging.critical( - "Since Step3 is not enabled there must be a SigningResultFile for the result" - ) - return -5 - if options.SigningResultFile: - logging.debug( - "Step2 Result will be written to: " + options.SigningResultFile - ) - - if options.FinalizeInputDetachedSignatureFile: - logging.critical( - "Since Step2 is enabled an Input Detached signature file for Step3 is not allowed" - ) - return -13 - - if options.FinalizeInputFile: - logging.critical( - "Since Step2 is enabled an Input file for Step3 is not allowed" - ) - return -14 - - # Step 3 Finalize - if options.Step3Enable: - logging.debug("Step 3 Enabled") - - if (not options.Step2Enable) and (options.Step1Enable): - logging.critical("Can't have only Step1 and 3 Enabled") - return -12 - - if (not options.Step2Enable) and ( - (not options.FinalizeInputFile) - or (not os.path.isfile(options.FinalizeInputFile)) - or (not options.FinalizeInputDetachedSignatureFile) - or (not os.path.isfile(options.FinalizeInputDetachedSignatureFile)) - ): - logging.critical( - "For Step3 you must do Step2 or have a valid FinalizeInputFile and FinalizeInputDetachedSignatureFile" - ) - return -6 - - # must have an output file - if not options.FinalizeResultFile: - logging.critical("For Step3 you must have a FinalizeResultFile") - return -7 - else: - logging.debug( - "Step3 Result will be written to: " + options.FinalizeResultFile - ) - - tempdir = "_temp_" + str(time.time()) - logging.critical("Temp directory is: " + os.path.join(os.getcwd(), tempdir)) - os.makedirs(tempdir) - - # STEP 1 - Prep Var - if options.Step1Enable: - logging.critical("Step1 Started") - Step1OutFile = os.path.join(tempdir, "Step1Out.bin") - SEM = PermissionApplyVariable(None, int(options.HdrVersion)) - - if int(options.HdrVersion) == PermissionApplyVariable.VERSION_V1: - SEM.SNTarget = int(options.SnTarget) - elif int(options.HdrVersion) == PermissionApplyVariable.VERSION_V2: - if options.SMBIOSMfg is None: - SEM.Manufacturer = "OEMSH" - else: - SEM.Manufacturer = options.SMBIOSMfg - - if options.SMBIOSProd is None: - SEM.ProductName = "OEMSH Product" - else: - SEM.ProductName = options.SMBIOSProd - - if options.SMBIOSSerial is None: - SEM.SerialNumber = "789789789" - else: - SEM.SerialNumber = options.SMBIOSSerial - else: - logging.critical("Invalid header version specified") - return -31 - - a = open(options.XmlFilePath, "r") - SEM.AddXmlPayload(a.read()) - a.close() - - of = open(Step1OutFile, "wb") - SEM.Write(of) - of.close() - - # if user requested a step1 output file copy the temp file - if options.PrepResultFile: - shutil.copy(Step1OutFile, options.PrepResultFile) - - # setup input for Step2 - options.SigningInputFile = Step1OutFile - - # STEP 2 - Local sign - if options.Step2Enable: - logging.critical("Step2 Started") - # copy SigningInputFile into temp dir - FileToSign = os.path.join(tempdir, "Step2In.bin") - shutil.copy(options.SigningInputFile, FileToSign) - options.SigningInputFile = FileToSign - options.SigningOutputFile = os.path.join(tempdir, "Step2Signature.bin") - - # do local signature - ret = SignSEMData(options) - if ret != 0: - logging.critical("SignSEMData (Step2) Failed: " + str(ret)) - return ret - - if options.SigningResultFile: - shutil.copy(options.SigningOutputFile, options.SigningResultFile) - - # setup input for Step3 - options.FinalizeInputFile = options.SigningInputFile - options.FinalizeInputDetachedSignatureFile = options.SigningOutputFile - - # STEP 3 - Write Signature Structure and complete file - if options.Step3Enable: - logging.critical("Step3 Started") - sstep1file = open(options.FinalizeInputFile, "rb") - SEM = PermissionApplyVariable(sstep1file) - sstep1file.close() - SEM.Signature = WinCertUefiGuid() - detached = open(options.FinalizeInputDetachedSignatureFile, "rb") - SEM.Signature.AddCertData(detached) - detached.close() - SEM.SessionId = random.randint(0, 4294967295) # generate a random session id - - if not options.FinalizeResultFile: - options.FinalizeResultFile = os.path.join(tempdir, "Step3Out.bin") - - of = open(options.FinalizeResultFile, "wb") - SEM.Write(of) - of.close() - - # - # Function to print SEM - # - if (options.PrintFile) and (os.path.isfile(options.PrintFile)): - PrintSEM(options.PrintFile) - - if (options.PrintResultsFile) and (os.path.isfile(options.PrintResultsFile)): - PrintSEMResults(options.PrintResultsFile) - - if (options.PrintCurrentFile) and (os.path.isfile(options.PrintCurrentFile)): - PrintSEMCurrent(options.PrintCurrentFile) - - # clean up if user didn't request to leave around - if not options.dirty: - shutil.rmtree(tempdir) - - return 0 - - -if __name__ == "__main__": - # setup main console as logger - logger = logging.getLogger("") - logger.setLevel(logging.DEBUG) - formatter = logging.Formatter("%(levelname)s - %(message)s") - console = logging.StreamHandler() - console.setLevel(logging.CRITICAL) - console.setFormatter(formatter) - logger.addHandler(console) - - # call main worker function - retcode = main() - - if retcode != 0: - logging.critical("Failed. Return Code: %i" % retcode) - # end logging - logging.shutdown() - sys.exit(retcode) diff --git a/SetupDataPkg/Tools/SettingSupport/GenerateSettingsPacketData.py b/SetupDataPkg/Tools/SettingSupport/GenerateSettingsPacketData.py deleted file mode 100644 index d3523990..00000000 --- a/SetupDataPkg/Tools/SettingSupport/GenerateSettingsPacketData.py +++ /dev/null @@ -1,502 +0,0 @@ -# @file -# -# Script to Generate a Device Firmware Configuration Interface Settings Blob -# -# Copyright (c), Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -## -## Script to Generate a Device Firmware Configuration Interface Settings Blob -## This tool takes in a XML file in SettingsPacket format, packages it in a -## DFCI_SECURED_SETTINGS_APPLY_VAR structure, signs it with the -## requested key, and then attaches the signature data in WIN_CERTIFICATE_UEFI_GUID format. -## -## This binary file can then be written to variable store: -## GUID: gDfciSettingsManagerVarNamespace -## NAME: DFCI_SETTINGS_APPLY_INPUT_VAR_NAME L"DfciSettingsRequest" -## -## THIS IS FOR UNIT TEST -## -## General process: -## Phase 1: Create payload file by combining relevant info -## Phase 2: Sign it using signtool.exe -## Phase 3: Parse signature into WIN_CERT and package to create final output -## - -import os -import sys -import argparse -import logging -import datetime -import shutil -import time -import random - -# get script path -sp = os.path.dirname(os.path.realpath(sys.argv[0])) - -# setup python path for build modules -sys.path.append(sp) -sys.path.append(os.path.dirname(sp)) - -from DFCI_SupportLib import DFCI_SupportLib # noqa: E402 -from edk2toollib.uefi.wincert import WinCertUefiGuid # noqa: E402 -from edk2toollib.utility_functions import DetachedSignWithSignTool # noqa: E402 -from Data.SecureSettingVariable import SecureSettingsApplyVariable # noqa: E402 -from Data.SecureSettingVariable import SecureSettingsResultVariable # noqa: E402 - - -# PKCS7 Signed Data OID -gOid = "1.2.840.113549.1.7.2" -gPath2SignTool = None - - -def PrintSEM(filepath): - if filepath and os.path.isfile(filepath): - s = open(filepath, "rb") - SEM = SecureSettingsApplyVariable(s) - s.close() - - # now print it out. - SEM.Print(True) - - -def PrintSEMCurrent(filepath): - if filepath and os.path.isfile(filepath): - out_file_name = os.path.basename(filepath) + "_Current" + ".xml" - a = DFCI_SupportLib() - a.extract_payload_from_current(filepath, out_file_name) - - -def PrintSEMResults(filepath): - if filepath and os.path.isfile(filepath): - s = open(filepath, "rb") - SEM = SecureSettingsResultVariable(s) - s.close() - - # now print it out. - SEM.Print(True) - - -def SignSEMData(options): - global gPath2SignTool - if gPath2SignTool is None: - a = DFCI_SupportLib() - gPath2SignTool = a.get_signtool_path() - - return DetachedSignWithSignTool( - gPath2SignTool, - options.SigningInputFile, - options.SigningOutputFile, - options.SigningPfxFile, - options.SigningPfxPw, - gOid, - ) - - -# -# main script function -# -def main(): - parser = argparse.ArgumentParser(description="Create SEM Settings Packet Variable") - - # Output debug log - parser.add_argument( - "-l", - dest="OutputLog", - help="Create an output log file: ie -l out.txt", - default=None, - ) - parser.add_argument( - "-p", dest="PrintFile", help="Print File as Settings Blob", default=None - ) - parser.add_argument( - "-pr", - dest="PrintResultsFile", - help="Print Results File as Settings Blob", - default=None, - ) - parser.add_argument( - "-pc", - dest="PrintCurrentFile", - help="Print Current File as {basename}_Current.xml", - default=None, - ) - parser.add_argument( - "--dirty", - action="store_true", - dest="dirty", - help="Leave around the temp files after finished", - default=False, - ) - - Step1Group = parser.add_argument_group( - title="Step1", description="Signed Data Prep. Build data structure." - ) - Step1Group.add_argument( - "--Step1Enable", - dest="Step1Enable", - help="Do Step 1 - Signed Data Prep", - default=False, - action="store_true", - ) - Step1Group.add_argument( - "--SnTarget", - dest="SnTarget", - help="Target to only a device with given Serial Number in decimal. Zero means all devices", - default=0, - ) - Step1Group.add_argument( - "--XmlFilePath", - dest="XmlFilePath", - help="Path to Xml Permission Packet File", - default=None, - ) - Step1Group.add_argument( - "--PrepResultFile", - dest="PrepResultFile", - help="Optional File for output from Step1. Required if not doing step2", - default=None, - ) - Step1Group.add_argument( - "--HdrVersion", - dest="HdrVersion", - help="Specify packet version", - default=SecureSettingsApplyVariable.VERSION_V1, - ) - Step1Group.add_argument( - "--SMBIOSMfg", - dest="SMBIOSMfg", - help="Specify SMBIOS Manufacturer", - default=None, - ) - Step1Group.add_argument( - "--SMBIOSProd", - dest="SMBIOSProd", - help="Specify SMBIOS Product Name", - default=None, - ) - Step1Group.add_argument( - "--SMBIOSSerial", - dest="SMBIOSSerial", - help="Specify SMBIOS Serial Number", - default=None, - ) - - Step2Group = parser.add_argument_group( - title="Step2", description="Signature Generation Step." - ) - Step2Group.add_argument( - "--Step2Enable", - dest="Step2Enable", - help="Do Step 2 - Local Signing", - default=False, - action="store_true", - ) - # need to add arguments here for signing. signtool path and parameters - Step2Group.add_argument( - "--SigningInputFile", - dest="SigningInputFile", - help="Optional File for intput for Step2. Required if not doing step1", - default=None, - ) - Step2Group.add_argument( - "--SigningResultFile", - dest="SigningResultFile", - help="Optional File for output from Step2. Required if not doing step3", - default=None, - ) - Step2Group.add_argument( - "--SigningPfxFile", - dest="SigningPfxFile", - help="Path to PFX file for signing", - default=None, - ) - Step2Group.add_argument( - "--SigningPfxPw", - dest="SigningPfxPw", - help="Optional Password for PFX file for signing", - default=None, - ) - - Step3Group = parser.add_argument_group( - title="Step3", description="Final Var Construction." - ) - Step3Group.add_argument( - "--Step3Enable", - dest="Step3Enable", - help="Do Step 3 - Final Provisioning Var Construction", - default=False, - action="store_true", - ) - Step3Group.add_argument( - "--FinalizeInputFile", - dest="FinalizeInputFile", - help="Optional if doing Step2. Generally Step1 Output or Step2 input. ", - default=None, - ) - Step3Group.add_argument( - "--FinalizeInputDetachedSignatureFile", - dest="FinalizeInputDetachedSignatureFile", - help="Signtool Detached Signature File. Optional if doing Step2", - default=None, - ) - Step3Group.add_argument( - "--FinalizeResultFile", - dest="FinalizeResultFile", - help="File for output from Step3. Complete SEM Provisioning Var File.", - default=None, - ) - - # Turn on debug level logging - parser.add_argument( - "--debug", - action="store_true", - dest="debug", - help="turn on debug logging level for file log", - default=False, - ) - options = parser.parse_args() - - # setup file based logging if outputReport specified - if options.OutputLog: - if len(options.OutputLog) < 2: - logging.critical("the output log file parameter is invalid") - return -27 - else: - # setup file based logging - file_logger = logging.FileHandler(filename=options.OutputLog, mode="w") - if options.debug: - file_logger.setLevel(logging.DEBUG) - else: - file_logger.setLevel(logging.INFO) - - file_logger.setFormatter(formatter) - logging.getLogger("").addHandler(file_logger) - - logging.info( - "Log Started: " - + datetime.datetime.strftime(datetime.datetime.now(), "%A, %B %d, %Y %I:%M%p") - ) - - # Step 1 Prep - if options.Step1Enable: - logging.debug("Step 1 Enabled") - if (not options.XmlFilePath) or (not os.path.isfile(options.XmlFilePath)): - logging.critical("For Step1 there must be a valid XML Settings file") - return -2 - - if not options.Step2Enable: - # must have output file - if not options.PrepResultFile: - logging.critical( - "Since Step2 is not enabled there must be a PrepResultFile for the result" - ) - return -3 - - if options.PrepResultFile: - logging.debug("Step 1 Result will be written to: " + options.PrepResultFile) - - if options.SigningInputFile: - logging.critical( - "Since Step1 is enabled an Input File for Step2 is not allowed" - ) - return -11 - - # Step 2 signing - if options.Step2Enable: - logging.debug("Step 2 Enabled") - if not options.SigningPfxFile: - logging.critical( - "Since Step2 is enabled you must supply a path to a PFX file for signing" - ) - return -10 - - if (not options.Step1Enable) and ( - (not options.SigningInputFile) - or (not os.path.isfile(options.SigningInputFile)) - ): - logging.critical( - "For Step2 you must do Step1 or have a valid SigningInputFile" - ) - return -4 - - if not options.Step3Enable: - # must have output file - if not options.SigningResultFile: - logging.critical( - "Since Step3 is not enabled there must be a SigningResultFile for the result" - ) - return -5 - if options.SigningResultFile: - logging.debug( - "Step2 Result will be written to: " + options.SigningResultFile - ) - - if options.FinalizeInputDetachedSignatureFile: - logging.critical( - "Since Step2 is enabled an Input Detached signature file for Step3 is not allowed" - ) - return -13 - - if options.FinalizeInputFile: - logging.critical( - "Since Step2 is enabled an Input file for Step3 is not allowed" - ) - return -14 - - # Step 3 Finalize - if options.Step3Enable: - logging.debug("Step 3 Enabled") - - if (not options.Step2Enable) and (options.Step1Enable): - logging.critical("Can't have only Step1 and 3 Enabled") - return -12 - - if (not options.Step2Enable) and ( - (not options.FinalizeInputFile) - or (not os.path.isfile(options.FinalizeInputFile)) - or (not options.FinalizeInputDetachedSignatureFile) - or (not os.path.isfile(options.FinalizeInputDetachedSignatureFile)) - ): - logging.critical( - "For Step3 you must do Step2 or have a valid FinalizeInputFile and FinalizeInputDetachedSignatureFile" - ) - return -6 - - # must have an output file - if not options.FinalizeResultFile: - logging.critical("For Step3 you must have a FinalizeResultFile") - return -7 - else: - logging.debug( - "Step3 Result will be written to: " + options.FinalizeResultFile - ) - - tempdir = "_temp_" + str(time.time()) - logging.critical("Temp directory is: " + os.path.join(os.getcwd(), tempdir)) - os.makedirs(tempdir) - - # STEP 1 - Prep Var - if options.Step1Enable: - logging.critical("Step1 Started") - Step1OutFile = os.path.join(tempdir, "Step1Out.bin") - SEM = SecureSettingsApplyVariable(None, int(options.HdrVersion)) - - if int(options.HdrVersion) == SecureSettingsApplyVariable.VERSION_V1: - SEM.SNTarget = int(options.SnTarget) - elif int(options.HdrVersion) == SecureSettingsApplyVariable.VERSION_V2: - if options.SMBIOSMfg is None: - SEM.Manufacturer = "OEMSH" - else: - SEM.Manufacturer = options.SMBIOSMfg - - if options.SMBIOSProd is None: - SEM.ProductName = "OEMSH Product" - else: - SEM.ProductName = options.SMBIOSProd - - if options.SMBIOSSerial is None: - SEM.SerialNumber = "789789789" - else: - SEM.SerialNumber = options.SMBIOSSerial - - else: - logging.critical("Invalid header version specified") - return -31 - - a = open(options.XmlFilePath, "r") - SEM.AddXmlPayload(a.read()) - a.close() - - of = open(Step1OutFile, "wb") - SEM.Write(of) - of.close() - - # if user requested a step1 output file copy the temp file - if options.PrepResultFile: - shutil.copy(Step1OutFile, options.PrepResultFile) - - # setup input for Step2 - options.SigningInputFile = Step1OutFile - - # STEP 2 - Local sign - if options.Step2Enable: - logging.critical("Step2 Started") - # copy SigningInputFile into temp dir - FileToSign = os.path.join(tempdir, "Step2In.bin") - shutil.copy(options.SigningInputFile, FileToSign) - options.SigningInputFile = FileToSign - options.SigningOutputFile = os.path.join(tempdir, "Step2Signature.bin") - - # do local signature - ret = SignSEMData(options) - if ret != 0: - logging.critical("SignSEMData (Step2) Failed: " + str(ret)) - return ret - - if options.SigningResultFile: - shutil.copy(options.SigningOutputFile, options.SigningResultFile) - - # setup input for Step3 - options.FinalizeInputFile = options.SigningInputFile - options.FinalizeInputDetachedSignatureFile = options.SigningOutputFile - - # STEP 3 - Write Signature Structure and complete file - if options.Step3Enable: - logging.critical("Step3 Started") - sstep1file = open(options.FinalizeInputFile, "rb") - SEM = SecureSettingsApplyVariable(sstep1file) - sstep1file.close() - SEM.Signature = WinCertUefiGuid() - detached = open(options.FinalizeInputDetachedSignatureFile, "rb") - SEM.Signature.AddCertData(detached) - detached.close() - # generate a random session id - SEM.SessionId = random.randint(0, 4294967295) - - if not options.FinalizeResultFile: - options.FinalizeResultFile = os.path.join(tempdir, "Step3Out.bin") - - of = open(options.FinalizeResultFile, "wb") - SEM.Write(of) - of.close() - - # - # Function to print SEM - # - if (options.PrintFile) and (os.path.isfile(options.PrintFile)): - PrintSEM(options.PrintFile) - - if (options.PrintResultsFile) and (os.path.isfile(options.PrintResultsFile)): - PrintSEMResults(options.PrintResultsFile) - - if (options.PrintCurrentFile) and (os.path.isfile(options.PrintCurrentFile)): - PrintSEMCurrent(options.PrintCurrentFile) - - # clean up if user didn't request to leave around - if not options.dirty: - shutil.rmtree(tempdir) - - return 0 - - -if __name__ == "__main__": - # setup main console as logger - logger = logging.getLogger("") - logger.setLevel(logging.DEBUG) - formatter = logging.Formatter("%(levelname)s - %(message)s") - console = logging.StreamHandler() - console.setLevel(logging.CRITICAL) - console.setFormatter(formatter) - logger.addHandler(console) - - # call main worker function - retcode = main() - - if retcode != 0: - logging.critical("Failed. Return Code: %i" % retcode) - # end logging - logging.shutdown() - sys.exit(retcode) diff --git a/SetupDataPkg/Tools/SettingSupport/InsertCertIntoXML.py b/SetupDataPkg/Tools/SettingSupport/InsertCertIntoXML.py deleted file mode 100644 index a792f094..00000000 --- a/SetupDataPkg/Tools/SettingSupport/InsertCertIntoXML.py +++ /dev/null @@ -1,69 +0,0 @@ -# @file -# -# Convert Bin cert file to base 64 string, and replace the XYZZY string with the -# base 64 string. -# -# Copyright (c), Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -import sys - -import argparse -import logging -import binascii - - -# -# main script function -# -def main(): - parser = argparse.ArgumentParser(description='Create SEM Provisioning Cert CSP XML') - - parser.add_argument("--BinFilePath", dest="BinFilePath", help="Path to binary packet", default=None) - parser.add_argument("--OutputFilePath", dest="OutputFilePath", help="Path to output file", default=None) - parser.add_argument("--PatternFilePath", dest="PatternFilePath", help="Path to Xml pattern", default=None) - - options = parser.parse_args() - - with open(options.BinFilePath, "rb") as bin_file: - bindata = bin_file.read() - - if bindata is None: - raise Exception("Invalid binary data") - - b64data = binascii.b2a_base64(bindata).decode("utf-8") - - FoundXYZZY = False - with open(options.OutputFilePath, "w") as outfile: - with open(options.PatternFilePath, "r") as pattern_file: - for pl in pattern_file: - if pl.strip() == "XYZZY": - FoundXYZZY = True - outfile.write(b64data) - else: - outfile.write(pl) - if not FoundXYZZY: - raise Exception("Invalid pattern data") - logging.critical("Successfully created XML pkt") - return 0 - - -if __name__ == '__main__': - # setup main console as logger - logger = logging.getLogger('') - logger.setLevel(logging.DEBUG) - formatter = logging.Formatter("%(levelname)s - %(message)s") - console = logging.StreamHandler() - console.setLevel(logging.CRITICAL) - console.setFormatter(formatter) - logger.addHandler(console) - - # call main worker function - retcode = main() - - if retcode != 0: - logging.critical("Failed. Return Code: %i" % retcode) - # end logging - logging.shutdown() - sys.exit(retcode) diff --git a/SetupDataPkg/Tools/SettingSupport/PermissionsXMLLib.py b/SetupDataPkg/Tools/SettingSupport/PermissionsXMLLib.py deleted file mode 100644 index 05f34b60..00000000 --- a/SetupDataPkg/Tools/SettingSupport/PermissionsXMLLib.py +++ /dev/null @@ -1,110 +0,0 @@ -# @file -# -# Script to Generate a a Permissions XML payload. -# -# Copyright (c), Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent - -import datetime -from DFCI_SupportLib import DFCI_SupportLib - - -class PermissionsXMLLib(object): - - # - # Create Permissions XML - # - # Given a list of permissions, PMASK, and DMASK, create an XML permissions payload - # - def create_permissions_xml(self, filename, version, lsv, def_pmask, def_dmask, permissionslist): - - f = open(filename, "w") - f.write('\n') - f.write('\n') - f.write(' Dfci Testcase Libraries\n') - f.write(' ') - - print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), end='', file=f) - - f.write('\n') - f.write(' ') - print(version, end='', file=f) - f.write('\n') - f.write(' 2\n') - f.write(' ') - - # - # The permissions list is a list of a list. The lowest level list is really a tuple of - # permission id, PMASK, and DMASK. DMASK may be None. - # - for permission in permissionslist: - f.write(' \n') - f.write(' ') - print(permission[0], end='', file=f) - f.write('\n') - f.write(' ') - print(permission[1], end='', file=f) - f.write('\n') - if (permission[2] is not None): - f.write(' ') - print(permission[2], end='', file=f) - f.write('\n') - f.write(' \n') - - f.write(' \n') - f.write('\n') - - f.close - - return True - - # - # Validate Current Permissions - # - # Input is the current permissions and a list of permission/PMASK/DMASK tuples (list of lists) - # - # Ensure the settings in the checklist have the proper value - # - def validate_current_permissions(self, test_name, currentPermissionsXmlFile, checklist): - - for item in checklist: - a = DFCI_SupportLib() - PMask, DMask = a.get_current_permission_value(currentPermissionsXmlFile, item[0]) - - if (PMask != item[1]): - print('PMask Mismatch for %s, was=%s, Should be=%s' % (item[0], PMask, item[1])) - return False - - if (PMask is not None): - if (DMask != item[2]): - print('DMask Mismatch for %s, was=%s, Should be=%s' % (item[0], DMask, item[2])) - return False - - return True - - # - # Validate Current Permission Defaults - # - # Input is the current permissions and the default PMASK and DMASK - # - # Ensure the settings in the checklist have the proper value - # - def validate_current_permission_defaults(self, test_name, currentPermissionsXmlFile, CheckDefault, CheckDelegated): - - a = DFCI_SupportLib() - Default, Delegated = a.get_current_permission_defaults(currentPermissionsXmlFile) - - if (Default != CheckDefault): - print('PMask Mismatch was %s should be %s' % (Default, CheckDefault)) - return False - - if (Delegated != CheckDelegated): - print('DMask Mismatch was %s should be %s' % (Delegated, CheckDelegated)) - return False - - return True diff --git a/SetupDataPkg/Tools/SettingSupport/PyRobotRemote.py b/SetupDataPkg/Tools/SettingSupport/PyRobotRemote.py deleted file mode 100644 index 634fce18..00000000 --- a/SetupDataPkg/Tools/SettingSupport/PyRobotRemote.py +++ /dev/null @@ -1,107 +0,0 @@ -# @file -# -# PyRobotRemote - Runs on the System Under Test (DUT) providing -# functionality needed for DFCI testing -# -# Copyright (c), Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -import os -import sys -import subprocess -import logging -import shlex -import win32api -import win32con -import win32security -import winnt - -from Lib.UefiVariablesSupportLib import UefiVariable - - -# update this whenever you make a change -RobotRemoteChangeDate = "2020-10-02 09:30" -RobotRemoteVersion = 1.05 - - -class UefiRemoteTesting(object): - """Library to be used with Robot Framework's remote server. - - This supports Robot Framework Remote Interface. This lets a remote test system perform local operations using - remote framework and built in remote "Keywords" - """ - def __init__(self): - self.filepath = None - self.lines = [] - - def Run_Command_And_Return_Output(self, cmdline): - cmd = shlex.split(cmdline) - p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - p.wait() - out = p.communicate()[0] - rc = p.returncode - lines = out.splitlines() - - if rc != 0 or len(lines) < 3: - return "Error" - else: - return lines[2].decode('utf-8').strip() - - # - # String variables are designed to have a NULL. This does - # confuse Python, so get rid of the NULL when it is expected - # - def GetUefiVariable(self, name, guid, trim): - UefiVar = UefiVariable() - logging.info("Calling GetUefiVar(name='%s', GUID='%s')" % (name, "{%s}" % guid)) - (rc, var) = UefiVar.GetUefiVar(name, guid) - var2 = var - if (var is not None) and (trim == 'trim'): - varlen = len(var) - if varlen > 1: - var2 = var[0: varlen - 1] - return (rc, var2, "") - - def SetUefiVariable(self, name, guid, attrs=None, contents=None): - UefiVar = UefiVariable() - return UefiVar.SetUefiVar(name, guid, contents, attrs) - - def remote_ack(self): - return True - - def remote_get_version(self): - return RobotRemoteVersion - - def remote_warm_reboot(self): - os.system("shutdown -r -t 1") - - def remote_reboot_to_firmware(self): - TokenHandle = win32security.OpenProcessToken(win32api.GetCurrentProcess(), - win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY) - NewPrivilege = [(win32security.LookupPrivilegeValue(None, winnt.SE_SHUTDOWN_NAME), - winnt.SE_PRIVILEGE_ENABLED)] - win32security.AdjustTokenPrivileges(TokenHandle, False, NewPrivilege) - os.system("shutdown -r -fw -t 0") - - -if __name__ == '__main__': - from robotremoteserver import RobotRemoteServer - print("Version %s - %s" % (str(RobotRemoteVersion), RobotRemoteChangeDate)) - - # setup main console as logger - logger = logging.getLogger('') - logger.setLevel(logging.DEBUG) - formatter = logging.Formatter("%(levelname)s - %(message)s") - console = logging.StreamHandler() - console.setLevel(logging.CRITICAL) - console.setFormatter(formatter) - logger.addHandler(console) - - # Display IP address for convenience of tester - os.system('ipconfig | findstr IPv4') - - RobotRemoteServer(UefiRemoteTesting(), host='0.0.0.0', port=8270) - - logging.shutdown() - sys.exit(0) diff --git a/SetupDataPkg/Tools/SettingSupport/SettingsXMLLib.py b/SetupDataPkg/Tools/SettingSupport/SettingsXMLLib.py deleted file mode 100644 index ae792e7f..00000000 --- a/SetupDataPkg/Tools/SettingSupport/SettingsXMLLib.py +++ /dev/null @@ -1,72 +0,0 @@ -# @file -# -# Script to Generate a Settings XML payload. -# -# Copyright (c), Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent - -import datetime -from SettingSupport.DFCI_SupportLib import DFCI_SupportLib - - -class SettingsXMLLib(object): - - # - # Create Settings XML - # - # Given a list of settings and values, create an XML settings payload - # - def create_settings_xml(self, filename, version, lsv, settingslist): - - with open(filename, "w") as f: - f.write('\n') - f.write('\n') - f.write(' Dfci Testcase Libraries\n') - f.write(' ') - - print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), end='', file=f) - - f.write('\n') - f.write(' ') - print(version, end='', file=f) - f.write('\n') - f.write(' ') - print(lsv, end='', file=f) - f.write('\n') - f.write(' \n') - - # - # The settings list is a list of a list. The lowest level list is really a tuple of - # setting id and value - # - for setting in settingslist: - f.write(' \n') - f.write(' ') - print(setting[0], end='', file=f) - f.write('\n') - f.write(' ') - print(setting[1], end='', file=f) - f.write('\n') - f.write(' \n') - - f.write(' \n') - f.write('\n') - - return True - - # - # Validate Current Settings - # - # Input is the current settings and a list of setting/value pairs (list of lists) - # - # Ensure the settings in the checklist have the proper value - # - def validate_current_settings(self, testname, currentSettingXmlFile, checklist): - - for item in checklist: - a = DFCI_SupportLib() - rc = a.check_current_setting_value(currentSettingXmlFile, item[0], item[1]) - if not rc: - return rc - - return True diff --git a/SetupDataPkg/Tools/SettingSupport/UtilityFunctions.py b/SetupDataPkg/Tools/SettingSupport/UtilityFunctions.py deleted file mode 100644 index 6224f10d..00000000 --- a/SetupDataPkg/Tools/SettingSupport/UtilityFunctions.py +++ /dev/null @@ -1,191 +0,0 @@ -# @file -# -# Utility Functions to support re-use in python scripts. -# -# Copyright (c), Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent - -## -## Utility Functions to support re-use in python scripts. -## -## Includes functions for running external commands, etc -## -# support Python3 and 2 for print -from __future__ import print_function -import os -import logging -import datetime -import shutil -import threading -import subprocess - -import edk2toollib.windows.locate_tools as locate_tools - -gSignToolPath = locate_tools.FindToolInWinSdk("signtool.exe") -if gSignToolPath is None: - logging.critical("Cannot find WinSdk installation of signtool.exe\n") - - -gCertMgrPath = locate_tools.FindToolInWinSdk("certmgr.exe") -if gCertMgrPath is None: - logging.critical("Cannot find WinSdk installation of certmgr.exe\n") - - -# -# Cert Util is used to import PFX into cert store -# -gCertUtilPath = "CertUtil.exe" - - -# -# process output stream and write to log. -# part of the threading pattern. -# -# http://stackoverflow.com/questions/19423008/logged-subprocess-communicate -# -def reader(stream): - while True: - s = stream.readline() - if not s: - break - logging.info(s.rstrip()) - stream.close() - - -def filereader(filepath, stream): - file = open(filepath, "w") - while True: - s = stream.readline() - if not s: - break - file.write(s) - stream.close() - file.close() - - -# -# Run a shell command and print the output to the log file -# -def RunCmd(cmd, capture=True, outfile=None): - starttime = datetime.datetime.now() - logging.debug("Cmd to run is: " + cmd) - logging.info("------------------------------------------------") - logging.info("--------------Cmd Output Starting---------------") - logging.info("------------------------------------------------") - c = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - if capture: - if outfile: - out_r = threading.Thread( - target=filereader, - args=( - outfile, - c.stdout, - ), - ) - else: - out_r = threading.Thread(target=reader, args=(c.stdout,)) - out_r.start() - c.wait() - out_r.join() - else: - c.wait() - - # replaced communicate method with modified threading solution found here - # http://stackoverflow.com/questions/19423008/logged-subprocess-communicate - # - - endtime = datetime.datetime.now() - delta = endtime - starttime - logging.info("------------------------------------------------") - logging.info("--------------Cmd Output Finished---------------") - logging.info( - "--------- Running Time (mm:ss): {0[0]:02}:{0[1]:02} ----------".format( - divmod(delta.seconds, 60) - ) - ) - logging.info("------------------------------------------------") - return c.returncode - - -def SignWithSignTool( - ToSignFilePath, DetachedSignatureOutputFilePath, PfxFile, PfxPass, Oid -): - OutputDir = os.path.dirname(DetachedSignatureOutputFilePath) - cmd = ( - gSignToolPath - + " sign /p7ce DetachedSignedData /fd sha256 /p7co " - + Oid - + ' /p7 "' - + OutputDir - + '" /f "' - + PfxFile - + '"' - ) - if PfxPass: - # add password if set - cmd = cmd + " /p " + PfxPass - cmd = cmd + ' /debug /v "' + ToSignFilePath + '" ' - logging.critical("Command is: %s" % cmd) - ret = RunCmd(cmd) - if ret != 0: - raise Exception("Signtool error %d" % ret) - signed_file = os.path.join(OutputDir, os.path.basename(ToSignFilePath) + ".p7") - if not os.path.isfile(signed_file): - raise Exception("Output file doesn't exist %s" % signed_file) - - shutil.move(signed_file, DetachedSignatureOutputFilePath) - return ret - - -### -# Function to print a byte list as hex and optionally output ascii as well as -# offset within the buffer -### -def PrintByteList( - ByteList, IncludeAscii=True, IncludeOffset=True, IncludeHexSep=True, OffsetStart=0 -): - Ascii = "" - for index in range(len(ByteList)): - # Start of New Line - if index % 16 == 0: - if IncludeOffset: - print("0x%04X -" % (index + OffsetStart), end="") - - # Midpoint of a Line - if index % 16 == 8: - if IncludeHexSep: - print(" -", end="") - - # Print As Hex Byte - print(" 0x%02X" % ByteList[index], end="") - - # Prepare to Print As Ascii - if (ByteList[index] < 0x20) or (ByteList[index] > 0x7E): - Ascii += "." - else: - Ascii += "%c" % ByteList[index] - - # End of Line - if index % 16 == 15: - if IncludeAscii: - print(" %s" % Ascii, end="") - Ascii = "" - print("") - - # Done - Lets check if we have partial - if index % 16 != 15: - # Lets print any partial line of ascii - if (IncludeAscii) and (Ascii != ""): - # Pad out to the correct spot - - while index % 16 != 15: - print(" ", end="") - # account for the - symbol in the hex dump - if index % 16 == 7: - if IncludeOffset: - print(" ", end="") - index += 1 - # print the ascii partial line - print(" %s" % Ascii, end="") - # print a single newline so that next print will be on new line - print("") diff --git a/SetupDataPkg/Tools/WrapAndSetSvd.py b/SetupDataPkg/Tools/WrapAndSetSvd.py deleted file mode 100644 index bcb1a898..00000000 --- a/SetupDataPkg/Tools/WrapAndSetSvd.py +++ /dev/null @@ -1,132 +0,0 @@ -# @file -# -# Build a JSON packet for the USB Refresh option -# -# Copyright (c), Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent - -## -## -## Convert each of the bin files to Base64 then add each of them to a JSON element. -## - -import os -import sys -import logging -import argparse -from edk2toollib.utility_functions import RunPythonScript -from edk2toollib.os.uefivariablesupport import UefiVariable - -# get script path -sp = os.path.abspath(os.path.dirname(__file__)) - -# setup python path for build modules -sys.path.append(sp) - - -DFCI_SETTINGS_APPLY_INPUT_VAR_NAME = "DfciSettingsRequest" -DFCI_SETTINGS_GUID = "D41C8C24-3F5E-4EF4-8FDD-073E1866CD01" -DFCI_SECURED_SETTINGS_VAR_ATTRIBUTES = 7 # (NV | BS | RT) - - -# Setup import and argument parser -def path_parse(): - - parser = argparse.ArgumentParser() - - parser.add_argument( - "-i", - "--InputSVDFile", - dest="InputSVDFile", - required=True, - type=str, - help="""Specify the absolute path to SVD file intended to be set.""", - ) - parser.add_argument( - "-m", - "--Manufacturer", - dest="Manufacturer", - type=str, - default='""', - help="""Specify the your manufacturer name.""", - ) - parser.add_argument( - "-p", - "--Product", - dest="Product", - type=str, - default='""', - help="""Specify the your product name.""", - ) - parser.add_argument( - "-s", - "--SerialNum", - dest="SerialNum", - type=str, - default='""', - help="""Specify the your targeted serial number.""", - ) - - Paths = parser.parse_args() - - if not os.path.isfile(Paths.InputSVDFile): - raise Exception("Invalid input files %s" % Paths.InputSVDFile) - - return Paths - - -# -# main script function -# -def main(): - - Paths = path_parse() - - setting_file = "Unsigned_Settings_apply.bin" - py_file = "SettingSupport/GenerateSettingsPacketData.py" - params = ["--Step1Enable"] - params += ["--PrepResultFile", setting_file] - params += ["--XmlFilePath", Paths.InputSVDFile] - params += ["--HdrVersion", "2"] - params += ["--SMBIOSMfg", Paths.Manufacturer] - params += ["--SMBIOSProd", Paths.Product] - params += ["--SMBIOSSerial", Paths.SerialNum] - ret = RunPythonScript( - py_file, " ".join(params), workingdir=sp, environ=os.environ.copy() - ) - if ret != 0: - raise Exception("Failed to generate package - %x" % ret) - - with open(os.path.join(sp, setting_file), "rb") as file: - var = file.read() - UefiVar = UefiVariable() - rc = UefiVar.SetUefiVar( - DFCI_SETTINGS_APPLY_INPUT_VAR_NAME, - DFCI_SETTINGS_GUID, - var, - DFCI_SECURED_SETTINGS_VAR_ATTRIBUTES, - ) - if rc == 0: # This is per function document... - logging.error( - f"Failed to set mailbox settings into UEFI variable - {rc}" - ) - return 1 - return 0 - - -if __name__ == "__main__": - # setup main console as logger - logger = logging.getLogger("") - logger.setLevel(logging.DEBUG) - formatter = logging.Formatter("%(levelname)s - %(message)s") - console = logging.StreamHandler() - console.setLevel(logging.CRITICAL) - - # call main worker function - retcode = main() - - if retcode != 0: - logging.critical("Failed. Return Code: %i" % retcode) - # end logging - logging.shutdown() - sys.exit(retcode)