Here's an example of how you can use the golang.org/x/crypto/ssh package to connect to a remote server using an ED25519 key and verify the server against its fingerprint:
package main
import (
"crypto/sha256"
"encoding/base64"
"fmt"
"io/ioutil"
"log"
"golang.org/x/crypto/ssh"
)
func main() {
// Load the private key
privateKey, err := ioutil.ReadFile("path/to/private/key")
if err != nil {
log.Fatal(err)
}
// Parse the private key
signer, err := ssh.ParsePrivateKey(privateKey)
if err != nil {
log.Fatal(err)
}
// Set up the SSH client config
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
// Verify the server's fingerprint
fingerprint := ssh.FingerprintSHA256(key)
expectedFingerprint := "SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU"
// Convert the expected fingerprint to bytes
expectedFingerprintBytes, err := base64.StdEncoding.DecodeString(expectedFingerprint[7:])
if err != nil {
return fmt.Errorf("failed to decode expected fingerprint: %v", err)
}
// Hash the expected fingerprint
expectedHash := sha256.Sum256(expectedFingerprintBytes)
// Hash the actual fingerprint
actualHash := sha256.Sum256([]byte(fingerprint))
// Compare the hashes
if expectedHash != actualHash {
return fmt.Errorf("server fingerprint does not match expected value")
}
return nil
},
}
// Connect to the remote server
client, err := ssh.Dial("tcp", "remote.server.com:22", config)
if err != nil {
log.Fatal(err)
}
defer client.Close()
// Run a command on the remote server
session, err := client.NewSession()
if err != nil {
log.Fatal(err)
}
defer session.Close()
output, err := session.CombinedOutput("uname -a")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(output))
}
Here's what's happening in the code:
- We load the private key from a file and parse it using
ssh.ParsePrivateKey.
- We set up the SSH client config with the parsed private key and a custom
HostKeyCallback function.
- In the
HostKeyCallback function, we verify the server's fingerprint by:
- Calculating the fingerprint of the received public key using
ssh.FingerprintSHA256.
- Decoding the expected fingerprint from the given string using
base64.StdEncoding.DecodeString.
- Hashing the expected fingerprint using
sha256.Sum256.
- Hashing the actual fingerprint using
sha256.Sum256.
- Comparing the two hashes. If they don't match, we return an error.
- We connect to the remote server using
ssh.Dial and run a command using client.NewSession.
Note that you should replace path/to/private/key with the actual path to your private key file, and username with the actual username you want to use to connect to the remote server.