Esempio n. 1
0
		public void request(Session session, Channel channel)
		{
			Buffer buf=new Buffer();
			Packet packet=new Packet(buf);

			bool reply=waitForReply();
			if(reply)
			{
				channel.reply=-1;
			}

			packet.reset();
			buf.putByte((byte)Session.SSH_MSG_CHANNEL_REQUEST);
			buf.putInt(channel.getRecipient());
			buf.putString( new String( "subsystem" ).getBytes());
			buf.putByte((byte)(waitForReply() ? 1 : 0));
			buf.putString(subsystem.getBytes());
			session.write(packet);

			if(reply)
			{
				while(channel.reply==-1)
				{
					try{Thread.sleep(10);}
					catch//(System.Exception ee)
					{
					}
				}
				if(channel.reply==0)
				{
					throw new JSchException("failed to send subsystem request");
				}
			}
		}
		private void receive_newkeys(Buffer buf, KeyExchange kex)  
		{
			//    send_newkeys();
			updateKeys(kex);
			in_kex=false;
		}
		public Buffer read(Buffer buf) 
		{
			int j=0;
			while(true)
			{
				buf.reset();
				io.getByte(buf.buffer, buf.index, cipher_size); buf.index+=cipher_size;
				if(s2ccipher!=null)
				{
					s2ccipher.update(buf.buffer, 0, cipher_size, buf.buffer, 0);
				}
//				j=((buf.buffer[0]<<24)&0xff000000)|
//					((buf.buffer[1]<<16)&0x00ff0000)|
//					((buf.buffer[2]<< 8)&0x0000ff00)|
//					((buf.buffer[3]    )&0x000000ff);
				j=Util.ToInt32( buf.buffer, 0 );
				j=j-4-cipher_size+8;
				if(j<0 || (buf.index+j)>buf.buffer.Length)
				{
					throw new IOException("invalid data");
				}
				if(j>0)
				{
					io.getByte(buf.buffer, buf.index, j); buf.index+=(j);
					if(s2ccipher!=null)
					{
						s2ccipher.update(buf.buffer, cipher_size, j, buf.buffer, cipher_size);
					}
				}

				if(s2cmac!=null)
				{
					s2cmac.update(seqi);
					s2cmac.update(buf.buffer, 0, buf.index);
					byte[] result=s2cmac.doFinal();
					io.getByte(mac_buf, 0, mac_buf.Length);
					if(!Arrays.equals(result, mac_buf))
					{
						throw new IOException("MAC Error");
					}
				}
				seqi++;

				if(inflater!=null)
				{
					//inflater.uncompress(buf);
					int pad=buf.buffer[4];
					uncompress_len[0]=buf.index-5-pad;
					byte[] foo=inflater.uncompress(buf.buffer, 5, uncompress_len);
					if(foo!=null)
					{
						buf.buffer=foo;
						buf.index=5+uncompress_len[0];
					}
					else
					{
						System.Console.Error.WriteLine("fail in inflater");
						break;
					}
				}

				int type=buf.buffer[5]&0xff;
				//System.Console.WriteLine("read: "+type);
				if(type==SSH_MSG_DISCONNECT)
				{
					buf.rewind();
					buf.getInt();buf.getShort();
					int reason_code=buf.getInt();
					byte[] description=buf.getString();
					byte[] language_tag=buf.getString();
					/*
						System.Console.Error.WriteLine("SSH_MSG_DISCONNECT:"+
											   " "+reason_code+
								   " "+new String(description)+
								   " "+new String(language_tag));
					*/
					throw new JSchException("SSH_MSG_DISCONNECT:"+
						" "+reason_code+
						" "+new String(description)+
						" "+new String(language_tag));
					//break;
				}
				else if(type==SSH_MSG_IGNORE)
				{
				}
				else if(type==SSH_MSG_DEBUG)
				{
					buf.rewind();
					buf.getInt();buf.getShort();
					/*
						byte always_display=(byte)buf.getByte();
						byte[] message=buf.getString();
						byte[] language_tag=buf.getString();
						System.Console.Error.WriteLine("SSH_MSG_DEBUG:"+
								   " "+new String(message)+
								   " "+new String(language_tag));
					*/
				}
				else if(type==SSH_MSG_CHANNEL_WINDOW_ADJUST)
				{
					buf.rewind();
					buf.getInt();buf.getShort();
					Channel c=Channel.getChannel(buf.getInt(), this);
					if(c==null)
					{
					}
					else
					{
						c.addRemoteWindowSize(buf.getInt());
					}
				}
				else
				{
					break;
				}
			}
			buf.rewind();
			return buf;
		}
		private KeyExchange receive_kexinit(Buffer buf)  
		{
			int j=buf.getInt();
			if(j!=buf.getLength())
			{    // packet was compressed and
				buf.getByte();           // j is the size of deflated packet.
				I_S=new byte[buf.index-5];
			}
			else
			{
				I_S=new byte[j-1-buf.getByte()];
			}
			Tamir.SharpSsh.java.System.arraycopy(buf.buffer, buf.s, I_S, 0, I_S.Length);
			/*
			try{
			byte[] tmp=new byte[I_S.Length];
			Tamir.SharpSsh.java.System.arraycopy(I_S, 0, tmp, 0, I_S.Length);
			Buffer tmpb=new Buffer(tmp);
			System.Console.WriteLine("I_S: len="+I_S.Length);
			tmpb.setOffSet(17);
			System.Console.WriteLine("kex: "+new String(tmpb.getString()));
			System.Console.WriteLine("server_host_key: "+new String(tmpb.getString()));
			System.Console.WriteLine("cipher.c2s: "+new String(tmpb.getString()));
			System.Console.WriteLine("cipher.s2c: "+new String(tmpb.getString()));
			System.Console.WriteLine("mac.c2s: "+new String(tmpb.getString()));
			System.Console.WriteLine("mac.s2c: "+new String(tmpb.getString()));
			System.Console.WriteLine("compression.c2s: "+new String(tmpb.getString()));
			System.Console.WriteLine("compression.s2c: "+new String(tmpb.getString()));
			System.Console.WriteLine("lang.c2s: "+new String(tmpb.getString()));
			System.Console.WriteLine("lang.s2c: "+new String(tmpb.getString()));
			System.Console.WriteLine("?: "+(tmpb.getByte()&0xff));
			System.Console.WriteLine("??: "+tmpb.getInt());
			}
			catch(Exception e){
			System.Console.WriteLine(e);
			}
			*/

			send_kexinit();
			String[] guess=KeyExchange.guess(I_S, I_C);
			if(guess==null)
			{
				throw new JSchException("Algorithm negotiation fail");
			}

			if(!isAuthed &&
				(guess[KeyExchange.PROPOSAL_ENC_ALGS_CTOS].equals("none") ||
				(guess[KeyExchange.PROPOSAL_ENC_ALGS_STOC].equals("none"))))
			{
				throw new JSchException("NONE Cipher should not be chosen before authentification is successed.");
			}

			KeyExchange kex=null;
			try
			{
				Class c=Class.forName(getConfig(guess[KeyExchange.PROPOSAL_KEX_ALGS]));
				kex=(KeyExchange)(c.newInstance());
			}
			catch(Exception e){ System.Console.Error.WriteLine("kex: "+e); }
			kex._guess=guess;
			kex.init(this, V_S, V_C, I_S, I_C);
			return kex;
		}
		public void sendKeepAliveMsg()
		{
			Buffer buf=new Buffer();
			Packet packet=new Packet(buf);
			packet.reset();
			buf.putByte((byte)SSH_MSG_GLOBAL_REQUEST);
			buf.putString(keepalivemsg);
			buf.putByte((byte)1);
			write(packet);
		}
		public void sendIgnore() 
		{
			Buffer buf=new Buffer();
			Packet packet=new Packet(buf);
			packet.reset();
			buf.putByte((byte)SSH_MSG_IGNORE);
			write(packet);
		}
		private void setPortForwarding(int rport) 
		{
			lock(grr)
			{
				Buffer buf=new Buffer(100); // ??
				Packet packet=new Packet(buf);

				try
				{
					// byte SSH_MSG_GLOBAL_REQUEST 80
					// String "tcpip-forward"
					// bool want_reply
					// String  address_to_bind
					// uint32  port number to bind
					packet.reset();
					buf.putByte((byte) SSH_MSG_GLOBAL_REQUEST);
					buf.putString( new String( "tcpip-forward" ).getBytes());
					//      buf.putByte((byte)0);
					buf.putByte((byte)1);
					buf.putString(new String("0.0.0.0").getBytes());
					buf.putInt(rport);
					write(packet);
				}
				catch(Exception e)
				{
					throw new JSchException(e.ToString());
				}

				grr.setThread(Thread.currentThread());
				try{ Thread.Sleep(10000);}
				catch(Exception e)
				{
				}
				int reply=grr.getReply();
				grr.setThread(null);
				if(reply==0)
				{
					throw new JSchException("remote port forwarding failed for listen port "+rport);
				}
			}
		}
		public void connect(int connectTimeout) 
		{
			if(_isConnected)
			{
				throw new JSchException("session is already connected");
			}
			io=new IO();
			if(random==null)
			{
				try
				{
					Class c=Class.forName(getConfig("random"));
					random=(Random)(c.newInstance());
				}
				catch(Exception e)
				{
					System.Console.Error.WriteLine("connect: random "+e);
				}
			}
			Packet.setRandom(random);

			try	
			{
				int i, j;
				int pad=0;

				if(proxy==null)
				{
					proxy=jsch.getProxy(host);
					if(proxy!=null)
					{
						lock(proxy)
						{
							proxy.close();
						}
					}
				}

				if(proxy==null)
				{
					Stream In;
					Stream 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.setTcpNoDelay(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.setSoTimeout(connectTimeout);
				}

				_isConnected=true;

				while(true)
				{

					i=0;
					j=0;
					while(i<buf.buffer.Length)
					{
						j=io.getByte();
						if(j<0)break;
						buf.buffer[i]=(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(buf.buffer[i-1]==13)
						{  // 0x0d
							i--;
						}
					}

					if(i>4 && (i!=buf.buffer.Length) &&
						(buf.buffer[0]!='S'||buf.buffer[1]!='S'||
						buf.buffer[2]!='H'||buf.buffer[3]!='-'))
					{
						//System.err.println(new String(buf.buffer, 0, i);
						continue;
					}

					if(i==buf.buffer.Length ||
						i<7 ||                                      // SSH-1.99 or SSH-2.0
						(buf.buffer[4]=='1' && buf.buffer[6]!='9')  // SSH-1.5
						)
					{
						throw new JSchException("invalid server's version String");
					}
					break;
				}				

				V_S=new byte[i]; Tamir.SharpSsh.java.System.arraycopy(buf.buffer, 0, V_S, 0, i);
				//System.Console.WriteLine("V_S: ("+i+") ["+new String(V_S)+"]");

				//io.put(V_C, 0, V_C.Length); io.put("\n".getBytes(), 0, 1);
			{
				// Some Cisco devices will miss to read '\n' if it is sent separately.
				byte[] foo=new byte[V_C.Length+1];
				Tamir.SharpSsh.java.System.arraycopy(V_C, 0, foo, 0, V_C.Length);
				foo[foo.Length-1]=(byte)'\n';
				io.put(foo, 0, foo.Length);
			}

				buf=read(buf);
				//System.Console.WriteLine("read: 20 ? "+buf.buffer[5]);
				if(buf.buffer[5]!=SSH_MSG_KEXINIT)
				{
					throw new JSchException("invalid protocol: "+buf.buffer[5]);
				}
				KeyExchange kex=receive_kexinit(buf);

				while(true)
				{
					buf=read(buf);
					if(kex.getState()==buf.buffer[5])
					{
						bool result=kex.next(buf);
						if(!result)
						{
							//System.Console.WriteLine("verify: "+result);
							in_kex=false;
							throw new JSchException("verify: "+result);
						}
					}
					else
					{
						in_kex=false;
						throw new JSchException("invalid protocol(kex): "+buf.buffer[5]);
					}
					if(kex.getState()==KeyExchange.STATE_END)
					{
						break;
					}
				}

				try{ checkHost(host, kex); }
				catch(JSchException ee)
				{
					in_kex=false;
					throw ee;
				}

				send_newkeys();

				// receive SSH_MSG_NEWKEYS(21)
				buf=read(buf);
				//System.Console.WriteLine("read: 21 ? "+buf.buffer[5]);
				if(buf.buffer[5]==SSH_MSG_NEWKEYS)
				{
					receive_newkeys(buf, kex);
				}
				else
				{
					in_kex=false;
					throw new JSchException("invalid protocol(newkyes): "+buf.buffer[5]);
				}

				bool auth=false;
				bool auth_cancel=false;

				UserAuthNone usn=new UserAuthNone(userinfo);
				auth=usn.start(this);

				String methods=null;
				if(!auth)
				{
					methods=usn.getMethods();
					if(methods!=null)
					{
						methods=methods.toLowerCase();
					}
					else
					{
						// methods: publickey,password,keyboard-interactive
						methods="publickey,password,keyboard-interactive";
					}
				}

			loop:
				while(true)
				{

					//System.Console.WriteLine("methods: "+methods);

					while(!auth &&
						methods!=null && methods.Length()>0)
					{

						//System.Console.WriteLine("  methods: "+methods);

						UserAuth us=null;
						if(methods.startsWith("publickey"))
						{
							//System.Console.WriteLine("   jsch.identities.size()="+jsch.identities.size());
							lock(jsch.identities)
							{
								if(jsch.identities.size()>0)
								{
									us=new UserAuthPublicKey(userinfo);
								}
							}
						}
						else if(methods.startsWith("keyboard-interactive"))
						{
							if(userinfo is UIKeyboardInteractive)
							{
								us=new UserAuthKeyboardInteractive(userinfo);
							}
						}
						else if(methods.startsWith("password"))
						{
							us=new UserAuthPassword(userinfo);
						}
						if(us!=null)
						{
							try
							{
								auth=us.start(this);
								auth_cancel=false;
							}
							catch(JSchAuthCancelException ee)
							{
								//System.Console.WriteLine(ee);
								auth_cancel=true;
							}
							catch(JSchPartialAuthException ee)
							{
								methods=ee.getMethods();
								//System.Console.WriteLine("PartialAuth: "+methods);
								auth_cancel=false;
								continue;//loop;
							}
							catch(RuntimeException ee)
							{
								throw ee;
							}
							catch(Exception ee)
							{
								System.Console.WriteLine("ee: "+ee); // SSH_MSG_DISCONNECT: 2 Too many authentication failures
							}
						}
						if(!auth)
						{
							int comma=methods.indexOf(",");
							if(comma==-1) break;
							methods=methods.subString(comma+1);
						}
					}
					break;
				}

				if(connectTimeout>0 || timeout>0)
				{
					socket.setSoTimeout(timeout);
				}

				if(auth)
				{
					isAuthed=true;
					connectThread=new Thread(this);
					connectThread.setName("Connect thread "+host+" session");
					connectThread.start();
					return;
				}
				if(auth_cancel)
					throw new JSchException("Auth cancel");
				throw new JSchException("Auth fail");
			}
			catch(Exception e) 
			{
				in_kex=false;
				if(_isConnected)
				{
					try
					{
						packet.reset();
						buf.putByte((byte)SSH_MSG_DISCONNECT);
						buf.putInt(3);
						buf.putString(new String(e.ToString()).getBytes());
						buf.putString(new String("en").getBytes());
						write(packet);
						disconnect();
					}
					catch(Exception ee)
					{
					}
				}
				_isConnected=false;
				//e.printStackTrace();
				if(e is RuntimeException) throw (RuntimeException)e;
				if(e is JSchException) throw (JSchException)e;
				throw new JSchException("Session.connect: "+e);
			}
		}
		internal Session(JSch jsch)  
		{
			;
			this.jsch=jsch;
			buf=new Buffer();
			packet=new Packet(buf);
		}
Esempio n. 10
0
		public 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;

			try
			{
				while(_isConnected &&
					thread!=null)
				{
					buf=read(buf);
					int msgType=buf.buffer[5]&0xff;
					//      if(msgType!=94)
					//System.Console.WriteLine("read: 94 ? "+msgType);

					if(kex!=null && kex.getState()==msgType)
					{
						bool result=kex.next(buf);
						if(!result)
						{
							throw new JSchException("verify: "+result);
						}
						continue;
					}

					switch(msgType)
					{
						case SSH_MSG_KEXINIT:
							//System.Console.WriteLine("KEXINIT");
							kex=receive_kexinit(buf);
							break;

						case SSH_MSG_NEWKEYS:
							//System.Console.WriteLine("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;
							}
							try
							{
								channel.write(foo, start[0], length[0]);
							}
							catch(Exception e)
							{
								//System.Console.WriteLine(e);
								try{channel.disconnect();}
								catch(Exception ee){}
								break;
							}
							int len=length[0];
							channel.setLocalWindowSize(channel.lwsize-len);
							if(channel.lwsize<channel.lwsize_max/2)
							{
								packet.reset();
								buf.putByte((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.Console.WriteLine("stderr: "+new String(foo,start[0],length[0]));
							if(channel==null)
							{
								break;
							}
							//channel.write(foo, start[0], length[0]);
							channel.write_ext(foo, start[0], length[0]);

							len=length[0];
							channel.setLocalWindowSize(channel.lwsize-len);
							if(channel.lwsize<channel.lwsize_max/2)
							{
								packet.reset();
								buf.putByte((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();
							}
							/*
							packet.reset();
							buf.putByte((byte)SSH_MSG_CHANNEL_EOF);
							buf.putInt(channel.getRecipient());
							write(packet);
							*/
							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();
							}
							/*
								if(Channel.pool.size()==0){
							  thread=null;
							}
							*/
							break;
						case SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
							buf.getInt();
							buf.getShort();
							i=buf.getInt();
							channel=Channel.getChannel(i, this);
							if(channel==null)
							{
								//break;
							}
							channel.setRecipient(buf.getInt());
							channel.setRemoteWindowSize(buf.getInt());
							channel.setRemotePacketSize(buf.getInt());
							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=(byte)SSH_MSG_CHANNEL_FAILURE;
								if((new String(foo)).equals("exit-status"))
								{
									i=buf.getInt();             // exit-status
									channel.setExitStatus(i);
									//	    System.Console.WriteLine("exit-stauts: "+i);
									//          channel.close();
									reply_type=(byte)SSH_MSG_CHANNEL_SUCCESS;
								}
								if(reply)
								{
									packet.reset();
									buf.putByte(reply_type);
									buf.putInt(channel.getRecipient());
									write(packet);
								}
							}
							else
							{
							}
							break;
						case SSH_MSG_CHANNEL_OPEN:
							buf.getInt();
							buf.getShort();
							foo=buf.getString();
							String ctyp=new String(foo);
							//System.Console.WriteLine("type="+ctyp);
							if(!new String("forwarded-tcpip").equals(ctyp) &&
								!(new String("x11").equals(ctyp) && x11_forwarding))
							{
								System.Console.WriteLine("Session.run: CHANNEL OPEN "+ctyp);
								throw new IOException("Session.run: CHANNEL OPEN "+ctyp);
							}
							else
							{
								channel=Channel.getChannel(ctyp);
								addChannel(channel);
								channel.getData(buf);
								channel.init();

								packet.reset();
								buf.putByte((byte)SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
								buf.putInt(channel.getRecipient());
								buf.putInt(channel.id);
								buf.putInt(channel.lwsize);
								buf.putInt(channel.lmpsize);
								write(packet);
								Thread tmp=new Thread(channel);
								tmp.setName("Channel "+ctyp+" "+host);
								tmp.start();
								break;
							}
						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
							reply=(buf.getByte()!=0);
							if(reply)
							{
								packet.reset();
								buf.putByte((byte)SSH_MSG_REQUEST_FAILURE);
								write(packet);
							}
							break;
						case SSH_MSG_REQUEST_FAILURE:
						case SSH_MSG_REQUEST_SUCCESS:
							Thread t=grr.getThread();
							if(t!=null)
							{
								grr.setReply(msgType==SSH_MSG_REQUEST_SUCCESS? 1 : 0);
								t.interrupt();
							}
							break;
						default:
							System.Console.WriteLine("Session.run: unsupported type "+msgType);
							throw new IOException("Unknown SSH message type "+msgType);
					}
				}
			}
			catch(Exception e)
			{
				//System.Console.WriteLine("# Session.run");
				//e.printStackTrace();
			}
			try
			{
				disconnect();
			}
			catch(NullReferenceException e)
			{
				//System.Console.WriteLine("@1");
				//e.printStackTrace();
			}
			catch(Exception e)
			{
				//System.Console.WriteLine("@2");
				//e.printStackTrace();
			}
			_isConnected=false;
		}
Esempio n. 11
0
		internal Header header(Buffer buf, Header header)
		{
			buf.rewind();
			int i=fill(buf.buffer, 0, 9);
			header.length=buf.getInt()-5;
			header.type=buf.getByte()&0xff;
			header.rid=buf.getInt();  
			return header;
		}
Esempio n. 12
0
		private void throwStatusError(Buffer buf, int i) 
		{ //throws SftpException{
			if(server_version>=3)
			{
				byte[] str=buf.getString();
				//byte[] tag=buf.getString();
				throw new SftpException(i, new String(str));
			}
			else
			{
				throw new SftpException(i, "Failure");
			}
		}
Esempio n. 13
0
		public override void start() 
		{ //throws JSchException{
			try
			{

				PipedOutputStream pos=new PipedOutputStream();
				io.setOutputStream(pos);
				PipedInputStream pis=new MyPipedInputStream(pos, 32*1024);
				io.setInputStream(pis);

				Request request=new RequestSftp();
				request.request(session, this);

				/*
					  System.err.println("lmpsize: "+lmpsize);
					  System.err.println("lwsize: "+lwsize);
					  System.err.println("rmpsize: "+rmpsize);
					  System.err.println("rwsize: "+rwsize);
				*/

				buf=new Buffer(rmpsize);
				packet=new Packet(buf);
				int i=0;
				int length;
				int type;
				byte[] str;

				// send SSH_FXP_INIT
				sendINIT();

				// receive SSH_FXP_VERSION
				Header _header=new Header();
				_header=header(buf, _header);
				length=_header.length;
				if(length > MAX_MSG_LENGTH)
				{
					throw new SftpException(SSH_FX_FAILURE, "Received message is too long: " + length);
				}
				type=_header.type;             // 2 -> SSH_FXP_VERSION
				server_version=_header.rid;
				skip(length);
				//System.err.println("SFTP protocol server-version="+server_version);
				//System.Console.WriteLine("server_version="+server_version+", type="+type+", length="+length+", i="+i);
				
				// send SSH_FXP_REALPATH
				sendREALPATH(new String(".").getBytes());

				// receive SSH_FXP_NAME
				_header=header(buf, _header);
				length=_header.length;
				type=_header.type;            // 104 -> SSH_FXP_NAME
				buf.rewind();
				fill(buf.buffer, 0, length);
				i=buf.getInt();              // count
				//System.Console.WriteLine("type="+type+", length="+length+", i="+i);
				str=buf.getString();         // filename
				//System.Console.WriteLine("str.length="+str.Length);
				home=cwd=new String(str);
				str=buf.getString();         // logname
				//    SftpATTRS.getATTR(buf);      // attrs

				lcwd=new File(".").getCanonicalPath();
			}
			catch(Exception e)
			{
				//System.out.println(e);
				//System.Console.WriteLine(e);
				if(e is JSchException) throw (JSchException)e;
				throw new JSchException(e.toString());
			}
		}
Esempio n. 14
0
        public override bool start(Session session)
        {
//    super.start(session);
//System.out.println("UserAuthPassword: start");
            Packet packet   = session.packet;
            Buffer buf      = session.buf;
            String username = session.username;
            String password = session.password;
            String dest     = username + "@" + session.host;

            if (session.port != 22)
            {
                dest += (":" + session.port);
            }

            while (true)
            {
                if (password == null)
                {
                    if (userinfo == null)
                    {
                        //throw new JSchException("USERAUTH fail");
                        return(false);
                    }
                    if (!userinfo.promptPassword("Password for " + dest))
                    {
                        throw new JSchAuthCancelException("password");
                        //break;
                    }
                    password = userinfo.getPassword();

                    if (password == null)
                    {
                        throw new JSchAuthCancelException("password");
                        //break;
                    }
                }

                byte[] _username = null;
                try{ _username = Util.getBytesUTF8(username); }
                catch {//(java.io.UnsupportedEncodingException e){
                    _username = Util.getBytes(username);
                }

                byte[] _password = null;
                try{ _password = Util.getBytesUTF8(password); }
                catch {//(java.io.UnsupportedEncodingException e){
                    _password = Util.getBytes(password);
                }

                // send
                // byte      SSH_MSG_USERAUTH_REQUEST(50)
                // string    user name
                // string    service name ("ssh-connection")
                // string    "password"
                // boolen    FALSE
                // string    plaintext password (ISO-10646 UTF-8)
                packet.reset();
                buf.putByte((byte)Session.SSH_MSG_USERAUTH_REQUEST);
                buf.putString(_username);
                buf.putString(Util.getBytes("ssh-connection"));
                buf.putString(Util.getBytes("password"));
                buf.putByte((byte)0);
                buf.putString(_password);
                session.write(packet);

loop:
                while (true)
                {
                    // receive
                    // byte      SSH_MSG_USERAUTH_SUCCESS(52)
                    // string    service name
                    buf = session.read(buf);
                    //System.out.println("read: 52 ? "+    buf.buffer[5]);
                    if (buf.buffer[5] == Session.SSH_MSG_USERAUTH_SUCCESS)
                    {
                        return(true);
                    }
                    if (buf.buffer[5] == Session.SSH_MSG_USERAUTH_BANNER)
                    {
                        buf.getInt(); buf.getByte(); buf.getByte();
                        byte[] _message = buf.getString();
                        byte[] lang     = buf.getString();
                        String message  = null;
                        try{ message = Util.getStringUTF8(_message); }
                        catch {//(java.io.UnsupportedEncodingException e){
                            message = Util.getString(_message);
                        }
                        if (userinfo != null)
                        {
                            userinfo.showMessage(message);
                        }
                        goto loop;
                    }
                    if (buf.buffer[5] == Session.SSH_MSG_USERAUTH_FAILURE)
                    {
                        buf.getInt(); buf.getByte(); buf.getByte();
                        byte[] foo             = buf.getString();
                        int    partial_success = buf.getByte();
                        //System.out.println(new String(foo)+
                        //		 " partial_success:"+(partial_success!=0));
                        if (partial_success != 0)
                        {
                            throw new JSchPartialAuthException(Util.getString(foo));
                        }
                        break;
                    }
                    else
                    {
//        System.out.println("USERAUTH fail ("+buf.buffer[5]+")");
//	  throw new JSchException("USERAUTH fail ("+buf.buffer[5]+")");
                        return(false);
                    }
                }
                password = null;
            }
            //throw new JSchException("USERAUTH fail");
            //return false;
        }