package conn import ( "context" "errors" "fmt" "io" "net" "os" "strings" "sync" "sync/atomic" "time" "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/agent" ) // agentConn is the process-wide connection to ssh-agent (N-P2-1: the old // code opened a new socket per connect and never closed it). It is opened on // first use, reopened after an error, and closed by dialer.close. type agentConn struct { sock string mu sync.Mutex c net.Conn ag agent.ExtendedAgent dials atomic.Int32 // sockets opened, for tests } // signers returns the agent's keys; no agent (or an agent error) yields nil. func (a *agentConn) signers() []ssh.Signer { if a == nil || a.sock == "" { return nil } a.mu.Lock() defer a.mu.Unlock() if a.ag == nil { c, err := net.DialTimeout("unix", a.sock, 2*time.Second) if err != nil { return nil } a.dials.Add(1) a.c, a.ag = c, agent.NewClient(c) } ss, err := a.ag.Signers() if err != nil { a.c.Close() a.c, a.ag = nil, nil return nil } return ss } func (a *agentConn) close() { if a == nil { return } a.mu.Lock() defer a.mu.Unlock() if a.c != nil { a.c.Close() a.c, a.ag = nil, nil } } // authMethods builds the auth chain (N-P2-2): public keys (explicit // IdentityFiles, then agent keys, then default key files), password (stored // or asked), keyboard-interactive (questions shown as they are, so 2FA // works). x/crypto tries each method name once, so all keys go into one // publickey method. func (d *dialer) authMethods(ctx context.Context, ep Endpoint, prompt func(func() error) error) []ssh.AuthMethod { methods := []ssh.AuthMethod{ssh.PublicKeysCallback(func() ([]ssh.Signer, error) { return d.signers(ctx, ep, prompt), nil })} p := d.opts.Prompter storedUsed := false // the handshake runs auth sequentially if ep.Password != "" || p != nil { methods = append(methods, ssh.PasswordCallback(func() (string, error) { if ep.Password != "" && !storedUsed { storedUsed = true return ep.Password, nil } if p == nil { return "", errors.New("password rejected") } var pw string err := prompt(func() error { var err error pw, err = p.Password(ctx, ep) return err }) return pw, err })) methods = append(methods, ssh.KeyboardInteractive(func(name, instruction string, qs []string, echo []bool) ([]string, error) { if len(qs) == 0 { return nil, nil } // A lone hidden question is the server's password prompt. if ep.Password != "" && !storedUsed && len(qs) == 1 && !echo[0] { storedUsed = true return []string{ep.Password}, nil } if p == nil { return nil, errors.New("keyboard-interactive: no way to ask the user") } instr := strings.TrimSpace(strings.TrimSpace(name) + "\n" + strings.TrimSpace(instruction)) var answers []string err := prompt(func() error { var err error answers, err = p.KeyboardInteractive(ctx, ep, instr, qs, echo) return err }) if err == nil && len(answers) != len(qs) { err = fmt.Errorf("keyboard-interactive: %d answers for %d questions", len(answers), len(qs)) } return answers, err })) } return methods } func (d *dialer) signers(ctx context.Context, ep Endpoint, prompt func(func() error) error) []ssh.Signer { var out []ssh.Signer seen := map[string]bool{} add := func(s ssh.Signer) { if s == nil { return } k := string(s.PublicKey().Marshal()) if !seen[k] { seen[k] = true out = append(out, s) } } agentKeys := d.agent.signers() inAgent := make(map[string]ssh.Signer, len(agentKeys)) for _, s := range agentKeys { inAgent[string(s.PublicKey().Marshal())] = s } for _, p := range ep.IdentityFiles { add(d.loadKey(ctx, p, inAgent, prompt)) } if !ep.IdentitiesOnly { for _, s := range agentKeys { add(s) } for _, p := range d.opts.DefaultIdentityFiles { add(d.loadKey(ctx, p, inAgent, prompt)) } } return out } // loadKey reads a private key. An encrypted key whose public half is known // (embedded in the OpenSSH format or in path.pub) becomes a lazySigner: the // passphrase is asked only if the server accepts the key. A key already // unlocked in the agent is used from there. func (d *dialer) loadKey(ctx context.Context, path string, inAgent map[string]ssh.Signer, prompt func(func() error) error) ssh.Signer { data, err := os.ReadFile(path) if err != nil { return nil } s, err := ssh.ParsePrivateKey(data) if err == nil { return s } var pm *ssh.PassphraseMissingError if !errors.As(err, &pm) { d.warnf("identity %s: %v", path, err) return nil } pub := pm.PublicKey if pub == nil { if b, err := os.ReadFile(path + ".pub"); err == nil { pub, _, _, _, _ = ssh.ParseAuthorizedKey(b) } } if pub != nil { if as := inAgent[string(pub.Marshal())]; as != nil { return as } } if d.opts.Prompter == nil { return nil } ls := &lazySigner{pub: pub, path: path, pem: data, ask: func() ([]byte, error) { var pass []byte err := prompt(func() error { var err error pass, err = d.opts.Prompter.Passphrase(ctx, path) return err }) return pass, err }} if pub == nil { // Without the public half the key cannot be offered lazily. if _, err := ls.load(); err != nil { d.warnf("identity %s: %v", path, err) return nil } ls.pub = ls.s.PublicKey() } return ls } // lazySigner decrypts a passphrase-protected key on first Sign. type lazySigner struct { pub ssh.PublicKey path string pem []byte ask func() ([]byte, error) once sync.Once s ssh.AlgorithmSigner err error } const passphraseAttempts = 3 func (l *lazySigner) load() (ssh.AlgorithmSigner, error) { l.once.Do(func() { for i := 0; i < passphraseAttempts; i++ { pass, err := l.ask() if err != nil { l.err = err return } s, err := ssh.ParsePrivateKeyWithPassphrase(l.pem, pass) clear(pass) if err != nil { l.err = fmt.Errorf("identity %s: %w", l.path, err) continue } as, ok := s.(ssh.AlgorithmSigner) if !ok { l.err = fmt.Errorf("identity %s: unsupported key type", l.path) return } l.s, l.err = as, nil return } }) return l.s, l.err } func (l *lazySigner) PublicKey() ssh.PublicKey { return l.pub } func (l *lazySigner) Sign(r io.Reader, data []byte) (*ssh.Signature, error) { s, err := l.load() if err != nil { return nil, err } return s.Sign(r, data) } func (l *lazySigner) SignWithAlgorithm(r io.Reader, data []byte, algo string) (*ssh.Signature, error) { s, err := l.load() if err != nil { return nil, err } return s.SignWithAlgorithm(r, data, algo) }