/// <summary> /// Gets the current configuration on the given server and for given URI. /// This issues a GET request to the server. /// </summary> /// <param name="serverSession">Current server session.</param> public CurrentConfigurations(IWSManSession serverSession) { if (serverSession == null) { throw new ArgumentNullException("serverSession"); } this.rootDocument = new XmlDocument(); this.serverSession = serverSession; }
internal string ProcessInput(IWSManEx wsman, string filepath, string operation, string root, Hashtable valueset, IWSManResourceLocator resourceUri, IWSManSession sessionObj) { string outerXml = null; if (string.IsNullOrEmpty(filepath) || valueset != null) { string str = operation; string str1 = str; if (str != null) { if (str1 == "new" || str1 == "invoke") { string str2 = null; string str3 = null; string xmlNs = this.GetXmlNs(resourceUri.resourceUri); if (valueset != null) { foreach (DictionaryEntry dictionaryEntry in valueset) { str2 = string.Concat(str2, "<p:", dictionaryEntry.Key.ToString()); if (dictionaryEntry.Value.ToString() == null) { str2 = string.Concat(str2, " xsi:nil=\"true\""); str3 = " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""; } string[] strArrays = new string[6]; strArrays[0] = str2; strArrays[1] = ">"; strArrays[2] = dictionaryEntry.Value.ToString(); strArrays[3] = "</p:"; strArrays[4] = dictionaryEntry.Key.ToString(); strArrays[5] = ">"; str2 = string.Concat(strArrays); } } string[] strArrays1 = new string[10]; strArrays1[0] = "<p:"; strArrays1[1] = root; strArrays1[2] = " "; strArrays1[3] = xmlNs; strArrays1[4] = str3; strArrays1[5] = ">"; strArrays1[6] = str2; strArrays1[7] = "</p:"; strArrays1[8] = root; strArrays1[9] = ">"; outerXml = string.Concat(strArrays1); } else { if (str1 == "set") { string str4 = sessionObj.Get(resourceUri, 0); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(str4); if (valueset != null) { foreach (DictionaryEntry dictionaryEntry1 in valueset) { string str5 = string.Concat("/*/*[local-name()=\"", dictionaryEntry1.Key, "\"]"); if (dictionaryEntry1.Key.ToString().Equals("location", StringComparison.OrdinalIgnoreCase)) { str5 = string.Concat("/*/*[local-name()=\"", dictionaryEntry1.Key, "\" and namespace-uri() != \"http://schemas.dmtf.org/wbem/wsman/1/base\"]"); } XmlNodeList xmlNodeLists = xmlDocument.SelectNodes(str5); if (xmlNodeLists.Count != 0) { if (xmlNodeLists.Count <= 1) { XmlNode itemOf = xmlNodeLists[0]; if (itemOf.HasChildNodes) { if (itemOf.ChildNodes.Count <= 1) { XmlNode xmlNodes = itemOf.ChildNodes[0]; if (!xmlNodes.NodeType.ToString().Equals("text", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(this._resourceMgr.GetString("NOAttributeMatch")); } } else { throw new ArgumentException(this._resourceMgr.GetString("NOAttributeMatch")); } } if (!string.IsNullOrEmpty(dictionaryEntry1.Key.ToString())) { itemOf.Attributes.RemoveNamedItem("xsi:nil"); itemOf.InnerText = dictionaryEntry1.Value.ToString(); } else { XmlAttribute xmlAttribute = xmlDocument.CreateAttribute(XmlNodeType.Attribute.ToString(), "xsi:nil", "http://www.w3.org/2001/XMLSchema-instance"); xmlAttribute.Value = "true"; itemOf.Attributes.Append(xmlAttribute); itemOf.Value = ""; } } else { throw new ArgumentException(this._resourceMgr.GetString("MultipleResourceMatch")); } } else { throw new ArgumentException(this._resourceMgr.GetString("NoResourceMatch")); } } } outerXml = xmlDocument.OuterXml; } } } return outerXml; } else { if (File.Exists(filepath)) { outerXml = this.ReadFile(filepath); return outerXml; } else { throw new FileNotFoundException(this._resourceMgr.GetString("InvalidFileName")); } } }
protected override void ProcessRecord() { try { IWSManResourceLocator wSManResourceLocator = this.helper.InitializeResourceLocator(this.optionset, this.selectorset, null, null, this.m_wsmanObject, this.resourceuri); this.m_session = this.helper.CreateSessionObject(this.m_wsmanObject, this.Authentication, this.sessionoption, this.Credential, this.connectionStr, this.CertificateThumbprint, this.usessl.IsPresent); string rootNodeName = this.helper.GetRootNodeName(this.helper.WSManOp, wSManResourceLocator.resourceUri, null); string str = this.helper.ProcessInput(this.m_wsmanObject, this.filepath, this.helper.WSManOp, rootNodeName, this.valueset, wSManResourceLocator, this.m_session); try { string str1 = this.m_session.Create(wSManResourceLocator, str, 0); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(str1); base.WriteObject(xmlDocument.DocumentElement); } catch (Exception exception1) { Exception exception = exception1; this.helper.AssertError(exception.Message, false, this.computername); } } finally { if (!string.IsNullOrEmpty(this.m_wsmanObject.Error)) { this.helper.AssertError(this.m_wsmanObject.Error, true, this.resourceuri); } if (!string.IsNullOrEmpty(this.m_session.Error)) { this.helper.AssertError(this.m_session.Error, true, this.resourceuri); } if (this.m_session != null) { this.Dispose(this.m_session); } } }
/// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { try { //create the resourcelocator object IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); //create the session object m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, action); string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session); string resultXml = m_session.Invoke(action, m_resource, input, 0); XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(resultXml); WriteObject(xmldoc.DocumentElement); } finally { if (!String.IsNullOrEmpty(m_wsmanObject.Error)) { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } if (!String.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } if (m_session != null) Dispose(m_session); } }//End ProcessRecord()
internal string ProcessInput(IWSManEx wsman, string filepath, string operation, string root, Hashtable valueset, IWSManResourceLocator resourceUri, IWSManSession sessionObj) { string resultString = null; //if file path is given if (!string.IsNullOrEmpty(filepath) && valueset == null) { if (!File.Exists(filepath)) { throw new FileNotFoundException(_resourceMgr.GetString("InvalidFileName")); } resultString = ReadFile(filepath); return resultString; } switch (operation) { case "new": case "invoke": string parameters = null, nilns = null; string xmlns = GetXmlNs(resourceUri.ResourceUri); //if valueset is given, i.e hashtable if (valueset != null) { foreach (DictionaryEntry entry in valueset) { parameters = parameters + "<p:" + entry.Key.ToString(); if (entry.Value.ToString() == null) { parameters = parameters + " " + ATTR_NIL; nilns = " " + NS_XSI; } parameters = parameters + ">" + entry.Value.ToString() + "</p:" + entry.Key.ToString() + ">"; } } resultString = "<p:" + root + " " + xmlns + nilns + ">" + parameters + "</p:" + root + ">"; break; case "set": string getResult = sessionObj.Get(resourceUri, 0); XmlDocument xmlfile = new XmlDocument(); xmlfile.LoadXml(getResult); string xpathString = null; if (valueset != null) { foreach (DictionaryEntry entry in valueset) { xpathString = @"/*/*[local-name()=""" + entry.Key + @"""]"; if (entry.Key.ToString().Equals("location", StringComparison.OrdinalIgnoreCase)) { //'Ignore cim:Location xpathString = @"/*/*[local-name()=""" + entry.Key + @""" and namespace-uri() != """ + NS_CIMBASE + @"""]"; } XmlNodeList nodes = xmlfile.SelectNodes(xpathString); if (nodes.Count == 0) { throw new ArgumentException(_resourceMgr.GetString("NoResourceMatch")); } else if (nodes.Count > 1) { throw new ArgumentException(_resourceMgr.GetString("MultipleResourceMatch")); } else { XmlNode node = nodes[0]; if (node.HasChildNodes) { if (node.ChildNodes.Count > 1) { throw new ArgumentException(_resourceMgr.GetString("NOAttributeMatch")); } else { XmlNode tmpNode = node.ChildNodes[0];//.Item[0]; if (!tmpNode.NodeType.ToString().Equals("text", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(_resourceMgr.GetString("NOAttributeMatch")); } } } if (string.IsNullOrEmpty(entry.Key.ToString())) { //XmlNode newnode = xmlfile.CreateNode(XmlNodeType.Attribute, ATTR_NIL_NAME, NS_XSI_URI); XmlAttribute newnode = xmlfile.CreateAttribute(XmlNodeType.Attribute.ToString(), ATTR_NIL_NAME, NS_XSI_URI); newnode.Value = "true"; node.Attributes.Append(newnode); //(newnode.Attributes.Item(0).FirstChild ); node.Value = ""; } else { node.Attributes.RemoveNamedItem(ATTR_NIL_NAME); node.InnerText = entry.Value.ToString(); } } }//end for }//end if valueset resultString = xmlfile.OuterXml; break; }//end switch return resultString; }
}//End BeginProcessing() #region private private void QuickConfigRemoting(bool serviceonly) { IWSManSession m_SessionObj = null; try { string transport; IWSManEx wsmanObject = (IWSManEx) new WSManClass(); m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null); string xpathEnabled = string.Empty; string xpathText = string.Empty; string xpathUpdate = string.Empty; string analysisInputXml = string.Empty; string action = string.Empty; string xpathStatus = string.Empty; string xpathResult = string.Empty; if (!usessl) { transport = "http"; } else { transport = "https"; } if (serviceonly) { analysisInputXml = @"<AnalyzeService_INPUT xmlns=""http://schemas.microsoft.com/wbem/wsman/1/config/service""></AnalyzeService_INPUT>"; action = "AnalyzeService"; } else { string openAllProfiles = skipNetworkProfileCheck ? "<Force/>" : String.Empty; analysisInputXml = @"<Analyze_INPUT xmlns=""http://schemas.microsoft.com/wbem/wsman/1/config/service""><Transport>" + transport + "</Transport>" + openAllProfiles + "</Analyze_INPUT>"; action = "Analyze"; } string analysisOutputXml = m_SessionObj.Invoke(action, "winrm/config/service", analysisInputXml, 0); XmlDocument resultopxml = new XmlDocument(); resultopxml.LoadXml(analysisOutputXml); if (serviceonly) { xpathEnabled = "/cfg:AnalyzeService_OUTPUT/cfg:RemotingEnabled"; xpathText = "/cfg:AnalyzeService_OUTPUT/cfg:Results"; xpathUpdate = "/cfg:AnalyzeService_OUTPUT/cfg:EnableService_INPUT"; } else { xpathEnabled = "/cfg:Analyze_OUTPUT/cfg:RemotingEnabled"; xpathText = "/cfg:Analyze_OUTPUT/cfg:Results"; xpathUpdate = "/cfg:Analyze_OUTPUT/cfg:EnableRemoting_INPUT"; } XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable); nsmgr.AddNamespace("cfg", "http://schemas.microsoft.com/wbem/wsman/1/config/service"); string enabled = resultopxml.SelectSingleNode(xpathEnabled, nsmgr).InnerText; XmlNode sourceAttribute = resultopxml.SelectSingleNode(xpathEnabled, nsmgr).Attributes.GetNamedItem("Source"); string source = null; if (sourceAttribute != null) { source = sourceAttribute.Value; } string rxml = ""; if (enabled.Equals("true")) { string Err_Msg = ""; if (serviceonly) { Err_Msg = WSManResourceLoader.GetResourceString("L_QuickConfigNoServiceChangesNeeded_Message"); } else { Err_Msg = WSManResourceLoader.GetResourceString("L_QuickConfigNoChangesNeeded_Message"); } // ArgumentException e = new ArgumentException(Err_Msg); // ErrorRecord er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null); // WriteError(er); WriteObject(Err_Msg); return; } if (!enabled.Equals("false")) { ArgumentException e = new ArgumentException(WSManResourceLoader.GetResourceString("L_QuickConfig_InvalidBool_0_ErrorMessage")); ErrorRecord er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null); WriteError(er); return; } string resultAction = resultopxml.SelectSingleNode(xpathText, nsmgr).InnerText; if (source != null && source.Equals("GPO")) { String Info_Msg = WSManResourceLoader.GetResourceString("L_QuickConfig_RemotingDisabledbyGP_00_ErrorMessage"); Info_Msg += " " + resultAction; ArgumentException e = new ArgumentException(Info_Msg); WriteError(new ErrorRecord(e, "NotSpecified", ErrorCategory.NotSpecified, null)); return; } string inputXml = resultopxml.SelectSingleNode(xpathUpdate, nsmgr).OuterXml; if (resultAction.Equals("") || inputXml.Equals("")) { ArgumentException e = new ArgumentException(WSManResourceLoader.GetResourceString("L_ERR_Message") + WSManResourceLoader.GetResourceString("L_QuickConfig_MissingUpdateXml_0_ErrorMessage")); ErrorRecord er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null); WriteError(er); return; } if (serviceonly) { action = "EnableService"; } else { action = "EnableRemoting"; } rxml = m_SessionObj.Invoke(action, "winrm/config/service", inputXml, 0); XmlDocument finalxml = new XmlDocument(); finalxml.LoadXml(rxml); if (serviceonly) { xpathStatus = "/cfg:EnableService_OUTPUT/cfg:Status"; xpathResult = "/cfg:EnableService_OUTPUT/cfg:Results"; } else { xpathStatus = "/cfg:EnableRemoting_OUTPUT/cfg:Status"; xpathResult = "/cfg:EnableRemoting_OUTPUT/cfg:Results"; } if (finalxml.SelectSingleNode(xpathStatus, nsmgr).InnerText.ToString().Equals("succeeded")) { if (serviceonly) { WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdatedService_Message")); } else { WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdated_Message")); } WriteObject(finalxml.SelectSingleNode(xpathResult, nsmgr).InnerText); } else { helper.AssertError(WSManResourceLoader.GetResourceString("L_ERR_Message") + WSManResourceLoader.GetResourceString("L_QuickConfigUpdateFailed_ErrorMessage"), false, null); } } finally { if (!String.IsNullOrEmpty(m_SessionObj.Error)) { helper.AssertError(m_SessionObj.Error, true, null); } if (m_SessionObj != null) { Dispose(m_SessionObj); } } }
private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsmanResourceLocator, IWSManSession wsmanSession) { string fragment; try { int flags = 0; IWSManEnumerator obj; if (returntype != null) { if (returntype.Equals("object", StringComparison.CurrentCultureIgnoreCase)) { flags = wsmanObject.EnumerationFlagReturnObject(); } else if (returntype.Equals("epr", StringComparison.CurrentCultureIgnoreCase)) { flags = wsmanObject.EnumerationFlagReturnEPR(); } else { flags = wsmanObject.EnumerationFlagReturnObjectAndEPR(); } } if (shallow) { flags |= wsmanObject.EnumerationFlagHierarchyShallow(); } else if (basepropertiesonly) { flags |= wsmanObject.EnumerationFlagHierarchyDeepBasePropsOnly(); } else { flags |= wsmanObject.EnumerationFlagHierarchyDeep(); } if (dialect != null && filter != null) { if (dialect.ToString().Equals(helper.ALIAS_WQL, StringComparison.CurrentCultureIgnoreCase) || dialect.ToString().Equals(helper.URI_WQL_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { fragment = helper.URI_WQL_DIALECT; dialect = new Uri(fragment); } else if (dialect.ToString().Equals(helper.ALIAS_ASSOCIATION, StringComparison.CurrentCultureIgnoreCase) || dialect.ToString().Equals(helper.URI_ASSOCIATION_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { if (associations) { flags |= wsmanObject.EnumerationFlagAssociationInstance(); } else { flags |= wsmanObject.EnumerationFlagAssociatedInstance(); } fragment = helper.URI_ASSOCIATION_DIALECT; dialect = new Uri(fragment); } else if (dialect.ToString().Equals(helper.ALIAS_SELECTOR, StringComparison.CurrentCultureIgnoreCase) || dialect.ToString().Equals(helper.URI_SELECTOR_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { filter = GetFilter(); fragment = helper.URI_SELECTOR_DIALECT; dialect = new Uri(fragment); } obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); } else if (filter != null) { fragment = helper.URI_WQL_DIALECT; dialect = new Uri(fragment); obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); } else { obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, null, flags); } while (!obj.AtEndOfStream) { XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(obj.ReadItem()); WriteObject(xmldoc.FirstChild); } } catch (Exception ex) { ErrorRecord er = new ErrorRecord(ex, "Exception", ErrorCategory.InvalidOperation, null); WriteError(er); } }
private void EnableServerSideSettings() { String query = helper.GetResourceMsgFromResourcetext("CredSSPServerContinueQuery"); String caption = helper.GetResourceMsgFromResourcetext("CredSSPContinueCaption"); if (!force && !ShouldContinue(query, caption)) { return; } IWSManSession m_SessionObj = CreateWSManSession(); if (m_SessionObj == null) { return; } try { //get the credssp node to check if wsman is configured on this machine string result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0); XmlNode node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.Service_CredSSP_XMLNmsp); if (node == null) { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } try { XmlDocument xmldoc = new XmlDocument(); string newxmlcontent = string.Format(CultureInfo.InvariantCulture, @"<cfg:Auth xmlns:cfg=""{0}""><cfg:CredSSP>true</cfg:CredSSP></cfg:Auth>", helper.Service_CredSSP_XMLNmsp); //push the xml string with credssp enabled xmldoc.LoadXml(m_SessionObj.Put(helper.Service_CredSSP_Uri, newxmlcontent, 0)); WriteObject(xmldoc.FirstChild); } catch (COMException) { helper.AssertError(m_SessionObj.Error, true, delegatecomputer); } } finally { if (!String.IsNullOrEmpty(m_SessionObj.Error)) { helper.AssertError(m_SessionObj.Error, true, delegatecomputer); } if (m_SessionObj != null) { Dispose(m_SessionObj); } } }
Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); }
private void DisableClientSideSettings() { WSManHelper helper = new WSManHelper(this); IWSManSession m_SessionObj = CreateWSManSession(); if (m_SessionObj == null) { return; } try { string result = m_SessionObj.Get(helper.CredSSP_RUri, 0); XmlDocument resultopxml = new XmlDocument(); string inputXml = null; resultopxml.LoadXml(result); XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable); nsmgr.AddNamespace("cfg", helper.CredSSP_XMLNmsp); XmlNode xNode = resultopxml.SelectSingleNode(helper.CredSSP_SNode, nsmgr); if (!(xNode == null)) { inputXml = @"<cfg:Auth xmlns:cfg=""http://schemas.microsoft.com/wbem/wsman/1/config/client/auth""><cfg:CredSSP>false</cfg:CredSSP></cfg:Auth>"; } else { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } m_SessionObj.Put(helper.CredSSP_RUri, inputXml, 0); if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) { this.DeleteUserDelegateSettings(); } else { ThreadStart start = new ThreadStart(this.DeleteUserDelegateSettings); Thread thread = new Thread(start); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); } if (!helper.ValidateCreadSSPRegistryRetry(false, null, applicationname)) { helper.AssertError(helper.GetResourceMsgFromResourcetext("DisableCredSSPPolicyValidateError"), false, null); } } catch (System.Xml.XPath.XPathException ex) { ErrorRecord er = new ErrorRecord(ex, "XpathException", ErrorCategory.InvalidOperation, null); WriteError(er); } finally { if (!String.IsNullOrEmpty(m_SessionObj.Error)) { helper.AssertError(m_SessionObj.Error, true, null); } if (m_SessionObj != null) { Dispose(m_SessionObj); } } }
}//End BeginProcessing() /* * /// <summary> * /// This method returns DynamicParameters used for Enable-WSManCredSSP cmdlet. Enable-WSManCredSSP * /// supports -DelegateComputer parameter when -Role is client. * /// </summary> * /// <returns> * /// An object representing the dynamic parameters for the cmdlet or null if there * /// are none. * /// </returns> * object IDynamicParameters.GetDynamicParameters() * { * // return null if the role is not client. * if (!Role.Equals(ClientRole, StringComparison.OrdinalIgnoreCase)) * { * return dynamicParameters; * } * * // Construct attributes for the DelegateComputer parameter * Collection<Attribute> delegateComputerAttributeCollection = new Collection<Attribute>(); * ParameterAttribute paramAttribute = new ParameterAttribute(); * paramAttribute.Mandatory = true; * paramAttribute.Position = 1; * ValidateNotNullOrEmptyAttribute notNullAttribute = new ValidateNotNullOrEmptyAttribute(); * delegateComputerAttributeCollection.Add(paramAttribute); * delegateComputerAttributeCollection.Add(notNullAttribute); * * // Construct the parameter and return. * RuntimeDefinedParameter delegateComputer = new RuntimeDefinedParameter( * DelegateComputerParam, * typeof(string[]), * delegateComputerAttributeCollection); * dynamicParameters.Add(DelegateComputerParam, delegateComputer); * * return dynamicParameters; * * } // GetDynamicParameters*/ #endregion /// <summary> /// /// </summary> /// <exception cref="InvalidOperationException"> /// </exception> private void EnableClientSideSettings() { String query = helper.GetResourceMsgFromResourcetext("CredSSPContinueQuery"); String caption = helper.GetResourceMsgFromResourcetext("CredSSPContinueCaption"); if (!force && !ShouldContinue(query, caption)) { return; } IWSManSession m_SessionObj = CreateWSManSession(); if (m_SessionObj == null) { return; } try { //get the credssp node to check if wsman is configured on this machine string result = m_SessionObj.Get(helper.CredSSP_RUri, 0); XmlNode node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp); if (node == null) { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } // Extract delegateComputer information from dynamic parameters collection //RuntimeDefinedParameter delegateComputerParameter = dynamicParameters[DelegateComputerParam]; //delegatecomputer = (string[])delegateComputerParameter.Value; string newxmlcontent = @"<cfg:Auth xmlns:cfg=""http://schemas.microsoft.com/wbem/wsman/1/config/client/auth""><cfg:CredSSP>true</cfg:CredSSP></cfg:Auth>"; try { XmlDocument xmldoc = new XmlDocument(); //push the xml string with credssp enabled xmldoc.LoadXml(m_SessionObj.Put(helper.CredSSP_RUri, newxmlcontent, 0)); // set the Registry using GroupPolicyObject if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) { this.UpdateCurrentUserRegistrySettings(); } else { ThreadStart start = new ThreadStart(this.UpdateCurrentUserRegistrySettings); Thread thread = new Thread(start); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); } if (helper.ValidateCreadSSPRegistryRetry(true, delegatecomputer, applicationname)) { WriteObject(xmldoc.FirstChild); } else { helper.AssertError(helper.GetResourceMsgFromResourcetext("EnableCredSSPPolicyValidateError"), false, delegatecomputer); } } catch (COMException) { helper.AssertError(m_SessionObj.Error, true, delegatecomputer); } } finally { if (!String.IsNullOrEmpty(m_SessionObj.Error)) { helper.AssertError(m_SessionObj.Error, true, delegatecomputer); } if (m_SessionObj != null) { Dispose(m_SessionObj); } } }
internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationMechanism authentication, SessionOption sessionoption, PSCredential credential, string connectionString, string certificateThumbprint, bool usessl) { ValidateSpecifiedAuthentication(authentication, credential, certificateThumbprint); ////if authentication is given int sessionFlags = 0; if (authentication.ToString() != null) { if (authentication.Equals(AuthenticationMechanism.None)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseNoAuthentication; } if (authentication.Equals(AuthenticationMechanism.Basic)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseBasic | (int)WSManSessionFlags.WSManFlagCredUserNamePassword; } if (authentication.Equals(AuthenticationMechanism.Negotiate)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseNegotiate; } if (authentication.Equals(AuthenticationMechanism.Kerberos)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseKerberos; } if (authentication.Equals(AuthenticationMechanism.Digest)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseDigest | (int)WSManSessionFlags.WSManFlagCredUserNamePassword; } if (authentication.Equals(AuthenticationMechanism.Credssp)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseCredSsp | (int)WSManSessionFlags.WSManFlagCredUserNamePassword; } if (authentication.Equals(AuthenticationMechanism.ClientCertificate)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseClientCertificate; } } IWSManConnectionOptionsEx2 connObject = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions(); if (credential != null) { //connObject = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions(); System.Net.NetworkCredential nwCredential = new System.Net.NetworkCredential(); if (credential.UserName != null) { nwCredential = credential.GetNetworkCredential(); if (String.IsNullOrEmpty(nwCredential.Domain)) { if (authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic)) { connObject.UserName = nwCredential.UserName; } else { // just wanted to not use null domain, empty is actually fine connObject.UserName = "******" + nwCredential.UserName; } } else { connObject.UserName = nwCredential.Domain + "\\" + nwCredential.UserName; } connObject.Password = nwCredential.Password; if (!authentication.Equals(AuthenticationMechanism.Credssp) || !authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagCredUserNamePassword; } } } if (certificateThumbprint != null) { connObject.CertificateThumbprint = certificateThumbprint; sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseClientCertificate; } if (sessionoption != null) { if (sessionoption.ProxyAuthentication != 0) { int ProxyAccessflags = 0; int ProxyAuthenticationFlags = 0; if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyIEConfig)) { ProxyAccessflags = connObject.ProxyIEConfig(); } else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyAutoDetect)) { ProxyAccessflags = connObject.ProxyAutoDetect(); } else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyNoProxyServer)) { ProxyAccessflags = connObject.ProxyNoProxyServer(); } else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyWinHttpConfig)) { ProxyAccessflags = connObject.ProxyWinHttpConfig(); } if (sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Basic)) { ProxyAuthenticationFlags = connObject.ProxyAuthenticationUseBasic(); } else if (sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Negotiate)) { ProxyAuthenticationFlags = connObject.ProxyAuthenticationUseNegotiate(); } else if (sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Digest)) { ProxyAuthenticationFlags = connObject.ProxyAuthenticationUseDigest(); } if (sessionoption.ProxyCredential != null) { try { connObject.SetProxy(ProxyAccessflags, ProxyAuthenticationFlags, sessionoption.ProxyCredential.UserName, sessionoption.ProxyCredential.Password); } catch (Exception ex) { AssertError(ex.Message, false, null); } } else { connObject.SetProxy((int)sessionoption.ProxyAccessType, (int)sessionoption.ProxyAuthentication, null, null); } } if (sessionoption.SkipCACheck) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagSkipCACheck; } if (sessionoption.SkipCNCheck) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagSkipCNCheck; } if (sessionoption.SPNPort > 0) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagEnableSpnServerPort; } if (sessionoption.UseUtf16) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUtf16; } else { //If UseUtf16 is false, then default Encoding is Utf8 sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUtf8; } if (!sessionoption.UseEncryption) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagNoEncryption; } if (sessionoption.SkipRevocationCheck) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagSkipRevocationCheck; } } else { //If SessionOption is null then, default Encoding is Utf8 sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUtf8; } if (usessl) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseSsl; } IWSManSession m_SessionObj = null; try { m_SessionObj = (IWSManSession)wsmanObject.CreateSession(connectionString, sessionFlags, connObject); if (sessionoption != null) { if (sessionoption.OperationTimeout > 0) { m_SessionObj.Timeout = sessionoption.OperationTimeout; } } } catch (COMException ex) { AssertError(ex.Message, false, null); } return(m_SessionObj); }
internal string ProcessInput(IWSManEx wsman, string filepath, string operation, string root, Hashtable valueset, IWSManResourceLocator resourceUri, IWSManSession sessionObj) { string resultString = null; //if file path is given if (!string.IsNullOrEmpty(filepath) && valueset == null) { if (!File.Exists(filepath)) { throw new FileNotFoundException(_resourceMgr.GetString("InvalidFileName")); } resultString = ReadFile(filepath); return(resultString); } switch (operation) { case "new": case "invoke": string parameters = null, nilns = null; string xmlns = GetXmlNs(resourceUri.ResourceUri); //if valueset is given, i.e hashtable if (valueset != null) { foreach (DictionaryEntry entry in valueset) { parameters = parameters + "<p:" + entry.Key.ToString(); if (entry.Value.ToString() == null) { parameters = parameters + " " + ATTR_NIL; nilns = " " + NS_XSI; } parameters = parameters + ">" + entry.Value.ToString() + "</p:" + entry.Key.ToString() + ">"; } } resultString = "<p:" + root + " " + xmlns + nilns + ">" + parameters + "</p:" + root + ">"; break; case "set": string getResult = sessionObj.Get(resourceUri, 0); XmlDocument xmlfile = new XmlDocument(); xmlfile.LoadXml(getResult); string xpathString = null; if (valueset != null) { foreach (DictionaryEntry entry in valueset) { xpathString = @"/*/*[local-name()=""" + entry.Key + @"""]"; if (entry.Key.ToString().Equals("location", StringComparison.OrdinalIgnoreCase)) { //'Ignore cim:Location xpathString = @"/*/*[local-name()=""" + entry.Key + @""" and namespace-uri() != """ + NS_CIMBASE + @"""]"; } XmlNodeList nodes = xmlfile.SelectNodes(xpathString); if (nodes.Count == 0) { throw new ArgumentException(_resourceMgr.GetString("NoResourceMatch")); } else if (nodes.Count > 1) { throw new ArgumentException(_resourceMgr.GetString("MultipleResourceMatch")); } else { XmlNode node = nodes[0]; if (node.HasChildNodes) { if (node.ChildNodes.Count > 1) { throw new ArgumentException(_resourceMgr.GetString("NOAttributeMatch")); } else { XmlNode tmpNode = node.ChildNodes[0]; //.Item[0]; if (!tmpNode.NodeType.ToString().Equals("text", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(_resourceMgr.GetString("NOAttributeMatch")); } } } if (string.IsNullOrEmpty(entry.Key.ToString())) { //XmlNode newnode = xmlfile.CreateNode(XmlNodeType.Attribute, ATTR_NIL_NAME, NS_XSI_URI); XmlAttribute newnode = xmlfile.CreateAttribute(XmlNodeType.Attribute.ToString(), ATTR_NIL_NAME, NS_XSI_URI); newnode.Value = "true"; node.Attributes.Append(newnode); //(newnode.Attributes.Item(0).FirstChild ); node.Value = string.Empty; } else { node.Attributes.RemoveNamedItem(ATTR_NIL_NAME); node.InnerText = entry.Value.ToString(); } } } //end for } //end if valueset resultString = xmlfile.OuterXml; break; }//end switch return(resultString); }
/// <summary> /// Method to begin processing. /// </summary> protected override void BeginProcessing() { // If not running elevated, then throw an "elevation required" error message. WSManHelper.ThrowIfNotAdministrator(); helper = new WSManHelper(this); IWSManSession m_SessionObj = null; try { IWSManEx wsmanObject = (IWSManEx) new WSManClass(); m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null); string result = m_SessionObj.Get(helper.CredSSP_RUri, 0); XmlNode node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp); if (node == null) { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } // The application name MUST be "wsman" as wsman got approval from security // folks who suggested to register the SPN with name "wsman". string applicationname = "wsman"; string credsspResult = GetDelegateSettings(applicationname); if (string.IsNullOrEmpty(credsspResult)) { WriteObject(helper.GetResourceMsgFromResourcetext("NoDelegateFreshCred")); } else { WriteObject(helper.GetResourceMsgFromResourcetext("DelegateFreshCred") + credsspResult); } // Get the server side settings result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0); node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.Service_CredSSP_XMLNmsp); if (node == null) { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } if (node.InnerText.Equals("true", StringComparison.OrdinalIgnoreCase)) { WriteObject(helper.GetResourceMsgFromResourcetext("CredSSPServiceConfigured")); } else { WriteObject(helper.GetResourceMsgFromResourcetext("CredSSPServiceNotConfigured")); } } catch (UnauthorizedAccessException ex) { ErrorRecord er = new ErrorRecord(ex, "UnauthorizedAccess", ErrorCategory.PermissionDenied, null); WriteError(er); } catch (SecurityException ex) { ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.InvalidOperation, null); WriteError(er); } catch (ArgumentException ex) { ErrorRecord er = new ErrorRecord(ex, "InvalidArgument", ErrorCategory.InvalidOperation, null); WriteError(er); } catch (System.Xml.XPath.XPathException ex) { ErrorRecord er = new ErrorRecord(ex, "XPathException", ErrorCategory.InvalidOperation, null); WriteError(er); } finally { if (!string.IsNullOrEmpty(m_SessionObj.Error)) { helper.AssertError(m_SessionObj.Error, true, null); } if (m_SessionObj != null) { Dispose(m_SessionObj); } } }
public void Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); }
private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsmanResourceLocator, IWSManSession wsmanSession) { string uRIWQLDIALECT; IWSManEnumerator wSManEnumerator; try { int num = 0; if (this.returntype != null) { if (!this.returntype.Equals("object", StringComparison.CurrentCultureIgnoreCase)) { if (!this.returntype.Equals("epr", StringComparison.CurrentCultureIgnoreCase)) { num = wsmanObject.EnumerationFlagReturnObjectAndEPR(); } else { num = wsmanObject.EnumerationFlagReturnEPR(); } } else { num = wsmanObject.EnumerationFlagReturnObject(); } } if (!this.shallow) { if (!this.basepropertiesonly) { num = num | wsmanObject.EnumerationFlagHierarchyDeep(); } else { num = num | wsmanObject.EnumerationFlagHierarchyDeepBasePropsOnly(); } } else { num = num | wsmanObject.EnumerationFlagHierarchyShallow(); } if (!(this.dialect != null) || this.filter == null) { if (this.filter == null) { wSManEnumerator = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, this.filter, null, num); } else { uRIWQLDIALECT = this.helper.URI_WQL_DIALECT; this.dialect = new Uri(uRIWQLDIALECT); wSManEnumerator = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, this.filter, this.dialect.ToString(), num); } } else { if (this.dialect.ToString().Equals(this.helper.ALIAS_WQL, StringComparison.CurrentCultureIgnoreCase) || this.dialect.ToString().Equals(this.helper.URI_WQL_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { uRIWQLDIALECT = this.helper.URI_WQL_DIALECT; this.dialect = new Uri(uRIWQLDIALECT); } else { if (this.dialect.ToString().Equals(this.helper.ALIAS_ASSOCIATION, StringComparison.CurrentCultureIgnoreCase) || this.dialect.ToString().Equals(this.helper.URI_ASSOCIATION_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { if (!this.associations) { num = num | wsmanObject.EnumerationFlagAssociatedInstance(); } else { num = num | wsmanObject.EnumerationFlagAssociationInstance(); } uRIWQLDIALECT = this.helper.URI_ASSOCIATION_DIALECT; this.dialect = new Uri(uRIWQLDIALECT); } else { if (this.dialect.ToString().Equals(this.helper.ALIAS_SELECTOR, StringComparison.CurrentCultureIgnoreCase) || this.dialect.ToString().Equals(this.helper.URI_SELECTOR_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { this.filter = this.GetFilter(); uRIWQLDIALECT = this.helper.URI_SELECTOR_DIALECT; this.dialect = new Uri(uRIWQLDIALECT); } } } wSManEnumerator = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, this.filter, this.dialect.ToString(), num); } while (!wSManEnumerator.AtEndOfStream) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(wSManEnumerator.ReadItem()); base.WriteObject(xmlDocument.FirstChild); } } catch (Exception exception1) { Exception exception = exception1; ErrorRecord errorRecord = new ErrorRecord(exception, "Exception", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord); } }
/// <summary> /// Sets up a CIM connection with the remote XenServer /// </summary> public void SetupCIMConnection(string server, string user, string pass) { m_cim_resourceURIBase = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2"; m_wsman = new WSManClass(); IWSManConnectionOptions cOptions = (IWSManConnectionOptions)m_wsman.CreateConnectionOptions(); cOptions.UserName = user; cOptions.Password = pass; int iFlags = m_wsman.SessionFlagUTF8() | m_wsman.SessionFlagUseBasic() | m_wsman.SessionFlagCredUsernamePassword() | m_wsman.SessionFlagNoEncryption(); string hostUri = string.Format("http://{0}:5988", server); m_wsmanSession = (IWSManSession)m_wsman.CreateSession(hostUri, iFlags, cOptions); string identifyResponse = m_wsmanSession.Identify(0); if (!identifyResponse.Contains("Citrix")) throw new Exception("Unknown WS-Management Server" + identifyResponse); }
protected override void ProcessRecord() { WSManHelper wSManHelper = new WSManHelper(this); IWSManEx wSManClass = (IWSManEx)(new WSManClass()); wSManHelper.WSManOp = "remove"; IWSManSession wSManSession = null; try { string str = wSManHelper.CreateConnectionString(this.connectionuri, this.port, this.computername, this.applicationname); if (this.connectionuri != null) { try { string[] strArrays = new string[1]; object[] objArray = new object[4]; objArray[0] = ":"; objArray[1] = this.port; objArray[2] = "/"; objArray[3] = this.applicationname; strArrays[0] = string.Concat(objArray); string[] strArrays1 = this.connectionuri.OriginalString.Split(strArrays, StringSplitOptions.None); string[] strArrays2 = new string[1]; strArrays2[0] = "//"; string[] strArrays3 = strArrays1[0].Split(strArrays2, StringSplitOptions.None); this.computername = strArrays3[1].Trim(); } catch (IndexOutOfRangeException indexOutOfRangeException) { wSManHelper.AssertError(wSManHelper.GetResourceMsgFromResourcetext("NotProperURI"), false, this.connectionuri); } } wSManHelper.InitializeResourceLocator(this.optionset, this.selectorset, null, null, wSManClass, this.resourceuri); wSManSession = wSManHelper.CreateSessionObject(wSManClass, this.Authentication, this.sessionoption, this.Credential, str, this.CertificateThumbprint, this.usessl.IsPresent); string uRIWithFilter = wSManHelper.GetURIWithFilter(this.resourceuri.ToString(), null, this.selectorset, wSManHelper.WSManOp); try { wSManSession.Delete(uRIWithFilter, 0); } catch (Exception exception1) { Exception exception = exception1; wSManHelper.AssertError(exception.Message, false, this.computername); } } finally { if (!string.IsNullOrEmpty(wSManSession.Error)) { wSManHelper.AssertError(wSManSession.Error, true, this.resourceuri); } if (!string.IsNullOrEmpty(wSManClass.Error)) { wSManHelper.AssertError(wSManClass.Error, true, this.resourceuri); } if (wSManSession != null) { this.Dispose(wSManSession); } } }