Giter VIP home page Giter VIP logo

jsch's People

Contributors

alex-vol-amz avatar bmiddaugh avatar chklauser avatar dependabot[bot] avatar github-actions[bot] avatar kimmerin avatar mvegter avatar mwiede avatar norrisjeremy avatar shadelessfox avatar st-ddt avatar stsiano avatar turbanoff avatar wiedemam-vu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsch's Issues

Incompatibility with legacy jsch as used by jgit

I tried to replace the original jsch with this updated variant, but that caused an NPE.

CloneCommand cloneCommand = Git.cloneRepository()
                .setURI("[email protected]:mwiede/jsch.git")
                .setDirectory(new File("target/junit/clone-test));
assertDoesNotThrow(cloneCommand::call).close(); // <-- Error

This is caused by the following line: Source

JSch.setConfig("ssh-rsa", JSch.getConfig("signature.rsa"));
JSch.setConfig("ssh-dss", JSch.getConfig("signature.dss"));

In the original jsch version this was set to:

config.put("signature.rsa", "com.jcraft.jsch.jce.SignatureRSA");

This version no longer sets these properties.

My dependencies:

        <!-- Git -->
        <dependency>
            <groupId>org.eclipse.jgit</groupId>
            <artifactId>org.eclipse.jgit</artifactId>
            <version>5.13.0.202109080827-r</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jgit</groupId>
            <artifactId>org.eclipse.jgit.ssh.jsch</artifactId>
            <version>5.13.0.202109080827-r</version>
            <exclusions>
                <exclusion>
                    <groupId>com.jcraft</groupId>
                    <artifactId>jsch</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.github.mwiede</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.68</version>
        </dependency>
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch.agentproxy.connector-factory</artifactId>
            <version>0.0.9</version>
        </dependency>
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch.agentproxy.jsch</artifactId>
            <version>0.0.9</version>
            <exclusions>
                <exclusion>
                    <groupId>com.jcraft</groupId>
                    <artifactId>jsch</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

Stacktrace

Caused by: org.eclipse.jgit.api.errors.TransportException: [email protected]:mwiede/jsch.git: remote hung up unexpectedly
	at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:224)
	at org.eclipse.jgit.api.CloneCommand.fetch(CloneCommand.java:303)
	at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:178)
	at org.junit.jupiter.api.AssertDoesNotThrow.assertDoesNotThrow(AssertDoesNotThrow.java:72)
	... 71 more
Caused by: org.eclipse.jgit.errors.TransportException: [email protected]:mwiede/jsch.git: remote hung up unexpectedly
	at org.eclipse.jgit.transport.TransportGitSsh$SshFetchConnection.<init>(TransportGitSsh.java:313)
	at org.eclipse.jgit.transport.TransportGitSsh.openFetch(TransportGitSsh.java:153)
	at org.eclipse.jgit.transport.FetchProcess.executeImp(FetchProcess.java:142)
	at org.eclipse.jgit.transport.FetchProcess.execute(FetchProcess.java:94)
	at org.eclipse.jgit.transport.Transport.fetch(Transport.java:1309)
	at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:213)
	... 74 more
Caused by: java.lang.NullPointerException
	at java.util.Hashtable.put(Hashtable.java:460)
	at com.jcraft.jsch.JSch.setConfig(JSch.java:666)
	at org.eclipse.jgit.transport.JschConfigSessionFactory.createDefaultJSch(JschConfigSessionFactory.java:401)
	at org.eclipse.jgit.transport.JschConfigSessionFactory.getJSch(JschConfigSessionFactory.java:361)
	at org.eclipse.jgit.transport.JschConfigSessionFactory.createSession(JschConfigSessionFactory.java:317)
	at org.eclipse.jgit.transport.JschConfigSessionFactory.createSession(JschConfigSessionFactory.java:184)
	at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:108)
	at org.eclipse.jgit.transport.SshTransport.getSession(SshTransport.java:107)
	at org.eclipse.jgit.transport.TransportGitSsh$SshFetchConnection.<init>(TransportGitSsh.java:281)
	... 79 more

Host keyword in ssh config should be case-insensitive

Hi,

According to man ssh_config keywords should be case-insensitive and arguments should be case-sensitive.

However, it appears that the "Host" keyword is case-sensitive in the current implementation (on line 127 in OpenSSHConfig.java we have a case-sensitive equality check if(key_value[0].equals("Host")){ )

We have seen cases where this leads to confusing bugs when users assume that the config keywords are case-insensitive, so it would probably be good to change the code to match the specification.

Regards,
Johan Sundman Norberg

"no passphrase set." for already decrypted IdentityFile (KeyPairDeferred)

I'm using this fork of jsch together with Spring Integration SFTP. The Spring Integration SFTP wrapper will do setPassphrase on an identity file ahead of time. That means I get a KeyPairDeferred where encrypted is set to true, but on its delegate, it's set to false (as it has been decrypted already by the earlier call to setPassphrase)

image

Now com.jcraft.jsch.UserAuthPublicKey#decryptKey sees (correctly) that the identity is not encrypted and tries to call setPassphrase(null)

if(!identity.isEncrypted() || passphrase!=null){
  if(identity.setPassphrase(passphrase)){
    if(passphrase!=null &&
       (session.getIdentityRepository() instanceof IdentityRepository.Wrapper)){
      ((IdentityRepository.Wrapper)session.getIdentityRepository()).check();
    }
    break;
  }
}

But then two calls down in com.jcraft.jsch.KeyPair#decrypt(byte[]), we check the encrypted field on the KeyPairDeferred itself instead, which means that the decrypt call doesn't abort early (already decrypted case), but instead falls into the "no passphrase set." case

@Override
public boolean decrypt(byte[] _passphrase) {
    try {
        if (!encrypted) {
            return true;
        }
        if (_passphrase == null) {
            JSch.getLogger().log(Logger.ERROR, "no passphrase set.");
            return false;
        }

Shouldn't this be

if(!isEncrypted()) {

instead for this scenario to work?

JDK11 - Session.connect: java.io.IOException: End of IO Stream Read

Hi,

Versions tested:
Open/Oracle JDK 11.0.x (any version) <- randomly fails, maybe 1 out of 50
Open/Oracle JDK 1.8.0 181-301 <- works fine

On JDK8, JSCH works perfectly.
When using JDK11, it randomly fails with the following part stacktrace:

Caused by: com.jcraft.jsch.JSchException: Session.connect: java.io.IOException: End of IO Stream Read
at com.jcraft.jsch.Session.connect(Session.java:568)
at com.jcraft.jsch.Session.connect(Session.java:186)
at JschDelegate.connect(JschDelegate.groovy:172)

If you need more info, I will provide it.

Disable ssh-rsa (RSA/SHA1) signature scheme by default

OpenSSH has stated in the release notes for version 8.7 that they will finally disable the ssh-rsa (RSA/SHA1) signature scheme by default in their next release (see openssh/openssh-portable@2344750).

Since SHA-1 is no longer considered cryptographically secure, I think we should follow suit at some point in the near future, so that JSch provides sensible defaults that are aligned with general security practices.

This would not unequivocally disable the use of ssh-rsa type keys themselves, as they can still be utilized with the rsa-sha2-256 (RSA/SHA256) & rsa-sha2-512 (RSA/SHA512) signature schemes.

Additionally users would still be able to programmatically reenable the ssh-rsa (RSA/SHA1) signature scheme if needed via the server_host_key & PubkeyAcceptedAlgorithms config options (or jsch.server_host_key & jsch.client_pubkey system properties).

when the latest version will be published?

Hi,
I noticed that the current version is 0.1.59, and below maven reposotory can be used.

com.github.mwiede
jsch
0.1.59

When the latest com.github.mwiede.jsch dependency will be published? because the "support for openssh-v1-private-key format" can fix my issue :)

Ssh connection broken while browse large file with vim

Hi Jsch experts,

This is Peter from China.
First of all, thanks a lot for maintaining this project. It is really a great thing.
We are going to use Jsch and I hope I can contribute on it in the future.

I ran into one issue and I have debugged it for one week but still did not find any solution.
I hope you can give me some advice.

I am using Jsch & ChannelShell

I am using Jsch to login to one server, then use vim to browse one large file (700, 000 line).
What I did is just hold on the down arrow.
After a while, sometime it can get to 10000 lines, sometime it can get to 40000 lines, but it always result in error (three cases of exception).

But if I use the binary command ‘ssh’ instead of Jsch to try the same thing, everything is fine.

I download the source code from github and debug it.
I got three kinds of exception (three cases).

First case(I got this exception almost all the time):
The IO.java, the code:
int completed = in.read(array, begin, length);
this line will throw exception java.net.SocketException: Connection reset

The exception will be catch in Session.java, the main loop.
This exception means, the tcp session is closed/reset but I am still reading data from it.

I use tcpdump capture the packages and use wireshark to analyze it.
I find the last message the client sends to the server is same to former, the ‘down arrow’.
But after that the server will send RST message to client.

I try some configuration of openssh(sshd) but get no luck.

Second case(some time I got this exception):
This line throw exception:
Session.java
if(type==SSH_MSG_DISCONNECT){
buf.rewind();
buf.getInt();buf.getShort();
int reason_code=buf.getInt();
byte[] description=buf.getString();
byte[] language_tag=buf.getString();
throw new JSchException("SSH_MSG_DISCONNECT: "+
reason_code +
" description: " + Util.byte2str(description)+
" language_tag: " + Util.byte2str(language_tag) + " end");
//break;
}

Third case(this case happen 2 or 3 times ):

IO.java
if(completed<0){
throw new IOException("End of IO Stream Read");
}

This line will throw exception.

I have tried everything I know. But still cannot resolve it.
Could you share your suggestion for this kind of issue?

Thanks in advance.

Best Regards,
Peter Qin

RequestEnv should be unwant reply

RFC4254 Section 6.4 describe environment variable passing can be filtered in security imprecations.
This can be resulted a reply become false, but it is not an error.

According to JGit discussion about behavior of Jsch env request,
it should be 'unwant-reply' and it is a JSch bug that it throws exception.
https://bugs.eclipse.org/bugs/show_bug.cgi?id=576922

When JGit request GIT_PROTOCOL=version=2 environment variable,
JSch should return even when it is not succeeded.

Cannot connect to old OpenSSH server since version 0.1.57

Hi,

we need to connect to a quite old sftp server running OpenSSH 5.3. This worked nicely with the original Jsch and also with this fork up to version 0.1.56. Unfortunately, it is broken with all versions since 0.1.57 up to the current version 0.1.62.

This is the debug log of a working connection using 0.1.56:

1: Connecting to CENSORED port 22
1: Connection established
1: Remote version string: SSH-2.0-OpenSSH_5.3
1: Local version string: SSH-2.0-JSCH-null
1: CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
1: CheckKexes: diffie-hellman-group14-sha1,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521
1: CheckSignatures: ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
1: SSH_MSG_KEXINIT sent
1: SSH_MSG_KEXINIT received
1: kex: server: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
1: kex: server: ssh-rsa,ssh-dss
1: kex: server: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
1: kex: server: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
1: kex: server: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
1: kex: server: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
1: kex: server: none,[email protected]
1: kex: server: none,[email protected]
1: kex: server: 
1: kex: server: 
1: kex: client: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1
1: kex: client: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
1: kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc
1: kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc
1: kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
1: kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
1: kex: client: none
1: kex: client: none
1: kex: client: 
1: kex: client: 
1: kex: server->client aes128-ctr hmac-md5 none
1: kex: client->server aes128-ctr hmac-md5 none
1: SSH_MSG_KEXDH_INIT sent
1: expecting SSH_MSG_KEXDH_REPLY
1: ssh_rsa_verify: signature true
2: Permanently added 'CENSORED' (RSA) to the list of known hosts.
1: SSH_MSG_NEWKEYS sent
1: SSH_MSG_NEWKEYS received
1: SSH_MSG_SERVICE_REQUEST sent
1: SSH_MSG_SERVICE_ACCEPT received
1: Authentications that can continue: publickey
1: Next authentication method: publickey
1: Authentication succeeded (publickey).

This is a debug log of version 0.1.57 where the connection is broken:

1: Connecting to CENSORED port 22
1: Connection established
1: Remote version string: SSH-2.0-OpenSSH_5.3
1: Local version string: SSH-2.0-JSCH-null
1: CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
1: CheckKexes: diffie-hellman-group14-sha1,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521
1: CheckSignatures: ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
1: SSH_MSG_KEXINIT sent
1: SSH_MSG_KEXINIT received
1: kex: server: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
1: kex: server: ssh-rsa,ssh-dss
1: kex: server: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
1: kex: server: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
1: kex: server: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
1: kex: server: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
1: kex: server: none,[email protected]
1: kex: server: none,[email protected]
1: kex: server: 
1: kex: server: 
1: kex: client: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1
1: kex: client: rsa-sha2-256,rsa-sha2-512,ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
1: kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc
1: kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc
1: kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
1: kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
1: kex: client: none
1: kex: client: none
1: kex: client: 
1: kex: client: 
1: kex: server->client aes128-ctr hmac-md5 none
1: kex: client->server aes128-ctr hmac-md5 none
1: SSH_MSG_KEXDH_INIT sent
1: expecting SSH_MSG_KEXDH_REPLY
1: ssh_rsa_verify: signature true
2: Permanently added 'CENSORED' (RSA) to the list of known hosts.
1: SSH_MSG_NEWKEYS sent
1: SSH_MSG_NEWKEYS received
1: SSH_MSG_SERVICE_REQUEST sent
1: SSH_MSG_SERVICE_ACCEPT received
1: Authentications that can continue: publickey
1: Next authentication method: publickey
1: Disconnecting from CENSORED port 22
Exception in thread "main" com.jcraft.jsch.JSchException: SSH_MSG_DISCONNECT: 2 Too many authentication failures for anb0230 
	at com.jcraft.jsch.Session.read(Session.java:1010)
	at com.jcraft.jsch.UserAuthPublicKey.start(UserAuthPublicKey.java:125)
	at com.jcraft.jsch.Session.connect(Session.java:473)
	at com.jcraft.jsch.Session.connect(Session.java:186)
	at de.mycompany.test.Application.main(Application.java:37)

As you can see, only one line is different:

1: kex: client: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521

vs

1: kex: client: rsa-sha2-256,rsa-sha2-512,ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521

Surprisingly, setting this in my code does not fix the issue, even though it makes the log look identical (except for the disconnect and the exception at the end):

    session.setConfig("server_host_key", "ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521");	

Instead, I am able to workaround the issue by setting this:

    session.setConfig("PubkeyAcceptedKeyTypes", "ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521");

This change moves ssh-rsa to the front of the value, compared to the default config.

But I really do not want to do that, for multiple reasons:

  • I barely understand what I am doing here.
  • I believe this library is supposed to be a "drop in " replacement for the original Jsch, so I expect those low-level-thingies to just work like before. The original Jsch library didn't even have the config option PubkeyAcceptedKeyTypes.

I can't find any documentation for PubkeyAcceptedKeyTypes. I just found out about this by reading this commit: 045799e

Again, this worked with the original version of Jsch and broke with a minor version update. Also, the remote server uses a completely normal (but rather old) OpenSSH version without exotic settings. These are the reasons why I believe this to be a bug in this library.

Packet corrupt

First off I downloaded jsch-0.1.55 from jcraft.com

Background: I have written a Java program that is a GUI use to configure a Cisco telephone router. This is normally done logging into the router using either telnet or ssh. Configuration is done through the terminal.

I have successfully written code using the ChannelExec but it only works once. And I get the Packet corrupt on the next command.

In this application I do not store user credentials for security reasons. So the proposed workaround of recreating the session is not ideal because I do not want to keep prompting the user to enter credentials, I only want to prompt for credentials when a real time out occurs, and in my opinion not being able to send commands back to back with in milliseconds of each other is not a session timeout.

Below is the stack trace and my example code. I have done the initial setup in my class constructor. And I create the Session in a separate method when I prompt the user for credentials.

com.icraft.isch.JSchException: Packet corrupt
at com.jcraft.jsch.Session.start discard (Session.java:1067)
at com.jcraft.jsch.Session. read (Session. java: 937)
at com.jcraft.jsch.Session. connect (Session.java: 309)
at gov.jdaccs. comm.SecureShellChannel. sendCommand (SecureShellChannel.java: 122)
at gov. jdaccs. views. RouterPanelView$3$1. doInBackground (RouterPanelView.java: 239)
at gov. jdaccs. views. RouterPanelView$3$1. doInBackground (RouterPanelView.java: 1)
at javax.swing.SwingWorker$l.call(Swingworker.iava:295)
at java.util. concurrent. FutureTask. run (FutureTask java: 266)
at javax. swing.SwingWorker.run (SwingWorker.java: 334)
at java.util. concurrent. ThreadPoolExecutor, runworker (ThreadPoolExecutor. java: 1149)
at java.til. concurrent-ThreadPoolExecutorsworker.run(IhreadPoolExecutor.java:624)
at java.lang.Thread. run (Thread. java: 748)

System.out.println("String Builder") ;
StringBuilder output = new StringBuilder();

System.out.println("Create Channel")
channel = session. openChannel("exec”);
System.out.println( "Sending command: + command) ;
( (ChannelExec) channel) .setCommand (command) ;
InputStream commandOutput = channel. getInputStream();
channel. connect ();

int readByte = commandOutput. read () ;

while (readByte != Oxffffffff)
{
output. append ( (char) readByte):
readbyte = commandOutput. read() ;
}

// close Channel	
channel. disconnect () ;

// close Session
session.disconnect () ;
return output. tostring();

}

Auth fail with private key in string

I want to use a key to access my SSH server, but I keep getting an Auth Fail error.
This is for an Android application in Kotlin.

private fun sshCommand(
            username: String? = "root",
            //password: String? = "xxxxxxxxxx",
            host: String? = "192.168.1.1",
            port: Int = 22,
            command: String?
    ) {
        GlobalScope.launch(Dispatchers.IO) {
            var session: Session? = null
            var channel: ChannelExec? = null

            val privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" +
                    "MIIEowIBAAKCAQEAuwYj4yZ427dxKKksO05+J9tZQJh75KlbfajFuiI2K4RwTQf1\n" +
                    "DCZwxHAsvNikOVd1QpO2KaOovRvaPxtxaa7lfSdakJaYDG3xNkIlC6lu6r2AelVq\n" +
                    "bNEqRwrIbWxO9hfH2a9Bx/ffEolj6aPnclzNuh5cJvGhq0yySiyJZgkdmc1mTV8K\n" +
                    "ZiOiS5Tr5jIBagRyHL5tAEnLr4Jm4I/vrkr9H/wbeo5bASlxHGBpUezMIyBidWpJ\n" +
                    "lbGKn+fEjg5pDpf4dFylNOV8zLWLpEWIXDg4rzmJudeU4Q6CJuExwFyo8v85qYc0\n" +
                    "95DmeLINTQt6yEMFjWdvuOUntviQBU8SODG5mwIBJQKCAQEAtfgi6tlS/0qzSigP\n" +
                    "XExfEgXaTLAJ15AF/bj3vAWcfV5DwJIe22Or/WY5XcveDkdBqI+4KIOPa+O/l1j4\n" +
                    "udqaGOgFFw8QesvV75pNjs5eFNQOTYOKJK/WG5vJ7ezXNKGELb9G7BPESWMVGq1P\n" +
                    "5OSsfbyssEUMAJ2mjVvD9JM/ZTTf6xu2GKyWt9go+NhUQGLKFlQe/aEq4tf1MGQP\n" +
                    "IFpOoLkPY3Y9twK4iYIHiZ2m7BpSufrukkrqrcuttNZ86/ftM0iuPzflSWJjaIQj\n" +
                    "wRhOl1/ilu9GkV8Edcx9LcN/N5GBSRsO7zmgrbZrAgXZo60zlcblDkdBNnJmaHE+\n" +
                    "DBZqLQKBgQD3+xhjIjoX0ooSBpZ7CALXq1AtJ45d010kj0sY041+QgZ+aNouAfAw\n" +
                    "vTowvukdCJtfEgULtVIJkRNS8txe21XQwUFMyz/9Wnonh1RIYLZDhogrx4BLydJu\n" +
                    "69Xp/RNvEgW93j0DG5RCW55N3y+fwMFanB2kzQjDwHAF++yrD4N8KwKBgQDBEmos\n" +
                    "HFSaPBdabhKFH9T1aLQ8cIBzj3H4GGw5Fe7m8akwzwjfWHZ0fH0GKSGnGaLZB84B\n" +
                    "kSC6ht+NTABCsoNXd0mI4Y+a5s8onDCNA0VrfuQm1zayVyij+tyqqZWhy2sMQCdG\n" +
                    "EMiGFTS1ARz0O7pSXnZDDva2Ra9n5SbnY15QUQKBgEm5Wkb8VnXI+J2TQX6F11Tf\n" +
                    "52deyXXXDdpvyjfQMPwFypRIr5EjK7t2huvluuz0uJHiwzrVCo049+g6XTD1GYNA\n" +
                    "X4WIiKVEaYFflZj6KFlDq/FW/KDo+V8/McIazm0hCKA7JuU/jPEiKCT9KdWMVSjG\n" +
                    "oQd7OfUB3B10aPSV6NHjAoGBAIzj7Jy6ukcJQXlXPfJxLLMVDebqT+WgBw79ELQJ\n" +
                    "Fh4l+AEFyDRHeQjlOKOheWwZoFkvNXbD2Zze9ijWmGgFuco0c+5Du9Hmsthx+epc\n" +
                    "VUCa3dcnbRpbRyuNjEUvpIrSteZYVAKyTSOS7xxM6513sXpgm30K62JqM+QIFXhr\n" +
                    "G09dAoGBAOvogarpounrMCPTAtcyiYtoiVoV5X1zZKkEP9yvJJlZobKsIo8Fk+mP\n" +
                    "GkcnIp+sKaGq8j/lBtxt3jWQSI/z7OFFm++0CYQDRmdqMhxszfYmeOX/e8c1V/rz\n" +
                    "2iwuMcc2qWAlifsHeLubUGIn0f7nWURR9cgYekE8h5ad7KKO3Q8O\n" +
                    "-----END RSA PRIVATE KEY-----\n"

            try {
                JSch().addIdentity("blabla123", privateKey.toByteArray(), null, null)
                session = JSch().getSession(username, host, port)
                //session.setPassword(password)
                session.setConfig("StrictHostKeyChecking", "no")
                session.connect()
                channel = session.openChannel("exec") as ChannelExec
                channel.setCommand(command)
                val responseStream = ByteArrayOutputStream()
                channel.outputStream = responseStream
                channel.connect()
                while (channel.isConnected) {
                    Thread.sleep(100)
                }
                val responseString = String(responseStream.toByteArray())
                println(responseString)
            } finally {
                session?.disconnect()
                channel?.disconnect()
            }
        }
    }

Log in Android Studio:

W/System.err: INFO: Connecting to 192.168.1.1 port 22
W/System.err: INFO: Connection established
W/System.err: INFO: Remote version string: SSH-2.0-dropbear
W/System.err: INFO: Local version string: SSH-2.0-JSCH-0.1.54
W/System.err: INFO: CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
W/System.err: INFO: CheckKexes: diffie-hellman-group14-sha1,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521
W/System.err: INFO: CheckSignatures: ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
W/System.err: INFO: SSH_MSG_KEXINIT sent
    INFO: SSH_MSG_KEXINIT received
W/System.err: INFO: kex: server: curve25519-sha256,[email protected],diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,[email protected]
W/System.err: INFO: kex: server: ssh-rsa
    INFO: kex: server: aes128-ctr,aes256-ctr
W/System.err: INFO: kex: server: aes128-ctr,aes256-ctr
    INFO: kex: server: hmac-sha1,hmac-sha2-256
W/System.err: INFO: kex: server: hmac-sha1,hmac-sha2-256
    INFO: kex: server: none
W/System.err: INFO: kex: server: none
    INFO: kex: server: 
W/System.err: INFO: kex: server: 
W/System.err: INFO: kex: client: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1
W/System.err: INFO: kex: client: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
W/System.err: INFO: kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc
W/System.err: INFO: kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc
W/System.err: INFO: kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
W/System.err: INFO: kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
    INFO: kex: client: none
W/System.err: INFO: kex: client: none
W/System.err: INFO: kex: client: 
    INFO: kex: client: 
W/System.err: INFO: kex: server->client aes128-ctr hmac-sha1 none
W/System.err: INFO: kex: client->server aes128-ctr hmac-sha1 none
W/System.err: INFO: SSH_MSG_KEXDH_INIT sent
W/System.err: INFO: expecting SSH_MSG_KEXDH_REPLY
W/System.err: INFO: ssh_rsa_verify: signature true
W/System.err: WARN: Permanently added '192.168.1.1' (RSA) to the list of known hosts.
W/System.err: INFO: SSH_MSG_NEWKEYS sent
W/System.err: INFO: SSH_MSG_NEWKEYS received
W/System.err: INFO: SSH_MSG_SERVICE_REQUEST sent
W/System.err: INFO: SSH_MSG_SERVICE_ACCEPT received
W/System.err: INFO: Authentications that can continue: publickey,keyboard-interactive,password
W/System.err: INFO: Next authentication method: publickey
W/System.err: INFO: Authentications that can continue: password
    INFO: Next authentication method: password
W/System.err: INFO: Disconnecting from 192.168.1.1 port 22
E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
    Process: com.example.ps4nuker, PID: 9354
    com.jcraft.jsch.JSchException: Auth fail
        at com.jcraft.jsch.Session.connect(Session.java:519)
        at com.jcraft.jsch.Session.connect(Session.java:183)
        at com.example.ps4nuker.MainActivity$sshCommand$1.invokeSuspend(MainActivity.kt:101)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
        at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)

I believe the private key is in the right format for JSch to understand.
The connection works perfectly when I use a password, or when I use the same private key in Mobaxterm.
How can I get it to work with the private key in a string?

Support for forwarding local unix domain sockets

The recent addition of the USocketFactory interface for ssh-agent support should now also unlock the ability to add support for local unix domain socket forwarding.

Ultimately we should be able to support all of the following forwarding capabilities for feature parity with OpenSSH:

  • Local forwarding to remote:
    • local tcpip => remote tcpip
      • Already supported
    • local tcpip => remote unix domain socket
      • Already supported
    • local unix domain socket => remote tcpip
      • Currently unsupported
    • local unix domain socket => remote unix domain socket
      • Currently unsupported
  • Reverse forwarding from remote
    • local tcpip <= remote tcpip
      • Already supported
    • local tcpip <= remote unix domain socket
      • Currently unsupported
    • local unix domain socket <= remote tcpip
      • Currently unsupported
    • local unix domain socket <= remote unix domain socket
      • Currently unsupported

Just want to say thanks.

Just want to say thanks for the fork on this project, that is all! We had the ECDSA host key issue and we had to contemplate switching to MINA (which has a terrifying and overcomplicated API based on spaghetti code and ugly callbacks).

If you have a crpyto donation address, I'll kick you some beans 😎

Missing KexAlgorithms +diffie-hellman-group1-sha1

I have a Java project which uses the jsch classes. I tried your repo, but had to switch back to sschlib because it supported this:

KexAlgorithms +diffie-hellman-group1-sha1

requirement in my thousands of remote nodes running older dropbear all over the world. They are not upgradeable. I tried unsuccessfully to add support for that KexAlgorithm back into your library. So the path of least resistance was to switch back to something that works: sschlib. It is not an option to upgrade these little servers.

I can connect to these boxes fine using command line ssh on modern linux if I add the above statement to file: ~/.ssh/config.

Is there a simple trick to support this when creating the JSch class instance by modifying the config records without modifying the library source? Nothing I tried along that pathway worked after a full day of trying.

Execution failed for JetifyTransform

I tried to use the this jsch fork as a drop in replacement for the original library:

app/build.gradle

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.github.mwiede:jsch:0.1.62'
    ...
}

gradle.properties

android.useAndroidX=true
android.enableJetifier=true

Android Studio now gives me:

Execution failed for task ':app:javaPreCompileFdroidDebug'.
> Could not resolve all files for configuration ':app:fdroidDebugCompileClasspath'.
   > Failed to transform artifact 'jsch.jar (com.github.mwiede:jsch:0.1.62)' to match attributes {artifactType=android-classes, org.gradle.usage=java-runtime-jars}
      > Execution failed for JetifyTransform: /home/mwarning/.gradle/caches/modules-2/files-2.1/com.github.mwiede/jsch/0.1.62/de4b21c9c2d40481ec19644c16c66fc7a44027c8/jsch-0.1.62.jar.
         > Failed to transform '/home/mwarning/.gradle/caches/modules-2/files-2.1/com.github.mwiede/jsch/0.1.62/de4b21c9c2d40481ec19644c16c66fc7a44027c8/jsch-0.1.62.jar' using Jetifier. Reason: null. (Run with --stacktrace for more details.)

I also tried jsch 0.1.58 and cleared the cache each time.

Any idea how to fix this?

What can cause the ssh connection exit when I create the ssh with jsch

I am focus on one project about webshell, Jsch is used to create the ssh connection. But when the ssh connection is created , the connection will exit without any error or info occasionally.
below is my code, I am not sure what can cause the issue? anyone can take a look at it?
when keyLogin() is called then method output() is called, in output(), it create one thread
to check the inputstream. when inputStream.read(bytes) != -1, I think the ssh connection exit, but I don't know why the ssh connection exit.

Login method

`public class ShellPlatform {

..............

private boolean loginByEkey(String user, String host, int port, Map<String, Integer> ptySizeMap) {
	boolean result = true;
	try {
		String keyPath = SecretKeyUtil.getSecretKeyPath(user);
		File key = new File(keyPath);
		if (key.isFile()) {
			shellUtil.keyLogin(user, host, port, keyPath, ptySizeMap);
			outputStream = shellUtil.getInput();
			inputStream = shellUtil.getOutput();
			output();
		} 
	} catch (Exception e) {
		LOGGER.logException(e);
		this.classifyProcessException(e);
		result = false;
	}
	return result;
}


private boolean output() {
	try {
		Thread thread = new Thread() {
			@Override
			public void run() {
				while (running) {
					byte[] bytes = new byte[1024];
					try {
						int i;
						while ((i = inputStream.read(bytes)) != -1) {
							initResult();
							resultMessage.setData(new String(bytes,0,i));
							resultMessage.setBdata(Arrays.copyOfRange(bytes,0,i));
							sendMessage(resultMessage);
							Thread.sleep(20L);
						}
						// break the while, the ssh connection exit
						initResult();
						resultMessage.setCode("1012");
						resultMessage.setData("exit the shell");
						sendMessage(resultMessage);
						break;
					} catch (Exception e) {
						initResult();
						resultMessage.setCode("1012");
						resultMessage.setData("get command result fail");
						resultMessage.setMsg(e.getMessage());
						sendMessage(resultMessage);
					}
				}
			}
		};
		thread.setName("outPutThread");
		thread.start();
	} catch (Exception e) {
		initResult();
		resultMessage.setCode("1012");
		resultMessage.setData("thread start fail");
		resultMessage.setMsg(e.getMessage());
		sendMessage(resultMessage);
		return false;
	}
	return true;
}

}`

ShellUtil.java

`public class ShellUtil {
private Session session;
private ChannelShell channel;
private InputStream inputStream;
private OutputStream outputStream;
// TODO
private static GLogger logger = ClustertoolLogger.getLogger();

public void login(String user, String host, int port, String pswd, Map<String, Integer> ptySizeMap)
		throws JSchException, IOException {
	JSch jsch = new JSch();
	session = jsch.getSession(user, host, port);
	if (null != pswd) {
		session.setPassword(pswd);
	}
	this.connect(ptySizeMap);
}

public void keyLogin(String user, String host, int port, String keyPath, Map<String, Integer> ptySizeMap)
		throws JSchException, IOException {
	JSch jsch = new JSch();
	jsch.addIdentity(keyPath);

	session = jsch.getSession(user, host, port);
	this.connect(ptySizeMap);
}

private void connect(Map<String, Integer> ptySizeMap) throws JSchException, IOException {
	try {
		session.setConfig("StrictHostKeyChecking", "no");
		session.connect(30000); // making a connection with timeout. 30s
		channel = (ChannelShell) session.openChannel("shell");
		inputStream = channel.getInputStream();
		outputStream = channel.getOutputStream();
		Integer col = ptySizeMap.get("col") == null ? 80 : ptySizeMap.get("col");
		Integer row = ptySizeMap.get("row") == null ? 24 : ptySizeMap.get("row");
		Integer wp = ptySizeMap.get("wp") == null ? 640 : ptySizeMap.get("wp");
		Integer hp = ptySizeMap.get("hp") == null ? 480 : ptySizeMap.get("hp");
		channel.setPtyType("xterm");
		channel.setPtySize(col, row, wp, hp);
		channel.connect(30000); // making a connection with timeout. 30s			
	} catch (JSchException e) {
		//String。contains()可能存在JDK版本沖突
		if(null != e.getMessage() && e.getMessage().indexOf("channel is not opened") != -1){
			throw new JSchException("SSH connection timeout");
		}
		throw e;
	}
}

public boolean isLogined() {
	return session.isConnected() && channel.isConnected() && !channel.isClosed();
}

public void logout() throws IOException {
	if (null != inputStream) {
		inputStream.close();
	}
	if (null != outputStream) {
		outputStream.close();
	}
	if (null != channel) {
		channel.disconnect();
	}
	if (null != session) {
		session.disconnect();
	}
}

public OutputStream getInput() throws JSchException, IOException {
	if (isLogined()) {
		if (null == outputStream) {
			outputStream = channel.getOutputStream();
		}
		return outputStream;
	} else {
		throw new JSchException("not have login");
	}
}

public InputStream getOutput() throws JSchException, IOException {
	if (isLogined()) {
		if (null == inputStream) {
			inputStream = channel.getInputStream();
		}
		return inputStream;
	} else {
		throw new JSchException("not have login");
	}
}

public void changePtySize(Map<String, Integer> ptySizeMap) throws JSchException, IOException {
	if (isLogined()) {
		Integer col = ptySizeMap.get("col") == null ? 80 : ptySizeMap.get("col");
		Integer row = ptySizeMap.get("row") == null ? 24 : ptySizeMap.get("row");
		Integer wp = ptySizeMap.get("wp") == null ? 640 : ptySizeMap.get("wp");
		Integer hp = ptySizeMap.get("hp") == null ? 480 : ptySizeMap.get("hp");
		channel.setPtySize(col, row, wp, hp);
	} else {
		throw new JSchException("link exception");
	}
}

}`

BouncyCastle NoSuchMethodError

Hey, I switched from latest com.jcraft:jsch to your repo.
I read of the missing config for older servers but I receive a different error.

java.lang.NoSuchMethodError: org.bouncycastle.crypto.params.X25519PublicKeyParameters.<init>([B)V

	at com.jcraft.jsch.bc.XDH.getSecret(XDH.java:71)
	at com.jcraft.jsch.DHXEC.next(DHXEC.java:144)
	at com.jcraft.jsch.Session.connect(Session.java:330)

I use JSch inside Spring Application to provide SSH command executions. I tried #37 and #40, but those settings doesn't help. Any hint?

Authentication with public key fails with 0.1.62

Hi,

We were using 0.1.55 to connect to a server using public key auth without a problem.
After we upgraded to 0.1.62, public key authentication fails with "Auth Fail".
If we use the UserAuthPublicKey class from 0.1.55, we are able to login again.

Is this a known bug?

Thanks,
Avner

Flag to enable "legacy" algos on initialization?

Hi, I see a lot of users are expecing full in-place compatibility with old Jsch, but that does not happen due to the retirement of some now insecure algos:

#48
#47
#45
#40
#37

I propose adding a flag that would enable all algos that were previously enabled in the legacy Jsch, something like:

new com.jcraft.jsch.JSch(enable_insecure = "true");

Of course, they would be the least preferred/offered option in the negotiation list.

Reason:
we use Jsch to connect to all kinds of versions (some 10+ years old) of below OSes, and its simply impossible to live without these legacy algos. I know we can enable them via configuration as in the example existing issues, but a simple flag that would enable all of them at once is definitely a cleaner way.

  • 3Com
  • A10 ACOS
  • Allot
  • Arista EOS
  • Aruba AOS
  • BlueCat
  • BlueCoat CAS
  • BlueCoat PacketShaper
  • BlueCoat ProxyAV
  • BlueCoat ProxySG
  • Brocade Vyatta NetworkOS
  • CheckPoint GAIA
  • CheckPoint IPSO
  • CheckPoint SPLAT
  • Cisco ACE
  • Cisco ACS
  • Cisco APIC
  • Cisco ASA
  • Cisco AsyncOS
  • Cisco CatOS
  • Cisco CSS
  • Cisco Express
  • Cisco FTD
  • Cisco FWSM
  • Cisco FXOS
  • Cisco IOS
  • Cisco IOS XR
  • Cisco IPS
  • Cisco ISE
  • Cisco NXOS
  • Cisco Prime
  • Cisco WAAS
  • Cisco WLC
  • Citrix NetScaler
  • Dell iDRAC
  • Dell NetworkingOS
  • Enterasys
  • F5
  • Forcepoint Stonesoft
  • Fortinet FortiOS
  • Gigamon GigaVUEOS
  • HP
  • Huawei
  • IBM AlteonOS/BladeOS/NetworkingOS
  • IBM ISCLI
  • Infoblox NIOS
  • Juniper JUNOS
  • Juniper ScreenOS
  • Lenovo CNOS
  • Linux
  • Nokia VitalQIP
  • Nortel WSS
  • Oracle Acme PacketOS
  • Palo Alto PANOS
  • PulseSecure
  • Radware Alteon
  • Riverbed RiOS
  • Spectracom
  • TrendMicro IPS TOS
  • TrendMicro TPS TOS

Integrating with JGit

I recently started using JGit for an internal application. When I tried to run it on our server, however, I got an error. Eventually, I discovered it was because JCraft's JSch does not support the OpenSSH private key format.

I looked into using this project as a drop-in replacement for JCraft's JSch. I used the following lines in my Gradle build.

dependencies {
    implementation("org.eclipse.jgit:org.eclipse.jgit:5.11.0.202103091610-r")
    // The default implementation of JSch does not support new OpenSSH key formats
    implementation("com.github.mwiede:jsch:0.1.62")
}

configurations.all {
    resolutionStrategy.eachDependency {
        if (requested.group == "com.jcraft" && requested.name == "jsch") {
            useTarget("com.github.mwiede:jsch:0.1.58")
            because("default jsch does not support OpenSSH keys")
        }
    }
}

Unfortunately, if I did that, I did not have a working implementation of org.eclipse.jgit.transport.SshConnectionFactory.

I then tried adding implementation("org.eclipse.jgit:org.eclipse.jgit.ssh.jsch:5.11.0.202103091610-r") back into my list of dependencies. Now I had a working SshConnectionFactory. However, I then got a NullPointerException because the JschConfigSessionFactory expected a value for "signature.rsa" to be present in the JSch config, which this fork does not have.

Do you have any tips for how to integrate this fork with JGit? I know it's not your project but figured this would be a good place to ask. I've tried adding my own implementation of org.eclipse.jgit.transport.SshConnectionFactory but haven't been able to convince the class loader to find it (I'm very inexperienced with this area of Java).

If the answer is "you'll have to figure it out yourself" that's completely understandable 😃

IPV6 support

Does this library support talking to an SSH server running only IPV6?

If not, what would have to be done to support that?

could not connect to my Huawei switch.

Hello, I can't connect to my switch after migrating ganymed-ssh2 to jsch(Session.connect: java.security.SignatureException: Could not verify signature). Other ssh service like Ubuntu, Centos working well. Can anyone help?
using ganymed-ssh2 and linux ssh command worked.
jsch version:

       <dependency>

            <groupId>com.github.mwiede</groupId>

            <artifactId>jsch</artifactId>

            <version>0.1.69</version>

        </dependency>

Here is my session config code:

Properties p = new Properties();
        String rawkex = session.getConfig("kex");
        String extendKex = "diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1";
        String finalKex = Stream.concat(Arrays.stream(rawkex.split(",")), Arrays.stream(extendKex.split(",")))
                .distinct()
                .collect(Collectors.joining(","));
        p.setProperty("kex", finalKex);

        String serverHostKey = session.getConfig("server_host_key");
        //enable ssh-dss
        p.setProperty("server_host_key", serverHostKey + ",ssh-dss");
        p.setProperty("StrictHostKeyChecking", "no");
        p.setProperty("PreferredAuthentications", "password,keyboard-interactive");
        //Solaris
        p.setProperty("dhgex_preferred", "1024");
        p.setProperty("dhgex_min", "1024");

Java version:

openjdk version "1.8.0_302"
OpenJDK Runtime Environment (build 1.8.0_302-b08)
OpenJDK 64-Bit Server VM (build 25.302-b08, mixed mode)

Stacktrace:

com.jcraft.jsch.JSchException: Session.connect: java.security.SignatureException: Could not verify signature
	at com.jcraft.jsch.Session.connect(Session.java:570)
	at com.topsec.tap.collector.agent.connection.JschConnection.initializeOpen(JschConnection.java:186)
	at com.topsec.tap.collector.agent.connection.JschConnection.open(JschConnection.java:116)
	at com.topsec.tap.collector.agent.connection.JschConnection.main(JschConnection.java:730)
Caused by: java.security.SignatureException: Could not verify signature
	at sun.security.ec.ECDSASignature.engineVerify(ECDSASignature.java:413)
	at java.security.Signature$Delegate.engineVerify(Signature.java:1394)
	at java.security.Signature.verify(Signature.java:771)
	at com.jcraft.jsch.jce.SignatureECDSAN.verify(SignatureECDSAN.java:175)
	at com.jcraft.jsch.KeyExchange.verify(KeyExchange.java:346)
	at com.jcraft.jsch.DHGEX.next(DHGEX.java:224)
	at com.jcraft.jsch.Session.connect(Session.java:331)
	... 3 more
Caused by: java.security.SignatureException: Invalid encoding for signature
	at sun.security.util.ECUtil.decodeSignature(ECUtil.java:258)
	at sun.security.ec.ECDSASignature.engineVerify(ECDSASignature.java:409)
	... 9 more
Caused by: java.io.IOException: Invalid encoding: redundant leading 0s
	at sun.security.util.DerInputBuffer.getBigInteger(DerInputBuffer.java:161)
	at sun.security.util.DerValue.getPositiveBigInteger(DerValue.java:559)
	at sun.security.util.ECUtil.decodeSignature(ECUtil.java:242)
	... 10 more

ssh server information using ssh -vvv :

OpenSSH_8.2p1 Ubuntu-4ubuntu0.3, OpenSSL 1.1.1f  31 Mar 2020
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: include /etc/ssh/ssh_config.d/*.conf matched no files
debug1: /etc/ssh/ssh_config line 21: Applying options for *
debug3: kex names ok: [diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1]
debug2: resolve_canonicalize: hostname 10.8.20.100 is address
debug2: ssh_connect_direct
debug1: Connecting to 10.8.20.100 [10.8.20.100] port 22.
debug1: Connection established.
debug1: identity file /home/leen/.ssh/id_rsa type 0
debug1: identity file /home/leen/.ssh/id_rsa-cert type -1
debug1: identity file /home/leen/.ssh/id_dsa type -1
debug1: identity file /home/leen/.ssh/id_dsa-cert type -1
debug1: identity file /home/leen/.ssh/id_ecdsa type -1
debug1: identity file /home/leen/.ssh/id_ecdsa-cert type -1
debug1: identity file /home/leen/.ssh/id_ecdsa_sk type -1
debug1: identity file /home/leen/.ssh/id_ecdsa_sk-cert type -1
debug1: identity file /home/leen/.ssh/id_ed25519 type -1
debug1: identity file /home/leen/.ssh/id_ed25519-cert type -1
debug1: identity file /home/leen/.ssh/id_ed25519_sk type -1
debug1: identity file /home/leen/.ssh/id_ed25519_sk-cert type -1
debug1: identity file /home/leen/.ssh/id_xmss type -1
debug1: identity file /home/leen/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_8.2p1 Ubuntu-4ubuntu0.3
debug1: Remote protocol version 2.0, remote software version -
debug1: no match: -
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to 10.8.20.100:22 as 'admin2'
debug3: hostkeys_foreach: reading file "/home/leen/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/leen/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from 10.8.20.100
debug3: order_hostkeyalgs: prefer hostkeyalgs: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,[email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1,ext-info-c
debug2: host key algorithms: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],ssh-ed25519,[email protected],rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss
debug2: ciphers ctos: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]
debug2: ciphers stoc: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]
debug2: MACs ctos: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,[email protected],zlib
debug2: compression stoc: none,[email protected],zlib
debug2: languages ctos: 
debug2: languages stoc: 
debug2: first_kex_follows 0 
debug2: reserved 0 
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1
debug2: host key algorithms: ecdsa-sha2-nistp521,ssh-dss,ssh-rsa
debug2: ciphers ctos: aes256-ctr,aes128-ctr,aes256-cbc,aes128-cbc,3des-cbc
debug2: ciphers stoc: aes256-ctr,aes128-ctr,aes256-cbc,aes128-cbc,3des-cbc
debug2: MACs ctos: hmac-sha2-256,hmac-sha2-256-96,hmac-sha1,hmac-sha1-96,hmac-md5,hmac-md5-96
debug2: MACs stoc: hmac-sha2-256,hmac-sha2-256-96,hmac-sha1,hmac-sha1-96,hmac-md5,hmac-md5-96
debug2: compression ctos: none,zlib
debug2: compression stoc: none,zlib
debug2: languages ctos: 
debug2: languages stoc: 
debug2: first_kex_follows 0 
debug2: reserved 0 
debug1: kex: algorithm: diffie-hellman-group-exchange-sha1
debug1: kex: host key algorithm: ecdsa-sha2-nistp521
debug1: kex: server->client cipher: aes128-ctr MAC: hmac-sha2-256 compression: none
debug1: kex: client->server cipher: aes128-ctr MAC: hmac-sha2-256 compression: none
debug3: send packet: type 34
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(2048<8192<8192) sent
debug3: receive packet: type 31
debug1: got SSH2_MSG_KEX_DH_GEX_GROUP
debug2: bits set: 2049/4096
debug3: send packet: type 32
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug3: receive packet: type 33
debug1: got SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: ecdsa-sha2-nistp521 SHA256:RJpTh5BR8X+DWEK6+otU4KD3STSHpBy4zs5YEPNEI1Y
debug3: hostkeys_foreach: reading file "/home/leen/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/leen/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from 10.8.20.100
debug1: Host '10.8.20.100' is known and matches the ECDSA host key.
debug1: Found key in /home/leen/.ssh/known_hosts:1
debug2: bits set: 2045/4096
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey out after 4294967296 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey in after 4294967296 blocks
debug1: Will attempt key: /home/leen/.ssh/id_rsa RSA SHA256:Prg2XpliU/m8Hnk6gwyLgL0fr+/r6F1LN0AByCyVHOo agent
debug1: Will attempt key: /home/leen/.ssh/id_dsa 
debug1: Will attempt key: /home/leen/.ssh/id_ecdsa 
debug1: Will attempt key: /home/leen/.ssh/id_ecdsa_sk 
debug1: Will attempt key: /home/leen/.ssh/id_ed25519 
debug1: Will attempt key: /home/leen/.ssh/id_ed25519_sk 
debug1: Will attempt key: /home/leen/.ssh/id_xmss 
debug2: pubkey_prepare: done
debug3: send packet: type 5
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering public key: /home/leen/.ssh/id_rsa RSA SHA256:Prg2XpliU/m8Hnk6gwyLgL0fr+/r6F1LN0AByCyVHOo agent
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: password
debug3: start over, passed a different list password
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup password
debug3: remaining preferred: ,keyboard-interactive,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password

NullPointerException at connect

Hi!

First I'd like to thank you for proving this new distribution of Jsch. Very appreciated!!

Using a key (New openssh-v1-private-key format) that has not been added at the server leads to NullPointerException.
Converting the key to PEM format and the error is instead the expected "Auth fail".

Caused by: java.lang.NullPointerException at com.jcraft.jsch.KeyPairDeferred.getKeyTypeName(KeyPairDeferred.java:120) at com.jcraft.jsch.IdentityFile.getAlgName(IdentityFile.java:106)

Full log and key in attached files below.
By the way in the release notes you state that ssh-ed25519 is supported. Is this implementation ripped out of Java 15 or does it require a Java 15 VM to be used?

Kind regards Ulf

FailDbvisNewSSHKey.txt
id_rsa_notTrustedNewSSHFormat.txt

cisco switch connection failed.

Hello, I'm back again. I have two cisco switches that failed to connect. Can you help me see what's the problem?

jsch Version (with bug fixed #90 ) :

<dependency>
            <groupId>com.github.mwiede</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.69</version>
        </dependency>

java version:

java version "1.8.0_221"
Java(TM) SE Runtime Environment (build 1.8.0_221-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.221-b11, mixed mode)

stack trace:

com.jcraft.jsch.JSchException: Session.connect: java.io.IOException: End of IO Stream Read
	at com.jcraft.jsch.Session.connect(Session.java:570)
	at com.topsec.tap.collector.agent.connection.JschConnection.initializeOpen(JschConnection.java:217)
	at com.topsec.tap.collector.agent.connection.JschConnection.open(JschConnection.java:140)
	at com.topsec.tap.collector.agent.connection.Connection$1.execute(Connection.java:68)
	at com.topsec.tap.collector.agent.connection.Connection$1.execute(Connection.java:64)
	at com.topsec.tap.collector.agent.util.TimeoutExecution.call(TimeoutExecution.java:61)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.IOException: End of IO Stream Read
	at com.jcraft.jsch.IO.getByte(IO.java:85)
	at com.jcraft.jsch.Session.read(Session.java:1178)
	at com.jcraft.jsch.Session.connect(Session.java:314)
	... 11 more

ssh info (one):

[root@localhost system]# ssh -vvv 10.28.11.41
OpenSSH_8.6p1, OpenSSL 1.1.1k  25 Mar 2021
debug1: Reading configuration data /etc/ssh/ssh_config
debug2: resolve_canonicalize: hostname 10.28.11.41 is address
debug3: expanded UserKnownHostsFile '~/.ssh/known_hosts' -> '/root/.ssh/known_hosts'
debug3: expanded UserKnownHostsFile '~/.ssh/known_hosts2' -> '/root/.ssh/known_hosts2'
debug1: Authenticator provider $SSH_SK_PROVIDER did not resolve; disabling
debug3: ssh_connect_direct: entering
debug1: Connecting to 10.28.11.41 [10.28.11.41] port 22.
debug3: set_sock_tos: set socket 3 IP_TOS 0x48
debug1: Connection established.
debug1: identity file /root/.ssh/id_rsa type -1
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: identity file /root/.ssh/id_dsa type -1
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: identity file /root/.ssh/id_ecdsa_sk type -1
debug1: identity file /root/.ssh/id_ecdsa_sk-cert type -1
debug1: identity file /root/.ssh/id_ed25519 type -1
debug1: identity file /root/.ssh/id_ed25519-cert type -1
debug1: identity file /root/.ssh/id_ed25519_sk type -1
debug1: identity file /root/.ssh/id_ed25519_sk-cert type -1
debug1: identity file /root/.ssh/id_xmss type -1
debug1: identity file /root/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_8.6
debug1: Remote protocol version 2.0, remote software version Cisco-1.25
debug1: compat_banner: match: Cisco-1.25 pat Cisco-1.* compat 0x60000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to 10.28.11.41:22 as 'root'
debug1: load_hostkeys: fopen /root/.ssh/known_hosts2: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts2: No such file or directory
debug3: order_hostkeyalgs: no algorithms matched; accept original
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
Connection closed by 10.28.11.41 port 22

ssh info (the other one):

[root@localhost system]# ssh -vvv 10.28.11.33
OpenSSH_8.6p1, OpenSSL 1.1.1k  25 Mar 2021
debug1: Reading configuration data /etc/ssh/ssh_config
debug2: resolve_canonicalize: hostname 10.28.11.33 is address
debug3: expanded UserKnownHostsFile '~/.ssh/known_hosts' -> '/root/.ssh/known_hosts'
debug3: expanded UserKnownHostsFile '~/.ssh/known_hosts2' -> '/root/.ssh/known_hosts2'
debug1: Authenticator provider $SSH_SK_PROVIDER did not resolve; disabling
debug3: ssh_connect_direct: entering
debug1: Connecting to 10.28.11.33 [10.28.11.33] port 22.
debug3: set_sock_tos: set socket 3 IP_TOS 0x48
debug1: Connection established.
debug1: identity file /root/.ssh/id_rsa type -1
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: identity file /root/.ssh/id_dsa type -1
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: identity file /root/.ssh/id_ecdsa_sk type -1
debug1: identity file /root/.ssh/id_ecdsa_sk-cert type -1
debug1: identity file /root/.ssh/id_ed25519 type -1
debug1: identity file /root/.ssh/id_ed25519-cert type -1
debug1: identity file /root/.ssh/id_ed25519_sk type -1
debug1: identity file /root/.ssh/id_ed25519_sk-cert type -1
debug1: identity file /root/.ssh/id_xmss type -1
debug1: identity file /root/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_8.6
debug1: Remote protocol version 2.0, remote software version Cisco-1.25
debug1: compat_banner: match: Cisco-1.25 pat Cisco-1.* compat 0x60000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to 10.28.11.33:22 as 'root'
debug1: load_hostkeys: fopen /root/.ssh/known_hosts2: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts2: No such file or directory
debug3: order_hostkeyalgs: no algorithms matched; accept original
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
Connection closed by 10.28.11.33 port 22

Still throws JSchException: invalid privatekey

I run my program using this version to connect remote host by private id_rsa file on mac ,but program run error throws this exception:

com.jcraft.jsch.JSchException: invalid privatekey: [B@9807454
at com.jcraft.jsch.KeyPair.load(KeyPair.java:666)
at com.jcraft.jsch.KeyPair.load(KeyPair.java:563)
at com.jcraft.jsch.IdentityFile.newInstance(IdentityFile.java:40)
at com.jcraft.jsch.JSch.addIdentity(JSch.java:425)
at com.jcraft.jsch.JSch.addIdentity(JSch.java:406)

image

ssh version:
OpenSSH_7.9p1, LibreSSL 2.7.3
The id_rsa file is generated by the command " ssh-keygen -t rsa" , so current version does not support this encryption algorithm ?

ChannelForwardedTCPIP.getPortForwarding(Session) DO NOT CHECK a Session instance.

HI, I'm Park, Jun Hong in Korea.

I have been used a original Jsch and developed a program that maintains a ssh tunneling.

I found a below bug and fixed it for my application.

So, I report this bug and hope to fix this bug for here.

Found Bugs
Recently I've finished a program that provides a remote port forwarding. This program provides 3 functions.

  1. Connects a remote port forwarding.
  2. Disconnects a remote port forwarding connection.
  3. Lists remote port forwarding.

I found a bug that Remote Port Forwardings are mixed, although it's remote server is different from each other.

A method that provides Local Port Forwarding checks a Session instance.

file: com.jcraft.jsch.PortWatcher.java

static String[] getPortForwarding(Session session){
  java.util.Vector foo=new java.util.Vector();
 
  synchronized(pool){
    for(int i=0; i<pool.size(); i++){
      PortWatcher p=(PortWatcher)(pool.elementAt(i));
      if(p.session==session){
        foo.addElement(p.lport+":"+p.host+":"+p.rport);
      }
    }
  }

String[] bar=new String[foo.size()];
for(int i=0; i<foo.size(); i++){
bar[i]=(String)(foo.elementAt(i));
}
return bar;
}
But a method that provides Remote Port Forwardings DO NOT CHECK a Session instance.

file: com.jcraft.jsch.ChannelForwardedTCPIP.java

static String[] getPortForwarding(Session session){
  Vector foo = new Vector();
 
  synchronized(pool){
    for(int i=0; i<pool.size(); i++){
      Config config = (Config)(pool.elementAt(i));
      if(config instanceof ConfigDaemon)
        foo.addElement(config.allocated_rport+":"+config.target+":");
      else
        foo.addElement(config.allocated_rport+":"+config.target+":"+((ConfigLHost)config).lport);
    }
  }
 
  String[] bar=new String[foo.size()];
  for(int i=0; i<foo.size(); i++){
    bar[i]=(String)(foo.elementAt(i));
  }
  return bar;
}

To fix this bug, add codes to check whether config.session is equals to the parameter 'session'.

 static String[] getPortForwarding(Session session) {
        Vector foo = new Vector();
        synchronized (pool) {
            for (int i = 0; i < pool.size(); i++) {
                Config config = (Config) (pool.elementAt(i));
                // (start) [BUG-FIX]: check an instance of a session / Park_Jun_Hong_(parkjunhong77_at_gmail_com): 2020.
                // 5. 25. PM. 5:34:14
                if (!config.session.equals(session)) {
                    continue;
                }
                // (end): 2020. 5. 25. PM. 5:34:14

                if (config instanceof ConfigDaemon)
                    foo.addElement(config.allocated_rport + ":" + config.target + ":");
                else
                    foo.addElement(config.allocated_rport + ":" + config.target + ":" + ((ConfigLHost) config).lport);
            }
        }
        String[] bar = new String[foo.size()];
        for (int i = 0; i < foo.size(); i++) {
            bar[i] = (String) (foo.elementAt(i));
        }
        return bar;
    }

reject HostKey with some servers

Hello!

The issue is starting from 0.1.58

Old hostkeys (ssh-rsa) are not working. Getting the following error in log:

JSCHLogger] (default task-5) kex: server: curve25519-sha256,[email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
JSCHLogger] (default task-5) kex: server: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
JSCHLogger] (default task-5) kex: server: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],aes128-cbc,aes192-cbc,aes256-cbc,blowfish-cbc,cast128-cbc,3des-cbc
JSCHLogger] (default task-5) kex: server: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],aes128-cbc,aes192-cbc,aes256-cbc,blowfish-cbc,cast128-cbc,3des-cbc
JSCHLogger] (default task-5) kex: server: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
JSCHLogger] (default task-5) kex: server: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
JSCHLogger] (default task-5) kex: server: none,[email protected]
JSCHLogger] (default task-5) kex: server: none,[email protected]
JSCHLogger] (default task-5) kex: server: 
JSCHLogger] (default task-5) kex: server: 
JSCHLogger] (default task-5) kex: client: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256
JSCHLogger] (default task-5) kex: client: ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,rsa-sha2-512,rsa-sha2-256,rsa-sha2-512,ssh-rsa
JSCHLogger] (default task-5) kex: client: aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]
JSCHLogger] (default task-5) kex: client: aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]
JSCHLogger] (default task-5) kex: client: [email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
JSCHLogger] (default task-5) kex: client: [email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
JSCHLogger] (default task-5) kex: client: none
JSCHLogger] (default task-5) kex: client: none
JSCHLogger] (default task-5) kex: client: 
JSCHLogger] (default task-5) kex: client: 
JSCHLogger] (default task-5) kex: algorithm: ecdh-sha2-nistp256
JSCHLogger] (default task-5) kex: host key algorithm: ecdsa-sha2-nistp256
JSCHLogger] (default task-5) kex: server->client cipher: aes128-ctr MAC: [email protected] compression: none
JSCHLogger] (default task-5) kex: client->server cipher: aes128-ctr MAC: [email protected] compression: none
JSCHLogger] (default task-5) SSH_MSG_KEX_ECDH_INIT sent
JSCHLogger] (default task-5) expecting SSH_MSG_KEX_ECDH_REPLY
JSCHLogger] (default task-5) Disconnecting from [xxx] port 22

Using host key with type ecdsa-sha2-nistp256 is working. As well, some other sftp servers are working with old host keys - on log I see kex: host key algorithm: rsa-sha2-512

Is it possible to support old host keys? Tried changing different config options with no luck.

UPD: server version which is failing is OpenSSH_7.4

comply with RFC4253 / 4.2 Protocol Version Exchange - missing CR in identification string

Hi,

Recent CISCO devices are complaining against missing CR in identification string:
DAEMON-3-SYSTEM_MSG: error: protocol identification string lack carriage return - dcos_sshd[14616]

Based on RFC4253 section 4.2, identification string must be:
SSH-protoversion-softwareversion SP comments CR LF

Spent very few times on sources but it seems a fix would only need following changes in src/main/java/com/jcraft/jsch/Session.java:
session_fix

Would you kindly review & consider implementing a fix ?
Thank you.

Support for automatic rekeying

Add support for automatic rekeying as recommend by RFC 4253 & RFC 4344.

It is RECOMMENDED that the keys be changed after each gigabyte of
transmitted data or after each hour of connection time, whichever
comes sooner.  However, since the re-exchange is a public key
operation, it requires a fair amount of processing power and should
not be performed too often.
Section 9 of [RFC4253] suggests that SSH implementations rekey after
every gigabyte of transmitted data.  [RFC4253] does not, however,
discuss all the problems that could arise if an SSH implementation
does not rekey frequently enough.  This section serves to strengthen
the suggestion in [RFC4253] by giving firm upper bounds on the
tolerable number of encryptions between rekeying operations.  In
Section 6, we discuss the motivation for these rekeying
recommendations in more detail.

This section makes two recommendations.  Informally, the first
recommendation is intended to protect against possible information
leakage through the MAC tag, and the second recommendation is
intended to protect against possible information leakage through the
block cipher.  Note that, depending on the block length of the
underlying block cipher and the length of the encrypted packets, the
first recommendation may supersede the second recommendation, or vice
versa.
Because of possible information leakage through the MAC tag, SSH
implementations SHOULD rekey at least once every 2**32 outgoing
packets.  More explicitly, after a key exchange, an SSH
implementation SHOULD NOT send more than 2**32 packets before
rekeying again.

SSH implementations SHOULD also attempt to rekey before receiving
more than 2**32 packets since the last rekey operation.  The
preferred way to do this is to rekey after receiving more than 2**31
packets since the last rekey operation.
Because of a birthday property of block ciphers and some modes of
operation, implementations must be careful not to encrypt too many
blocks with the same encryption key.

Let L be the block length (in bits) of an SSH encryption method's
block cipher (e.g., 128 for AES).  If L is at least 128, then, after
rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4)
blocks before rekeying again.  If L is at least 128, then SSH
implementations should also attempt to force a rekey before receiving
more than 2**(L/4) blocks.  If L is less than 128 (which is the case
for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then,
although it may be too expensive to rekey every 2**(L/4) blocks, it
is still advisable for SSH implementations to follow the original
recommendation in [RFC4253]: rekey at least once for every gigabyte
of transmitted data.

Note that if L is less than or equal to 128, then the recommendation
in this subsection supersedes the recommendation in Section 3.1.  If
an SSH implementation uses a block cipher with a larger block size
(e.g., Rijndael with 256-bit blocks), then the recommendations in
Section 3.1 may supersede the recommendations in this subsection
(depending on the lengths of the packets).

Algorithm negotiation fail with 0.1.63

I got com.jcraft.jsch.JSchException: Algorithm negotiation fail when I connect to a server which only support ssh-dss and ssh-rsa.
This problem doesn't happen with 0.1.57.
Are these algorithm no longer supported?

Collaboration with other forks?

There appears to be at least two other JSch forks on Github:

I wonder if it would be worthwhile to attempt to contact those project owners and investigate the possibility of collaborating on a single joint fork?

Getting Algorithm negotiation fail on version 0.1.62

Recently we had requirement to upgrade Jsch to support openSSH 7.8.
We upgraded the jsch to 0.1.62 from maven repo.
However when connecting the session using username, password method we are getting "Algorithm Negotiation Fail" on windows environment.

image

The same piece of code works fine when using Jsch version 0.1.54 jar

Our Environment
OpenJDK 1.8.0_252
Windows Server 2016
Tomcat 8.5.55
Freeftpd version 1.0.13

ssh-ed25519 not available for identity my_key

I use0.1.67.

        ...
	JSch jsch = new JSch();
        jsch.setKnownHosts("src/test/resources/known_hosts");
        jsch.addIdentity("src/test/resources/id_ed25519", "");
        Session session = jsch.getSession(jumpServerUsername, jumpServerHost, 22);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        config.put("Compression", "yes");
        config.put("ConnectionAttempts","2");
        session.setConfig(config);

        session.connect(2500); //<- com.jcraft.jsch.JSchException: Auth fail
	...
	int forwardedPort = session.setPortForwardingL(0, databaseHost, databasePort);

Logging:

PubkeyAcceptedAlgorithms = ssh-ed25519,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,rsa-sha2-512,rsa-sha2-256,ssh-rsa
Signature algorithms unavailable for non-agent identities = [ssh-ed25519, ssh-ed448]
PubkeyAcceptedAlgorithms in server-sig-algs = [ssh-ed25519, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384, ecdsa-sha2-nistp521, rsa-sha2-512, rsa-sha2-256, ssh-rsa]
ssh-ed25519 not available for identity D:\git\repon\***\src\test\resources\id_ed25519
Disconnecting from *.*.** port 22

What am I doing wrong?

Reading Identity file from ~/.ssh/config

Does JSCH reads the Identity file used for a certain jump host?

I have the following in my ~/.ssh/config:

        ForwardAgent yes    
        HostName $hostName    
        IdentityFile ~/.ssh/$newIdentityFile    
        User $USER    

and I get Auth fail when connecting to hosts using this jump host.

jsch with wagon-maven-plugin and ED25519

Hello,

In the past we used wagon-maven-plugin to copy files (war) to a remote host. We used RSA for authentication. Recently we switched to ED25519 which is not supported by jsch, therefore I came across this fork. As mentioned in @mwiede blog post you can simply switch jsch dependencies.
So i tried to replace it in my pom as following:

 <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>wagon-maven-plugin</artifactId>
    <version>1.0</version>
    <dependencies>
        <dependency>
            <groupId>com.github.mwiede</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.69</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.wagon</groupId>
            <artifactId>wagon-ssh</artifactId>
            <version>3.4.3</version>
            <exclusions>
                <exclusion>
                    <groupId>com.jcraft</groupId>
                    <artifactId>jsch</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <configuration>
        <serverId>xxx</serverId>
        <url>scp://blablublub</url>
        <commands>
            <command>ls -l</command>
        </commands>
    </configuration>
</plugin>

Unfortunately it is not working with the following exception:

[ERROR] Failed to execute goal org.codehaus.mojo:wagon-maven-plugin:1.0:sshexec (default-cli) on project fun2: Unable to create a Wagon instance for scp://blablublub: Cannot connect. Reason: invalid privatekey -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:wagon-maven-plugin:1.0:sshexec (default-cli) on project fun2: Unable to create a Wagon instance for scp://blablublub
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:568)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at org.codehaus.classworlds.Launcher.main (Launcher.java:47)
Caused by: org.apache.maven.plugin.MojoExecutionException: Unable to create a Wagon instance for scp://blablublub
    at org.codehaus.mojo.wagon.AbstractWagonMojo.createWagon (AbstractWagonMojo.java:86)
    at org.codehaus.mojo.wagon.AbstractSingleWagonMojo.execute (AbstractSingleWagonMojo.java:63)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:568)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at org.codehaus.classworlds.Launcher.main (Launcher.java:47)
Caused by: org.apache.maven.wagon.authentication.AuthenticationException: Cannot connect. Reason: invalid privatekey
    at org.apache.maven.wagon.providers.ssh.jsch.AbstractJschWagon.openConnectionInternal (AbstractJschWagon.java:148)
    at org.apache.maven.wagon.AbstractWagon.openConnection (AbstractWagon.java:138)
    at org.apache.maven.wagon.AbstractWagon.connect (AbstractWagon.java:238)
    at org.apache.maven.wagon.AbstractWagon.connect (AbstractWagon.java:175)
    at org.codehaus.mojo.wagon.shared.WagonUtils.createWagon (WagonUtils.java:75)
    at org.codehaus.mojo.wagon.AbstractWagonMojo.createWagon (AbstractWagonMojo.java:82)
    at org.codehaus.mojo.wagon.AbstractSingleWagonMojo.execute (AbstractSingleWagonMojo.java:63)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:568)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at org.codehaus.classworlds.Launcher.main (Launcher.java:47)
Caused by: com.jcraft.jsch.JSchException: invalid privatekey
    at com.jcraft.jsch.KeyPair.load (KeyPair.java:772)
    at com.jcraft.jsch.KeyPair.load (KeyPair.java:575)
    at com.jcraft.jsch.IdentityFile.newInstance (IdentityFile.java:40)
    at com.jcraft.jsch.JSch.addIdentity (JSch.java:491)
    at com.jcraft.jsch.JSch.addIdentity (JSch.java:472)
    at org.apache.maven.wagon.providers.ssh.jsch.AbstractJschWagon.openConnectionInternal (AbstractJschWagon.java:144)
    at org.apache.maven.wagon.AbstractWagon.openConnection (AbstractWagon.java:138)
    at org.apache.maven.wagon.AbstractWagon.connect (AbstractWagon.java:238)
    at org.apache.maven.wagon.AbstractWagon.connect (AbstractWagon.java:175)
    at org.codehaus.mojo.wagon.shared.WagonUtils.createWagon (WagonUtils.java:75)
    at org.codehaus.mojo.wagon.AbstractWagonMojo.createWagon (AbstractWagonMojo.java:82)
    at org.codehaus.mojo.wagon.AbstractSingleWagonMojo.execute (AbstractSingleWagonMojo.java:63)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:568)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at org.codehaus.classworlds.Launcher.main (Launcher.java:47)

The exception is the same with com.jcraft.jsch which basically tells that ED25519 is not supported in a pretty bad phrasing.
Maybe you guys have an advise for me what I could try next.

Many thanks in advance.

Support for ssh-agent?

HI,

Thanks for maintaining this project, it really is a great contribution to the software development community!

WIth older version of Jsch, it was possible to use jsch-agent-proxy https://github.com/ymnk/jsch-agent-proxy but that is not actively developed and no longer compatible with newer versions of Jsch (does not even compile due to changes in the Identity interface). I have been able to make it work by changing a few lines of the source code, but it would be wonderful (and definitely more secure) to have a solution which is maintained by somebody with deep domain knowledge.

Are there any plans to implement support for ssh-agent or possibly fork the existing repository, or maybe build something new entirely?

Regards,
Johan Sundman Norberg

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.