/
ssh.go
108 lines (88 loc) · 2.24 KB
/
ssh.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// Package ssh is based on github.com/crosbymichael/slex/blob/master/ssh.go
package ssh
import (
"io/ioutil"
"net"
"os"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
// ClientConfig stores the configuration
// and the ssh agent to forward authentication requests
type ClientConfig struct {
// agent is the connection to the ssh agent
a agent.Agent
*ssh.ClientConfig
ForwardAgent bool
}
// Session stores the open session and connection to execute a command.
type Session struct {
// conn is the ssh client that started the session.
conn *ssh.Client
*ssh.Session
}
// NewSession creates a new ssh session with the host.
// It forwards authentication to the agent when it's configured.
func (c *ClientConfig) NewSession(host string) (*Session, error) {
conn, err := ssh.Dial("tcp", host, c.ClientConfig)
if err != nil {
return nil, err
}
if c.a != nil && c.ForwardAgent {
if err := agent.ForwardToAgent(conn, c.a); err != nil {
return nil, err
}
}
session, err := conn.NewSession()
// Move this up
if c.a != nil && c.ForwardAgent {
err = agent.RequestAgentForwarding(session)
}
return &Session{
conn: conn,
Session: session,
}, err
}
func agentSigners() (*agent.Agent, []ssh.Signer, error) {
sock, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
if err != nil {
return nil, nil, err
}
a := agent.NewClient(sock)
signers, err := a.Signers()
if err != nil {
return nil, nil, err
}
return &a, signers, nil
}
func pemSigner(file string) (ssh.Signer, error) {
pemBytes, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
return ssh.ParsePrivateKey(pemBytes)
}
// NewClientConfig returns a config using an ssh agent unless ident is not empty.
func NewClientConfig(ident string, user string) (*ClientConfig, error) {
// I think this could be simplified by using PublicKeysCallback
cfg := &ClientConfig{
ClientConfig: &ssh.ClientConfig{
User: user,
},
}
if ident != "" {
s, err := pemSigner(ident)
if err != nil {
return nil, err
}
cfg.ClientConfig.Auth = []ssh.AuthMethod{ssh.PublicKeys(s)}
return cfg, nil
}
a, s, err := agentSigners()
if err != nil {
return nil, err
}
cfg.a = *a
cfg.ClientConfig.Auth = []ssh.AuthMethod{ssh.PublicKeys(s...)}
return cfg, nil
}