forked from bramvdbogaerde/go-scp
/
key.go
90 lines (75 loc) · 2.32 KB
/
key.go
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/* Copyright (c) 2020 Bram Vandenbogaerde
* You may use, distribute or modify this code under the
* terms of the Mozilla Public License 2.0, which is distributed
* along with the source code.
*/
package auth
import (
"io/ioutil"
"net"
"os"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
// PrivateKey Loads a private and public key from "path" and returns a SSH ClientConfig to authenticate with the server
func PrivateKey(username string, path string, keyCallBack ssh.HostKeyCallback) (ssh.ClientConfig, error) {
privateKey, err := ioutil.ReadFile(path)
if err != nil {
return ssh.ClientConfig{}, err
}
signer, err := ssh.ParsePrivateKey(privateKey)
if err != nil {
return ssh.ClientConfig{}, err
}
return ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: keyCallBack,
}, nil
}
// Creates the configuration for a client that authenticates with a password protected private key
func PrivateKeyWithPassphrase(username string, passpharase []byte, path string, keyCallBack ssh.HostKeyCallback) (ssh.ClientConfig, error) {
privateKey, err := ioutil.ReadFile(path)
if err != nil {
return ssh.ClientConfig{}, err
}
signer, err := ssh.ParsePrivateKeyWithPassphrase(privateKey, passpharase)
if err != nil {
return ssh.ClientConfig{}, err
}
return ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: keyCallBack,
}, nil
}
// Creates a configuration for a client that fetches public-private key from the SSH agent for authentication
func SshAgent(username string, keyCallBack ssh.HostKeyCallback) (ssh.ClientConfig, error) {
socket := os.Getenv("SSH_AUTH_SOCK")
conn, err := net.Dial("unix", socket)
if err != nil {
return ssh.ClientConfig{}, err
}
agentClient := agent.NewClient(conn)
return ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.PublicKeysCallback(agentClient.Signers),
},
HostKeyCallback: keyCallBack,
}, nil
}
// Creates a configuration for a client that authenticates using username and password
func PasswordKey(username string, password string, keyCallBack ssh.HostKeyCallback) (ssh.ClientConfig, error) {
return ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.Password(password),
},
HostKeyCallback: keyCallBack,
}, nil
}