//---------------------------------------------------------------------------- // // Copyright © 2009-2012, Intel Corporation. All rights reserved. // // File: ConnectionSettings.cs // //---------------------------------------------------------------------------- using System; using System.Windows.Forms; using System.ComponentModel; using System.Text.RegularExpressions; using UCT.Utils; using System.Collections.Generic; using System.Security; using Intel.Management.Wsman; using Common.Utils; namespace UCT.Forms { /// /// Form that treat the connection settings /// public partial class ConnectionSettings : BaseForm { #region - Private Members - private bool _validHost; private bool _validProxyHost; private bool _validUserName; private bool _validPassword; private bool _validCIRA = true; private bool _validTLS = true; private bool _connectionCancel; // Indicate whether the user cancel the conncetion progress bar private string _errorMessage = string.Empty; private ProgressBarWindow _progressWindow; private ConnectionHistory _history; private List _historyList; private Connection _curConnectionInfo; #endregion #region - Constructors - /// /// Default Constructor /// public ConnectionSettings() { InitializeComponent(); // Load the history list InitializeHistory(); // Load the saved connection settings LoadDefaultSettings(); // Disable / Enable the Cira parameters EnableCIRAParams(cbCIRA.Checked); // Validate the input (Hostname, Username, password) ValidateHostName(tbHostName); ValidateUserName(); ValidatePassword(); } private void LoadHistory() { tbHostName.Items.Clear(); foreach (Connection con in _historyList) { tbHostName.Items.Add(con); tbHostName.DisplayMember = "HostName"; } } /// /// Constructor that get ConnectionInfo object and fill the connection data. /// This constructor is used when opening the application via command line and /// specified parameters. /// /// ConnectionInfo object that hold the data public ConnectionSettings(IWsmanConnection conArgs) { InitializeComponent(); InitializeHistory(); string ipAddress = ""; if (conArgs.Address.StartsWith("https")) { ipAddress = conArgs.Address.Substring(8, conArgs.Address.Length - 8); } else if (conArgs.Address.StartsWith("http")) { ipAddress = conArgs.Address.Substring(7, conArgs.Address.Length - 7); } if (ipAddress.Contains(":")) { int index = ipAddress.IndexOf(":"); ipAddress = ipAddress.Substring(0, index); } tbHostName.Text = ipAddress; tbUserName.Text = conArgs.Username; tbPassword.Text = conArgs.Password.ConvertToString(); // Validating and filling TLS parameters if (!conArgs.Address.Contains("https")) { rbNoneTLS.Checked = true; } else { if (null != conArgs.Options.ClientCertificate) { rbMTLS.Checked = true; EnableTLSParams(true); tbCertWithKey.Text = Configuration.CertificateSettings.GetInstance().PersonalCertificate; //to check } else { rbServerTLS.Checked = true; } } // Validating and filling authentication parameters if (conArgs.AuthenticationScheme.CompareTo("Digest") == 0) { rbDigest.Checked = true; } else { rbKerberos.Checked = true; ValidateKerberos(); } tbCertWithKey.Text = Configuration.CertificateSettings.GetInstance().PersonalCertificate; //to check //Validating and filling proxy parameters EnableCIRAParams(cbCIRA.Checked = (!string.IsNullOrEmpty(conArgs.Options.ProxyAddress))); if (!string.IsNullOrEmpty(conArgs.Options.ProxyAddress)) { tbProxyHostName.Text = conArgs.Options.ProxyAddress; int index = conArgs.Options.ProxyAddress.LastIndexOf(":") + 1; string port = conArgs.Options.ProxyAddress.Substring(index, conArgs.Options.ProxyAddress.Length - index); tbProxyPort.Text = port; tbProxyUserName.Text = !string.IsNullOrEmpty(conArgs.Options.ProxyUser) ? conArgs.Options.ProxyUser : null; // Convert password from secure string to comply with wsman dll which supports passwords in SecureString // format only. tbProxyPassword.Text = !string.IsNullOrEmpty(conArgs.Options.ProxyPassword.ConvertToString()) ? conArgs.Options.ProxyPassword.ConvertToString() : null; ValidateCiraParameters(); } } private void InitializeHistory() { // Create history object _history = new ConnectionHistory(); _historyList = _history.LoadConnections(); LoadHistory(); } #endregion #region - Methods - #region SETTINGS AND CONNECTION METHODS /// /// Loading the default settings from the setting file /// private void LoadDefaultSettings() { try { // Write the operation to the log LogManager.WriteOperation(LogLevel.DETAILED, Properties.Resources.LOADING_DEFAULT_SETTINGS, LogInteraction.Information); // Loading and filling the basic connection parameters tbHostName.Text = Properties.Settings.Default.HOST_NAME; tbUserName.Text = Properties.Settings.Default.USER_NAME; rbKerberos.Checked = Properties.Settings.Default.KRB_ENABLE; // Loading and filling TLS parameters if (!(rbServerTLS.Checked = Properties.Settings.Default.TLS_ENABLE) && !(rbMTLS.Checked = Properties.Settings.Default.MTLS_ENABLE)) { rbNoneTLS.Checked = true; } tbCertWithKey.Text = Properties.Settings.Default.CLIENT_CERTIFICATE; rbDigest.Checked = !Properties.Settings.Default.KRB_ENABLE; tbCertWithKey.Text = Properties.Settings.Default.CLIENT_CERTIFICATE; // Loading and filling the basic connection parameters if (Properties.Settings.Default.USE_CIRA) { cbCIRA.Checked = true; tbProxyHostName.Text = Properties.Settings.Default.PROXY_HOSTNAME; tbProxyPort.Text = Properties.Settings.Default.PROXY_PORT; tbProxyUserName.Text = Properties.Settings.Default.PROXY_USERNAME; } } catch { } } /// /// Set the state of "Connect" (Disable/Enable) button according the input validation /// private void SetConnectionState() { if (_validHost && _validCIRA && _validTLS) { if (rbDigest.Checked) { if (_validPassword && _validUserName) { SetButtonStyle(true); } else { SetButtonStyle(false); } } else // Kerberos Authentication { if ((_validPassword && _validUserName) || (tbPassword.Text == string.Empty && tbUserName.Text == string.Empty)) { SetButtonStyle(true); } else { SetButtonStyle(false); } } } else { SetButtonStyle(false); } } /// /// Set the style of "Connect" button (Change his color when button should be grayed out and vice versa) /// /// private void SetButtonStyle(bool isEnable) { btnConnect.Enabled = isEnable; if (isEnable) { btnConnect.ButtonColor = System.Drawing.Color.Black; } else { btnConnect.ButtonColor = System.Drawing.Color.FromArgb(64, 64, 64); } } /// /// Trying to connect to AMT machine /// private void Connect() { try { _connectionCancel = false; LogManager.WriteOperation(LogLevel.BASIC, string.Format(Properties.Resources.CONNECTING_TO, tbHostName.Text), LogInteraction.UserOperation); RetrieveConnectionObjFromGUI(); _progressWindow = new ProgressBarWindow(new ProgressDelegate(ConnectToAMT), Properties.Resources.TRYING_TO_CONNECT, null, string.Format(Properties.Resources.CONNECTING_TO, tbHostName.Text), true, false, false); { if (_progressWindow.ShowDialog(this) == DialogResult.Ignore) { _connectionCancel = true; } this.Refresh(); } if (DialogResult != DialogResult.OK) { LogManager.WriteOperation(LogLevel.BASIC, string.Format(Properties.Resources.FAILED_TO_CONNECT, tbHostName.Text), LogInteraction.Information); _errorMessage = (_errorMessage.Equals(string.Empty)) ? Properties.Resources.CANCEL_CONNECTION_BY_USER : _errorMessage; LogManager.WriteOperation(LogLevel.DETAILED, string.Format(Properties.Resources.EXCEPTION_WAS_THROWN, _errorMessage), LogInteraction.Error); if (DialogResult != DialogResult.Ignore) { AMT_SW_GUI.MessageManager.ShowMessage(_errorMessage, Properties.Resources.CANCEL_CONNECTION_PROGRESS_BAR_MESSAGE, this); } } else { LogManager.WriteOperation(LogLevel.BASIC, string.Format(Properties.Resources.SUCCESSFULLY_CONNECTED_TO, tbHostName.Text), LogInteraction.Connection); Close(); } } catch (Exception ex) { throw new Exception(ex.Message + "Connection Failed"); } } /// /// BackgroundWorker - Running progress bar when trying to connect /// /// /// /// private void ConnectToAMT(BackgroundWorker worker, DoWorkEventArgs e, object[] obj) { try { LogManager.WriteOperation(LogLevel.DETAILED, Properties.Resources.SAVING_PARAMETER_FOR_NEXT_EXECUTION, LogInteraction.Information); if (Configuration.GetInstance().InitWSManClient() != UCT.ConnectionStatus.Connected) { DialogResult = DialogResult.Ignore; return; } if (!_connectionCancel) // Ensure the connection progress didn't stop { if (CertificateUtils.ValidateCertificate()) { Utilities.SaveConfigFile(_curConnectionInfo); this.DialogResult = DialogResult.OK; } else { this.DialogResult = DialogResult.Ignore; } } } catch (Exception ex) { this.DialogResult = DialogResult.Cancel; this._errorMessage = ex.Message; } } #endregion #region EVENT HANDLER METHODS /// /// Validating host name /// /// /// private void tbHostName_TextChanged(object sender, EventArgs e) { _validHost = ValidateHostName(tbHostName); SetConnectionState(); } /// /// Validating proxy host name content /// /// /// private void tbProxyHostName_TextChanged(object sender, EventArgs e) { _validProxyHost = ValidateHostName(tbProxyHostName); ValidateCiraParameters(); } /// /// Validating user name content /// /// /// private void tbUserName_TextChanged(object sender, EventArgs e) { ValidateUserName(); SetConnectionState(); } /// /// Validating password content /// /// /// private void tbPassword_TextChanged(object sender, EventArgs e) { ValidatePassword(); SetConnectionState(); } /// /// Validating proxy parameters /// /// /// private void ProxyParameters_TextChanged(object sender, EventArgs e) { ValidateCiraParameters(); if (!String.IsNullOrEmpty(tbProxyPort.Text)) { try { ushort port = ushort.Parse(tbProxyPort.Text); } catch (Exception) { errorProvider.SetError(tbProxyPort, Properties.Resources.ILLEGAL_PORT_FORMAT); _validCIRA = false; } } SetConnectionState(); } /// /// Use CIRA check box - checked change event /// /// /// private void cbCIRA_CheckedChanged(object sender, EventArgs e) { if (((CheckBox)sender).Checked) { EnableCIRAParams(true); ValidateCiraParameters(); } else { EnableCIRAParams(false); tbProxyHostName.Clear(); tbProxyPort.Clear(); tbProxyUserName.Clear(); tbProxyPassword.Clear(); errorProvider.SetError(tbProxyHostName, String.Empty); errorProvider.SetError(tbProxyUserName, String.Empty); errorProvider.SetError(tbProxyPort, String.Empty); errorProvider.SetError(tbProxyPort, String.Empty); _validCIRA = true; } SetConnectionState(); } /// /// Use TLS check box - checked change event /// /// /// private void rbTLS_CheckedChanged(object sender, EventArgs e) { if (rbMTLS.Checked) { EnableTLSParams(true); cbAcceptSelfSignedCert.Enabled = true; } else { EnableTLSParams(false); errorProvider.SetError(tbCertWithKey, String.Empty); tbCertWithKey.Text = String.Empty; _validTLS = true; if (rbServerTLS.Checked) { cbAcceptSelfSignedCert.Enabled = true; } else { cbAcceptSelfSignedCert.Enabled = false; } } SetConnectionState(); } /// /// "Kerberos" radio button - checked /// /// /// private void rbKerberos_CheckedChanged(object sender, EventArgs e) { if (rbKerberos.Checked) { tbUserName.MaxLength = 512; if (!String.IsNullOrEmpty(tbHostName.Text)) { ValidateHostName(tbHostName); } ValidateKerberos(); } else { tbUserName.MaxLength = 16; ValidateUserName(); ValidatePassword(); } SetConnectionState(); } /// /// "Cancel" button - click event /// /// /// private void btnCancel_Click(object sender, EventArgs e) { LogManager.WriteOperation(LogLevel.BASIC, Properties.Resources.APPLICATION_WAS_TERMINATED_BY_THE_USER, LogInteraction.Information); this.Close(); } /// /// "Connect" button click event /// /// /// private void btnConnect_Click(object sender, EventArgs e) { try { AddConnectionToHistoryList(); Configuration.BasicSettings.GetInstance().AmtHost = tbHostName.Text; Configuration.BasicSettings.GetInstance().AmtPassword = tbPassword.Text.ConvertToSecureString(); Configuration.BasicSettings.GetInstance().AmtUsername = tbUserName.Text; Configuration.BasicSettings.GetInstance().KerberosEnable = rbKerberos.Checked; // TLS parameters Configuration.BasicSettings.GetInstance().TlsEnable = !rbNoneTLS.Checked; Configuration.CertificateSettings.GetInstance().PersonalCertificate = rbMTLS.Checked ? tbCertWithKey.Text : string.Empty; // CIRA parameters Configuration.GetInstance().Basic.CIRAEnable = cbCIRA.Checked; Configuration.ProxySettings.GetInstance().ProxyHostHttp = cbCIRA.Checked ? tbProxyHostName.Text : string.Empty; Configuration.ProxySettings.GetInstance().ProxyPortHttp = cbCIRA.Checked ? ushort.Parse(tbProxyPort.Text) : ushort.MinValue; Configuration.ProxySettings.GetInstance().ProxyUsernameHttp = cbCIRA.Checked ? tbProxyUserName.Text : string.Empty; Configuration.ProxySettings.GetInstance().ProxyPasswordHttp = cbCIRA.Checked ? tbProxyPassword.Text.ConvertToSecureString() : null; //Using Self-Signed certificate Configuration.acceptSelfSignedCert = cbAcceptSelfSignedCert.Checked; Connect(); } catch(Exception ex) { LogManager.WriteOperation(LogLevel.BASIC, string.Format(Properties.Resources.FAILED_TO_CONNECT, tbHostName.Text), LogInteraction.Error); AMT_SW_GUI.MessageManager.ShowErrorMessage(ex.Message, "Connection Failed", this); } } /// /// Add the new machine settings to the history list /// private void AddConnectionToHistoryList() { try { ushort port = 0; if (tbProxyPort.Text != string.Empty) port = (ushort)Convert.ToInt32(tbProxyPort.Text); Connection con = new Connection(tbHostName.Text, tbUserName.Text, rbKerberos.Checked, rbServerTLS.Checked, rbMTLS.Checked, tbCertWithKey.Text, cbCIRA.Checked, tbProxyHostName.Text, port, tbProxyUserName.Text, tbProxyPassword.Text); if (_history.CheckExistingConnectionInfo(con)) { if (AMT_SW_GUI.MessageManager.ShowQuestionMessage("The history list already contains settings for this host.\n" + "Would you like to replace the existing settings?", "Confirm Settings Replace") == DialogResult.Yes) { _history.ReplaceConnectionInfo(con); } } LoadHistory(); } catch(Exception ex) { throw new Exception(ex.Message + "Failed to add connection to history list"); } } /// /// "About user consent tool" link - click event /// /// /// private void linkLabelAboutUCT_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { (new AboutUCT()).ShowDialog(this); } /// /// Button help click /// /// /// private void btnHelp_Click(object sender, EventArgs e) { Utilities.DisplayHelpDocument(this); } /// /// Handel selected index change of the host name combobox /// /// /// private void tbHostName_SelectedIndexChanged(object sender, EventArgs e) { Connection curCon = _historyList[tbHostName.SelectedIndex]; tbUserName.Text = curCon.UserName; rbKerberos.Checked = curCon.KerberosEnable; // Loading and filling TLS parameters if (!(rbServerTLS.Checked = curCon.TLSEnable) && !(rbMTLS.Checked = curCon.MTLSEnable)) { rbNoneTLS.Checked = true; } tbCertWithKey.Text = curCon.ClientCertificate; rbDigest.Checked = !curCon.KerberosEnable; // Loading and filling the basic connection parameters cbCIRA.Checked = curCon.CiraEnable; tbProxyHostName.Text = (curCon.CiraEnable) ? curCon.ProxyHost : string.Empty; tbProxyPort.Text = (curCon.CiraEnable) ? curCon.ProxyPort.ToString() : string.Empty; tbProxyUserName.Text = (curCon.CiraEnable) ? curCon.ProxyUserName : string.Empty; } /// /// Handel click event on the clear all field button /// /// /// private void btnClearFields_Click(object sender, EventArgs e) { tbHostName.Text = tbUserName.Text = tbPassword.Text = tbCertWithKey.Text = tbProxyPassword.Text = tbProxyPort.Text = tbProxyUserName.Text = tbProxyHostName.Text = string.Empty; rbDigest.Checked = rbNoneTLS.Checked = true; cbCIRA.Checked = false; } private delegate void GetParamsFromGUI_D(); private void RetrieveConnectionObjFromGUI() { if (this.InvokeRequired) { this.Invoke(new GetParamsFromGUI_D(RetrieveConnectionObjFromGUI)); } else { ushort port = 0; if (tbProxyPort.Text != string.Empty) port = (ushort)Convert.ToInt32(tbProxyPort.Text); _curConnectionInfo = new Connection(tbHostName.Text, tbUserName.Text, rbKerberos.Checked, rbServerTLS.Checked, rbMTLS.Checked, tbCertWithKey.Text, cbCIRA.Checked, tbProxyHostName.Text, port, tbProxyUserName.Text, tbProxyPassword.Text); } } #endregion #region INPUT VALIDATION /// /// Validate the host name parameter /// /// /// Indicate if the host name is valid or not private bool ValidateHostName(Control host) { bool validHost = true; if (string.IsNullOrEmpty(host.Text.Trim())) { errorProvider.SetError(host, string.Format(Properties.Resources.EMPTY_FIELD_ERROR, Properties.Resources.HOST_STRING)); validHost = false; } else { if (!Utilities.IsValidFQDN(host.Text) && !Utilities.IsValidIPV4(host.Text) && !Utilities.IsValidIPV6(host.Text)) { errorProvider.SetError(host, Properties.Resources.ILLEGAL_ADDRESS_ERROR); validHost = false; } else { errorProvider.SetError(host, String.Empty); validHost = true; } } return validHost; } /// /// Validate the user name parameter /// private void ValidateUserName() { if (rbKerberos.Checked) { ValidateKerberos(); return; } if (string.IsNullOrEmpty(tbUserName.Text.Trim())) { errorProvider.SetError(tbUserName, string.Format(Properties.Resources.EMPTY_FIELD_ERROR, Properties.Resources.USER_NAME_STRING)); _validUserName = false; } else { if (!Utilities.IsValidUserName(tbUserName.Text)) { errorProvider.SetError(tbUserName, Properties.Resources.ILLEGAL_USERNAME_ERROR); _validUserName = false; } else { errorProvider.SetError(tbUserName, String.Empty); _validUserName = true; } } SetConnectionState(); } /// /// Validate the password parameter /// private void ValidatePassword() { if (string.IsNullOrEmpty(tbPassword.Text.Trim())) { if (rbKerberos.Checked) { ValidateKerberos(); } else { if (rbDigest.Checked) { errorProvider.SetError(tbPassword, string.Format(Properties.Resources.EMPTY_FIELD_ERROR, Properties.Resources.PASSWORD_STRING)); _validPassword = false; } else { errorProvider.SetError(tbPassword, String.Empty); } } } else { if (!Utilities.IsStrongPassword(tbPassword.Text)) { errorProvider.SetError(tbPassword, Properties.Resources.ILLEGAL_PASSWORD_ERROR); _validPassword = false; } else { errorProvider.SetError(tbPassword, String.Empty); _validPassword = true; } } SetConnectionState(); } /// /// Validate the kerberos parameter /// private void ValidateKerberos() { if (!String.IsNullOrEmpty(tbUserName.Text) && String.IsNullOrEmpty(tbPassword.Text)) { errorProvider.SetError(tbPassword, string.Format(Properties.Resources.EMPTY_FIELD_ERROR, Properties.Resources.PASSWORD_STRING)); _validPassword = false; } else { errorProvider.SetError(tbPassword, String.Empty); } if (String.IsNullOrEmpty(tbUserName.Text) && !String.IsNullOrEmpty(tbPassword.Text)) { errorProvider.SetError(tbUserName, string.Format(Properties.Resources.EMPTY_FIELD_ERROR, Properties.Resources.USER_NAME_STRING)); _validUserName = false; } else { errorProvider.SetError(tbUserName, String.Empty); } if (!String.IsNullOrEmpty(tbUserName.Text.Trim())) { if (!Regex.IsMatch(tbUserName.Text, Properties.Resources.HOST_NAME_FORMAT)) { errorProvider.SetError(tbUserName, Properties.Resources.ILLEGAL_KERBEROS_HOST_NAME); _validUserName = false; } else { errorProvider.SetError(tbUserName, String.Empty); _validUserName = true; } } SetConnectionState(); } /// /// Validate the TLS parameter /// private void ValidateTLSParams() { _validTLS = true; errorProvider.SetError(tbCertWithKey, String.Empty); SetConnectionState(); } /// /// Validate the CIRA parameter /// private void ValidateCiraParameters() { _validCIRA = true; // Validating CIRA parameters if (String.IsNullOrEmpty(tbProxyHostName.Text.Trim())) { errorProvider.SetError(tbProxyHostName, String.Format(Properties.Resources.EMPTY_FIELD_ERROR, Properties.Resources.PROXY_HOST_NAME_STRING)); _validCIRA = false; } else { errorProvider.SetError(tbProxyHostName, String.Empty); } if (String.IsNullOrEmpty(tbProxyPort.Text.Trim())) { errorProvider.SetError(tbProxyPort, String.Format(Properties.Resources.EMPTY_FIELD_ERROR, Properties.Resources.PROXY_PORT_STRING)); _validProxyHost = ValidateHostName(tbProxyHostName); _validCIRA = false; } else { errorProvider.SetError(tbProxyPort, String.Empty); } if (!String.IsNullOrEmpty(tbProxyUserName.Text.Trim()) && String.IsNullOrEmpty(tbProxyPassword.Text.Trim())) { errorProvider.SetError(tbProxyPassword, String.Format(Properties.Resources.EMPTY_FIELD_ERROR, Properties.Resources.PROXY_PASSWORD_STRING)); _validCIRA = false; } else { errorProvider.SetError(tbProxyPassword, String.Empty); } if (String.IsNullOrEmpty(tbProxyUserName.Text) && !String.IsNullOrEmpty(tbProxyPassword.Text)) { errorProvider.SetError(tbProxyUserName, String.Format(Properties.Resources.EMPTY_FIELD_ERROR, Properties.Resources.PROXY_USER_NAME_STRING)); _validCIRA = false; } else { errorProvider.SetError(tbProxyUserName, String.Empty); } if (!String.IsNullOrEmpty(tbProxyUserName.Text) && !String.IsNullOrEmpty(tbProxyPassword.Text)) { if (!Utilities.IsValidUserName(tbProxyUserName.Text)) { errorProvider.SetError(tbProxyUserName, Properties.Resources.ILLEGAL_USERNAME_ERROR); _validCIRA = false; } else { errorProvider.SetError(tbProxyUserName, String.Empty); } if (!Utilities.IsStrongPassword(tbProxyPassword.Text)) { errorProvider.SetError(tbProxyPassword, Properties.Resources.ILLEGAL_PASSWORD_ERROR); _validCIRA = false; } else { errorProvider.SetError(tbProxyPassword, String.Empty); } } SetConnectionState(); } /// /// Change the TLS controls (e.g certificate text box) to enable/disable /// /// Indicate the state of the controls private void EnableTLSParams(bool enable) { lblCertWithKey.Enabled = enable; tbCertWithKey.Enabled = enable; } /// /// Change the CIRA controls (e.g certificate text box) to enable/disable /// /// Indicate the state of the controls private void EnableCIRAParams(bool enable) { lblCIRAHostName.Enabled = enable; lblCIRAPassword.Enabled = enable; lblCIRAPort.Enabled = enable; lblCIRAUserName.Enabled = enable; tbProxyHostName.Enabled = enable; tbProxyPort.Enabled = enable; tbProxyPassword.Enabled = enable; tbProxyUserName.Enabled = enable; } #endregion #endregion } }