feat(ssh): add conn dialer with bounded handshake, host keys and auth chain (2B.2)

The whole handshake (TCP, kex, auth, SFTP init) runs under a deadline
that ctx cancellation cuts short, and a late client is closed (N-P1-3).
HostKeyAlgorithms come from known_hosts (N-P1-4); unknown and changed
keys go to a Prompter (N-P2-14). Auth tries identity files, then agent
keys over one shared agent connection, then default keys, password and
keyboard-interactive through the Prompter (N-P2-1, N-P2-2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-31 23:33:26 +03:00
parent 8584a638f1
commit 94002e286f
9 changed files with 1720 additions and 0 deletions

263
internal/ssh/conn/auth.go Normal file
View file

@ -0,0 +1,263 @@
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)
}

235
internal/ssh/conn/dial.go Normal file
View file

@ -0,0 +1,235 @@
package conn
import (
"context"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"sync"
"sync/atomic"
"time"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
// DefaultHandshakeTimeout bounds TCP connect + kex + auth + SFTP init.
const DefaultHandshakeTimeout = 20 * time.Second
// ErrHandshakeTimeout: the server accepted TCP but did not finish the
// handshake in time (N-P1-3).
var ErrHandshakeTimeout = errors.New("ssh handshake timed out")
// DialOptions configures how connections are established.
type DialOptions struct {
Prompter Prompter
// HandshakeTimeout covers the whole path TCP + kex + auth + SFTP init,
// excluding time spent waiting for the Prompter. Default 20s.
HandshakeTimeout time.Duration
// Home is the home directory for the default known_hosts and identity
// files ("" = os.UserHomeDir()).
Home string
// KnownHostsFiles are read in order. nil means Home/.ssh/known_hosts and
// /etc/ssh/ssh_known_hosts.
KnownHostsFiles []string
// KnownHostsWrite receives AcceptAndSave lines. "" means the first of
// KnownHostsFiles (the default user file). Set to "-" for memory only.
KnownHostsWrite string
// AgentSocket is the ssh-agent socket. "" means $SSH_AUTH_SOCK; "-"
// disables the agent.
AgentSocket string
// DefaultIdentityFiles are tried when the endpoint does not set
// IdentitiesOnly. nil means Home/.ssh/id_{ed25519,ecdsa,rsa}.
DefaultIdentityFiles []string
// Warn receives non-fatal problems (host key kept in memory only,
// unreadable identity file). May be nil.
Warn func(msg string)
}
func (o DialOptions) withDefaults() DialOptions {
if o.HandshakeTimeout <= 0 {
o.HandshakeTimeout = DefaultHandshakeTimeout
}
if o.Home == "" {
o.Home, _ = os.UserHomeDir()
}
ssh := filepath.Join(o.Home, ".ssh")
if o.KnownHostsFiles == nil {
o.KnownHostsFiles = []string{filepath.Join(ssh, "known_hosts"), "/etc/ssh/ssh_known_hosts"}
}
switch o.KnownHostsWrite {
case "":
if len(o.KnownHostsFiles) > 0 {
o.KnownHostsWrite = o.KnownHostsFiles[0]
}
case "-":
o.KnownHostsWrite = ""
}
switch o.AgentSocket {
case "":
o.AgentSocket = os.Getenv("SSH_AUTH_SOCK")
case "-":
o.AgentSocket = ""
}
if o.DefaultIdentityFiles == nil {
for _, n := range []string{"id_ed25519", "id_ecdsa", "id_rsa"} {
o.DefaultIdentityFiles = append(o.DefaultIdentityFiles, filepath.Join(ssh, n))
}
}
return o
}
// dialer establishes connections. One per Pool (i.e. per process): it owns
// the shared agent connection and the session-trusted host keys.
type dialer struct {
opts DialOptions
hosts *knownHosts
agent *agentConn
dials atomic.Int64 // successful TCP connects, for tests
}
func newDialer(o DialOptions) *dialer {
o = o.withDefaults()
return &dialer{
opts: o,
hosts: newKnownHosts(o.KnownHostsFiles, o.KnownHostsWrite, o.Warn),
agent: &agentConn{sock: o.AgentSocket},
}
}
func (d *dialer) close() { d.agent.close() }
func (d *dialer) warnf(format string, args ...any) {
if d.opts.Warn != nil {
d.opts.Warn(fmt.Sprintf(format, args...))
}
}
// link is one established generation of a connection.
type link struct {
ssh *ssh.Client
sftp *sftp.Client
id HostIdentity
serverVersion string
}
func (l *link) close() {
l.sftp.Close()
l.ssh.Close()
}
// deadlineGate applies the handshake deadline to the raw connection and
// pauses it while the Prompter waits for the user.
type deadlineGate struct {
nc net.Conn
timeout time.Duration
mu sync.Mutex
done bool // handshake finished: never touch deadlines again
}
func (g *deadlineGate) arm() {
g.mu.Lock()
defer g.mu.Unlock()
if !g.done {
g.nc.SetDeadline(time.Now().Add(g.timeout))
}
}
func (g *deadlineGate) finish() {
g.mu.Lock()
defer g.mu.Unlock()
g.done = true
g.nc.SetDeadline(time.Time{})
}
func (g *deadlineGate) prompt(fn func() error) error {
g.mu.Lock()
if !g.done {
g.nc.SetDeadline(time.Time{})
}
g.mu.Unlock()
defer g.arm()
return fn()
}
// sftpOptions: concurrent reads/writes so a transfer is not one packet per
// RTT (N-P1-6).
var sftpOptions = []sftp.ClientOption{
sftp.UseConcurrentWrites(true),
sftp.UseConcurrentReads(true),
sftp.MaxConcurrentRequestsPerFile(64),
}
// dial connects, verifies the host key, authenticates and starts SFTP.
// Cancelling ctx closes the socket at once; if the handshake still
// completes, the late client is closed here, never leaked (N-P1-3).
func (d *dialer) dial(ctx context.Context, ep Endpoint) (*link, error) {
timeout := d.opts.HandshakeTimeout
tcpTimeout := timeout
if ep.ConnectTimeout > 0 && ep.ConnectTimeout < tcpTimeout {
tcpTimeout = ep.ConnectTimeout
}
addr := ep.Addr()
nd := net.Dialer{Timeout: tcpTimeout}
nc, err := nd.DialContext(ctx, "tcp", addr)
if err != nil {
if ctx.Err() != nil {
return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err())
}
return nil, fmt.Errorf("connect %s: %w", ep.Label(), err)
}
d.dials.Add(1)
gate := &deadlineGate{nc: nc, timeout: timeout}
gate.arm()
stop := context.AfterFunc(ctx, func() { nc.Close() })
var idMu sync.Mutex
var id HostIdentity
onKey := func(h HostIdentity) {
idMu.Lock()
defer idMu.Unlock()
if id.KeyType == "" {
id = h
}
}
cfg := &ssh.ClientConfig{
User: ep.User,
Auth: d.authMethods(ctx, ep, gate.prompt),
HostKeyCallback: d.hosts.callback(ctx, ep, d.opts.Prompter, gate.prompt, onKey),
HostKeyAlgorithms: d.hosts.algorithms(addr),
}
fail := func(err error) (*link, error) {
stop()
nc.Close()
if ctx.Err() != nil {
return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err())
}
if errors.Is(err, os.ErrDeadlineExceeded) {
return nil, fmt.Errorf("connect %s: %w after %v", ep.Label(), ErrHandshakeTimeout, timeout)
}
return nil, fmt.Errorf("connect %s: %w", ep.Label(), err)
}
sc, chans, reqs, err := ssh.NewClientConn(nc, addr, cfg)
if err != nil {
return fail(err)
}
client := ssh.NewClient(sc, chans, reqs)
sc2, err := sftp.NewClient(client, sftpOptions...)
if err != nil {
client.Close()
return fail(fmt.Errorf("sftp: %w", err))
}
l := &link{ssh: client, sftp: sc2, serverVersion: string(client.ServerVersion())}
if !stop() {
// ctx fired while we were finishing: the caller is gone.
l.close()
return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err())
}
gate.finish()
idMu.Lock()
l.id = id
idMu.Unlock()
return l, nil
}

View file

@ -0,0 +1,452 @@
package conn
import (
"bytes"
"context"
"crypto/rsa"
"errors"
"math/big"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"golang.org/x/crypto/ssh"
"vcom/internal/testutil/sshtest"
)
// N-P1-3: the server accepts TCP and then goes silent; the dial must fail
// within HandshakeTimeout (+1s slack), not hang.
func TestHandshakeTimeout(t *testing.T) {
noLeak(t, func(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := sshtest.NewProxy(t, srv.Addr)
px.Freeze(true)
const timeout = 300 * time.Millisecond
d := e.dialer(DialOptions{HandshakeTimeout: timeout})
start := time.Now()
l, err := d.dial(context.Background(), endpointFor(px.Addr, srv.Password))
el := time.Since(start)
if err == nil {
l.close()
t.Fatal("dial through a frozen proxy succeeded")
}
if !errors.Is(err, ErrHandshakeTimeout) {
t.Errorf("err = %v, want ErrHandshakeTimeout", err)
}
if el > timeout+time.Second {
t.Errorf("dial took %v, want <= %v", el, timeout+time.Second)
}
px.Freeze(false)
})
}
// N-P1-3: cancelling ctx mid-handshake returns at once; once the link
// unfreezes nothing is left behind (no client, no goroutines).
func TestDialCancelClosesLateClient(t *testing.T) {
noLeak(t, func(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := sshtest.NewProxy(t, srv.Addr)
px.Freeze(true)
d := e.dialer(DialOptions{HandshakeTimeout: 10 * time.Second})
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(100*time.Millisecond, cancel)
start := time.Now()
l, err := d.dial(ctx, endpointFor(px.Addr, srv.Password))
if err == nil {
l.close()
t.Fatal("cancelled dial succeeded")
}
if !errors.Is(err, context.Canceled) {
t.Errorf("err = %v, want context.Canceled", err)
}
if el := time.Since(start); el > time.Second {
t.Errorf("cancel took %v", el)
}
px.Freeze(false)
// The proxy forwards the buffered handshake now; the server must see
// the client gone and drop the connection.
time.Sleep(100 * time.Millisecond)
})
}
// A prompt answered after the caller gave up must not produce a live client.
func TestDialCancelDuringPrompt(t *testing.T) {
noLeak(t, func(t *testing.T) {
e := newEnv(t)
srv := sshtest.Start(t, sshtest.Options{})
ctx, cancel := context.WithCancel(context.Background())
p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) {
cancel()
time.Sleep(50 * time.Millisecond)
return AcceptOnce, nil // ignores ctx on purpose
}}
d := e.dialer(DialOptions{Prompter: p})
l, err := d.dial(ctx, endpointFor(srv.Addr, srv.Password))
if err == nil {
l.close()
t.Fatal("dial succeeded after cancel")
}
if !errors.Is(err, context.Canceled) {
t.Errorf("err = %v", err)
}
})
}
// The deadline is paused while the Prompter waits for the user.
func TestHandshakeDeadlinePausedDuringPrompt(t *testing.T) {
e := newEnv(t)
srv := sshtest.Start(t, sshtest.Options{})
p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) {
time.Sleep(400 * time.Millisecond)
return AcceptOnce, nil
}}
d := e.dialer(DialOptions{Prompter: p, HandshakeTimeout: 200 * time.Millisecond})
l, err := d.dial(context.Background(), endpointFor(srv.Addr, srv.Password))
if err != nil {
t.Fatalf("slow user answer must not time out the handshake: %v", err)
}
l.close()
}
// Ported from the testbed (B9), N-P1-4: known_hosts has only the ed25519
// key, the server offers ed25519+ECDSA; Go would pick ECDSA and raise a
// false "host key changed".
func TestHostKeyAlgoMismatch(t *testing.T) {
e := newEnv(t)
ed, ec := sshtest.GenKeys(t)
srv := sshtest.Start(t, sshtest.Options{HostKeys: []ssh.Signer{ec, ed}})
e.trust(srv.Addr, ed.PublicKey())
d := e.dialer(DialOptions{})
l, err := d.dial(context.Background(), endpointFor(srv.Addr, srv.Password))
if err != nil {
t.Fatalf("connect with a valid known ed25519 key: %v", err)
}
defer l.close()
if want := IdentityOf(ed.PublicKey()); l.id != want {
t.Errorf("identity = %+v, want %+v", l.id, want)
}
if got := d.hosts.algorithms(srv.Addr); len(got) != 1 || got[0] != ssh.KeyAlgoED25519 {
t.Errorf("algorithms = %v", got)
}
}
func TestHostKeyAlgorithmsRSA(t *testing.T) {
e := newEnv(t)
_, ec := sshtest.GenKeys(t)
rsaPub, err := ssh.ParsePublicKey(testRSAPublicKeyWire(t))
if err != nil {
t.Fatal(err)
}
e.trust("[h]:2222", rsaPub, ec.PublicKey())
d := e.dialer(DialOptions{})
got := d.hosts.algorithms("h:2222")
want := []string{ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256, ssh.KeyAlgoRSA, ssh.KeyAlgoECDSA256}
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Errorf("algorithms = %v, want %v", got, want)
}
if got := d.hosts.algorithms("other:22"); got != nil {
t.Errorf("unknown host algorithms = %v, want nil", got)
}
}
func TestHostKeyChangedRejected(t *testing.T) {
e := newEnv(t)
ed, _ := sshtest.GenKeys(t)
stale, _ := sshtest.GenKeys(t)
srv := sshtest.Start(t, sshtest.Options{HostKeys: []ssh.Signer{ed}})
e.trust(srv.Addr, stale.PublicKey())
before, _ := os.ReadFile(e.kh)
// No prompter: refused.
d := e.dialer(DialOptions{})
_, err := d.dial(context.Background(), endpointFor(srv.Addr, srv.Password))
if !errors.Is(err, ErrHostKeyChanged) {
t.Fatalf("err = %v, want ErrHostKeyChanged", err)
}
var hke *HostKeyError
if !errors.As(err, &hke) || !hke.Changed || len(hke.Known) != 1 || hke.Known[0] != IdentityOf(stale.PublicKey()) {
t.Errorf("HostKeyError = %+v", hke)
}
// Prompter told about the change, rejects.
p := &fakePrompter{}
d = e.dialer(DialOptions{Prompter: p})
_, err = d.dial(context.Background(), endpointFor(srv.Addr, srv.Password))
if !errors.Is(err, ErrHostKeyChanged) {
t.Fatalf("err = %v, want ErrHostKeyChanged", err)
}
if len(p.hostKeys) != 1 || !p.hostKeys[0].changed {
t.Errorf("prompter calls = %+v, want one with changed=true", p.hostKeys)
}
after, _ := os.ReadFile(e.kh)
if !bytes.Equal(before, after) {
t.Error("known_hosts modified on a rejected changed key")
}
}
// N-P2-14: an unknown host goes to the Prompter instead of silent TOFU.
func TestUnknownHostAsksPrompter(t *testing.T) {
e := newEnv(t)
srv := sshtest.Start(t, sshtest.Options{})
ep := endpointFor(srv.Addr, srv.Password)
t.Run("Reject", func(t *testing.T) {
p := &fakePrompter{}
_, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep)
if !errors.Is(err, ErrHostKeyRejected) {
t.Fatalf("err = %v, want ErrHostKeyRejected", err)
}
if n, _, _, _ := p.counts(); n != 1 || p.hostKeys[0].changed || len(p.hostKeys[0].known) != 0 {
t.Errorf("prompter calls = %+v", p.hostKeys)
}
if _, err := os.Stat(e.kh); !os.IsNotExist(err) {
t.Error("known_hosts written on Reject")
}
})
t.Run("NoPrompter", func(t *testing.T) {
_, err := e.dialer(DialOptions{}).dial(context.Background(), ep)
if !errors.Is(err, ErrHostKeyRejected) {
t.Fatalf("err = %v, want ErrHostKeyRejected", err)
}
})
t.Run("AcceptOnce", func(t *testing.T) {
p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { return AcceptOnce, nil }}
d := e.dialer(DialOptions{Prompter: p})
for i := 0; i < 2; i++ {
l, err := d.dial(context.Background(), ep)
if err != nil {
t.Fatal(err)
}
l.close()
}
if n, _, _, _ := p.counts(); n != 1 {
t.Errorf("asked %d times, want once per process", n)
}
if _, err := os.Stat(e.kh); !os.IsNotExist(err) {
t.Error("known_hosts written on AcceptOnce")
}
})
t.Run("AcceptAndSave", func(t *testing.T) {
p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { return AcceptAndSave, nil }}
l, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep)
if err != nil {
t.Fatal(err)
}
l.close()
data, err := os.ReadFile(e.kh)
if err != nil || !strings.Contains(string(data), "127.0.0.1") {
t.Fatalf("known_hosts = %q, %v", data, err)
}
if fi, _ := os.Stat(e.kh); fi.Mode().Perm() != 0o600 {
t.Errorf("known_hosts mode %v", fi.Mode().Perm())
}
// A fresh process (dialer) trusts it without asking.
l, err = e.dialer(DialOptions{}).dial(context.Background(), ep)
if err != nil {
t.Fatalf("saved key not trusted: %v", err)
}
l.close()
})
t.Run("MemoryOnlyWarns", func(t *testing.T) {
os.Remove(e.kh)
var warns []string
var mu sync.Mutex
p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { return AcceptAndSave, nil }}
d := e.dialer(DialOptions{Prompter: p, KnownHostsWrite: "-", Warn: func(s string) {
mu.Lock()
warns = append(warns, s)
mu.Unlock()
}})
l, err := d.dial(context.Background(), ep)
if err != nil {
t.Fatal(err)
}
l.close()
if len(warns) != 1 || !strings.Contains(warns[0], "session only") {
t.Errorf("warnings = %q", warns)
}
if _, err := os.Stat(e.kh); !os.IsNotExist(err) {
t.Error("known_hosts written in memory-only mode")
}
})
}
// N-P2-2: a rejected IdentityFile used to end authentication; the agent
// must still be tried.
func TestAuthFallbackToAgentAfterIdentityRejected(t *testing.T) {
e := newEnv(t)
agentPriv, agentSigner := newKey(t)
otherPriv, _ := newKey(t)
idPath := filepath.Join(e.home, ".ssh", "id_other")
writeKey(t, idPath, otherPriv, "")
ag := startAgent(t, agentPriv)
srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{agentSigner.PublicKey()}})
d := e.dialer(DialOptions{AgentSocket: ag.sock})
ep := endpointFor(srv.Addr, "")
ep.IdentityFiles = []string{idPath, filepath.Join(e.home, ".ssh", "missing")}
l, err := d.dial(context.Background(), ep)
if err != nil {
t.Fatalf("agent key not tried after the identity file was rejected: %v", err)
}
l.close()
// IdentitiesOnly: the agent key is not offered.
ep.IdentitiesOnly = true
if _, err := d.dial(context.Background(), ep); err == nil {
t.Fatal("IdentitiesOnly must not offer unrelated agent keys")
}
}
func TestAuthDefaultIdentityAndPasswordFallback(t *testing.T) {
e := newEnv(t)
priv, signer := newKey(t)
writeKey(t, filepath.Join(e.home, ".ssh", "id_ed25519"), priv, "")
srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{signer.PublicKey()}})
l, err := e.dialer(DialOptions{}).dial(context.Background(), endpointFor(srv.Addr, ""))
if err != nil {
t.Fatalf("default identity: %v", err)
}
l.close()
// Password server: keys are offered and rejected, the prompter's password works.
srv2 := e.startTrusted(sshtest.Options{Password: "s3cret"})
p := &fakePrompter{password: func(context.Context) (string, error) { return "s3cret", nil }}
l, err = e.dialer(DialOptions{Prompter: p}).dial(context.Background(), endpointFor(srv2.Addr, ""))
if err != nil {
t.Fatalf("prompted password: %v", err)
}
l.close()
if _, pw, _, _ := p.counts(); pw != 1 {
t.Errorf("password asked %d times", pw)
}
}
// N-P2-2: keyboard-interactive questions reach the Prompter as they are
// (the old code answered every question, 2FA included, with the password).
func TestKeyboardInteractiveUsesPrompter(t *testing.T) {
e := newEnv(t)
qs := []string{"Password: ", "Verification code: "}
echo := []bool{false, true}
addr, hostKey := kiServer(t, qs, echo, []string{"pw", "123456"})
e.trust(addr, hostKey)
p := &fakePrompter{ki: func([]string) ([]string, error) { return []string{"pw", "123456"}, nil }}
ep := endpointFor(addr, "pw") // the stored password must not answer the 2FA question
l, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep)
if err != nil {
t.Fatalf("keyboard-interactive: %v", err)
}
l.close()
if len(p.kiCalls) != 1 || strings.Join(p.kiCalls[0], "|") != strings.Join(qs, "|") ||
p.kiEcho[0][0] || !p.kiEcho[0][1] {
t.Errorf("prompter saw %q echo %v", p.kiCalls, p.kiEcho)
}
if !strings.Contains(p.kiInstr[0], "Two factors please") {
t.Errorf("instruction = %q", p.kiInstr[0])
}
// A lone hidden question is answered with the stored password.
addr2, hostKey2 := kiServer(t, []string{"Password: "}, []bool{false}, []string{"pw"})
e.trust(addr2, hostKey2)
p2 := &fakePrompter{}
l, err = e.dialer(DialOptions{Prompter: p2}).dial(context.Background(), endpointFor(addr2, "pw"))
if err != nil {
t.Fatalf("stored password via keyboard-interactive: %v", err)
}
l.close()
if _, _, ki, _ := p2.counts(); ki != 0 {
t.Errorf("prompter asked %d times", ki)
}
}
// N-P2-1: one agent connection per process, not one per connect.
func TestAgentConnectionShared(t *testing.T) {
e := newEnv(t)
priv, signer := newKey(t)
ag := startAgent(t, priv)
srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{signer.PublicKey()}})
d := newDialer(DialOptions{Home: e.home, AgentSocket: ag.sock, KnownHostsFiles: []string{e.kh}})
ep := endpointFor(srv.Addr, "")
var wg sync.WaitGroup
errs := make(chan error, 6)
for i := 0; i < 6; i++ {
wg.Add(1)
go func() {
defer wg.Done()
l, err := d.dial(context.Background(), ep)
if err == nil {
l.close()
}
errs <- err
}()
}
wg.Wait()
close(errs)
for err := range errs {
if err != nil {
t.Fatal(err)
}
}
if n := ag.accepts.Load(); n != 1 {
t.Errorf("agent connections = %d, want 1", n)
}
d.close()
waitFor(t, 2*time.Second, "agent connection closed", func() bool { return ag.active.Load() == 0 })
}
// An encrypted key is decrypted only when the server accepts it.
func TestPassphraseAskedLazily(t *testing.T) {
e := newEnv(t)
accPriv, accSigner := newKey(t)
rejPriv, _ := newKey(t)
rej := filepath.Join(e.home, ".ssh", "id_rejected")
acc := filepath.Join(e.home, ".ssh", "id_accepted")
writeKey(t, rej, rejPriv, "one")
writeKey(t, acc, accPriv, "two")
srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{accSigner.PublicKey()}})
tries := 0
p := &fakePrompter{passphrase: func(path string) ([]byte, error) {
tries++
if tries == 1 {
return []byte("wrong"), nil
}
return []byte("two"), nil
}}
ep := endpointFor(srv.Addr, "")
ep.IdentityFiles = []string{rej, acc}
l, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep)
if err != nil {
t.Fatalf("encrypted key: %v", err)
}
l.close()
for _, ph := range p.phrases {
if ph != acc {
t.Errorf("passphrase asked for %s (server never accepted it)", ph)
}
}
if len(p.phrases) != 2 {
t.Errorf("passphrase asked %d times, want 2 (one wrong attempt)", len(p.phrases))
}
}
// testRSAPublicKeyWire returns an RSA public key in wire format. Only the
// type matters here, so the modulus is arbitrary (no slow key generation).
func testRSAPublicKeyWire(t *testing.T) []byte {
t.Helper()
n := new(big.Int).Lsh(big.NewInt(1), 2047)
n.Add(n, big.NewInt(12345))
pub, err := ssh.NewPublicKey(&rsa.PublicKey{N: n, E: 65537})
if err != nil {
t.Fatal(err)
}
return pub.Marshal()
}

View file

@ -0,0 +1,384 @@
package conn
import (
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/pem"
"errors"
"net"
"os"
"path/filepath"
"runtime"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/crypto/ssh/knownhosts"
"vcom/internal/testutil/sshtest"
)
// noLeak runs fn as a subtest (so its Cleanups run) and then checks that the
// goroutine count returns to the baseline within ±2.
func noLeak(t *testing.T, fn func(t *testing.T)) {
t.Helper()
runtime.GC()
base := runtime.NumGoroutine()
t.Run("body", fn)
deadline := time.Now().Add(5 * time.Second)
var n int
for time.Now().Before(deadline) {
n = runtime.NumGoroutine()
if n <= base+2 {
return
}
time.Sleep(20 * time.Millisecond)
}
buf := make([]byte, 1<<20)
buf = buf[:runtime.Stack(buf, true)]
t.Errorf("goroutines: base=%d after cleanup=%d\n%s", base, n, buf)
}
// waitFor polls cond until it holds or d elapses.
func waitFor(t *testing.T, d time.Duration, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(d)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out after %v waiting for %s", d, what)
}
time.Sleep(5 * time.Millisecond)
}
}
// env is an isolated HOME with helpers to dial the in-process server.
type env struct {
t *testing.T
home string
kh string // ~/.ssh/known_hosts
}
func newEnv(t *testing.T) *env {
t.Helper()
home := sshtest.IsolatedHome(t)
return &env{t: t, home: home, kh: filepath.Join(home, ".ssh", "known_hosts")}
}
// dialer returns a dialer rooted at the env HOME; the agent is disabled
// unless o.AgentSocket is set.
func (e *env) dialer(o DialOptions) *dialer {
if o.Home == "" {
o.Home = e.home
}
if o.AgentSocket == "" {
o.AgentSocket = "-"
}
if o.KnownHostsFiles == nil {
o.KnownHostsFiles = []string{e.kh}
}
d := newDialer(o)
e.t.Cleanup(d.close)
return d
}
// trust writes known_hosts lines for addr.
func (e *env) trust(addr string, keys ...ssh.PublicKey) {
e.t.Helper()
var data []byte
for _, k := range keys {
data = append(data, knownhosts.Line([]string{knownhosts.Normalize(addr)}, k)+"\n"...)
}
if err := os.WriteFile(e.kh, data, 0o600); err != nil {
e.t.Fatal(err)
}
}
func endpointFor(addr, password string) Endpoint {
host, port, _ := net.SplitHostPort(addr)
p, _ := strconv.Atoi(port)
return Endpoint{Alias: "test", User: "u", Host: host, Port: p, Password: password}
}
// startTrusted starts a server whose host keys are in known_hosts.
func (e *env) startTrusted(o sshtest.Options) *sshtest.Server {
srv := sshtest.Start(e.t, o)
var pubs []ssh.PublicKey
for _, k := range srv.HostKeys {
pubs = append(pubs, k.PublicKey())
}
e.trust(srv.Addr, pubs...)
return srv
}
func (l *link) closeOnCleanup(t *testing.T) *link {
t.Cleanup(l.close)
return l
}
// fakePrompter records calls and answers with the configured functions.
type fakePrompter struct {
mu sync.Mutex
hostKeys []hostKeyCall
passwords int
kiCalls [][]string
kiEcho [][]bool
kiInstr []string
phrases []string
hostKey func(ctx context.Context, changed bool) (HostKeyDecision, error)
password func(ctx context.Context) (string, error)
ki func(qs []string) ([]string, error)
passphrase func(path string) ([]byte, error)
}
type hostKeyCall struct {
id HostIdentity
known []HostIdentity
changed bool
}
func (p *fakePrompter) HostKey(ctx context.Context, ep Endpoint, id HostIdentity, known []HostIdentity, changed bool) (HostKeyDecision, error) {
p.mu.Lock()
p.hostKeys = append(p.hostKeys, hostKeyCall{id, known, changed})
p.mu.Unlock()
if p.hostKey == nil {
return Reject, nil
}
return p.hostKey(ctx, changed)
}
func (p *fakePrompter) Password(ctx context.Context, ep Endpoint) (string, error) {
p.mu.Lock()
p.passwords++
p.mu.Unlock()
if p.password == nil {
return "", errors.New("no password")
}
return p.password(ctx)
}
func (p *fakePrompter) KeyboardInteractive(ctx context.Context, ep Endpoint, instr string, qs []string, echo []bool) ([]string, error) {
p.mu.Lock()
p.kiCalls = append(p.kiCalls, append([]string(nil), qs...))
p.kiEcho = append(p.kiEcho, append([]bool(nil), echo...))
p.kiInstr = append(p.kiInstr, instr)
p.mu.Unlock()
if p.ki == nil {
return nil, errors.New("no answers")
}
return p.ki(qs)
}
func (p *fakePrompter) Passphrase(ctx context.Context, path string) ([]byte, error) {
p.mu.Lock()
p.phrases = append(p.phrases, path)
p.mu.Unlock()
if p.passphrase == nil {
return nil, errors.New("no passphrase")
}
return p.passphrase(path)
}
func (p *fakePrompter) counts() (hostKeys, passwords, ki, phrases int) {
p.mu.Lock()
defer p.mu.Unlock()
return len(p.hostKeys), p.passwords, len(p.kiCalls), len(p.phrases)
}
// newKey returns a fresh ed25519 private key and its signer.
func newKey(t *testing.T) (ed25519.PrivateKey, ssh.Signer) {
t.Helper()
_, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
s, err := ssh.NewSignerFromKey(priv)
if err != nil {
t.Fatal(err)
}
return priv, s
}
// writeKey stores priv in OpenSSH format (encrypted when passphrase != "").
func writeKey(t *testing.T, path string, priv ed25519.PrivateKey, passphrase string) {
t.Helper()
var blk *pem.Block
var err error
if passphrase == "" {
blk, err = ssh.MarshalPrivateKey(priv, "test")
} else {
blk, err = ssh.MarshalPrivateKeyWithPassphrase(priv, "test", []byte(passphrase))
}
if err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, pem.EncodeToMemory(blk), 0o600); err != nil {
t.Fatal(err)
}
}
// fakeAgent serves an in-memory keyring on a unix socket.
type fakeAgent struct {
sock string
accepts atomic.Int32
active atomic.Int32
}
func startAgent(t *testing.T, keys ...ed25519.PrivateKey) *fakeAgent {
t.Helper()
kr := agent.NewKeyring()
for _, k := range keys {
if err := kr.Add(agent.AddedKey{PrivateKey: k}); err != nil {
t.Fatal(err)
}
}
dir, err := os.MkdirTemp("", "agent")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(dir) })
a := &fakeAgent{sock: filepath.Join(dir, "s")}
ln, err := net.Listen("unix", a.sock)
if err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
var mu sync.Mutex
var conns []net.Conn
wg.Add(1)
go func() {
defer wg.Done()
for {
c, err := ln.Accept()
if err != nil {
return
}
a.accepts.Add(1)
a.active.Add(1)
mu.Lock()
conns = append(conns, c)
mu.Unlock()
wg.Add(1)
go func() {
defer wg.Done()
defer a.active.Add(-1)
agent.ServeAgent(kr, c)
c.Close()
}()
}
}()
t.Cleanup(func() {
ln.Close()
mu.Lock()
for _, c := range conns {
c.Close()
}
mu.Unlock()
wg.Wait()
})
return a
}
// kiServer is a minimal SSH server that only allows keyboard-interactive
// auth with the given questions; answers must equal want. It serves SFTP so
// the full dial path succeeds.
func kiServer(t *testing.T, questions []string, echo []bool, want []string) (string, ssh.PublicKey) {
t.Helper()
ed, _ := sshtest.GenKeys(t)
cfg := &ssh.ServerConfig{
KeyboardInteractiveCallback: func(_ ssh.ConnMetadata, ch ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
ans, err := ch("vcom-test", "Two factors please", questions, echo)
if err != nil {
return nil, err
}
if len(ans) != len(want) {
return nil, errors.New("wrong answer count")
}
for i := range want {
if ans[i] != want[i] {
return nil, errors.New("wrong answer")
}
}
return nil, nil
},
}
cfg.AddHostKey(ed)
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
var mu sync.Mutex
var conns []net.Conn
wg.Add(1)
go func() {
defer wg.Done()
for {
nc, err := ln.Accept()
if err != nil {
return
}
mu.Lock()
conns = append(conns, nc)
mu.Unlock()
wg.Add(1)
go func() {
defer wg.Done()
defer nc.Close()
sc, chans, reqs, err := ssh.NewServerConn(nc, cfg)
if err != nil {
return
}
defer sc.Close()
go ssh.DiscardRequests(reqs)
for nch := range chans {
ch, creqs, err := nch.Accept()
if err != nil {
continue
}
wg.Add(1)
go func() {
defer wg.Done()
defer ch.Close()
for req := range creqs {
if req.Type == "subsystem" {
req.Reply(true, nil)
srv, err := sftp.NewServer(ch)
if err != nil {
return
}
go func() {
for range creqs {
}
}()
srv.Serve()
srv.Close()
return
}
req.Reply(false, nil)
}
}()
}
}()
}
}()
t.Cleanup(func() {
ln.Close()
mu.Lock()
for _, c := range conns {
c.Close()
}
mu.Unlock()
wg.Wait()
})
return ln.Addr().String(), ed.PublicKey()
}

View file

@ -0,0 +1,272 @@
package conn
import (
"context"
"crypto/ed25519"
"crypto/rand"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"sync"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
"vcom/internal/ssh/internal/atomicwrite"
)
var (
// ErrHostKeyRejected: the key is unknown and the user (or the absence of
// a Prompter) refused it.
ErrHostKeyRejected = errors.New("host key rejected")
// ErrHostKeyChanged: known_hosts has a different key of the same type.
ErrHostKeyChanged = errors.New("REMOTE HOST IDENTIFICATION HAS CHANGED")
)
// HostKeyError describes a refused host key. It unwraps to
// ErrHostKeyChanged or ErrHostKeyRejected.
type HostKeyError struct {
Host string // host:port as checked against known_hosts
Identity HostIdentity
Known []HostIdentity
Changed bool
}
func (e *HostKeyError) Error() string {
if e.Changed {
return fmt.Sprintf("%v for %s: server offers %s %s; remove the stale entry with `ssh-keygen -R %s` once the new key is verified",
ErrHostKeyChanged, e.Host, e.Identity.KeyType, e.Identity.FingerprintSHA256, e.Host)
}
return fmt.Sprintf("%v: %s %s %s", ErrHostKeyRejected, e.Host, e.Identity.KeyType, e.Identity.FingerprintSHA256)
}
func (e *HostKeyError) Unwrap() error {
if e.Changed {
return ErrHostKeyChanged
}
return ErrHostKeyRejected
}
// probeKey is a throwaway key that is never in known_hosts: checking it
// makes knownhosts report every key it has for a host (KeyError.Want).
var probeKey = sync.OnceValue(func() ssh.PublicKey {
pub, _, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
panic(err)
}
k, err := ssh.NewPublicKey(pub)
if err != nil {
panic(err)
}
return k
})
// knownHosts verifies host keys against known_hosts files plus keys
// accepted during this process.
type knownHosts struct {
files []string // read in order
write string // AcceptAndSave appends here ("" = memory only)
warn func(string)
mu sync.Mutex
session map[string][]ssh.PublicKey // knownhosts.Normalize(host:port) -> keys
}
func newKnownHosts(files []string, write string, warn func(string)) *knownHosts {
return &knownHosts{files: files, write: write, warn: warn, session: map[string][]ssh.PublicKey{}}
}
// db parses the existing known_hosts files; nil when there are none.
func (h *knownHosts) db() (ssh.HostKeyCallback, error) {
var files []string
for _, f := range h.files {
if _, err := os.Stat(f); err == nil {
files = append(files, f)
}
}
if len(files) == 0 {
return nil, nil
}
return knownhosts.New(files...)
}
// known returns every key on record for hostport (files, then session).
func (h *knownHosts) known(hostport string) []ssh.PublicKey {
var out []ssh.PublicKey
if cb, err := h.db(); err == nil && cb != nil {
var ke *knownhosts.KeyError
if err := cb(hostport, &net.TCPAddr{IP: net.IPv4zero}, probeKey()); errors.As(err, &ke) {
for _, k := range ke.Want {
out = append(out, k.Key)
}
}
}
h.mu.Lock()
out = append(out, h.session[knownhosts.Normalize(hostport)]...)
h.mu.Unlock()
return out
}
// algorithms lists host key algorithms for the key types on record, so the
// server is asked for a key we can actually verify (N-P1-4: Go prefers ECDSA,
// OpenSSH usually records ed25519). nil means "library defaults".
func (h *knownHosts) algorithms(hostport string) []string {
var algos []string
seen := map[string]bool{}
add := func(a string) {
if !seen[a] {
seen[a] = true
algos = append(algos, a)
}
}
for _, k := range h.known(hostport) {
switch t := k.Type(); t {
case ssh.KeyAlgoRSA:
add(ssh.KeyAlgoRSASHA512)
add(ssh.KeyAlgoRSASHA256)
add(ssh.KeyAlgoRSA)
default:
add(t)
}
}
return algos
}
func (h *knownHosts) sessionHas(hostport string, key ssh.PublicKey) bool {
h.mu.Lock()
defer h.mu.Unlock()
for _, k := range h.session[knownhosts.Normalize(hostport)] {
if string(k.Marshal()) == string(key.Marshal()) {
return true
}
}
return false
}
func (h *knownHosts) remember(hostport string, key ssh.PublicKey) {
h.mu.Lock()
defer h.mu.Unlock()
n := knownhosts.Normalize(hostport)
h.session[n] = append(h.session[n], key)
}
func (h *knownHosts) warnf(format string, args ...any) {
if h.warn != nil {
h.warn(fmt.Sprintf(format, args...))
}
}
// save appends a known_hosts line atomically (rewrite via temp copy). When
// the file belongs to another user (vcom under sudo) or cannot be written,
// the key is trusted for this process only and a warning is emitted
// (N-P2-14).
func (h *knownHosts) save(hostport string, key ssh.PublicKey) {
h.remember(hostport, key)
if h.write == "" {
h.warnf("host key for %s accepted for this session only (no known_hosts file configured)", hostport)
return
}
if foreignOwner(h.write) {
h.warnf("host key for %s accepted for this session only: %s belongs to another user", hostport, h.write)
return
}
h.mu.Lock()
defer h.mu.Unlock()
if err := appendKnownHost(h.write, knownhosts.Line([]string{knownhosts.Normalize(hostport)}, key)); err != nil {
h.warnf("host key for %s accepted for this session only: %v", hostport, err)
}
}
func appendKnownHost(path, line string) error {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
perm := os.FileMode(0o600)
data, err := os.ReadFile(path)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
if fi, err := os.Stat(path); err == nil {
perm = fi.Mode().Perm()
}
if len(data) > 0 && data[len(data)-1] != '\n' {
data = append(data, '\n')
}
data = append(data, line+"\n"...)
return atomicwrite.WriteFile(path, data, perm)
}
// callback builds the HostKeyCallback for one dial. prompt wraps Prompter
// calls so the handshake deadline is paused while the user decides; onKey
// sees every key the server presents (also on later re-keys).
func (h *knownHosts) callback(ctx context.Context, ep Endpoint, p Prompter, prompt func(func() error) error, onKey func(HostIdentity)) ssh.HostKeyCallback {
return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
id := IdentityOf(key)
onKey(id)
if h.sessionHas(hostname, key) {
return nil
}
var wants []ssh.PublicKey
cb, err := h.db()
if err != nil {
return fmt.Errorf("known_hosts: %w", err)
}
if cb != nil {
err := cb(hostname, remote, key)
if err == nil {
return nil
}
var ke *knownhosts.KeyError
if !errors.As(err, &ke) {
return err // revoked key, unreadable file, ...
}
for _, k := range ke.Want {
wants = append(wants, k.Key)
}
}
h.mu.Lock()
wants = append(wants, h.session[knownhosts.Normalize(hostname)]...)
h.mu.Unlock()
// Alarm only when a key of the same type is on record and differs; a
// key of a type we have no record for is merely unknown.
changed := false
known := make([]HostIdentity, 0, len(wants))
for _, k := range wants {
known = append(known, IdentityOf(k))
if k.Type() == key.Type() {
changed = true
}
}
herr := &HostKeyError{Host: hostname, Identity: id, Known: known, Changed: changed}
if p == nil {
return herr
}
var dec HostKeyDecision
if err := prompt(func() error {
var err error
dec, err = p.HostKey(ctx, ep, id, known, changed)
return err
}); err != nil {
return err
}
switch dec {
case AcceptOnce:
h.remember(hostname, key)
return nil
case AcceptAndSave:
if changed {
// Replacing a stale line is left to `ssh-keygen -R`; trust the
// new key for this process only.
h.remember(hostname, key)
h.warnf("changed host key for %s accepted for this session only", hostname)
return nil
}
h.save(hostname, key)
return nil
default:
return herr
}
}
}

View file

@ -0,0 +1,5 @@
//go:build !unix
package conn
func foreignOwner(string) bool { return false }

View file

@ -0,0 +1,23 @@
//go:build unix
package conn
import (
"os"
"path/filepath"
"syscall"
)
// foreignOwner reports whether path (or, if it does not exist, its parent
// directory) belongs to a user other than the effective one, e.g. the
// invoking user's ~/.ssh while vcom runs under sudo.
func foreignOwner(path string) bool {
fi, err := os.Stat(path)
if err != nil {
if fi, err = os.Stat(filepath.Dir(path)); err != nil {
return false
}
}
st, ok := fi.Sys().(*syscall.Stat_t)
return ok && int(st.Uid) != os.Geteuid()
}

View file

@ -0,0 +1,55 @@
// Package conn owns SSH connections: dialing with a bounded handshake,
// host-key verification, authentication, keepalive, reconnect, remote exec
// and a reference-counted pool. Nothing outside the Pool closes a
// connection.
package conn
import (
"context"
"crypto/sha256"
"encoding/base64"
"golang.org/x/crypto/ssh"
"vcom/internal/ssh/sshconfig"
)
// Endpoint is the resolved host to dial.
type Endpoint = sshconfig.Endpoint
// HostIdentity identifies a server host key.
type HostIdentity struct {
KeyType string // e.g. "ssh-ed25519"
FingerprintSHA256 string // "SHA256:..." as printed by ssh-keygen -l
}
// IdentityOf returns the identity of a public key.
func IdentityOf(k ssh.PublicKey) HostIdentity {
sum := sha256.Sum256(k.Marshal())
return HostIdentity{
KeyType: k.Type(),
FingerprintSHA256: "SHA256:" + base64.RawStdEncoding.EncodeToString(sum[:]),
}
}
// HostKeyDecision is the answer to an unknown or changed host key.
type HostKeyDecision uint8
const (
Reject HostKeyDecision = iota // refuse to connect
AcceptOnce // trust for this process only
AcceptAndSave // trust and append to known_hosts
)
// Prompter asks the user. The UI implements it via jobs.Ask; every method
// must return promptly when ctx is cancelled. A nil Prompter rejects unknown
// host keys and offers no interactive authentication.
type Prompter interface {
// HostKey is called for a key that is not in known_hosts. changed is
// true when known_hosts has a different key of the same type (possible
// MITM); known lists the keys known_hosts has for the host.
HostKey(ctx context.Context, ep Endpoint, id HostIdentity, known []HostIdentity, changed bool) (HostKeyDecision, error)
Password(ctx context.Context, ep Endpoint) (string, error)
KeyboardInteractive(ctx context.Context, ep Endpoint, instruction string, questions []string, echo []bool) ([]string, error)
Passphrase(ctx context.Context, keyPath string) ([]byte, error)
}

View file

@ -29,3 +29,34 @@
- `Endpoint` дополнен `Addr()` и `Label()`; `ProxyJump` разбирается (`[user@]host[:port]`, хопы разрешаются через
тот же конфиг), но подключение через хопы — этап 8. `IdentityFile none` пропускается; токены `%h %d %u %r %%`
раскрываются в `HostName`/`IdentityFile`.
## 2B.2 `ssh/conn` Dialer
- **Dialer не экспортируется.** Внутренний `dialer` (один на Pool, т.е. на процесс: держит общее соединение с
агентом и принятые на сессию host keys) настраивается через `DialOptions{Prompter, HandshakeTimeout, Home,
KnownHostsFiles, KnownHostsWrite, AgentSocket, DefaultIdentityFiles, Warn}`; `PoolOptions` встраивает
`DialOptions` (2B.4). Снаружи соединение получают только через `Pool.Acquire`.
- **Дедлайн handshake на паузе, пока ждём Prompter** (host key, пароль, KI, passphrase): иначе пользователь,
думающий дольше 20 с, получал бы таймаут. После ответа таймер взводится заново на полный `HandshakeTimeout`.
`ConnectTimeout` из ssh_config ограничивает только TCP connect (как в OpenSSH).
- **SFTP:** `sftp.NewClient(sshClient, UseConcurrentWrites, UseConcurrentReads, MaxConcurrentRequestsPerFile(64))`
вместо `NewClientPipe` — те же опции, меньше кода; ожидание VERSION идёт под тем же дедлайном.
- **Порядок ключей:** явные `IdentityFile` (если ключ уже есть в агенте — подпись агентом) → остальные ключи агента →
`~/.ssh/id_{ed25519,ecdsa,rsa}` (последние два шага — только без `IdentitiesOnly`). В дизайне агент стоял первым;
явный ключ первым ближе к OpenSSH и не съедает `MaxAuthTries` сервера ключами агента. Все ключи — в одном
методе `publickey` (x/crypto пробует каждое имя метода один раз; два `PublicKeys` подряд — второй игнорируется).
- **Зашифрованный ключ:** если известна публичная половина (встроена в формат OpenSSH или лежит в `.pub`),
passphrase спрашивается только когда сервер принял ключ (lazy signer), до 3 попыток. Отмена в Prompter
прерывает аутентификацию целиком (так устроен x/crypto: ошибка подписи = ошибка auth).
- **Пароль/KI:** пароль из hosts.dat используется один раз (метод `password` или одиночный скрытый вопрос KI);
всё остальное — через Prompter как есть (2FA). Без Prompter и без пароля эти методы не предлагаются.
- **Host key.** Неизвестный ключ без Prompter → отказ (`ErrHostKeyRejected`), а не молчаливый TOFU. Ключ другого
типа, чем записанные, — «неизвестный» (`changed=false`, `known` заполнен). Изменившийся ключ того же типа →
Prompter с `changed=true`; Reject → `*HostKeyError` (unwrap → `ErrHostKeyChanged`); AcceptOnce/AcceptAndSave для
изменившегося ключа → доверие только на сессию (строку в known_hosts не переписываем, это `ssh-keygen -R`).
Ошибка — тип `*HostKeyError{Host, Identity, Known, Changed}` для UI.
- **sudo / known_hosts:** если файл (или каталог, если файла нет) принадлежит не эффективному uid, либо запись не
удалась, либо `KnownHostsWrite: "-"`, ключ доверяется только в памяти и вызывается `Warn`. Чтение по умолчанию
ещё и из `/etc/ssh/ssh_known_hosts`.
- Тест `TestKeyboardInteractiveUsesPrompter` использует свой мини-сервер в `helpers_test.go` (у `sshtest` нет KI);
`sshtest` не трогал, чтобы не выходить из своей зоны.