package main import ( "encoding/json" "fmt" "net" "os" "path/filepath" "strings" "testing" ) // loadKnownHostsMust loads the store at path and fails the test when the // file exists but cannot be parsed. func loadKnownHostsMust(t *testing.T, path string) knownHostsStore { t.Helper() st, err := loadKnownHosts(path) if err != nil { t.Fatalf("loadKnownHosts(%q) failed: %v", path, err) } return st } // newTestStore returns an empty, fully-initialized store for direct // recordPin / recordGlobalFingerprint unit tests. func newTestStore() knownHostsStore { return knownHostsStore{ Pins: map[string]string{}, Global: map[string][]string{}, GlobalContrib: map[string]string{}, } } // Core of the eviction attack: a malicious user floods first-use pins for // hosts they control; eviction must be PER USER (offender pays) so the // flood only costs the attacker their own oldest pins and can never evict // another user's pinned key (which would let a MITM key be silently pinned // on the victim's next connect). func TestPinFloodDoesNotEvictOtherUsersPins(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} victimKey := mkKey(t) victim := tofuHostKeyCallback(store, "victim", false) if err := victim("victim.example:22", addr, victimKey); err != nil { t.Fatalf("victim first-use pin failed: %v", err) } attacker := tofuHostKeyCallback(store, "attacker", false) for i := 0; i < 300; i++ { if err := attacker(fmt.Sprintf("flood-%d.example:22", i), addr, mkKey(t)); err != nil { t.Fatalf("attacker flood pin %d failed: %v", i, err) } } // The victim's pin survived the flood: reconnect still verifies exactly. if err := victim("victim.example:22", addr, victimKey); err != nil { t.Fatalf("victim pin must survive an attacker's pin flood, got: %v", err) } st := loadKnownHostsMust(t, store) if got := st.Pins[userHostKey("victim", "victim.example:22")]; got != hostKeyFingerprint(victimKey) { t.Fatalf("victim pin missing from store, got %q", got) } // The attacker absorbed the cap themselves. if n := countUserPins(&st, "attacker"); n != maxKnownHostsPinsPerUser { t.Fatalf("attacker should be capped at %d own pins, has %d", maxKnownHostsPinsPerUser, n) } } // Same attack against the advisory Global divergence map: flooding hosts // must only evict the attacker's OWN contributed hosts, so the victim's // advisory entry survives and divergences on it are still reported. func TestGlobalFloodDoesNotEvictOtherUsersAdvisoryHosts(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} victimKey := mkKey(t) victim := tofuHostKeyCallback(store, "victim", false) if err := victim("shared.example:22", addr, victimKey); err != nil { t.Fatalf("victim first-use pin failed: %v", err) } attacker := tofuHostKeyCallback(store, "attacker", false) for i := 0; i < 300; i++ { if err := attacker(fmt.Sprintf("gossip-%d.example:22", i), addr, mkKey(t)); err != nil { t.Fatalf("attacker flood %d failed: %v", i, err) } } st := loadKnownHostsMust(t, store) if _, ok := st.Global["shared.example:22"]; !ok { t.Fatal("victim host's advisory entry must survive an attacker's global flood") } // The attacker absorbed the per-contributor cap themselves; without that // cap this assertion fails (the flood would leave 300 attacker hosts in // the map, all below the 2048 total cap, so nothing else here would catch // the missing per-user eviction). if n := countUserGlobalHosts(&st, "attacker"); n != maxGlobalHostsPerUser { t.Fatalf("attacker should be capped at %d own advisory hosts, has %d", maxGlobalHostsPerUser, n) } // The advisory entry is still live: a third user presenting a NEW key on // the victim's host must still get the divergence warning. third := tofuHostKeyCallback(store, "third", false) err := third("shared.example:22", addr, mkKey(t)) if err == nil { t.Fatal("divergence for the victim host must still be detected after the flood") } else if !strings.Contains(strings.ToLower(err.Error()), "divergence") { t.Fatalf("expected divergence error, got: %v", err) } } // A user exceeding the per-user cap ends at exactly the cap, losing their // OWN oldest entries; no other user's entries are touched. Covers both the // pin store and the advisory Global map's per-contributor cap. func TestPerUserCapEvictsOwnOldest(t *testing.T) { st := newTestStore() for i := 0; i < maxKnownHostsPinsPerUser+6; i++ { recordPin(&st, "u1", userHostKey("u1", fmt.Sprintf("h%03d:22", i)), fmt.Sprintf("fp-%d", i)) } recordPin(&st, "u2", userHostKey("u2", "other:22"), "fp-u2") if n := countUserPins(&st, "u1"); n != maxKnownHostsPinsPerUser { t.Fatalf("u1 should hold exactly %d pins, has %d", maxKnownHostsPinsPerUser, n) } if _, ok := st.Pins[userHostKey("u1", "h000:22")]; ok { t.Fatal("u1's own oldest pin should have been evicted") } if got := st.Pins[userHostKey("u1", fmt.Sprintf("h%03d:22", maxKnownHostsPinsPerUser+5))]; got != fmt.Sprintf("fp-%d", maxKnownHostsPinsPerUser+5) { t.Fatalf("u1's newest pin should survive, got %q", got) } if got := st.Pins[userHostKey("u2", "other:22")]; got != "fp-u2" { t.Fatalf("another user's pin must be untouched, got %q", got) } recordGlobalFingerprint(&st, "u2host.example:22", "gfp-u2", "u2") for i := 0; i < maxGlobalHostsPerUser+2; i++ { recordGlobalFingerprint(&st, fmt.Sprintf("g%03d.example:22", i), fmt.Sprintf("gfp-%d", i), "u1") } if n := countUserGlobalHosts(&st, "u1"); n != maxGlobalHostsPerUser { t.Fatalf("u1 should contribute exactly %d advisory hosts, has %d", maxGlobalHostsPerUser, n) } if _, ok := st.Global["g000.example:22"]; ok { t.Fatal("u1's own oldest contributed host should have been evicted") } if _, ok := st.Global[fmt.Sprintf("g%03d.example:22", maxGlobalHostsPerUser+1)]; !ok { t.Fatal("u1's newest contributed host should survive") } if _, ok := st.Global["u2host.example:22"]; !ok { t.Fatal("another user's advisory host must be untouched") } } // The total caps are backstops: an overflowing insert must evict from the // LARGEST contributor's entries (offender pays), not from the globally // oldest entry, and the total must stay at the cap. The setup builds the // two users up to the cap directly, because recordPin would keep each user // at maxKnownHostsPinsPerUser long before 2048 entries. The smaller user's // entries are inserted FIRST, so they are the globally oldest: a globally- // oldest eviction would hit them, so the assertions below only pass with // true offender-pays eviction. func TestOffenderPaysBackstopEviction(t *testing.T) { st := newTestStore() for i := 0; i < 10; i++ { k := userHostKey("u2", fmt.Sprintf("small-%04d:22", i)) st.Pins[k] = "fp-u2" st.PinsOrder = append(st.PinsOrder, k) } for i := 0; i < maxKnownHostsPins-10; i++ { k := userHostKey("u1", fmt.Sprintf("big-%04d:22", i)) st.Pins[k] = "fp-u1" st.PinsOrder = append(st.PinsOrder, k) } if len(st.Pins) != maxKnownHostsPins { t.Fatalf("setup: store must be exactly at the cap %d, has %d", maxKnownHostsPins, len(st.Pins)) } // Overflowing insert BY u2 must cost the largest user (u1). recordPin(&st, "u2", userHostKey("u2", "overflow:22"), "fp-overflow") if len(st.Pins) != maxKnownHostsPins { t.Fatalf("total pins must stay at the cap %d, got %d", maxKnownHostsPins, len(st.Pins)) } if _, ok := st.Pins[userHostKey("u1", "big-0000:22")]; ok { t.Fatal("backstop eviction must hit the largest user's OLDEST pin (u1)") } if n := countUserPins(&st, "u1"); n != maxKnownHostsPins-11 { t.Fatalf("u1 should have paid one pin (%d), has %d", maxKnownHostsPins-11, n) } if n := countUserPins(&st, "u2"); n != 11 { t.Fatalf("u2 should have gained a pin (11), has %d", n) } if _, ok := st.Pins[userHostKey("u2", "small-0000:22")]; !ok { t.Fatal("the inserting user's oldest pin must not be evicted by the backstop") } // Same offender-pays shape for the advisory Global map. for i := 0; i < maxKnownHostsGlobalHosts-10; i++ { h := fmt.Sprintf("gh-big-%04d.example:22", i) st.Global[h] = []string{"gfp"} st.GlobalOrder = append(st.GlobalOrder, h) st.GlobalContrib[h] = "u1" } for i := 0; i < 10; i++ { h := fmt.Sprintf("gh-small-%04d.example:22", i) st.Global[h] = []string{"gfp"} st.GlobalOrder = append(st.GlobalOrder, h) st.GlobalContrib[h] = "u2" } recordGlobalFingerprint(&st, "gh-overflow.example:22", "gfp", "u2") if len(st.Global) != maxKnownHostsGlobalHosts { t.Fatalf("total advisory hosts must stay at the cap %d, got %d", maxKnownHostsGlobalHosts, len(st.Global)) } if _, ok := st.Global["gh-big-0000.example:22"]; ok { t.Fatal("backstop eviction must hit the largest contributor's OLDEST host (u1)") } if n := countUserGlobalHosts(&st, "u1"); n != maxKnownHostsGlobalHosts-11 { t.Fatalf("u1 should have paid one host (%d), has %d", maxKnownHostsGlobalHosts-11, n) } if st.GlobalContrib["gh-overflow.example:22"] != "u2" { t.Fatalf("new host must be attributed to its contributor, got %q", st.GlobalContrib["gh-overflow.example:22"]) } } // BUG 6 regression: the resident store must reload when the file changes on // disk. An admin edit takes effect on the next connection (no restart), a // corrupt file keeps the last good state (fail closed), and a deleted file // behaves as an empty store (the next save recreates it). func TestKnownHostsReloadOnFileChange(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 := "reload.example:22" key1 := mkKey(t) key2 := mkKey(t) key3 := mkKey(t) key4 := mkKey(t) cb := tofuHostKeyCallback(store, "userA", false) if err := cb(host, addr, key1); err != nil { t.Fatalf("initial pin failed: %v", err) } // An admin edits the file out-of-band, removing userA's entry (pin and // advisory host) — exactly what the mismatch error text instructs. b, err := os.ReadFile(store) if err != nil { t.Fatal(err) } var edited knownHostsStore if err := json.Unmarshal(b, &edited); err != nil { t.Fatal(err) } delete(edited.Pins, userHostKey("userA", host)) delete(edited.Global, host) delete(edited.GlobalContrib, host) out, err := json.MarshalIndent(edited, "", " ") if err != nil { t.Fatal(err) } if err := os.WriteFile(store, out, 0o600); err != nil { t.Fatal(err) } // The next connection must see the edited file WITHOUT a restart: userA // gets a fresh first-use pin (a stale cache would reject key2 as a // mismatch against the removed key1 pin). if err := cb(host, addr, key2); err != nil { t.Fatalf("next connection must behave as first use after the admin edit, got: %v", err) } // A corrupt file must not take the resident (last good) store down: the // key pinned above still mismatches a different key, fail closed. if err := os.WriteFile(store, []byte("{not json"), 0o600); err != nil { t.Fatal(err) } err = cb(host, addr, key3) if err == nil || !strings.Contains(strings.ToLower(err.Error()), "host key mismatch") { t.Fatalf("corrupt file must keep the last good state (mismatch expected), got: %v", err) } // A deleted file means "clear all": the next connection is a first use // again, and the next save recreates the file. if err := os.Remove(store); err != nil { t.Fatal(err) } if err := cb(host, addr, key4); err != nil { t.Fatalf("deleted store must behave as empty (first-use pin), got: %v", err) } if _, err := os.Stat(store); err != nil { t.Fatalf("next save should recreate the store file: %v", err) } } // A store file that exists but cannot be READ (permissions, I/O error, the // path replaced by a directory) is NOT the same as a missing or empty one: // loadKnownHosts must report the error so callers keep their last good state // instead of silently degrading to an empty store, which would drop every // pin and let the next connection re-pin whatever key it is shown. func TestLoadKnownHostsUnreadableFileIsAnError(t *testing.T) { dir := t.TempDir() // Missing file: a fresh store, not an error. if _, err := loadKnownHosts(filepath.Join(dir, "missing.json")); err != nil { t.Fatalf("a missing store file must load as empty, got: %v", err) } // Empty file: also a fresh store (v0 behavior). emptyPath := filepath.Join(dir, "empty.json") if err := os.WriteFile(emptyPath, nil, 0o600); err != nil { t.Fatal(err) } if _, err := loadKnownHosts(emptyPath); err != nil { t.Fatalf("an empty store file must load as empty, got: %v", err) } // A directory where the file is expected: os.Stat succeeds, the read // fails with EISDIR (not ENOENT) — a read error, not a fresh store. This // works even when running the tests as root, unlike a chmod 000. if err := os.Mkdir(filepath.Join(dir, "dir.json"), 0o700); err != nil { t.Fatal(err) } if _, err := loadKnownHosts(filepath.Join(dir, "dir.json")); err == nil { t.Fatal("a directory in place of the store file must be a load error, not an empty store") } } // End-to-end version of the above: once the store is resident, replacing the // file with something unreadable must keep the last good state — the old pin // stays enforced (a different key must MISMATCH), rather than the store // degrading to empty and silently pinning the new key. func TestReloadKeepsLastGoodStateOnUnreadableFile(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 := "unreadable.example:22" key1 := mkKey(t) key2 := mkKey(t) cb := tofuHostKeyCallback(store, "userU", false) if err := cb(host, addr, key1); err != nil { t.Fatalf("initial pin failed: %v", err) } // Replace the store file with a DIRECTORY: the stat in cachedKnownHosts // succeeds (so the reload triggers) but the read fails. The resident // store must keep the last good state; the reload of the unreadable file // must NOT be treated as an empty store. if err := os.Remove(store); err != nil { t.Fatal(err) } if err := os.Mkdir(store, 0o700); err != nil { t.Fatal(err) } err := cb(host, addr, key2) if err == nil { t.Fatal("pinned key must still be enforced when the store file is unreadable") } if !strings.Contains(strings.ToLower(err.Error()), "host key mismatch") { // An empty-store degradation would instead fail later with "host key // store unavailable" (the save hits the directory) after silently // accepting the new key's re-pin path. t.Fatalf("expected the kept last-good pin to mismatch, got: %v", err) } } // A store written over the caps heals itself on load: every user is trimmed // to their own per-user cap (keeping their newest entries) and the total // stays within the global cap. A v1 file without globalContrib still loads // and works (backward compatibility). func TestTrimHealsOverCapStores(t *testing.T) { dir := t.TempDir() store := filepath.Join(dir, "data", "ssh_known_hosts.json") // 3000 pins spread across 30 users in per-user chunks (100 each). over := newTestStore() for u := 0; u < 30; u++ { uid := fmt.Sprintf("user%02d", u) for i := 0; i < 100; i++ { k := userHostKey(uid, fmt.Sprintf("h%03d:22", i)) over.Pins[k] = "fp" over.PinsOrder = append(over.PinsOrder, k) } } b, err := json.MarshalIndent(over, "", " ") if err != nil { t.Fatal(err) } if err := os.MkdirAll(filepath.Dir(store), 0o700); err != nil { t.Fatal(err) } if err := os.WriteFile(store, b, 0o600); err != nil { t.Fatal(err) } st, err := loadKnownHosts(store) if err != nil { t.Fatalf("over-cap store must still load: %v", err) } total := 0 for uid, n := range countPinsPerUser(&st) { if n > maxKnownHostsPinsPerUser { t.Fatalf("user %q has %d pins, over the per-user cap %d", uid, n, maxKnownHostsPinsPerUser) } total += n } if total > maxKnownHostsPins { t.Fatalf("healed store holds %d pins, over the total cap %d", total, maxKnownHostsPins) } if total == 0 { t.Fatal("healing must not empty the store") } if n := countUserPins(&st, "user00"); n != maxKnownHostsPinsPerUser { t.Fatalf("user00 should be healed to exactly %d pins, has %d", maxKnownHostsPinsPerUser, n) } if _, ok := st.Pins[userHostKey("user00", "h000:22")]; ok { t.Fatal("user00's own oldest pin should have been evicted by healing") } if _, ok := st.Pins[userHostKey("user00", "h099:22")]; !ok { t.Fatal("user00's newest pin should survive healing") } // Backward compat: a v1 file (pins/global/orders, NO globalContrib) // still loads, its pins stay readable, and recording still works on it. v1 := knownHostsStore{ Pins: map[string]string{userHostKey("legacy", "old.example:22"): "fp-legacy"}, Global: map[string][]string{"old.example:22": {"fp-legacy"}}, PinsOrder: []string{userHostKey("legacy", "old.example:22")}, GlobalOrder: []string{"old.example:22"}, } v1b, err := json.MarshalIndent(v1, "", " ") if err != nil { t.Fatal(err) } v1Path := filepath.Join(dir, "data", "v1_known_hosts.json") if err := os.WriteFile(v1Path, v1b, 0o600); err != nil { t.Fatal(err) } v1st, err := loadKnownHosts(v1Path) if err != nil { t.Fatalf("v1 store must load without error: %v", err) } if got := v1st.Pins[userHostKey("legacy", "old.example:22")]; got != "fp-legacy" { t.Fatalf("v1 pin must be readable, got %q", got) } if v1st.GlobalContrib == nil { t.Fatal("loadKnownHosts must initialize GlobalContrib for v1 stores") } recordGlobalFingerprint(&v1st, "new.example:22", "gfp-new", "legacy") if _, ok := v1st.Global["new.example:22"]; !ok { t.Fatal("recording on a v1-loaded store must work") } if v1st.GlobalContrib["new.example:22"] != "legacy" { t.Fatalf("new host must be attributed to its contributor, got %q", v1st.GlobalContrib["new.example:22"]) } }