309 lines
10 KiB
C#

//----------------------------------------------------------------------------
//
// Copyright (C) Intel Corporation, 2011 - 2015.
//
// File: CmdLineArguments.cs
//
// Contents: This file is an infrastructure for the entire WSMan sample.
// It contains a parser for the information inputted by the user
// via the command line arguments.
//
//----------------------------------------------------------------------------
using System;
using Intel.Management.Wsman;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Net.Security;
using System.Security;
namespace Connection
{
/// <summary>
/// Creates a Connection to AMT and handles connection errors
/// </summary>
/// <remarks> Demonstrates the liratry task of creating a connection to AMT</remarks>
public class Connection_setup : IDisposable
{
#region PRIVATE_DATA_MEMBERS
// The WSManClient - connection object
public readonly IWsmanConnection wsmanClient = null;
#endregion PRIVATE_DATA_MEMBERS
#region CONSTRUCTORS
/// <summary>
/// Constructor.
/// </summary>
/// Creating the connection to the WSMan Client.
public Connection_setup(string ip, string username, SecureString pwd, bool krb, MpsManager proxy, bool acceptSelfSignedCertificate = false) //IWSManClient wsmanClient)
{
wsmanClient = new WsmanConnection
{
Address = ValidateIP6(ip)
? "http://[" + ip + "]:16992/wsman"
: "http://" + ip + ":16992/wsman"
};
if (krb)
{
wsmanClient.AuthenticationScheme = "Negotiate";
}
else
{
wsmanClient.Username = username;
wsmanClient.Password = pwd;
wsmanClient.AuthenticationScheme = "Digest";
}
if (acceptSelfSignedCertificate)
{
wsmanClient.Options.ServerCertificateValidationCallback = SelfSignedCertificateCallback;
}
//check if proxy enabled - Else enable proxy and set Authentication Scheme to Digest
Proxy_Check(proxy);
proxy?.Dispose();
//check for issues with Connection
Connection_Check();
}
public Connection_setup(string ip, string username, SecureString pwd, string clientCert, bool krb, MpsManager proxy, bool acceptSelfSignedCertificate = false)//IWSManClient wsmanClient)
{
wsmanClient = new WsmanConnection
{
Address = ValidateIP6(ip)
? "https://[" + ip + "]:16993/wsman"
: "https://" + ip + ":16993/wsman"
};
//Client Certificate information retrieved from Store.
wsmanClient.Options.ClientCertificate = !string.IsNullOrEmpty(clientCert) ? getCertFromStore(clientCert)[0] : null;
if (acceptSelfSignedCertificate)
{
wsmanClient.Options.ServerCertificateValidationCallback = SelfSignedCertificateCallback;
}
if (krb)
{
wsmanClient.AuthenticationScheme = "Negotiate";
}
else
{
wsmanClient.Username = username;
wsmanClient.Password = pwd;
wsmanClient.AuthenticationScheme = "Digest";
}
//check if proxy is enabled - else Enable and set authentication scheme to Digest
Proxy_Check(proxy);
Connection_Check();
}
#endregion
#region Public Functions
//Check if proxy is Enabled
//if not Enable Proxy
void Proxy_Check(MpsManager mps)
{
// MpsManager mps = new Intel.Management.Wsman.MpsManager();
if (mps != null)
{
if (mps.Enabled)
{
Console.WriteLine("MPS Enabled:{0} ", mps.Enabled); // -fore Green
}
else
{
Console.WriteLine("MPS Enabled: False");// -fore Red
Console.WriteLine("Enabling Proxy now..");
mps.Enabled = true;
wsmanClient.AuthenticationScheme = "digest";
}
Console.WriteLine("HTTP Proxy: {0}", mps.HttpProxy);
Console.WriteLine("SOCKS Proxy: {0}", mps.SocksProxy);
foreach (string computer in mps.Hosts)
{
Console.WriteLine("AMT Host:{0}", computer);
}
}
}
//end ProxyCheck
//Perform a check for the connection...
void Connection_Check()
{
try
{
wsmanClient.Identify();
}
catch
{
Console.WriteLine("Error Occurred in Wsman Connection!");
throw;
}
}
//Get Client Cert from Store.
public static X509CertificateCollection getCertFromStore(string clientCert)
{
const string OID_LOCAL = "2.16.840.1.113741.1.2.2";
const string OID_REMOTE = "2.16.840.1.113741.1.2.1";
X509CertificateCollection certificatesCollection = new X509CertificateCollection();
// Open CurrentUser cert store
using (X509Store currentUserStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
currentUserStore.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 certificate in currentUserStore.Certificates)
{
if (certificate.Subject.Contains(clientCert))
{
// Checking that the Enhanced Key Usage in the certificate is the one for AMT
foreach (X509Extension extension in certificate.Extensions)
{
if (extension is X509EnhancedKeyUsageExtension usageExtension)
{
foreach (Oid OID in usageExtension.EnhancedKeyUsages)
{
if (OID.Value == OID_REMOTE || OID.Value == OID_LOCAL)
certificatesCollection.Add(certificate);
}
}
}
}
}
}
// Open LocalMachine cert store
using (X509Store localMachineStore = new X509Store(StoreName.My, StoreLocation.LocalMachine))
{
localMachineStore.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 certificate in localMachineStore.Certificates)
{
if (certificate.Subject.Contains(clientCert))
{
// Checking that the Enhanced Key Usage in the certificate is the one for AMT
foreach (X509Extension extension in certificate.Extensions)
{
if (extension is X509EnhancedKeyUsageExtension)
{
X509EnhancedKeyUsageExtension ex = (X509EnhancedKeyUsageExtension)extension;
foreach (Oid OID in ex.EnhancedKeyUsages)
{
if (OID.Value == OID_REMOTE || OID.Value == OID_LOCAL)
certificatesCollection.Add(certificate);
}
}
}
}
}
if (certificatesCollection.Count < 1)
throw new Exception("Can not find appropriate certificate in certificate store");
}
return certificatesCollection;
}
#endregion CONSTRUCTORS
#region Private Functions
public static bool ValidateIP6(string ip)
{
UriHostNameType tmpType = Uri.CheckHostName(ip);
if (tmpType == UriHostNameType.IPv6)
{
return true;
}
return false;
}
private static bool SelfSignedCertificateCallback(X509Certificate certificate, SslPolicyErrors error)
{
//If certificate is self signed, ignore all errors
if (certificate.Subject.Equals(certificate.Issuer))
{
return true;
}
if (error == SslPolicyErrors.None)
{
return true;
}
return false;
}
#endregion
#region IDisposable Implementation
private bool _disposed = false;
/// <summary>
/// Implement IDisposable method
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
wsmanClient?.Dispose();
}
_disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Connection_setup()
{
Dispose(false);
}
#endregion
}
public static class UtilitiesMethods
{
/// <summary>
/// Get FW/Core Version
/// </summary>
public static string GetCoreVersion(IWsmanConnection wsmanClient)
{
IManagedReference softwareIdentityRef = wsmanClient.NewReference("SELECT * FROM CIM_SoftwareIdentity WHERE InstanceID='AMT FW Core Version'");
IManagedInstance softwareIdentityInstance = softwareIdentityRef.Get();
string versionString = softwareIdentityInstance.GetProperty("VersionString").ToString();
return versionString;
}
public static int CompareVersions(string amtVersion, string version)
{
try
{
Version amtVersionToCompare = new Version(amtVersion);
Version versionToCompare = new Version(version);
return amtVersionToCompare.CompareTo(versionToCompare);
}
catch (Exception)
{
throw new Exception("Failed to compare versions. Check if the versions are in a correct format.");
}
}
}
}