I need to initiate an ssh connection to a remote host given its public RSA key. The code I have so far is the following
func sftpClient(host, port, user, pass string) (*sftp.Client, error) {
var authMethod ssh.AuthMethod
if strings.Index(pass, "-----BEGIN RSA PRIVATE KEY-----") == 0 {
signer, err := ssh.ParsePrivateKey([]byte(pass))
if err != nil {
return nil, err
}
authMethod = ssh.PublicKeys(signer)
} else if strings.Index(pass, "---- BEGIN SSH2 PUBLIC KEY ----") == 0 {
publicKey, err := ssh.ParsePublicKey([]byte(pass))
if err != nil {
return nil, err
}
authMethod = ???
} else {
authMethod = ssh.Password(pass)
}
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{authMethod},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Config: ssh.Config{
Ciphers: []string{
// some ciphers here
},
},
}
conn, err := ssh.Dial("tcp", host ":" port, config)
if err != nil {
return nil, err
}
client, err := sftp.NewClient(conn)
if err != nil {
return nil, err
}
return client, nil
}
The password based authentication and the private key based authentication work just fine since the ssh library provides these wrappers (ssh.Password
and ssh.PublicKeys
which create some sort of AuthMethod
). I have not tried a lot since I could not find a lot of options:
authMethod = ssh.NewPublicKey(publicKey)
authMethod = publicKey
None of them work.
I also tried to parse the public key using a different method but this also fails. The method I used was ssh.ParseAuthorizedKey
but this - similar to the ss.ParsePublicKey
return a PublicKey
which cannot be used as an authentication method apparently.
So my question is: How can I initiate an ssh client on Go using a given public RSA key?
CodePudding user response:
How can I initiate an ssh client on Go using a given public RSA key?
You can't use a public key to authenticate an ssh client. You give the public key to the server, then the client uses the private key to authenticate.
The value of ssh key authentication is that the private key never leaves the system; nothing sensitive has to be transferred across the wire.