//---------------------------------------------------------------------------- // // Copyright (c) Intel Corporation, 2011 - 2015 All Rights Reserved. // // File: RemoteControlApi.cs // // Contents: Api code for Intel(R) Active Management Technology // (Intel® AMT) RemoteControl Sample. // // Notes: This sample demonstrates how to use various commands of // the RemoteControl service. // //---------------------------------------------------------------------------- using System; using Utils; using Intel.Management.Wsman; using Connection; using Common.Utils; namespace RemoteControl { #region ENUMS public enum PowerState { Other = 1, On, LightSleep, DeepSleep, SoftPowerCycle, HardOff, Hibernate, SoftOff, HardPowerCycle, MasterBusReset, DiagnosticInterrupt, GracefulOff, GracefulReset = 14, WakeFromPowerSaving = 15 } enum PowerSavingState { Unsupported = 1, FullPower, PowerSaving }; public enum IderBootDevice { Floppy = 0, CD = 1 } public enum BIOSstatus { Success = 0, InProgress, NotUpdated, Failed = 0xFFFF } public enum BIOSErrorStatus { SuccessOrInProgress = 0, GeneralDriveFailure, DrivePasswordOrAuthenticationFailure, FeatureNotSupported } #endregion public class RemoteControlApi : Connection.Connection_setup { #region CONSTANTS private const uint PT_STATUS_SUCCESS = 0; private const uint PT_STATUS_UNSPECIFIED_ERROR = 2; private const string BOOT_CONFIG_SETTINGS_KEY = "InstanceID"; private const string BOOT_CONFIG_SETTINGS_VALUE = "Intel(r) AMT: Boot Configuration 0"; private const string STR_UNSPECIFIED_ERROR = "Requested operation is not allowed in AMT system's current state."; private const string STR_BOOT_HARD_DRIVE = "Intel(r) AMT: Force Hard-drive Boot"; private const string STR_BOOT_CD_DVD = "Intel(r) AMT: Force CD/DVD Boot"; private const string STR_BOOT_DIAGNOSTIC = "Intel(r) AMT: Force Diagnostic Boot"; private const string STR_BOOT_PXE = "Intel(r) AMT: Force PXE Boot"; private const string STR_BOOT_CONFIGURATION = "Intel(r) AMT: Boot Configuration 0"; public const string SRC_BOOT_NONE = "none"; public const string SRC_BOOT_HARD_DRIVE = "harddisk"; public const string SRC_BOOT_CD_DVD = "cd"; public const string SRC_BOOT_DIAGNOSTIC = "diagnostic"; public const string SRC_BOOT_PXE = "pxe"; public const string SRC_IDER_FLOPPY = "iderfloppy"; public const string SRC_IDER_CD = "idercd"; private const ushort IS_NEXT_USE = 1; private const string RESOURCE_URI_PREFIX_AMT = "http://intel.com/wbem/wscim/1/amt-schema/1/"; private const string RESOURCE_URI_PREFIX_CIM = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/"; #endregion CONSTANTS #region DATA MEMBERS public static CmdLineArguments Params = new CmdLineArguments(); #endregion #region CONSTRUCTORS /// /// Constructor. /// /// IWSManClient, the wsmanClient object /// Inheriting Connection details from Connection_setup class. // Convert password to secure string to comply with wsman dll which supports passwords in SecureString // format only. public RemoteControlApi(string ip, string username, string pwd, bool krb, MpsManager proxy, bool acceptSelfSignedCertificate = false) : base(ip, username, pwd.ConvertToSecureString(), krb, proxy, acceptSelfSignedCertificate) { } public RemoteControlApi(string ip, string username, string pwd, string clientCert, bool krb, MpsManager proxy, bool acceptSelfSignedCertificate = false) : base(ip, username, pwd.ConvertToSecureString(), clientCert, krb, proxy, acceptSelfSignedCertificate) { } #endregion CONSTRUCTORS #region PUBLIC FUNCTIONS /// /// Display the current power state. /// /// CIM_PowerManagementService instance associated to CIM_ComputerSystem. public PowerState GetSystemPowerState() { //Get CIM Associated Power Mgmt Service - data is held here. IManagedReference computerSysRef = wsmanClient.NewReference("SELECT * FROM CIM_ComputerSystem WHERE Name='ManagedSystem'"); IManagedReference associatedPowerMgmtRef = wsmanClient.NewReference("CIM_AssociatedPowerManagementService"); Console.WriteLine("\n Getting system power state..."); associatedPowerMgmtRef.AddSelector("UserOfService", computerSysRef); IManagedInstance associatedPowerMgmtInstance = null; //Traverse to the CIM AssociatedMgmt Service instances that are connected to CIM_ComputerSys instances. int powerState = 0; foreach (IWsmanItem associatedPowerMgmtItem in associatedPowerMgmtRef.Enumerate("http://schemas.dmtf.org/wbem/wsman/1/wsman/SelectorFilter", null)) { //For each instance,check if it is associated to the CIM_powerManagmentService instance. if (associatedPowerMgmtItem.Object.GetProperty("ServiceProvided").IsA("CIM_PowerManagementService")) { associatedPowerMgmtInstance = associatedPowerMgmtItem.Object; powerState = Convert.ToInt16(associatedPowerMgmtInstance.GetProperty("PowerState").ToString()); switch (powerState) { //Assign variables to each of the values... This will help for other functions as well... case (int)PowerState.On: Console.WriteLine("\nCurrent Power State is: On"); break; case (int)PowerState.LightSleep: Console.WriteLine("\nCurrent Power State is: Light sleep"); break; case (int)PowerState.DeepSleep: Console.WriteLine("\nCurrent Power State is: Deep sleep"); break; case (int)PowerState.SoftPowerCycle: Console.WriteLine("\nCurrent Power State is: Power cycle (Off Soft)"); break; case (int)PowerState.HardOff: Console.WriteLine("\nCurrent Power State is: Power Off - Hard"); break; case (int)PowerState.Hibernate: Console.WriteLine("\nCurrent Power State is: Hibernate"); break; case (int)PowerState.SoftOff: Console.WriteLine("\nCurrent Power State is : Power Off - Soft"); break; case (int)PowerState.HardPowerCycle: Console.WriteLine("\nCurrent Power State is : Power Cycle (Off Hard)"); break; case (int)PowerState.MasterBusReset: Console.WriteLine("\nCurrent Power State is: Master Bus Reset"); break; case (int)PowerState.DiagnosticInterrupt: Console.WriteLine("\nCurrent Power State is : Diagnostic Interrupt(NMI)"); break; } } } //Get IPS Power Management Service - data is held here. IManagedReference IPS_PowerManagementServiceRef = wsmanClient.NewReference("IPS_PowerManagementService"); Console.WriteLine("\n Getting system power saving state..."); int powerSavingState; IWsmanItem PowerMgmtItem = IPS_PowerManagementServiceRef.Enumerate("http://schemas.dmtf.org/wbem/wsman/1/wsman", null).Next(); try { powerSavingState = Convert.ToInt16(PowerMgmtItem.Object.GetProperty("OSPowerSavingState").ToString()); } catch { powerSavingState = 0; } switch (powerSavingState) { case (int)PowerSavingState.Unsupported: Console.WriteLine("\nCurrent Power Saving State is : Unsupported."); break; case (int)PowerSavingState.FullPower: Console.WriteLine("\nCurrent Power Saving State is : Full Power."); break; case (int)PowerSavingState.PowerSaving: Console.WriteLine("\nCurrent Power Saving State is : Power Saving."); break; default: Console.WriteLine("\nCurrent Power Saving State is : Unknown."); break; } Params.MessageDisplay_Color("Success.", ConsoleColor.Green); PowerState state = new PowerState(); if (associatedPowerMgmtInstance != null) { state = (PowerState)Enum.Parse(typeof(PowerState), (associatedPowerMgmtInstance.GetProperty("PowerState").ToString())); } return state; // return associatedPowerMgmtInstance; } /// /// Get system power management capabilities. /// /// CIM_PowerManagementCapabilities instance public IManagedInstance GetSystemPowerManagementCapabilities() { IManagedReference powerManagementCapabilitiesRef = wsmanClient.NewReference("SELECT * FROM CIM_PowerManagementCapabilities WHERE InstanceID='Intel(r) AMT:PowerManagementCapabilities 0'"); Console.WriteLine("Getting system power management capabilities..."); IManagedInstance powerManagementCapabilitiesInstance = powerManagementCapabilitiesRef.Get(); Params.MessageDisplay_Color("Success.", ConsoleColor.Green); IWsmanItem powerChangeCapabilities = powerManagementCapabilitiesInstance.GetProperty("PowerChangeCapabilities"); Console.Write("\nPower Change Capabilities: "); foreach (IWsmanItem powerChangeCapability in powerChangeCapabilities) { Console.Write("\n * "); switch (Convert.ToUInt32(powerChangeCapability.ToString())) { case 0: Console.Write("Unknown"); break; case 1: Console.Write("Other"); break; case 2: Console.Write("Power Saving Modes Entered Automatically"); break; case 3: Console.Write("Power State Settable"); break; case 4: Console.Write("Power Cycling Supported"); break; case 5: Console.Write("Timed Power On Supported"); break; case 6: Console.Write("Off Hard Power Cycling Supported"); break; case 7: Console.Write("HW Reset Supported"); break; case 8: Console.Write("Graceful Shutdown Supported"); break; } } Console.Write("\n"); return powerManagementCapabilitiesInstance; } /// /// Change system power state. /// /// The desire power state. /// Indicates whether to print extended details about the operation. /// The operation status. public uint ChangeSystemPowerState(PowerState powerState, bool verbose) { Console.WriteLine("Changing System Power State..."); //Wake from power saving state if (powerState == PowerState.WakeFromPowerSaving) { if (verbose) Console.WriteLine("\n Getting the instance of IPS_PowerManagementService"); // Traverse the IPS_PowerManagementService that activates the power state change. IManagedReference IPS_powerManagementRef = wsmanClient.NewReference( "SELECT * FROM IPS_PowerManagementService WHERE Name='Intel(r) AMT Power Management Service'"); IManagedInstance IPS_inputObject = IPS_powerManagementRef.CreateMethodInput("RequestOSPowerSavingStateChange"); IPS_inputObject.SetProperty("OSPowerSavingState", "2"); IManagedReference IPS_computerSystemRef = wsmanClient.NewReference("SELECT * FROM CIM_ComputerSystem WHERE Name='ManagedSystem'"); IPS_inputObject.SetProperty("ManagedElement", IPS_computerSystemRef); IManagedInstance IPS_outputObject = IPS_powerManagementRef.InvokeMethod(IPS_inputObject); IWsmanItem IPS_returnValue = IPS_outputObject.GetProperty("ReturnValue"); if (Convert.ToUInt16(IPS_returnValue.ToString()) != PT_STATUS_SUCCESS) { string error; if (Convert.ToUInt16(IPS_returnValue.ToString()) == PT_STATUS_UNSPECIFIED_ERROR) { Console.WriteLine(STR_UNSPECIFIED_ERROR); return 1; } error = "RequestedPowerStatusChange returned the error code:" + IPS_returnValue.ToString(); Params.MessageDisplay_Color("Failed to change power state...\n" + error, ConsoleColor.Red); throw new Exception(error); } Params.MessageDisplay_Color("Success.", ConsoleColor.Green); return 0; } if (verbose) Console.WriteLine("\n Getting the instance of CIM_PowerManagementService"); // Traverse the CIM_PowereMAnagementService that activates the power state change. IManagedReference powerManagementRef = wsmanClient.NewReference( "SELECT * FROM CIM_PowerManagementService WHERE Name='Intel(r) AMT Power Management Service'"); //Creating an inputObject to perform the necessary changes. IManagedInstance inputObject = powerManagementRef.CreateMethodInput("RequestPowerStateChange"); inputObject.SetProperty("PowerState", ((int)(powerState)).ToString()); // 5 = SoftPowerCycle - other options can also be set, based on the value that is being passed. /* * The supported PowerState values are * 2 (Power Up), 5 (Power Cycle), 8 (Power Down), 10 (Reset) ; * Since AMT 9.0 also 3 (LightSleep), 7 (Hibernate), 11 (DiagnosticInterrupt), 12 (GracefulOff), 15 (GracefulReset). */ IManagedReference computerSystemRef = wsmanClient.NewReference("SELECT * FROM CIM_ComputerSystem WHERE Name='ManagedSystem'"); inputObject.SetProperty("ManagedElement", computerSystemRef); IManagedInstance outputObject = powerManagementRef.InvokeMethod(inputObject); IWsmanItem returnValue = outputObject.GetProperty("ReturnValue"); if (Convert.ToUInt16(returnValue.ToString()) != PT_STATUS_SUCCESS) { string error; if (Convert.ToUInt16(returnValue.ToString()) == PT_STATUS_UNSPECIFIED_ERROR) { Console.WriteLine(STR_UNSPECIFIED_ERROR); return 1; } error = "RequestedPowerStatusChange returned the error code:" + returnValue.ToString(); Params.MessageDisplay_Color("Failed to change power state...\n" + error, ConsoleColor.Red); throw new Exception(error); } Params.MessageDisplay_Color("Success.", ConsoleColor.Green); return 0; } public IManagedInstance RetrieveTheBootConfigurationSettings(bool verbose) { if (verbose) { Console.WriteLine("Getting the Current Boot Config Setting"); } IManagedReference bootConfigSettingRef = wsmanClient.NewReference("SELECT * FROM CIM_BootConfigSetting WHERE InstanceID='Intel(r) AMT: Boot Configuration 0'"); IManagedInstance bootConfigSettingInstance = bootConfigSettingRef.Get(); return bootConfigSettingInstance; } /// /// Display the current boot status. /// /// Indicate whether to print extended details about the operation. public void GetBootDetails(bool verbose) { GetBootDevice(verbose); GetBootSettings(verbose); GetSystemPowerState(); } /// /// Display the current boot device. /// /// Indicate whether to print extended details about the operation. /// AMT_BootSettingData instance. public IManagedInstance GetBootDevice(bool verbose) { Console.WriteLine("Getting Boot Device settings..."); //Get CIM_boot Configuration settings. IManagedReference bootConfigSettingRef = wsmanClient.NewReference("SELECT * FROM CIM_BootConfigSetting WHERE Name='Intel(r) AMT: Boot Configuration 0'"); IManagedInstance bootSourceSettingInstance = null; if (verbose) Console.WriteLine("\n Enumerating instances of CIM_BootOrdered that are connected to CIM_BootConfigSetting"); //Enumerate all CIM_BootOrdered connected to the CIM_BootConfigSetting. Those CIM object are connecting the CIM_BootConfigSetting with the CIM_BootSources IManagedReference orderedComponentRef = wsmanClient.NewReference("CIM_OrderedComponent"); orderedComponentRef.AddSelector("GroupComponent", bootConfigSettingRef); int flag = 0; //traverse to the CIM_OrderedComponent instances that are connected to the CIM_BootConfigSetting foreach (IWsmanItem orderedComponentItem in orderedComponentRef.Enumerate("http://schemas.dtmf.org/wbem/wsman/1/wsman/SelectorFilter", null)) { //for each Instance check if it is associated to the CIM_BootSourceSetting instance. if (orderedComponentItem.Object.GetProperty("PartComponent").IsA("CIM_BootSourceSetting")) { IWsmanItem assignedSequence = orderedComponentItem.Object.GetProperty("AssignedSequence"); if (assignedSequence.ToString().StartsWith("1")) // - Like "1" { flag = 1; //get the CIM_bootSourceSetting object using its EPR bootSourceSettingInstance = orderedComponentItem.Object.GetProperty("PartComponent").Ref.Get(); IWsmanItem instanceId = bootSourceSettingInstance.GetProperty("InstanceID"); if (instanceId.IsNull.Equals(false)) // .ToString().Equals("InstanceID")) { string[] sourceName = instanceId.ToString().Split(new char[] { ':' }); Console.WriteLine(" Boot Device is:" + sourceName[1]); break; } } } } // The boot source is one of the following sources: IDERCD, IDERFloppy, none. if (flag == 0) { //Get the AMT_BootSettingData Ref for retrieving the Boot Device Details. IManagedReference bootSettingDataRef = wsmanClient.NewReference("SELECT * FROM AMT_BootSettingData WHERE InstanceID='Intel(r) AMT:BootSettingData 0'"); IManagedInstance bootSettingDataInstance = bootSettingDataRef.Get(); if (bootSettingDataInstance.GetProperty("UseIDER").ToString() == "true") { Console.WriteLine( bootSettingDataInstance.GetProperty("IDERBootDevice").ToString().Equals( ((byte)IderBootDevice.Floppy).ToString()) ? "Boot Device is: IDER-Floppy" : "Boot Device is: IDER-CD"); } else { Console.WriteLine("\n No boot Device Enabled"); } } Params.MessageDisplay_Color("Success.", ConsoleColor.Green); return bootSourceSettingInstance; } /// /// Display the current boot settings. /// /// Indicate whether to print extended details about the operation. /// AMT_BootSettingData instance. public IManagedInstance GetBootSettings(bool verbose) { //Get the AMT bootsetting Data - where details about the configuration boot are held. IManagedReference bootCapabilitiesObjRef = wsmanClient.NewReference( "SELECT * FROM AMT_BootSettingData WHERE InstanceID='Intel(r) AMT:BootSettingData 0'"); Console.WriteLine("\n Getting the Boot Setting Data "); IManagedInstance bootCapabilitiesObjInstance = bootCapabilitiesObjRef.Get(); Console.WriteLine("\n Boot Settings: "); Console.WriteLine("\t IDER: " + bootCapabilitiesObjInstance.GetProperty("UseIDER")); Console.WriteLine("\t IDER Boot Device: " + bootCapabilitiesObjInstance.GetProperty("IDERBootDevice")); Console.WriteLine("\t SOL: " + bootCapabilitiesObjInstance.GetProperty("UseSOL")); Console.WriteLine("\t Reflash BIOS: " + bootCapabilitiesObjInstance.GetProperty("ReflashBIOS")); Console.WriteLine("\t BIOS setup: " + bootCapabilitiesObjInstance.GetProperty("BIOSSetup")); Console.WriteLine("\t BIOS pause: " + bootCapabilitiesObjInstance.GetProperty("BIOSPause")); Console.WriteLine("\t Firmware verbosity: " + bootCapabilitiesObjInstance.GetProperty("FirmwareVerbosity")); Console.WriteLine("\t Lock power button: " + bootCapabilitiesObjInstance.GetProperty("LockPowerButton")); Console.WriteLine("\t Lock reset button: " + bootCapabilitiesObjInstance.GetProperty("LockResetButton")); Console.WriteLine("\t Lock keyboard: " + bootCapabilitiesObjInstance.GetProperty("LockKeyboard")); Console.WriteLine("\t Lock sleep button: " + bootCapabilitiesObjInstance.GetProperty("LockSleepButton")); Console.WriteLine("\t User password bypass: " + bootCapabilitiesObjInstance.GetProperty("UserPasswordBypass")); Console.WriteLine("\t Forced progress events: " + bootCapabilitiesObjInstance.GetProperty("ForcedProgressEvents")); Console.WriteLine("\t Configuration data reset: " + bootCapabilitiesObjInstance.GetProperty("ConfigurationDataReset")); Console.WriteLine("\t Boot media index: " + bootCapabilitiesObjInstance.GetProperty("BootMediaIndex")); Console.WriteLine("\t Use safe mode: " + bootCapabilitiesObjInstance.GetProperty("UseSafeMode")); if (UtilitiesMethods.CompareVersions(UtilitiesMethods.GetCoreVersion(wsmanClient), "11.0") >= 0) { Console.WriteLine("\t Secure erase: " + bootCapabilitiesObjInstance.GetProperty("SecureErase")); IWsmanItem lastStatusWsmanItem = bootCapabilitiesObjInstance.GetProperty("BIOSLastStatus"); UInt16 status = UInt16.Parse(lastStatusWsmanItem.Item(0).ToString()); UInt16 errorStatus = UInt16.Parse(lastStatusWsmanItem.Item(1).ToString()); switch ((BIOSstatus)status) { case BIOSstatus.Success: Console.WriteLine("\t Last boot status reported by BIOS: {0} - Success", status); break; case BIOSstatus.InProgress: Console.WriteLine("\t Last boot status reported by BIOS: {0} - In Progress", status); break; case BIOSstatus.NotUpdated: Console.WriteLine("\t Last boot status reported by BIOS: {0} - Not Updated", status); break; case BIOSstatus.Failed: Console.WriteLine("\t Last boot status reported by BIOS: {0} - Failed", status); break; default: Console.WriteLine("\t Last boot status reported by BIOS: {0} - Unknown status", status); break; } switch ((BIOSErrorStatus)errorStatus) { case BIOSErrorStatus.SuccessOrInProgress: Console.WriteLine("\t Detailed error status: {0} - Success/In Progress", errorStatus); break; case BIOSErrorStatus.GeneralDriveFailure: Console.WriteLine("\t Detailed error status: {0} - General Drive Failure", errorStatus); break; case BIOSErrorStatus.DrivePasswordOrAuthenticationFailure: Console.WriteLine("\t Detailed error status: {0} - Drive Password/Authentication Failure", errorStatus); break; case BIOSErrorStatus.FeatureNotSupported: Console.WriteLine("\t Detailed error status: {0} - Feature is not supported", errorStatus); break; default: Console.WriteLine("\t Detailed error status: {0} - Unknown error status", errorStatus); break; } } Params.MessageDisplay_Color("Success.", ConsoleColor.Green); return bootCapabilitiesObjInstance; } /// /// Display the boot capabilities. /// /// Indicate whether to print extended details about the operation. /// AMT_BootCapabilities instance. public IManagedInstance GetBootCapabilities(bool verbose) { //Get AMT_BootCapabilities where the data is held using the managed host as EPR and CIM_ElementCapabilities as association. IManagedReference bootCapabilitiesRef = wsmanClient.NewReference("SELECT * FROM AMT_BootCapabilities WHERE InstanceID='Intel(r) AMT:BootCapabilities 0'"); Console.WriteLine("\n Getting the AMT Boot Capabilities"); //Examine the properties of the object. IManagedInstance bootCapabilitiesItem = bootCapabilitiesRef.Get(); Console.WriteLine("\n\t Boot Capabilities"); Console.WriteLine("\t\t IDER: " + bootCapabilitiesItem.GetProperty("IDER")); Console.WriteLine("\t\t SOL: " + bootCapabilitiesItem.GetProperty("SOL")); Console.WriteLine("\t\t BIOS Reflash: " + bootCapabilitiesItem.GetProperty("BIOSReflash")); Console.WriteLine("\t\t BIOS Setup: " + bootCapabilitiesItem.GetProperty("BIOSSetup")); Console.WriteLine("\t\t BIOS Pause: " + bootCapabilitiesItem.GetProperty("BIOSPause")); Console.WriteLine("\t\t Force Pxe Boot: " + bootCapabilitiesItem.GetProperty("ForcePXEBoot")); Console.WriteLine("\t\t Force HardDrive Boot: " + bootCapabilitiesItem.GetProperty("ForceHardDriveBoot")); Console.WriteLine("\t\t Force hard drive safe mode boot: " + bootCapabilitiesItem.GetProperty("ForceHardDriveSafeModeBoot")); Console.WriteLine("\t\t Force diagnostic boot: " + bootCapabilitiesItem.GetProperty("ForceDiagnosticBoot")); Console.WriteLine("\t\t Force CD or DVD boot: " + bootCapabilitiesItem.GetProperty("ForceCDorDVDBoot")); Console.WriteLine("\t\t Verbosity screen blank: " + bootCapabilitiesItem.GetProperty("VerbosityScreenBlank")); Console.WriteLine("\t\t Power button lock: " + bootCapabilitiesItem.GetProperty("PowerButtonLock")); Console.WriteLine("\t\t Reset button lock: " + bootCapabilitiesItem.GetProperty("ResetButtonLock")); Console.WriteLine("\t\t Keyboard lock: " + bootCapabilitiesItem.GetProperty("KeyboardLock")); Console.WriteLine("\t\t Sleep button lock: " + bootCapabilitiesItem.GetProperty("SleepButtonLock")); Console.WriteLine("\t\t User password bypass: " + bootCapabilitiesItem.GetProperty("UserPasswordBypass")); Console.WriteLine("\t\t Forced progress events: " + bootCapabilitiesItem.GetProperty("ForcedProgressEvents")); Console.WriteLine("\t\t Verbosity verbose: " + bootCapabilitiesItem.GetProperty("VerbosityVerbose")); Console.WriteLine("\t\t Verbosity quiet: " + bootCapabilitiesItem.GetProperty("VerbosityQuiet")); Console.WriteLine("\t\t Configuration data reset: " + bootCapabilitiesItem.GetProperty("ConfigurationDataReset")); if (UtilitiesMethods.CompareVersions(UtilitiesMethods.GetCoreVersion(wsmanClient), "11.0") >= 0) Console.WriteLine("\t\t Secure erase: " + bootCapabilitiesItem.GetProperty("SecureErase")); Console.WriteLine("\n"); Params.MessageDisplay_Color("Success.", ConsoleColor.Green); return bootCapabilitiesItem; } /// /// Set the boot source for the next boot. /// /// Reference for the boot source object. /// Indicate whether to print extended details about the operation. public void SetBootOption(IManagedInstance bootSourceSettingInstance, bool verbose) { Console.WriteLine("\n Getting the Current boot Config Setting"); //Retrieve BootSettingData. IManagedReference bootSettingDataRef = wsmanClient.NewReference("SELECT * FROM AMT_BootSettingData WHERE InstanceID='Intel(r) AMT:BootSettingData 0'"); IManagedInstance bootSettingDataInstance = bootSettingDataRef.Get(); bool useIder = false; //setting values of all properties to false bootSettingDataInstance.SetProperty("BIOSPause", "false"); bootSettingDataInstance.SetProperty("BIOSSetup", "false"); bootSettingDataInstance.SetProperty("BootMediaIndex", "0"); // 0 - default boot media is booted. 1 - Primary boot media, 2- secondary boot media, For PXE - property must be 0. bootSettingDataInstance.SetProperty("ConfigurationDataReset", "false"); bootSettingDataInstance.SetProperty("FirmwareVerbosity", "0"); bootSettingDataInstance.SetProperty("ForcedProgressEvents", "false"); if (bootSourceSettingInstance != null && bootSourceSettingInstance.GetProperty("IDERBootDevice").ToString().ToLower() == "1")// 1-CD/DVD, 0- default or floppy { bootSettingDataInstance.SetProperty("IDERBootDevice", "1"); } else { bootSettingDataInstance.SetProperty("IDERBootDevice", "0"); } bootSettingDataInstance.SetProperty("LockKeyboard", "false"); bootSettingDataInstance.SetProperty("LockPowerButton", "false"); bootSettingDataInstance.SetProperty("LockResetButton", "false"); bootSettingDataInstance.SetProperty("LockSleepButton", "false"); bootSettingDataInstance.SetProperty("ReflashBIOS", "false"); bootSettingDataInstance.SetProperty("BIOSSetup", "false"); if (bootSourceSettingInstance != null && bootSourceSettingInstance.GetProperty("UseIDER").ToString().ToLower() == "true") { bootSettingDataInstance.SetProperty("UseIDER", "true"); useIder = true; } else { bootSettingDataInstance.SetProperty("UseIDER", "false"); } bootSettingDataInstance.SetProperty("UseSOL", "false"); bootSettingDataInstance.SetProperty("UseSafeMode", "false"); bootSettingDataInstance.SetProperty("UserPasswordBypass", "false"); bootSettingDataRef.Put(bootSettingDataInstance); Params.MessageDisplay_Color("Success.", ConsoleColor.Green); if (!useIder) ChangeBootOrder(bootSourceSettingInstance); } /// /// Check if the Host CPU has halted unexpectedly. /// /// CIM_Watchdog instance. public IManagedInstance GetCPUState() { Console.WriteLine("Checking if the Host CPU has halted unexpectedly"); IManagedReference watchDogRef = wsmanClient.NewReference("SELECT * FROM CIM_Watchdog WHERE DeviceID='Watchdog 0'"); IManagedInstance watchdogInstance = watchDogRef.Get(); string fwVersion = UtilitiesMethods.GetCoreVersion(wsmanClient); string minVersion = "5.1"; if (UtilitiesMethods.CompareVersions(fwVersion, minVersion) >= 0) { string timeOfLastExpiration = watchdogInstance.GetProperty("TimeOfLastExpiration").ToString(); if (timeOfLastExpiration == "1111-11-11T11:11:11Z") Console.WriteLine("Host CPU has halted unexpectedly."); else Console.WriteLine("Host CPU is healthy."); Params.MessageDisplay_Color("Success.", ConsoleColor.Green); } return watchdogInstance; } /// /// Configure the boot source. /// /// The source for the next boot. /// Indicate whether to print extended details about the operation. public void ConfigBootSource(string bootSource, bool verbose) { Console.WriteLine("Config boot source..."); //Boot sources hard disk, CD , diagnostic, pxe require a change using changeBootSource command on CIM_ConfigBootSetting. // Boot sources IderCD, IderFloppy require an update of AMT_BootSettingData object. // Also, if boot sources hard disk, CD, diagnostic, pxe are configured, no IDER can be set and all BIOS // options in AMT_BootSettingData should be set to false. bool useIder = false; bool deactivateBiosOptions = false; if (verbose) { Console.WriteLine("\n Getting the Boot Setting Data"); } //Get the Intel AMT boot setting data where the data is held. IManagedReference bootSettingDataRef = wsmanClient.NewReference("SELECT * FROM AMT_BootSettingData WHERE InstanceID='Intel(r) AMT:BootSettingData 0'"); //Retrieve an Instance of a Single Resource. IManagedInstance bootSourceSettingInstance = null; // Analyze the user request and decide what methods to use. if (bootSource == null) { Params.MessageDisplay_Color("\nFailed to config source...\nThe boot source should be defined.", ConsoleColor.Red); throw new ArgumentException("bootSource", "The boot source should be defined."); } switch (bootSource) { case SRC_BOOT_NONE: bootSourceSettingInstance = null; break; case SRC_BOOT_HARD_DRIVE: bootSourceSettingInstance = GetBootSourceReference(STR_BOOT_HARD_DRIVE, verbose); deactivateBiosOptions = true; break; case SRC_BOOT_CD_DVD: bootSourceSettingInstance = GetBootSourceReference(STR_BOOT_CD_DVD, verbose); deactivateBiosOptions = true; break; case SRC_BOOT_DIAGNOSTIC: bootSourceSettingInstance = GetBootSourceReference(STR_BOOT_DIAGNOSTIC, verbose); deactivateBiosOptions = true; break; case SRC_BOOT_PXE: bootSourceSettingInstance = GetBootSourceReference(STR_BOOT_PXE, verbose); deactivateBiosOptions = true; break; case SRC_IDER_FLOPPY: bootSourceSettingInstance = bootSettingDataRef.Get(); useIder = true; bootSourceSettingInstance.SetProperty("IDERBootDevice", ((byte)IderBootDevice.Floppy).ToString()); break; case SRC_IDER_CD: bootSourceSettingInstance = bootSettingDataRef.Get(); useIder = true; bootSourceSettingInstance.SetProperty("IDERBootDevice", ((byte)IderBootDevice.CD).ToString()); break; default: Params.MessageDisplay_Color("\nFailed to config source...\nBoot source is not a valid boot source. Please check the usage for details.", ConsoleColor.Red); throw new ArgumentException("Boot source is not a valid boot source. Please check the usage for details"); } if (bootSourceSettingInstance != null) bootSourceSettingInstance.SetProperty("UseIDER", useIder.ToString().ToLower()); if (useIder) { // Set the boot source to the required source. ChangeBootOrder(null); } // Set the IDER status. // In case boot source is harddisk, cd, diagnostic, Pxe set BIOS options to false. if (deactivateBiosOptions) { bootSourceSettingInstance.SetProperty("BIOSPause", bool.FalseString.ToLower()); bootSourceSettingInstance.SetProperty("BIOSSetup", bool.FalseString.ToLower()); bootSourceSettingInstance.SetProperty("ReflashBIOS", bool.FalseString.ToLower()); } if (verbose) { Console.WriteLine("\n Modifying AMT_BootSettingData to adjust the IDER and BIOS statuses"); } // Set the boot source to the required source. SetBootOption(bootSourceSettingInstance, verbose); // Enable the boot configuration for next Intel AMT boot. // This is required in order to activate the setting - only setting // the CIM object won't cause the boot to use them. EnableConfigSettingsToNextRemoteBoot(verbose); Params.MessageDisplay_Color("Success.", ConsoleColor.Green); } public void SetRSE(bool rse, bool verbose) { if (UtilitiesMethods.CompareVersions(UtilitiesMethods.GetCoreVersion(wsmanClient), "11.0") < 0) Console.WriteLine("Set Remote Secure Erase boot flag is not supported Intel AMT versions earlier than 11.0."); else { IManagedReference bootSettingDataRef = wsmanClient.NewReference("SELECT * FROM AMT_BootSettingData WHERE InstanceID='Intel(r) AMT:BootSettingData 0'"); IManagedInstance bootSettingDataInstance = bootSettingDataRef.Get(); bootSettingDataInstance.SetProperty("SecureErase", rse.ToString().ToLower()); bootSettingDataRef.Put(bootSettingDataInstance); Params.MessageDisplay_Color("Success.", ConsoleColor.Green); } } public void ClearBootOptions(bool verbose) { IManagedReference bootSettingDataRef = wsmanClient.NewReference( "SELECT * FROM AMT_BootSettingData WHERE InstanceID='Intel(r) AMT:BootSettingData 0'"); IManagedInstance bootSettingDataInstance = bootSettingDataRef.Get(); bootSettingDataInstance.SetProperty("BIOSPause", "false"); bootSettingDataInstance.SetProperty("BIOSSetup", "false"); bootSettingDataInstance.SetProperty("ConfigurationDataReset", "false"); bootSettingDataInstance.SetProperty("ForcedProgressEvents", "false"); bootSettingDataInstance.SetProperty("LockKeyboard", "false"); bootSettingDataInstance.SetProperty("LockPowerButton", "false"); bootSettingDataInstance.SetProperty("LockResetButton", "false"); bootSettingDataInstance.SetProperty("LockSleepButton", "false"); bootSettingDataInstance.SetProperty("ReflashBIOS", "false"); bootSettingDataInstance.SetProperty("UserPasswordBypass", "false"); bootSettingDataInstance.SetProperty("UseSafeMode", "false"); bootSettingDataInstance.SetProperty("UseSOL", "false"); bootSettingDataInstance.SetProperty("LockSleepButton", "false"); //The Enforce Secure Boot option is enabled in AMT version 8.1 and above. if (UtilitiesMethods.CompareVersions(UtilitiesMethods.GetCoreVersion(wsmanClient), "8.1") >= 0) bootSettingDataInstance.SetProperty("EnforceSecureBoot", "false"); //The Remote Secure Erase option is enabled in AMT version 11.0 and above. if (UtilitiesMethods.CompareVersions(UtilitiesMethods.GetCoreVersion(wsmanClient), "11.0") >= 0) bootSettingDataInstance.SetProperty("SecureErase", "false"); bootSettingDataRef.Put(bootSettingDataInstance); Params.MessageDisplay_Color("Success.", ConsoleColor.Green); } public void SetRSEPassword(string pass, bool verbose) { if (UtilitiesMethods.CompareVersions(UtilitiesMethods.GetCoreVersion(wsmanClient), "11.0") < 0) Console.WriteLine("Set Remote Secure Erase password is not supported Intel AMT versions earlier than 11.0."); else { IManagedReference bootSettingDataRef = wsmanClient.NewReference( "Select * from AMT_BootSettingData WHERE InstanceID='Intel(r) AMT:BootSettingData 0'"); IManagedInstance bootSettingDataInstance = bootSettingDataRef.Get(); bootSettingDataInstance.SetProperty("RSEPassword", pass); bootSettingDataRef.Put(bootSettingDataInstance); Params.MessageDisplay_Color("Success.", ConsoleColor.Green); } } #endregion #region HELP FUNCTIONS public void EnableConfigSettingsToNextRemoteBoot(bool verbose) { IManagedReference bootServiceRef = wsmanClient.NewReference("SELECT * FROM CIM_BootService WHERE Name='Intel(r) AMT Boot Service'"); //Get the CIM_BootConfigSetting where the data is held. IManagedReference bootSettingDataRef = wsmanClient.NewReference("SELECT * FROM CIM_BootConfigSetting WHERE InstanceID='Intel(r) AMT: Boot Configuration 0'"); IWsmanItem returnValue = null; //input, output instances for method IManagedInstance inputObject = null; IManagedInstance outputObject = null; //prepare input object - create method and add properties inputObject = bootServiceRef.CreateMethodInput("SetBootConfigRole"); inputObject.SetProperty("BootConfigSetting", bootSettingDataRef); inputObject.SetProperty("Role", IS_NEXT_USE.ToString()); outputObject = bootServiceRef.InvokeMethod(inputObject); returnValue = outputObject.GetProperty("ReturnValue"); //--------It can be that the InvokeMethod will not throw an exception //but the function did not succeed. //need to ask about the return value if it's equal to 0.------------------------// if (returnValue.ToString().CompareTo("0") != 0) { Params.MessageDisplay_Color("\nFailed to Set boot config role.", ConsoleColor.Red); throw new Exception("Failed to Set boot config role"); } } /// /// Return the EPR of the CIM_bootSourceSetting which corresponds to the given string(instance ID) /// /// /// public IManagedInstance GetBootSourceReference(string sourceInstanceId, bool verbose) { if (verbose) Console.WriteLine("Getting Boot Source Reference..."); if (sourceInstanceId == null) { Params.MessageDisplay_Color("Failed to get the current boot config setting...\nGetBootSourceEORSneworder inputs should not be null!.", ConsoleColor.Red); throw new ArgumentNullException("sourceInstanceID", "getBootSourceEORSneworder inputs should not be null!"); } // IManagedReference bsources = wsmanClient.NewReference("SELECT * FROM CIM_BootSourceSetting WHERE ElementName = 'Intel(r) AMT: Boot Source'"); IManagedReference bootConfigSettingRef = wsmanClient.NewReference("SELECT * FROM CIM_BootConfigSetting WHERE InstanceID='Intel(r) AMT: Boot Configuration 0'"); IManagedReference orderedComponentRef = wsmanClient.NewReference("CIM_OrderedComponent"); orderedComponentRef.AddSelector("GroupComponent", bootConfigSettingRef); //Traverse the CIM_OrderedComponent instances that are connected to the CIM_bootConfigSetting. foreach (IWsmanItem orderedComponentItem in orderedComponentRef.Enumerate("http://schemas.dmtf.org/wbem/wsman/1/wsman/SelectorFilter", null)) { //For each instance, check if it is associated to the CIM_bootSourceSetting Instance. if (orderedComponentItem.Object.GetProperty("PartComponent").IsA("CIM_BootSourceSetting")) { // IWsmanItem assignedSequence = OrderedComponentItem.Object.GetProperty("AssignedSequence"); IWsmanItem assignedSequence = orderedComponentItem.Object.GetProperty("AssignedSequence"); //Get the CIM_BootSourceSetting object using its EPR. IManagedInstance bootSourceSettingInstance = orderedComponentItem.Object.GetProperty("PartComponent").Ref.Get(); IWsmanItem instanceId = bootSourceSettingInstance.GetProperty("InstanceID"); //Return the currently obtained Reference. if (instanceId.ToString().Equals(sourceInstanceId)) { if (verbose) Params.MessageDisplay_Color("Success.", ConsoleColor.Green); return bootSourceSettingInstance; } } } Params.MessageDisplay_Color("\nFailed to get boot source reference...\nRequested CIM_BootSourceSetting does not exist on the machine.", ConsoleColor.Red); throw new Exception("Requested CIM_BootSourceSetting does not exist on the machine"); } /// /// Set boot source for next boot. /// /// Reference to boot source for next boot. private void ChangeBootOrder(IManagedInstance bootSourceSettingInstance) { Console.WriteLine("\nChange Boot Order..."); //Retrieve Boot Configuration Settings IManagedReference bootConfigSettingRef = wsmanClient.NewReference("SELECT * FROM CIM_BootConfigSetting WHERE InstanceID='Intel(r) AMT: Boot Configuration 0'"); IManagedInstance inputObject = null; IWsmanItem returnValue = null; inputObject = bootConfigSettingRef.CreateMethodInput("ChangeBootOrder"); CmdLineArguments Params = new CmdLineArguments(); if (bootSourceSettingInstance != null) { //Setting the requested configuration. string fwVersion = UtilitiesMethods.GetCoreVersion(wsmanClient); if (UtilitiesMethods.CompareVersions(fwVersion, "5.1") < 0) { inputObject.SetProperty("source", bootSourceSettingInstance.ToReference("InstanceID")); } else { inputObject.SetProperty("Source", bootSourceSettingInstance.ToReference("InstanceID")); } } //If set boot source to none - change boot order without input IManagedInstance outputObject = bootConfigSettingRef.InvokeMethod(inputObject); returnValue = outputObject.GetProperty("ReturnValue"); //--------It can be that the InvokeMethod will not throw an exception //but the function did not succeed. //need to ask about the return value if it's equal to 0.------------------------// if (returnValue.ToString().CompareTo("0") != 0) { Params.MessageDisplay_Color("\nFailed to Change Boot Order.", ConsoleColor.Red); throw new Exception("Failed to Change Boot Order"); } Params.MessageDisplay_Color("Success.", ConsoleColor.Green); } public void setRSENextBoot(bool verbose) { if (UtilitiesMethods.CompareVersions(UtilitiesMethods.GetCoreVersion(wsmanClient), "11.0") < 0) { Console.WriteLine("Set Remote Secure Erase boot flag is not supported Intel AMT versions earlier than 11.0."); return; } //Clear boot options ClearBootOptions(verbose); //Set secure erase flag to true in AMT_BootSettingData IManagedReference bootSettingDataRef = wsmanClient.NewReference("SELECT * FROM AMT_BootSettingData WHERE InstanceID='Intel(r) AMT:BootSettingData 0'"); IManagedInstance bootSettingDataInstance = bootSettingDataRef.Get(); bootSettingDataInstance.SetProperty("SecureErase", "true"); bootSettingDataRef.Put(bootSettingDataInstance); //Clearing boot source setting - will set boot source to none IManagedReference bootConfigSettingRef = wsmanClient.NewReference("SELECT * FROM CIM_BootConfigSetting WHERE InstanceID='Intel(r) AMT: Boot Configuration 0'"); IManagedInstance inputObject = null; IWsmanItem returnValue = null; //When invoking ChangeBootOrder without parameters (Boot source reference) then boot source will be set to none inputObject = bootConfigSettingRef.CreateMethodInput("ChangeBootOrder"); IManagedInstance outputObject = bootConfigSettingRef.InvokeMethod(inputObject); returnValue = outputObject.GetProperty("ReturnValue"); if (returnValue.ToString().CompareTo("0") != 0) { Params.MessageDisplay_Color("\nFailed to Change Boot Order.", ConsoleColor.Red); throw new Exception("Failed to Change Boot Order: " + returnValue.ToString()); } // Enable the boot configuration for next Intel AMT boot. // This is required in order to activate the setting - only setting // the CIM object won't cause the boot to use them. EnableConfigSettingsToNextRemoteBoot(verbose); Params.MessageDisplay_Color("Success.", ConsoleColor.Green); } #endregion } }