internal static Dictionary <string, object> GetSessionObjCache() { try { lock (Sessions.SessionObjCache) { if (!Sessions.SessionObjCache.ContainsKey("localhost")) { IWSManEx wsmanObject = (IWSManEx) new WSManClass(); IWSManSession SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null); Sessions.SessionObjCache.Add("localhost", SessionObj); } } } catch (IOException) { } catch (System.Security.SecurityException) { } catch (System.UnauthorizedAccessException) { } catch (COMException) { } return(Sessions.SessionObjCache); }
private Version GetWSManStackVersion() { Version version = WSManNativeApi.WSMAN_STACK_VERSION; try { IWSManEx ex = (IWSManEx) new WSManClass(); int flags = 0x8000; object connectionOptions = ex.CreateConnectionOptions(); if (connectionOptions != null) { ; string str = ((IWSManSession)ex.CreateSession(null, flags, connectionOptions)).Identify(0); if (!string.IsNullOrEmpty(str)) { XmlDocument document = new XmlDocument(); document.LoadXml(str); XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable); nsmgr.AddNamespace("wsmid", "http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd"); System.Xml.XmlNode node = document.SelectSingleNode("/wsmid:IdentifyResponse/wsmid:ProductVersion", nsmgr); if (node != null) { string innerText = node.InnerText; version = new Version(innerText.Substring(innerText.IndexOf("Stack:", StringComparison.OrdinalIgnoreCase) + 6).Trim()); } } } } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } return(version); }
/// <summary> /// </summary> /// <returns> /// Returns a session object upon successful creation..otherwise /// writes an error using WriteError and returns null. /// </returns> internal IWSManSession CreateWSManSession() { IWSManEx wsmanObject = (IWSManEx) new WSManClass(); IWSManSession m_SessionObj = null; try { m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null); return(m_SessionObj); } catch (COMException ex) { ErrorRecord er = new ErrorRecord(ex, "COMException", ErrorCategory.InvalidOperation, null); WriteError(er); } return(null); }
internal IWSManSession CreateWSManSession() { IWSManSession wSManSession; IWSManEx wSManClass = (IWSManEx)(new WSManClass()); try { IWSManSession wSManSession1 = (IWSManSession)wSManClass.CreateSession(null, 0, null); wSManSession = wSManSession1; } catch (COMException cOMException1) { COMException cOMException = cOMException1; ErrorRecord errorRecord = new ErrorRecord(cOMException, "COMException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord); return(null); } return(wSManSession); }
protected override void ProcessRecord() { WSManHelper wSManHelper = new WSManHelper(this); IWSManEx wSManClass = (IWSManEx)(new WSManClass()); string str = wSManHelper.CreateConnectionString(null, this.port, this.computername, this.applicationname); IWSManSession wSManSession = null; try { try { wSManSession = wSManHelper.CreateSessionObject(wSManClass, this.Authentication, null, this.Credential, str, this.CertificateThumbprint, this.usessl.IsPresent); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(wSManSession.Identify(0)); base.WriteObject(xmlDocument.DocumentElement); } catch (Exception exception1) { try { if (!string.IsNullOrEmpty(wSManSession.Error)) { XmlDocument xmlDocument1 = new XmlDocument(); xmlDocument1.LoadXml(wSManSession.Error); InvalidOperationException invalidOperationException = new InvalidOperationException(xmlDocument1.OuterXml); ErrorRecord errorRecord = new ErrorRecord(invalidOperationException, "WsManError", ErrorCategory.InvalidOperation, this.computername); base.WriteError(errorRecord); } } catch (Exception exception) { } } } finally { if (wSManSession != null) { this.Dispose(wSManSession); } } }
/// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { WSManHelper helper = new WSManHelper(this); IWSManEx wsmanObject = (IWSManEx) new WSManClass(); string connectionStr = string.Empty; connectionStr = helper.CreateConnectionString(null, port, computername, applicationname); IWSManSession m_SessionObj = null; try { m_SessionObj = helper.CreateSessionObject(wsmanObject, Authentication, null, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); m_SessionObj.Timeout = 1000; //1 sec. we are putting this low so that Test-WSMan can return promptly if the server goes unresponsive. XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(m_SessionObj.Identify(0)); WriteObject(xmldoc.DocumentElement); } catch (Exception) { try { if (!string.IsNullOrEmpty(m_SessionObj.Error)) { XmlDocument ErrorDoc = new XmlDocument(); ErrorDoc.LoadXml(m_SessionObj.Error); InvalidOperationException ex = new InvalidOperationException(ErrorDoc.OuterXml); ErrorRecord er = new ErrorRecord(ex, "WsManError", ErrorCategory.InvalidOperation, computername); this.WriteError(er); } } catch (Exception) {} } finally { if (m_SessionObj != null) { Dispose(m_SessionObj); } } }//End BeginProcessing()
/// <summary> /// This method is used by Connect-WsMan Cmdlet and New-Item of WsMan Provider to create connection to WsMan. /// </summary> /// <param name="ParameterSetName"></param> /// <param name="connectionuri"></param> /// <param name="port"></param> /// <param name="computername"></param> /// <param name="applicationname"></param> /// <param name="usessl"></param> /// <param name="authentication"></param> /// <param name="sessionoption"></param> /// <param name="credential"></param> /// <param name="certificateThumbprint"></param> internal void CreateWsManConnection(string ParameterSetName, Uri connectionuri, int port, string computername, string applicationname, bool usessl, AuthenticationMechanism authentication, SessionOption sessionoption, PSCredential credential, string certificateThumbprint) { IWSManEx m_wsmanObject = (IWSManEx) new WSManClass(); try { string connectionStr = CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { // in the format http(s)://server[:port/applicationname] string[] constrsplit = connectionStr.Split(":" + port + "/" + applicationname, StringSplitOptions.None); string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); computername = constrsplit1[1].Trim(); } IWSManSession m_session = CreateSessionObject(m_wsmanObject, authentication, sessionoption, credential, connectionStr, certificateThumbprint, usessl); m_session.Identify(0); string key = computername; if (key == null) { key = "localhost"; } AddtoDictionary(key, m_session); } catch (IndexOutOfRangeException) { AssertError(_resourceMgr.GetString("NotProperURI"), false, connectionuri); } catch (Exception ex) { AssertError(ex.Message, false, computername); } finally { if (!string.IsNullOrEmpty(m_wsmanObject.Error)) { AssertError(m_wsmanObject.Error, true, computername); } } }
public InvokeWSManActionCommand() { this.m_wsmanObject = (IWSManEx)(new WSManClass()); this.connectionStr = string.Empty; }
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; }
public NewWSManInstanceCommand() { this.m_wsmanObject = (IWSManEx)(new WSManClass()); this.connectionStr = string.Empty; }
protected override void BeginProcessing() { WSManHelper.ThrowIfNotAdministrator(); this.helper = new WSManHelper(this); if (Environment.OSVersion.Version.Major >= 6) { WSManHelper.ThrowIfNotAdministrator(); IWSManSession wSManSession = null; try { try { IWSManEx wSManClass = (IWSManEx)(new WSManClass()); wSManSession = (IWSManSession)wSManClass.CreateSession(null, 0, null); string str = wSManSession.Get(this.helper.CredSSP_RUri, 0); XmlNode xmlNode = this.helper.GetXmlNode(str, this.helper.CredSSP_SNode, this.helper.CredSSP_XMLNmsp); if (xmlNode != null) { string str1 = "wsman"; string delegateSettings = this.GetDelegateSettings(str1); if (!string.IsNullOrEmpty(delegateSettings)) { base.WriteObject(string.Concat(this.helper.GetResourceMsgFromResourcetext("DelegateFreshCred"), delegateSettings)); } else { base.WriteObject(this.helper.GetResourceMsgFromResourcetext("NoDelegateFreshCred")); } str = wSManSession.Get(this.helper.Service_CredSSP_Uri, 0); xmlNode = this.helper.GetXmlNode(str, this.helper.CredSSP_SNode, this.helper.Service_CredSSP_XMLNmsp); if (xmlNode != null) { if (!xmlNode.InnerText.Equals("true", StringComparison.OrdinalIgnoreCase)) { base.WriteObject(this.helper.GetResourceMsgFromResourcetext("CredSSPServiceNotConfigured")); } else { base.WriteObject(this.helper.GetResourceMsgFromResourcetext("CredSSPServiceConfigured")); } } else { InvalidOperationException invalidOperationException = new InvalidOperationException(); ErrorRecord errorRecord = new ErrorRecord(invalidOperationException, this.helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord); return; } } else { InvalidOperationException invalidOperationException1 = new InvalidOperationException(); ErrorRecord errorRecord1 = new ErrorRecord(invalidOperationException1, this.helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord1); return; } } catch (UnauthorizedAccessException unauthorizedAccessException1) { UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1; ErrorRecord errorRecord2 = new ErrorRecord(unauthorizedAccessException, "UnauthorizedAccess", ErrorCategory.PermissionDenied, null); base.WriteError(errorRecord2); } catch (SecurityException securityException1) { SecurityException securityException = securityException1; ErrorRecord errorRecord3 = new ErrorRecord(securityException, "SecurityException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord3); } catch (ArgumentException argumentException1) { ArgumentException argumentException = argumentException1; ErrorRecord errorRecord4 = new ErrorRecord(argumentException, "InvalidArgument", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord4); } catch (XPathException xPathException1) { XPathException xPathException = xPathException1; ErrorRecord errorRecord5 = new ErrorRecord(xPathException, "XPathException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord5); } } finally { if (!string.IsNullOrEmpty(wSManSession.Error)) { this.helper.AssertError(wSManSession.Error, true, null); } if (wSManSession != null) { this.Dispose(wSManSession); } } return; } else { string str2 = this.helper.FormatResourceMsgFromResourcetext("CmdletNotAvailable", new object[0]); throw new InvalidOperationException(str2); } }
protected override void ProcessRecord() { IWSManSession wSManSession = null; IWSManEx wSManClass = (IWSManEx)(new WSManClass()); this.helper = new WSManHelper(this); this.helper.WSManOp = "Get"; string str = this.helper.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) { this.helper.AssertError(this.helper.GetResourceMsgFromResourcetext("NotProperURI"), false, this.connectionuri); } } try { IWSManResourceLocator wSManResourceLocator = this.helper.InitializeResourceLocator(this.optionset, this.selectorset, this.fragment, this.dialect, wSManClass, this.resourceuri); wSManSession = this.helper.CreateSessionObject(wSManClass, this.Authentication, this.sessionoption, this.Credential, str, this.CertificateThumbprint, this.usessl.IsPresent); if (this.enumerate) { try { this.ReturnEnumeration(wSManClass, wSManResourceLocator, wSManSession); } catch (Exception exception1) { Exception exception = exception1; this.helper.AssertError(exception.Message, false, this.computername); } } else { XmlDocument xmlDocument = new XmlDocument(); try { xmlDocument.LoadXml(wSManSession.Get(wSManResourceLocator, 0)); } catch (XmlException xmlException1) { XmlException xmlException = xmlException1; this.helper.AssertError(xmlException.Message, false, this.computername); } if (string.IsNullOrEmpty(this.fragment)) { base.WriteObject(xmlDocument.FirstChild); } else { base.WriteObject(string.Concat(xmlDocument.FirstChild.LocalName, "=", xmlDocument.FirstChild.InnerText)); } } } finally { if (!string.IsNullOrEmpty(wSManClass.Error)) { this.helper.AssertError(wSManClass.Error, true, this.resourceuri); } if (!string.IsNullOrEmpty(wSManSession.Error)) { this.helper.AssertError(wSManSession.Error, true, this.resourceuri); } if (wSManSession != null) { this.Dispose(wSManSession); } } }
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); } }
internal IWSManResourceLocator InitializeResourceLocator(Hashtable optionset, Hashtable selectorset, string fragment, Uri dialect, IWSManEx wsmanObj, Uri resourceuri) { string resource = null; if (resourceuri != null) { resource = resourceuri.ToString(); } if (selectorset != null) { resource = resource + "?"; int i = 0; foreach (DictionaryEntry entry in selectorset) { i++; resource = resource + entry.Key.ToString() + "=" + entry.Value.ToString(); if (i < selectorset.Count) { resource += "+"; } } } IWSManResourceLocator m_resource = null; try { m_resource = (IWSManResourceLocator)wsmanObj.CreateResourceLocator(resource); if (optionset != null) { foreach (DictionaryEntry entry in optionset) { if (entry.Value.ToString() == null) { m_resource.AddOption(entry.Key.ToString(), null, 1); } else { m_resource.AddOption(entry.Key.ToString(), entry.Value, 1); } } } if (!string.IsNullOrEmpty(fragment)) { m_resource.FragmentPath = fragment; } if (dialect != null) { m_resource.FragmentDialect = dialect.ToString(); } } catch (COMException ex) { AssertError(ex.Message, false, null); } return(m_resource); }
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 = string.Empty; if (enabled.Equals("true")) { string Err_Msg = string.Empty; 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(string.Empty) || inputXml.Equals(string.Empty)) { 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); } }
internal IWSManResourceLocator InitializeResourceLocator(Hashtable optionset, Hashtable selectorset, string fragment, Uri dialect, IWSManEx wsmanObj, Uri resourceuri) { string resource = null; if (resourceuri != null) { resource = resourceuri.ToString(); } if (selectorset != null) { resource = resource + "?"; int i = 0; foreach (DictionaryEntry entry in selectorset) { i++; resource = resource + entry.Key.ToString() + "=" + entry.Value.ToString(); if (i < selectorset.Count) resource += "+"; } } IWSManResourceLocator m_resource = null; try { m_resource = (IWSManResourceLocator)wsmanObj.CreateResourceLocator(resource); if (optionset != null) { foreach (DictionaryEntry entry in optionset) { if (entry.Value.ToString() == null) { m_resource.AddOption(entry.Key.ToString(), null, 1); } else { m_resource.AddOption(entry.Key.ToString(), entry.Value, 1); } } } if (!string.IsNullOrEmpty(fragment)) { m_resource.FragmentPath = fragment; } if (dialect != null) { m_resource.FragmentDialect = dialect.ToString(); } } catch (COMException ex) { AssertError(ex.Message, false, null); } return m_resource; }
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; }
private void QuickConfigRemoting(bool serviceonly) { string str; string str1; string str2; string str3; string str4; string str5; string str6; string str7; string resourceString; string empty; IWSManSession wSManSession = null; try { IWSManEx wSManClass = (IWSManEx)(new WSManClass()); wSManSession = (IWSManSession)wSManClass.CreateSession(null, 0, null); if (this.usessl) { str = "https"; } else { str = "http"; } if (!serviceonly) { if (this.skipNetworkProfileCheck) { empty = "<Force/>"; } else { empty = string.Empty; } string str8 = empty; string[] strArrays = new string[5]; strArrays[0] = "<Analyze_INPUT xmlns=\"http://schemas.microsoft.com/wbem/wsman/1/config/service\"><Transport>"; strArrays[1] = str; strArrays[2] = "</Transport>"; strArrays[3] = str8; strArrays[4] = "</Analyze_INPUT>"; str4 = string.Concat(strArrays); str5 = "Analyze"; } else { str4 = "<AnalyzeService_INPUT xmlns=\"http://schemas.microsoft.com/wbem/wsman/1/config/service\"></AnalyzeService_INPUT>"; str5 = "AnalyzeService"; } string str9 = wSManSession.Invoke(str5, "winrm/config/service", str4, 0); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(str9); if (!serviceonly) { str1 = "/cfg:Analyze_OUTPUT/cfg:RemotingEnabled"; str2 = "/cfg:Analyze_OUTPUT/cfg:Results"; str3 = "/cfg:Analyze_OUTPUT/cfg:EnableRemoting_INPUT"; } else { str1 = "/cfg:AnalyzeService_OUTPUT/cfg:RemotingEnabled"; str2 = "/cfg:AnalyzeService_OUTPUT/cfg:Results"; str3 = "/cfg:AnalyzeService_OUTPUT/cfg:EnableService_INPUT"; } XmlNamespaceManager xmlNamespaceManagers = new XmlNamespaceManager(xmlDocument.NameTable); xmlNamespaceManagers.AddNamespace("cfg", "http://schemas.microsoft.com/wbem/wsman/1/config/service"); string innerText = xmlDocument.SelectSingleNode(str1, xmlNamespaceManagers).InnerText; XmlNode namedItem = xmlDocument.SelectSingleNode(str1, xmlNamespaceManagers).Attributes.GetNamedItem("Source"); string value = null; if (namedItem != null) { value = namedItem.Value; } if (!innerText.Equals("true")) { if (innerText.Equals("false")) { string innerText1 = xmlDocument.SelectSingleNode(str2, xmlNamespaceManagers).InnerText; if (value == null || !value.Equals("GPO")) { string outerXml = xmlDocument.SelectSingleNode(str3, xmlNamespaceManagers).OuterXml; if (innerText1.Equals("") || outerXml.Equals("")) { ArgumentException argumentException = new ArgumentException(string.Concat(WSManResourceLoader.GetResourceString("L_ERR_Message"), WSManResourceLoader.GetResourceString("L_QuickConfig_MissingUpdateXml_0_ErrorMessage"))); ErrorRecord errorRecord = new ErrorRecord(argumentException, "InvalidOperation", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord); } else { if (!serviceonly) { str5 = "EnableRemoting"; } else { str5 = "EnableService"; } string str10 = wSManSession.Invoke(str5, "winrm/config/service", outerXml, 0); XmlDocument xmlDocument1 = new XmlDocument(); xmlDocument1.LoadXml(str10); if (!serviceonly) { str6 = "/cfg:EnableRemoting_OUTPUT/cfg:Status"; str7 = "/cfg:EnableRemoting_OUTPUT/cfg:Results"; } else { str6 = "/cfg:EnableService_OUTPUT/cfg:Status"; str7 = "/cfg:EnableService_OUTPUT/cfg:Results"; } if (!xmlDocument1.SelectSingleNode(str6, xmlNamespaceManagers).InnerText.ToString().Equals("succeeded")) { this.helper.AssertError(string.Concat(WSManResourceLoader.GetResourceString("L_ERR_Message"), WSManResourceLoader.GetResourceString("L_QuickConfigUpdateFailed_ErrorMessage")), false, null); } else { if (!serviceonly) { base.WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdated_Message")); } else { base.WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdatedService_Message")); } base.WriteObject(xmlDocument1.SelectSingleNode(str7, xmlNamespaceManagers).InnerText); } } } else { string resourceString1 = WSManResourceLoader.GetResourceString("L_QuickConfig_RemotingDisabledbyGP_00_ErrorMessage"); resourceString1 = string.Concat(resourceString1, " ", innerText1); ArgumentException argumentException1 = new ArgumentException(resourceString1); base.WriteError(new ErrorRecord(argumentException1, "NotSpecified", ErrorCategory.NotSpecified, null)); } } else { ArgumentException argumentException2 = new ArgumentException(WSManResourceLoader.GetResourceString("L_QuickConfig_InvalidBool_0_ErrorMessage")); ErrorRecord errorRecord1 = new ErrorRecord(argumentException2, "InvalidOperation", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord1); } } else { if (!serviceonly) { resourceString = WSManResourceLoader.GetResourceString("L_QuickConfigNoChangesNeeded_Message"); } else { resourceString = WSManResourceLoader.GetResourceString("L_QuickConfigNoServiceChangesNeeded_Message"); } base.WriteObject(resourceString); } } finally { if (!string.IsNullOrEmpty(wSManSession.Error)) { this.helper.AssertError(wSManSession.Error, true, null); } if (wSManSession != null) { this.Dispose(wSManSession); } } }
protected override void ProcessRecord() { IWSManEx wSManClass = (IWSManEx)(new WSManClass()); this.helper = new WSManHelper(this); this.helper.WSManOp = "set"; IWSManSession wSManSession = null; if (this.dialect != null) { if (this.dialect.ToString().Equals(this.helper.ALIAS_WQL, StringComparison.CurrentCultureIgnoreCase)) { this.dialect = new Uri(this.helper.URI_WQL_DIALECT); } if (this.dialect.ToString().Equals(this.helper.ALIAS_SELECTOR, StringComparison.CurrentCultureIgnoreCase)) { this.dialect = new Uri(this.helper.URI_SELECTOR_DIALECT); } if (this.dialect.ToString().Equals(this.helper.ALIAS_ASSOCIATION, StringComparison.CurrentCultureIgnoreCase)) { this.dialect = new Uri(this.helper.URI_ASSOCIATION_DIALECT); } } try { string str = this.helper.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) { this.helper.AssertError(this.helper.GetResourceMsgFromResourcetext("NotProperURI"), false, this.connectionuri); } } IWSManResourceLocator wSManResourceLocator = this.helper.InitializeResourceLocator(this.optionset, this.selectorset, this.fragment, this.dialect, wSManClass, this.resourceuri); wSManSession = this.helper.CreateSessionObject(wSManClass, this.Authentication, this.sessionoption, this.Credential, str, this.CertificateThumbprint, this.usessl.IsPresent); string rootNodeName = this.helper.GetRootNodeName(this.helper.WSManOp, wSManResourceLocator.resourceUri, null); string str1 = this.helper.ProcessInput(wSManClass, this.filepath, this.helper.WSManOp, rootNodeName, this.valueset, wSManResourceLocator, wSManSession); XmlDocument xmlDocument = new XmlDocument(); try { xmlDocument.LoadXml(wSManSession.Put(wSManResourceLocator, str1, 0)); } catch (XmlException xmlException1) { XmlException xmlException = xmlException1; this.helper.AssertError(xmlException.Message, false, this.computername); } if (string.IsNullOrEmpty(this.fragment)) { base.WriteObject(xmlDocument.DocumentElement); } else { if (xmlDocument.DocumentElement.ChildNodes.Count > 0) { foreach (XmlNode childNode in xmlDocument.DocumentElement.ChildNodes) { if (!childNode.Name.Equals(this.fragment, StringComparison.CurrentCultureIgnoreCase)) { continue; } base.WriteObject(string.Concat(childNode.Name, " = ", childNode.InnerText)); } } } } finally { if (!string.IsNullOrEmpty(wSManClass.Error)) { this.helper.AssertError(wSManClass.Error, true, this.resourceuri); } if (!string.IsNullOrEmpty(wSManSession.Error)) { this.helper.AssertError(wSManSession.Error, true, this.resourceuri); } if (wSManSession != null) { this.Dispose(wSManSession); } } }
/// <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". const 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); } } }
internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationMechanism authentication, SessionOption sessionoption, PSCredential credential, string connectionString, string certificateThumbprint, bool usessl) { WSManHelper.ValidateSpecifiedAuthentication(authentication, credential, certificateThumbprint); int num = 0; if (authentication.ToString() != null) { if (authentication.Equals(AuthenticationMechanism.None)) { num = num | 0x8000; } if (authentication.Equals(AuthenticationMechanism.Basic)) { num = num | 0x40000 | 0x1000; } if (authentication.Equals(AuthenticationMechanism.Negotiate)) { num = num | 0x20000; } if (authentication.Equals(AuthenticationMechanism.Kerberos)) { num = num | 0x80000; } if (authentication.Equals(AuthenticationMechanism.Digest)) { num = num | 0x10000 | 0x1000; } if (authentication.Equals(AuthenticationMechanism.Credssp)) { num = num | 0x1000000 | 0x1000; } if (authentication.Equals(AuthenticationMechanism.ClientCertificate)) { num = num | 0x200000; } } IWSManConnectionOptionsEx2 userName = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions(); if (credential != null) { if (credential.UserName != null) { NetworkCredential networkCredential = credential.GetNetworkCredential(); if (!string.IsNullOrEmpty(networkCredential.Domain)) { userName.UserName = string.Concat(networkCredential.Domain, "\\", networkCredential.UserName); } else { if (authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic)) { userName.UserName = networkCredential.UserName; } else { userName.UserName = string.Concat("\\", networkCredential.UserName); } } userName.Password = networkCredential.Password; if (!authentication.Equals(AuthenticationMechanism.Credssp) || !authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic)) { num = num | 0x1000; } } } if (certificateThumbprint != null) { userName.CertificateThumbprint = certificateThumbprint; num = num | 0x200000; } if (sessionoption == null) { num = num | 1; } else { if (sessionoption.ProxyAuthentication != 0) { int num1 = 0; int num2 = 0; if (!sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyIEConfig)) { if (!sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyAutoDetect)) { if (!sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyNoProxyServer)) { if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyWinHttpConfig)) { num1 = userName.ProxyWinHttpConfig(); } } else { num1 = userName.ProxyNoProxyServer(); } } else { num1 = userName.ProxyAutoDetect(); } } else { num1 = userName.ProxyIEConfig(); } if (!sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Basic)) { if (!sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Negotiate)) { if (sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Digest)) { num2 = userName.ProxyAuthenticationUseDigest(); } } else { num2 = userName.ProxyAuthenticationUseNegotiate(); } } else { num2 = userName.ProxyAuthenticationUseBasic(); } if (sessionoption.ProxyCredential == null) { userName.SetProxy((int)sessionoption.ProxyAccessType, (int)sessionoption.ProxyAuthentication, null, null); } else { try { userName.SetProxy(num1, num2, sessionoption.ProxyCredential.UserName, sessionoption.ProxyCredential.Password); } catch (Exception exception1) { Exception exception = exception1; this.AssertError(exception.Message, false, null); } } } if (sessionoption.SkipCACheck) { num = num | 0x2000; } if (sessionoption.SkipCNCheck) { num = num | 0x4000; } if (sessionoption.SPNPort > 0) { num = num | 0x400000; } if (!sessionoption.UseUtf16) { num = num | 1; } else { num = num | 0x800000; } if (!sessionoption.UseEncryption) { num = num | 0x100000; } if (sessionoption.SkipRevocationCheck) { num = num | 0x2000000; } } if (usessl) { num = num | 0x8000000; } IWSManSession operationTimeout = null; try { operationTimeout = (IWSManSession)wsmanObject.CreateSession(connectionString, num, userName); if (sessionoption != null && sessionoption.OperationTimeout > 0) { operationTimeout.Timeout = sessionoption.OperationTimeout; } } catch (COMException cOMException1) { COMException cOMException = cOMException1; this.AssertError(cOMException.Message, false, null); } return operationTimeout; }
internal IWSManResourceLocator InitializeResourceLocator(Hashtable optionset, Hashtable selectorset, string fragment, Uri dialect, IWSManEx wsmanObj, Uri resourceuri) { string str = null; if (resourceuri != null) { str = resourceuri.ToString(); } if (selectorset != null) { str = string.Concat(str, "?"); int num = 0; foreach (DictionaryEntry dictionaryEntry in selectorset) { num++; str = string.Concat(str, dictionaryEntry.Key.ToString(), "=", dictionaryEntry.Value.ToString()); if (num >= selectorset.Count) { continue; } str = string.Concat(str, "+"); } } IWSManResourceLocator wSManResourceLocator = null; try { wSManResourceLocator = (IWSManResourceLocator)wsmanObj.CreateResourceLocator(str); if (optionset != null) { foreach (DictionaryEntry dictionaryEntry1 in optionset) { if (dictionaryEntry1.Value.ToString() != null) { wSManResourceLocator.AddOption(dictionaryEntry1.Key.ToString(), dictionaryEntry1.Value, 1); } else { wSManResourceLocator.AddOption(dictionaryEntry1.Key.ToString(), null, 1); } } } if (!string.IsNullOrEmpty(fragment)) { wSManResourceLocator.FragmentPath = fragment; } if (dialect != null) { wSManResourceLocator.FragmentDialect = dialect.ToString(); } } catch (COMException cOMException1) { COMException cOMException = cOMException1; this.AssertError(cOMException.Message, false, null); } return wSManResourceLocator; }
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")); } } }
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); }
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); }
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); } } }