Exemplo n.º 1
0
        public void StreamTxt(string filePath)
        {
            using (Stream fileStream = File.OpenRead(filePath))
            {
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    while (!reader.EndOfStream)
                    {
                        var password = reader.ReadLine();
                        Console.WriteLine(String.Format("Trying Username: {0}, Password: {1}, on {2}, {3}.", _username, password, _host, _port));
                        var valid = _sshConn.Connect(_host, _port, _username, password);
                        if (valid)
                        {
                            Console.WriteLine(String.Format("The password '{0}' is valid for User '{1}'.", password, _username));

                            if (!PromptUserToContinue())
                            {
                                broken = true;
                                break;
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 2
0
        public void start()
        {
            try
            {
                SSHConnectionParameter f = new SSHConnectionParameter();
                f.UserName = userName;

                f.Password           = passwordWord;
                f.Protocol           = SSHProtocol.SSH2;
                f.AuthenticationType = AuthenticationType.Password;
                f.WindowSize         = 0x1000;
                _objTmp = new Dictionary <TextBox, StringBuilder>();
                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //s.Blocking = false;
                s.Connect(new IPEndPoint(IPAddress.Parse(ip), _port));

                _conn = SSHConnection.Connect(f, this, s);


                this._conn = _conn;

                SSHChannel ch = _conn.OpenShell(this);
                this._pf  = ch;
                _linePool = new List <string>();
                SSHConnectionInfo ci = _conn.ConnectionInfo;
            }
            catch (Exception e1)
            {
                SetText(_objTmp, form.consoleBox, e1.Message);
            }
        }
Exemplo n.º 3
0
 public void Connect(Socket s)
 {
     this._params.WindowSize = 0x1000;
     this._conn = SSHConnection.Connect(this._params, this, s);
     this._pf   = this._conn.OpenShell(this);
     SSHConnectionInfo ci = this._conn.ConnectionInfo;
 }
Exemplo n.º 4
0
 private void connectbutton_Click(object sender, EventArgs e)
 {
     if (sshcheckbox.Checked)
     {
         if (SSHConnection.Connect(tboxsshhost.Text, tboxsshuser.Text, tboxsshpw.Text, tboxsshport.Text))
         {
             if (SQLConnection.Connect(tboxmysqlhost.Text, tboxmysqlname.Text, tboxmysqlpw.Text, /*tboxmysqlsd2db.Text,*/ tboxmysqlwordldb.Text))
             {
                 Datastores.dbused = true;
                 this.Close();
             }
             else
             {
                 MessageBox.Show(SQLConnection.error.Message);
             }
         }
         else
         {
             MessageBox.Show(SSHConnection.error.Message);
         }
     }
     else
     {
         if (SQLConnection.Connect(tboxmysqlhost.Text, tboxmysqlname.Text, tboxmysqlpw.Text, /*tboxmysqlsd2db.Text,*/ tboxmysqlwordldb.Text))
         {
             Datastores.dbused = true;
             this.Close();
         }
         else
         {
             MessageBox.Show(SQLConnection.error.Message);
         }
     }
 }
Exemplo n.º 5
0
        private void button2_Click(object sender, EventArgs e)
        {
            SSHConnectionParameter f = new SSHConnectionParameter();

            f.UserName = "******";

            f.Password           = "******";
            f.Protocol           = SSHProtocol.SSH2;
            f.AuthenticationType = AuthenticationType.Password;

            Reader reader = new Reader();
            Socket s      = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            s.Connect(new IPEndPoint(IPAddress.Parse("192.168.10.131"), 22));
            _conn        = SSHConnection.Connect(f, reader, s);
            reader._conn = _conn;
            SSHChannel ch = _conn.OpenShell(reader);

            reader._pf = ch;
            SSHConnectionInfo ci = _conn.ConnectionInfo;

            Thread.Sleep(1000);

            byte[] b = new byte[1];

            string cmd = "ls";

            byte[] data = (new UnicodeEncoding()).GetBytes(cmd);
            reader._pf.Transmit(data);


            Thread.Sleep(5000);
            string x = reader.SessionLog;
            //reader.OnData +=
        }
Exemplo n.º 6
0
 public void Connect(Socket s)
 {
     _params.WindowSize   = 0x1000;
     _params.IdentityFile = SSH2PrivateKeyFile;
     _conn = SSHConnection.Connect(_params, this, s);
     _pf   = _conn.OpenShell(this);
     SSHConnectionInfo ci = _conn.ConnectionInfo;
 }
Exemplo n.º 7
0
        public bool Connect(string host, string username, string password)
        {
            if (IsConnected)
            {
                return(false);
            }

            try
            {
                m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // send TCP keep-alive packets after 10 seconds of inactivity, then every 5 seconds
                SocketUtil.SetKeepAliveValues(m_socket, true, 10 * 1000, 5 * 1000);

                m_socket.Connect(host, 22);

                SSHConnectionParameter f = new SSHConnectionParameter();

                f.UserName           = username;
                f.Password           = password;
                f.Protocol           = SSHProtocol.SSH2;
                f.AuthenticationType = AuthenticationType.Password;
                f.WindowSize         = 0x1000;

                NullReader r = new NullReader();

                if (m_timer != null)
                {
                    m_timer.Stop();
                    m_timer.Dispose();
                }

                m_conn = (SSH2Connection)SSHConnection.Connect(f, r, m_socket);

                m_timer = new Timer();
                // check connection every 10 milliseconds
                m_timer.Interval = 10;

                m_timer.Tick += new EventHandler(OnTimerTick);
            }
            catch (Exception e)
            {
                if (e.Message == "User authentication failed")
                {
                    MessageBox.Show("This username and/or password were not accepted.  Check them and try again",
                                    "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    MessageBox.Show("SSH connection exception: " + e.Message);
                }

                return(false);
            }

            return(true);
        }
Exemplo n.º 8
0
        //Tutorial: Connecting to a host and opening a shell
        private static void ConnectAndOpenShell()
        {
            SampleKeyboardInteractiveAuthenticationHandler authHandler = null;
            SSHConnectionParameter f = new SSHConnectionParameter("172.22.1.15", 22, SSHProtocol.SSH2, AuthenticationType.PublicKey, "okajima", "aaa");

            //former algorithm is given priority in the algorithm negotiation
            f.PreferableHostKeyAlgorithms = new PublicKeyAlgorithm[] { PublicKeyAlgorithm.RSA, PublicKeyAlgorithm.DSA };
            f.PreferableCipherAlgorithms  = new CipherAlgorithm[] { CipherAlgorithm.Blowfish, CipherAlgorithm.TripleDES };
            f.WindowSize = 0x1000; //this option is ignored with SSH1
            f.KeyboardInteractiveAuthenticationHandlerCreator =
                (connection) => {
                return(authHandler = new SampleKeyboardInteractiveAuthenticationHandler("aaa"));
            };

            Tracer tracer = new Tracer();

            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            s.Connect(new IPEndPoint(IPAddress.Parse(f.HostName), f.PortNumber)); //22 is the default SSH port

            ISSHConnection conn;

            if (f.AuthenticationType == AuthenticationType.KeyboardInteractive)
            {
                //Creating a new SSH connection over the underlying socket
                conn = SSHConnection.Connect(s, f, c => new Reader(c), c => new Tracer());
                bool result = authHandler.GetResult();
                Debug.Assert(result == true);
            }
            else
            {
                //NOTE: if you use public-key authentication, follow this sample instead of the line above:
                //f.AuthenticationType = AuthenticationType.PublicKey;
                f.IdentityFile     = "C:\\P4\\tools\\keys\\aaa";
                f.VerifySSHHostKey = (info) => {
                    byte[] h = info.HostKeyFingerPrint;
                    foreach (byte b in h)
                    {
                        Debug.Write(String.Format("{0:x2} ", b));
                    }
                    return(true);
                };

                //Creating a new SSH connection over the underlying socket
                conn = SSHConnection.Connect(s, f, c => new Reader(c), null);
            }

            //Opening a shell
            var ch = conn.OpenShell(channelOperator => new ChannelHandler(channelOperator));

            //you can get the detailed connection information in this way:
            //SSHConnectionInfo ci = _conn.ConnectionInfo;

            //Go to sample shell
            SampleShell(ch);
        }
Exemplo n.º 9
0
 public void OpenConnect()
 {
     f.UserName           = username;
     f.Password           = password;
     f.Protocol           = SSHProtocol.SSH2;
     f.AuthenticationType = AuthenticationType.Password;
     f.WindowSize         = 0x1000;
     s.Connect(new IPEndPoint(IPAddress.Parse(host), port));
     _conn    = SSHConnection.Connect(f, this, s);
     this._pf = _conn.OpenShell(this);
     SSHConnectionInfo ci = _conn.ConnectionInfo;
 }
Exemplo n.º 10
0
        //Tutorial: port forwarding
        private static void ConnectSSH2AndPortforwarding()
        {
            SSHConnectionParameter f = new SSHConnectionParameter();

            f.EventTracer = new Tracer();             //to receive detailed events, set ISSHEventTracer
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            f.Protocol = SSHProtocol.SSH1;                           //this sample works on both SSH1 and SSH2
            string host_ip = "10.10.9.8";                            //<--!!! [TO USERS OF Granados]

            f.UserName = "******";                                     //<--!!! if you try this sample, edit these values for your environment!
            f.Password = "";                                         //<--!!!
            s.Connect(new IPEndPoint(IPAddress.Parse(host_ip), 22)); //22 is the default SSH port

            f.Protocol = SSHProtocol.SSH2;

            f.AuthenticationType = AuthenticationType.Password;
            //NOTE: if you use public-key authentication, follow this sample instead of the line above:
            //  f.AuthenticationType = AuthenticationType.PublicKey;
            //  f.IdentityFile = "privatekey.bin";
            //  f.Password = "******";

            //former algorithm is given priority in the algorithm negotiation
            f.PreferableHostKeyAlgorithms = new PublicKeyAlgorithm[] { PublicKeyAlgorithm.DSA };
            f.PreferableCipherAlgorithms  = new CipherAlgorithm[] { CipherAlgorithm.Blowfish, CipherAlgorithm.TripleDES };

            f.WindowSize = 0x1000;             //this option is ignored with SSH1

            Reader reader = new Reader();      //simple event receiver

            //Creating a new SSH connection over the underlying socket
            _conn        = SSHConnection.Connect(f, reader, s);
            reader._conn = _conn;

            //Local->Remote port forwarding
            SSHChannel ch = _conn.ForwardPort(reader, "www.google.co.jp", 80, "localhost", 0);

            reader._pf = ch;
            while (!reader._ready)
            {
                System.Threading.Thread.Sleep(100);                                 //wait response
            }
            reader._pf.Transmit(Encoding.ASCII.GetBytes("GET / HTTP/1.0\r\n\r\n")); //get the toppage

            //Remote->Local
            // if you want to listen to a port on the SSH server, follow this line:
            //_conn.ListenForwardedPort("0.0.0.0", 10000);

            //NOTE: if you use SSH2, dynamic key exchange feature is supported.
            //((SSH2Connection)_conn).ReexchangeKeys();
        }
Exemplo n.º 11
0
        protected override void Negotiate()
        {
            ITerminalParameter term = (ITerminalParameter)_destination.GetAdapter(typeof(ITerminalParameter));
            ITCPParameter      tcp  = (ITCPParameter)_destination.GetAdapter(typeof(ITCPParameter));

            SSHConnectionParameter con = new SSHConnectionParameter();

#if DEBUG
            // con.EventTracer = new SSHDebugTracer();
#endif
            con.Protocol                    = _destination.Method;
            con.CheckMACError               = PEnv.Options.SSHCheckMAC;
            con.UserName                    = _destination.Account;
            con.Password                    = _destination.PasswordOrPassphrase;
            con.AuthenticationType          = _destination.AuthenticationType;
            con.IdentityFile                = _destination.IdentityFileName;
            con.TerminalWidth               = term.InitialWidth;
            con.TerminalHeight              = term.InitialHeight;
            con.TerminalName                = term.TerminalType;
            con.WindowSize                  = PEnv.Options.SSHWindowSize;
            con.PreferableCipherAlgorithms  = LocalSSHUtil.ParseCipherAlgorithm(PEnv.Options.CipherAlgorithmOrder);
            con.PreferableHostKeyAlgorithms = LocalSSHUtil.ParsePublicKeyAlgorithm(PEnv.Options.HostKeyAlgorithmOrder);
            con.AgentForward                = _destination.AgentForward;
            if (ProtocolsPlugin.Instance.ProtocolOptions.LogSSHEvents)
            {
                con.EventTracer = new SSHEventTracer(tcp.Destination);
            }
            if (_keycheck != null)
            {
                con.KeyCheck += new HostKeyCheckCallback(this.CheckKey);
            }


            SSHTerminalConnection r   = new SSHTerminalConnection(_destination);
            SSHConnection         ssh = SSHConnection.Connect(con, r.ConnectionEventReceiver, _socket);
            if (ssh != null)
            {
                if (PEnv.Options.RetainsPassphrase && _destination.AuthenticationType != AuthenticationType.KeyboardInteractive)
                {
                    ProtocolsPlugin.Instance.PassphraseCache.Add(tcp.Destination, _destination.Account, _destination.PasswordOrPassphrase);                     //接続成功時のみセット
                }
                //_destination.PasswordOrPassphrase = ""; 接続の複製のためにここで消さずに残しておく
                r.AttachTransmissionSide(ssh);
                r.UsingSocks = _socks != null;
                _result      = r;
            }
            else
            {
                throw new IOException(PEnv.Strings.GetString("Message.SSHConnector.Cancelled"));
            }
        }
Exemplo n.º 12
0
        protected override void Negotiate()
        {
            //const string defaultCipherAlgoOrder = "AES256CTR;AES256;AES192CTR;AES192;AES128CTR;AES128;Blowfish;TripleDES";
            //string[] cipherAlgorithmOrderArray = defaultCipherAlgoOrder.Split(new Char[] {';'});
            //string[] hostKeyAlgorithmOrderArray = new string[] { "DSA", "RSA" };

            SSHConnectionParameter con = new SSHConnectionParameter();

            con.Protocol           = _destination.Method;
            con.CheckMACError      = (System.Boolean)true; // PEnv.Options.SSHCheckMAC;
            con.UserName           = _destination.Account;
            con.Password           = _destination.PasswordOrPassphrase;
            con.AuthenticationType = _destination.AuthenticationType;
            con.IdentityFile       = _destination.IdentityFileName;
            con.TerminalWidth      = _destination.InitialWidth;
            con.TerminalHeight     = _destination.InitialHeight;
            con.TerminalName       = _destination.TerminalType;
            con.WindowSize         = _client.ConMain.ProtocolOptions.SSHWindowSize;
            //con.PreferableCipherAlgorithms = LocalSSHUtil.ParseCipherAlgorithm(ConsoleMain.Instance.ProtocolOptions.CipherAlgorithmOrder);
            //con.PreferableHostKeyAlgorithms = ConsoleMain.Instance.ProtocolOptions.HostKeyAlgorithmOrder;
            con.AgentForward = _destination.AgentForward;
            if (_client.ConMain.ProtocolOptions.LogSSHEvents)
            {
                con.EventTracer = new SSHEventTracer(_destination.Destination);
            }
            if (_keycheck != null)
            {
                con.KeyCheck += new HostKeyCheckCallback(this.CheckKey);
            }

            SSHTerminalConnection r   = new SSHTerminalConnection((ISSHLoginParameter)_destination);
            SSHConnection         ssh = SSHConnection.Connect(con, r.ConnectionEventReceiver, _socket);

            if (ssh != null)
            {
                if (_client.ConMain.ProtocolOptions.RetainsPassphrase && _destination.AuthenticationType != AuthenticationType.KeyboardInteractive)
                {
                    _client.ConMain.PassphraseCache.Add(_destination.Destination, _destination.Account, _destination.PasswordOrPassphrase); //Ú‘±¬Œ÷Žž‚̂݃Zƒbƒg
                }
                ////_destination.PasswordOrPassphrase = ""; Ú‘±‚Ì•¡»‚Ì‚½‚ß‚É‚±‚±‚ŏÁ‚³‚¸‚ÉŽc‚µ‚Ä‚¨‚­
                r.AttachTransmissionSide(ssh);
                r.UsingSocks = _socks != null;
                _result      = r;
            }
            else
            {
                throw new IOException("Message.SSHConnector.Cancelled");
            }
        }
Exemplo n.º 13
0
        protected override void Negotiate()
        {
            SSHConnectionParameter con = new SSHConnectionParameter();

            con.Protocol           = _param.Method == ConnectionMethod.SSH1 ? SSHProtocol.SSH1 : SSHProtocol.SSH2;
            con.CheckMACError      = GEnv.Options.SSHCheckMAC;
            con.UserName           = _param.Account;
            con.Password           = _password;
            con.AuthenticationType = _param.AuthType == AuthType.KeyboardInteractive ? AuthenticationType.KeyboardInteractive : _param.AuthType == AuthType.Password ? AuthenticationType.Password : AuthenticationType.PublicKey;
            con.IdentityFile       = _param.IdentityFile;
            con.TerminalWidth      = _size.Width;
            con.TerminalHeight     = _size.Height;
            con.TerminalName       = EnumDescAttribute.For(typeof(TerminalType)).GetDescription(_param.TerminalType);
            //con.TerminalName = "xterm";
            con.WindowSize = GEnv.Options.SSHWindowSize;
            con.PreferableCipherAlgorithms  = LocalSSHUtil.ParseCipherAlgorithm(GEnv.Options.CipherAlgorithmOrder);
            con.PreferableHostKeyAlgorithms = LocalSSHUtil.ParsePublicKeyAlgorithm(GEnv.Options.HostKeyAlgorithmOrder);
            if (_keycheck != null)
            {
                con.KeyCheck += new HostKeyCheckCallback(this.CheckKey);
            }

            SSHTerminalConnection r   = new SSHTerminalConnection(_param, _size.Width, _size.Height);
            SSHConnection         ssh = SSHConnection.Connect(con, r, _socket);

            if (ssh != null)
            {
                if (GEnv.Options.RetainsPassphrase)
                {
                    _param.Passphrase = _password;
                }

                r.FixConnection(ssh);

                if (ssh.AuthenticationResult == AuthenticationResult.Success)
                {
                    r.OpenShell();
                }

                r.UsingSocks = _socks != null;
                r.SetServerInfo(_param.Host, this.IPAddress);

                _result = new ConnectionTag(r);
            }
            else
            {
                throw new IOException(GEnv.Strings.GetString("Message.SSHConnector.Cancelled"));
            }
        }
Exemplo n.º 14
0
        //Tutorial: port forwarding
        private static void ConnectSSH2AndPortforwarding()
        {
            SSHConnectionParameter f = new SSHConnectionParameter("10.10.9.8", 22, SSHProtocol.SSH2, AuthenticationType.Password, "root", "");

            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            s.Connect(new IPEndPoint(IPAddress.Parse(f.HostName), f.PortNumber)); //22 is the default SSH port

            //NOTE: if you use public-key authentication, follow this sample instead of the line above:
            //  f.AuthenticationType = AuthenticationType.PublicKey;
            //  f.IdentityFile = "privatekey.bin";
            //  f.Password = "******";

            //former algorithm is given priority in the algorithm negotiation
            f.PreferableHostKeyAlgorithms = new PublicKeyAlgorithm[] { PublicKeyAlgorithm.DSA };
            f.PreferableCipherAlgorithms  = new CipherAlgorithm[] { CipherAlgorithm.Blowfish, CipherAlgorithm.TripleDES };

            f.WindowSize = 0x1000; //this option is ignored with SSH1

            //Creating a new SSH connection over the underlying socket
            Reader reader = null;
            var    conn   = SSHConnection.Connect(s, f,
                                                  c => {
                return(reader = new Reader(c));
            },
                                                  c => new Tracer());

            Debug.Assert(reader != null);

            //Local->Remote port forwarding
            ChannelHandler ch = conn.ForwardPort(
                channelOperator => new ChannelHandler(channelOperator),
                "www.google.co.jp", 80u, "localhost", 0u);

            while (!reader._ready)
            {
                System.Threading.Thread.Sleep(100); //wait response
            }
            byte[] data = Encoding.ASCII.GetBytes("GET / HTTP/1.0\r\n\r\n");
            ch.Operator.Send(new DataFragment(data, 0, data.Length)); //get the toppage

            //Remote->Local
            // if you want to listen to a port on the SSH server, follow this line:
            //_conn.ListenForwardedPort("0.0.0.0", 10000);

            //NOTE: if you use SSH2, dynamic key exchange feature is supported.
            //((SSH2Connection)_conn).ReexchangeKeys();
        }
Exemplo n.º 15
0
        private void OpenShell()
        {
            m_cmdLineAdapter = Dialect.CreateCmdLineAdapter();
            m_stream         = new PipeStream();
            //m_reader = new StreamReader(m_stream);
            SSHConnectionParameter f = new SSHConnectionParameter();

            f.UserName           = Params.SshLogin;
            f.Password           = Params.SshPassword;
            f.Protocol           = SSHProtocol.SSH2;
            f.AuthenticationType = AuthenticationType.Password;
            f.WindowSize         = 0x1000;
            m_treader            = new STunReader(m_stream);
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            s.Connect(Params.SshHost, Params.SshPort);
            m_conn = SSHConnection.Connect(f, m_treader, s);

            m_treader.Channel = m_conn.OpenShell(m_treader);

            //SSHConnectionInfo ci = m__conn.ConnectionInfo;

            //byte[] b = new byte[1];
            //while (true)
            //{
            //    int input = System.Console.Read();

            //    b[0] = (byte)input;
            //    //Debug.WriteLine(input);
            //    reader._pf.Transmit(b);
            //}


            //m_shell = new SshShell(Params.SshHost, Params.SshLogin);
            //if (!String.IsNullOrEmpty(Params.SshPassword)) m_shell.Password = Params.SshPassword;
            //if (!String.IsNullOrEmpty(Params.IdentifyFile)) m_shell.AddIdentityFile(Params.IdentifyFile);
            //m_shell.Connect(Params.SshPort);
            //m_shell.WriteLine("echo AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
            //m_instream = new PipeStream();
            //m_outstream = new PipeStream();
            //m_outstream.BlockLastReadBuffer = false;
            //m_shell.SetStream(m_instream, m_outstream);
            ////m_stream = m_shell.GetStream();
            ////m_shell.m_instream = (PipedInputStream)((CombinedStream)m_stream).InputStream;
            //m_reader = new StreamReader(m_outstream);
            //ConsumeOutput();
        }
Exemplo n.º 16
0
        private static void AgentForward()
        {
            SSHConnectionParameter f = new SSHConnectionParameter();

            f.EventTracer = new Tracer(); //to receive detailed events, set ISSHEventTracer
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            f.Protocol = SSHProtocol.SSH2;  //this sample works on both SSH1 and SSH2
            string host_ip = "172.22.1.15"; //<--!!! [TO USERS OF Granados]

            f.UserName = "******";            //<--!!! if you try this sample, edit these values for your environment!
            string password = "";

            s.Connect(new IPEndPoint(IPAddress.Parse(host_ip), 22)); //22 is the default SSH port

            //former algorithm is given priority in the algorithm negotiation
            f.PreferableHostKeyAlgorithms = new PublicKeyAlgorithm[] { PublicKeyAlgorithm.RSA, PublicKeyAlgorithm.DSA };
            f.PreferableCipherAlgorithms  = new CipherAlgorithm[] { CipherAlgorithm.Blowfish, CipherAlgorithm.TripleDES };
            f.WindowSize   = 0x1000;      //this option is ignored with SSH1
            f.AgentForward = new AgentForwardClient();
            Reader reader = new Reader(); //simple event receiver

            AuthenticationType at = AuthenticationType.Password;

            f.AuthenticationType = at;
            f.Password           = password;

            //Creating a new SSH connection over the underlying socket
            _conn        = SSHConnection.Connect(f, reader, s);
            reader._conn = _conn;

            //Opening a shell
            SSHChannel ch = _conn.OpenShell(reader);

            reader._pf = ch;

            while (!reader._ready)
            {
                Thread.Sleep(100);
            }

            Thread.Sleep(1000);
            ch.Transmit(Encoding.Default.GetBytes("ssh -A -l okajima localhost\r"));

            //Go to sample shell
            SampleShell(reader);
        }
Exemplo n.º 17
0
        private static void AgentForward()
        {
            SSHConnectionParameter f = new SSHConnectionParameter("172.22.1.15", 22, SSHProtocol.SSH2, AuthenticationType.Password, "root", "");

            Tracer tracer = new Tracer();

            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            s.Connect(new IPEndPoint(IPAddress.Parse(f.HostName), f.PortNumber)); //22 is the default SSH port

            //former algorithm is given priority in the algorithm negotiation
            f.PreferableHostKeyAlgorithms = new PublicKeyAlgorithm[] { PublicKeyAlgorithm.RSA, PublicKeyAlgorithm.DSA };
            f.PreferableCipherAlgorithms  = new CipherAlgorithm[] { CipherAlgorithm.Blowfish, CipherAlgorithm.TripleDES };
            f.WindowSize = 0x1000; //this option is ignored with SSH1
            f.AgentForwardingAuthKeyProvider = new AgentForwardingAuthKeyProvider();

            //Creating a new SSH connection over the underlying socket
            Reader reader = null;
            var    conn   = SSHConnection.Connect(s, f,
                                                  c => {
                return(reader = new Reader(c));
            },
                                                  c => new Tracer()
                                                  );

            Debug.Assert(reader != null);

            //Opening a shell
            var ch = conn.OpenShell(channelOperator => new ChannelHandler(channelOperator));

            while (!reader._ready)
            {
                Thread.Sleep(100);
            }

            Thread.Sleep(1000);
            byte[] data = Encoding.Default.GetBytes("ssh -A -l okajima localhost\r");
            ch.Operator.Send(new DataFragment(data, 0, data.Length));

            //Go to sample shell
            SampleShell(ch);
        }
Exemplo n.º 18
0
        protected override void Negotiate()
        {
            SSHConnectionParameter con = new SSHConnectionParameter();

            con.Protocol                    = SSHProtocol.SSH2;
            con.UserName                    = _profile.SSHAccount;
            con.Password                    = _password;
            con.AuthenticationType          = _profile.AuthType;
            con.IdentityFile                = _profile.PrivateKeyFile;
            con.PreferableCipherAlgorithms  = SSHUtil.ParseCipherAlgorithm(Env.Options.CipherAlgorithmOrder);
            con.PreferableHostKeyAlgorithms = SSHUtil.ParsePublicKeyAlgorithm(Env.Options.HostKeyAlgorithmOrder);
            con.WindowSize                  = Env.Options.SSHWindowSize;
            con.CheckMACError               = Env.Options.SSHCheckMAC;
            if (_keycheck != null)
            {
                con.KeyCheck += new HostKeyCheckCallback(this.CheckKey);
            }

            _result = ChannelFactory.Create(_profile);
            SSHConnection c = SSHConnection.Connect(con, _result, _socket);

            c.AutoDisconnect = false;
            if (c != null)
            {
                /*
                 * if(_profile.ProtocolType==ProtocolType.Udp)
                 *  OpenUdpDestination(c, (UdpChannelFactory)_result);
                 * else
                 */
                _result.FixConnection(c);
                if (Env.Options.RetainsPassphrase)
                {
                    _profile.Passphrase = _password; //接続成功時のみセット
                }
            }
            else
            {
                throw new IOException(Env.Strings.GetString("Message.ConnectionManager.ConnectionCancelled"));
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Method to connect to the Wabis machine
        /// </summary>
        /// <returns>true if connected else false</returns>
        public bool Connect()
        {
            connParameter.Protocol           = Routrek.SSHC.SSHProtocol.SSH2;
            connParameter.AuthenticationType = AuthenticationType.Password;
            connParameter.WindowSize         = 0x1000;
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);

            try
            {
                s.Connect(new IPEndPoint(_ipAddress, 22));
            }
            catch
            {
                s.Close();
                return(false);
            }

            try
            {
                _conn             = SSHConnection.Connect(connParameter, reader, s);
                reader.connection = _conn;
                Routrek.SSHC.SSHChannel ch = _conn.OpenShell(reader);
                reader.Channel = ch;
                SSHConnectionInfo ci = _conn.ConnectionInfo;
                reader.notify += new RcvdData(PrintResult);
                if (_conn.AuthenticationResult.ToString() == "Success")
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception connectionException)
            {
                Framework.Logger.LogError("Fail to connect to SSH Server, error: " + connectionException.Message);
                throw connectionException;
            }
        }
Exemplo n.º 20
0
        protected override void Negotiate()
        {
            SSHConnectionParameter con = new SSHConnectionParameter(_host, _port, SSHProtocol.SSH2, _profile.AuthType, _profile.SSHAccount, _password);

            con.IdentityFile = _profile.PrivateKeyFile;
            con.PreferableCipherAlgorithms  = SSHUtil.ParseCipherAlgorithm(Env.Options.CipherAlgorithmOrder);
            con.PreferableHostKeyAlgorithms = SSHUtil.ParsePublicKeyAlgorithm(Env.Options.HostKeyAlgorithmOrder);
            con.WindowSize    = Env.Options.SSHWindowSize;
            con.CheckMACError = Env.Options.SSHCheckMAC;
            if (_keycheck != null)
            {
                con.VerifySSHHostKey = this.CheckKey;
            }

            _result = ChannelFactory.Create(_profile);
            ISSHConnection c = SSHConnection.Connect(
                _socket, con,
                sshconn => _result, null);

            if (c != null)
            {
                /*
                 * if(_profile.ProtocolType==ProtocolType.Udp)
                 *  OpenUdpDestination(c, (UdpChannelFactory)_result);
                 * else
                 */
                _result.FixConnection(c);
                if (Env.Options.RetainsPassphrase)
                {
                    _profile.Passphrase = _password; //接続成功時のみセット
                }
            }
            else
            {
                throw new IOException(Env.Strings.GetString("Message.ConnectionManager.ConnectionCancelled"));
            }
        }
Exemplo n.º 21
0
        private void Connect(ConnectionInfo con)
        {
            if (String.IsNullOrWhiteSpace(Password))
            {
                DialogResult res = Login();
                if (res != DialogResult.OK)
                {
                    return;
                }
            }

            con.Password = Password;
            con.UserName = Settings.Default.UserName;

            this.Cursor = Cursors.WaitCursor;

            SSHConnection ssh = new SSHConnection();

            if (!ssh.Connect(con))
            {
                Password = "";
                Connect(con);
                this.Cursor = Cursors.Default;
                return;
            }


            this.SuspendLayout();
            ConnectionTab tab = CreateTab(String.Format("{0} - {1}", con.ConnectionName, con.Host), ssh);

            //commandString = "tail -f /apps/jboss/wildfly/standalone/log/server.log";
            //tab.Connection.ExecuteCommand("tail -f -n 100 /apps/jboss/wildfly/standalone/log/server.log");

            this.ResumeLayout();
            this.Cursor = Cursors.Default;
        }
Exemplo n.º 22
0
        protected override void Negotiate()
        {
            ITerminalParameter term = (ITerminalParameter)_destination.GetAdapter(typeof(ITerminalParameter));
            ITCPParameter      tcp  = (ITCPParameter)_destination.GetAdapter(typeof(ITCPParameter));

            SSHTerminalConnection terminalConnection = new SSHTerminalConnection(_destination);

            SSHConnectionParameter con =
                new SSHConnectionParameter(
                    tcp.Destination,
                    tcp.Port,
                    _destination.Method,
                    _destination.AuthenticationType,
                    _destination.Account,
                    _destination.PasswordOrPassphrase);

#if DEBUG
            // con.EventTracer = new SSHDebugTracer();
#endif
            con.Protocol                       = _destination.Method;
            con.CheckMACError                  = PEnv.Options.SSHCheckMAC;
            con.UserName                       = _destination.Account;
            con.Password                       = _destination.PasswordOrPassphrase;
            con.AuthenticationType             = _destination.AuthenticationType;
            con.IdentityFile                   = _destination.IdentityFileName;
            con.TerminalWidth                  = term.InitialWidth;
            con.TerminalHeight                 = term.InitialHeight;
            con.TerminalName                   = term.TerminalType;
            con.WindowSize                     = PEnv.Options.SSHWindowSize;
            con.PreferableCipherAlgorithms     = LocalSSHUtil.ParseCipherAlgorithm(PEnv.Options.CipherAlgorithmOrder);
            con.PreferableHostKeyAlgorithms    = LocalSSHUtil.ParsePublicKeyAlgorithm(PEnv.Options.HostKeyAlgorithmOrder);
            con.AgentForwardingAuthKeyProvider = _destination.AgentForwardingAuthKeyProvider;
            if (_keycheck != null)
            {
                con.VerifySSHHostKey = (info) => {
                    return(_keycheck.Vefiry(info));
                };
            }
            con.KeyboardInteractiveAuthenticationHandlerCreator =
                sshconn => terminalConnection.GetKeyboardInteractiveAuthenticationHandler();

            ISSHProtocolEventLogger protocolEventLogger;
            if (ProtocolsPlugin.Instance.ProtocolOptions.LogSSHEvents)
            {
                protocolEventLogger = new SSHEventTracer(tcp.Destination);
            }
            else
            {
                protocolEventLogger = null;
            }

            var connection = SSHConnection.Connect(_socket, con,
                                                   sshconn => terminalConnection.ConnectionEventReceiver,
                                                   sshconn => protocolEventLogger);
            if (PEnv.Options.RetainsPassphrase && _destination.AuthenticationType != AuthenticationType.KeyboardInteractive)
            {
                ProtocolsPlugin.Instance.PassphraseCache.Add(tcp.Destination, _destination.Account, _destination.PasswordOrPassphrase); //接続成功時のみセット
            }
            //_destination.PasswordOrPassphrase = ""; 接続の複製のためにここで消さずに残しておく
            terminalConnection.AttachTransmissionSide(connection, connection.AuthenticationStatus);
            _result = terminalConnection;
        }
Exemplo n.º 23
0
        protected override void Negotiate()
        {
            ITerminalParameter term = (ITerminalParameter)_destination.GetAdapter(typeof(ITerminalParameter));
            ITCPParameter      tcp  = (ITCPParameter)_destination.GetAdapter(typeof(ITCPParameter));

            SSHTerminalConnection terminalConnection = new SSHTerminalConnection(_destination);

            SSHConnectionParameter con =
                new SSHConnectionParameter(
                    tcp.Destination,
                    tcp.Port,
                    _destination.Method,
                    _destination.AuthenticationType,
                    _destination.Account,
                    _destination.PasswordOrPassphrase);

#if DEBUG
            // con.EventTracer = new SSHDebugTracer();
#endif
            con.Protocol                   = _destination.Method;
            con.CheckMACError              = PEnv.Options.SSHCheckMAC;
            con.UserName                   = _destination.Account;
            con.Password                   = _destination.PasswordOrPassphrase;
            con.AuthenticationType         = _destination.AuthenticationType;
            con.IdentityFile               = _destination.IdentityFileName;
            con.TerminalWidth              = term.InitialWidth;
            con.TerminalHeight             = term.InitialHeight;
            con.TerminalName               = term.TerminalType;
            con.WindowSize                 = PEnv.Options.SSHWindowSize;
            con.Timeouts.ResponseTimeout   = PEnv.Options.SSHResponseTimeout;
            con.PreferableCipherAlgorithms =
                LocalSSHUtil.AppendMissingCipherAlgorithm(
                    LocalSSHUtil.ParseCipherAlgorithm(PEnv.Options.CipherAlgorithmOrder));
            con.PreferableHostKeyAlgorithms =
                LocalSSHUtil.AppendMissingPublicKeyAlgorithm(
                    LocalSSHUtil.ParsePublicKeyAlgorithm(PEnv.Options.HostKeyAlgorithmOrder));
            con.AgentForwardingAuthKeyProvider = _destination.AgentForwardingAuthKeyProvider;
            con.X11ForwardingParams            = _destination.X11Forwarding;
            if (_keycheck != null)
            {
                con.VerifySSHHostKey = (info) => {
                    return(_keycheck.Vefiry(info));
                };
            }
            con.KeyboardInteractiveAuthenticationHandlerCreator =
                sshconn => terminalConnection.GetKeyboardInteractiveAuthenticationHandler();

            ISSHProtocolEventLogger protocolEventLogger;
            if (ProtocolsPlugin.Instance.ProtocolOptions.LogSSHEvents)
            {
                protocolEventLogger = new SSHEventTracer(tcp.Destination);
            }
            else
            {
                protocolEventLogger = null;
            }

            var connection = SSHConnection.Connect(_socket, con,
                                                   sshconn => terminalConnection.ConnectionEventReceiver,
                                                   sshconn => protocolEventLogger);

            // Note: password must not be cleared here. it will be required when duplicating connection later.

            // The login settings was accepted.
            // No need to ask a password on the new attempt to login from the shortcut functionality.
            _destination.LetUserInputPassword = false;

            terminalConnection.AttachTransmissionSide(connection, connection.AuthenticationStatus);
            _result = terminalConnection;
        }
Exemplo n.º 24
0
        /// <summary>
        /// Connect to remote host:port over SSH tunnel
        /// </summary>
        public void Connect(string host, int port)
        {
            try
            {
                //remember remote target
                m_RemoteTarget = new IPEndPoint(ResolveHost(host), port);

                //connect to SSH server
                m_Client.Connect(new IPEndPoint(m_RemoteTarget.Address, SSHServerPort));

                //get password from user
                var pass = ErlTransportPasswordSource.GetPassword(this, NodeName, SSHUserName);

                //set params
                var param = new SSHConnectionParameter();
                param.EventTracer        = this; //to receive detailed events
                param.UserName           = SSHUserName;
                param.Password           = pass;
                param.Protocol           = SSHProtocol.SSH2;
                param.AuthenticationType = (AuthenticationType)Enum.Parse(typeof(SSH.AuthenticationType), SSHAuthenticationType);

                if (param.AuthenticationType == AuthenticationType.PublicKey)
                {
                    param.IdentityFile = SSHPrivateKeyFilePath;
                }

                //former algorithm is given priority in the algorithm negotiation
                param.PreferableHostKeyAlgorithms = new PublicKeyAlgorithm[] { PublicKeyAlgorithm.RSA, PublicKeyAlgorithm.DSA };
                param.PreferableCipherAlgorithms  = new CipherAlgorithm[] { CipherAlgorithm.Blowfish, CipherAlgorithm.TripleDES, CipherAlgorithm.AES192CTR, CipherAlgorithm.AES256CTR, CipherAlgorithm.AES128CTR };

                param.WindowSize = 0x1000; //this option is ignored with SSH1

                //Creating a new SSH connection over the underlying socket
                m_Connection = SSHConnection.Connect(param, this, m_Client);
                m_Connection.AutoDisconnect = true;
                m_IsChannelReady            = false;

                //Local->Remote port forwarding (we use localhost:0 as local port, because local port is not required for us, we will use this tunnel directly)
                m_Channel = m_Connection.ForwardPort(this, host, port, "localhost", 0);
                var deadLine = DateTime.Now.AddMilliseconds(SSHTunnelCreationTimeout);
                while (!m_IsChannelReady && deadLine > DateTime.Now)
                {
                    System.Threading.Thread.Sleep(50); //wait response
                }
                //if timeouted - throw exception
                if (!m_IsChannelReady && deadLine < DateTime.Now)
                {
                    throw new ErlException(ERL_CREATE_SSH_TUNNEL_ERROR);
                }

                //create network stream
                m_Stream = new SshTunnelStream(m_Channel);

                //Remote->Local
                // if you want to listen to a port on the SSH server, follow this line:
                //_conn.ListenForwardedPort("0.0.0.0", 10000);

                //NOTE: if you use SSH2, dynamic key exchange feature is supported.
                //((SSH2Connection)_conn).ReexchangeKeys();
            }
            catch (Exception ex)
            {
                OnTrace(ErlTraceLevel.Ctrl, Direction.Inbound, ex.Message);
                throw;
            }
        }
Exemplo n.º 25
0
        public void CheckFresh()
        {
            //if (ThreadManager.IsRunning == false) return;

            try
            {
                string[] cols = row.Split('|');
                Host = cols[0].Trim();
                User = cols[1].Trim();
                Pass = cols[2].Trim();
                if (cols.Count() == 3)
                {
                    Country = "UNKNOWN";
                }
                else
                {
                    Country = cols[3].Trim();
                }
                _f                    = new SSHConnectionParameter();
                _f.UserName           = User;
                _f.Password           = Pass;
                _f.Protocol           = SSHProtocol.SSH2;
                _f.AuthenticationType = AuthenticationType.Password;
                _f.WindowSize         = 0x1000;

                _reader = new Reader();
                _reader.TimeoutSeconds = TimeoutSeconds;
                _reader.passControl    = new Reader.PassControl(passControl);
                _reader._country       = Country;
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //s.Blocking = false;
                _socket.SendTimeout    = TimeoutSeconds * 1000;
                _socket.ReceiveTimeout = TimeoutSeconds * 1000;
                _socket.Connect(new IPEndPoint(IPAddress.Parse(Host), DefaultPort));

                new Thread(new ThreadStart(SetSSHConnectionTimeout)).Start();
                _conn = SSHConnection.Connect(_f, _reader, _socket);
                if (SSHConnectTimeout)
                {
                    throw new Exception("SSH Connect Timeout");
                }
                _reader._conn = _conn;

                SSHChannel ch = _conn.ForwardPort(_reader, "ipinfo.io", 80, "localhost", 80);
                _reader._pf = ch;

                int seconds = TimeoutSeconds;
                while (_reader._ready == false && seconds > 0)
                {
                    seconds--; Thread.Sleep(1000);
                }
                if (_reader._ready == false && seconds <= 0)
                {
                    throw new Exception("Reader._ready timeout");
                }

                _reader.LineIndex = LineIndex;
                _reader.Host      = Host;
                _reader.User      = User;
                _reader.Pass      = Pass;

                new Thread(new ThreadStart(_reader.SetHTTPRequestTimeout)).Start();
                _reader._pf.Transmit(Encoding.ASCII.GetBytes("GET /json HTTP/1.1\r\nHost:ipinfo.io\r\n\r\n")); //http://ipinfo.io/json
            }
            catch (Exception ex)
            {
                passControl(LineIndex, false, "", ex.Message);
            }
        }
Exemplo n.º 26
0
        // This method uses SCP protocol.
        private static void ScpCommand(string[] args)
        {
            ScpParameter scp_param = new ScpParameter();

#if true //OKAJIMA
#if true
            scp_param.Direction      = SCPCopyDirection.LocalToRemote;
            scp_param.RemoteFilename = "test.txt";
            scp_param.LocalSource    = new ScpLocalSource("C:\\IOPort\\test.txt");
#else
            scp_param.Direction      = SCPCopyDirection.RemoteToLocal;
            scp_param.RemoteFilename = "hiro.jpg";
            scp_param.LocalSource    = new ScpLocalSource("C:\\IOPort\\hiro.jpg");
#endif
            //string host_ip;
            //string username, password;

            SSHConnectionParameter f = new SSHConnectionParameter();
            f.EventTracer = new Tracer();             //to receive detailed events, set ISSHEventTracer
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            f.Protocol           = SSHProtocol.SSH2;
            f.UserName           = "******";                                //<--!!! if you try this sample, edit these values for your environment!
            f.Password           = "******";                             //<--!!!
            f.AuthenticationType = AuthenticationType.Password;
            s.Connect(new IPEndPoint(IPAddress.Parse("172.22.1.2"), 22)); //22 is the default SSH port

            SSHConnection conn = SSHConnection.Connect(f, new Reader(), s);
            conn.AutoDisconnect = false; //auto close is disabled for multiple scp operations
            conn.ExecuteSCP(scp_param);

            conn.Disconnect("");
#endif
#if HIRATA
            // check argument
            if (args.Length != 6)
            {
                Console.WriteLine("Usage: ScpCommand <server:port> <username> <password> to|from <src_file> <dst_file>");
                Environment.Exit(0);
            }

            // test pattern
            int test = 103;

            if (test == 0)
            {
                args[0] = "192.168.1.2";
                args[1] = "yutaka";
                args[2] = "yutaka";
                args[3] = "to";
                args[4] = "hoge6.txt";
                args[5] = "hoge6s.txt";
            }
            if (test == 1)
            {
                args[0] = "192.168.1.2";
                args[1] = "yutaka";
                args[2] = "yutaka";
                args[3] = "to";
                args[4] = "hoge28k.txt";
                args[5] = "hoge28ks.txt";
            }
            if (test == 2)
            {
                args[0] = "192.168.1.2";
                args[1] = "yutaka";
                args[2] = "yutaka";
                args[3] = "to";
                args[4] = null;   // use Local Memory
                args[5] = "hogeLM.txt";
            }
            if (test == 3)   // big file transfer
            {
                args[0] = "192.168.1.2";
                args[1] = "yutaka";
                args[2] = "yutaka";
                args[3] = "to";
                args[4] = "bigfile.bin";
                args[5] = "bigfile.bin";
            }

            if (test == 100)
            {
                args[0] = "192.168.1.2";
                args[1] = "yutaka";
                args[2] = "yutaka";
                args[3] = "from";
                args[4] = "hoge6.txt";
                args[5] = "hoge6c.txt";
            }
            if (test == 101)
            {
                args[0] = "192.168.1.2";
                args[1] = "yutaka";
                args[2] = "yutaka";
                args[3] = "from";
                args[4] = "hoge28k.txt";
                args[5] = "hoge28kc.txt";
            }
            if (test == 102)
            {
                args[0] = "192.168.1.2";
                args[1] = "yutaka";
                args[2] = "yutaka";
                args[3] = "from";
                args[4] = "hoge6.txt";
                //args[4] = "hoge28k.txt";
                args[5] = null; // use Local Memory
            }
            if (test == 103)    // big file transfer
            {
                args[0] = "192.168.1.2";
                args[1] = "yutaka";
                args[2] = "yutaka";
                args[3] = "from";
                args[4] = "bigfile.bin";
                args[5] = "bigfilec.bin";
            }

            host_ip  = args[0];
            username = args[1];
            password = args[2];

            // setup SCP parameter
            if (args[3] == "to")                // Local to Remote
            {
                if (args[5] == null || args[5] == "")
                {
                    param.RemoteFilename = null;
                }
                else
                {
                    param.RemoteFilename = args[5];  // remote file
                }

                // 転送元の指定(ローカルファイルおよびローカルメモリを選択)
                if (args[4] != null)
                {
                    // ローカルファイルの転送
                    param.LocalSource = args[4]; // src file
                }
                else
                {
                    // オンラインメモリの転送
                    //param.IoStream = new MemoryStream(256);
                    param.IoStream = new MemoryStream(8192);
                    for (int i = 0; i < 8192; i++)
                    {
                        param.IoStream.WriteByte((byte)i);
                    }
                    param.IoStream.Seek(0, SeekOrigin.Begin);
                }
                param.Direction = true;

                param.Permission = "0666";
            }
            else                                // Remote to Local
            {
                param.RemoteFilename = args[4]; // remote file

                // 転送元の指定(ローカルファイルおよびローカルメモリを選択)
                if (args[5] != null)
                {
                    // ローカルファイルの転送
                    param.LocalSource = args[5];
                }
                else
                {
                    // オンラインメモリの転送
                    param.IoStream = null;
                }
                param.Direction = false;
            }

            // connect to server with SSH protocol
            SSHConnectionParameter f = new SSHConnectionParameter();
            f.EventTracer = new Tracer();             //to receive detailed events, set ISSHEventTracer
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            f.Protocol = SSHProtocol.SSH2;                           //this sample works on both SSH1 and SSH2
            f.UserName = username;                                   //<--!!! if you try this sample, edit these values for your environment!
            f.Password = password;                                   //<--!!!
            s.Connect(new IPEndPoint(IPAddress.Parse(host_ip), 22)); //22 is the default SSH port

            f.AuthenticationType = AuthenticationType.Password;
            //NOTE: if you use public-key authentication, follow this sample instead of the line above:
            //  f.AuthenticationType = AuthenticationType.PublicKey;
            //  f.IdentityFile = "privatekey.bin";
            //  f.Password = "******";

            //former algorithm is given priority in the algorithm negotiation
            f.PreferableHostKeyAlgorithms = new PublicKeyAlgorithm[] { PublicKeyAlgorithm.DSA };
            f.PreferableCipherAlgorithms  = new CipherAlgorithm[] { CipherAlgorithm.Blowfish, CipherAlgorithm.TripleDES };

            //this option is ignored with SSH1
            f.WindowSize = 0x1000; //NG: ERROR: MAC mismatch
            //f.WindowSize = 0x800; //NG
            //f.WindowSize = 0x30000; //NG
            //f.WindowSize = 0x400; //OK
            //f.CheckMACError = false; //NG: unexpected channel pt=SSH_MSG_CHANNEL_DATA local_channel=33243

            /* USER OPTION */
            //param.CancelTransfer = true;  // cancel flag
            param.ProgressCallback = delegate() { Debug.Write("*"); };   // callback function

            if (SSHConnection.SCPExecute(param, f, s))
            {
                Debug.WriteLine("scp success!");

                if (param.Direction == false)
                {
                    if (param.IoStream != null)
                    {
                        Debug.Write("IO Stream: ");
                        for (int i = 0; i < param.IoStream.Length; i++)
                        {
                            byte b = (byte)param.IoStream.ReadByte();
                            Debug.Write(b.ToString("x2") + " ");
                        }
                        Debug.WriteLine("");
                    }
                }
            }
            else
            {
                Debug.WriteLine("scp failure: " + param.ErrorMessage);
            }
#endif
        }
Exemplo n.º 27
0
        public bool CheckFresh(string SSH, int timeout)
        {
            bool flag;

            try
            {
                string[] strArrays = SSH.Split(new char[] { '|' });
                this.Host = strArrays[0].Trim();
                this.User = strArrays[1].Trim();
                this.Pass = strArrays[2].Trim();
                this._f   = new SSHConnectionParameter()
                {
                    UserName           = this.User,
                    Password           = this.Pass,
                    Protocol           = SSHProtocol.SSH2,
                    AuthenticationType = AuthenticationType.Password,
                    WindowSize         = 4096
                };
                this._reader = new Reader();
                this._socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                {
                    SendTimeout    = timeout,
                    ReceiveTimeout = timeout
                };
                this._socket.Connect(new IPEndPoint(IPAddress.Parse(this.Host), 22));
                SshChecker._sshTimeOut = timeout;
                (new Thread(new ThreadStart(this.SetSSHConnectionTimeout))).Start();
                this._conn = SSHConnection.Connect(this._f, this._reader, this._socket);
                if (this.SSHConnectTimeout)
                {
                    throw new Exception("SSH Connect Timeout");
                }
                this._reader._conn = this._conn;
                SSHChannel sSHChannel = this._conn.ForwardPort(this._reader, "ipinfo.io", 80, "localhost", 80);
                this._reader._pf = sSHChannel;
                int num = timeout;
                while (true)
                {
                    if ((this._reader._ready ? true : num <= 0))
                    {
                        break;
                    }
                    num--;
                    Thread.Sleep(1000);
                }
                if ((this._reader._ready ? false : num <= 0))
                {
                    throw new Exception("Reader._ready timeout");
                }
                this._reader.Host = this.Host;
                this._reader.User = this.User;
                this._reader.Pass = this.Pass;
                this._reader.SetHTTPRequestTimeout();
                SshChecker.checkDone = false;
                this._reader._pf.Transmit(Encoding.ASCII.GetBytes("GET /json HTTP/1.1\r\nHost:ipinfo.io\r\n\r\n"));
                DateTime now = DateTime.Now;
                while (!SshChecker.checkDone)
                {
                    Thread.Sleep(100);
                    if ((DateTime.Now - now).TotalSeconds > (double)timeout)
                    {
                        throw new Exception("Request timeout");
                    }
                }
                if (!SshChecker.isFresh)
                {
                    flag = false;
                    return(flag);
                }
            }
            catch (Exception exception)
            {
                flag = false;
                return(flag);
            }
            flag = true;
            return(flag);
        }
Exemplo n.º 28
0
        //Tutorial: Connecting to a host and opening a shell
        private static void ConnectAndOpenShell()
        {
            SSHConnectionParameter f = new SSHConnectionParameter();

            f.EventTracer = new Tracer();             //to receive detailed events, set ISSHEventTracer
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            f.Protocol = SSHProtocol.SSH2;  //this sample works on both SSH1 and SSH2
            string host_ip = "172.22.1.15"; //<--!!! [TO USERS OF Granados]

            f.UserName = "******";         //<--!!! if you try this sample, edit these values for your environment!
            string password = "******";

            s.Connect(new IPEndPoint(IPAddress.Parse(host_ip), 22));             //22 is the default SSH port

            //former algorithm is given priority in the algorithm negotiation
            f.PreferableHostKeyAlgorithms = new PublicKeyAlgorithm[] { PublicKeyAlgorithm.RSA, PublicKeyAlgorithm.DSA };
            f.PreferableCipherAlgorithms  = new CipherAlgorithm[] { CipherAlgorithm.Blowfish, CipherAlgorithm.TripleDES };
            f.WindowSize = 0x1000;        //this option is ignored with SSH1
            Reader reader = new Reader(); //simple event receiver

            AuthenticationType at = AuthenticationType.PublicKey;

            f.AuthenticationType = at;

            if (at == AuthenticationType.KeyboardInteractive)
            {
                //Creating a new SSH connection over the underlying socket
                _conn        = SSHConnection.Connect(f, reader, s);
                reader._conn = _conn;
                Debug.Assert(_conn.AuthenticationResult == AuthenticationResult.Prompt);
                AuthenticationResult r = ((SSH2Connection)_conn).DoKeyboardInteractiveAuth(new string[] { password });
                Debug.Assert(r == AuthenticationResult.Success);
            }
            else
            {
                //NOTE: if you use public-key authentication, follow this sample instead of the line above:
                //f.AuthenticationType = AuthenticationType.PublicKey;
                f.IdentityFile = "C:\\P4\\tools\\keys\\aaa";
                f.Password     = password;
                f.KeyCheck     = delegate(SSHConnectionInfo info) {
                    byte[] h = info.HostKeyMD5FingerPrint();
                    foreach (byte b in h)
                    {
                        Debug.Write(String.Format("{0:x2} ", b));
                    }
                    return(true);
                };

                //Creating a new SSH connection over the underlying socket
                _conn        = SSHConnection.Connect(f, reader, s);
                reader._conn = _conn;
            }

            //Opening a shell
            SSHChannel ch = _conn.OpenShell(reader);

            reader._pf = ch;

            //you can get the detailed connection information in this way:
            SSHConnectionInfo ci = _conn.ConnectionInfo;

            //Go to sample shell
            SampleShell(reader);
        }
Exemplo n.º 29
0
        // Token: 0x060003D1 RID: 977 RVA: 0x0002707C File Offset: 0x0002527C
        public bool CheckFresh(string SSH, int timeout)
        {
            bool result;

            try
            {
                string[] array = SSH.Split(new char[]
                {
                    '|'
                });
                this.Host                   = array[0].Trim();
                this.User                   = array[1].Trim();
                this.Pass                   = array[2].Trim();
                this._f                     = new SSHConnectionParameter();
                this._f.UserName            = this.User;
                this._f.Password            = this.Pass;
                this._f.Protocol            = SSHProtocol.SSH2;
                this._f.AuthenticationType  = AuthenticationType.Password;
                this._f.WindowSize          = 4096;
                this._reader                = new Reader();
                this._socket                = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                this._socket.SendTimeout    = timeout;
                this._socket.ReceiveTimeout = timeout;
                this._socket.Connect(new IPEndPoint(IPAddress.Parse(this.Host), 22));
                SshChecker._sshTimeOut = timeout;
                new Thread(new ThreadStart(this.SetSSHConnectionTimeout)).Start();
                this._conn = SSHConnection.Connect(this._f, this._reader, this._socket);
                bool sSHConnectTimeout = this.SSHConnectTimeout;
                if (sSHConnectTimeout)
                {
                    throw new Exception("SSH Connect Timeout");
                }
                this._reader._conn = this._conn;
                SSHChannel pf = this._conn.ForwardPort(this._reader, "ipinfo.io", 80, "localhost", 80);
                this._reader._pf = pf;
                int num = timeout;
                while (!this._reader._ready && num > 0)
                {
                    num--;
                    Thread.Sleep(1000);
                }
                bool flag = !this._reader._ready && num <= 0;
                if (flag)
                {
                    throw new Exception("Reader._ready timeout");
                }
                this._reader.Host = this.Host;
                this._reader.User = this.User;
                this._reader.Pass = this.Pass;
                this._reader.SetHTTPRequestTimeout();
                SshChecker.checkDone = false;
                this._reader._pf.Transmit(Encoding.ASCII.GetBytes("GET /json HTTP/1.1\r\nHost:ipinfo.io\r\n\r\n"));
                DateTime now = DateTime.Now;
                while (!SshChecker.checkDone)
                {
                    Thread.Sleep(100);
                    bool flag2 = (DateTime.Now - now).TotalSeconds > (double)timeout;
                    if (flag2)
                    {
                        throw new Exception("Request timeout");
                    }
                }
                bool flag3 = !SshChecker.isFresh;
                if (flag3)
                {
                    result = false;
                    return(result);
                }
            }
            catch (Exception var_13_297)
            {
                result = false;
                return(result);
            }
            result = true;
            return(result);
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            /*
             * string cn = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
             * string t1 = Routrek.SSHC.Strings.GetString("NotSSHServer");
             * System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ja");
             * Routrek.SSHC.Strings.Reload();
             * string t2 = Routrek.SSHC.Strings.GetString("NotSSHServer");
             */

#if false //RSA keygen
            //RSA KEY GENERATION TEST
            byte[]     testdata = Encoding.ASCII.GetBytes("CHRISTIAN VIERI");
            RSAKeyPair kp       = RSAKeyPair.GenerateNew(2048, new Random());
            byte[]     sig      = kp.Sign(testdata);
            kp.Verify(sig, testdata);

            new SSH2UserAuthKey(kp).WritePublicPartInOpenSSHStyle(new FileStream("C:\\IOPort\\newrsakey", FileMode.Create));
            //SSH2UserAuthKey newpk = SSH2PrivateKey.FromSECSHStyleFile("C:\\IOPort\\newrsakey", "nedved");
#endif

#if false //DSA keygen
            //DSA KEY GENERATION TEST
            byte[]     testdata = Encoding.ASCII.GetBytes("CHRISTIAN VIERI 0000");
            DSAKeyPair kp       = DSAKeyPair.GenerateNew(2048, new Random());
            byte[]     sig      = kp.Sign(testdata);
            kp.Verify(sig, testdata);
            new SSH2UserAuthKey(kp).WritePublicPartInOpenSSHStyle(new FileStream("C:\\IOPort\\newdsakey", FileMode.Create));
            //SSH2PrivateKey newpk = SSH2PrivateKey.FromSECSHStyleFile("C:\\IOPort\\newdsakey", "nedved");
#endif

            SSHConnectionParameter f = new SSHConnectionParameter();
            f.UserName = "******";
#if false //SSH1
            //SSH1
            f.Password                   = "";
            f.Protocol                   = SSHProtocol.SSH2;
            f.AuthenticationType         = AuthenticationType.Password;
            f.PreferableCipherAlgorithms = new CipherAlgorithm[] { CipherAlgorithm.Blowfish, CipherAlgorithm.TripleDES };
#else //SSH2
            f.Password           = "";
            f.Protocol           = SSHProtocol.SSH2;
            f.AuthenticationType = AuthenticationType.Password;
            f.WindowSize         = 0x1000;
#endif
            Reader reader = new Reader();
            Socket s      = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //s.Blocking = false;
            s.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.1"), 22));
            _conn        = SSHConnection.Connect(f, reader, s);
            reader._conn = _conn;
#if false   //Remote->Local
            _conn.ListenForwardedPort("0.0.0.0", 29472);
#elif false //Local->Remote
            SSHChannel ch = _conn.ForwardPort(reader, "www.yahoo.co.jp", 80, "localhost", 0);
            reader._pf = ch;
            while (!reader._ready)
            {
                System.Threading.Thread.Sleep(100);
            }
            reader._pf.Transmit(Encoding.ASCII.GetBytes("GET / HTTP/1.0\r\n\r\n"));
#elif false //SSH over SSH
            f.Password = "******";
            SSHConnection con2 = _conn.OpenPortForwardedAnotherConnection(f, reader, "kuromatsu", 22);
            reader._conn = con2;
            SSHChannel ch = con2.OpenShell(reader);
            reader._pf = ch;
#else //normal shell
            SSHChannel ch = _conn.OpenShell(reader);
            reader._pf = ch;
#endif

            //Debug.WriteLine(_conn.ConnectionInfo.DumpHostKeyInKnownHostsStyle());
            SSHConnectionInfo ci = _conn.ConnectionInfo;

            Thread.Sleep(1000);
            //((SSH2Connection)_conn).ReexchangeKeys();

            byte[] b = new byte[1];
            while (true)
            {
                int input = System.Console.Read();

                b[0] = (byte)input;
                //Debug.WriteLine(input);
                reader._pf.Transmit(b);
            }
        }