At work, I was asked to refactor our SFTP authentication from a couple username/password to an SSH certificate authentication.
So, I’ll post that snippet here, in case of someone need it someday, or just the future me for a future similar task.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
| package main
import (
_ "embed"
"golang.org/x/crypto/ssh"
)
//go:embed resources/id_rsa
var privateKey []byte
var user = "boulou"
func main() {
// here we create a signer base on the private key
signer, err := ssh.ParsePrivateKey(privateKey)
if err != nil {
// TODO: handle error gracefully
panic(err)
}
sshClientConfig := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
// And we have our client config, you can use this to handle an `ssh.Dial` call :
conn, err := ssh.Dial(
"tcp",
"boulou.example:22",
sshClientConfig,
)
if err != nil {
// TODO: handle error gracefully
panic(err)
}
defer func() {
// don't forget to close the connection
if errC := conn.Close(); errC != nil {
panic(errC)
}
}()
}
|