-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
78 lines (70 loc) · 1.71 KB
/
auth.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
package gosh
import (
"errors"
"net"
"os"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
// Auth returns a single ssh.AuthMethod.
func Auth(opts *Options) (ssh.AuthMethod, error) {
var (
auth ssh.AuthMethod
err error
)
if opts.UseAgent && HasAgent() {
if auth, err = Agent(); err == nil {
return auth, nil
}
}
if opts.Key != "" {
if auth, err = Key(opts.Key, opts.KeyPassphrase); err == nil {
return auth, nil
}
}
if opts.Password != "" {
auth = Password(opts.Password)
return auth, nil
}
return nil, errors.New("no auth method")
}
// HasAgent checks if ssh agent exists.
func HasAgent() bool {
return os.Getenv("SSH_AUTH_SOCK") != ""
}
// Agent returns ssh.AuthMethod of ssh agent, (Unix systems only).
func Agent() (ssh.AuthMethod, error) {
if !HasAgent() {
return nil, errors.New("no agent")
}
sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
if err != nil {
return nil, err
}
return ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers), nil
}
// Password returns ssh.AuthMethod of password.
func Password(pass string) ssh.AuthMethod {
return ssh.Password(pass)
}
// Key returns ssh.AuthMethod from private key file.
func Key(sshkey string, passphrase string) (ssh.AuthMethod, error) {
signer, err := GetSigner(sshkey, passphrase)
if err != nil {
return nil, err
}
return ssh.PublicKeys(signer), nil
}
// GetSigner returns ssh.Signer from private key file.
func GetSigner(sshkey, passphrase string) (signer ssh.Signer, err error) {
data, err := os.ReadFile(sshkey)
if err != nil {
return
}
if passphrase != "" {
signer, err = ssh.ParsePrivateKeyWithPassphrase(data, []byte(passphrase))
} else {
signer, err = ssh.ParsePrivateKey(data)
}
return
}