public void EstablishPortforwarding(ISSHChannelEventReceiver rec, SSHChannel channel)
 {
     _pf = channel;
 }
 public void RegisterChannel(int local_id, SSHChannel ch)
 {
     throw new NotImplementedException();
 }
Beispiel #3
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="channel">SSH2 channel object</param>
 /// <param name="channelReceiver">event receiver object</param>
 private SFTPClient(SSHChannel channel, SFTPClientChannelEventReceiver channelReceiver)
 {
     this._channel = channel;
     this._channelReceiver = channelReceiver;
 }
Beispiel #4
0
 public void OpenShell()
 {
     _channel = _connection.OpenShell(this);
 }
Beispiel #5
0
 public virtual void EstablishPortforwarding(ISSHChannelEventReceiver receiver, SSHChannel channel)
 {
 }
 public SynchronizedSSHChannel(SSHChannel ch)
 {
     _channel    = ch;
     _connection = _channel.Connection;
     _closed     = false;
 }
Beispiel #7
0
 /// <summary>
 /// Create a new subsystem channel
 /// </summary>
 /// <param name="channel"></param>
 public SubsystemChannel(SSHChannel channel)
 {
     this.channel = channel;
 }
Beispiel #8
0
 // Token: 0x06000520 RID: 1312 RVA: 0x00031C2C File Offset: 0x0002FE2C
 public bool CheckFresh(string SSH, int timeout)
 {
     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, "ip-api.com", 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:\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)
         {
             return(false);
         }
     }
     catch (Exception ex)
     {
         return(false);
     }
     return(true);
 }
Beispiel #9
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;
            }
        }
Beispiel #10
0
 public void RegisterChannel(int local_id, SSHChannel ch)
 {
     FindChannelEntry(local_id)._channel = ch;
 }
Beispiel #11
0
        protected ChannelEntry RegisterChannelEventReceiver(SSHChannel ch, ISSHChannelEventReceiver r)
        {
            lock (this)
            {
                ChannelEntry e = new ChannelEntry();
                e._channel = ch;
                e._receiver = r;
                e._localID = _channel_sequence++;

                for (int i = 0; i < _channel_entries.Count; i++)
                {
                    if (_channel_entries[i] == null)
                    {
                        _channel_entries[i] = e;
                        return e;
                    }
                }
                _channel_entries.Add(e);
                return e;
            }
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            /*
             * string cn = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
             * string t1 = Granados.SSHC.Strings.GetString("NotSSHServer");
             * System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ja");
             * Granados.SSHC.Strings.Reload();
             * string t2 = Granados.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);
            }
        }
 public void FixChannel(SSHChannel ch)
 {
     _channel = new SynchronizedSSHChannel(ch);
     Env.Log.LogChannelOpened(_remoteDescription, _connectionID);
 }
 public override void EstablishPortforwarding(ISSHChannelEventReceiver receiver, SSHChannel channel)
 {
     try {
         Channel ch = (Channel)receiver;
         ch.FixChannel(channel);
         ch.OnChannelReady();
         ch.StartAsyncReceive();
     }
     catch (Exception ex) {
         Debug.WriteLine(ex.StackTrace);
         Util.InterThreadWarning(ex.Message);
     }
 }
Beispiel #15
0
        /// <summary>
        /// Opens channel.
        /// </summary>
        /// <param name="connection">SSH connection object</param>
        /// <param name="command">Remote command</param>
        /// <param name="millisecondsTimeout">timeout in milliseconds</param>
        /// <exception cref="SCPClientInvalidStatusException">Channel has been already opened or already closed.</exception>
        /// <exception cref="SCPClientTimeoutException">Timeout has occurred while waiting for READY status.</exception>
        public void Open(SSHConnection connection, string command, int millisecondsTimeout)
        {
            if (_status != StreamStatus.NotOpened)
                throw new SCPClientInvalidStatusException();

            SCPClientChannelEventReceiver channelReceiver =
                new SCPClientChannelEventReceiver(
                    new DataReceivedDelegate(OnDataReceived),
                    new ChannelStatusChangedDelegate(OnChannelStatusChanged)
                );

            SSHChannel channel;
            /* FIXME: SSH1's executing command is not implemented !!
            if (connection is SSH1Connection) {
                channel = ((SSH1Connection)connection).DoExecCommand(channelReceiver, command);
            }
            else
            */
            if (connection is SSH2Connection) {
                channel = ((SSH2Connection)connection).DoExecCommand(channelReceiver, command);
            }
            else {
                // FIXME:
                //throw new ArgumentException("connection must be SSH1Connection or SSH2Connection.");
                throw new ArgumentException("connection must be SSH2Connection.");
            }

            _channelReceiver = channelReceiver;
            _channel = channel;

            lock (_channelReceiver.StatusChangeNotifier) {
                while (_channelReceiver.ChannelStatus != SCPChannelStatus.READY) {
                    bool signaled = Monitor.Wait(_channelReceiver.StatusChangeNotifier, millisecondsTimeout);
                    if (!signaled) {
                        throw new SCPClientTimeoutException();
                    }
                }
            }

            lock(_statusSync) {
                if (_status == StreamStatus.NotOpened) {
                    _status = StreamStatus.Opened;
                }
            }
        }
Beispiel #16
0
 public void EstablishPortforwarding(ISSHChannelEventReceiver rec, SSHChannel channel)
 {
     _pf = channel;
 }
Beispiel #17
0
        internal void OpenForTest(SSHChannel dummyChannel)
        {
            if (_status != StreamStatus.NotOpened)
                throw new SCPClientInvalidStatusException();

            SCPClientChannelEventReceiver channelReceiver =
                new SCPClientChannelEventReceiver(
                    new DataReceivedDelegate(OnDataReceived),
                    new ChannelStatusChangedDelegate(OnChannelStatusChanged)
                );

            _channelReceiver = channelReceiver;
            _channel = dummyChannel;

            lock (_statusSync) {
                if (_status == StreamStatus.NotOpened) {
                    _status = StreamStatus.Opened;
                }
            }
        }
Beispiel #18
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);
        }