-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
agent.go
68 lines (61 loc) · 1.78 KB
/
agent.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
package ssh
import (
"net"
"os"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh/agent"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
)
// getAgent attempts to connect to the running SSH agent, returning a newly
// initialized static agent if that fails.
func getAgent(keys []string) (agent.Agent, string, error) {
// Attempt to use the existing SSH agent if it's configured or use the default ssh pair generated.
if authSock := os.Getenv("SSH_AUTH_SOCK"); authSock != "" {
logrus.Debugf("Using SSH_AUTH_SOCK %s to connect to an existing agent", authSock)
if conn, err := net.Dial("unix", authSock); err == nil {
return agent.NewClient(conn), "agent", nil
}
}
return newAgent(keys)
}
// newAgent initializes an SSH Agent with the keys.
// If no keys are provided, it loads all the keys from the user's environment.
func newAgent(keyPaths []string) (agent.Agent, string, error) {
keys, err := loadKeys(keyPaths)
if err != nil {
return nil, "", err
}
ag := agent.NewKeyring()
var errs []error
for name, key := range keys {
if err := ag.Add(agent.AddedKey{PrivateKey: key}); err != nil {
errs = append(errs, errors.Wrapf(err, "failed to add %s to agent", name))
}
logrus.Debugf("Added %s to installer's internal agent", name)
}
if agg := utilerrors.NewAggregate(errs); agg != nil {
return nil, "", agg
}
return ag, "keys", nil
}
func loadKeys(paths []string) (map[string]interface{}, error) {
keys := map[string]interface{}{}
if len(paths) > 0 {
pkeys, err := LoadPrivateSSHKeys(paths)
if err != nil {
return nil, err
}
for k, v := range pkeys {
keys[k] = v
}
}
dkeys, err := defaultPrivateSSHKeys()
if err != nil && len(paths) == 0 {
return nil, err
}
for k, v := range dkeys {
keys[k] = v
}
return keys, nil
}