package main import ( "crypto/ed25519" "errors" "log" "net" "os" "path/filepath" "strconv" "strings" "testing" "golang.org/x/crypto/ssh" ) // The scenarios below exercise the accept-after-warning flow for cross-user // first-use host-key divergence: a user hitting the divergence refusal (two // different servers behind one shared hostname:port — NAT/bastion/reinstall) // must have an in-product recovery (explicit accept) instead of a permanent // dead end, WITHOUT weakening any TOFU invariant: // // - the DEFAULT remains refuse (the accept flag only lives on the retry // that follows the client's informed confirmation), // - a PINNED-key mismatch is refused even with the flag (the flag never // enables replacing one's own pin), // - a clean first use behaves identically with the flag, // - a failed store save still fails closed (the pin is not committed). // setupDivergence pins keyA for userA on the shared host and returns the // pieces the divergence tests need. func setupDivergence(t *testing.T, store string, keyA ssh.PublicKey) { t.Helper() first := tofuHostKeyCallback(store, "userA", false) addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22} if err := first("shared.example:22", addr, keyA); err != nil { t.Fatalf("setup: userA first-use pin failed: %v", err) } } // 1. Default refusal: the second user presenting a different key on a host // another user already recorded gets the typed divergence error carrying the // presented fingerprint and the previously-seen ones — that is the payload // handleWS forwards to the client as the structured divergence notice. func TestDivergenceDefaultRefusalIsTypedWithFingerprints(t *testing.T) { dir := t.TempDir() store := filepath.Join(dir, "data", "ssh_known_hosts.json") addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22} host := "shared.example:22" keyA := mkKey(t) keyB := mkKey(t) setupDivergence(t, store, keyA) second := tofuHostKeyCallback(store, "userB", false) err := second(host, addr, keyB) if err == nil { t.Fatal("default must refuse a divergent first-use key") } var dke *hostKeyDivergenceError if !errors.As(err, &dke) { t.Fatalf("refusal must be a *hostKeyDivergenceError, got %T: %v", err, err) } if dke.presented != hostKeyFingerprint(keyB) { t.Fatalf("presented must be key B's fingerprint, got %q", dke.presented) } if len(dke.known) != 1 || dke.known[0] != hostKeyFingerprint(keyA) { t.Fatalf("known must contain exactly key A's fingerprint, got %v", dke.known) } if dke.host != host { t.Fatalf("host must be the dial target, got %q", dke.host) } // Error() text is the historical refusal text: the divergence branch of // explainSSHConnectError keys on it, and the client-facing message keeps // demanding an explicit confirmation. msg := dke.Error() if !strings.Contains(msg, "host key divergence") || !strings.Contains(msg, "possible interception") { t.Fatalf("historical refusal text must be preserved, got: %s", msg) } } // 2. Explicit accept: the same divergence WITH allowDivergentFirstUse=true — // the server-side effect of the client's accept-after-warning retry — pins // the presented key for the accepting user and records it in the advisory // Global set. func TestDivergenceExplicitAcceptPinsPresentedKey(t *testing.T) { dir := t.TempDir() store := filepath.Join(dir, "data", "ssh_known_hosts.json") addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22} host := "shared.example:22" keyA := mkKey(t) keyB := mkKey(t) setupDivergence(t, store, keyA) accepting := tofuHostKeyCallback(store, "userB", true) if err := accepting(host, addr, keyB); err != nil { t.Fatalf("explicit accept must succeed, got: %v", err) } st := loadKnownHostsMust(t, store) if got := st.Pins[userHostKey("userB", host)]; got != hostKeyFingerprint(keyB) { t.Fatalf("userB must be pinned to the presented key B, got %q", got) } found := false for _, fp := range st.Global[host] { if fp == hostKeyFingerprint(keyB) { found = true } } if !found { t.Fatalf("key B's fingerprint must be recorded in Global[%s], got %v", host, st.Global[host]) } // The accepting user must never inherit userA's key either. if got := st.Pins[userHostKey("userB", host)]; got == hostKeyFingerprint(keyA) { t.Fatal("userB must NOT be pinned to userA's key") } } // 3. After the accepted pin, the same user's subsequent DEFAULT connection // (flag false — the normal connect path) succeeds against key B: the // divergence flow only ever needed to run once. func TestDivergenceAfterAcceptDefaultConnectSucceeds(t *testing.T) { dir := t.TempDir() store := filepath.Join(dir, "data", "ssh_known_hosts.json") addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22} host := "shared.example:22" keyA := mkKey(t) keyB := mkKey(t) setupDivergence(t, store, keyA) accepting := tofuHostKeyCallback(store, "userB", true) if err := accepting(host, addr, keyB); err != nil { t.Fatalf("explicit accept failed: %v", err) } normal := tofuHostKeyCallback(store, "userB", false) if err := normal(host, addr, keyB); err != nil { t.Fatalf("post-accept default connection must succeed on the pin match, got: %v", err) } } // 4. Pinned-mismatch invariant: a user's own pin stays ABSOLUTE. The accept // flag must never enable replacing one's own pinned key with a presented one. func TestPinnedMismatchRefusedEvenWithAllowDivergentFirstUse(t *testing.T) { dir := t.TempDir() store := filepath.Join(dir, "data", "ssh_known_hosts.json") addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22} host := "pinned.example:22" keyA := mkKey(t) keyB := mkKey(t) user := tofuHostKeyCallback(store, "userA", false) if err := user(host, addr, keyA); err != nil { t.Fatalf("initial pin failed: %v", err) } withFlag := tofuHostKeyCallback(store, "userA", true) err := withFlag(host, addr, keyB) if err == nil { t.Fatal("a pinned mismatch must be refused even with allowDivergentFirstUse=true") } var dke *hostKeyDivergenceError if errors.As(err, &dke) { t.Fatalf("pinned mismatch must NOT surface as a divergence error (it stays admin-mediated), got: %v", err) } if !strings.Contains(strings.ToLower(err.Error()), "host key mismatch") { t.Fatalf("expected the pinned-mismatch refusal, got: %v", err) } // The pin is unchanged and the presented key never entered the advisory // set: the accept path did not run at all. st := loadKnownHostsMust(t, store) if got := st.Pins[userHostKey("userA", host)]; got != hostKeyFingerprint(keyA) { t.Fatalf("the original pin must be untouched, got %q", got) } for _, fp := range st.Global[host] { if fp == hostKeyFingerprint(keyB) { t.Fatal("the refused key must not be recorded in the advisory set") } } } // 5. Clean first use with the flag true (empty Global for that host — no // divergence to confirm) still pins normally: the flag changes nothing when // there is no divergence. func TestCleanFirstUseWithFlagStillPins(t *testing.T) { dir := t.TempDir() store := filepath.Join(dir, "data", "ssh_known_hosts.json") addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22} host := "clean.example:22" key := mkKey(t) cb := tofuHostKeyCallback(store, "userC", true) if err := cb(host, addr, key); err != nil { t.Fatalf("clean first use with the flag must pin normally, got: %v", err) } st := loadKnownHostsMust(t, store) if got := st.Pins[userHostKey("userC", host)]; got != hostKeyFingerprint(key) { t.Fatalf("clean first use must pin the presented key, got %q", got) } // Reconnect with the same key (flag true again) still matches the pin. if err := cb(host, addr, key); err != nil { t.Fatalf("pin match must succeed regardless of the flag, got: %v", err) } } // 6. The divergence branch of explainSSHConnectError must describe the // in-product recovery (confirm to accept when prompted) instead of the old // dead-end advice. func TestExplainSSHConnectErrorDivergenceDescribesConfirmFlow(t *testing.T) { dke := &hostKeyDivergenceError{ host: "shared.example:22", presented: "ssh-ed25519:SHA256:presented", known: []string{"ssh-ed25519:SHA256:known"}, } msg := explainSSHConnectError(dke) lower := strings.ToLower(msg) if !strings.Contains(lower, "confirm to accept it when prompted") { t.Fatalf("explanation must point at the in-product confirm flow, got: %s", msg) } const oldDeadEnd = "verify the server fingerprint out-of-band" if strings.Contains(lower, oldDeadEnd) { t.Fatalf("explanation must not contain the old dead-end phrase %q, got: %s", oldDeadEnd, msg) } if !strings.Contains(lower, "possible interception") { t.Fatalf("explanation must keep the interception warning, got: %s", msg) } } // 7. Fail-closed on store save errors is unchanged on the accept path too: a // save failure refuses the connection AND commits nothing, so the accepting // user is not silently pinned to the presented key. func TestDivergenceAcceptFailsClosedWhenSaveFails(t *testing.T) { dir := t.TempDir() store := filepath.Join(dir, "data", "ssh_known_hosts.json") addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22} host := "shared.example:22" keyA := mkKey(t) keyB := mkKey(t) setupDivergence(t, store, keyA) // Replace the store FILE with a directory: loads keep the resident // last-good state (so the divergence is still detected) but every save // fails — the accept path must fail closed on it. if err := os.Remove(store); err != nil { t.Fatal(err) } if err := os.Mkdir(store, 0o700); err != nil { t.Fatal(err) } accepting := tofuHostKeyCallback(store, "userB", true) err := accepting(host, addr, keyB) if err == nil || !strings.Contains(strings.ToLower(err.Error()), "host key store unavailable") { t.Fatalf("accept path must fail closed when the save fails, got: %v", err) } // Nothing was committed: the accepting user has no pin, so their next // DEFAULT attempt is still the divergence refusal (a committed pin would // have made it succeed). normal := tofuHostKeyCallback(store, "userB", false) if err := normal(host, addr, keyB); err == nil { t.Fatal("a failed save must not commit the accept: the next default attempt must still be refused") } else if !errors.As(err, new(*hostKeyDivergenceError)) { t.Fatalf("next attempt must still be the divergence refusal, got: %v", err) } } // mkSignerKey generates a fresh ed25519 keypair as an ssh.Signer (for the // in-process server below) plus its public key. func mkSignerKey(t *testing.T) (ssh.PublicKey, ssh.Signer) { t.Helper() _, priv, err := ed25519.GenerateKey(nil) if err != nil { t.Fatal(err) } signer, err := ssh.NewSignerFromKey(priv) if err != nil { t.Fatal(err) } return signer.PublicKey(), signer } // startDivergenceSSHServer runs an in-process SSH server that presents // serverSigner's host key and accepts any password, servicing pty/shell // requests so openSSHSession can complete a REAL handshake against it. The // returned string is the dial target ("127.0.0.1:port") — exactly the // hostport string tofuHostKeyCallback sees as t.dialAddress during that // handshake. func startDivergenceSSHServer(t *testing.T, serverSigner ssh.Signer) string { t.Helper() config := &ssh.ServerConfig{ PasswordCallback: func(ssh.ConnMetadata, []byte) (*ssh.Permissions, error) { return &ssh.Permissions{}, nil }, } config.AddHostKey(serverSigner) ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = ln.Close() }) go func() { for { c, err := ln.Accept() if err != nil { return } go serveDivergenceSSHConn(c, config) } }() return ln.Addr().String() } func serveDivergenceSSHConn(c net.Conn, config *ssh.ServerConfig) { sconn, chans, reqs, err := ssh.NewServerConn(c, config) if err != nil { return } defer sconn.Close() go func() { for req := range reqs { if req.WantReply { _ = req.Reply(false, nil) } } }() for newCh := range chans { if newCh.ChannelType() != "session" { _ = newCh.Reject(ssh.UnknownChannelType, "unsupported channel type") continue } ch, chReqs, err := newCh.Accept() if err != nil { continue } go func() { defer ch.Close() for req := range chReqs { switch req.Type { case "pty-req", "shell", "env": if req.WantReply { _ = req.Reply(true, nil) } default: if req.WantReply { _ = req.Reply(false, nil) } } } }() } } // 8. THE propagation proof: the divergence refusal raised inside the TOFU // host-key callback must survive the whole x/crypto handshake path (kexLoop // → readOnePacket → clientHandshake → the "ssh: handshake failed: %w" wrap in // NewClientConn) so handleWS's errors.As can still match it and upgrade the // refusal to the structured client notice. Verified against a real in-process // SSH server presenting a different key than the one userA pinned. func TestDivergenceRefusalPropagatesThroughRealHandshake(t *testing.T) { dir := t.TempDir() store := filepath.Join(dir, "data", "ssh_known_hosts.json") keyA := mkKey(t) serverKey, serverSigner := mkSignerKey(t) // userA pins keyA for the REAL listener address, so the global advisory // set holds a fingerprint that differs from the server's key. target := startDivergenceSSHServer(t, serverSigner) first := tofuHostKeyCallback(store, "userA", false) if err := first(target, &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}, keyA); err != nil { t.Fatalf("setup: userA first-use pin failed: %v", err) } _, _, _, _, _, err := openSSHSession(sshTarget{User: "root", Host: "127.0.0.1", Port: portOf(t, target)}, "pw", store, "userB", 80, 24, false) if err == nil { t.Fatal("default connect against the divergent server must be refused") } if !strings.Contains(err.Error(), "ssh: handshake failed:") { t.Fatalf("refusal must surface through the real x/crypto handshake wrap, got: %v", err) } var dke *hostKeyDivergenceError if !errors.As(err, &dke) { t.Fatalf("divergence error must survive the handshake for errors.As (got %T: %v)", err, err) } if dke.presented != hostKeyFingerprint(serverKey) { t.Fatalf("presented must be the server's key fingerprint, got %q", dke.presented) } if len(dke.known) != 1 || dke.known[0] != hostKeyFingerprint(keyA) { t.Fatalf("known must contain exactly userA's fingerprint, got %v", dke.known) } if dke.host != target { t.Fatalf("host must be the dial target, got %q", dke.host) } } // 9. The accept retry (flag true) against the SAME divergent server completes // a real end-to-end connection, pins the presented key, and its audit log // line carries fingerprints only — never the password. func TestDivergenceAcceptRetryCompletesRealConnection(t *testing.T) { dir := t.TempDir() store := filepath.Join(dir, "data", "ssh_known_hosts.json") keyA := mkKey(t) serverKey, serverSigner := mkSignerKey(t) target := startDivergenceSSHServer(t, serverSigner) first := tofuHostKeyCallback(store, "userA", false) if err := first(target, &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}, keyA); err != nil { t.Fatalf("setup: userA first-use pin failed: %v", err) } const password = "sup3r-secret-password-DO-NOT-LOG" // The initial (default) attempt is the divergence refusal — the client's // warning step. if _, _, _, _, _, err := openSSHSession(sshTarget{User: "root", Host: "127.0.0.1", Port: portOf(t, target)}, password, store, "userB", 80, 24, false); !errors.As(err, new(*hostKeyDivergenceError)) { t.Fatalf("pre-accept attempt must be the divergence refusal, got: %v", err) } // Capture the package log while the accept retry runs. var logBuf strings.Builder prevWriter := log.Writer() log.SetOutput(&logBuf) t.Cleanup(func() { log.SetOutput(prevWriter) }) client, _, _, _, _, err := openSSHSession(sshTarget{User: "root", Host: "127.0.0.1", Port: portOf(t, target)}, password, store, "userB", 80, 24, true) if err != nil { t.Fatalf("accept retry must complete a real connection, got: %v", err) } t.Cleanup(func() { _ = client.Close() }) logged := logBuf.String() if !strings.Contains(logged, "explicitly accepted divergent host key") { t.Fatalf("the accept must leave the audit line, got log: %q", logged) } if strings.Contains(logged, password) { t.Fatalf("the audit line must never contain the password, got log: %q", logged) } st := loadKnownHostsMust(t, store) if got := st.Pins[userHostKey("userB", target)]; got != hostKeyFingerprint(serverKey) { t.Fatalf("the accept retry must pin the server's presented key, got %q", got) } } func portOf(t *testing.T, hostport string) int { t.Helper() _, portText, err := net.SplitHostPort(hostport) if err != nil { t.Fatalf("bad test listener address %q: %v", hostport, err) } port, err := strconv.Atoi(portText) if err != nil || port < 1 || port > 65535 { t.Fatalf("bad port %q", portText) } return port }