JSchException: UnknownHostKey
Asked Answered
E

6

2

I'm trying to use Jsch to establish an SSH connection in Java. I have set "StrictHostKeyChecking" to yes. I understand that the hostkey of the server has to be obtained before hand and store in the hostkey file before the first attempt to connect to the server. How can I get the HostKey of the server. My code produces the following exception:

com.jcraft.jsch.JSchException: UnknownHostKey: ASY-PC RSA key fingerprint is 22:fb:ee:fe:18:cd:aa:9a:9c:78:89:9f:b4:78:75:b4

How can I make connection with StrictHostKeyChecking Yes. Here is my code.

package sshexample;

import com.jcraft.jsch.*;
import java.io.*;

public class SSHexample 
{
public static void main(String[] args) 
{
    String user = "user";
    String password = "password";
    String host = "192.168.100.103";
    int port=22;
    try
    {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "yes");
        System.out.println("Establishing Connection...");
        session.connect();
        System.out.println("Connection established.");
        System.out.println("Crating SFTP Channel.");
        ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
        sftpChannel.connect();
}catch(Exception e) {
e.printStackTrace();
}
}
Eyas answered 28/9, 2013 at 4:3 Comment(3)
I think it's widely discussed and already answered with possible solutions in #2003919 ?Couscous
Thanx for reply ..But There is no any solution for make connection with StrictHostKeyChecking Yes...I want make connection with check Host key..Eyas
check comments other than accepted, it tells you how to set known hosts file.Couscous
Y
11

You have to supply a KnownHostKeys file by calling following function

jsch.setKnownHosts(new FileInputStream(knownHostsFile));

this file should have all the the known hosts' fingerprints separated by new lines.

for example

hostname,10.1.1.120, ssh-rsa AAAAC3NzaC1yc2EAAAADAQABAAABAQCi5b647581SwC0uUDQw1ENjKSz3rhJMRRZEgIjHylvF4fbuAEzj645YoAf9SItb51MhetFAJrq98jYsHpedSm3IoMG+aR/P1CjsBz1RtJKlfR2NfYDCZ7Dyx11P8FnJbwbYif/GeG0xEujekwF1pyL0tNPmf0H4/GPR4mwrv/llGlB3Lo3BzxrGtl4f4X/oSHDoo7FrQkDwqOfeSM++3vPPHxyVO5zhFJ5u9f7M/uuxUeHS+YS5JWAI7NLXKgbiM9dluGzZU/6Awo3ux4x5ojL+kf29JEVxK+o6GfW2bIW+LhgIGZNThnN5nHzBVfNNHvQ7KC5ic0h2z2gbVpwJr1h

you can obtain this key from server by using any sftp client however following command may help if you are using linux or unix

ssh-keyscan -t rsa 10.1.1.120
Yettayetti answered 29/5, 2014 at 2:20 Comment(0)
G
3

After a few minutes of testing i found a solution for this. If you don't want to use the default knownHost File, just create your own

This how the file could look:

192.168.0.1 ssh-rsa
AAAAC3NzaC1yc2EAAAADAQABAAABAQCi5b647581SwC0uUDQw1ENjKSz3rhJMRRZEgIjHylvF4fbuAEzj645YoAf9SI
tb51MhetFAJrq98jYsHpedSm3IoMG+aR/P1CjsBz1RtJKlfR2NfYDCZ7Dyx11P8FnJbwbYif
/GeG0xEujekwF1pyL0tNPmf0H4/GPR4mwrv/llGlB3Lo3BzxrGtl4f4X
/oSHDoo7FrQkDwqOfeSM++3vPPHxyVO5zhFJ5u9f7M/uuxUeHS+YS5JWAI7NLXKgbiM9dluGzZU
/6Awo3ux4x5ojL+kf29JEVxK+o6GfW2bIW+LhgIGZNThnN5nHzBVfNNHvQ7KC5ic0h2z2gbVpwJr1h

And all those entries are separated by new lines. You get the RSA key that you want by asking your session:

session=null;
com.jcraft.jsch.Channel channel =null;
try{
    ssh=new JSch();
    ssh.setKnownHosts("test");
    session=ssh.getSession(userTextField.getText(),ip,22);
    session.setPassword(passwordField1.getText());

    System.out.println(session.getHostKey());
    session.connect();
    channel=session.openChannel("sftp");
    channel.connect();
    ChannelSftp sftp=(ChannelSftp) channel;
    System.out.println(sftp.getHome());
    for (Object o : sftp.ls(sftp.getHome())) {
        System.out.println(((ChannelSftp.LsEntry)o).getFilename());
    }

    } catch (JSchException e1) {
        e1.printStackTrace();
        addHost(session.getHostKey().getKey());
    } catch (SftpException e1) {
        e1.printStackTrace();
    }
}

private void addHost(String key){
    try {
        FileWriter tmpwriter=new FileWriter("test",true);

            tmpwriter.append(ip + " ssh-rsa " + key+"\n");
            System.out.println(ip + " ssh-rsa " + key);

        tmpwriter.flush();
        tmpwriter.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

So session.getHostKey().getKey() is what you want to call to get the key.

You also need to call session.connect(); before you ask for the key and handle it in the catch.

Gassaway answered 15/7, 2014 at 20:36 Comment(2)
What is the second line in the host file? How is it generated?Mercymerdith
@Mercymerdith it is very simple to get it. I have mentioned it in my answer below - #19063615Misguidance
M
2

As most the of the answers suggest you have to provide know host file but fail to address how to get it. You simply need to SSH to the host.

Eg ssh [email protected]

when prompted provide password. For first time connection it will you to save the hosts ssh key fingerprint. Once you are connected you can find your known_host file at

user/.ssh/known_hosts

For me on windows path is C:\Users\athakur\.ssh\known_hosts. You can directly use this file. Or edit the file and pick up entry from it corresponding to your IP address which would look something like

192.168.100.103 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA1UsgiLH5hjIScZlqPA4kNhPoXAX00mMv65N8qTvYd1D1M5DwWtTTcxK4w0wGKKVA7RERzWbtjPpSomJwT1LofZr+qafLdiEvhirIXVYHSWZqp6zTJW0jzk3p07ugjoHV3YUWKDzOaiFuOMslt8hD7pZv8nhOYfxBZdsVHdukYRP8MADXC0ZgOD5ZYZ0EglaQJYPG7n73PSMZWZT/oafUcx6bFiRF4QsXaguWuu6umX9gaV7VvoyMJg+kxPAKnGDFY7If61AG7vAchUUhlQ44SB1FFr25y+qeUg2NGqAxH/Z/ZAfvZ+pDv3Cd9s+KCnEIqxyxY/sPQ2zCvwf0Z9fTeQ==

Note : Host machines SSH fingerprint (based on hosts public key that you can find at /etc/ssh/ssh_host_rsa_key.pub) may change in SSH is reinstalled in that machine. Or you may encounter MIM attack (even it is for testing sake). In such cases you will have to pick new entry in same way mentioned above.

Misguidance answered 21/7, 2015 at 15:54 Comment(1)
better if you just use this ssh-keyscan -t rsa 10.1.1.120Yettayetti
C
1

Maybe it's no more relevant but in my case, the similar problem was happened with docker-compose.yml in container, that was build from spring-boot application that 100 % worked locally

config-service:
    image: <host>/<bla>-config-service:<version>
    hostname: config-service
    ports:
        - 3000:3000
    depends_on:
        - discovery
    environment:
        - CONSUL_HOST=discovery
        - CONSUL_PORT=<port> 
        - CONFIG_GIT_URI=git@<host>:<group>/<repository>.git
        - CONFIG_GIT_BRANCH=development
    volumes:
        - ~/.ssh/:/root/.ssh/:ro

Solution was to apply hack on ~/.ssh folder.

chcon -Rt svirt_sandbox_file_t ~/.ssh

After that I suppose volumes was correctly mapped between docker container and local machine, and described exception was gone.

Cornucopia answered 6/2, 2018 at 12:42 Comment(0)
S
0

Based on @nothing-to-know answer, the following method can be very handy:

public static String getHostKey(String hostName, int port, String userName, char[] password) {
    JSch ssh;
    Session session = null;
    String hostKey = "";
    try {
        ssh = new JSch();
        session = ssh.getSession(userName, hostName, port);
        session.setPassword(new String(password));
        if (session.getHostKey() != null) {
            hostKey = session.getHostKey().getHost() + " " + session.getHostKey().getType() + " " + session.getHostKey().getKey();
        }
        session.connect();
    } catch (JSchException e1) {
        hostKey = session.getHostKey().getHost() + " " + session.getHostKey().getType() + " " + session.getHostKey().getKey();
    } finally {
        session.disconnect();
        return hostKey;
    }
}
Stickney answered 6/7, 2022 at 5:27 Comment(0)
S
0

using ssh-keyscan -t rsa 10.1.1.120 works for me

Severson answered 7/5 at 11:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.