public void InitProcessTest()
        {
            var proc             = new Mock <IProcess>();
            ProcessStartInfo psi = new ProcessStartInfo(null);

            psi.FileName = "filename";
            psi.RedirectStandardError  = false;
            psi.RedirectStandardInput  = false;
            psi.RedirectStandardOutput = false;
            psi.UseShellExecute        = true;
            proc.Setup(p => p.StartInfo).Returns(psi);

            ProcessSpawnable ps = null;
            Exception        caughtException = null;

            try
            {
                ps = new ProcessSpawnable(proc.Object);
                ps.Init();
            }
            catch (Exception e)
            {
                caughtException = e;
            }

            Assert.IsNull(caughtException);
            Assert.IsTrue(ps.Process.StartInfo.RedirectStandardError);
            Assert.IsTrue(ps.Process.StartInfo.RedirectStandardInput);
            Assert.IsTrue(ps.Process.StartInfo.RedirectStandardOutput);
            Assert.IsFalse(ps.Process.StartInfo.UseShellExecute);
            proc.Verify(p => p.Start());
        }
        public void CtorFilenameTest()
        {
            string           filename = "testFileName";
            ProcessSpawnable proc     = new ProcessSpawnable(filename);

            Assert.IsNotNull(proc.Process);
            Assert.AreEqual(filename, proc.Process.StartInfo.FileName);
            Assert.AreEqual("", proc.Process.StartInfo.Arguments);
        }
        public void CtorFilenameArgumentsTest()
        {
            string           filename = "testFileName";
            string           args     = "arg1 arg2";
            ProcessSpawnable proc     = new ProcessSpawnable(filename, args);

            Assert.NotNull(proc.Process);
            Assert.Equal(filename, proc.Process.StartInfo.FileName);
            Assert.Equal(args, proc.Process.StartInfo.Arguments);
        }
        public void CtorProcessTest()
        {
            string  filename = "testFileName";
            string  args     = "arg1 arg2";
            Process p        = new Process();

            p.StartInfo.FileName  = filename;
            p.StartInfo.Arguments = args;
            ProcessSpawnable proc = new ProcessSpawnable(p);

            Assert.IsNotNull(proc.Process);
            Assert.AreSame(p.StartInfo, proc.Process.StartInfo);
        }
        public void WriteTest()
        {
            //Arrange
            string testText = "This is text to write";
            Stream so       = new MemoryStream();

            so.WriteByte(1);
            so.Seek(0, SeekOrigin.Begin);
            StreamReader output = new StreamReader(so);

            Assert.IsFalse(output.EndOfStream);

            Stream se = new MemoryStream();

            se.WriteByte(2);
            se.Seek(0, SeekOrigin.Begin);
            StreamReader error = new StreamReader(se);

            Assert.IsFalse(error.EndOfStream);

            Stream       si    = new MemoryStream();
            StreamWriter input = new StreamWriter(si);

            var proc             = new Mock <IProcess>();
            ProcessStartInfo psi = new ProcessStartInfo("filename");

            proc.SetupGet <ProcessStartInfo>(p => p.StartInfo).Returns(psi);
            proc.SetupGet <StreamReader>(p => p.StandardError).Returns(error);
            proc.SetupGet <StreamReader>(p => p.StandardOutput).Returns(output);
            proc.SetupGet <StreamWriter>(p => p.StandardInput).Returns(input);
            ProcessSpawnable ps = new ProcessSpawnable(proc.Object);

            ps.Init();

            //Act
            ps.Write(testText);

            //Assert
            ps.Process.StandardInput.Flush();
            int maxSize = 4096;

            byte[] tmp = new byte[maxSize];
            si.Seek(0, SeekOrigin.Begin);
            int    n           = si.Read(tmp, 0, maxSize);
            string writtenText = System.Text.Encoding.Default.GetString(tmp, 0, n);

            Assert.IsTrue(output.EndOfStream);
            Assert.IsTrue(error.EndOfStream);
            Assert.AreEqual(testText, writtenText);
        }
        public void EmptyFilenameTest()
        {
            var proc             = new Mock <IProcess>();
            ProcessStartInfo psi = new ProcessStartInfo(null);

            proc.Setup(p => p.StartInfo).Returns(psi);
            Exception caughtException = null;

            try
            {
                ProcessSpawnable process = new ProcessSpawnable(proc.Object);
                process.Init();
            }
            catch (Exception e)
            {
                caughtException = e;
            }

            Assert.IsNotNull(caughtException);
            Assert.IsInstanceOfType(caughtException, typeof(ArgumentException));
            Assert.AreEqual("_process.StartInfo.FileName", (caughtException as ArgumentException).ParamName);
        }
Exemple #7
0
        public void InitialiseOpenSshSession(string host_name, string user, object pass, OperatingSystem os)
        {
            #region Create actions for client responses
            Action <IResult> ConnectionEstablished = (result) =>
            {
                Info("Connected to host {0}.", host_name);
            };
            Action <IResult> FailedToConnect = (result) =>
            {
                Error(Here(), "Failed to connect to host {0}. SSH output: {1}", host_name, (string)result.Text);
            };
            Action <IResult> HostKeyReceived = (result) =>
            {
                Match m = result.Result as Match;
                Success("Received host key of type {0} with fingerprint {1}", m.Groups[1].Value, m.Groups[2].Value);
            };
            Action <IResult> FailedToReceiveHostKey = (result) =>
            {
                Match m = result.Result as Match;
                Error(Here(), "Failed to receive host key. SSH output: {0}", (string)result.Result);
            };
            Action <IResult> HostKnown = (result) =>
            {
                Info("Host {0} is know and matches the host key.", host_name);
            };
            Action <IResult> HostNotKnown = (result) =>
            {
                Warning("Host key not known. The host key is not trusted. The host fingerprint will be added to your known_hosts file.");
                //SshSession.Send.String("yes", true);
            };
            #endregion

            string           ssh_command   = Environment.OSVersion.Platform == PlatformID.Win32NT ? "openssh-win32\\ssh.exe" : "ssh";
            string           ssh_arguments = string.Format("-v -l {0} {1}", user, host_name);
            ProcessStartInfo psi           = new ProcessStartInfo(ssh_command, ssh_arguments);
            psi.CreateNoWindow         = true;
            psi.RedirectStandardError  = true;
            psi.RedirectStandardInput  = true;
            psi.RedirectStandardOutput = true;
            psi.UseShellExecute        = false;
            Process p = new Process();
            p.StartInfo           = psi;
            p.EnableRaisingEvents = true;
            p.OutputDataReceived += OnOutputDataReceived;
            p.ErrorDataReceived  += OnErrorDataReceived;
            ProcessSpawnable s = new ProcessSpawnable(p);
            SshSession = Expect.Spawn(s, this.LineTerminator);
            IResult r = SshSession.Expect.Regex("Reading configuration data (\\S+)", null, 300);
            if (r.IsMatch)
            {
                Match m = (Match)r.Result;
                Info("Using OpenSSH configuration from {0}.", m.Groups[1].Value);
            }
            if (!SshSession.Expect.ContainsElse("Connection established", ConnectionEstablished, FailedToConnect, 6000).IsMatch)
            {
                this.IsConnected = false;
                return;
            }
            if (!SshSession.Expect.RegexElse("Server host key: ([a-zA-Z0-9\\-]+)\\s+([a-zA-Z0-9\\-\\:]+)", HostKeyReceived, FailedToReceiveHostKey, 6000).IsMatch)
            {
                this.IsConnected = false;
                return;
            }
            List <IResult> ok = SshSession.Expect.ContainsEither(string.Format("is known", host_name), HostKnown, "can't be established", HostNotKnown, 6000);
        }
Exemple #8
0
        public void InitialisePlinkSesion(string host_name, string user, object pass, OperatingSystem os)
        {
            this.HostName = host_name;
            FileFound     = (o) =>
            {
                Debug(this.Here(), "ls returned file exists.");
            };
            FileNotFound = (o) =>
            {
                Debug(this.Here(), "ls returns file does not exist.");
            };
            DirectoryFound = (o) =>
            {
                Debug(this.Here(), "stat returned directory exists.");
            };
            DirectoryNotFound = (o) =>
            {
                Debug(this.Here(), "stat returns directory does not exist.");
            };

            string ssh_command   = Environment.OSVersion.Platform == PlatformID.Win32NT ? "plink.exe" : "ssh";
            string ssh_arguments = Environment.OSVersion.Platform == PlatformID.Win32NT ? string.Format("-v -ssh -2 -l {0} -pw \"{1}\" -sshlog plink_ssh.log {2}", user,
                                                                                                        ToInsecureString(pass), host_name) : "";
            ProcessStartInfo psi = new ProcessStartInfo(ssh_command, ssh_arguments);

            psi.CreateNoWindow         = true;
            psi.RedirectStandardError  = true;
            psi.RedirectStandardInput  = true;
            psi.RedirectStandardOutput = true;
            psi.UseShellExecute        = false;
            Process p = new Process();

            p.StartInfo           = psi;
            p.EnableRaisingEvents = true;
            p.OutputDataReceived += OnOutputDataReceived;
            p.ErrorDataReceived  += OnErrorDataReceived;
            ProcessSpawnable s = new ProcessSpawnable(p);

            SshSession = Expect.Spawn(s, this.LineTerminator);
            Action <IResult> LogFileExists = (o) =>
            {
                Info("Plink log file exists, overwriting.");
                SshSession.Send.Char('y');
            };

            Action <IResult> ConnectedToServer = (o) =>
            {
                Info("Connected to host {0}.", host_name);
            };

            Action <IResult> FailedConnectToServer = (o) =>
            {
                Info("Failed to connect to host {0}.", host_name);
                this.IsConnected = false;
                return;
            };

            Action <IResult> GotHostKeyFingerprint = (match) =>
            {
                string lt = Environment.OSVersion.Platform == PlatformID.Win32NT ? "\r\n" : "\n";
                Match  m  = Regex.Match((string)match.Result, "Host key fingerprint is:" + lt + "([\\w\\-\\d\\s\\:]+)" + lt);
                if (m.Success && m.Groups.Count == 2)
                {
                    this.HostKey = m.Groups[1].Value;
                    Success("Host key: {0}", this.HostKey);
                }
                else
                {
                    SshSession.Expect.Contains(lt, (hk) =>
                    {
                        Match nm = Regex.Match((string)hk.Result, "([\\w\\-\\d\\s\\:]+)" + lt);
                        if (nm.Success && nm.Groups.Count == 2)
                        {
                            this.HostKey = nm.Groups[1].Value;
                            Success("Host key: {0}", this.HostKey);
                        }
                        else
                        {
                            throw new Exception("Could not parse host key from output: " + nm.Value);
                        }
                    });
                }
            };

            Action <IResult> ServerKeyNotCached = (o) =>
            {
                Warning("Server key not cached. The host key is not trusted.");
                SshSession.Send.Char('n');
            };

            Action <IResult> AccessGranted = (o) =>
            {
                this.HostName    = host_name;
                this.IsConnected = true;
                Success("Password authentication succeded.");
                Success("Connected to host {0}.", host_name);
                return;
            };

            Action <IResult> PasswordAuthenticationFailed = (match) =>
            {
                string o = (string)match.Result;
                if (o.Contains("Password authentication failed"))
                {
                    this.IsConnected = false;
                    Error("The user name or password is incorrect. Could not connect to host {0}.", host_name);
                }
            };

            Action <IResult> AccessDenied = (o) =>
            {
                this.IsConnected = false;
                Error("Unknown error in authentication. Access denied.");
                return;
            };

            SshSession.Expect.Contains("The session log file \"plink_ssh.log\" already exists.", LogFileExists);
            if (!SshSession.Expect.Contains("Using SSH protocol version 2", ConnectedToServer, 1000, 10).IsMatch)
            {
                Error("Failed to connect to host {0}.", host_name);
                this.IsConnected = false;
                Error("Failed to initialise SSH audit environment.");
                return;
            }
            if (!SshSession.Expect.Contains("Host key fingerprint is:", GotHostKeyFingerprint, 1000, 10).IsMatch)
            {
                throw new Exception("Failed to get host key.");
            }
            SshSession.Expect.Contains("Store key in cache?", ServerKeyNotCached);
            List <IResult> access = SshSession.Expect.ContainsEither("Access granted", AccessGranted, "Password authentication failed", PasswordAuthenticationFailed, 5000);

            if (access[0].IsMatch)
            {
                this.IsConnected = true;
                Success("SSH audit environment initalised."); return;
            }
            else if (access[1].IsMatch || SshSession.Expect.Contains("Access denied", AccessDenied, 100, 5).IsMatch)
            {
                this.IsConnected = false;
                Error("Access denied to host {0}.", host_name);
                Error("Failed to initialise SSH audit environment.");
                return;
            }
            else
            {
                throw new Exception("Could not parse SSH command output.");
            }
        }