/// <exception cref="System.Exception"></exception>
        internal override void DoRequest(Session session, Channel channel)
        {
            base.DoRequest(session, channel);
            Buffer buf    = new Buffer();
            Packet packet = new Packet(buf);

            //byte      SSH_MSG_CHANNEL_REQUEST
            //uint32    recipient_channel
            //string    "window-change"
            //boolean   FALSE
            //uint32    terminal width, columns
            //uint32    terminal height, rows
            //uint32    terminal width, pixels
            //uint32    terminal height, pixels
            packet.Reset();
            buf.PutByte(unchecked ((byte)Session.SSH_MSG_CHANNEL_REQUEST));
            buf.PutInt(channel.GetRecipient());
            buf.PutString(Util.Str2byte("window-change"));
            buf.PutByte(unchecked ((byte)(WaitForReply() ? 1 : 0)));
            buf.PutInt(width_columns);
            buf.PutInt(height_rows);
            buf.PutInt(width_pixels);
            buf.PutInt(height_pixels);
            Write(packet);
        }
Exemple #2
0
        /// <exception cref="System.Exception"></exception>
        internal override void DoRequest(Session session, Channel channel)
        {
            base.DoRequest(session, channel);
            Buffer buf    = new Buffer();
            Packet packet = new Packet(buf);

            // byte      SSH_MSG_CHANNEL_REQUEST(98)
            // uint32 recipient channel
            // string request type        // "x11-req"
            // boolean want reply         // 0
            // boolean   single connection
            // string    x11 authentication protocol // "MIT-MAGIC-COOKIE-1".
            // string    x11 authentication cookie
            // uint32    x11 screen number
            packet.Reset();
            buf.PutByte(unchecked ((byte)Session.SSH_MSG_CHANNEL_REQUEST));
            buf.PutInt(channel.GetRecipient());
            buf.PutString(Util.Str2byte("x11-req"));
            buf.PutByte(unchecked ((byte)(WaitForReply() ? 1 : 0)));
            buf.PutByte(unchecked ((byte)0));
            buf.PutString(Util.Str2byte("MIT-MAGIC-COOKIE-1"));
            buf.PutString(ChannelX11.GetFakedCookie(session));
            buf.PutInt(0);
            Write(packet);
            session.x11_forwarding = true;
        }
Exemple #3
0
		/// <exception cref="System.Exception"></exception>
		internal override void DoRequest(Session session, Channel channel)
		{
			base.DoRequest(session, channel);
			Buffer buf = new Buffer();
			Packet packet = new Packet(buf);
			// byte      SSH_MSG_CHANNEL_REQUEST(98)
			// uint32 recipient channel
			// string request type        // "x11-req"
			// boolean want reply         // 0
			// boolean   single connection
			// string    x11 authentication protocol // "MIT-MAGIC-COOKIE-1".
			// string    x11 authentication cookie
			// uint32    x11 screen number
			packet.Reset();
			buf.PutByte(unchecked((byte)Session.SSH_MSG_CHANNEL_REQUEST));
			buf.PutInt(channel.GetRecipient());
			buf.PutString(Util.Str2byte("x11-req"));
			buf.PutByte(unchecked((byte)(WaitForReply() ? 1 : 0)));
			buf.PutByte(unchecked((byte)0));
			buf.PutString(Util.Str2byte("MIT-MAGIC-COOKIE-1"));
			buf.PutString(ChannelX11.GetFakedCookie(session));
			buf.PutInt(0);
			Write(packet);
			session.x11_forwarding = true;
		}
        internal static void DelPort(Session session, string address_to_bind, int rport)
        {
            lock (pool)
            {
                object[] foo = null;
                for (int i = 0; i < pool.Count; i++)
                {
                    object[] bar = (object[])(pool[i]);
                    if (bar[0] != session)
                    {
                        continue;
                    }
                    if (((int)bar[1]) != rport)
                    {
                        continue;
                    }
                    foo = bar;
                    break;
                }
                if (foo == null)
                {
                    return;
                }
                pool.RemoveElement(foo);
                if (address_to_bind == null)
                {
                    address_to_bind = (string)foo[4];
                }
                if (address_to_bind == null)
                {
                    address_to_bind = "0.0.0.0";
                }
            }
            Buffer buf = new Buffer(100);
            // ??
            Packet packet = new Packet(buf);

            try
            {
                // byte SSH_MSG_GLOBAL_REQUEST 80
                // string "cancel-tcpip-forward"
                // boolean want_reply
                // string  address_to_bind (e.g. "127.0.0.1")
                // uint32  port number to bind
                packet.Reset();
                buf.PutByte(unchecked ((byte)80));
                buf.PutString(Util.Str2byte("cancel-tcpip-forward"));
                buf.PutByte(unchecked ((byte)0));
                buf.PutString(Util.Str2byte(address_to_bind));
                buf.PutInt(rport);
                session.Write(packet);
            }
            catch (Exception)
            {
            }
        }
		/// <exception cref="System.Exception"></exception>
		internal override void DoRequest(Session session, Channel channel)
		{
			base.DoRequest(session, channel);
			Buffer buf = new Buffer();
			Packet packet = new Packet(buf);
			packet.Reset();
			buf.PutByte(unchecked((byte)Session.SSH_MSG_CHANNEL_REQUEST));
			buf.PutInt(channel.GetRecipient());
			buf.PutString(Util.Str2byte("subsystem"));
			buf.PutByte(unchecked((byte)(WaitForReply() ? 1 : 0)));
			buf.PutString(Util.Str2byte(subsystem));
			Write(packet);
		}
Exemple #6
0
        /// <exception cref="System.Exception"></exception>
        internal override void DoRequest(Session session, Channel channel)
        {
            base.DoRequest(session, channel);
            Buffer buf    = new Buffer();
            Packet packet = new Packet(buf);

            packet.Reset();
            buf.PutByte(unchecked ((byte)Session.SSH_MSG_CHANNEL_REQUEST));
            buf.PutInt(channel.GetRecipient());
            buf.PutString(Util.Str2byte("subsystem"));
            buf.PutByte(unchecked ((byte)(WaitForReply() ? 1 : 0)));
            buf.PutString(Util.Str2byte(subsystem));
            Write(packet);
        }
Exemple #7
0
        public override void Run()
        {
            Buffer buf    = new Buffer(rmpsize);
            Packet packet = new Packet(buf);
            int    i      = 0;

            try
            {
                Session _session = GetSession();
                while (IsConnected() && thread != null && io != null && io.@in != null)
                {
                    i = [email protected](buf.buffer, 14, buf.buffer.Length - 14 - 32 - 20);
                    // padding and mac
                    if (i <= 0)
                    {
                        Eof();
                        break;
                    }
                    if (close)
                    {
                        break;
                    }
                    packet.Reset();
                    buf.PutByte(unchecked ((byte)Session.SSH_MSG_CHANNEL_DATA));
                    buf.PutInt(recipient);
                    buf.PutInt(i);
                    buf.Skip(i);
                    _session.Write(packet, this, i);
                }
            }
            catch (Exception)
            {
            }
            Disconnect();
        }
Exemple #8
0
 internal virtual void Eof()
 {
     if (eof_local)
     {
         return;
     }
     eof_local = true;
     try
     {
         Buffer buf    = new Buffer(100);
         Packet packet = new Packet(buf);
         packet.Reset();
         buf.PutByte(unchecked ((byte)Session.SSH_MSG_CHANNEL_EOF));
         buf.PutInt(GetRecipient());
         lock (this)
         {
             if (!close)
             {
                 GetSession().Write(packet);
             }
         }
     }
     catch (Exception)
     {
     }
 }
Exemple #9
0
		/// <exception cref="System.Exception"></exception>
		internal override void DoRequest(Session session, Channel channel)
		{
			base.DoRequest(session, channel);
			Buffer buf = new Buffer();
			Packet packet = new Packet(buf);
			// send
			// byte     SSH_MSG_CHANNEL_REQUEST(98)
			// uint32 recipient channel
			// string request type       // "shell"
			// boolean want reply        // 0
			packet.Reset();
			buf.PutByte(unchecked((byte)Session.SSH_MSG_CHANNEL_REQUEST));
			buf.PutInt(channel.GetRecipient());
			buf.PutString(Util.Str2byte("shell"));
			buf.PutByte(unchecked((byte)(WaitForReply() ? 1 : 0)));
			Write(packet);
		}
Exemple #10
0
        /// <exception cref="System.Exception"></exception>
        internal override void DoRequest(Session session, Channel channel)
        {
            base.DoRequest(session, channel);
            Buffer buf    = new Buffer();
            Packet packet = new Packet(buf);

            // send
            // byte     SSH_MSG_CHANNEL_REQUEST(98)
            // uint32 recipient channel
            // string request type       // "shell"
            // boolean want reply        // 0
            packet.Reset();
            buf.PutByte(unchecked ((byte)Session.SSH_MSG_CHANNEL_REQUEST));
            buf.PutInt(channel.GetRecipient());
            buf.PutString(Util.Str2byte("shell"));
            buf.PutByte(unchecked ((byte)(WaitForReply() ? 1 : 0)));
            Write(packet);
        }
		/// <exception cref="System.Exception"></exception>
		internal override void DoRequest(Session session, Channel channel)
		{
			base.DoRequest(session, channel);
			SetReply(false);
			Buffer buf = new Buffer();
			Packet packet = new Packet(buf);
			// byte      SSH_MSG_CHANNEL_REQUEST(98)
			// uint32 recipient channel
			// string request type        // "*****@*****.**"
			// boolean want reply         // 0
			packet.Reset();
			buf.PutByte(unchecked((byte)Session.SSH_MSG_CHANNEL_REQUEST));
			buf.PutInt(channel.GetRecipient());
			buf.PutString(Util.Str2byte("*****@*****.**"));
			buf.PutByte(unchecked((byte)(WaitForReply() ? 1 : 0)));
			Write(packet);
			session.agent_forwarding = true;
		}
Exemple #12
0
		/// <exception cref="System.Exception"></exception>
		internal override void DoRequest(Session session, Channel channel)
		{
			base.DoRequest(session, channel);
			Buffer buf = new Buffer();
			Packet packet = new Packet(buf);
			packet.Reset();
			buf.PutByte(unchecked((byte)Session.SSH_MSG_CHANNEL_REQUEST));
			buf.PutInt(channel.GetRecipient());
			buf.PutString(Util.Str2byte("pty-req"));
			buf.PutByte(unchecked((byte)(WaitForReply() ? 1 : 0)));
			buf.PutString(Util.Str2byte(ttype));
			buf.PutInt(tcol);
			buf.PutInt(trow);
			buf.PutInt(twp);
			buf.PutInt(thp);
			buf.PutString(terminal_mode);
			Write(packet);
		}
Exemple #13
0
        /// <exception cref="System.Exception"></exception>
        internal override void DoRequest(Session session, Channel channel)
        {
            base.DoRequest(session, channel);
            Buffer buf    = new Buffer();
            Packet packet = new Packet(buf);

            packet.Reset();
            buf.PutByte(unchecked ((byte)Session.SSH_MSG_CHANNEL_REQUEST));
            buf.PutInt(channel.GetRecipient());
            buf.PutString(Util.Str2byte("pty-req"));
            buf.PutByte(unchecked ((byte)(WaitForReply() ? 1 : 0)));
            buf.PutString(Util.Str2byte(ttype));
            buf.PutInt(tcol);
            buf.PutInt(trow);
            buf.PutInt(twp);
            buf.PutInt(thp);
            buf.PutString(terminal_mode);
            Write(packet);
        }
Exemple #14
0
        /// <exception cref="System.Exception"></exception>
        internal override void DoRequest(Session session, Channel channel)
        {
            base.DoRequest(session, channel);
            SetReply(false);
            Buffer buf    = new Buffer();
            Packet packet = new Packet(buf);

            // byte      SSH_MSG_CHANNEL_REQUEST(98)
            // uint32 recipient channel
            // string request type        // "*****@*****.**"
            // boolean want reply         // 0
            packet.Reset();
            buf.PutByte(unchecked ((byte)Session.SSH_MSG_CHANNEL_REQUEST));
            buf.PutInt(channel.GetRecipient());
            buf.PutString(Util.Str2byte("*****@*****.**"));
            buf.PutByte(unchecked ((byte)(WaitForReply() ? 1 : 0)));
            Write(packet);
            session.agent_forwarding = true;
        }
Exemple #15
0
        public override void Run()
        {
            try
            {
                socket         = Util.CreateSocket(host, port, TIMEOUT);
                socket.NoDelay = true;
                io             = new IO();
                io.SetInputStream(socket.GetInputStream());
                io.SetOutputStream(socket.GetOutputStream());
                SendOpenConfirmation();
            }
            catch (Exception)
            {
                SendOpenFailure(SSH_OPEN_ADMINISTRATIVELY_PROHIBITED);
                close = true;
                Disconnect();
                return;
            }
            thread = Sharpen.Thread.CurrentThread();
            Buffer buf    = new Buffer(rmpsize);
            Packet packet = new Packet(buf);
            int    i      = 0;

            try
            {
                while (thread != null && io != null && io.@in != null)
                {
                    i = [email protected](buf.buffer, 14, buf.buffer.Length - 14 - 32 - 20);
                    // padding and mac
                    if (i <= 0)
                    {
                        Eof();
                        break;
                    }
                    if (close)
                    {
                        break;
                    }
                    packet.Reset();
                    buf.PutByte(unchecked ((byte)Session.SSH_MSG_CHANNEL_DATA));
                    buf.PutInt(recipient);
                    buf.PutInt(i);
                    buf.Skip(i);
                    GetSession().Write(packet, this, i);
                }
            }
            catch (Exception)
            {
            }
            //System.err.println(e);
            Disconnect();
        }
Exemple #16
0
        /// <exception cref="System.Exception"></exception>
        protected internal virtual void SendOpenConfirmation()
        {
            Buffer buf    = new Buffer(100);
            Packet packet = new Packet(buf);

            packet.Reset();
            buf.PutByte(unchecked ((byte)SSH_MSG_CHANNEL_OPEN_CONFIRMATION));
            buf.PutInt(GetRecipient());
            buf.PutInt(id);
            buf.PutInt(lwsize);
            buf.PutInt(lmpsize);
            GetSession().Write(packet);
        }
Exemple #17
0
        public override void Run()
        {
            //System.err.println(this+":run >");
            Buffer buf    = new Buffer(rmpsize);
            Packet packet = new Packet(buf);
            int    i      = -1;

            try
            {
                while (IsConnected() && thread != null && io != null && io.@in != null)
                {
                    i = [email protected](buf.buffer, 14, buf.buffer.Length - 14 - 32 - 20);
                    // padding and mac
                    if (i == 0)
                    {
                        continue;
                    }
                    if (i == -1)
                    {
                        Eof();
                        break;
                    }
                    if (close)
                    {
                        break;
                    }
                    //System.out.println("write: "+i);
                    packet.Reset();
                    buf.PutByte(unchecked ((byte)Session.SSH_MSG_CHANNEL_DATA));
                    buf.PutInt(recipient);
                    buf.PutInt(i);
                    buf.Skip(i);
                    GetSession().Write(packet, this, i);
                }
            }
            catch (Exception)
            {
            }
            //System.err.println("# ChannelExec.run");
            //e.printStackTrace();
            Sharpen.Thread _thread = thread;
            if (_thread != null)
            {
                lock (_thread)
                {
                    Sharpen.Runtime.NotifyAll(_thread);
                }
            }
            thread = null;
        }
Exemple #18
0
 private void Send(byte[] message)
 {
     packet.Reset();
     wbuf.PutByte(unchecked ((byte)Session.SSH_MSG_CHANNEL_DATA));
     wbuf.PutInt(recipient);
     wbuf.PutInt(4 + message.Length);
     wbuf.PutString(message);
     try
     {
         GetSession().Write(packet, this, 4 + message.Length);
     }
     catch (Exception)
     {
     }
 }
		/// <exception cref="System.Exception"></exception>
		internal override void DoRequest(Session session, Channel channel)
		{
			base.DoRequest(session, channel);
			Buffer buf = new Buffer();
			Packet packet = new Packet(buf);
			//byte      SSH_MSG_CHANNEL_REQUEST
			//uint32    recipient_channel
			//string    "window-change"
			//boolean   FALSE
			//uint32    terminal width, columns
			//uint32    terminal height, rows
			//uint32    terminal width, pixels
			//uint32    terminal height, pixels
			packet.Reset();
			buf.PutByte(unchecked((byte)Session.SSH_MSG_CHANNEL_REQUEST));
			buf.PutInt(channel.GetRecipient());
			buf.PutString(Util.Str2byte("window-change"));
			buf.PutByte(unchecked((byte)(WaitForReply() ? 1 : 0)));
			buf.PutInt(width_columns);
			buf.PutInt(height_rows);
			buf.PutInt(width_pixels);
			buf.PutInt(height_pixels);
			Write(packet);
		}
 //  static int min=512;
 //  static int preferred=1024;
 //  static int max=2000;
 //  com.jcraft.jsch.DH dh;
 //private byte[] f;
 /// <exception cref="System.Exception"></exception>
 public override void Init(Session session, byte[] V_S, byte[] V_C, byte[] I_S, byte
                           [] I_C)
 {
     this.session = session;
     this.V_S     = V_S;
     this.V_C     = V_C;
     this.I_S     = I_S;
     this.I_C     = I_C;
     try
     {
         Type c = Sharpen.Runtime.GetType(session.GetConfig("sha-1"));
         sha = (HASH)(System.Activator.CreateInstance(c));
         sha.Init();
     }
     catch (Exception e)
     {
         System.Console.Error.WriteLine(e);
     }
     buf    = new Buffer();
     packet = new Packet(buf);
     try
     {
         Type c = Sharpen.Runtime.GetType(session.GetConfig("dh"));
         dh = (NSch.DH)(System.Activator.CreateInstance(c));
         dh.Init();
     }
     catch (Exception e)
     {
         //      System.err.println(e);
         throw;
     }
     packet.Reset();
     buf.PutByte(unchecked ((byte)SSH_MSG_KEX_DH_GEX_REQUEST));
     buf.PutInt(min);
     buf.PutInt(preferred);
     buf.PutInt(max);
     session.Write(packet);
     if (JSch.GetLogger().IsEnabled(Logger.INFO))
     {
         JSch.GetLogger().Log(Logger.INFO, "SSH_MSG_KEX_DH_GEX_REQUEST(" + min + "<" + preferred
                              + "<" + max + ") sent");
         JSch.GetLogger().Log(Logger.INFO, "expecting SSH_MSG_KEX_DH_GEX_GROUP");
     }
     state = SSH_MSG_KEX_DH_GEX_GROUP;
 }
Exemple #21
0
 protected internal virtual void SendOpenFailure(int reasoncode)
 {
     try
     {
         Buffer buf    = new Buffer(100);
         Packet packet = new Packet(buf);
         packet.Reset();
         buf.PutByte(unchecked ((byte)SSH_MSG_CHANNEL_OPEN_FAILURE));
         buf.PutInt(GetRecipient());
         buf.PutInt(reasoncode);
         buf.PutString(Util.Str2byte("open failed"));
         buf.PutString(Util.empty);
         GetSession().Write(packet);
     }
     catch (Exception)
     {
     }
 }
        protected internal virtual Packet GenChannelOpenPacket()
        {
            Buffer buf    = new Buffer(100);
            Packet packet = new Packet(buf);

            // byte   SSH_MSG_CHANNEL_OPEN(90)
            // string channel type         //
            // uint32 sender channel       // 0
            // uint32 initial window size  // 0x100000(65536)
            // uint32 maxmum packet size   // 0x4000(16384)
            packet.Reset();
            buf.PutByte(unchecked ((byte)90));
            buf.PutString(this.type);
            buf.PutInt(this.id);
            buf.PutInt(this.lwsize);
            buf.PutInt(this.lmpsize);
            return(packet);
        }
        protected internal override Packet GenChannelOpenPacket()
        {
            Buffer buf    = new Buffer(150);
            Packet packet = new Packet(buf);

            // byte   SSH_MSG_CHANNEL_OPEN(90)
            // string channel type         //
            // uint32 sender channel       // 0
            // uint32 initial window size  // 0x100000(65536)
            // uint32 maxmum packet size   // 0x4000(16384)
            packet.Reset();
            buf.PutByte(unchecked ((byte)90));
            buf.PutString(this.type);
            buf.PutInt(id);
            buf.PutInt(lwsize);
            buf.PutInt(lmpsize);
            buf.PutString(Util.Str2byte(host));
            buf.PutInt(port);
            buf.PutString(Util.Str2byte(originator_IP_address));
            buf.PutInt(originator_port);
            return(packet);
        }
 public override void Run()
 {
     try
     {
         SendChannelOpen();
         Buffer  buf      = new Buffer(rmpsize);
         Packet  packet   = new Packet(buf);
         Session _session = GetSession();
         int     i        = 0;
         while (IsConnected() && thread != null && io != null && io.@in != null)
         {
             i = [email protected](buf.buffer, 14, buf.buffer.Length - 14 - Session.buffer_margin);
             if (i <= 0)
             {
                 Eof();
                 break;
             }
             packet.Reset();
             buf.PutByte(unchecked ((byte)Session.SSH_MSG_CHANNEL_DATA));
             buf.PutInt(recipient);
             buf.PutInt(i);
             buf.Skip(i);
             lock (this)
             {
                 if (close)
                 {
                     break;
                 }
                 _session.Write(packet, this, i);
             }
         }
     }
     catch (Exception)
     {
     }
     Disconnect();
 }
		internal static void DelPort(Session session, string address_to_bind, int rport)
		{
			lock (pool)
			{
				object[] foo = null;
				for (int i = 0; i < pool.Count; i++)
				{
					object[] bar = (object[])(pool[i]);
					if (bar[0] != session)
					{
						continue;
					}
					if (((int)bar[1]) != rport)
					{
						continue;
					}
					foo = bar;
					break;
				}
				if (foo == null)
				{
					return;
				}
				pool.RemoveElement(foo);
				if (address_to_bind == null)
				{
					address_to_bind = (string)foo[4];
				}
				if (address_to_bind == null)
				{
					address_to_bind = "0.0.0.0";
				}
			}
			Buffer buf = new Buffer(100);
			// ??
			Packet packet = new Packet(buf);
			try
			{
				// byte SSH_MSG_GLOBAL_REQUEST 80
				// string "cancel-tcpip-forward"
				// boolean want_reply
				// string  address_to_bind (e.g. "127.0.0.1")
				// uint32  port number to bind
				packet.Reset();
				buf.PutByte(unchecked((byte)80));
				buf.PutString(Util.Str2byte("cancel-tcpip-forward"));
				buf.PutByte(unchecked((byte)0));
				buf.PutString(Util.Str2byte(address_to_bind));
				buf.PutInt(rport);
				session.Write(packet);
			}
			catch (Exception)
			{
			}
		}
        // OID 1.2.840.113554.1.2.2 in DER
        /// <exception cref="System.Exception"></exception>
        public override bool Start(Session session)
        {
            base.Start(session);
            byte[] _username = Util.Str2byte(username);
            packet.Reset();
            // byte            SSH_MSG_USERAUTH_REQUEST(50)
            // string          user name(in ISO-10646 UTF-8 encoding)
            // string          service name(in US-ASCII)
            // string          "gssapi"(US-ASCII)
            // uint32          n, the number of OIDs client supports
            // string[n]       mechanism OIDS
            buf.PutByte(unchecked ((byte)SSH_MSG_USERAUTH_REQUEST));
            buf.PutString(_username);
            buf.PutString(Util.Str2byte("ssh-connection"));
            buf.PutString(Util.Str2byte("gssapi-with-mic"));
            buf.PutInt(supported_oid.Length);
            for (int i = 0; i < supported_oid.Length; i++)
            {
                buf.PutString(supported_oid[i]);
            }
            session.Write(packet);
            string method = null;
            int    command;

            while (true)
            {
                buf     = session.Read(buf);
                command = buf.GetCommand() & unchecked ((int)(0xff));
                if (command == SSH_MSG_USERAUTH_FAILURE)
                {
                    return(false);
                }
                if (command == SSH_MSG_USERAUTH_GSSAPI_RESPONSE)
                {
                    buf.GetInt();
                    buf.GetByte();
                    buf.GetByte();
                    byte[] message = buf.GetString();
                    for (int i_1 = 0; i_1 < supported_oid.Length; i_1++)
                    {
                        if (Util.Array_equals(message, supported_oid[i_1]))
                        {
                            method = supported_method[i_1];
                            break;
                        }
                    }
                    if (method == null)
                    {
                        return(false);
                    }
                    break;
                }
                // success
                if (command == SSH_MSG_USERAUTH_BANNER)
                {
                    buf.GetInt();
                    buf.GetByte();
                    buf.GetByte();
                    byte[] _message = buf.GetString();
                    byte[] lang     = buf.GetString();
                    string message  = Util.Byte2str(_message);
                    if (userinfo != null)
                    {
                        userinfo.ShowMessage(message);
                    }
                    continue;
                }
                return(false);
            }
            NSch.GSSContext context = null;
            try
            {
                Type c = Sharpen.Runtime.GetType(session.GetConfig(method));
                context = (NSch.GSSContext)(System.Activator.CreateInstance(c));
            }
            catch (Exception)
            {
                return(false);
            }
            try
            {
                context.Create(username, session.host);
            }
            catch (JSchException)
            {
                return(false);
            }
            byte[] token = new byte[0];
            while (!context.IsEstablished())
            {
                try
                {
                    token = context.Init(token, 0, token.Length);
                }
                catch (JSchException)
                {
                    // TODO
                    // ERRTOK should be sent?
                    // byte        SSH_MSG_USERAUTH_GSSAPI_ERRTOK
                    // string      error token
                    return(false);
                }
                if (token != null)
                {
                    packet.Reset();
                    buf.PutByte(unchecked ((byte)SSH_MSG_USERAUTH_GSSAPI_TOKEN));
                    buf.PutString(token);
                    session.Write(packet);
                }
                if (!context.IsEstablished())
                {
                    buf     = session.Read(buf);
                    command = buf.GetCommand() & unchecked ((int)(0xff));
                    if (command == SSH_MSG_USERAUTH_GSSAPI_ERROR)
                    {
                        // uint32    major_status
                        // uint32    minor_status
                        // string    message
                        // string    language tag
                        buf     = session.Read(buf);
                        command = buf.GetCommand() & unchecked ((int)(0xff));
                    }
                    else
                    {
                        //return false;
                        if (command == SSH_MSG_USERAUTH_GSSAPI_ERRTOK)
                        {
                            // string error token
                            buf     = session.Read(buf);
                            command = buf.GetCommand() & unchecked ((int)(0xff));
                        }
                    }
                    //return false;
                    if (command == SSH_MSG_USERAUTH_FAILURE)
                    {
                        return(false);
                    }
                    buf.GetInt();
                    buf.GetByte();
                    buf.GetByte();
                    token = buf.GetString();
                }
            }
            Buffer mbuf = new Buffer();

            // string    session identifier
            // byte      SSH_MSG_USERAUTH_REQUEST
            // string    user name
            // string    service
            // string    "gssapi-with-mic"
            mbuf.PutString(session.GetSessionId());
            mbuf.PutByte(unchecked ((byte)SSH_MSG_USERAUTH_REQUEST));
            mbuf.PutString(_username);
            mbuf.PutString(Util.Str2byte("ssh-connection"));
            mbuf.PutString(Util.Str2byte("gssapi-with-mic"));
            byte[] mic = context.GetMIC(mbuf.buffer, 0, mbuf.GetLength());
            if (mic == null)
            {
                return(false);
            }
            packet.Reset();
            buf.PutByte(unchecked ((byte)SSH_MSG_USERAUTH_GSSAPI_MIC));
            buf.PutString(mic);
            session.Write(packet);
            context.Dispose();
            buf     = session.Read(buf);
            command = buf.GetCommand() & unchecked ((int)(0xff));
            if (command == SSH_MSG_USERAUTH_SUCCESS)
            {
                return(true);
            }
            else
            {
                if (command == SSH_MSG_USERAUTH_FAILURE)
                {
                    buf.GetInt();
                    buf.GetByte();
                    buf.GetByte();
                    byte[] foo             = buf.GetString();
                    int    partial_success = buf.GetByte();
                    //System.err.println(new String(foo)+
                    //		 " partial_success:"+(partial_success!=0));
                    if (partial_success != 0)
                    {
                        throw new JSchPartialAuthException(Util.Byte2str(foo));
                    }
                }
            }
            return(false);
        }
		protected internal override Packet GenChannelOpenPacket()
		{
			Buffer buf = new Buffer(150);
			Packet packet = new Packet(buf);
			// byte   SSH_MSG_CHANNEL_OPEN(90)
			// string channel type         //
			// uint32 sender channel       // 0
			// uint32 initial window size  // 0x100000(65536)
			// uint32 maxmum packet size   // 0x4000(16384)
			packet.Reset();
			buf.PutByte(unchecked((byte)90));
			buf.PutString(this.type);
			buf.PutInt(id);
			buf.PutInt(lwsize);
			buf.PutInt(lmpsize);
			buf.PutString(Util.Str2byte(host));
			buf.PutInt(port);
			buf.PutString(Util.Str2byte(originator_IP_address));
			buf.PutInt(originator_port);
			return packet;
		}
Exemple #28
0
		protected internal virtual Packet GenChannelOpenPacket()
		{
			Buffer buf = new Buffer(100);
			Packet packet = new Packet(buf);
			// byte   SSH_MSG_CHANNEL_OPEN(90)
			// string channel type         //
			// uint32 sender channel       // 0
			// uint32 initial window size  // 0x100000(65536)
			// uint32 maxmum packet size   // 0x4000(16384)
			packet.Reset();
			buf.PutByte(unchecked((byte)90));
			buf.PutString(this.type);
			buf.PutInt(this.id);
			buf.PutInt(this.lwsize);
			buf.PutInt(this.lmpsize);
			return packet;
		}
Exemple #29
0
		protected internal virtual void SendOpenFailure(int reasoncode)
		{
			try
			{
				Buffer buf = new Buffer(100);
				Packet packet = new Packet(buf);
				packet.Reset();
				buf.PutByte(unchecked((byte)SSH_MSG_CHANNEL_OPEN_FAILURE));
				buf.PutInt(GetRecipient());
				buf.PutInt(reasoncode);
				buf.PutString(Util.Str2byte("open failed"));
				buf.PutString(Util.empty);
				GetSession().Write(packet);
			}
			catch (Exception)
			{
			}
		}
Exemple #30
0
 /// <exception cref="NSch.JSchException"></exception>
 public override void Connect()
 {
     try
     {
         Session _session = GetSession();
         if (!_session.IsConnected())
         {
             throw new JSchException("session is down");
         }
         Buffer buf    = new Buffer(150);
         Packet packet = new Packet(buf);
         // send
         // byte   SSH_MSG_CHANNEL_OPEN(90)
         // string channel type         //
         // uint32 sender channel       // 0
         // uint32 initial window size  // 0x100000(65536)
         // uint32 maxmum packet size   // 0x4000(16384)
         packet.Reset();
         buf.PutByte(unchecked ((byte)90));
         buf.PutString(Util.Str2byte("direct-tcpip"));
         buf.PutInt(id);
         buf.PutInt(lwsize);
         buf.PutInt(lmpsize);
         buf.PutString(Util.Str2byte(host));
         buf.PutInt(port);
         buf.PutString(Util.Str2byte(originator_IP_address));
         buf.PutInt(originator_port);
         _session.Write(packet);
         int retry = 1000;
         try
         {
             while (this.GetRecipient() == -1 && _session.IsConnected() && retry > 0 && !eof_remote
                    )
             {
                 //Thread.sleep(500);
                 Sharpen.Thread.Sleep(50);
                 retry--;
             }
         }
         catch (Exception)
         {
         }
         if (!_session.IsConnected())
         {
             throw new JSchException("session is down");
         }
         if (retry == 0 || this.eof_remote)
         {
             throw new JSchException("channel is not opened.");
         }
         connected = true;
         if (io.@in != null)
         {
             thread = new Sharpen.Thread(this);
             thread.SetName("DirectTCPIP thread " + _session.GetHost());
             if (_session.daemon_thread)
             {
                 thread.SetDaemon(_session.daemon_thread);
             }
             thread.Start();
         }
     }
     catch (Exception e)
     {
         io.Close();
         io = null;
         Channel.Del(this);
         if (e is JSchException)
         {
             throw (JSchException)e;
         }
     }
 }
        public override void Run()
        {
            try
            {
                if (lport == -1)
                {
                    Type c = Sharpen.Runtime.GetType(target);
                    daemon = (ForwardedTCPIPDaemon)System.Activator.CreateInstance(c);
                    PipedOutputStream @out = new PipedOutputStream();
                    io.SetInputStream(new Channel.PassiveInputStream(this, @out, 32 * 1024), false);
                    daemon.SetChannel(this, GetInputStream(), @out);
                    object[] foo = GetPort(GetSession(), rport);
                    daemon.SetArg((object[])foo[3]);
                    new Sharpen.Thread(daemon).Start();
                }
                else
                {
                    socket = (factory == null) ? Util.CreateSocket(target, lport, TIMEOUT) : factory.
                             CreateSocket(target, lport);
                    socket.NoDelay = true;
                    io.SetInputStream(socket.GetInputStream());
                    io.SetOutputStream(socket.GetOutputStream());
                }
                SendOpenConfirmation();
            }
            catch (Exception)
            {
                SendOpenFailure(SSH_OPEN_ADMINISTRATIVELY_PROHIBITED);
                close = true;
                Disconnect();
                return;
            }
            thread = Sharpen.Thread.CurrentThread();
            Buffer buf    = new Buffer(rmpsize);
            Packet packet = new Packet(buf);
            int    i      = 0;

            try
            {
                Session _session = GetSession();
                while (thread != null && io != null && io.@in != null)
                {
                    i = [email protected](buf.buffer, 14, buf.buffer.Length - 14 - Session.buffer_margin);
                    if (i <= 0)
                    {
                        Eof();
                        break;
                    }
                    packet.Reset();
                    buf.PutByte(unchecked ((byte)Session.SSH_MSG_CHANNEL_DATA));
                    buf.PutInt(recipient);
                    buf.PutInt(i);
                    buf.Skip(i);
                    lock (this)
                    {
                        if (close)
                        {
                            break;
                        }
                        _session.Write(packet, this, i);
                    }
                }
            }
            catch (Exception)
            {
            }
            //System.err.println(e);
            //thread=null;
            //eof();
            Disconnect();
        }
Exemple #32
0
		public override void Run()
		{
			try
			{
				socket = Util.CreateSocket(host, port, TIMEOUT);
				socket.NoDelay = true;
				io = new IO();
				io.SetInputStream(socket.GetInputStream());
				io.SetOutputStream(socket.GetOutputStream());
				SendOpenConfirmation();
			}
			catch (Exception)
			{
				SendOpenFailure(SSH_OPEN_ADMINISTRATIVELY_PROHIBITED);
				close = true;
				Disconnect();
				return;
			}
			thread = Sharpen.Thread.CurrentThread();
			Buffer buf = new Buffer(rmpsize);
			Packet packet = new Packet(buf);
			int i = 0;
			try
			{
				while (thread != null && io != null && io.@in != null)
				{
					i = [email protected](buf.buffer, 14, buf.buffer.Length - 14 - 32 - 20);
					// padding and mac
					if (i <= 0)
					{
						Eof();
						break;
					}
					if (close)
					{
						break;
					}
					packet.Reset();
					buf.PutByte(unchecked((byte)Session.SSH_MSG_CHANNEL_DATA));
					buf.PutInt(recipient);
					buf.PutInt(i);
					buf.Skip(i);
					GetSession().Write(packet, this, i);
				}
			}
			catch (Exception)
			{
			}
			//System.err.println(e);
			Disconnect();
		}
Exemple #33
0
		/// <exception cref="NSch.JSchException"></exception>
		public virtual void Connect(int connectTimeout)
		{
			Session _session = GetSession();
			if (!_session.IsConnected())
			{
				throw new JSchException("session is down");
			}
			this.connectTimeout = connectTimeout;
			try
			{
				Buffer buf = new Buffer(100);
				Packet packet = new Packet(buf);
				// send
				// byte   SSH_MSG_CHANNEL_OPEN(90)
				// string channel type         //
				// uint32 sender channel       // 0
				// uint32 initial window size  // 0x100000(65536)
				// uint32 maxmum packet size   // 0x4000(16384)
				packet.Reset();
				buf.PutByte(unchecked((byte)90));
				buf.PutString(this.type);
				buf.PutInt(this.id);
				buf.PutInt(this.lwsize);
				buf.PutInt(this.lmpsize);
				_session.Write(packet);
				int retry = 1000;
				long start = Runtime.CurrentTimeMillis();
				long timeout = connectTimeout;
				while (this.GetRecipient() == -1 && _session.IsConnected() && retry > 0)
				{
					if (timeout > 0L)
					{
						if ((Runtime.CurrentTimeMillis() - start) > timeout)
						{
							retry = 0;
							continue;
						}
					}
					try
					{
						Sharpen.Thread.Sleep(50);
					}
					catch (Exception)
					{
					}
					retry--;
				}
				if (!_session.IsConnected())
				{
					throw new JSchException("session is down");
				}
				if (retry == 0)
				{
					throw new JSchException("channel is not opened.");
				}
				if (this.IsClosed())
				{
					throw new JSchException("channel is not opened.");
				}
				connected = true;
				Start();
			}
			catch (Exception e)
			{
				connected = false;
				Disconnect();
				if (e is JSchException)
				{
					throw (JSchException)e;
				}
				throw new JSchException(e.ToString(), e);
			}
		}
		public override void Run()
		{
			try
			{
				if (lport == -1)
				{
					Type c = Sharpen.Runtime.GetType(target);
					daemon = (ForwardedTCPIPDaemon)System.Activator.CreateInstance(c);
					PipedOutputStream @out = new PipedOutputStream();
					io.SetInputStream(new Channel.PassiveInputStream(this, @out, 32 * 1024), false);
					daemon.SetChannel(this, GetInputStream(), @out);
					object[] foo = GetPort(GetSession(), rport);
					daemon.SetArg((object[])foo[3]);
					new Sharpen.Thread(daemon).Start();
				}
				else
				{
					socket = (factory == null) ? Util.CreateSocket(target, lport, TIMEOUT) : factory.
						CreateSocket(target, lport);
					socket.NoDelay = true;
					io.SetInputStream(socket.GetInputStream());
					io.SetOutputStream(socket.GetOutputStream());
				}
				SendOpenConfirmation();
			}
			catch (Exception)
			{
				SendOpenFailure(SSH_OPEN_ADMINISTRATIVELY_PROHIBITED);
				close = true;
				Disconnect();
				return;
			}
			thread = Sharpen.Thread.CurrentThread();
			Buffer buf = new Buffer(rmpsize);
			Packet packet = new Packet(buf);
			int i = 0;
			try
			{
				while (thread != null && io != null && io.@in != null)
				{
					i = [email protected](buf.buffer, 14, buf.buffer.Length - 14 - 32 - 20);
					// padding and mac
					if (i <= 0)
					{
						Eof();
						break;
					}
					packet.Reset();
					if (close)
					{
						break;
					}
					buf.PutByte(unchecked((byte)Session.SSH_MSG_CHANNEL_DATA));
					buf.PutInt(recipient);
					buf.PutInt(i);
					buf.Skip(i);
					GetSession().Write(packet, this, i);
				}
			}
			catch (Exception)
			{
			}
			//System.err.println(e);
			//thread=null;
			//eof();
			Disconnect();
		}
Exemple #35
0
		/// <exception cref="System.Exception"></exception>
		public virtual void SendKeepAliveMsg()
		{
			Buffer buf = new Buffer();
			Packet packet = new Packet(buf);
			packet.Reset();
			buf.PutByte(unchecked((byte)SSH_MSG_GLOBAL_REQUEST));
			buf.PutString(keepalivemsg);
			buf.PutByte(unchecked((byte)1));
			Write(packet);
		}
Exemple #36
0
		/// <exception cref="NSch.JSchException"></exception>
		public virtual void Connect(int connectTimeout)
		{
			if (isConnected)
			{
				throw new JSchException("session is already connected");
			}
			io = new IO();
			if (random == null)
			{
				try
				{
					Type c = Sharpen.Runtime.GetType(GetConfig("random"));
					random = (Random)(System.Activator.CreateInstance(c));
				}
				catch (Exception e)
				{
					throw new JSchException(e.ToString(), e);
				}
			}
			Packet.SetRandom(random);
			if (JSch.GetLogger().IsEnabled(Logger.INFO))
			{
				JSch.GetLogger().Log(Logger.INFO, "Connecting to " + host + " port " + port);
			}
			try
			{
				int i;
				int j;
				if (proxy == null)
				{
					InputStream @in;
					OutputStream @out;
					if (socket_factory == null)
					{
						socket = Util.CreateSocket(host, port, connectTimeout);
						@in = socket.GetInputStream();
						@out = socket.GetOutputStream();
					}
					else
					{
						socket = socket_factory.CreateSocket(host, port);
						@in = socket_factory.GetInputStream(socket);
						@out = socket_factory.GetOutputStream(socket);
					}
					//if(timeout>0){ socket.setSoTimeout(timeout); }
					socket.NoDelay = true;
					io.SetInputStream(@in);
					io.SetOutputStream(@out);
				}
				else
				{
					lock (proxy)
					{
						proxy.Connect(socket_factory, host, port, connectTimeout);
						io.SetInputStream(proxy.GetInputStream());
						io.SetOutputStream(proxy.GetOutputStream());
						socket = proxy.GetSocket();
					}
				}
				if (connectTimeout > 0 && socket != null)
				{
					socket.ReceiveTimeout = connectTimeout;
				}
				isConnected = true;
				if (JSch.GetLogger().IsEnabled(Logger.INFO))
				{
					JSch.GetLogger().Log(Logger.INFO, "Connection established");
				}
				jsch.AddSession(this);
				{
					// Some Cisco devices will miss to read '\n' if it is sent separately.
					byte[] foo = new byte[V_C.Length + 1];
					System.Array.Copy(V_C, 0, foo, 0, V_C.Length);
					foo[foo.Length - 1] = unchecked((byte)(byte)('\n'));
					io.Put(foo, 0, foo.Length);
				}
				while (true)
				{
					i = 0;
					j = 0;
					while (i < buf.buffer.Length)
					{
						j = io.GetByte();
						if (j < 0)
						{
							break;
						}
						buf.buffer[i] = unchecked((byte)j);
						i++;
						if (j == 10)
						{
							break;
						}
					}
					if (j < 0)
					{
						throw new JSchException("connection is closed by foreign host");
					}
					if (buf.buffer[i - 1] == 10)
					{
						// 0x0a
						i--;
						if (i > 0 && buf.buffer[i - 1] == 13)
						{
							// 0x0d
							i--;
						}
					}
					if (i <= 3 || ((i != buf.buffer.Length) && (buf.buffer[0] != 'S' || buf.buffer[1]
						 != 'S' || buf.buffer[2] != 'H' || buf.buffer[3] != '-')))
					{
						// It must not start with 'SSH-'
						//System.err.println(new String(buf.buffer, 0, i);
						continue;
					}
					if (i == buf.buffer.Length || i < 7 || (buf.buffer[4] == '1' && buf.buffer[6] != 
						'9'))
					{
						// SSH-1.99 or SSH-2.0
						// SSH-1.5
						throw new JSchException("invalid server's version string");
					}
					break;
				}
				V_S = new byte[i];
				System.Array.Copy(buf.buffer, 0, V_S, 0, i);
				//System.err.println("V_S: ("+i+") ["+new String(V_S)+"]");
				if (JSch.GetLogger().IsEnabled(Logger.INFO))
				{
					JSch.GetLogger().Log(Logger.INFO, "Remote version string: " + Util.Byte2str(V_S));
					JSch.GetLogger().Log(Logger.INFO, "Local version string: " + Util.Byte2str(V_C));
				}
				Send_kexinit();
				buf = Read(buf);
				if (buf.GetCommand() != SSH_MSG_KEXINIT)
				{
					in_kex = false;
					throw new JSchException("invalid protocol: " + buf.GetCommand());
				}
				if (JSch.GetLogger().IsEnabled(Logger.INFO))
				{
					JSch.GetLogger().Log(Logger.INFO, "SSH_MSG_KEXINIT received");
				}
				KeyExchange kex = Receive_kexinit(buf);
				while (true)
				{
					buf = Read(buf);
					if (kex.GetState() == buf.GetCommand())
					{
						kex_start_time = Runtime.CurrentTimeMillis();
						bool result = kex.Next(buf);
						if (!result)
						{
							//System.err.println("verify: "+result);
							in_kex = false;
							throw new JSchException("verify: " + result);
						}
					}
					else
					{
						in_kex = false;
						throw new JSchException("invalid protocol(kex): " + buf.GetCommand());
					}
					if (kex.GetState() == KeyExchange.STATE_END)
					{
						break;
					}
				}
				try
				{
					CheckHost(host, port, kex);
				}
				catch (JSchException ee)
				{
					in_kex = false;
					throw;
				}
				Send_newkeys();
				// receive SSH_MSG_NEWKEYS(21)
				buf = Read(buf);
				//System.err.println("read: 21 ? "+buf.getCommand());
				if (buf.GetCommand() == SSH_MSG_NEWKEYS)
				{
					if (JSch.GetLogger().IsEnabled(Logger.INFO))
					{
						JSch.GetLogger().Log(Logger.INFO, "SSH_MSG_NEWKEYS received");
					}
					Receive_newkeys(buf, kex);
				}
				else
				{
					in_kex = false;
					throw new JSchException("invalid protocol(newkyes): " + buf.GetCommand());
				}
				bool auth = false;
				bool auth_cancel = false;
				UserAuth ua = null;
				try
				{
					Type c = Sharpen.Runtime.GetType(GetConfig("userauth.none"));
					ua = (UserAuth)(System.Activator.CreateInstance(c));
				}
				catch (Exception e)
				{
					throw new JSchException(e.ToString(), e);
				}
				auth = ua.Start(this);
				string cmethods = GetConfig("PreferredAuthentications");
				string[] cmethoda = Util.Split(cmethods, ",");
				string smethods = null;
				if (!auth)
				{
					smethods = ((UserAuthNone)ua).GetMethods();
					if (smethods != null)
					{
						smethods = smethods.ToLower();
					}
					else
					{
						// methods: publickey,password,keyboard-interactive
						//smethods="publickey,password,keyboard-interactive";
						smethods = cmethods;
					}
				}
				string[] smethoda = Util.Split(smethods, ",");
				int methodi = 0;
				while (true)
				{
					//System.err.println("methods: "+methods);
					while (!auth && cmethoda != null && methodi < cmethoda.Length)
					{
						string method = cmethoda[methodi++];
						bool acceptable = false;
						for (int k = 0; k < smethoda.Length; k++)
						{
							if (smethoda[k].Equals(method))
							{
								acceptable = true;
								break;
							}
						}
						if (!acceptable)
						{
							continue;
						}
						//System.err.println("  method: "+method);
						if (JSch.GetLogger().IsEnabled(Logger.INFO))
						{
							string str = "Authentications that can continue: ";
							for (int k_1 = methodi - 1; k_1 < cmethoda.Length; k_1++)
							{
								str += cmethoda[k_1];
								if (k_1 + 1 < cmethoda.Length)
								{
									str += ",";
								}
							}
							JSch.GetLogger().Log(Logger.INFO, str);
							JSch.GetLogger().Log(Logger.INFO, "Next authentication method: " + method);
						}
						ua = null;
						try
						{
							Type c = null;
							if (GetConfig("userauth." + method) != null)
							{
								c = Sharpen.Runtime.GetType(GetConfig("userauth." + method));
								ua = (UserAuth)(System.Activator.CreateInstance(c));
							}
						}
						catch (Exception)
						{
							if (JSch.GetLogger().IsEnabled(Logger.WARN))
							{
								JSch.GetLogger().Log(Logger.WARN, "failed to load " + method + " method");
							}
						}
						if (ua != null)
						{
							auth_cancel = false;
							try
							{
								auth = ua.Start(this);
								if (auth && JSch.GetLogger().IsEnabled(Logger.INFO))
								{
									JSch.GetLogger().Log(Logger.INFO, "Authentication succeeded (" + method + ").");
								}
							}
							catch (JSchAuthCancelException)
							{
								auth_cancel = true;
							}
							catch (JSchPartialAuthException ee)
							{
								string tmp = smethods;
								smethods = ee.GetMethods();
								smethoda = Util.Split(smethods, ",");
								if (!tmp.Equals(smethods))
								{
									methodi = 0;
								}
								//System.err.println("PartialAuth: "+methods);
								auth_cancel = false;
								goto loop_continue;
							}
							catch (RuntimeException ee)
							{
								throw;
							}
							catch (Exception)
							{
								//System.err.println("ee: "+ee); // SSH_MSG_DISCONNECT: 2 Too many authentication failures
								goto loop_break;
							}
						}
					}
					break;
loop_continue: ;
				}
loop_break: ;
				if (!auth)
				{
					if (auth_cancel)
					{
						throw new JSchException("Auth cancel");
					}
					throw new JSchException("Auth fail");
				}
				if (connectTimeout > 0 || timeout > 0)
				{
					socket.ReceiveTimeout = timeout;
				}
				isAuthed = true;
				lock (Lock)
				{
					if (isConnected)
					{
						connectThread = new Sharpen.Thread(this);
						connectThread.SetName("Connect thread " + host + " session");
						if (daemon_thread)
						{
							connectThread.SetDaemon(daemon_thread);
						}
						connectThread.Start();
					}
				}
			}
			catch (Exception e)
			{
				// The session has been already down and
				// we don't have to start new thread.
				in_kex = false;
				if (isConnected)
				{
					try
					{
						packet.Reset();
						buf.PutByte(unchecked((byte)SSH_MSG_DISCONNECT));
						buf.PutInt(3);
						buf.PutString(Util.Str2byte(e.ToString()));
						buf.PutString(Util.Str2byte("en"));
						Write(packet);
						Disconnect();
					}
					catch (Exception)
					{
					}
				}
				isConnected = false;
				//e.printStackTrace();
				if (e is RuntimeException)
				{
					throw (RuntimeException)e;
				}
				if (e is JSchException)
				{
					throw (JSchException)e;
				}
				throw new JSchException("Session.connect: " + e);
			}
			finally
			{
				Util.Bzero(this.password);
				this.password = null;
			}
		}
Exemple #37
0
		public virtual void Run()
		{
			thread = this;
			byte[] foo;
			Buffer buf = new Buffer();
			Packet packet = new Packet(buf);
			int i = 0;
			Channel channel;
			int[] start = new int[1];
			int[] length = new int[1];
			KeyExchange kex = null;
			int stimeout = 0;
			try
			{
				while (isConnected && thread != null)
				{
					try
					{
						buf = Read(buf);
						stimeout = 0;
					}
					catch (ThreadInterruptedException ee)
					{
						if (!in_kex && stimeout < serverAliveCountMax)
						{
							SendKeepAliveMsg();
							stimeout++;
							continue;
						}
						throw;
					}
					int msgType = buf.GetCommand() & unchecked((int)(0xff));
					if (kex != null && kex.GetState() == msgType)
					{
						kex_start_time = Runtime.CurrentTimeMillis();
						bool result = kex.Next(buf);
						if (!result)
						{
							throw new JSchException("verify: " + result);
						}
						continue;
					}
					switch (msgType)
					{
						case SSH_MSG_KEXINIT:
						{
							//System.err.println("KEXINIT");
							kex = Receive_kexinit(buf);
							break;
						}

						case SSH_MSG_NEWKEYS:
						{
							//System.err.println("NEWKEYS");
							Send_newkeys();
							Receive_newkeys(buf, kex);
							kex = null;
							break;
						}

						case SSH_MSG_CHANNEL_DATA:
						{
							buf.GetInt();
							buf.GetByte();
							buf.GetByte();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							foo = buf.GetString(start, length);
							if (channel == null)
							{
								break;
							}
							if (length[0] == 0)
							{
								break;
							}
							try
							{
								channel.Write(foo, start[0], length[0]);
							}
							catch (Exception)
							{
								//System.err.println(e);
								try
								{
									channel.Disconnect();
								}
								catch (Exception)
								{
								}
								break;
							}
							int len = length[0];
							channel.SetLocalWindowSize(channel.lwsize - len);
							if (channel.lwsize < channel.lwsize_max / 2)
							{
								packet.Reset();
								buf.PutByte(unchecked((byte)SSH_MSG_CHANNEL_WINDOW_ADJUST));
								buf.PutInt(channel.GetRecipient());
								buf.PutInt(channel.lwsize_max - channel.lwsize);
								Write(packet);
								channel.SetLocalWindowSize(channel.lwsize_max);
							}
							break;
						}

						case SSH_MSG_CHANNEL_EXTENDED_DATA:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							buf.GetInt();
							// data_type_code == 1
							foo = buf.GetString(start, length);
							//System.err.println("stderr: "+new String(foo,start[0],length[0]));
							if (channel == null)
							{
								break;
							}
							if (length[0] == 0)
							{
								break;
							}
							channel.Write_ext(foo, start[0], length[0]);
							int len = length[0];
							channel.SetLocalWindowSize(channel.lwsize - len);
							if (channel.lwsize < channel.lwsize_max / 2)
							{
								packet.Reset();
								buf.PutByte(unchecked((byte)SSH_MSG_CHANNEL_WINDOW_ADJUST));
								buf.PutInt(channel.GetRecipient());
								buf.PutInt(channel.lwsize_max - channel.lwsize);
								Write(packet);
								channel.SetLocalWindowSize(channel.lwsize_max);
							}
							break;
						}

						case SSH_MSG_CHANNEL_WINDOW_ADJUST:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							if (channel == null)
							{
								break;
							}
							channel.AddRemoteWindowSize(buf.GetInt());
							break;
						}

						case SSH_MSG_CHANNEL_EOF:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							if (channel != null)
							{
								//channel.eof_remote=true;
								//channel.eof();
								channel.Eof_remote();
							}
							break;
						}

						case SSH_MSG_CHANNEL_CLOSE:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							if (channel != null)
							{
								//	      channel.close();
								channel.Disconnect();
							}
							break;
						}

						case SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							if (channel == null)
							{
							}
							//break;
							int r = buf.GetInt();
							long rws = buf.GetUInt();
							int rps = buf.GetInt();
							channel.SetRemoteWindowSize(rws);
							channel.SetRemotePacketSize(rps);
							channel.SetRecipient(r);
							break;
						}

						case SSH_MSG_CHANNEL_OPEN_FAILURE:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							if (channel == null)
							{
							}
							//break;
							int reason_code = buf.GetInt();
							//foo=buf.getString();  // additional textual information
							//foo=buf.getString();  // language tag 
							channel.exitstatus = reason_code;
							channel.close = true;
							channel.eof_remote = true;
							channel.SetRecipient(0);
							break;
						}

						case SSH_MSG_CHANNEL_REQUEST:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							foo = buf.GetString();
							bool reply = (buf.GetByte() != 0);
							channel = Channel.GetChannel(i, this);
							if (channel != null)
							{
								byte reply_type = unchecked((byte)SSH_MSG_CHANNEL_FAILURE);
								if ((Util.Byte2str(foo)).Equals("exit-status"))
								{
									i = buf.GetInt();
									// exit-status
									channel.SetExitStatus(i);
									reply_type = unchecked((byte)SSH_MSG_CHANNEL_SUCCESS);
								}
								if (reply)
								{
									packet.Reset();
									buf.PutByte(reply_type);
									buf.PutInt(channel.GetRecipient());
									Write(packet);
								}
							}
							break;
						}

						case SSH_MSG_CHANNEL_OPEN:
						{
							buf.GetInt();
							buf.GetShort();
							foo = buf.GetString();
							string ctyp = Util.Byte2str(foo);
							if (!"forwarded-tcpip".Equals(ctyp) && !("x11".Equals(ctyp) && x11_forwarding) &&
								 !("*****@*****.**".Equals(ctyp) && agent_forwarding))
							{
								//System.err.println("Session.run: CHANNEL OPEN "+ctyp); 
								//throw new IOException("Session.run: CHANNEL OPEN "+ctyp);
								packet.Reset();
								buf.PutByte(unchecked((byte)SSH_MSG_CHANNEL_OPEN_FAILURE));
								buf.PutInt(buf.GetInt());
								buf.PutInt(Channel.SSH_OPEN_ADMINISTRATIVELY_PROHIBITED);
								buf.PutString(Util.empty);
								buf.PutString(Util.empty);
								Write(packet);
							}
							else
							{
								channel = Channel.GetChannel(ctyp);
								AddChannel(channel);
								channel.GetData(buf);
								channel.Init();
								Sharpen.Thread tmp = new Sharpen.Thread(channel);
								tmp.SetName("Channel " + ctyp + " " + host);
								if (daemon_thread)
								{
									tmp.SetDaemon(daemon_thread);
								}
								tmp.Start();
								break;
							}
							goto case SSH_MSG_CHANNEL_SUCCESS;
						}

						case SSH_MSG_CHANNEL_SUCCESS:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							if (channel == null)
							{
								break;
							}
							channel.reply = 1;
							break;
						}

						case SSH_MSG_CHANNEL_FAILURE:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							if (channel == null)
							{
								break;
							}
							channel.reply = 0;
							break;
						}

						case SSH_MSG_GLOBAL_REQUEST:
						{
							buf.GetInt();
							buf.GetShort();
							foo = buf.GetString();
							// request name
							bool reply = (buf.GetByte() != 0);
							if (reply)
							{
								packet.Reset();
								buf.PutByte(unchecked((byte)SSH_MSG_REQUEST_FAILURE));
								Write(packet);
							}
							break;
						}

						case SSH_MSG_REQUEST_FAILURE:
						case SSH_MSG_REQUEST_SUCCESS:
						{
							Sharpen.Thread t = grr.GetThread();
							if (t != null)
							{
								grr.SetReply(msgType == SSH_MSG_REQUEST_SUCCESS ? 1 : 0);
								t.Interrupt();
							}
							break;
						}

						default:
						{
							//System.err.println("Session.run: unsupported type "+msgType); 
							throw new IOException("Unknown SSH message type " + msgType);
						}
					}
				}
			}
			catch (Exception e)
			{
				in_kex = false;
				if (JSch.GetLogger().IsEnabled(Logger.INFO))
				{
					JSch.GetLogger().Log(Logger.INFO, "Caught an exception, leaving main loop due to "
						 + e.Message);
				}
			}
			//System.err.println("# Session.run");
			//e.printStackTrace();
			try
			{
				Disconnect();
			}
			catch (ArgumentNullException)
			{
			}
			catch (Exception)
			{
			}
			//System.err.println("@1");
			//e.printStackTrace();
			//System.err.println("@2");
			//e.printStackTrace();
			isConnected = false;
		}
Exemple #38
0
        /// <exception cref="NSch.JSchException"></exception>
        public virtual void Connect(int connectTimeout)
        {
            Session _session = GetSession();

            if (!_session.IsConnected())
            {
                throw new JSchException("session is down");
            }
            this.connectTimeout = connectTimeout;
            try
            {
                Buffer buf    = new Buffer(100);
                Packet packet = new Packet(buf);
                // send
                // byte   SSH_MSG_CHANNEL_OPEN(90)
                // string channel type         //
                // uint32 sender channel       // 0
                // uint32 initial window size  // 0x100000(65536)
                // uint32 maxmum packet size   // 0x4000(16384)
                packet.Reset();
                buf.PutByte(unchecked ((byte)90));
                buf.PutString(this.type);
                buf.PutInt(this.id);
                buf.PutInt(this.lwsize);
                buf.PutInt(this.lmpsize);
                _session.Write(packet);
                int  retry   = 1000;
                long start   = Runtime.CurrentTimeMillis();
                long timeout = connectTimeout;
                while (this.GetRecipient() == -1 && _session.IsConnected() && retry > 0)
                {
                    if (timeout > 0L)
                    {
                        if ((Runtime.CurrentTimeMillis() - start) > timeout)
                        {
                            retry = 0;
                            continue;
                        }
                    }
                    try
                    {
                        Sharpen.Thread.Sleep(50);
                    }
                    catch (Exception)
                    {
                    }
                    retry--;
                }
                if (!_session.IsConnected())
                {
                    throw new JSchException("session is down");
                }
                if (retry == 0)
                {
                    throw new JSchException("channel is not opened.");
                }
                if (this.IsClosed())
                {
                    throw new JSchException("channel is not opened.");
                }
                connected = true;
                Start();
            }
            catch (Exception e)
            {
                connected = false;
                Disconnect();
                if (e is JSchException)
                {
                    throw (JSchException)e;
                }
                throw new JSchException(e.ToString(), e);
            }
        }
        /// <exception cref="System.Exception"></exception>
        public override bool Next(Buffer _buf)
        {
            int i;
            int j;

            switch (state)
            {
            case SSH_MSG_KEX_DH_GEX_GROUP:
            {
                // byte  SSH_MSG_KEX_DH_GEX_GROUP(31)
                // mpint p, safe prime
                // mpint g, generator for subgroup in GF (p)
                _buf.GetInt();
                _buf.GetByte();
                j = _buf.GetByte();
                if (j != SSH_MSG_KEX_DH_GEX_GROUP)
                {
                    System.Console.Error.WriteLine("type: must be SSH_MSG_KEX_DH_GEX_GROUP " + j);
                    return(false);
                }
                p = _buf.GetMPInt();
                g = _buf.GetMPInt();
                dh.SetP(p);
                dh.SetG(g);
                // The client responds with:
                // byte  SSH_MSG_KEX_DH_GEX_INIT(32)
                // mpint e <- g^x mod p
                //         x is a random number (1 < x < (p-1)/2)
                e = dh.GetE();
                packet.Reset();
                buf.PutByte(unchecked ((byte)SSH_MSG_KEX_DH_GEX_INIT));
                buf.PutMPInt(e);
                session.Write(packet);
                if (JSch.GetLogger().IsEnabled(Logger.INFO))
                {
                    JSch.GetLogger().Log(Logger.INFO, "SSH_MSG_KEX_DH_GEX_INIT sent");
                    JSch.GetLogger().Log(Logger.INFO, "expecting SSH_MSG_KEX_DH_GEX_REPLY");
                }
                state = SSH_MSG_KEX_DH_GEX_REPLY;
                return(true);
            }

            case SSH_MSG_KEX_DH_GEX_REPLY:
            {
                //break;
                // The server responds with:
                // byte      SSH_MSG_KEX_DH_GEX_REPLY(33)
                // string    server public host key and certificates (K_S)
                // mpint     f
                // string    signature of H
                j = _buf.GetInt();
                j = _buf.GetByte();
                j = _buf.GetByte();
                if (j != SSH_MSG_KEX_DH_GEX_REPLY)
                {
                    System.Console.Error.WriteLine("type: must be SSH_MSG_KEX_DH_GEX_REPLY " + j);
                    return(false);
                }
                K_S = _buf.GetString();
                // K_S is server_key_blob, which includes ....
                // string ssh-dss
                // impint p of dsa
                // impint q of dsa
                // impint g of dsa
                // impint pub_key of dsa
                //System.err.print("K_S: "); dump(K_S, 0, K_S.length);
                byte[] f        = _buf.GetMPInt();
                byte[] sig_of_H = _buf.GetString();
                dh.SetF(f);
                K = dh.GetK();
                //The hash H is computed as the HASH hash of the concatenation of the
                //following:
                // string    V_C, the client's version string (CR and NL excluded)
                // string    V_S, the server's version string (CR and NL excluded)
                // string    I_C, the payload of the client's SSH_MSG_KEXINIT
                // string    I_S, the payload of the server's SSH_MSG_KEXINIT
                // string    K_S, the host key
                // uint32    min, minimal size in bits of an acceptable group
                // uint32   n, preferred size in bits of the group the server should send
                // uint32    max, maximal size in bits of an acceptable group
                // mpint     p, safe prime
                // mpint     g, generator for subgroup
                // mpint     e, exchange value sent by the client
                // mpint     f, exchange value sent by the server
                // mpint     K, the shared secret
                // This value is called the exchange hash, and it is used to authenti-
                // cate the key exchange.
                buf.Reset();
                buf.PutString(V_C);
                buf.PutString(V_S);
                buf.PutString(I_C);
                buf.PutString(I_S);
                buf.PutString(K_S);
                buf.PutInt(min);
                buf.PutInt(preferred);
                buf.PutInt(max);
                buf.PutMPInt(p);
                buf.PutMPInt(g);
                buf.PutMPInt(e);
                buf.PutMPInt(f);
                buf.PutMPInt(K);
                byte[] foo = new byte[buf.GetLength()];
                buf.GetByte(foo);
                sha.Update(foo, 0, foo.Length);
                H = sha.Digest();
                // System.err.print("H -> "); dump(H, 0, H.length);
                i = 0;
                j = 0;
                j = ((K_S[i++] << 24) & unchecked ((int)(0xff000000))) | ((K_S[i++] << 16) & unchecked (
                                                                              (int)(0x00ff0000))) | ((K_S[i++] << 8) & unchecked ((int)(0x0000ff00))) | ((K_S[i
                                                                                                                                                              ++]) & unchecked ((int)(0x000000ff)));
                string alg = Util.Byte2str(K_S, i, j);
                i += j;
                bool result = false;
                if (alg.Equals("ssh-rsa"))
                {
                    byte[] tmp;
                    byte[] ee;
                    byte[] n;
                    type = RSA;
                    j    = ((K_S[i++] << 24) & unchecked ((int)(0xff000000))) | ((K_S[i++] << 16) & unchecked (
                                                                                     (int)(0x00ff0000))) | ((K_S[i++] << 8) & unchecked ((int)(0x0000ff00))) | ((K_S[i
                                                                                                                                                                     ++]) & unchecked ((int)(0x000000ff)));
                    tmp = new byte[j];
                    System.Array.Copy(K_S, i, tmp, 0, j);
                    i += j;
                    ee = tmp;
                    j  = ((K_S[i++] << 24) & unchecked ((int)(0xff000000))) | ((K_S[i++] << 16) & unchecked (
                                                                                   (int)(0x00ff0000))) | ((K_S[i++] << 8) & unchecked ((int)(0x0000ff00))) | ((K_S[i
                                                                                                                                                                   ++]) & unchecked ((int)(0x000000ff)));
                    tmp = new byte[j];
                    System.Array.Copy(K_S, i, tmp, 0, j);
                    i += j;
                    n  = tmp;
                    //	SignatureRSA sig=new SignatureRSA();
                    //	sig.init();
                    NSch.SignatureRSA sig = null;
                    try
                    {
                        Type c = Sharpen.Runtime.GetType(session.GetConfig("signature.rsa"));
                        sig = (NSch.SignatureRSA)(System.Activator.CreateInstance(c));
                        sig.Init();
                    }
                    catch (Exception ex)
                    {
                        System.Console.Error.WriteLine(ex);
                    }
                    sig.SetPubKey(ee, n);
                    sig.Update(H);
                    result = sig.Verify(sig_of_H);
                    if (JSch.GetLogger().IsEnabled(Logger.INFO))
                    {
                        JSch.GetLogger().Log(Logger.INFO, "ssh_rsa_verify: signature " + result);
                    }
                }
                else
                {
                    if (alg.Equals("ssh-dss"))
                    {
                        byte[] q = null;
                        byte[] tmp;
                        type = DSS;
                        j    = ((K_S[i++] << 24) & unchecked ((int)(0xff000000))) | ((K_S[i++] << 16) & unchecked (
                                                                                         (int)(0x00ff0000))) | ((K_S[i++] << 8) & unchecked ((int)(0x0000ff00))) | ((K_S[i
                                                                                                                                                                         ++]) & unchecked ((int)(0x000000ff)));
                        tmp = new byte[j];
                        System.Array.Copy(K_S, i, tmp, 0, j);
                        i += j;
                        p  = tmp;
                        j  = ((K_S[i++] << 24) & unchecked ((int)(0xff000000))) | ((K_S[i++] << 16) & unchecked (
                                                                                       (int)(0x00ff0000))) | ((K_S[i++] << 8) & unchecked ((int)(0x0000ff00))) | ((K_S[i
                                                                                                                                                                       ++]) & unchecked ((int)(0x000000ff)));
                        tmp = new byte[j];
                        System.Array.Copy(K_S, i, tmp, 0, j);
                        i += j;
                        q  = tmp;
                        j  = ((K_S[i++] << 24) & unchecked ((int)(0xff000000))) | ((K_S[i++] << 16) & unchecked (
                                                                                       (int)(0x00ff0000))) | ((K_S[i++] << 8) & unchecked ((int)(0x0000ff00))) | ((K_S[i
                                                                                                                                                                       ++]) & unchecked ((int)(0x000000ff)));
                        tmp = new byte[j];
                        System.Array.Copy(K_S, i, tmp, 0, j);
                        i += j;
                        g  = tmp;
                        j  = ((K_S[i++] << 24) & unchecked ((int)(0xff000000))) | ((K_S[i++] << 16) & unchecked (
                                                                                       (int)(0x00ff0000))) | ((K_S[i++] << 8) & unchecked ((int)(0x0000ff00))) | ((K_S[i
                                                                                                                                                                       ++]) & unchecked ((int)(0x000000ff)));
                        tmp = new byte[j];
                        System.Array.Copy(K_S, i, tmp, 0, j);
                        i += j;
                        f  = tmp;
                        //	SignatureDSA sig=new SignatureDSA();
                        //	sig.init();
                        NSch.SignatureDSA sig = null;
                        try
                        {
                            Type c = Sharpen.Runtime.GetType(session.GetConfig("signature.dss"));
                            sig = (NSch.SignatureDSA)(System.Activator.CreateInstance(c));
                            sig.Init();
                        }
                        catch (Exception ex)
                        {
                            System.Console.Error.WriteLine(ex);
                        }
                        sig.SetPubKey(f, p, q, g);
                        sig.Update(H);
                        result = sig.Verify(sig_of_H);
                        if (JSch.GetLogger().IsEnabled(Logger.INFO))
                        {
                            JSch.GetLogger().Log(Logger.INFO, "ssh_dss_verify: signature " + result);
                        }
                    }
                    else
                    {
                        System.Console.Error.WriteLine("unknown alg");
                    }
                }
                state = STATE_END;
                return(result);
            }
            }
            return(false);
        }
Exemple #40
0
		//  static int min=512;
		//  static int preferred=1024;
		//  static int max=2000;
		//  com.jcraft.jsch.DH dh;
		//private byte[] f;
		/// <exception cref="System.Exception"></exception>
		public override void Init(Session session, byte[] V_S, byte[] V_C, byte[] I_S, byte
			[] I_C)
		{
			this.session = session;
			this.V_S = V_S;
			this.V_C = V_C;
			this.I_S = I_S;
			this.I_C = I_C;
			try
			{
				Type c = Sharpen.Runtime.GetType(session.GetConfig("sha-1"));
				sha = (HASH)(System.Activator.CreateInstance(c));
				sha.Init();
			}
			catch (Exception e)
			{
				System.Console.Error.WriteLine(e);
			}
			buf = new Buffer();
			packet = new Packet(buf);
			try
			{
				Type c = Sharpen.Runtime.GetType(session.GetConfig("dh"));
				dh = (NSch.DH)(System.Activator.CreateInstance(c));
				dh.Init();
			}
			catch (Exception e)
			{
				//      System.err.println(e);
				throw;
			}
			packet.Reset();
			buf.PutByte(unchecked((byte)SSH_MSG_KEX_DH_GEX_REQUEST));
			buf.PutInt(min);
			buf.PutInt(preferred);
			buf.PutInt(max);
			session.Write(packet);
			if (JSch.GetLogger().IsEnabled(Logger.INFO))
			{
				JSch.GetLogger().Log(Logger.INFO, "SSH_MSG_KEX_DH_GEX_REQUEST(" + min + "<" + preferred
					 + "<" + max + ") sent");
				JSch.GetLogger().Log(Logger.INFO, "expecting SSH_MSG_KEX_DH_GEX_GROUP");
			}
			state = SSH_MSG_KEX_DH_GEX_GROUP;
		}
Exemple #41
0
		//System.err.println("Channel.eof");
		//e.printStackTrace();
		internal virtual void Close()
		{
			if (close)
			{
				return;
			}
			close = true;
			eof_local = eof_remote = true;
			try
			{
				Buffer buf = new Buffer(100);
				Packet packet = new Packet(buf);
				packet.Reset();
				buf.PutByte(unchecked((byte)Session.SSH_MSG_CHANNEL_CLOSE));
				buf.PutInt(GetRecipient());
				lock (this)
				{
					GetSession().Write(packet);
				}
			}
			catch (Exception)
			{
			}
		}
Exemple #42
0
        /// <exception cref="System.IO.IOException"></exception>
        internal override void Write(byte[] foo, int s, int l)
        {
            if (packet == null)
            {
                wbuf   = new Buffer(rmpsize);
                packet = new Packet(wbuf);
            }
            rbuf.Shift();
            if (rbuf.buffer.Length < rbuf.index + l)
            {
                byte[] newbuf = new byte[rbuf.s + l];
                System.Array.Copy(rbuf.buffer, 0, newbuf, 0, rbuf.buffer.Length);
                rbuf.buffer = newbuf;
            }
            rbuf.PutByte(foo, s, l);
            int mlen = rbuf.GetInt();

            if (mlen > rbuf.GetLength())
            {
                rbuf.s -= 4;
                return;
            }
            int     typ      = rbuf.GetByte();
            Session _session = null;

            try
            {
                _session = GetSession();
            }
            catch (JSchException e)
            {
                throw new IOException(e.ToString());
            }
            IdentityRepository irepo    = _session.jsch.GetIdentityRepository();
            UserInfo           userinfo = _session.GetUserInfo();

            mbuf.Reset();
            if (typ == SSH2_AGENTC_REQUEST_IDENTITIES)
            {
                mbuf.PutByte(SSH2_AGENT_IDENTITIES_ANSWER);
                ArrayList identities = irepo.GetIdentities();
                lock (identities)
                {
                    int count = 0;
                    for (int i = 0; i < identities.Count; i++)
                    {
                        Identity identity = (Identity)(identities[i]);
                        if (identity.GetPublicKeyBlob() != null)
                        {
                            count++;
                        }
                    }
                    mbuf.PutInt(count);
                    for (int i_1 = 0; i_1 < identities.Count; i_1++)
                    {
                        Identity identity   = (Identity)(identities[i_1]);
                        byte[]   pubkeyblob = identity.GetPublicKeyBlob();
                        if (pubkeyblob == null)
                        {
                            continue;
                        }
                        mbuf.PutString(pubkeyblob);
                        mbuf.PutString(Util.empty);
                    }
                }
            }
            else
            {
                if (typ == SSH_AGENTC_REQUEST_RSA_IDENTITIES)
                {
                    mbuf.PutByte(SSH_AGENT_RSA_IDENTITIES_ANSWER);
                    mbuf.PutInt(0);
                }
                else
                {
                    if (typ == SSH2_AGENTC_SIGN_REQUEST)
                    {
                        byte[] blob  = rbuf.GetString();
                        byte[] data  = rbuf.GetString();
                        int    flags = rbuf.GetInt();
                        //      if((flags & 1)!=0){ //SSH_AGENT_OLD_SIGNATURE // old OpenSSH 2.0, 2.1
                        //        datafellows = SSH_BUG_SIGBLOB;
                        //      }
                        ArrayList identities = irepo.GetIdentities();
                        Identity  identity   = null;
                        lock (identities)
                        {
                            for (int i = 0; i < identities.Count; i++)
                            {
                                Identity _identity = (Identity)(identities[i]);
                                if (_identity.GetPublicKeyBlob() == null)
                                {
                                    continue;
                                }
                                if (!Util.Array_equals(blob, _identity.GetPublicKeyBlob()))
                                {
                                    continue;
                                }
                                if (_identity.IsEncrypted())
                                {
                                    if (userinfo == null)
                                    {
                                        continue;
                                    }
                                    while (_identity.IsEncrypted())
                                    {
                                        if (!userinfo.PromptPassphrase("Passphrase for " + _identity.GetName()))
                                        {
                                            break;
                                        }
                                        string _passphrase = userinfo.GetPassphrase();
                                        if (_passphrase == null)
                                        {
                                            break;
                                        }
                                        byte[] passphrase = Util.Str2byte(_passphrase);
                                        try
                                        {
                                            if (_identity.SetPassphrase(passphrase))
                                            {
                                                break;
                                            }
                                        }
                                        catch (JSchException)
                                        {
                                            break;
                                        }
                                    }
                                }
                                if (!_identity.IsEncrypted())
                                {
                                    identity = _identity;
                                    break;
                                }
                            }
                        }
                        byte[] signature = null;
                        if (identity != null)
                        {
                            signature = identity.GetSignature(data);
                        }
                        if (signature == null)
                        {
                            mbuf.PutByte(SSH2_AGENT_FAILURE);
                        }
                        else
                        {
                            mbuf.PutByte(SSH2_AGENT_SIGN_RESPONSE);
                            mbuf.PutString(signature);
                        }
                    }
                    else
                    {
                        if (typ == SSH2_AGENTC_REMOVE_IDENTITY)
                        {
                            byte[] blob = rbuf.GetString();
                            irepo.Remove(blob);
                            mbuf.PutByte(SSH_AGENT_SUCCESS);
                        }
                        else
                        {
                            if (typ == SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES)
                            {
                                mbuf.PutByte(SSH_AGENT_SUCCESS);
                            }
                            else
                            {
                                if (typ == SSH2_AGENTC_REMOVE_ALL_IDENTITIES)
                                {
                                    irepo.RemoveAll();
                                    mbuf.PutByte(SSH_AGENT_SUCCESS);
                                }
                                else
                                {
                                    if (typ == SSH2_AGENTC_ADD_IDENTITY)
                                    {
                                        int    fooo = rbuf.GetLength();
                                        byte[] tmp  = new byte[fooo];
                                        rbuf.GetByte(tmp);
                                        bool result = irepo.Add(tmp);
                                        mbuf.PutByte(result ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
                                    }
                                    else
                                    {
                                        rbuf.Skip(rbuf.GetLength() - 1);
                                        mbuf.PutByte(SSH_AGENT_FAILURE);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            byte[] response = new byte[mbuf.GetLength()];
            mbuf.GetByte(response);
            Send(response);
        }
Exemple #43
0
		/// <exception cref="System.Exception"></exception>
		protected internal virtual void SendOpenConfirmation()
		{
			Buffer buf = new Buffer(100);
			Packet packet = new Packet(buf);
			packet.Reset();
			buf.PutByte(unchecked((byte)SSH_MSG_CHANNEL_OPEN_CONFIRMATION));
			buf.PutInt(GetRecipient());
			buf.PutInt(id);
			buf.PutInt(lwsize);
			buf.PutInt(lmpsize);
			GetSession().Write(packet);
		}
Exemple #44
0
		public override void Run()
		{
			//System.err.println(this+":run >");
			Buffer buf = new Buffer(rmpsize);
			Packet packet = new Packet(buf);
			int i = -1;
			try
			{
				while (IsConnected() && thread != null && io != null && io.@in != null)
				{
					i = [email protected](buf.buffer, 14, buf.buffer.Length - 14 - Session.buffer_margin);
					if (i == 0)
					{
						continue;
					}
					if (i == -1)
					{
						Eof();
						break;
					}
					if (close)
					{
						break;
					}
					//System.out.println("write: "+i);
					packet.Reset();
					buf.PutByte(unchecked((byte)Session.SSH_MSG_CHANNEL_DATA));
					buf.PutInt(recipient);
					buf.PutInt(i);
					buf.Skip(i);
					GetSession().Write(packet, this, i);
				}
			}
			catch (Exception)
			{
			}
			//System.err.println("# ChannelExec.run");
			//e.printStackTrace();
			Sharpen.Thread _thread = thread;
			if (_thread != null)
			{
				lock (_thread)
				{
					Sharpen.Runtime.NotifyAll(_thread);
				}
			}
			thread = null;
		}
		// OID 1.2.840.113554.1.2.2 in DER
		/// <exception cref="System.Exception"></exception>
		public override bool Start(Session session)
		{
			base.Start(session);
			byte[] _username = Util.Str2byte(username);
			packet.Reset();
			// byte            SSH_MSG_USERAUTH_REQUEST(50)
			// string          user name(in ISO-10646 UTF-8 encoding)
			// string          service name(in US-ASCII)
			// string          "gssapi"(US-ASCII)
			// uint32          n, the number of OIDs client supports
			// string[n]       mechanism OIDS
			buf.PutByte(unchecked((byte)SSH_MSG_USERAUTH_REQUEST));
			buf.PutString(_username);
			buf.PutString(Util.Str2byte("ssh-connection"));
			buf.PutString(Util.Str2byte("gssapi-with-mic"));
			buf.PutInt(supported_oid.Length);
			for (int i = 0; i < supported_oid.Length; i++)
			{
				buf.PutString(supported_oid[i]);
			}
			session.Write(packet);
			string method = null;
			int command;
			while (true)
			{
				buf = session.Read(buf);
				command = buf.GetCommand() & unchecked((int)(0xff));
				if (command == SSH_MSG_USERAUTH_FAILURE)
				{
					return false;
				}
				if (command == SSH_MSG_USERAUTH_GSSAPI_RESPONSE)
				{
					buf.GetInt();
					buf.GetByte();
					buf.GetByte();
					byte[] message = buf.GetString();
					for (int i_1 = 0; i_1 < supported_oid.Length; i_1++)
					{
						if (Util.Array_equals(message, supported_oid[i_1]))
						{
							method = supported_method[i_1];
							break;
						}
					}
					if (method == null)
					{
						return false;
					}
					break;
				}
				// success
				if (command == SSH_MSG_USERAUTH_BANNER)
				{
					buf.GetInt();
					buf.GetByte();
					buf.GetByte();
					byte[] _message = buf.GetString();
					byte[] lang = buf.GetString();
					string message = Util.Byte2str(_message);
					if (userinfo != null)
					{
						userinfo.ShowMessage(message);
					}
					continue;
				}
				return false;
			}
			NSch.GSSContext context = null;
			try
			{
				Type c = Sharpen.Runtime.GetType(session.GetConfig(method));
				context = (NSch.GSSContext)(System.Activator.CreateInstance(c));
			}
			catch (Exception)
			{
				return false;
			}
			try
			{
				context.Create(username, session.host);
			}
			catch (JSchException)
			{
				return false;
			}
			byte[] token = new byte[0];
			while (!context.IsEstablished())
			{
				try
				{
					token = context.Init(token, 0, token.Length);
				}
				catch (JSchException)
				{
					// TODO
					// ERRTOK should be sent?
					// byte        SSH_MSG_USERAUTH_GSSAPI_ERRTOK
					// string      error token
					return false;
				}
				if (token != null)
				{
					packet.Reset();
					buf.PutByte(unchecked((byte)SSH_MSG_USERAUTH_GSSAPI_TOKEN));
					buf.PutString(token);
					session.Write(packet);
				}
				if (!context.IsEstablished())
				{
					buf = session.Read(buf);
					command = buf.GetCommand() & unchecked((int)(0xff));
					if (command == SSH_MSG_USERAUTH_GSSAPI_ERROR)
					{
						// uint32    major_status
						// uint32    minor_status
						// string    message
						// string    language tag
						buf = session.Read(buf);
						command = buf.GetCommand() & unchecked((int)(0xff));
					}
					else
					{
						//return false;
						if (command == SSH_MSG_USERAUTH_GSSAPI_ERRTOK)
						{
							// string error token
							buf = session.Read(buf);
							command = buf.GetCommand() & unchecked((int)(0xff));
						}
					}
					//return false;
					if (command == SSH_MSG_USERAUTH_FAILURE)
					{
						return false;
					}
					buf.GetInt();
					buf.GetByte();
					buf.GetByte();
					token = buf.GetString();
				}
			}
			Buffer mbuf = new Buffer();
			// string    session identifier
			// byte      SSH_MSG_USERAUTH_REQUEST
			// string    user name
			// string    service
			// string    "gssapi-with-mic"
			mbuf.PutString(session.GetSessionId());
			mbuf.PutByte(unchecked((byte)SSH_MSG_USERAUTH_REQUEST));
			mbuf.PutString(_username);
			mbuf.PutString(Util.Str2byte("ssh-connection"));
			mbuf.PutString(Util.Str2byte("gssapi-with-mic"));
			byte[] mic = context.GetMIC(mbuf.buffer, 0, mbuf.GetLength());
			if (mic == null)
			{
				return false;
			}
			packet.Reset();
			buf.PutByte(unchecked((byte)SSH_MSG_USERAUTH_GSSAPI_MIC));
			buf.PutString(mic);
			session.Write(packet);
			context.Dispose();
			buf = session.Read(buf);
			command = buf.GetCommand() & unchecked((int)(0xff));
			if (command == SSH_MSG_USERAUTH_SUCCESS)
			{
				return true;
			}
			else
			{
				if (command == SSH_MSG_USERAUTH_FAILURE)
				{
					buf.GetInt();
					buf.GetByte();
					buf.GetByte();
					byte[] foo = buf.GetString();
					int partial_success = buf.GetByte();
					//System.err.println(new String(foo)+
					//		 " partial_success:"+(partial_success!=0));
					if (partial_success != 0)
					{
						throw new JSchPartialAuthException(Util.Byte2str(foo));
					}
				}
			}
			return false;
		}
		public override void Run()
		{
			try
			{
				SendChannelOpen();
				Buffer buf = new Buffer(rmpsize);
				Packet packet = new Packet(buf);
				Session _session = GetSession();
				int i = 0;
				while (IsConnected() && thread != null && io != null && io.@in != null)
				{
					i = [email protected](buf.buffer, 14, buf.buffer.Length - 14 - Session.buffer_margin);
					if (i <= 0)
					{
						Eof();
						break;
					}
					packet.Reset();
					buf.PutByte(unchecked((byte)Session.SSH_MSG_CHANNEL_DATA));
					buf.PutInt(recipient);
					buf.PutInt(i);
					buf.Skip(i);
					lock (this)
					{
						if (close)
						{
							break;
						}
						_session.Write(packet, this, i);
					}
				}
			}
			catch (Exception)
			{
			}
			Disconnect();
		}
Exemple #47
0
		/// <exception cref="System.Exception"></exception>
		public override void Init(Session session, byte[] V_S, byte[] V_C, byte[] I_S, byte
			[] I_C)
		{
			throw new NotSupportedException (); // The crypto for this method is unusably slow
			this.session = session;
			this.V_S = V_S;
			this.V_C = V_C;
			this.I_S = I_S;
			this.I_C = I_C;
			try
			{
				Type c = Sharpen.Runtime.GetType(session.GetConfig("sha-1"));
				sha = (HASH)(System.Activator.CreateInstance(c));
				sha.Init();
			}
			catch (Exception ex)
			{
				System.Console.Error.WriteLine(e);
			}
			buf = new Buffer();
			packet = new Packet(buf);
			try
			{
				Type c = Sharpen.Runtime.GetType(session.GetConfig("dh"));
				dh = (NSch.DH)(System.Activator.CreateInstance(c));
				dh.Init();
			}
			catch (Exception ex)
			{
				//System.err.println(e);
				throw;
			}
			dh.SetP(p);
			dh.SetG(g);
			// The client responds with:
			// byte  SSH_MSG_KEXDH_INIT(30)
			// mpint e <- g^x mod p
			//         x is a random number (1 < x < (p-1)/2)
			e = dh.GetE();
			packet.Reset();
			buf.PutByte(unchecked((byte)SSH_MSG_KEXDH_INIT));
			buf.PutMPInt(e);
			if (V_S == null)
			{
				// This is a really ugly hack for Session.checkKexes ;-(
				return;
			}
			session.Write(packet);
			if (JSch.GetLogger().IsEnabled(Logger.INFO))
			{
				JSch.GetLogger().Log(Logger.INFO, "SSH_MSG_KEXDH_INIT sent");
				JSch.GetLogger().Log(Logger.INFO, "expecting SSH_MSG_KEXDH_REPLY");
			}
			state = SSH_MSG_KEXDH_REPLY;
		}
Exemple #48
0
		/// <exception cref="NSch.JSchException"></exception>
		private void SetPortForwarding(string bind_address, int rport)
		{
			lock (grr)
			{
				Buffer buf = new Buffer(100);
				// ??
				Packet packet = new Packet(buf);
				string address_to_bind = ChannelForwardedTCPIP.Normalize(bind_address);
				try
				{
					// byte SSH_MSG_GLOBAL_REQUEST 80
					// string "tcpip-forward"
					// boolean want_reply
					// string  address_to_bind
					// uint32  port number to bind
					packet.Reset();
					buf.PutByte(unchecked((byte)SSH_MSG_GLOBAL_REQUEST));
					buf.PutString(Util.Str2byte("tcpip-forward"));
					//      buf.putByte((byte)0);
					buf.PutByte(unchecked((byte)1));
					buf.PutString(Util.Str2byte(address_to_bind));
					buf.PutInt(rport);
					Write(packet);
				}
				catch (Exception e)
				{
					if (e is Exception)
					{
						throw new JSchException(e.ToString(), (Exception)e);
					}
					throw new JSchException(e.ToString());
				}
				grr.SetThread(Sharpen.Thread.CurrentThread());
				try
				{
					Sharpen.Thread.Sleep(10000);
				}
				catch (Exception)
				{
				}
				int reply = grr.GetReply();
				grr.SetThread(null);
				if (reply == 0)
				{
					throw new JSchException("remote port forwarding failed for listen port " + rport);
				}
			}
		}
		public override void Run()
		{
			Buffer buf = new Buffer(rmpsize);
			Packet packet = new Packet(buf);
			int i = 0;
			try
			{
				Session _session = GetSession();
				while (IsConnected() && thread != null && io != null && io.@in != null)
				{
					i = [email protected](buf.buffer, 14, buf.buffer.Length - 14 - 32 - 20);
					// padding and mac
					if (i <= 0)
					{
						Eof();
						break;
					}
					if (close)
					{
						break;
					}
					packet.Reset();
					buf.PutByte(unchecked((byte)Session.SSH_MSG_CHANNEL_DATA));
					buf.PutInt(recipient);
					buf.PutInt(i);
					buf.Skip(i);
					_session.Write(packet, this, i);
				}
			}
			catch (Exception)
			{
			}
			Disconnect();
		}
Exemple #50
0
		/// <exception cref="System.Exception"></exception>
		public virtual void SendIgnore()
		{
			Buffer buf = new Buffer();
			Packet packet = new Packet(buf);
			packet.Reset();
			buf.PutByte(unchecked((byte)SSH_MSG_IGNORE));
			Write(packet);
		}
		/// <exception cref="NSch.JSchException"></exception>
		public override void Connect()
		{
			try
			{
				Session _session = GetSession();
				if (!_session.IsConnected())
				{
					throw new JSchException("session is down");
				}
				Buffer buf = new Buffer(150);
				Packet packet = new Packet(buf);
				// send
				// byte   SSH_MSG_CHANNEL_OPEN(90)
				// string channel type         //
				// uint32 sender channel       // 0
				// uint32 initial window size  // 0x100000(65536)
				// uint32 maxmum packet size   // 0x4000(16384)
				packet.Reset();
				buf.PutByte(unchecked((byte)90));
				buf.PutString(Util.Str2byte("direct-tcpip"));
				buf.PutInt(id);
				buf.PutInt(lwsize);
				buf.PutInt(lmpsize);
				buf.PutString(Util.Str2byte(host));
				buf.PutInt(port);
				buf.PutString(Util.Str2byte(originator_IP_address));
				buf.PutInt(originator_port);
				_session.Write(packet);
				int retry = 1000;
				try
				{
					while (this.GetRecipient() == -1 && _session.IsConnected() && retry > 0 && !eof_remote
						)
					{
						//Thread.sleep(500);
						Sharpen.Thread.Sleep(50);
						retry--;
					}
				}
				catch (Exception)
				{
				}
				if (!_session.IsConnected())
				{
					throw new JSchException("session is down");
				}
				if (retry == 0 || this.eof_remote)
				{
					throw new JSchException("channel is not opened.");
				}
				connected = true;
				if (io.@in != null)
				{
					thread = new Sharpen.Thread(this);
					thread.SetName("DirectTCPIP thread " + _session.GetHost());
					if (_session.daemon_thread)
					{
						thread.SetDaemon(_session.daemon_thread);
					}
					thread.Start();
				}
			}
			catch (Exception e)
			{
				io.Close();
				io = null;
				Channel.Del(this);
				if (e is JSchException)
				{
					throw (JSchException)e;
				}
			}
		}
Exemple #52
0
		/// <exception cref="System.Exception"></exception>
		private void Send_kexinit()
		{
			if (in_kex)
			{
				return;
			}
			string cipherc2s = GetConfig("cipher.c2s");
			string ciphers2c = GetConfig("cipher.s2c");
			string[] not_available = CheckCiphers(GetConfig("CheckCiphers"));
			if (not_available != null && not_available.Length > 0)
			{
				cipherc2s = Util.DiffString(cipherc2s, not_available);
				ciphers2c = Util.DiffString(ciphers2c, not_available);
				if (cipherc2s == null || ciphers2c == null)
				{
					throw new JSchException("There are not any available ciphers.");
				}
			}
			in_kex = true;
			kex_start_time = Runtime.CurrentTimeMillis();
			// byte      SSH_MSG_KEXINIT(20)
			// byte[16]  cookie (random bytes)
			// string    kex_algorithms
			// string    server_host_key_algorithms
			// string    encryption_algorithms_client_to_server
			// string    encryption_algorithms_server_to_client
			// string    mac_algorithms_client_to_server
			// string    mac_algorithms_server_to_client
			// string    compression_algorithms_client_to_server
			// string    compression_algorithms_server_to_client
			// string    languages_client_to_server
			// string    languages_server_to_client
			Buffer buf = new Buffer();
			// send_kexinit may be invoked
			Packet packet = new Packet(buf);
			// by user thread.
			packet.Reset();
			buf.PutByte(unchecked((byte)SSH_MSG_KEXINIT));
			lock (random)
			{
				random.Fill(buf.buffer, buf.index, 16);
				buf.Skip(16);
			}
			buf.PutString(Util.Str2byte(GetConfig("kex")));
			buf.PutString(Util.Str2byte(GetConfig("server_host_key")));
			buf.PutString(Util.Str2byte(cipherc2s));
			buf.PutString(Util.Str2byte(ciphers2c));
			buf.PutString(Util.Str2byte(GetConfig("mac.c2s")));
			buf.PutString(Util.Str2byte(GetConfig("mac.s2c")));
			buf.PutString(Util.Str2byte(GetConfig("compression.c2s")));
			buf.PutString(Util.Str2byte(GetConfig("compression.s2c")));
			buf.PutString(Util.Str2byte(GetConfig("lang.c2s")));
			buf.PutString(Util.Str2byte(GetConfig("lang.s2c")));
			buf.PutByte(unchecked((byte)0));
			buf.PutInt(0);
			buf.SetOffSet(5);
			I_C = new byte[buf.GetLength()];
			buf.GetByte(I_C);
			Write(packet);
			if (JSch.GetLogger().IsEnabled(Logger.INFO))
			{
				JSch.GetLogger().Log(Logger.INFO, "SSH_MSG_KEXINIT sent");
			}
		}
Exemple #53
0
		/// <exception cref="System.Exception"></exception>
		private void PutHEAD(Buffer buf, byte type, int length)
		{
			buf.PutByte(unchecked((byte)Session.SSH_MSG_CHANNEL_DATA));
			buf.PutInt(recipient);
			buf.PutInt(length + 4);
			buf.PutInt(length);
			buf.PutByte(type);
		}