ReadString() public method

public ReadString ( ) : byte[]
return byte[]
        internal override void getData(Buffer buf)
        {
            setRecipient(buf.ReadInt());
            setRemoteWindowSize(buf.ReadInt());
            setRemotePacketSize(buf.ReadInt());
            byte[] addr = buf.ReadString();
            int    port = buf.ReadInt();

            byte[] orgaddr = buf.ReadString();
            int    orgport = buf.ReadInt();

            /*
             * System.out.println("addr: "+Encoding.UTF8.GetString(addr));
             * System.out.println("port: "+port);
             * System.out.println("orgaddr: "+Encoding.UTF8.GetString(orgaddr));
             * System.out.println("orgport: "+orgport);
             */

            lock (pool)
            {
                for (int i = 0; i < pool.Count; i++)
                {
                    Object[] foo = (Object[])(pool[i]);
                    if (foo[0] != session)
                    {
                        continue;
                    }
                    if (((int)foo[1]) != port)
                    {
                        continue;
                    }
                    this.rport  = port;
                    this.target = (String)foo[2];
                    if (foo[3] == null || (foo[3] is Object[]))
                    {
                        this.lport = -1;
                    }
                    else
                    {
                        this.lport = (int)foo[3];
                    }
                    if (foo.Length >= 5)
                    {
                        this.factory = ((SocketFactory)foo[4]);
                    }
                    break;
                }
                if (target == null)
                {
                    Console.WriteLine("??");
                }
            }
        }
Esempio n. 2
0
        internal static SftpATTRS getATTR(Buffer buf)
        {
            SftpATTRS attr = new SftpATTRS();

            attr.Flags = buf.ReadInt();
            if ((attr.Flags & SSH_FILEXFER_ATTR_SIZE) != 0)
            {
                attr._Size = buf.ReadLong();
            }
            if ((attr.Flags & SSH_FILEXFER_ATTR_UIDGID) != 0)
            {
                attr.uid = buf.ReadInt(); attr.gid = buf.ReadInt();
            }
            if ((attr.Flags & SSH_FILEXFER_ATTR_PERMISSIONS) != 0)
            {
                attr._Permissions = (PermissionFlags)buf.ReadInt();
            }
            if ((attr.Flags & SSH_FILEXFER_ATTR_ACMODTIME) != 0)
            {
                attr.AccessTime = buf.ReadInt();
            }
            if ((attr.Flags & SSH_FILEXFER_ATTR_ACMODTIME) != 0)
            {
                attr.ModificationTime = buf.ReadInt();
            }
            if ((attr.Flags & SSH_FILEXFER_ATTR_EXTENDED) != 0)
            {
                int count = buf.ReadInt();
                if (count > 0)
                {
                    attr.extended = new String[count * 2];
                    for (int i = 0; i < count; i++)
                    {
                        attr.extended[i * 2]     = Util.getString(buf.ReadString());
                        attr.extended[i * 2 + 1] = Util.getString(buf.ReadString());
                    }
                }
            }
            return(attr);
        }
Esempio n. 3
0
 private void throwStatusError(Buffer buf, int i)
 {
     if (ServerVersion >= 3)
     {
         byte[] str = buf.ReadString();
         //byte[] tag=buf.getString();
         throw new SftpException(i, Encoding.UTF8.GetString(str));
     }
     else
     {
         throw new SftpException(i, "Failure");
     }
 }
Esempio n. 4
0
        public override bool next(Buffer _buf)
        {
            int  i, j;
            bool result = false;

            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.ReadInt();
                _buf.ReadByte();
                j = _buf.ReadByte();
                if (j != 31)
                {
                    Console.WriteLine("type: must be 31 " + j);
                    result = false;
                }

                p = _buf.ReadMPInt();
                g = _buf.ReadMPInt();

                /*
                 * for(int iii=0; iii<p.length; iii++){
                 * System.out.println("0x"+Integer.toHexString(p[iii]&0xff)+",");
                 * }
                 * System.out.println("");
                 * for(int iii=0; iii<g.length; iii++){
                 * System.out.println("0x"+Integer.toHexString(g[iii]&0xff)+",");
                 * }
                 */
                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.WriteByte((byte)0x20);
                buf.WriteMPInt(e);
                session.write(packet);

                state  = SSH_MSG_KEX_DH_GEX_REPLY;
                result = true;
                break;

            case SSH_MSG_KEX_DH_GEX_REPLY:
                // 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.ReadInt();
                j = _buf.ReadByte();
                j = _buf.ReadByte();
                if (j != 33)
                {
                    Console.WriteLine("type: must be 33 " + j);
                    result = false;
                }

                K_S = _buf.ReadString();
                // 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.out.print("K_S: "); dump(K_S, 0, K_S.length);

                byte[] f        = _buf.ReadMPInt();
                byte[] sig_of_H = _buf.ReadString();

                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.WriteString(V_C); buf.WriteString(V_S);
                buf.WriteString(I_C); buf.WriteString(I_S);
                buf.WriteString(K_S);
                buf.WriteInt(min); buf.WriteInt(preferred); buf.WriteInt(max);
                buf.WriteMPInt(p); buf.WriteMPInt(g); buf.WriteMPInt(e); buf.WriteMPInt(f);
                buf.WriteMPInt(K);

                byte[] foo = new byte[buf.Length];
                buf.ReadByte(foo);
                sha.update(foo, 0, foo.Length);

                H = sha.digest();

                // System.out.print("H -> "); dump(H, 0, H.length);

                i = 0;
                j = 0;
                j = (int)((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) |
                    ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff);
                String alg = Util.getString(K_S, i, j);
                i += j;


                if (alg.Equals("ssh-rsa"))
                {
                    byte[] tmp;
                    byte[] ee;
                    byte[] n;

                    type = RSA;

                    j = (int)((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) |
                        ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff);
                    tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j;
                    ee  = tmp;
                    j   = (int)((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) |
                          ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff);
                    tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j;
                    n   = tmp;

                    //	SignatureRSA sig=new SignatureRSA();
                    //	sig.init();

                    SignatureRSA sig = null;
                    try
                    {
                        Type t = Type.GetType(session.getConfig("signature.rsa"));
                        sig = (SignatureRSA)(Activator.CreateInstance(t));
                        sig.init();
                    }
                    catch (Exception eee)
                    {
                        Console.WriteLine(eee);
                    }

                    sig.setPubKey(ee, n);
                    sig.update(H);
                    result = sig.verify(sig_of_H);
                }
                else if (alg.Equals("ssh-dss"))
                {
                    byte[] q = null;
                    byte[] tmp;

                    type = DSS;

                    j = (int)((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) |
                        ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff);
                    tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j;
                    p   = tmp;
                    j   = (int)((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) |
                          ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff);
                    tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j;
                    q   = tmp;
                    j   = (int)((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) |
                          ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff);
                    tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j;
                    g   = tmp;
                    j   = (int)((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) |
                          ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff);
                    tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j;
                    f   = tmp;

                    //	SignatureDSA sig=new SignatureDSA();
                    //	sig.init();

                    SignatureDSA sig = null;
                    try
                    {
                        Type t = Type.GetType(session.getConfig("signature.dss"));
                        sig = (SignatureDSA)(Activator.CreateInstance(t));
                        sig.init();
                    }
                    catch (Exception ee)
                    {
                        Console.WriteLine(ee);
                    }

                    sig.setPubKey(f, p, q, g);
                    sig.update(H);
                    result = sig.verify(sig_of_H);
                }
                else
                {
                    Console.WriteLine("unknow alg");
                }
                state = STATE_END;
                break;
            }
            return(result);
        }
Esempio n. 5
0
        internal IdentityFile(String identity, JSch jsch)
        {
            this.identity = identity;
            this.jsch     = jsch;
            try
            {
                Type c = Type.GetType(jsch.getConfig("3des-cbc"));
                cipher = (Cipher)Activator.CreateInstance(c);
                key    = new byte[cipher.getBlockSize()];              // 24
                iv     = new byte[cipher.getIVSize()];                 // 8
                c      = Type.GetType(jsch.getConfig("md5"));
                hash   = (HASH)(Activator.CreateInstance(c));
                hash.init();
                FileInfo   file = new FileInfo(identity);
                FileStream fis  = File.OpenRead(identity);
                byte[]     buf  = new byte[(int)(file.Length)];
                int        len  = fis.Read(buf, 0, buf.Length);
                fis.Close();

                int i = 0;
                while (i < len)
                {
                    if (buf[i] == 'B' && buf[i + 1] == 'E' && buf[i + 2] == 'G' && buf[i + 3] == 'I')
                    {
                        i += 6;
                        if (buf[i] == 'D' && buf[i + 1] == 'S' && buf[i + 2] == 'A')
                        {
                            type = DSS;
                        }
                        else if (buf[i] == 'R' && buf[i + 1] == 'S' && buf[i + 2] == 'A')
                        {
                            type = RSA;
                        }
                        else if (buf[i] == 'S' && buf[i + 1] == 'S' && buf[i + 2] == 'H')
                        {                         // FSecure
                            type    = UNKNOWN;
                            keytype = FSECURE;
                        }
                        else
                        {
                            //System.out.println("invalid format: "+identity);
                            throw new JSchException("invaid privatekey: " + identity);
                        }
                        i += 3;
                        continue;
                    }
                    if (buf[i] == 'C' && buf[i + 1] == 'B' && buf[i + 2] == 'C' && buf[i + 3] == ',')
                    {
                        i += 4;
                        for (int ii = 0; ii < iv.Length; ii++)
                        {
                            iv[ii] = (byte)(((a2b(buf[i++]) << 4) & 0xf0) +
                                            (a2b(buf[i++]) & 0xf));
                        }
                        continue;
                    }
                    if (buf[i] == 0x0d &&
                        i + 1 < buf.Length && buf[i + 1] == 0x0a)
                    {
                        i++;
                        continue;
                    }
                    if (buf[i] == 0x0a && i + 1 < buf.Length)
                    {
                        if (buf[i + 1] == 0x0a)
                        {
                            i += 2; break;
                        }
                        if (buf[i + 1] == 0x0d &&
                            i + 2 < buf.Length && buf[i + 2] == 0x0a)
                        {
                            i += 3; break;
                        }
                        bool inheader = false;
                        for (int j = i + 1; j < buf.Length; j++)
                        {
                            if (buf[j] == 0x0a)
                            {
                                break;
                            }
                            //if(buf[j]==0x0d) break;
                            if (buf[j] == ':')
                            {
                                inheader = true; break;
                            }
                        }
                        if (!inheader)
                        {
                            i++;
                            encrypted = false;                              // no passphrase
                            break;
                        }
                    }
                    i++;
                }

                if (type == ERROR)
                {
                    throw new JSchException("invaid privatekey: " + identity);
                }

                int start = i;
                while (i < len)
                {
                    if (buf[i] == 0x0a)
                    {
                        bool xd = (buf[i - 1] == 0x0d);
                        Array.Copy(buf, i + 1,
                                   buf,
                                   i - (xd ? 1 : 0),
                                   len - i - 1 - (xd ? 1 : 0)
                                   );
                        if (xd)
                        {
                            len--;
                        }
                        len--;
                        continue;
                    }
                    if (buf[i] == '-')
                    {
                        break;
                    }
                    i++;
                }
                encoded_data = Util.fromBase64(buf, start, i - start);

                if (encoded_data.Length > 4 &&                         // FSecure
                    encoded_data[0] == (byte)0x3f &&
                    encoded_data[1] == (byte)0x6f &&
                    encoded_data[2] == (byte)0xf9 &&
                    encoded_data[3] == (byte)0xeb)
                {
                    Buffer _buf = new Buffer(encoded_data);
                    _buf.ReadInt();                      // 0x3f6ff9be
                    _buf.ReadInt();
                    byte[] _type = _buf.ReadString();
                    //System.out.println("type: "+Encoding.UTF8.GetString(_type));
                    byte[] _cipher  = _buf.ReadString();
                    String s_cipher = System.Text.Encoding.Default.GetString(_cipher);
                    //System.out.println("cipher: "+cipher);
                    if (s_cipher.Equals("3des-cbc"))
                    {
                        _buf.ReadInt();
                        byte[] foo = new byte[encoded_data.Length - _buf.Offset];
                        _buf.ReadByte(foo);
                        encoded_data = foo;
                        encrypted    = true;
                        throw new JSchException("unknown privatekey format: " + identity);
                    }
                    else if (s_cipher.Equals("none"))
                    {
                        _buf.ReadInt();
                        //_buf.getInt();

                        encrypted = false;

                        byte[] foo = new byte[encoded_data.Length - _buf.Offset];
                        _buf.ReadByte(foo);
                        encoded_data = foo;
                    }
                }

                try
                {
                    file = new FileInfo(identity + ".pub");
                    fis  = File.OpenRead(identity + ".pub");
                    buf  = new byte[(int)(file.Length)];
                    len  = fis.Read(buf, 0, buf.Length);
                    fis.Close();
                }
                catch
                {
                    return;
                }

                if (buf.Length > 4 &&                          // FSecure's public key
                    buf[0] == '-' && buf[1] == '-' && buf[2] == '-' && buf[3] == '-')
                {
                    i = 0;
                    do
                    {
                        i++;
                    }while(buf.Length > i && buf[i] != 0x0a);
                    if (buf.Length <= i)
                    {
                        return;
                    }

                    while (true)
                    {
                        if (buf[i] == 0x0a)
                        {
                            bool inheader = false;
                            for (int j = i + 1; j < buf.Length; j++)
                            {
                                if (buf[j] == 0x0a)
                                {
                                    break;
                                }
                                if (buf[j] == ':')
                                {
                                    inheader = true; break;
                                }
                            }
                            if (!inheader)
                            {
                                i++;
                                break;
                            }
                        }
                        i++;
                    }
                    if (buf.Length <= i)
                    {
                        return;
                    }

                    start = i;
                    while (i < len)
                    {
                        if (buf[i] == 0x0a)
                        {
                            Array.Copy(buf, i + 1, buf, i, len - i - 1);
                            len--;
                            continue;
                        }
                        if (buf[i] == '-')
                        {
                            break;
                        }
                        i++;
                    }
                    publickeyblob = Util.fromBase64(buf, start, i - start);

                    if (type == UNKNOWN)
                    {
                        if (publickeyblob[8] == 'd')
                        {
                            type = DSS;
                        }
                        else if (publickeyblob[8] == 'r')
                        {
                            type = RSA;
                        }
                    }
                }
                else
                {
                    if (buf[0] != 's' || buf[1] != 's' || buf[2] != 'h' || buf[3] != '-')
                    {
                        return;
                    }
                    i = 0;
                    while (i < len)
                    {
                        if (buf[i] == ' ')
                        {
                            break;
                        }
                        i++;
                    }
                    i++;
                    if (i >= len)
                    {
                        return;
                    }
                    start = i;
                    while (i < len)
                    {
                        if (buf[i] == ' ')
                        {
                            break;
                        }
                        i++;
                    }
                    publickeyblob = Util.fromBase64(buf, start, i - start);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Identity: " + e);
                if (e is JSchException)
                {
                    throw (JSchException)e;
                }
                throw new JSchException(e.ToString());
            }
        }
Esempio n. 6
0
		public static KeyPair load(JSch jsch, String prvkey, String pubkey)
		{

			byte[] iv=new byte[8];       // 8
			bool encrypted=true;
			byte[] data=null;

			byte[] publickeyblob=null;

			int type=ERROR;
			int vendor=VENDOR_OPENSSH;

			try
			{
				//File file=new File(prvkey);
				FileStream fis=File.OpenRead(prvkey);
				byte[] buf=new byte[(int)(fis.Length)];
				int len=fis.Read(buf, 0, buf.Length);
				fis.Close();

				int i=0;

				while(i<len)
				{
					if(buf[i]=='B'&& buf[i+1]=='E'&& buf[i+2]=='G'&& buf[i+3]=='I')
					{
						i+=6;	    
						if(buf[i]=='D'&& buf[i+1]=='S'&& buf[i+2]=='A'){ type=DSA; }
						else if(buf[i]=='R'&& buf[i+1]=='S'&& buf[i+2]=='A'){ type=RSA; }
						else if(buf[i]=='S'&& buf[i+1]=='S'&& buf[i+2]=='H')
						{ // FSecure
							type=UNKNOWN;
							vendor=VENDOR_FSECURE;
						}
						else
						{
							//System.outs.println("invalid format: "+identity);
							throw new JSchException("invaid privatekey: "+prvkey);
						}
						i+=3;
						continue;
					}
					if(buf[i]=='C'&& buf[i+1]=='B'&& buf[i+2]=='C'&& buf[i+3]==',')
					{
						i+=4;
						for(int ii=0; ii<iv.Length; ii++)
						{
							iv[ii]=(byte)(((a2b(buf[i++])<<4)&0xf0)+(a2b(buf[i++])&0xf));
						}
						continue;
					}
					if(buf[i]==0x0d &&
						i+1<buf.Length && buf[i+1]==0x0a)
					{
						i++;
						continue;
					}
					if(buf[i]==0x0a && i+1<buf.Length)
					{
						if(buf[i+1]==0x0a){ i+=2; break; }
						if(buf[i+1]==0x0d &&
							i+2<buf.Length && buf[i+2]==0x0a)
						{
							i+=3; break;
						}
						bool inheader=false;
						for(int j=i+1; j<buf.Length; j++)
						{
							if(buf[j]==0x0a) break;
							//if(buf[j]==0x0d) break;
							if(buf[j]==':'){inheader=true; break;}
						}
						if(!inheader)
						{
							i++; 
							encrypted=false;    // no passphrase
							break;
						}
					}
					i++;
				}

				if(type==ERROR)
				{
					throw new JSchException("invaid privatekey: "+prvkey);
				}

				int start=i;
				while(i<len)
				{
					if(buf[i]==0x0a)
					{
						bool xd=(buf[i-1]==0x0d);
						Array.Copy(buf, i+1, 
							buf, 
							i-(xd ? 1 : 0), 
							len-i-1-(xd ? 1 : 0)
							);
						if(xd)len--;
						len--;
						continue;
					}
					if(buf[i]=='-'){  break; }
					i++;
				}
				data=Util.fromBase64(buf, start, i-start);

				if(data.Length>4 &&            // FSecure
					data[0]==(byte)0x3f &&
					data[1]==(byte)0x6f &&
					data[2]==(byte)0xf9 &&
					data[3]==(byte)0xeb)
				{

					Buffer _buf=new Buffer(data);
					_buf.ReadInt();  // 0x3f6ff9be
					_buf.ReadInt();
					byte[]_type=_buf.ReadString();
					//System.outs.println("type: "+Encoding.UTF8.GetString(_type)); 
					byte[] _cipher=_buf.ReadString();
					String cipher=Util.getString(_cipher);
					//System.outs.println("cipher: "+cipher); 
					if(cipher.Equals("3des-cbc"))
					{
						_buf.ReadInt();
						byte[] foo=new byte[data.Length-_buf.Offset];
						_buf.ReadByte(foo);
						data=foo;
						encrypted=true;
						throw new JSchException("unknown privatekey format: "+prvkey);
					}
					else if(cipher.Equals("none"))
					{
						_buf.ReadInt();
						_buf.ReadInt();

						encrypted=false;

						byte[] foo=new byte[data.Length-_buf.Offset];
						_buf.ReadByte(foo);
						data=foo;
					}
				}

				if(pubkey!=null)
				{
					try
					{
						//file=new File(pubkey);
						fis=File.OpenRead(pubkey);
						buf=new byte[(int)(fis.Length)];
						len=fis.Read(buf, 0, buf.Length);
						fis.Close();

						if(buf.Length>4 &&             // FSecure's public key
							buf[0]=='-' && buf[1]=='-' && buf[2]=='-' && buf[3]=='-')
						{

							bool valid=true;
							i=0;
							do{i++;}while(buf.Length>i && buf[i]!=0x0a);
							if(buf.Length<=i) {valid=false;}

							while(valid)
							{
								if(buf[i]==0x0a)
								{
									bool inheader=false;
									for(int j=i+1; j<buf.Length; j++)
									{
										if(buf[j]==0x0a) break;
										if(buf[j]==':'){inheader=true; break;}
									}
									if(!inheader)
									{
										i++; 
										break;
									}
								}
								i++;
							}
							if(buf.Length<=i){valid=false;}

							start=i;
							while(valid && i<len)
							{
								if(buf[i]==0x0a)
								{
									Array.Copy(buf, i+1, buf, i, len-i-1);
									len--;
									continue;
								}
								if(buf[i]=='-'){  break; }
								i++;
							}
							if(valid)
							{
								publickeyblob=Util.fromBase64(buf, start, i-start);
								if(type==UNKNOWN)
								{
									if(publickeyblob[8]=='d'){ type=DSA; }
									else if(publickeyblob[8]=='r'){ type=RSA; }
								}
							}
						}
						else
						{
							if(buf[0]=='s'&& buf[1]=='s'&& buf[2]=='h' && buf[3]=='-')
							{
								i=0;
								while(i<len){ if(buf[i]==' ')break; i++;} i++;
								if(i<len)
								{
									start=i;
									while(i<len){ if(buf[i]==' ')break; i++;}
									publickeyblob=Util.fromBase64(buf, start, i-start);
								}
							}
						}
					}
					catch//(Exception ee)
					{
					}
				}
			}
			catch(Exception e)
			{
				if(e is JSchException) throw (JSchException)e;
				throw new JSchException(e.ToString());
			}

			KeyPair kpair=null;
			if(type==DSA){ kpair=new KeyPairDSA(jsch); }
			else if(type==RSA){ kpair=new KeyPairRSA(jsch); }

			if(kpair!=null)
			{
				kpair.encrypted=encrypted;
				kpair.publickeyblob=publickeyblob;
				kpair.vendor=vendor;

				if(encrypted)
				{
					kpair.iv=iv;
					kpair.data=data;
				}
				else
				{
					if(kpair.parse(data))
					{
						return kpair;
					}
					else
					{
						throw new JSchException("invaid privatekey: "+prvkey);
					}
				}
			}

			return kpair;
		}
Esempio n. 7
0
		public override bool next(Buffer _buf) 
		{
			int i,j;
			bool result=false;
			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.ReadInt();
					_buf.ReadByte();
					j=_buf.ReadByte();
					if(j!=31)
					{
						Console.WriteLine("type: must be 31 "+j);
						result = false;
					}

					p=_buf.ReadMPInt();
					g=_buf.ReadMPInt();
					/*
			  for(int iii=0; iii<p.length; iii++){
			  System.out.println("0x"+Integer.toHexString(p[iii]&0xff)+",");
			  }
			  System.out.println("");
			  for(int iii=0; iii<g.length; iii++){
			  System.out.println("0x"+Integer.toHexString(g[iii]&0xff)+",");
			  }
					*/
					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.WriteByte((byte)0x20);
					buf.WriteMPInt(e);
					session.write(packet);

					state=SSH_MSG_KEX_DH_GEX_REPLY;
					result = true;
					break;

				case SSH_MSG_KEX_DH_GEX_REPLY:
					// 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.ReadInt();
					j=_buf.ReadByte();
					j=_buf.ReadByte();
					if(j!=33)
					{
						Console.WriteLine("type: must be 33 "+j);
						result = false;
					}

					K_S=_buf.ReadString();
					// 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.out.print("K_S: "); dump(K_S, 0, K_S.length);

					byte[] f=_buf.ReadMPInt();
					byte[] sig_of_H=_buf.ReadString();

					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.WriteString(V_C); buf.WriteString(V_S);
					buf.WriteString(I_C); buf.WriteString(I_S);
					buf.WriteString(K_S);
					buf.WriteInt(min); buf.WriteInt(preferred); buf.WriteInt(max);
					buf.WriteMPInt(p); buf.WriteMPInt(g); buf.WriteMPInt(e); buf.WriteMPInt(f);
					buf.WriteMPInt(K);

					byte[] foo=new byte[buf.Length];
					buf.ReadByte(foo);
					sha.update(foo, 0, foo.Length);

					H=sha.digest();

					// System.out.print("H -> "); dump(H, 0, H.length);

					i=0;
					j=0;
					j=(int)((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
						((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
					String alg=Util.getString(K_S, i, j);
					i+=j;

					
					if(alg.Equals("ssh-rsa"))
					{
						byte[] tmp;
						byte[] ee;
						byte[] n;
	
						type=RSA;

						j=(int)((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
							((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
						tmp=new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i+=j;
						ee=tmp;
						j=(int)((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
							((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
						tmp=new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i+=j;
						n=tmp;

						//	SignatureRSA sig=new SignatureRSA();
						//	sig.init();

						SignatureRSA sig=null;
						try
						{
							Type t=Type.GetType(session.getConfig("signature.rsa"));
							sig=(SignatureRSA)(Activator.CreateInstance(t));
							sig.init();
						}
						catch(Exception eee)
						{
							Console.WriteLine(eee);
						}

						sig.setPubKey(ee, n);   
						sig.update(H);
						result=sig.verify(sig_of_H);
					}
					else if(alg.Equals("ssh-dss"))
					{
						byte[] q=null;
						byte[] tmp;

						type=DSS;

						j=(int)((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
							((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
						tmp=new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i+=j;
						p=tmp;
						j=(int)((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
							((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
						tmp=new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i+=j;
						q=tmp;
						j=(int)((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
							((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
						tmp=new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i+=j;
						g=tmp;
						j=(int)((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
							((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
						tmp=new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i+=j;
						f=tmp;
	
						//	SignatureDSA sig=new SignatureDSA();
						//	sig.init();

						SignatureDSA sig=null;
						try
						{
							Type t=Type.GetType(session.getConfig("signature.dss"));
							sig=(SignatureDSA)(Activator.CreateInstance(t));
							sig.init();
						}
						catch(Exception ee)
						{
							Console.WriteLine(ee);
						}

						sig.setPubKey(f, p, q, g);   
						sig.update(H);
						result=sig.verify(sig_of_H);
					}
					else
					{
						Console.WriteLine("unknow alg");
					}	    
					state=STATE_END;
					break;
			}
			return result;
		}
Esempio n. 8
0
		/*
		void dump(byte[] foo){
		  for(int i=0; i<foo.length; i++){
			if((foo[i]&0xf0)==0)System.out.print("0");
			System.out.print(Integer.toHexString(foo[i]&0xff));
			if(i%16==15){System.out.println(""); continue;}
			if(i%2==1)System.out.print(" ");
		  }
		} 
		*/

		internal static String[] guess(byte[]I_S, byte[]I_C)
		{
			//System.out.println("guess: ");
			String[] guess=new String[PROPOSAL_MAX];
			Buffer sb=new Buffer(I_S); sb.Offset = 17;
			Buffer cb=new Buffer(I_C); cb.Offset = 17;

			for(int i=0; i<PROPOSAL_MAX; i++)
			{
				byte[] sp=sb.ReadString();  // server proposal
				byte[] cp=cb.ReadString();  // client proposal

				//System.out.println("server-proposal: |"+Encoding.UTF8.GetString(sp)+"|");
				//System.out.println("client-proposal: |"+Encoding.UTF8.GetString(cp)+"|");

				int j=0;
				int k=0;
				//System.out.println(Encoding.UTF8.GetString(cp));
			//loop(using BREAK instead):
				while(j<cp.Length)
				{
					while(j<cp.Length && cp[j]!=',')j++; 
					if(k==j) return null;
					String algorithm=Util.getString(cp, k, j-k);
					//System.out.println("algorithm: "+algorithm);
					int l=0;
					int m=0;
					while(l<sp.Length)
					{
						while(l<sp.Length && sp[l]!=',')l++; 
						if(m==l) return null;
						//System.out.println("  "+Encoding.UTF8.GetString(sp, m, l-m));
						if(algorithm.Equals(Util.getString(sp, m, l-m)))
						{
							guess[i]=algorithm;
							//System.out.println("  "+algorithm);
							goto BREAK;
						}
						l++;
						m=l;
					}	
					j++;
					k=j;
				}
			BREAK:
				if(j==0)
				{
					guess[i]="";
				}
				else if(guess[i]==null)
				{
					//System.out.println("  fail");
					return null;
				}
			}

			//    for(int i=0; i<PROPOSAL_MAX; i++){
			//      System.out.println("guess: ["+guess[i]+"]");
			//    }

			return guess;
		}
Esempio n. 9
0
		internal IdentityFile(String identity, JSch jsch) 
		{
			this.identity=identity;
			this.jsch=jsch;
			try
			{
				Type c=Type.GetType(jsch.getConfig("3des-cbc"));
				cipher=(Cipher)Activator.CreateInstance(c);
				key=new byte[cipher.getBlockSize()];   // 24
				iv=new byte[cipher.getIVSize()];       // 8
				c=Type.GetType(jsch.getConfig("md5"));
				hash=(HASH)(Activator.CreateInstance(c));
				hash.init();
				FileInfo file=new FileInfo(identity);
				FileStream fis = File.OpenRead(identity);
				byte[] buf=new byte[(int)(file.Length)];
				int len=fis.Read(buf, 0, buf.Length);
				fis.Close();

				int i=0;
				while(i<len)
				{
					if(buf[i]=='B'&& buf[i+1]=='E'&& buf[i+2]=='G'&& buf[i+3]=='I')
					{
						i+=6;	    
						if(buf[i]=='D'&& buf[i+1]=='S'&& buf[i+2]=='A'){ type=DSS; }
						else if(buf[i]=='R'&& buf[i+1]=='S'&& buf[i+2]=='A'){ type=RSA; }
						else if(buf[i]=='S'&& buf[i+1]=='S'&& buf[i+2]=='H')
						{ // FSecure
							type=UNKNOWN;
							keytype=FSECURE;
						}
						else
						{
							//System.out.println("invalid format: "+identity);
							throw new JSchException("invaid privatekey: "+identity);
						}
						i+=3;
						continue;
					}
					if(buf[i]=='C'&& buf[i+1]=='B'&& buf[i+2]=='C'&& buf[i+3]==',')
					{
						i+=4;
						for(int ii=0; ii<iv.Length; ii++)
						{
							iv[ii]=(byte)(((a2b(buf[i++])<<4)&0xf0)+
								(a2b(buf[i++])&0xf));
						}
						continue;
					}
					if(buf[i]==0x0d &&
						i+1<buf.Length && buf[i+1]==0x0a)
					{
						i++;
						continue;
					}
					if(buf[i]==0x0a && i+1<buf.Length)
					{
						if(buf[i+1]==0x0a){ i+=2; break; }
						if(buf[i+1]==0x0d &&
							i+2<buf.Length && buf[i+2]==0x0a)
						{
							i+=3; break;
						}
						bool inheader=false;
						for(int j=i+1; j<buf.Length; j++)
						{
							if(buf[j]==0x0a) break;
							//if(buf[j]==0x0d) break;
							if(buf[j]==':'){inheader=true; break;}
						}
						if(!inheader)
						{
							i++; 
							encrypted=false;    // no passphrase
							break;
						}
					}
					i++;
				}

				if(type==ERROR)
				{
					throw new JSchException("invaid privatekey: "+identity);
				}

				int start=i;
				while(i<len)
				{
					if(buf[i]==0x0a)
					{
						bool xd=(buf[i-1]==0x0d);
						Array.Copy(buf, i+1, 
							buf, 
							i-(xd ? 1 : 0), 
							len-i-1-(xd ? 1 : 0)
							);
						if(xd)len--;
						len--;
						continue;
					}
					if(buf[i]=='-'){  break; }
					i++;
				}
				encoded_data=Util.fromBase64(buf, start, i-start);

				if(encoded_data.Length>4 &&            // FSecure
					encoded_data[0]==(byte)0x3f &&
					encoded_data[1]==(byte)0x6f &&
					encoded_data[2]==(byte)0xf9 &&
					encoded_data[3]==(byte)0xeb)
				{

					Buffer _buf=new Buffer(encoded_data);
					_buf.ReadInt();  // 0x3f6ff9be
					_buf.ReadInt();
					byte[]_type=_buf.ReadString();
					//System.out.println("type: "+Encoding.UTF8.GetString(_type)); 
					byte[] _cipher=_buf.ReadString();
					String s_cipher=System.Text.Encoding.Default.GetString(_cipher);
					//System.out.println("cipher: "+cipher); 
					if(s_cipher.Equals("3des-cbc"))
					{
						_buf.ReadInt();
						byte[] foo=new byte[encoded_data.Length-_buf.Offset];
						_buf.ReadByte(foo);
						encoded_data=foo;
						encrypted=true;
						throw new JSchException("unknown privatekey format: "+identity);
					}
					else if(s_cipher.Equals("none"))
					{
						_buf.ReadInt();
						//_buf.getInt();

						encrypted=false;

						byte[] foo=new byte[encoded_data.Length-_buf.Offset];
						_buf.ReadByte(foo);
						encoded_data=foo;
					}

				}

				try
				{
					file=new FileInfo(identity+".pub");
					fis=File.OpenRead(identity+".pub");
					buf=new byte[(int)(file.Length)];
					len=fis.Read(buf, 0, buf.Length);
					fis.Close();
				}
				catch
				{
					return;
				}

				if(buf.Length>4 &&             // FSecure's public key
					buf[0]=='-' && buf[1]=='-' && buf[2]=='-' && buf[3]=='-')
				{

					i=0;
					do{i++;}while(buf.Length>i && buf[i]!=0x0a);
					if(buf.Length<=i) return;

					while(true)
					{
						if(buf[i]==0x0a)
						{
							bool inheader=false;
							for(int j=i+1; j<buf.Length; j++)
							{
								if(buf[j]==0x0a) break;
								if(buf[j]==':'){inheader=true; break;}
							}
							if(!inheader)
							{
								i++; 
								break;
							}
						}
						i++;
					}
					if(buf.Length<=i) return;

					start=i;
					while(i<len)
					{
						if(buf[i]==0x0a)
						{
							Array.Copy(buf, i+1, buf, i, len-i-1);
							len--;
							continue;
						}
						if(buf[i]=='-'){  break; }
						i++;
					}
					publickeyblob=Util.fromBase64(buf, start, i-start);

					if(type==UNKNOWN)
					{
						if(publickeyblob[8]=='d')
						{
							type=DSS;
						}
						else if(publickeyblob[8]=='r')
						{
							type=RSA;
						}
					}
				}
				else
				{
					if(buf[0]!='s'|| buf[1]!='s'|| buf[2]!='h'|| buf[3]!='-') return;
					i=0;
					while(i<len){ if(buf[i]==' ')break; i++;} i++;
					if(i>=len) return;
					start=i;
					while(i<len){ if(buf[i]==' ')break; i++;}
					publickeyblob=Util.fromBase64(buf, start, i-start);
				}

			}
			catch(Exception e)
			{
				Console.WriteLine("Identity: "+e);
				if(e is JSchException) throw (JSchException)e;
				throw new JSchException(e.ToString());
			}

		}
Esempio n. 10
0
        public override bool next(Buffer _buf)
        {
            int i,j;
            bool result = false;
            switch(state)
            {
                case SSH_MSG_KEXDH_REPLY:
                    // The server responds with:
                    // byte      SSH_MSG_KEXDH_REPLY(31)
                    // string    server public host key and certificates (K_S)
                    // mpint     f
                    // string    signature of H
                    j=_buf.ReadInt();
                    j=_buf.ReadByte();
                    j=_buf.ReadByte();
                    if(j!=31)
                    {
                        Console.WriteLine("type: must be 31 "+j);
                        result = false;
                        break;
                    }

                    K_S=_buf.ReadString();
                    // 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.out.print("K_S: "); //dump(K_S, 0, K_S.length);
                    byte[] f=_buf.ReadMPInt();
                    byte[] sig_of_H=_buf.ReadString();
                    /*
              for(int ii=0; ii<sig_of_H.length;ii++){
                System.out.print(Integer.toHexString(sig_of_H[ii]&0xff));
                System.out.print(": ");
              }
              Console.WriteLine("");
                    */

                    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
                    // 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.WriteString(V_C); buf.WriteString(V_S);
                    buf.WriteString(I_C); buf.WriteString(I_S);
                    buf.WriteString(K_S);
                    buf.WriteMPInt(e); buf.WriteMPInt(f);
                    buf.WriteMPInt(K);
                    byte[] foo=new byte[buf.Length];
                    buf.ReadByte(foo);
                    sha.update(foo, 0, foo.Length);
                    H=sha.digest();
                    //System.out.print("H -> "); //dump(H, 0, H.length);

                    i=0;
                    j=0;
                    j=(int)((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
                        ((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
                    String alg=Util.getString(K_S, i, j);
                    i+=j;

                    result=false;

                    if(alg.Equals("ssh-rsa"))
                    {
                        byte[] tmp;
                        byte[] ee;
                        byte[] n;

                        type=RSA;

                        j=(int)((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
                            ((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
                        tmp=new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i+=j;
                        ee=tmp;
                        j=(int)((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
                            ((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
                        tmp=new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i+=j;
                        n=tmp;

                        //	SignatureRSA sig=new SignatureRSA();
                        //	sig.init();

                        SignatureRSA sig=null;
                        try
                        {
                            Type t=Type.GetType(session.getConfig("signature.rsa"));
                            sig=(SignatureRSA)(Activator.CreateInstance(t));
                            sig.init();
                        }
                        catch(Exception eee)
                        {
                            Console.WriteLine(eee);
                        }

                        sig.setPubKey(ee, n);
                        sig.update(H);
                        result=sig.verify(sig_of_H);
                        //MainClass.dump(ee, n, sig_of_H, H);
                    }
                    else if(alg.Equals("ssh-dss"))
                    {
                        byte[] q=null;
                        byte[] tmp;
                        byte[] p;
                        byte[] g;

                        type=DSS;

                        j=(int)((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
                            ((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
                        tmp=new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i+=j;
                        p=tmp;
                        j=(int)((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
                            ((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
                        tmp=new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i+=j;
                        q=tmp;
                        j=(int)((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
                            ((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
                        tmp=new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i+=j;
                        g=tmp;
                        j=(int)((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
                            ((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
                        tmp=new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i+=j;
                        f=tmp;
                        //	SignatureDSA sig=new SignatureDSA();
                        //	sig.init();
                        SignatureDSA sig=null;
                        try
                        {
                            Type t=Type.GetType(session.getConfig("signature.dss"));
                            sig=(SignatureDSA)(Activator.CreateInstance(t));
                            sig.init();
                        }
                        catch(Exception ee)
                        {
                            Console.WriteLine(ee);
                        }
                        sig.setPubKey(f, p, q, g);
                        sig.update(H);
                        result=sig.verify(sig_of_H);
                    }
                    else
                    {
                        Console.WriteLine("unknow alg");
                    }
                    state=STATE_END;
                    break;
            }
            return result;
        }
Esempio n. 11
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.WriteByte((byte)Session.SSH_MSG_USERAUTH_REQUEST);
                buf.WriteString(_username);
                buf.WriteString(Util.getBytes("ssh-connection"));
                buf.WriteString(Util.getBytes("password"));
                buf.WriteByte((byte)0);
                buf.WriteString(_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.ReadInt(); buf.ReadByte(); buf.ReadByte();
                        byte[] _message = buf.ReadString();
                        byte[] lang     = buf.ReadString();
                        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.ReadInt(); buf.ReadByte(); buf.ReadByte();
                        byte[] foo             = buf.ReadString();
                        int    partial_success = buf.ReadByte();
                        //System.out.println(Encoding.UTF8.GetString(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;
        }
Esempio n. 12
0
		internal override void getData(Buffer buf)
		{
			setRecipient(buf.ReadInt());
			setRemoteWindowSize(buf.ReadInt());
			setRemotePacketSize(buf.ReadInt());
			byte[] addr=buf.ReadString();
			int port=buf.ReadInt();
			byte[] orgaddr=buf.ReadString();
			int orgport=buf.ReadInt();

			/*
			System.out.println("addr: "+Encoding.UTF8.GetString(addr));
			System.out.println("port: "+port);
			System.out.println("orgaddr: "+Encoding.UTF8.GetString(orgaddr));
			System.out.println("orgport: "+orgport);
			*/

			lock(pool)
			{
				for(int i=0; i<pool.Count; i++)
				{
					Object[] foo=(Object[])(pool[i]);
					if(foo[0]!=session) continue;
					if(((int)foo[1])!=port) continue;
					this.rport=port;
					this.target=(String)foo[2];
					if(foo[3]==null || (foo[3] is Object[])){ this.lport=-1; }
					else{ this.lport=(int)foo[3]; }
					if(foo.Length>=5)
					{
						this.factory=((SocketFactory)foo[4]);
					}
					break;
				}
				if(target==null)
				{
					Console.WriteLine("??");
				}
			}
		}
Esempio n. 13
0
        /*
         * void dump(byte[] foo){
         * for(int i=0; i<foo.length; i++){
         *      if((foo[i]&0xf0)==0)System.out.print("0");
         *      System.out.print(Integer.toHexString(foo[i]&0xff));
         *      if(i%16==15){System.out.println(""); continue;}
         *      if(i%2==1)System.out.print(" ");
         * }
         * }
         */

        internal static String[] guess(byte[] I_S, byte[] I_C)
        {
            //System.out.println("guess: ");
            String[] guess = new String[PROPOSAL_MAX];
            Buffer   sb    = new Buffer(I_S); sb.Offset = 17;
            Buffer   cb    = new Buffer(I_C); cb.Offset = 17;

            for (int i = 0; i < PROPOSAL_MAX; i++)
            {
                byte[] sp = sb.ReadString();                // server proposal
                byte[] cp = cb.ReadString();                // client proposal

                //System.out.println("server-proposal: |"+Encoding.UTF8.GetString(sp)+"|");
                //System.out.println("client-proposal: |"+Encoding.UTF8.GetString(cp)+"|");

                int j = 0;
                int k = 0;
                //System.out.println(Encoding.UTF8.GetString(cp));
                //loop(using BREAK instead):
                while (j < cp.Length)
                {
                    while (j < cp.Length && cp[j] != ',')
                    {
                        j++;
                    }
                    if (k == j)
                    {
                        return(null);
                    }
                    String algorithm = Util.getString(cp, k, j - k);
                    //System.out.println("algorithm: "+algorithm);
                    int l = 0;
                    int m = 0;
                    while (l < sp.Length)
                    {
                        while (l < sp.Length && sp[l] != ',')
                        {
                            l++;
                        }
                        if (m == l)
                        {
                            return(null);
                        }
                        //System.out.println("  "+Encoding.UTF8.GetString(sp, m, l-m));
                        if (algorithm.Equals(Util.getString(sp, m, l - m)))
                        {
                            guess[i] = algorithm;
                            //System.out.println("  "+algorithm);
                            goto BREAK;
                        }
                        l++;
                        m = l;
                    }
                    j++;
                    k = j;
                }
BREAK:
                if (j == 0)
                {
                    guess[i] = "";
                }
                else if (guess[i] == null)
                {
                    //System.out.println("  fail");
                    return(null);
                }
            }

            //    for(int i=0; i<PROPOSAL_MAX; i++){
            //      System.out.println("guess: ["+guess[i]+"]");
            //    }

            return(guess);
        }
Esempio n. 14
0
        public override bool start(Session session)
        {
            base.start(session);
            //System.out.println("UserAuthNone: start");
            Packet packet   = session.packet;
            Buffer buf      = session.buf;
            String username = session.username;

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

            // send
            // byte      SSH_MSG_USERAUTH_REQUEST(50)
            // string    user name
            // string    service name ("ssh-connection")
            // string    "none"
            packet.reset();
            buf.WriteByte((byte)Session.SSH_MSG_USERAUTH_REQUEST);
            buf.WriteString(_username);
            buf.WriteString(Util.getBytes("ssh-connection"));
            buf.WriteString(Util.getBytes("none"));
            session.write(packet);

loop:
            while (true)
            {
                // receive
                // byte      SSH_MSG_USERAUTH_SUCCESS(52)
                // string    service name
                buf = session.read(buf);
                //System.out.println("UserAuthNone: 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.ReadInt(); buf.ReadByte(); buf.ReadByte();
                    byte[] _message = buf.ReadString();
                    byte[] lang     = buf.ReadString();
                    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.ReadInt(); buf.ReadByte(); buf.ReadByte();
                    byte[] foo             = buf.ReadString();
                    int    partial_success = buf.ReadByte();
                    methods = Util.getString(foo);
                    //System.out.println("UserAuthNONE: "+methods+
                    //		   " partial_success:"+(partial_success!=0));
                    //	if(partial_success!=0){
                    //	  throw new JSchPartialAuthException(Encoding.UTF8.GetString(foo));
                    //	}
                    break;
                }
                else
                {
                    //      System.out.println("USERAUTH fail ("+buf.buffer[5]+")");
                    throw new JSchException("USERAUTH fail (" + buf.buffer[5] + ")");
                }
            }
            //throw new JSchException("USERAUTH fail");
            return(false);
        }
Esempio n. 15
0
 private void throwStatusError(Buffer buf, int i)
 {
     if (ServerVersion >= 3)
     {
         byte[] str = buf.ReadString();
         //byte[] tag=buf.getString();
         throw new SftpException(i, Encoding.UTF8.GetString(str));
     }
     else
     {
         throw new SftpException(i, "Failure");
     }
 }
Esempio n. 16
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 = ReadHeader(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
                ServerVersion = _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(".");

                // receive SSH_FXP_NAME
                _header = ReadHeader(buf, _header);
                length = _header.length;
                type = _header.type;            // 104 -> SSH_FXP_NAME
                buf.Rewind();
                fill(buf.buffer, 0, length);
                i = buf.ReadInt();              // count
                //System.Console.WriteLine("type="+type+", length="+length+", i="+i);
                str = buf.ReadString();         // filename
                //System.Console.WriteLine("str.length="+str.Length);
                home = cwd = Encoding.UTF8.GetString(str);
                str = buf.ReadString();         // logname
                //    SftpATTRS.getATTR(buf);      // attrs

                lcwd = System.IO.Path.GetFullPath(".");
            }
            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. 17
0
        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 (!result.SequenceEqual(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.ReadInt();buf.ReadShort();
                    int reason_code=buf.ReadInt();
                    byte[] description=buf.ReadString();
                    byte[] language_tag=buf.ReadString();
                    /*
                        System.Console.Error.WriteLine("SSH_MSG_DISCONNECT:"+
                                               " "+reason_code+
                                   " "+Encoding.UTF8.GetString(description)+
                                   " "+Encoding.UTF8.GetString(language_tag));
                    */
                    throw new JSchException(
                        "SSH_MSG_DISCONNECT:"+
                        " "+reason_code+
                        " "+description+
                        " "+language_tag);
                    //break;
                }
                else if(type==SSH_MSG_IGNORE)
                {
                }
                else if(type==SSH_MSG_DEBUG)
                {
                    buf.Rewind();
                    buf.ReadInt();buf.ReadShort();
                    /*
                        byte always_display=(byte)buf.getByte();
                        byte[] message=buf.getString();
                        byte[] language_tag=buf.getString();
                        System.Console.Error.WriteLine("SSH_MSG_DEBUG:"+
                                   " "+Encoding.UTF8.GetString(message)+
                                   " "+Encoding.UTF8.GetString(language_tag));
                    */
                }
                else if(type==SSH_MSG_CHANNEL_WINDOW_ADJUST)
                {
                    buf.Rewind();
                    buf.ReadInt();buf.ReadShort();
                    Channel c=Channel.getChannel(buf.ReadInt(), this);
                    if(c==null)
                    {
                    }
                    else
                    {
                        c.addRemoteWindowSize(buf.ReadInt());
                    }
                }
                else
                {
                    break;
                }
            }
            buf.Rewind();
            return buf;
        }
Esempio n. 18
0
        public override bool start(Session session)
        {
            //super.start(session);

            //Vector identities=JSch.identities;
            System.Collections.ArrayList identities = session.jsch.identities;

            Packet packet = session.packet;
            Buffer buf    = session.buf;

            String passphrase = null;
            String username   = session.username;

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

            for (int i = 0; i < identities.Count; i++)
            {
                Identity identity   = (Identity)(identities[i]);
                byte[]   pubkeyblob = identity.getPublicKeyBlob();

                //System.out.println("UserAuthPublicKey: "+identity+" "+pubkeyblob);

                if (pubkeyblob != null)
                {
                    // send
                    // byte      SSH_MSG_USERAUTH_REQUEST(50)
                    // string    user name
                    // string    service name ("ssh-connection")
                    // string    "publickey"
                    // boolen    FALSE
                    // string    plaintext password (ISO-10646 UTF-8)
                    packet.reset();
                    buf.WriteByte((byte)Session.SSH_MSG_USERAUTH_REQUEST);
                    buf.WriteString(_username);
                    buf.WriteString(Util.getBytes("ssh-connection"));
                    buf.WriteString(Util.getBytes("publickey"));
                    buf.WriteByte((byte)0);
                    buf.WriteString(Util.getBytes(identity.getAlgName()));
                    buf.WriteString(pubkeyblob);
                    session.write(packet);

loop1:
                    while (true)
                    {
                        // receive
                        // byte      SSH_MSG_USERAUTH_PK_OK(52)
                        // string    service name
                        buf = session.read(buf);
                        //System.out.println("read: 60 ? "+    buf.buffer[5]);
                        if (buf.buffer[5] == Session.SSH_MSG_USERAUTH_PK_OK)
                        {
                            break;
                        }
                        else if (buf.buffer[5] == Session.SSH_MSG_USERAUTH_FAILURE)
                        {
                            //	System.out.println("USERAUTH publickey "+session.getIdentity()+
                            //			   " is not acceptable.");
                            break;
                        }
                        else if (buf.buffer[5] == Session.SSH_MSG_USERAUTH_BANNER)
                        {
                            buf.ReadInt(); buf.ReadByte(); buf.ReadByte();
                            byte[] _message = buf.ReadString();
                            byte[] lang     = buf.ReadString();
                            String message  = null;
                            try{ message = Util.getStringUTF8(_message); }
                            catch
                            {                            //(java.io.UnsupportedEncodingException e){
                                message = Util.getString(_message);
                            }
                            if (userinfo != null)
                            {
                                userinfo.showMessage(message);
                            }
                            goto loop1;
                        }
                        else
                        {
                            //System.out.println("USERAUTH fail ("+buf.buffer[5]+")");
                            //throw new JSchException("USERAUTH fail ("+buf.buffer[5]+")");
                            break;
                        }
                    }
                    if (buf.buffer[5] != Session.SSH_MSG_USERAUTH_PK_OK)
                    {
                        continue;
                    }
                }

                //System.out.println("UserAuthPublicKey: identity.isEncrypted()="+identity.isEncrypted());

                int count = 5;
                while (true)
                {
                    if ((identity.isEncrypted() && passphrase == null))
                    {
                        if (userinfo == null)
                        {
                            throw new JSchException("USERAUTH fail");
                        }
                        if (identity.isEncrypted() &&
                            !userinfo.promptPassphrase("Passphrase for " + identity.getName()))
                        {
                            throw new JSchAuthCancelException("publickey");
                            //throw new JSchException("USERAUTH cancel");
                            //break;
                        }
                        passphrase = userinfo.getPassphrase();
                    }

                    if (!identity.isEncrypted() || passphrase != null)
                    {
                        //System.out.println("UserAuthPublicKey: @1 "+passphrase);
                        if (identity.setPassphrase(passphrase))
                        {
                            break;
                        }
                    }
                    passphrase = null;
                    count--;
                    if (count == 0)
                    {
                        break;
                    }
                }

                //System.out.println("UserAuthPublicKey: identity.isEncrypted()="+identity.isEncrypted());

                if (identity.isEncrypted())
                {
                    continue;
                }
                if (pubkeyblob == null)
                {
                    pubkeyblob = identity.getPublicKeyBlob();
                }

                //System.out.println("UserAuthPublicKey: pubkeyblob="+pubkeyblob);

                if (pubkeyblob == null)
                {
                    continue;
                }

                // send
                // byte      SSH_MSG_USERAUTH_REQUEST(50)
                // string    user name
                // string    service name ("ssh-connection")
                // string    "publickey"
                // boolen    TRUE
                // string    plaintext password (ISO-10646 UTF-8)
                packet.reset();
                buf.WriteByte((byte)Session.SSH_MSG_USERAUTH_REQUEST);
                buf.WriteString(_username);
                buf.WriteString(Util.getBytes("ssh-connection"));
                buf.WriteString(Util.getBytes("publickey"));
                buf.WriteByte((byte)1);
                buf.WriteString(Util.getBytes(identity.getAlgName()));
                buf.WriteString(pubkeyblob);

                //      byte[] tmp=new byte[buf.index-5];
                //      System.arraycopy(buf.buffer, 5, tmp, 0, tmp.length);
                //      buf.putString(signature);

                byte[] sid    = session.getSessionId();
                uint   sidlen = (uint)sid.Length;
                byte[] tmp    = new byte[4 + sidlen + buf.index - 5];
                tmp[0] = (byte)(sidlen >> 24);
                tmp[1] = (byte)(sidlen >> 16);
                tmp[2] = (byte)(sidlen >> 8);
                tmp[3] = (byte)(sidlen);
                Array.Copy(sid, 0, tmp, 4, sidlen);
                Array.Copy(buf.buffer, 5, tmp, 4 + sidlen, buf.index - 5);

                byte[] signature = identity.getSignature(session, tmp);
                if (signature == null)
                {                  // for example, too long key length.
                    break;
                }
                buf.WriteString(signature);

                session.write(packet);

loop2:
                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);
                    }
                    else if (buf.buffer[5] == Session.SSH_MSG_USERAUTH_BANNER)
                    {
                        buf.ReadInt(); buf.ReadByte(); buf.ReadByte();
                        byte[] _message = buf.ReadString();
                        byte[] lang     = buf.ReadString();
                        String message  = null;
                        try{ message = Util.getStringUTF8(_message); }
                        catch
                        {                        //(java.io.UnsupportedEncodingException e){
                            message = Util.getString(_message);
                        }
                        if (userinfo != null)
                        {
                            userinfo.showMessage(message);
                        }
                        goto loop2;
                    }
                    else if (buf.buffer[5] == Session.SSH_MSG_USERAUTH_FAILURE)
                    {
                        buf.ReadInt(); buf.ReadByte(); buf.ReadByte();
                        byte[] foo             = buf.ReadString();
                        int    partial_success = buf.ReadByte();
                        //System.out.println(Encoding.UTF8.GetString(foo)+
                        //                   " partial_success:"+(partial_success!=0));
                        if (partial_success != 0)
                        {
                            throw new JSchPartialAuthException(Util.getString(foo));
                        }
                        break;
                    }
                    //System.out.println("USERAUTH fail ("+buf.buffer[5]+")");
                    //throw new JSchException("USERAUTH fail ("+buf.buffer[5]+")");
                    break;
                }
            }
            return(false);
        }
Esempio n. 19
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.ReadInt();
                            buf.ReadByte();
                            buf.ReadByte();
                            i=buf.ReadInt();
                            channel=Channel.getChannel(i, this);
                            foo=buf.ReadString(start, length);
                            if(channel==null)
                            {
                                break;
                            }
                            try
                            {
                                channel.write(foo, start[0], length[0]);
                            }
                            catch(Exception)
                            {
                                //System.Console.WriteLine(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.WriteByte((byte)SSH_MSG_CHANNEL_WINDOW_ADJUST);
                                buf.WriteInt(channel.getRecipient());
                                buf.WriteInt(channel.lwsize_max-channel.lwsize);
                                write(packet);
                                channel.setLocalWindowSize(channel.lwsize_max);
                            }
                            break;

                        case SSH_MSG_CHANNEL_EXTENDED_DATA:
                            buf.ReadInt();
                            buf.ReadShort();
                            i=buf.ReadInt();
                            channel=Channel.getChannel(i, this);
                            buf.ReadInt();                   // data_type_code == 1
                            foo=buf.ReadString(start, length);
                            //System.Console.WriteLine("stderr: "+Encoding.UTF8.GetString(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.WriteByte((byte)SSH_MSG_CHANNEL_WINDOW_ADJUST);
                                buf.WriteInt(channel.getRecipient());
                                buf.WriteInt(channel.lwsize_max-channel.lwsize);
                                write(packet);
                                channel.setLocalWindowSize(channel.lwsize_max);
                            }
                            break;

                        case SSH_MSG_CHANNEL_WINDOW_ADJUST:
                            buf.ReadInt();
                            buf.ReadShort();
                            i=buf.ReadInt();
                            channel=Channel.getChannel(i, this);
                            if(channel==null)
                            {
                                break;
                            }
                            channel.addRemoteWindowSize(buf.ReadInt());
                            break;

                        case SSH_MSG_CHANNEL_EOF:
                            buf.ReadInt();
                            buf.ReadShort();
                            i=buf.ReadInt();
                            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.ReadInt();
                            buf.ReadShort();
                            i=buf.ReadInt();
                            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.ReadInt();
                            buf.ReadShort();
                            i=buf.ReadInt();
                            channel=Channel.getChannel(i, this);
                            if(channel==null)
                            {
                                //break;
                            }
                            channel.setRecipient(buf.ReadInt());
                            channel.setRemoteWindowSize(buf.ReadInt());
                            channel.setRemotePacketSize(buf.ReadInt());
                            break;
                        case SSH_MSG_CHANNEL_OPEN_FAILURE:
                            buf.ReadInt();
                            buf.ReadShort();
                            i=buf.ReadInt();
                            channel=Channel.getChannel(i, this);
                            if(channel==null)
                            {
                                //break;
                            }
                            int reason_code=buf.ReadInt();
                            //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.ReadInt();
                            buf.ReadShort();
                            i=buf.ReadInt();
                            foo=buf.ReadString();
                            bool reply=(buf.ReadByte()!=0);
                            channel=Channel.getChannel(i, this);
                            if(channel!=null)
                            {
                                byte reply_type=(byte)SSH_MSG_CHANNEL_FAILURE;
                                if((Encoding.UTF8.GetString(foo)) == "exit-status")
                                {
                                    i=buf.ReadInt();             // 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.WriteByte(reply_type);
                                    buf.WriteInt(channel.getRecipient());
                                    write(packet);
                                }
                            }
                            else
                            {
                            }
                            break;
                        case SSH_MSG_CHANNEL_OPEN:
                            buf.ReadInt();
                            buf.ReadShort();
                            foo=buf.ReadString();
                            String ctyp=Encoding.UTF8.GetString(foo);
                            //System.Console.WriteLine("type="+ctyp);
                            if(!("forwarded-tcpip" == ctyp) && !("x11" == 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.WriteByte((byte)SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                                buf.WriteInt(channel.getRecipient());
                                buf.WriteInt(channel.id);
                                buf.WriteInt(channel.lwsize);
                                buf.WriteInt(channel.lmpsize);
                                write(packet);
                                System.Threading.Thread tmp = new System.Threading.Thread(channel.run);
                                tmp.Name = "Channel "+ctyp+" "+host;
                                tmp.Start();
                                break;
                            }
                        case SSH_MSG_CHANNEL_SUCCESS:
                            buf.ReadInt();
                            buf.ReadShort();
                            i=buf.ReadInt();
                            channel=Channel.getChannel(i, this);
                            if(channel==null)
                            {
                                break;
                            }
                            channel.reply=1;
                            break;
                        case SSH_MSG_CHANNEL_FAILURE:
                            buf.ReadInt();
                            buf.ReadShort();
                            i=buf.ReadInt();
                            channel=Channel.getChannel(i, this);
                            if(channel==null)
                            {
                                break;
                            }
                            channel.reply=0;
                            break;
                        case SSH_MSG_GLOBAL_REQUEST:
                            buf.ReadInt();
                            buf.ReadShort();
                            foo=buf.ReadString();       // request name
                            reply=(buf.ReadByte()!=0);
                            if(reply)
                            {
                                packet.reset();
                                buf.WriteByte((byte)SSH_MSG_REQUEST_FAILURE);
                                write(packet);
                            }
                            break;
                        case SSH_MSG_REQUEST_FAILURE:
                        case SSH_MSG_REQUEST_SUCCESS:
                            System.Threading.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)
            {
                //System.Console.WriteLine("# Session.run");
                //e.printStackTrace();
            }
            try
            {
                disconnect();
            }
            catch(NullReferenceException)
            {
                //System.Console.WriteLine("@1");
                //e.printStackTrace();
            }
            catch(Exception)
            {
                //System.Console.WriteLine("@2");
                //e.printStackTrace();
            }
            _isConnected=false;
        }
Esempio n. 20
0
 internal static SftpATTRS getATTR(Buffer buf)
 {
     SftpATTRS attr = new SftpATTRS();
     attr.Flags = buf.ReadInt();
     if ((attr.Flags & SSH_FILEXFER_ATTR_SIZE) != 0) { attr._Size = buf.ReadLong(); }
     if ((attr.Flags & SSH_FILEXFER_ATTR_UIDGID) != 0)
     {
         attr.uid = buf.ReadInt(); attr.gid = buf.ReadInt();
     }
     if ((attr.Flags & SSH_FILEXFER_ATTR_PERMISSIONS) != 0)
     {
         attr._Permissions = (PermissionFlags)buf.ReadInt();
     }
     if ((attr.Flags & SSH_FILEXFER_ATTR_ACMODTIME) != 0)
     {
         attr.AccessTime = buf.ReadInt();
     }
     if ((attr.Flags & SSH_FILEXFER_ATTR_ACMODTIME) != 0)
     {
         attr.ModificationTime = buf.ReadInt();
     }
     if ((attr.Flags & SSH_FILEXFER_ATTR_EXTENDED) != 0)
     {
         int count = buf.ReadInt();
         if (count > 0)
         {
             attr.extended = new String[count * 2];
             for (int i = 0; i < count; i++)
             {
                 attr.extended[i * 2] = Util.getString(buf.ReadString());
                 attr.extended[i * 2 + 1] = Util.getString(buf.ReadString());
             }
         }
     }
     return attr;
 }
Esempio n. 21
0
        public override bool next(Buffer _buf)
        {
            int  i, j;
            bool result = false;

            switch (state)
            {
            case SSH_MSG_KEXDH_REPLY:
                // The server responds with:
                // byte      SSH_MSG_KEXDH_REPLY(31)
                // string    server public host key and certificates (K_S)
                // mpint     f
                // string    signature of H
                j = _buf.ReadInt();
                j = _buf.ReadByte();
                j = _buf.ReadByte();
                if (j != 31)
                {
                    Console.WriteLine("type: must be 31 " + j);
                    result = false;
                    break;
                }

                K_S = _buf.ReadString();
                // 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.out.print("K_S: "); //dump(K_S, 0, K_S.length);
                byte[] f        = _buf.ReadMPInt();
                byte[] sig_of_H = _buf.ReadString();

                /*
                 * for(int ii=0; ii<sig_of_H.length;ii++){
                 * System.out.print(Integer.toHexString(sig_of_H[ii]&0xff));
                 * System.out.print(": ");
                 * }
                 * Console.WriteLine("");
                 */

                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
                // 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.WriteString(V_C); buf.WriteString(V_S);
                buf.WriteString(I_C); buf.WriteString(I_S);
                buf.WriteString(K_S);
                buf.WriteMPInt(e); buf.WriteMPInt(f);
                buf.WriteMPInt(K);
                byte[] foo = new byte[buf.Length];
                buf.ReadByte(foo);
                sha.update(foo, 0, foo.Length);
                H = sha.digest();
                //System.out.print("H -> "); //dump(H, 0, H.length);

                i = 0;
                j = 0;
                j = (int)((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) |
                    ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff);
                String alg = Util.getString(K_S, i, j);
                i += j;

                result = false;

                if (alg.Equals("ssh-rsa"))
                {
                    byte[] tmp;
                    byte[] ee;
                    byte[] n;

                    type = RSA;

                    j = (int)((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) |
                        ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff);
                    tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j;
                    ee  = tmp;
                    j   = (int)((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) |
                          ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff);
                    tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j;
                    n   = tmp;

                    //	SignatureRSA sig=new SignatureRSA();
                    //	sig.init();

                    SignatureRSA sig = null;
                    try
                    {
                        Type t = Type.GetType(session.getConfig("signature.rsa"));
                        sig = (SignatureRSA)(Activator.CreateInstance(t));
                        sig.init();
                    }
                    catch (Exception eee)
                    {
                        Console.WriteLine(eee);
                    }

                    sig.setPubKey(ee, n);
                    sig.update(H);
                    result = sig.verify(sig_of_H);
                    //MainClass.dump(ee, n, sig_of_H, H);
                }
                else if (alg.Equals("ssh-dss"))
                {
                    byte[] q = null;
                    byte[] tmp;
                    byte[] p;
                    byte[] g;

                    type = DSS;

                    j = (int)((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) |
                        ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff);
                    tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j;
                    p   = tmp;
                    j   = (int)((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) |
                          ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff);
                    tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j;
                    q   = tmp;
                    j   = (int)((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) |
                          ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff);
                    tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j;
                    g   = tmp;
                    j   = (int)((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) |
                          ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff);
                    tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j;
                    f   = tmp;
                    //	SignatureDSA sig=new SignatureDSA();
                    //	sig.init();
                    SignatureDSA sig = null;
                    try
                    {
                        Type t = Type.GetType(session.getConfig("signature.dss"));
                        sig = (SignatureDSA)(Activator.CreateInstance(t));
                        sig.init();
                    }
                    catch (Exception ee)
                    {
                        Console.WriteLine(ee);
                    }
                    sig.setPubKey(f, p, q, g);
                    sig.update(H);
                    result = sig.verify(sig_of_H);
                }
                else
                {
                    Console.WriteLine("unknow alg");
                }
                state = STATE_END;
                break;
            }
            return(result);
        }
Esempio n. 22
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 = ReadHeader(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
                ServerVersion = _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(".");

                // receive SSH_FXP_NAME
                _header = ReadHeader(buf, _header);
                length  = _header.length;
                type    = _header.type;         // 104 -> SSH_FXP_NAME
                buf.Rewind();
                fill(buf.buffer, 0, length);
                i = buf.ReadInt();              // count
                //System.Console.WriteLine("type="+type+", length="+length+", i="+i);
                str = buf.ReadString();         // filename
                //System.Console.WriteLine("str.length="+str.Length);
                home = cwd = Encoding.UTF8.GetString(str);
                str  = buf.ReadString();        // logname
                //    SftpATTRS.getATTR(buf);      // attrs

                lcwd = System.IO.Path.GetFullPath(".");
            }
            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. 23
0
        public static KeyPair load(JSch jsch, String prvkey, String pubkey)
        {
            byte[] iv        = new byte[8];          // 8
            bool   encrypted = true;

            byte[] data = null;

            byte[] publickeyblob = null;

            int type   = ERROR;
            int vendor = VENDOR_OPENSSH;

            try
            {
                //File file=new File(prvkey);
                FileStream fis = File.OpenRead(prvkey);
                byte[]     buf = new byte[(int)(fis.Length)];
                int        len = fis.Read(buf, 0, buf.Length);
                fis.Close();

                int i = 0;

                while (i < len)
                {
                    if (buf[i] == 'B' && buf[i + 1] == 'E' && buf[i + 2] == 'G' && buf[i + 3] == 'I')
                    {
                        i += 6;
                        if (buf[i] == 'D' && buf[i + 1] == 'S' && buf[i + 2] == 'A')
                        {
                            type = DSA;
                        }
                        else if (buf[i] == 'R' && buf[i + 1] == 'S' && buf[i + 2] == 'A')
                        {
                            type = RSA;
                        }
                        else if (buf[i] == 'S' && buf[i + 1] == 'S' && buf[i + 2] == 'H')
                        {                         // FSecure
                            type   = UNKNOWN;
                            vendor = VENDOR_FSECURE;
                        }
                        else
                        {
                            //System.outs.println("invalid format: "+identity);
                            throw new JSchException("invaid privatekey: " + prvkey);
                        }
                        i += 3;
                        continue;
                    }
                    if (buf[i] == 'C' && buf[i + 1] == 'B' && buf[i + 2] == 'C' && buf[i + 3] == ',')
                    {
                        i += 4;
                        for (int ii = 0; ii < iv.Length; ii++)
                        {
                            iv[ii] = (byte)(((a2b(buf[i++]) << 4) & 0xf0) + (a2b(buf[i++]) & 0xf));
                        }
                        continue;
                    }
                    if (buf[i] == 0x0d &&
                        i + 1 < buf.Length && buf[i + 1] == 0x0a)
                    {
                        i++;
                        continue;
                    }
                    if (buf[i] == 0x0a && i + 1 < buf.Length)
                    {
                        if (buf[i + 1] == 0x0a)
                        {
                            i += 2; break;
                        }
                        if (buf[i + 1] == 0x0d &&
                            i + 2 < buf.Length && buf[i + 2] == 0x0a)
                        {
                            i += 3; break;
                        }
                        bool inheader = false;
                        for (int j = i + 1; j < buf.Length; j++)
                        {
                            if (buf[j] == 0x0a)
                            {
                                break;
                            }
                            //if(buf[j]==0x0d) break;
                            if (buf[j] == ':')
                            {
                                inheader = true; break;
                            }
                        }
                        if (!inheader)
                        {
                            i++;
                            encrypted = false;                              // no passphrase
                            break;
                        }
                    }
                    i++;
                }

                if (type == ERROR)
                {
                    throw new JSchException("invaid privatekey: " + prvkey);
                }

                int start = i;
                while (i < len)
                {
                    if (buf[i] == 0x0a)
                    {
                        bool xd = (buf[i - 1] == 0x0d);
                        Array.Copy(buf, i + 1,
                                   buf,
                                   i - (xd ? 1 : 0),
                                   len - i - 1 - (xd ? 1 : 0)
                                   );
                        if (xd)
                        {
                            len--;
                        }
                        len--;
                        continue;
                    }
                    if (buf[i] == '-')
                    {
                        break;
                    }
                    i++;
                }
                data = Util.fromBase64(buf, start, i - start);

                if (data.Length > 4 &&                         // FSecure
                    data[0] == (byte)0x3f &&
                    data[1] == (byte)0x6f &&
                    data[2] == (byte)0xf9 &&
                    data[3] == (byte)0xeb)
                {
                    Buffer _buf = new Buffer(data);
                    _buf.ReadInt();                      // 0x3f6ff9be
                    _buf.ReadInt();
                    byte[] _type = _buf.ReadString();
                    //System.outs.println("type: "+Encoding.UTF8.GetString(_type));
                    byte[] _cipher = _buf.ReadString();
                    String cipher  = Util.getString(_cipher);
                    //System.outs.println("cipher: "+cipher);
                    if (cipher.Equals("3des-cbc"))
                    {
                        _buf.ReadInt();
                        byte[] foo = new byte[data.Length - _buf.Offset];
                        _buf.ReadByte(foo);
                        data      = foo;
                        encrypted = true;
                        throw new JSchException("unknown privatekey format: " + prvkey);
                    }
                    else if (cipher.Equals("none"))
                    {
                        _buf.ReadInt();
                        _buf.ReadInt();

                        encrypted = false;

                        byte[] foo = new byte[data.Length - _buf.Offset];
                        _buf.ReadByte(foo);
                        data = foo;
                    }
                }

                if (pubkey != null)
                {
                    try
                    {
                        //file=new File(pubkey);
                        fis = File.OpenRead(pubkey);
                        buf = new byte[(int)(fis.Length)];
                        len = fis.Read(buf, 0, buf.Length);
                        fis.Close();

                        if (buf.Length > 4 &&                                  // FSecure's public key
                            buf[0] == '-' && buf[1] == '-' && buf[2] == '-' && buf[3] == '-')
                        {
                            bool valid = true;
                            i = 0;
                            do
                            {
                                i++;
                            }while(buf.Length > i && buf[i] != 0x0a);
                            if (buf.Length <= i)
                            {
                                valid = false;
                            }

                            while (valid)
                            {
                                if (buf[i] == 0x0a)
                                {
                                    bool inheader = false;
                                    for (int j = i + 1; j < buf.Length; j++)
                                    {
                                        if (buf[j] == 0x0a)
                                        {
                                            break;
                                        }
                                        if (buf[j] == ':')
                                        {
                                            inheader = true; break;
                                        }
                                    }
                                    if (!inheader)
                                    {
                                        i++;
                                        break;
                                    }
                                }
                                i++;
                            }
                            if (buf.Length <= i)
                            {
                                valid = false;
                            }

                            start = i;
                            while (valid && i < len)
                            {
                                if (buf[i] == 0x0a)
                                {
                                    Array.Copy(buf, i + 1, buf, i, len - i - 1);
                                    len--;
                                    continue;
                                }
                                if (buf[i] == '-')
                                {
                                    break;
                                }
                                i++;
                            }
                            if (valid)
                            {
                                publickeyblob = Util.fromBase64(buf, start, i - start);
                                if (type == UNKNOWN)
                                {
                                    if (publickeyblob[8] == 'd')
                                    {
                                        type = DSA;
                                    }
                                    else if (publickeyblob[8] == 'r')
                                    {
                                        type = RSA;
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (buf[0] == 's' && buf[1] == 's' && buf[2] == 'h' && buf[3] == '-')
                            {
                                i = 0;
                                while (i < len)
                                {
                                    if (buf[i] == ' ')
                                    {
                                        break;
                                    }
                                    i++;
                                }
                                i++;
                                if (i < len)
                                {
                                    start = i;
                                    while (i < len)
                                    {
                                        if (buf[i] == ' ')
                                        {
                                            break;
                                        }
                                        i++;
                                    }
                                    publickeyblob = Util.fromBase64(buf, start, i - start);
                                }
                            }
                        }
                    }
                    catch                    //(Exception ee)
                    {
                    }
                }
            }
            catch (Exception e)
            {
                if (e is JSchException)
                {
                    throw (JSchException)e;
                }
                throw new JSchException(e.ToString());
            }

            KeyPair kpair = null;

            if (type == DSA)
            {
                kpair = new KeyPairDSA(jsch);
            }
            else if (type == RSA)
            {
                kpair = new KeyPairRSA(jsch);
            }

            if (kpair != null)
            {
                kpair.encrypted     = encrypted;
                kpair.publickeyblob = publickeyblob;
                kpair.vendor        = vendor;

                if (encrypted)
                {
                    kpair.iv   = iv;
                    kpair.data = data;
                }
                else
                {
                    if (kpair.parse(data))
                    {
                        return(kpair);
                    }
                    else
                    {
                        throw new JSchException("invaid privatekey: " + prvkey);
                    }
                }
            }

            return(kpair);
        }
        public override bool start(Session session)
        {
//System.out.println("UserAuthKeyboardInteractive: start");
            Packet packet   = session.packet;
            Buffer buf      = session.buf;
            String username = session.username;
            String dest     = username + "@" + session.host;

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

            bool cancel = false;

            byte[] _username = null;
            try{ _username = System.Text.Encoding.UTF8.GetBytes(username); }
            catch {
                _username = Util.getBytes(username);
            }

            while (true)
            {
                // send
                // byte      SSH_MSG_USERAUTH_REQUEST(50)
                // string    user name (ISO-10646 UTF-8, as defined in [RFC-2279])
                // string    service name (US-ASCII) "ssh-userauth" ? "ssh-connection"
                // string    "keyboard-interactive" (US-ASCII)
                // string    language tag (as defined in [RFC-3066])
                // string    submethods (ISO-10646 UTF-8)
                packet.reset();
                buf.WriteByte((byte)Session.SSH_MSG_USERAUTH_REQUEST);
                buf.WriteString(_username);
                buf.WriteString(Util.getBytes("ssh-connection"));
                //buf.putString("ssh-userauth".getBytes());
                buf.WriteString(Util.getBytes("keyboard-interactive"));
                buf.WriteString(Util.getBytes(""));
                buf.WriteString(Util.getBytes(""));
                session.write(packet);

                bool firsttime = true;
loop:
                while (true)
                {
                    // receive
                    // byte      SSH_MSG_USERAUTH_SUCCESS(52)
                    // string    service name
                    try{ buf = session.read(buf); }
                    catch (JSchException e) {
                        e.GetType();
                        return(false);
                    }
                    catch (System.IO.IOException e) {
                        e.GetType();
                        return(false);
                    }
                    //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.ReadInt(); buf.ReadByte(); buf.ReadByte();
                        byte[] _message = buf.ReadString();
                        byte[] lang     = buf.ReadString();
                        String message  = null;
                        try{ message = Util.getStringUTF8(_message); }
                        catch {
                            message = Util.getString(_message);
                        }
                        if (userinfo != null)
                        {
                            userinfo.showMessage(message);
                        }
                        goto loop;
                    }
                    if (buf.buffer[5] == Session.SSH_MSG_USERAUTH_FAILURE)
                    {
                        buf.ReadInt(); buf.ReadByte(); buf.ReadByte();
                        byte[] foo             = buf.ReadString();
                        int    partial_success = buf.ReadByte();
//	  System.out.println(Encoding.UTF8.GetString(foo)+
//			     " partial_success:"+(partial_success!=0));

                        if (partial_success != 0)
                        {
                            throw new JSchPartialAuthException(Util.getString(foo));
                        }

                        if (firsttime)
                        {
                            throw new JSchException("USERAUTH KI is not supported");
                            //return false;
                            //cancel=true;  // ??
                        }
                        break;
                    }
                    if (buf.buffer[5] == Session.SSH_MSG_USERAUTH_INFO_REQUEST)
                    {
                        firsttime = false;
                        buf.ReadInt(); buf.ReadByte(); buf.ReadByte();
                        String name         = Util.getString(buf.ReadString());
                        String instruction  = Util.getString(buf.ReadString());
                        String languate_tag = Util.getString(buf.ReadString());
                        int    num          = buf.ReadInt();
//System.out.println("name: "+name);
//System.out.println("instruction: "+instruction);
//System.out.println("lang: "+languate_tag);
//System.out.println("num: "+num);
                        String[] prompt = new String[num];
                        bool[]   echo   = new bool[num];
                        for (int i = 0; i < num; i++)
                        {
                            prompt[i] = Util.getString(buf.ReadString());
                            echo[i]   = (buf.ReadByte() != 0);
//System.out.println("  "+prompt[i]+","+echo[i]);
                        }

                        String[] response = null;
                        if (num > 0 ||
                            (name.Length > 0 || instruction.Length > 0)
                            )
                        {
                            UIKeyboardInteractive kbi = (UIKeyboardInteractive)userinfo;
                            if (userinfo != null)
                            {
                                response = kbi.promptKeyboardInteractive(dest,
                                                                         name,
                                                                         instruction,
                                                                         prompt,
                                                                         echo);
                            }
                        }
                        // byte      SSH_MSG_USERAUTH_INFO_RESPONSE(61)
                        // int       num-responses
                        // string    response[1] (ISO-10646 UTF-8)
                        // ...
                        // string    response[num-responses] (ISO-10646 UTF-8)
//if(response!=null)
//System.out.println("response.length="+response.length);
//else
//System.out.println("response is null");
                        packet.reset();
                        buf.WriteByte((byte)Session.SSH_MSG_USERAUTH_INFO_RESPONSE);
                        if (num > 0 &&
                            (response == null || // cancel
                             num != response.Length))
                        {
                            buf.WriteInt(0);
                            if (response == null)
                            {
                                cancel = true;
                            }
                        }
                        else
                        {
                            buf.WriteInt(num);
                            for (int i = 0; i < num; i++)
                            {
//System.out.println("response: |"+response[i]+"| <- replace here with **** if you need");
                                buf.WriteString(Util.getBytes(response[i]));
                            }
                        }
                        session.write(packet);
                        if (cancel)
                        {
                            break;
                        }
//System.out.println("continue loop");
                        goto loop;
                    }
                    //throw new JSchException("USERAUTH fail ("+buf.buffer[5]+")");
                    return(false);
                }
                if (cancel)
                {
                    throw new JSchAuthCancelException("keyboard-interactive");
                    //break;
                }
            }
            //return false;
        }