SSH Handshake complains about missing host key

Viewed 8387

I'm trying to connect to a remote host and check if a file exist At this stage I'm trying just to connect but I'm getting an error:

2017/08/01 18:16:39 unable to connect: ssh: handshake failed: ssh: required host key was nil

I've tried to find out if others had issues as mine but I just couldn't find.

I understand that I need to check the knowns_hosts somehow in the process but I just can't figure out how...

    var hostKey ssh.PublicKey
    // A public key may be used to authenticate against the remote
    // server by using an unencrypted PEM-encoded private key file.
    //
    // If you have an encrypted private key, the crypto/x509 package
    // can be used to decrypt it.
    key, err := ioutil.ReadFile("/home/user/.ssh/id_rsa")
    if err != nil {
        log.Fatalf("unable to read private key: %v", err)
    }

    // Create the Signer for this private key.
    signer, err := ssh.ParsePrivateKey(key)
    if err != nil {
        log.Fatalf("unable to parse private key: %v", err)
    }

    config := &ssh.ClientConfig{
        User: "user",
        Auth: []ssh.AuthMethod{
            // Use the PublicKeys method for remote authentication.
            ssh.PublicKeys(signer),
        },
        HostKeyCallback: ssh.FixedHostKey(hostKey),
    }

    // Connect to the remote server and perform the SSH handshake.
    client, err := ssh.Dial("tcp", "host.com:22", config)
    if err != nil {
        log.Fatalf("unable to connect: %v", err)
    }
    defer client.Close()
}
2 Answers

I would suggest to use knownhosts subpackage

import knownhosts "golang.org/x/crypto/ssh/knownhosts"

...

hostKeyCallback, err := knownhosts.New("/Users/user/.ssh/known_hosts")
if err != nil {
    log.Fatal(err)
}

...

config := &ssh.ClientConfig{
    User: "user",
    Auth: []ssh.AuthMethod{
        // Use the PublicKeys method for remote authentication.
        ssh.PublicKeys(signer),
    },
    HostKeyCallback: hostKeyCallback,
}

So that you avoid parsing known_hosts yourself...

hth,

Related