Exemple #1
0
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo = null;
                switch (ParameterSetName)
                {
                case "NoKey":
                    WriteVerbose("Using SSH Username and Password authentication for connection.");
                    var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.UserName);
                    connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer,
                                                                                _port,
                                                                                _credential,
                                                                                _proxyserver,
                                                                                _proxytype,
                                                                                _proxyport,
                                                                                _proxycredential,
                                                                                kIconnectInfo);

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                            {
                                prompt.Response = _credential.GetNetworkCredential().Password;
                            }
                        }
                    };
                    break;

                case "Key":
                    ProviderInfo provider;
                    var          pathinfo      = GetResolvedProviderPathFromPSPath(_keyfile, out provider);
                    var          localfullPath = pathinfo[0];
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               localfullPath,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               _proxycredential);
                    break;

                case "KeyString":
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               _keystring,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               _proxycredential);
                    break;

                default:
                    break;
                }

                //Ceate instance of SSH Client with connection info
                var client = new ScpClient(connectInfo);


                // Handle host key
                if (_force)
                {
                    WriteWarning("Host key is not being verified since Force switch is used.");
                }
                else
                {
                    var computer1 = computer;
                    client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                    {
                        var sb = new StringBuilder();
                        foreach (var b in e.FingerPrint)
                        {
                            sb.AppendFormat("{0:x}:", b);
                        }
                        var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                        if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                        {
                            Host.UI.WriteVerboseLine("Fingerprint for " + computer1 + ": " + fingerPrint);
                        }

                        if (_sshHostKeys.ContainsKey(computer1))
                        {
                            if (_sshHostKeys[computer1] == fingerPrint)
                            {
                                if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                                {
                                    Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1);
                                }
                                e.CanTrust = true;
                            }
                            else
                            {
                                e.CanTrust = false;
                            }
                        }
                        else
                        {
                            if (_errorOnUntrusted)
                            {
                                e.CanTrust = false;
                            }
                            else
                            {
                                int choice;
                                if (_acceptkey)
                                {
                                    choice = 0;
                                }
                                else
                                {
                                    var choices = new Collection <ChoiceDescription>
                                    {
                                        new ChoiceDescription("Y"),
                                        new ChoiceDescription("N")
                                    };

                                    choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);
                                }
                                if (choice == 0)
                                {
                                    var keymng = new TrustedKeyMng();
                                    keymng.SetKey(computer1, fingerPrint);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    e.CanTrust = false;
                                }
                            }
                        }
                    };
                }
                try
                {
                    // Set the connection timeout
                    client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                    // Connect to host using Connection info
                    client.Connect();
                    //client.BufferSize = 1024;

                    if (_noProgress == false)
                    {
                        var counter = 0;
                        // Print progess of download.
                        client.Uploading += delegate(object sender, ScpUploadEventArgs e)
                        {
                            if (e.Size != 0)
                            {
                                counter++;

                                if (counter > 900)
                                {
                                    var percent = Convert.ToInt32((e.Uploaded * 100) / e.Size);

                                    if (percent == 100)
                                    {
                                        return;
                                    }

                                    var progressRecord = new ProgressRecord(1,
                                                                            "Uploading " + e.Filename,
                                                                            String.Format("{0} Bytes Uploaded of {1}",
                                                                                          e.Uploaded, e.Size))
                                    {
                                        PercentComplete = percent
                                    };

                                    Host.UI.WriteProgress(1, progressRecord);
                                    counter = 0;
                                }
                            }
                        };
                    }
                }
                catch (Renci.SshNet.Common.SshConnectionException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Renci.SshNet.Common.SshOperationTimeoutException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationTimeout, client);
                    WriteError(erec);
                }
                catch (Renci.SshNet.Common.SshAuthenticationException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Exception e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                    WriteError(erec);
                }
                if (client.IsConnected)
                {
                    WriteVerbose("Connection successful");


                    // Resolve the path even if a relative one is given.
                    ProviderInfo provider;
                    var          pathinfo      = GetResolvedProviderPathFromPSPath(_localfile, out provider);
                    var          localfullPath = pathinfo[0];

                    if (File.Exists(@localfullPath))
                    {
                        try
                        {
                            WriteVerbose("Uploading " + localfullPath);
                            var fil            = new FileInfo(@localfullPath);
                            var remoteFullpath = RemotePath.TrimEnd(new[] { '/' }) + "/" + fil.Name;
                            client.Upload(fil, remoteFullpath);

                            client.Disconnect();
                        }
                        catch (Exception e)
                        {
                            ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                            WriteError(erec);
                        }
                    }
                    else
                    {
                        var ex = new FileNotFoundException("File to upload " + localfullPath + " was not found.");

                        WriteError(new ErrorRecord(ex,
                                                   "File to upload " + localfullPath + " was not found.",
                                                   ErrorCategory.InvalidArgument,
                                                   localfullPath));
                    }
                }
            }
        } // End process record
Exemple #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PowerShellProcessInstance"/> class. Initializes the underlying dotnet process class.
        /// </summary>
        /// <param name="powerShellVersion">Specifies the version of powershell.</param>
        /// <param name="credential">Specifies a user account credentials.</param>
        /// <param name="initializationScript">Specifies a script that will be executed when the powershell process is initialized.</param>
        /// <param name="useWow64">Specifies if the powershell process will be 32-bit.</param>
        /// <param name="workingDirectory">Specifies the initial working directory for the new powershell process.</param>
        public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64, string workingDirectory)
        {
            string exePath = PwshExePath;
            bool   startingWindowsPowerShell51 = false;

#if !UNIX
            // if requested PS version was "5.1" then we start Windows PS instead of PS Core
            startingWindowsPowerShell51 = (powerShellVersion != null) && (powerShellVersion.Major == 5) && (powerShellVersion.Minor == 1);
            if (startingWindowsPowerShell51)
            {
                if (WinPwshExePath == null)
                {
                    throw new PSInvalidOperationException(RemotingErrorIdStrings.WindowsPowerShellNotPresent);
                }

                exePath = WinPwshExePath;

                if (useWow64)
                {
                    string procArch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");

                    if ((!string.IsNullOrEmpty(procArch)) && (procArch.Equals("amd64", StringComparison.OrdinalIgnoreCase) ||
                                                              procArch.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
                    {
                        exePath = WinPwshExePath.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\");

                        if (!File.Exists(exePath))
                        {
                            string message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.WowComponentNotPresent, exePath);
                            throw new PSInvalidOperationException(message);
                        }
                    }
                }
            }
#endif
            // 'WindowStyle' is used only if 'UseShellExecute' is 'true'. Since 'UseShellExecute' is set
            // to 'false' in our use, we can ignore the 'WindowStyle' setting in the initialization below.
            _startInfo = new ProcessStartInfo
            {
                FileName               = exePath,
                UseShellExecute        = false,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                CreateNoWindow         = true,
#if !UNIX
                LoadUserProfile = true,
#endif
            };
#if !UNIX
            if (startingWindowsPowerShell51)
            {
                _startInfo.ArgumentList.Add("-Version");
                _startInfo.ArgumentList.Add("5.1");

                // if starting Windows PowerShell, need to remove PowerShell specific segments of PSModulePath
                _startInfo.Environment["PSModulePath"] = ModuleIntrinsics.GetWindowsPowerShellModulePath();
            }
#endif
            _startInfo.ArgumentList.Add("-s");
            _startInfo.ArgumentList.Add("-NoLogo");
            _startInfo.ArgumentList.Add("-NoProfile");

            if (!string.IsNullOrWhiteSpace(workingDirectory) && !startingWindowsPowerShell51)
            {
                _startInfo.ArgumentList.Add("-wd");
                _startInfo.ArgumentList.Add(workingDirectory);
            }

            if (initializationScript != null)
            {
                var scriptBlockString = initializationScript.ToString();
                if (!string.IsNullOrEmpty(scriptBlockString))
                {
                    var encodedCommand = Convert.ToBase64String(Encoding.Unicode.GetBytes(scriptBlockString));
                    _startInfo.ArgumentList.Add("-EncodedCommand");
                    _startInfo.ArgumentList.Add(encodedCommand);
                }
            }

            if (credential != null)
            {
                Net.NetworkCredential netCredential = credential.GetNetworkCredential();

                _startInfo.UserName = netCredential.UserName;
                _startInfo.Domain   = string.IsNullOrEmpty(netCredential.Domain) ? "." : netCredential.Domain;
                _startInfo.Password = credential.Password;
            }

            Process = new Process {
                StartInfo = _startInfo, EnableRaisingEvents = true
            };
        }
        private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassName)
        {
            DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();

            //if paramset is defaultcredential, set the flag in wcclient
            if (_usedefaultcredential.IsPresent)
            {
                dcp.UseDefaultCredentials = true;
            }

            //if paramset is credential, assign the credentials
            if (ParameterSetName.Equals("Credential", StringComparison.OrdinalIgnoreCase))
            {
                dcp.Credentials = _credential.GetNetworkCredential();
            }

            try
            {
                dcp.AllowAutoRedirect = true;
                dcp.DiscoverAny(_uri.ToString());
                dcp.ResolveAll();
            }
            catch (WebException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "WebException", ErrorCategory.ObjectNotFound, _uri);
                if (ex.InnerException != null)
                {
                    er.ErrorDetails = new ErrorDetails(ex.InnerException.Message);
                }
                WriteError(er);
                return(null);
            }
            catch (InvalidOperationException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _uri);
                WriteError(er);
                return(null);
            }

            // create the namespace
            CodeNamespace codeNS = new CodeNamespace();

            if (!string.IsNullOrEmpty(NameSpace))
            {
                codeNS.Name = NameSpace;
            }

            //create the class and add it to the namespace
            if (!string.IsNullOrEmpty(ClassName))
            {
                CodeTypeDeclaration codeClass = new CodeTypeDeclaration(ClassName);
                codeClass.IsClass    = true;
                codeClass.Attributes = MemberAttributes.Public;
                codeNS.Types.Add(codeClass);
            }

            //create a web reference to the uri docs
            WebReference           wref  = new WebReference(dcp.Documents, codeNS);
            WebReferenceCollection wrefs = new WebReferenceCollection();

            wrefs.Add(wref);

            //create a codecompileunit and add the namespace to it
            CodeCompileUnit codecompileunit = new CodeCompileUnit();

            codecompileunit.Namespaces.Add(codeNS);

            WebReferenceOptions wrefOptions = new WebReferenceOptions();

            wrefOptions.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateOldAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
            wrefOptions.Verbose = true;

            //create a csharpprovider and compile it
            CSharpCodeProvider csharpprovider = new CSharpCodeProvider();
            StringCollection   Warnings       = ServiceDescriptionImporter.GenerateWebReferences(wrefs, csharpprovider, codecompileunit, wrefOptions);

            StringBuilder codegenerator = new StringBuilder();
            StringWriter  writer        = new StringWriter(codegenerator, CultureInfo.InvariantCulture);

            try
            {
                csharpprovider.GenerateCodeFromCompileUnit(codecompileunit, writer, null);
            }
            catch (NotImplementedException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri);
                WriteError(er);
            }
            //generate the hashcode of the CodeCompileUnit
            _sourceHash = codegenerator.ToString().GetHashCode();

            //if the sourcehash matches the hashcode in the cache,the proxy hasnt changed and so
            // return the instance of th eproxy in the cache
            if (s_srccodeCache.ContainsKey(_sourceHash))
            {
                object obj;
                s_srccodeCache.TryGetValue(_sourceHash, out obj);
                WriteObject(obj, true);
                return(null);
            }
            CompilerParameters options = new CompilerParameters();
            CompilerResults    results = null;

            foreach (string warning in Warnings)
            {
                this.WriteWarning(warning);
            }

            // add the references to the required assemblies
            options.ReferencedAssemblies.Add("System.dll");
            options.ReferencedAssemblies.Add("System.Data.dll");
            options.ReferencedAssemblies.Add("System.Xml.dll");
            options.ReferencedAssemblies.Add("System.Web.Services.dll");
            options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            GetReferencedAssemblies(typeof(Cmdlet).Assembly, options);
            options.GenerateInMemory      = true;
            options.TreatWarningsAsErrors = false;
            options.WarningLevel          = 4;
            options.GenerateExecutable    = false;
            try
            {
                results = csharpprovider.CompileAssemblyFromSource(options, codegenerator.ToString());
            }
            catch (NotImplementedException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri);
                WriteError(er);
            }

            return(results.CompiledAssembly);
        }
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo = null;
                switch (ParameterSetName)
                {
                case "NoKey":
                    WriteVerbose("Using SSH Username and Password authentication for connection.");
                    var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.UserName);
                    connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer,
                                                                                _port,
                                                                                _credential,
                                                                                _proxyserver,
                                                                                _proxytype,
                                                                                _proxyport,
                                                                                _proxycredential,
                                                                                kIconnectInfo);

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                            {
                                prompt.Response = _credential.GetNetworkCredential().Password;
                            }
                        }
                    };
                    break;

                case "Key":
                    ProviderInfo provider;
                    var          pathinfo      = GetResolvedProviderPathFromPSPath(_keyfile, out provider);
                    var          localfullPath = pathinfo[0];
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               localfullPath,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               _proxycredential);
                    break;

                case "KeyString":
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               _keystring,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               _proxycredential);
                    break;

                default:
                    break;
                }

                //Ceate instance of SSH Client with connection info
                BaseClient client;
                if (Protocol == "SSH")
                {
                    client = new SshClient(connectInfo);
                }
                else
                {
                    client = new SftpClient(connectInfo);
                }


                // Handle host key
                if (_force)
                {
                    WriteWarning("Host key is not being verified since Force switch is used.");
                }
                else
                {
                    var computer1 = computer;
                    client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                    {
                        var sb = new StringBuilder();
                        foreach (var b in e.FingerPrint)
                        {
                            sb.AppendFormat("{0:x}:", b);
                        }
                        var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                        if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                        {
                            Host.UI.WriteVerboseLine("Fingerprint for " + computer1 + ": " + fingerPrint);
                        }

                        if (_sshHostKeys.ContainsKey(computer1))
                        {
                            e.CanTrust = _sshHostKeys[computer1] == fingerPrint;
                            if (e.CanTrust && MyInvocation.BoundParameters.ContainsKey("Verbose"))
                            {
                                Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1);
                            }
                        }
                        else
                        {
                            if (_errorOnUntrusted)
                            {
                                e.CanTrust = false;
                            }
                            else
                            {
                                if (!_acceptkey)
                                {
                                    var choices = new Collection <ChoiceDescription>
                                    {
                                        new ChoiceDescription("Y"),
                                        new ChoiceDescription("N")
                                    };
                                    e.CanTrust = 0 == Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);
                                }
                                else
                                {
                                    e.CanTrust = true;
                                }
                                if (e.CanTrust)
                                {
                                    var keymng = new TrustedKeyMng();
                                    keymng.SetKey(computer1, fingerPrint);
                                }
                            }
                        }
                    };
                }
                try
                {
                    // Set the connection timeout
                    client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                    // Set Keepalive for connections
                    client.KeepAliveInterval = TimeSpan.FromSeconds(_keepaliveinterval);

                    // Connect to host using Connection info
                    client.Connect();

                    if (Protocol == "SSH")
                    {
                        WriteObject(SshModHelper.AddToSshSessionCollection(client as SshClient, SessionState), true);
                    }
                    else
                    {
                        WriteObject(SshModHelper.AddToSftpSessionCollection(client as SftpClient, SessionState), true);
                    }
                }
                catch (SshConnectionException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (SshOperationTimeoutException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationTimeout, client);
                    WriteError(erec);
                }
                catch (SshAuthenticationException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Exception e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                    WriteError(erec);
                }

                // Renci.SshNet.Common.SshOperationTimeoutException when host is not alive or connection times out.
                // Renci.SshNet.Common.SshConnectionException when fingerprint mismatched
                // Renci.SshNet.Common.SshAuthenticationException Bad password
            }
        } // End process record
Exemple #5
0
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo = null;
                switch (ParameterSetName)
                {
                case "NoKey":
                    WriteVerbose("Using SSH Username and Password authentication for connection.");
                    var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.UserName);
                    connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer,
                                                                                _port,
                                                                                _credential,
                                                                                _proxyserver,
                                                                                _proxytype,
                                                                                _proxyport,
                                                                                ProxyCredential,
                                                                                kIconnectInfo);

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                            {
                                prompt.Response = _credential.GetNetworkCredential().Password;
                            }
                        }
                    };
                    break;

                case "Key":
                    ProviderInfo provider;
                    var          pathinfo      = GetResolvedProviderPathFromPSPath(_keyfile, out provider);
                    var          localfullPath = pathinfo[0];
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               localfullPath,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               ProxyCredential);
                    break;

                case "KeyString":
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               _keystring,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               ProxyCredential);
                    break;

                default:
                    break;
                }

                //Ceate instance of SSH Client with connection info
                var client = new ScpClient(connectInfo);
                // Set the connection timeout
                client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                // Handle host key
                if (_force)
                {
                    WriteWarning("Host key for " + computer + " is not being verified since Force switch is used.");
                }
                else
                {
                    var computer1 = computer;
                    client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                    {
                        var sb = new StringBuilder();
                        foreach (var b in e.FingerPrint)
                        {
                            sb.AppendFormat("{0:x}:", b);
                        }
                        var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                        if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                        {
                            Host.UI.WriteVerboseLine("Fingerprint for " + computer1 + ": " + fingerPrint);
                        }

                        if (_sshHostKeys.ContainsKey(computer1))
                        {
                            if (_sshHostKeys[computer1] == fingerPrint)
                            {
                                if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                                {
                                    Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1);
                                }
                                e.CanTrust = true;
                            }
                            else
                            {
                                e.CanTrust = false;
                            }
                        }
                        else
                        {
                            if (_errorOnUntrusted)
                            {
                                e.CanTrust = false;
                            }
                            else
                            {
                                int choice;
                                if (_acceptkey)
                                {
                                    choice = 0;
                                }
                                else
                                {
                                    var choices = new Collection <ChoiceDescription>
                                    {
                                        new ChoiceDescription("Y"),
                                        new ChoiceDescription("N")
                                    };

                                    choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);
                                }
                                if (choice == 0)
                                {
                                    var keymng = new TrustedKeyMng();
                                    keymng.SetKey(computer1, fingerPrint);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    e.CanTrust = false;
                                }
                            }
                        }
                    };
                }
                try
                {
                    // Connect to host using Connection info
                    client.Connect();
                }
                catch (Renci.SshNet.Common.SshConnectionException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Renci.SshNet.Common.SshOperationTimeoutException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationTimeout, client);
                    WriteError(erec);
                }
                catch (Renci.SshNet.Common.SshAuthenticationException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Exception e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                    WriteError(erec);
                }

                try
                {
                    if (client.IsConnected)
                    {
                        if (String.Equals(_pathtype, "File", StringComparison.OrdinalIgnoreCase))
                        {
                            WriteVerbose("Item type selected: File");
                            var _progresspreference = (ActionPreference)this.SessionState.PSVariable.GetValue("ProgressPreference");

                            if (_noProgress == false)
                            {
                                var counter = 0;
                                // Print progess of download.

                                client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                                {
                                    if (e.Size != 0)
                                    {
                                        counter++;
                                        if (counter > 900)
                                        {
                                            var percent = Convert.ToInt32((e.Downloaded * 100) / e.Size);
                                            if (percent == 100)
                                            {
                                                return;
                                            }

                                            var progressRecord = new ProgressRecord(1,
                                                                                    "Downloading " + e.Filename,
                                                                                    String.Format("{0} Bytes Downloaded of {1}",
                                                                                                  e.Downloaded, e.Size))
                                            {
                                                PercentComplete = percent
                                            };

                                            Host.UI.WriteProgress(1, progressRecord);
                                            counter = 0;
                                        }
                                    }
                                };
                            }
                            WriteVerbose("Connection successful");

                            // Get file name for use when downloading the file.
                            var filename        = "";
                            var destinationpath = "";
                            var localfullPath   = this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(_localpath);

                            if (String.IsNullOrEmpty(_newname))
                            {
                                filename = new DirectoryInfo(@_remotepath).Name;
                            }
                            else
                            {
                                filename = _newname;
                            }
                            destinationpath = (localfullPath.TrimEnd('/', '\\')) + System.IO.Path.DirectorySeparatorChar + filename;
                            WriteVerbose("Downloading " + _remotepath);
                            WriteVerbose("Saving as " + destinationpath);
                            var fil = new FileInfo(@destinationpath);

                            // Download the file
                            client.Download(_remotepath, fil);

                            client.Disconnect();
                        }
                        else
                        {
                            WriteVerbose("Item type selected: Directory");

                            var counter = 0;
                            // Print progess of download.
                            if (!_noProgress)
                            {
                                client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                                {
                                    if (e.Size != 0)
                                    {
                                        counter++;
                                        if (counter > 900)
                                        {
                                            var percent = Convert.ToInt32((e.Downloaded * 100) / e.Size);

                                            if (percent == 100)
                                            {
                                                return;
                                            }

                                            var progressRecord = new ProgressRecord(1,
                                                                                    "Downloading " + e.Filename,
                                                                                    String.Format("{0} Bytes Downloaded of {1}",
                                                                                                  e.Downloaded,
                                                                                                  e.Size))
                                            {
                                                PercentComplete = percent
                                            };

                                            Host.UI.WriteProgress(1, progressRecord);
                                            counter = 0;
                                        }
                                    }
                                };
                            }

                            try
                            {
                                // Get directory name for use when downloading the file.
                                var dirname         = "";
                                var destinationpath = "";
                                var localfullPath   = this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(_localpath);

                                if (String.IsNullOrEmpty(_newname))
                                {
                                    dirname = new DirectoryInfo(@_remotepath).Name;
                                }
                                else
                                {
                                    dirname = _newname;
                                }
                                destinationpath = (localfullPath.TrimEnd('/', '\\')) + System.IO.Path.DirectorySeparatorChar + dirname;

                                Directory.CreateDirectory(destinationpath);
                                WriteVerbose("Downloading: " + _remotepath);
                                WriteVerbose("Destination: " + destinationpath);
                                var dirinfo = new DirectoryInfo(@destinationpath);
                                client.Download(_remotepath, dirinfo);
                                WriteVerbose("Finished downloading.");
                            }
                            catch (Exception e)
                            {
                                ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                                WriteError(erec);
                            }
                            client.Disconnect();
                        }
                    }
                }
                catch (Exception e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationStopped, client);
                    WriteError(erec);
                }
            }
        } // End process record
        public TestHttpClient(ApiProxyConfiguration configuration, PSCredential credential)
        {
            Credential             = credential;
            _apiProxyConfiguration = configuration;
            var clientHandler = ApiProxy.ApiProxyHttpClient.HttpClientHandlerFactory.GetHttpClientHandler(configuration,
                                                                                                          Credential?.GetNetworkCredential(), ApiRequestReceivEventHandler);

            _apiProxyClientHandler = clientHandler as ApiProxyClientHandler;
            HttpClient             = ApiProxy.ApiProxyHttpClient.HttpClientFactory.GetHttpClient(configuration, _apiProxyClientHandler);
        }
Exemple #7
0
        internal static SPOnlineConnection InstantiateAdfsConnection(Uri url, bool useKerberos, PSCredential credentials, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool disableTelemetry, bool skipAdminCheck = false, string loginProviderName = null)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            string adfsHost;
            string adfsRelyingParty;

            OfficeDevPnP.Core.AuthenticationManager.GetAdfsConfigurationFromTargetUri(url, loginProviderName, out adfsHost, out adfsRelyingParty);

            if (string.IsNullOrEmpty(adfsHost) || string.IsNullOrEmpty(adfsRelyingParty))
            {
                throw new Exception("Cannot retrieve ADFS settings.");
            }

            PnPClientContext context;

            if (useKerberos)
            {
                context = PnPClientContext.ConvertFrom(authManager.GetADFSKerberosMixedAuthenticationContext(url.ToString(),
                                                                                                             adfsHost,
                                                                                                             adfsRelyingParty),
                                                       retryCount,
                                                       retryWait * 1000);
            }
            else
            {
                if (null == credentials)
                {
                    throw new ArgumentNullException(nameof(credentials));
                }
                var networkCredentials = credentials.GetNetworkCredential();
                context = PnPClientContext.ConvertFrom(authManager.GetADFSUserNameMixedAuthenticatedContext(url.ToString(),
                                                                                                            networkCredentials.UserName,
                                                                                                            networkCredentials.Password,
                                                                                                            networkCredentials.Domain,
                                                                                                            adfsHost,
                                                                                                            adfsRelyingParty),
                                                       retryCount,
                                                       retryWait * 1000);
            }

            context.RetryCount = retryCount;
            context.Delay      = retryWait * 1000;

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016 || SP2019
            context.DisableReturnValueCache = true;
#endif

            var connectionType = ConnectionType.OnPrem;

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.ADFS);
            spoConnection.ConnectionMethod = Model.ConnectionMethod.ADFS;
            return(spoConnection);
        }
Exemple #8
0
        /// <summary>
        /// Generate a ConnectionInfoObject using a SSH Key.
        /// </summary>
        /// <param name="computer"></param>
        /// <param name="port"></param>
        /// <param name="keyfile"></param>
        /// <param name="credential"></param>
        /// <param name="proxyserver"></param>
        /// <param name="proxytype"></param>
        /// <param name="proxyport"></param>
        /// <param name="proxycredential"></param>
        /// <returns></returns>
        public static PrivateKeyConnectionInfo GetKeyConnectionInfo(string computer,
                                                                    int port,
                                                                    string keyfile,
                                                                    PSCredential credential,
                                                                    string proxyserver,
                                                                    string proxytype,
                                                                    int proxyport,
                                                                    PSCredential proxycredential)
        {
            PrivateKeyConnectionInfo connectionInfo;
            var fullPath = Path.GetFullPath(keyfile);

            // Check if the file actually exists.
            if (File.Exists(fullPath))
            {
                // Create the key object.
                PrivateKeyFile sshkey;
                if (credential.GetNetworkCredential().Password == "")
                {
                    sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                }
                else
                {
                    sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password);
                }

                if (proxyserver != "")
                {
                    // Set the proper proxy type
                    var ptype = ProxyTypes.Http;
                    switch (proxytype)
                    {
                    case "HTTP":
                        ptype = ProxyTypes.Http;
                        break;

                    case "Socks4":
                        ptype = ProxyTypes.Socks4;
                        break;

                    case "Socks5":
                        ptype = ProxyTypes.Socks5;
                        break;
                    }

                    if (proxycredential.GetNetworkCredential().UserName != "")
                    {
                        connectionInfo = new PrivateKeyConnectionInfo(computer,
                                                                      port,
                                                                      credential.GetNetworkCredential().UserName,
                                                                      ptype,
                                                                      proxyserver,
                                                                      proxyport,
                                                                      sshkey);
                    }
                    else
                    {
                        connectionInfo = new PrivateKeyConnectionInfo(computer,
                                                                      port,
                                                                      credential.GetNetworkCredential().UserName,
                                                                      ptype,
                                                                      proxyserver,
                                                                      proxyport,
                                                                      proxycredential.GetNetworkCredential().UserName,
                                                                      proxycredential.GetNetworkCredential().Password,
                                                                      sshkey);
                    }
                }
                else // Handle connection with no proxy server
                {
                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                                                  port,
                                                                  credential.GetNetworkCredential().UserName,
                                                                  sshkey);
                }
            } // file exists
            else
            {
                throw new FileNotFoundException("Key file " + fullPath + " was not found.");
            }
            return(connectionInfo);
        }
        /// <summary>
        /// </summary>
        /// <param name="powerShellVersion"></param>
        /// <param name="credential"></param>
        /// <param name="initializationScript"></param>
        /// <param name="useWow64"></param>
        public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
        {
            string psWow64Path = PwshExePath;

            if (useWow64)
            {
                string procArch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");

                if (!string.IsNullOrEmpty(procArch) && (procArch.Equals("amd64", StringComparison.OrdinalIgnoreCase) ||
                                                        procArch.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
                {
                    psWow64Path = PwshExePath.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\");

                    if (!File.Exists(psWow64Path))
                    {
                        string message =
                            PSRemotingErrorInvariants.FormatResourceString(
                                RemotingErrorIdStrings.IPCWowComponentNotPresent,
                                psWow64Path);
                        throw new PSInvalidOperationException(message);
                    }
                }
            }

            string processArguments = " -s -NoLogo -NoProfile";

            if (initializationScript != null)
            {
                string scripBlockAsString = initializationScript.ToString();
                if (!string.IsNullOrEmpty(scripBlockAsString))
                {
                    string encodedCommand =
                        Convert.ToBase64String(Encoding.Unicode.GetBytes(scripBlockAsString));
                    processArguments = string.Format(CultureInfo.InvariantCulture,
                                                     "{0} -EncodedCommand {1}", processArguments, encodedCommand);
                }
            }

            // 'WindowStyle' is used only if 'UseShellExecute' is 'true'. Since 'UseShellExecute' is set
            // to 'false' in our use, we can ignore the 'WindowStyle' setting in the initialization below.
            _startInfo = new ProcessStartInfo
            {
                FileName               = useWow64 ? psWow64Path : PwshExePath,
                Arguments              = processArguments,
                UseShellExecute        = false,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                CreateNoWindow         = true,
#if !UNIX
                LoadUserProfile = true,
#endif
            };

            if (credential != null)
            {
                Net.NetworkCredential netCredential = credential.GetNetworkCredential();

                _startInfo.UserName = netCredential.UserName;
                _startInfo.Domain   = string.IsNullOrEmpty(netCredential.Domain) ? "." : netCredential.Domain;
                _startInfo.Password = credential.Password;
            }

            Process = new Process {
                StartInfo = _startInfo, EnableRaisingEvents = true
            };
        }
Exemple #10
0
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo;
                if (_keyfile.Equals(""))
                {
                    WriteVerbose("Using SSH Username and Password authentication for connection.");
                    var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.GetNetworkCredential().UserName);
                    connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer,
                                                                                _port,
                                                                                _credential,
                                                                                _proxyserver,
                                                                                _proxytype,
                                                                                _proxyport,
                                                                                _proxycredential,
                                                                                kIconnectInfo);

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                            {
                                prompt.Response = _credential.GetNetworkCredential().Password;
                            }
                        }
                    };
                }
                else
                {
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               _keyfile,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               _proxycredential);
                }

                //Ceate instance of SSH Client with connection info
                var client = new SftpClient(connectInfo);


                // Handle host key
                var computer1 = computer;
                client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                {
                    var sb = new StringBuilder();
                    foreach (var b in e.FingerPrint)
                    {
                        sb.AppendFormat("{0:x}:", b);
                    }
                    var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                    if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                    {
                        Host.UI.WriteVerboseLine("Fingerprint for " + computer1 + ": " + fingerPrint);
                    }

                    if (_sshHostKeys.ContainsKey(computer1))
                    {
                        if (_sshHostKeys[computer1] == fingerPrint)
                        {
                            if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                            {
                                Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " +
                                                         computer);
                            }
                            e.CanTrust = true;
                        }
                        else
                        {
                            throw new System.Security.SecurityException("SSH fingerprint mismatch for host " + computer1);
                        }
                    }
                    else
                    {
                        int choice;
                        if (_acceptkey)
                        {
                            choice = 0;
                        }
                        else
                        {
                            var choices = new Collection <ChoiceDescription>
                            {
                                new ChoiceDescription("Y"),
                                new ChoiceDescription("N")
                            };

                            choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);
                        }
                        if (choice == 0)
                        {
                            var keymng = new TrustedKeyMng();
                            keymng.SetKey(computer1, fingerPrint);
                            e.CanTrust = true;
                        }
                        else
                        {
                            e.CanTrust = false;
                        }
                    }
                };
                // Set the connection timeout
                client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                // Set Keepalive for connections
                client.KeepAliveInterval = TimeSpan.FromSeconds(_keepaliveinterval);

                // Connect to host using Connection info
                client.Connect();
                WriteObject(SshModHelper.AddToSftpSessionCollection(client, SessionState), true);
            }
        } // End process record
Exemple #11
0
        public ADUser(string userName, SecureString password)
        {
            UserName      = userName;
            Authenticated = true;
            _History      = new List <string>();
            try
            {
                PSCredential   cred  = new PSCredential(UserName, password);
                DirectoryEntry entry = new DirectoryEntry("LDAP://192.168.76.3:389/DC=dublinschool,DC=org", UserName, cred.GetNetworkCredential().Password);
                Object         obj   = entry.NativeObject;
                WebhostEventLog.Syslog.LogInformation("Successfully Authenticated {0} via zoed.", userName);
            }
            catch (Exception f)
            {
                WebhostEventLog.Syslog.LogWarning("Could not contact zoed. {0}", f.Message);
                try
                {
                    PSCredential   cred  = new PSCredential(UserName, password);
                    DirectoryEntry entry = new DirectoryEntry("LDAP://192.168.76.4:389/DC=dublinschool,DC=org", UserName, cred.GetNetworkCredential().Password);
                    Object         obj   = entry.NativeObject;
                    WebhostEventLog.Syslog.LogInformation("Successfully Authenticated {0} via buddy.", userName);
                }
                catch (Exception e)
                {
                    Authenticated = false;
                    WebhostEventLog.Syslog.LogError("Failed to Authenticate on zoed and buddy {0}:  {1}", userName, e.Message);
                }
            }

            HttpContext.Current.Session[State.AuthUser] = this;
        }
Exemple #12
0
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo;
                if (_keyfile.Equals(""))
                {
                    WriteVerbose("Using SSH Username and Password authentication for connection.");
                    var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.UserName);
                    connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer,
                                                                                _port,
                                                                                _credential,
                                                                                _proxyserver,
                                                                                _proxytype,
                                                                                _proxyport,
                                                                                _proxycredential,
                                                                                kIconnectInfo);

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                            {
                                prompt.Response = _credential.GetNetworkCredential().Password;
                            }
                        }
                    };
                }
                else
                {
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               _keyfile,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               _proxycredential);
                }

                //Ceate instance of SSH Client with connection info
                var client = new ScpClient(connectInfo);


                // Handle host key
                if (_force)
                {
                    WriteWarning("Host key is not being verified since Force switch is used.");
                }
                else
                {
                    var computer1 = computer;
                    client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                    {
                        var sb = new StringBuilder();
                        foreach (var b in e.FingerPrint)
                        {
                            sb.AppendFormat("{0:x}:", b);
                        }
                        var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                        if (_sshHostKeys.ContainsKey(computer1))
                        {
                            if (_sshHostKeys[computer1] == fingerPrint)
                            {
                                if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                                {
                                    Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1);
                                }
                                e.CanTrust = true;
                            }
                            else
                            {
                                var ex = new System.Security.SecurityException("SSH fingerprint mismatch for host " + computer1);
                                ThrowTerminatingError(new ErrorRecord(
                                                          ex,
                                                          "SSH fingerprint mismatch for host " + computer1,
                                                          ErrorCategory.SecurityError,
                                                          computer1));
                            }
                        }
                        else
                        {
                            if (_errorOnUntrusted)
                            {
                                throw new System.Security.SecurityException("SSH fingerprint mismatch for host " + computer1);
                            }

                            int choice;
                            if (_acceptkey)
                            {
                                choice = 0;
                            }
                            else
                            {
                                var choices = new Collection <ChoiceDescription>
                                {
                                    new ChoiceDescription("Y"),
                                    new ChoiceDescription("N")
                                };

                                choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);
                            }
                            if (choice == 0)
                            {
                                var keymng = new TrustedKeyMng();
                                keymng.SetKey(computer1, fingerPrint);
                                e.CanTrust = true;
                            }
                            else
                            {
                                e.CanTrust = false;
                            }
                        }
                    };
                }
                // Set the connection timeout
                client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                // Connect to host using Connection info
                try
                {
                    client.Connect();

                    var counter = 0;
                    // Print progess of download.
                    if (!_noProgress)
                    {
                        client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                        {
                            if (e.Size != 0)
                            {
                                counter++;
                                if (counter > 900)
                                {
                                    var percent = Convert.ToInt32((e.Downloaded * 100) / e.Size);

                                    if (percent == 100)
                                    {
                                        return;
                                    }

                                    var progressRecord = new ProgressRecord(1,
                                                                            "Downloading " + e.Filename,
                                                                            String.Format("{0} Bytes Downloaded of {1}",
                                                                                          e.Downloaded,
                                                                                          e.Size))
                                    {
                                        PercentComplete = percent
                                    };

                                    Host.UI.WriteProgress(1, progressRecord);
                                    counter = 0;
                                }
                            }
                        };
                    }
                }
                catch (Renci.SshNet.Common.SshConnectionException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Renci.SshNet.Common.SshOperationTimeoutException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationTimeout, client);
                    WriteError(erec);
                }
                catch (Renci.SshNet.Common.SshAuthenticationException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Exception e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                    WriteError(erec);
                }

                if (client.IsConnected)
                {
                    try
                    {
                        var localfullPath = Path.GetFullPath(_localfolder);
                        WriteVerbose("Downloading " + _remotefolder);
                        var dirinfo = new DirectoryInfo(@localfullPath);
                        client.Download(_remotefolder, dirinfo);
                        WriteVerbose("Finished downloading.");
                    }
                    catch (Exception e)
                    {
                        ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                        WriteError(erec);
                    }
                    client.Disconnect();
                }
            }
        } // End process record
        private CimSession GetCimWinRMSession(PSCredential Credential)
        {
            // Prepare the last session if any
            CimSession tempSession = cimWinRMSession;

            // If we use different credentials than last time, now's the time to interrupt
            if (!(cimWinRMSessionLastCredential == null && Credential == null))
            {
                if (cimWinRMSessionLastCredential == null || Credential == null)
                {
                    tempSession = null;
                }
                else if (cimWinRMSessionLastCredential.UserName != Credential.UserName)
                {
                    tempSession = null;
                }
                else if (cimWinRMSessionLastCredential.GetNetworkCredential().Password !=
                         Credential.GetNetworkCredential().Password)
                {
                    tempSession = null;
                }
            }

            if (tempSession == null)
            {
                WSManSessionOptions options;
                if (CimWinRMOptions == null)
                {
                    options = GetDefaultCimWsmanOptions();
                }
                else
                {
                    options = CimWinRMOptions;
                }
                if (Credential != null)
                {
                    options.AddDestinationCredentials(new CimCredential(PasswordAuthenticationMechanism.Default,
                                                                        Credential.GetNetworkCredential().Domain, Credential.GetNetworkCredential().UserName,
                                                                        Credential.Password));
                }

                try
                {
                    tempSession = CimSession.Create(ComputerName, options);
                }
                catch (Exception e)
                {
                    bool testBadCredential = false;
                    try
                    {
                        string tempMessageId = ((CimException)(e.InnerException)).MessageId;
                        if (tempMessageId == "HRESULT 0x8007052e")
                        {
                            testBadCredential = true;
                        }
                        else if (tempMessageId == "HRESULT 0x80070005")
                        {
                            testBadCredential = true;
                        }
                    }
                    catch
                    {
                    }

                    if (testBadCredential)
                    {
                        throw new UnauthorizedAccessException("Invalid credentials", e);
                    }
                    throw;
                }

                cimWinRMSessionLastCredential = Credential;
            }

            return(tempSession);
        }
 public static NetworkCredential GetNetworkCredentialSafe(this PSCredential credential)
 => credential == PSCredential.Empty
         ? null // avoid exception
         : credential?.GetNetworkCredential();
Exemple #15
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);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="powerShellVersion"></param>
        /// <param name="credential"></param>
        /// <param name="initializationScript"></param>
        /// <param name="useWow64"></param>
        public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
        {
            string psWow64Path = s_PSExePath;

            if (useWow64)
            {
                string procArch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");

                if ((!string.IsNullOrEmpty(procArch)) && (procArch.Equals("amd64", StringComparison.OrdinalIgnoreCase) ||
                    procArch.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
                {
                    psWow64Path = s_PSExePath.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\");

                    if (!File.Exists(psWow64Path))
                    {
                        string message =
                            PSRemotingErrorInvariants.FormatResourceString(
                                RemotingErrorIdStrings.IPCWowComponentNotPresent,
                                psWow64Path);
                        throw new PSInvalidOperationException(message);
                    }
                }
            }

            string processArguments = string.Empty;
            // Adding Version parameter to powershell.exe
            // Version parameter needs to go before all other parameters because the native layer looks for Version or 
            // PSConsoleFile parameters before parsing other parameters.
            // The other parameters get parsed in the managed layer.
            Version tempVersion = powerShellVersion ?? PSVersionInfo.PSVersion;
            processArguments = string.Format(CultureInfo.InvariantCulture,
                       "-Version {0}", new Version(tempVersion.Major, tempVersion.Minor));

            processArguments = string.Format(CultureInfo.InvariantCulture,
                "{0} -s -NoLogo -NoProfile", processArguments);

            if (initializationScript != null)
            {
                string scripBlockAsString = initializationScript.ToString();
                if (!string.IsNullOrEmpty(scripBlockAsString))
                {
                    string encodedCommand =
                        Convert.ToBase64String(Encoding.Unicode.GetBytes(scripBlockAsString));
                    processArguments = string.Format(CultureInfo.InvariantCulture,
                        "{0} -EncodedCommand {1}", processArguments, encodedCommand);
                }
            }

            // 'WindowStyle' is used only if 'UseShellExecute' is 'true'. Since 'UseShellExecute' is set
            // to 'false' in our use, we can ignore the 'WindowStyle' setting in the initialization below.
            _startInfo = new ProcessStartInfo
            {
                FileName = useWow64 ? psWow64Path : s_PSExePath,
                Arguments = processArguments,
                UseShellExecute = false,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                LoadUserProfile = true,
            };

            if (credential != null)
            {
                Net.NetworkCredential netCredential = credential.GetNetworkCredential();

                _startInfo.UserName = netCredential.UserName;
                _startInfo.Domain = string.IsNullOrEmpty(netCredential.Domain) ? "." : netCredential.Domain;
#if CORECLR
                _startInfo.PasswordInClearText = ClrFacade.ConvertSecureStringToString(credential.Password);
#else
                _startInfo.Password = credential.Password;
#endif
            }

            Process = new Process { StartInfo = _startInfo, EnableRaisingEvents = true };
        }
Exemple #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="computer"></param>
        /// <param name="port"></param>
        /// <param name="credential"></param>
        /// <param name="proxyserver"></param>
        /// <param name="proxytype"></param>
        /// <param name="proxyport"></param>
        /// <param name="proxycredential"></param>
        /// <param name="kIconnectInfo"></param>
        /// <returns></returns>
        public static ConnectionInfo GetCredConnectionInfo(string computer,
                                                           int port,
                                                           PSCredential credential,
                                                           string proxyserver,
                                                           string proxytype,
                                                           int proxyport,
                                                           PSCredential proxycredential,
                                                           KeyboardInteractiveAuthenticationMethod kIconnectInfo)
        {
            ConnectionInfo connectionInfo;
            var            passconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName,
                                                                              credential.GetNetworkCredential().Password);

            if (proxyserver != "")
            {
                // Set the proper proxy type
                var ptype = ProxyTypes.Http;
                switch (proxytype)
                {
                case "HTTP":
                    ptype = ProxyTypes.Http;
                    break;

                case "Socks4":
                    ptype = ProxyTypes.Socks4;
                    break;

                case "Socks5":
                    ptype = ProxyTypes.Socks5;
                    break;
                }

                if (proxycredential.GetNetworkCredential().UserName != "")
                {
                    connectionInfo = new ConnectionInfo(computer,
                                                        port,
                                                        credential.GetNetworkCredential().UserName,
                                                        ptype,
                                                        proxyserver,
                                                        proxyport,
                                                        "",
                                                        "",
                                                        kIconnectInfo,
                                                        passconnectInfo);
                }
                else
                {
                    connectionInfo = new ConnectionInfo(computer,
                                                        port,
                                                        credential.GetNetworkCredential().UserName,
                                                        ptype,
                                                        proxyserver,
                                                        proxyport,
                                                        proxycredential.GetNetworkCredential().UserName,
                                                        proxycredential.GetNetworkCredential().Password,
                                                        kIconnectInfo,
                                                        passconnectInfo);
                }
            }
            else // Handle connection with no proxy server
            {
                connectionInfo = new ConnectionInfo(computer,
                                                    port,
                                                    credential.GetNetworkCredential().UserName,
                                                    passconnectInfo,
                                                    kIconnectInfo);
            }
            return(connectionInfo);
        }