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() }