Panic: runtime error: invalid memory address or nil pointer dereference

Dear collegues,

I have this small code for establish a ssh connection using private key :

func PublicKeyFile(file string) ssh.AuthMethod {
buffer, err := ioutil.ReadFile(file)
if err != nil {
return nil
}

key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
	return nil
}
return ssh.PublicKeys(key)

}

func main(){

sshConfig := &ssh.ClientConfig{
	User: "My Username",
	Auth: []ssh.AuthMethod{
		PublicKeyFile("$HOME/.ssh/key.pub"),
	},
	HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}

connection, err := ssh.Dial("tcp", "ip:port", sshConfig)
if err != nil {
	panic("Failed to dial source: " + err.Error())
}
   
   
sftp_destination, err := sftp.NewClient(connection)
if err != nil {
	log.Fatal(err)
}	
defer sftp_destination.Close()

}

So, when I execute this code I got a panic runtime error as you can see at the subject of this message. Can I help me, please ?

Hi!

You’re not showing the panic trace, which would tell us where the problem is. So I’m going to just wildly guess.

The

PublicKeyFile("$HOME/.ssh/key.pub")

call will always fail, because Go does no interpret the $HOME shell variable for you. The PublicKeyFile function then returns a nil on any error, essentially ignoring the error, and you’re just taking that result and putting it in the sshConfig. If you then get an ssh connection that will probably fail to authenticate. Depending on what the ssh package does it might fail with a nil pointer dereference.

So in summary, don’t “swallow” errors and return nils. Your PublicKeyFile function should probably return an (ssh.AuthMethod, error) pair and you should check the error before using the AuthMethod.

(Oh, and if you could put your code in a code block, that’d be easier to read.)

Thanks Jakob !
You’re right, the publicKeyFile is returning a nil . Now, I got the error when I attempt to connect to the server:

connection, err := ssh.Dial(“tcp”, “ip:port”, sshConfig)
if err != nil {
panic("Failed to dial source: " + err.Error())
}
I got this error:

panic: Failed to dial source: ssh: handshake failed: ssh: unable to authenticate, attempted methods [publickey none], no supported methods remain

The username and key are right.

I close this issue. Now the problem is not about code, is with keys in the server.
Thanks all ,

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.