Как я могу устранить ошибку, когда JSch не проходит аутентификацию с открытым ключом, в то время как другие утилиты успешно работают с тем же ключом? - PullRequest
0 голосов
/ 01 декабря 2018

Я использую библиотеку Java JSch для подключения к сайтам SFTP для загрузки файлов.До недавнего времени это работало довольно безупречно.Теперь один сайт SFTP не проходит аутентификацию с открытым ключом;этот же ключ можно использовать для подключения к отказавшему сайту с помощью командной строки sftp (solaris) и FileZilla (Windows).Я думаю, что у меня что-то неправильно настроено, и мне было интересно, кто-нибудь может предложить какое-либо решение этой проблемы.Любая помощь с благодарностью.

Я использую Java 1.8 и JSch v0.54.Вот пример, который терпит неудачу.package jsch_test;

import java.util.Properties;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class Test {
    static {
        JSch.setLogger(new TestLogger());
    }

    public static void main(String [] args) throws JSchException {
        Test test = new Test();
        final String identityFile = "w:/path/to/my/id_rsa";

        // Known-good SFTP site
        //test.connect("test.known-good.site", "username", 22, identityFile);


        // Failing SFTP site
        test.connect("test.failing.site", "differentUsername", 6039, identityFile);
    }

    public void connect(String host, String user, int port, String identityFile) throws JSchException {
        JSch jsch = new JSch();
        jsch.addIdentity(identityFile);

        Session session = jsch.getSession(user, host, port);

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");

        session.setConfig(config);

        try {
            session.connect();
        } finally {
            session.disconnect();
        }

    }

    public static class TestLogger implements com.jcraft.jsch.Logger {
        static java.util.Hashtable<Integer, String> name=new java.util.Hashtable<>();
        static{
            name.put(new Integer(DEBUG), "DEBUG: ");
            name.put(new Integer(INFO), "INFO: ");
            name.put(new Integer(WARN), "WARN: ");
            name.put(new Integer(ERROR), "ERROR: ");
            name.put(new Integer(FATAL), "FATAL: ");
        }

        public boolean isEnabled(int level){
            return true;
        }

        public void log(int level, String message){
            System.err.print(name.get(new Integer(level)));
            System.err.println(message);
        }
    }
}

Вот что регистрируется.

INFO: Connecting to test.failing.site port 6039
INFO: Connection established
INFO: Remote version string: SSH-2.0-Maverick_SSHD
INFO: Local version string: SSH-2.0-JSCH-0.1.54
INFO: CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
INFO: CheckKexes: diffie-hellman-group14-sha1,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521
INFO: CheckSignatures: ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
INFO: SSH_MSG_KEXINIT sent
INFO: SSH_MSG_KEXINIT received
INFO: kex: server: diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha1
INFO: kex: server: ssh-rsa
INFO: kex: server: aes256-cbc,aes192-cbc
INFO: kex: server: aes256-cbc,aes192-cbc
INFO: kex: server: hmac-sha1,hmac-sha1-96
INFO: kex: server: hmac-sha1,hmac-sha1-96
INFO: kex: server: none
INFO: kex: server: none
INFO: kex: server: 
INFO: kex: server: 
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
INFO: kex: client: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
INFO: kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc
INFO: kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc
INFO: kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
INFO: kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
INFO: kex: client: none
INFO: kex: client: none
INFO: kex: client: 
INFO: kex: client: 
INFO: kex: server->client aes192-cbc hmac-sha1 none
INFO: kex: client->server aes192-cbc hmac-sha1 none
INFO: SSH_MSG_KEX_DH_GEX_REQUEST(1024<2048<2048) sent
INFO: expecting SSH_MSG_KEX_DH_GEX_GROUP
INFO: SSH_MSG_KEX_DH_GEX_INIT sent
INFO: expecting SSH_MSG_KEX_DH_GEX_REPLY
INFO: ssh_rsa_verify: signature true
WARN: Permanently added 'test.failing.site' (RSA) to the list of known hosts.
INFO: SSH_MSG_NEWKEYS sent
INFO: SSH_MSG_NEWKEYS received
INFO: SSH_MSG_SERVICE_REQUEST sent
INFO: SSH_MSG_SERVICE_ACCEPT received
INFO: Authentications that can continue: publickey,keyboard-interactive,password
INFO: Next authentication method: publickey
INFO: Authentications that can continue: keyboard-interactive,password
INFO: Next authentication method: keyboard-interactive
INFO: Authentications that can continue: password
INFO: Next authentication method: password
INFO: Disconnecting from test.failing.site port 6039
Exception in thread "main" 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 jsch_test.Test.connect(Test.java:38)
    at jsch_test.Test.main(Test.java:23)

Здесь находится файл журнала из командной строки sftp, с того же компьютера, использующего тот же ключ id_rsa.

sftp -v -oPort=6039 -oIdentityFile=./id_rsa testuser@test.failing.site
Connecting to test.failing.site...
Sun_SSH_1.1.8, SSH protocols 1.5/2.0, OpenSSL 0x100020bf
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Rhosts Authentication disabled, originating port will not be trusted.
debug1: ssh_connect: needpriv 0
debug1: Connecting to test.failing.site [xxx.xxx.xxx.xxx] port 6039.
debug1: Connection established.
debug1: identity file p2idrsa type -1
debug1: Logging to host: test.failing.site
debug1: Local user: timrthy Remote user: testuser
debug1: Remote protocol version 2.0, remote software version Maverick_SSHD
debug1: no match: Maverick_SSHD
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-Sun_SSH_1.1.8
debug1: use_engine is 'yes'
debug1: pkcs11 engine initialized, now setting it as default for RSA, DSA, and symmetric ciphers
debug1: pkcs11 engine initialization complete
debug1: ssh_gssapi_init_ctx(8a218, test.failing.site, 0, 0, ffbff13c)
debug1: GSS-API error while calling GSS_Init_sec_context(): Unspecified GSS failure.  Minor code may provide more information
Server not found in Kerberos database

debug1: Skipping GSS-API mechanism kerberos_v5 (Unspecified GSS failure.  Minor code may provide more information
Server not found in Kerberos database
)
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes192-cbc hmac-sha1 none
debug1: kex: client->server aes192-cbc hmac-sha1 none
debug1: Peer sent proposed langtags, ctos:
debug1: Peer sent proposed langtags, stoc:
debug1: We proposed langtags, ctos: i-default
debug1: We proposed langtags, stoc: i-default
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: dh_gen_key: priv key bits set: 204/384
debug1: bits set: 1031/2048
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'test.failing.site' is known and matches the RSA host key.
debug1: Found key in /export/home/timrthy/.ssh/known_hosts:61
debug1: bits set: 1009/2048
debug1: ssh_rsa_verify: signature correct
debug1: newkeys: mode 1
debug1: set_newkeys: setting new keys for 'out' mode
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: newkeys: mode 0
debug1: set_newkeys: setting new keys for 'in' mode
debug1: SSH2_MSG_NEWKEYS received
debug1: done: ssh_kex2.
debug1: send SSH2_MSG_SERVICE_REQUEST
debug1: got SSH2_MSG_SERVICE_ACCEPT
debug1: Authentications that can continue: password,publickey,keyboard-interactive
debug1: Next authentication method: publickey
debug1: Trying private key: p2idrsa
debug1: read PEM private key done: type RSA
debug1: Authentication succeeded (publickey)
debug1: fd 7 setting O_NONBLOCK
debug1: SSH receive window size: 198720 B
debug1: channel 0: new [client-session]
debug1: send channel open 0
debug1: Entering interactive session.
debug1: ssh_session2_setup: id 0
debug1: Sending subsystem: sftp
debug1: channel request 0: subsystem
debug1: channel 0: open confirm rwindow 0 rmax 34000
sftp>

Внешние соединения с каждой машины в моей сети выглядят так, как будто они приходят с одного и того же IP-адреса, но я продолжил и убедился, что командная строка sftp с моей машины работает, а использование Java + JSch - нет.Командная строка sftp для других сайтов (в настоящее время 4 различных сайта) И Java + JSch работает, поэтому у меня заканчиваются идеи.

Спасибо за вашу помощь.

1 Ответ

0 голосов
/ 03 декабря 2018

Я не уверен, насколько полезным будет этот ответ кому-либо.Оказывается, это была проблема на удаленном сервере.Технические специалисты на стороне сервера сообщили мне, что проблема была исправлена;они не указали, какие изменения они должны были сделать, чтобы решить эту проблему.С моей стороны, протоколирование JSch выглядит так же, за исключением того, что аутентификация с открытым ключом прошла успешно.

Большое спасибо всем, кто посмотрел на это.

...