github.com/openshift/installer@v1.4.17/pkg/gather/ssh/agent.go (about) 1 package ssh 2 3 import ( 4 "net" 5 "os" 6 7 "github.com/pkg/errors" 8 "github.com/sirupsen/logrus" 9 "golang.org/x/crypto/ssh/agent" 10 utilerrors "k8s.io/apimachinery/pkg/util/errors" 11 ) 12 13 // getAgent attempts to connect to the running SSH agent, returning a newly 14 // initialized static agent if that fails. 15 func getAgent(keys []string) (agent.Agent, string, error) { 16 // Attempt to use the existing SSH agent if it's configured or use the default ssh pair generated. 17 if authSock := os.Getenv("SSH_AUTH_SOCK"); authSock != "" { 18 logrus.Debugf("Using SSH_AUTH_SOCK %s to connect to an existing agent", authSock) 19 if conn, err := net.Dial("unix", authSock); err == nil { 20 return agent.NewClient(conn), "agent", nil 21 } 22 } 23 24 return newAgent(keys) 25 } 26 27 // newAgent initializes an SSH Agent with the keys. 28 // If no keys are provided, it loads all the keys from the user's environment. 29 func newAgent(keyPaths []string) (agent.Agent, string, error) { 30 keys, err := loadKeys(keyPaths) 31 if err != nil { 32 return nil, "", err 33 } 34 35 ag := agent.NewKeyring() 36 var errs []error 37 for name, key := range keys { 38 if err := ag.Add(agent.AddedKey{PrivateKey: key}); err != nil { 39 errs = append(errs, errors.Wrapf(err, "failed to add %s to agent", name)) 40 } 41 logrus.Debugf("Added %s to installer's internal agent", name) 42 } 43 if agg := utilerrors.NewAggregate(errs); agg != nil { 44 return nil, "", agg 45 } 46 return ag, "keys", nil 47 } 48 49 func loadKeys(paths []string) (map[string]interface{}, error) { 50 keys := map[string]interface{}{} 51 if len(paths) > 0 { 52 pkeys, err := LoadPrivateSSHKeys(paths) 53 if err != nil { 54 return nil, err 55 } 56 for k, v := range pkeys { 57 keys[k] = v 58 } 59 } 60 dkeys, err := defaultPrivateSSHKeys() 61 if err != nil && len(paths) == 0 { 62 return nil, err 63 } 64 for k, v := range dkeys { 65 keys[k] = v 66 } 67 return keys, nil 68 }