fix(remote): skip unparseable known_hosts lines instead of failing every connection

A single known_hosts line with a key type x/crypto/ssh does not implement
(OpenSSH 10 ssh-mldsa44-ed25519) made knownhosts.New fail and every SSH
connection abort (QA-11). Such lines are now skipped with a warning in the
log. A host recorded only with an unsupported key type is refused instead
of being re-trusted on first use.

Host key algorithms of keys already recorded for the host are offered
first (like OpenSSH), so a host known only by its ed25519 key is not
reported as changed because x/crypto prefers ECDSA. Algorithms of skipped
lines are never offered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-31 23:39:02 +03:00
parent ecd99fcffc
commit d426752b6e
4 changed files with 369 additions and 14 deletions

View file

@ -87,7 +87,7 @@ func Connect(host SSHHost) (*SSHClient, error) {
return nil, fmt.Errorf("ssh auth: %w", err)
}
hostKeyCB, err := tofuHostKeyCallback()
hostKeyCB, hostKeyAlgos, err := tofuHostKeyCallback(host.Addr())
if err != nil {
return nil, fmt.Errorf("host key verification: %w", err)
}
@ -98,10 +98,11 @@ func Connect(host SSHHost) (*SSHClient, error) {
}
config := &ssh.ClientConfig{
User: user,
Auth: authMethods,
HostKeyCallback: hostKeyCB,
Timeout: 15 * time.Second,
User: user,
Auth: authMethods,
HostKeyCallback: hostKeyCB,
HostKeyAlgorithms: hostKeyAlgos,
Timeout: 15 * time.Second,
}
addr := host.Addr()
@ -154,30 +155,33 @@ func Connect(host SSHHost) (*SSHClient, error) {
// previously recorded entry is rejected outright, since that's the signature
// of a man-in-the-middle attack or a legitimately reissued key that the user
// must verify and update manually (e.g. via `ssh-keygen -R <host>`).
func tofuHostKeyCallback() (ssh.HostKeyCallback, error) {
//
// Lines of known_hosts that cannot be parsed (unknown key types) are skipped,
// see knownHostsDB. It also returns the host key algorithms to offer for addr.
func tofuHostKeyCallback(addr string) (ssh.HostKeyCallback, []string, error) {
khPath := KnownHostsPath()
if khPath == "" {
return nil, fmt.Errorf("cannot determine known_hosts path")
return nil, nil, fmt.Errorf("cannot determine known_hosts path")
}
if err := os.MkdirAll(filepath.Dir(khPath), 0o700); err != nil {
return nil, fmt.Errorf("create ssh dir: %w", err)
return nil, nil, fmt.Errorf("create ssh dir: %w", err)
}
if _, err := os.Stat(khPath); os.IsNotExist(err) {
f, err := os.OpenFile(khPath, os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return nil, fmt.Errorf("create known_hosts: %w", err)
return nil, nil, fmt.Errorf("create known_hosts: %w", err)
}
f.Close()
}
verify, err := knownhosts.New(khPath)
db, err := loadKnownHosts(khPath)
if err != nil {
return nil, fmt.Errorf("parse known_hosts: %w", err)
return nil, nil, err
}
return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
err := verify(hostname, remote, key)
err := db.verify(hostname, remote, key)
if err == nil {
return nil
}
@ -187,6 +191,10 @@ func tofuHostKeyCallback() (ssh.HostKeyCallback, error) {
return fmt.Errorf("REMOTE HOST IDENTIFICATION HAS CHANGED for %s! This may indicate a man-in-the-middle attack, or the server's key was legitimately reissued. Refusing to connect; run `ssh-keygen -R %s` to remove the stale entry once you've verified the new key: %w", hostname, hostname, err)
}
if db.unsupportedOnly(hostname) {
return fmt.Errorf("the host key of %s is recorded in %s only with a key type vcom does not support yet; refusing to trust a different key automatically. Add a supported key for it (e.g. from `ssh-keyscan -t ed25519`) after verifying it: %w", hostname, khPath, err)
}
// Unknown host: trust on first use and remember the key.
line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
f, ferr := os.OpenFile(khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
@ -198,7 +206,7 @@ func tofuHostKeyCallback() (ssh.HostKeyCallback, error) {
return fmt.Errorf("cannot save host key for %s: %w", hostname, werr)
}
return nil
}, nil
}, db.hostKeyAlgorithms(addr), nil
}
// sshAgentAuth connects to the running ssh-agent (via SSH_AUTH_SOCK) and

View file

@ -0,0 +1,202 @@
package remote
import (
"bufio"
"crypto/ed25519"
"errors"
"fmt"
"log"
"net"
"os"
"strconv"
"strings"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
)
// knownHostsDB is a tolerant view of ~/.ssh/known_hosts (QA-11).
//
// knownhosts.New rejects the whole file when a single line cannot be parsed,
// e.g. a key type x/crypto/ssh does not implement such as OpenSSH 10's
// "ssh-mldsa44-ed25519". OpenSSH skips such lines, and so do we: they are
// left out (with a warning in the log) and the rest of the file is used.
//
// A host whose skipped lines are its only record is not silently re-trusted
// on first use: unsupported records which apply to it make the unknown-host
// path refuse instead, since we cannot check the key the user already
// accepted.
type knownHostsDB struct {
verify ssh.HostKeyCallback
// unsupported matches the host patterns of skipped lines (with a
// placeholder key); nil when nothing was skipped.
unsupported ssh.HostKeyCallback
// hasCA: the file has @cert-authority lines, so known keys of a host
// cannot be told apart from CA keys; host key algorithms are then left
// at the x/crypto defaults.
hasCA bool
}
// placeholderKey never matches a real host key; it is used to probe which
// keys are recorded for a host and as the key of placeholder lines.
var placeholderKey = func() ssh.PublicKey {
priv := ed25519.NewKeyFromSeed(make([]byte, ed25519.SeedSize))
pub, err := ssh.NewPublicKey(priv.Public())
if err != nil {
panic(err)
}
return pub
}()
var probeRemote = &net.TCPAddr{IP: net.IPv4zero, Port: 0}
// loadKnownHosts reads khPath, dropping lines knownhosts cannot parse.
func loadKnownHosts(khPath string) (*knownHostsDB, error) {
data, err := os.ReadFile(khPath)
if err != nil {
return nil, fmt.Errorf("read known_hosts: %w", err)
}
lines := strings.Split(string(data), "\n")
verify, skipped, err := parseTolerant(lines, khPath)
if err != nil {
return nil, err
}
db := &knownHostsDB{verify: verify}
for _, l := range lines {
if strings.HasPrefix(strings.TrimSpace(l), "@cert-authority") {
db.hasCA = true
break
}
}
var placeholders []string
marshalled := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(placeholderKey)))
for _, n := range skipped {
fields := strings.Fields(lines[n])
if len(fields) == 0 || strings.HasPrefix(fields[0], "@") {
// @revoked / @cert-authority with an unsupported key: such a
// key can never be negotiated, nothing to protect.
continue
}
placeholders = append(placeholders, fields[0]+" "+marshalled)
}
if len(placeholders) > 0 {
unsupported, _, err := parseTolerant(placeholders, "")
if err == nil {
db.unsupported = unsupported
}
}
return db, nil
}
// parseTolerant feeds lines to knownhosts.New, commenting out every line it
// rejects, and returns the callback and the indexes of the rejected lines.
// origin names the file in log warnings ("" = no warnings).
func parseTolerant(lines []string, origin string) (ssh.HostKeyCallback, []int, error) {
work := make([]string, len(lines))
copy(work, lines)
var skipped []int
skip := func(i int, why string) {
if origin != "" {
log.Printf("[SSH] %s:%d: skipping known_hosts line: %s", origin, i+1, why)
}
work[i] = "#"
skipped = append(skipped, i)
}
for i, l := range work {
// bufio.Scanner in knownhosts fails the whole file on an over-long line.
if len(l) >= bufio.MaxScanTokenSize-1 {
skip(i, "line too long")
}
}
tmp, err := os.CreateTemp("", "vcom-known_hosts-*")
if err != nil {
return nil, nil, fmt.Errorf("parse known_hosts: %w", err)
}
tmpPath := tmp.Name()
tmp.Close()
defer os.Remove(tmpPath)
prefix := "knownhosts: " + tmpPath + ":"
for attempt := 0; attempt <= len(work); attempt++ {
if err := os.WriteFile(tmpPath, []byte(strings.Join(work, "\n")+"\n"), 0o600); err != nil {
return nil, nil, fmt.Errorf("parse known_hosts: %w", err)
}
cb, err := knownhosts.New(tmpPath)
if err == nil {
return cb, skipped, nil
}
msg := err.Error()
rest, ok := strings.CutPrefix(msg, prefix)
if !ok {
return nil, nil, fmt.Errorf("parse known_hosts: %w", err)
}
numStr, why, _ := strings.Cut(rest, ":")
n, perr := strconv.Atoi(numStr)
if perr != nil || n < 1 || n > len(work) || work[n-1] == "#" {
return nil, nil, fmt.Errorf("parse known_hosts: %w", err)
}
skip(n-1, strings.TrimSpace(why))
}
return nil, nil, errors.New("parse known_hosts: too many invalid lines")
}
// unsupportedOnly reports whether hostname has records only in lines that
// were skipped (so a new key must not be trusted on first use).
func (db *knownHostsDB) unsupportedOnly(hostname string) bool {
if db.unsupported == nil {
return false
}
var keyErr *knownhosts.KeyError
err := db.unsupported(hostname, probeRemote, placeholderKey)
if err == nil {
return true
}
return errors.As(err, &keyErr) && len(keyErr.Want) > 0
}
// plainHostKeyAlgos is what the client can verify without certificates.
var plainHostKeyAlgos = []string{
ssh.KeyAlgoED25519,
ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521,
ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256, ssh.KeyAlgoRSA,
}
// hostKeyAlgorithms returns the host key algorithms to offer for addr:
// those of keys already recorded for it first (like OpenSSH), then the rest
// of the plain algorithms. Without that, x/crypto prefers ECDSA, and a
// server known only by its ed25519 key looks like a changed host key.
// Only algorithms x/crypto implements are returned, never the type of a
// skipped line. nil means "use the defaults".
func (db *knownHostsDB) hostKeyAlgorithms(addr string) []string {
if db.hasCA {
return nil
}
var keyErr *knownhosts.KeyError
if err := db.verify(addr, probeRemote, placeholderKey); !errors.As(err, &keyErr) || len(keyErr.Want) == 0 {
return nil
}
known := map[string]bool{}
for _, k := range keyErr.Want {
t := k.Key.Type()
if t == ssh.KeyAlgoRSA {
known[ssh.KeyAlgoRSASHA512] = true
known[ssh.KeyAlgoRSASHA256] = true
}
known[t] = true
}
var first, rest []string
for _, a := range plainHostKeyAlgos {
if known[a] {
first = append(first, a)
} else {
rest = append(rest, a)
}
}
if len(first) == 0 {
return nil
}
return append(first, rest...)
}

View file

@ -0,0 +1,146 @@
package remote
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
"vcom/internal/testutil/sshtest"
)
// Unsupported OpenSSH 10 post-quantum key (QA-11). The blob only has to look
// like base64; x/crypto rejects it by its algorithm name.
const mldsaKey = "ssh-mldsa44-ed25519 AAAAFHNzaC1tbGRzYTQ0LWVkMjU1MTkAAAAA"
func writeKnownHosts(t *testing.T, lines ...string) string {
t.Helper()
p := filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts")
if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
t.Fatal(err)
}
return p
}
func connectTo(srv *sshtest.Server) (*SSHClient, error) {
return Connect(SSHHost{Name: "h", HostName: "127.0.0.1", Port: srv.Port(), User: "u", Password: srv.Password})
}
func hostPattern(srv *sshtest.Server) string {
return knownhosts.Normalize(fmt.Sprintf("127.0.0.1:%s", srv.Port()))
}
// Unparseable lines for other hosts (unknown key type, garbage, bad hash)
// are skipped; the connection proceeds and the new key is recorded.
func TestKnownHostsSkipsUnparseableLines(t *testing.T) {
sshtest.IsolatedHome(t)
srv := sshtest.Start(t, sshtest.Options{})
kh := writeKnownHosts(t,
"# comment",
"otherhost "+mldsaKey,
"garbage-without-key",
"|2|bad|hash ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl",
"@revoked * "+mldsaKey,
)
c, err := connectTo(srv)
if err != nil {
t.Fatalf("connect: %v", err)
}
c.Close()
data, _ := os.ReadFile(kh)
if !strings.Contains(string(data), "otherhost "+mldsaKey) {
t.Fatal("skipped lines must stay in known_hosts untouched")
}
if !strings.Contains(string(data), hostPattern(srv)+" ") {
t.Fatalf("new host key was not recorded:\n%s", data)
}
// Second connection verifies against the recorded key.
c, err = connectTo(srv)
if err != nil {
t.Fatalf("reconnect: %v", err)
}
c.Close()
}
// The maintainer's case: the host is recorded with an unsupported PQ key and
// with its ed25519 key only. The server also has an ECDSA key, which
// x/crypto would prefer by default and then report as a changed key; the
// recorded algorithm must be negotiated instead.
func TestKnownHostsPrefersRecordedAlgorithm(t *testing.T) {
sshtest.IsolatedHome(t)
ed, ec := sshtest.GenKeys(t)
srv := sshtest.Start(t, sshtest.Options{HostKeys: []ssh.Signer{ed, ec}})
writeKnownHosts(t,
hostPattern(srv)+" "+mldsaKey,
knownhosts.Line([]string{hostPattern(srv)}, ed.PublicKey()),
)
c, err := connectTo(srv)
if err != nil {
t.Fatalf("connect: %v", err)
}
c.Close()
}
// A recorded key of a type we cannot check must not be replaced silently
// by trust-on-first-use of another key.
func TestKnownHostsUnsupportedOnlyRefuses(t *testing.T) {
sshtest.IsolatedHome(t)
srv := sshtest.Start(t, sshtest.Options{})
kh := writeKnownHosts(t, hostPattern(srv)+" "+mldsaKey)
if c, err := connectTo(srv); err == nil {
c.Close()
t.Fatal("connected although the only recorded key is of an unsupported type")
} else if !strings.Contains(err.Error(), "does not support") {
t.Fatalf("unexpected error: %v", err)
}
data, _ := os.ReadFile(kh)
if strings.Count(string(data), "\n") != 1 {
t.Fatalf("known_hosts modified:\n%s", data)
}
}
// A changed key is still refused when the file also has unsupported lines.
func TestKnownHostsMismatchStillRefused(t *testing.T) {
sshtest.IsolatedHome(t)
srv := sshtest.Start(t, sshtest.Options{})
other, _ := sshtest.GenKeys(t)
writeKnownHosts(t,
"otherhost "+mldsaKey,
knownhosts.Line([]string{hostPattern(srv)}, other.PublicKey()),
)
if c, err := connectTo(srv); err == nil {
c.Close()
t.Fatal("connected with a mismatching recorded key")
} else if !strings.Contains(err.Error(), "HAS CHANGED") {
t.Fatalf("unexpected error: %v", err)
}
}
func TestHostKeyAlgorithmsNeverUnsupported(t *testing.T) {
sshtest.IsolatedHome(t)
ed, _ := sshtest.GenKeys(t)
kh := writeKnownHosts(t,
"h.example "+mldsaKey,
knownhosts.Line([]string{"h.example"}, ed.PublicKey()),
)
db, err := loadKnownHosts(kh)
if err != nil {
t.Fatal(err)
}
algos := db.hostKeyAlgorithms("h.example:22")
if len(algos) == 0 || algos[0] != ssh.KeyAlgoED25519 {
t.Fatalf("recorded algorithm not first: %v", algos)
}
for _, a := range algos {
if strings.Contains(a, "mldsa") {
t.Fatalf("unsupported algorithm offered: %v", algos)
}
}
if got := db.hostKeyAlgorithms("unknown.example:22"); got != nil {
t.Fatalf("unknown host: want defaults, got %v", got)
}
}

View file

@ -466,7 +466,6 @@ func TestQARemoteMirrorDeleteJobAndLeave(t *testing.T) {
// (OpenSSH 10 post-quantum "ssh-mldsa44-ed25519", present on the
// maintainer's machine) makes every connection fail with "parse known_hosts".
func TestQAKnownHostsUnknownAlgorithm(t *testing.T) {
t.Skip("BUG QA-11 (P1, since v0.2.7): an unknown key algorithm anywhere in ~/.ssh/known_hosts aborts every SSH connection (knownhosts.New parse error is fatal, internal/fs/remote/client.go:174-176)")
isolateEnv(t)
kh := filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts")
writeFile(t, kh, "otherhost ssh-mldsa44-ed25519 AAAAFHNzaC1tbGRzYTQ0LWVkMjU1MTkAAAAA\n")