vcom/internal/fs/remote/knownhosts.go
vrubelroman d426752b6e 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>
2026-10-31 23:39:02 +03:00

202 lines
6.1 KiB
Go

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