Example #1
0
 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);
 }
Example #2
0
        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);
        }
Example #3
0
        /// <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);
        }
Example #4
0
        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);
        }
Example #5
0
        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);
        }
        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);
                }
            }
        }
Example #7
0
        /// <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);
                }
            }
        }
Example #8
0
 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);
     }
 }
Example #9
0
		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;
		}
Example #10
0
        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;
        }
        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);
                }
            }
        }