The whole handshake (TCP, kex, auth, SFTP init) runs under a deadline that ctx cancellation cuts short, and a late client is closed (N-P1-3). HostKeyAlgorithms come from known_hosts (N-P1-4); unknown and changed keys go to a Prompter (N-P2-14). Auth tries identity files, then agent keys over one shared agent connection, then default keys, password and keyboard-interactive through the Prompter (N-P2-1, N-P2-2). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
272 lines
7.5 KiB
Go
272 lines
7.5 KiB
Go
package conn
|
|
|
|
import (
|
|
"context"
|
|
"crypto/ed25519"
|
|
"crypto/rand"
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"os"
|
|
"path/filepath"
|
|
"sync"
|
|
|
|
"golang.org/x/crypto/ssh"
|
|
"golang.org/x/crypto/ssh/knownhosts"
|
|
|
|
"vcom/internal/ssh/internal/atomicwrite"
|
|
)
|
|
|
|
var (
|
|
// ErrHostKeyRejected: the key is unknown and the user (or the absence of
|
|
// a Prompter) refused it.
|
|
ErrHostKeyRejected = errors.New("host key rejected")
|
|
// ErrHostKeyChanged: known_hosts has a different key of the same type.
|
|
ErrHostKeyChanged = errors.New("REMOTE HOST IDENTIFICATION HAS CHANGED")
|
|
)
|
|
|
|
// HostKeyError describes a refused host key. It unwraps to
|
|
// ErrHostKeyChanged or ErrHostKeyRejected.
|
|
type HostKeyError struct {
|
|
Host string // host:port as checked against known_hosts
|
|
Identity HostIdentity
|
|
Known []HostIdentity
|
|
Changed bool
|
|
}
|
|
|
|
func (e *HostKeyError) Error() string {
|
|
if e.Changed {
|
|
return fmt.Sprintf("%v for %s: server offers %s %s; remove the stale entry with `ssh-keygen -R %s` once the new key is verified",
|
|
ErrHostKeyChanged, e.Host, e.Identity.KeyType, e.Identity.FingerprintSHA256, e.Host)
|
|
}
|
|
return fmt.Sprintf("%v: %s %s %s", ErrHostKeyRejected, e.Host, e.Identity.KeyType, e.Identity.FingerprintSHA256)
|
|
}
|
|
|
|
func (e *HostKeyError) Unwrap() error {
|
|
if e.Changed {
|
|
return ErrHostKeyChanged
|
|
}
|
|
return ErrHostKeyRejected
|
|
}
|
|
|
|
// probeKey is a throwaway key that is never in known_hosts: checking it
|
|
// makes knownhosts report every key it has for a host (KeyError.Want).
|
|
var probeKey = sync.OnceValue(func() ssh.PublicKey {
|
|
pub, _, err := ed25519.GenerateKey(rand.Reader)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
k, err := ssh.NewPublicKey(pub)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return k
|
|
})
|
|
|
|
// knownHosts verifies host keys against known_hosts files plus keys
|
|
// accepted during this process.
|
|
type knownHosts struct {
|
|
files []string // read in order
|
|
write string // AcceptAndSave appends here ("" = memory only)
|
|
warn func(string)
|
|
|
|
mu sync.Mutex
|
|
session map[string][]ssh.PublicKey // knownhosts.Normalize(host:port) -> keys
|
|
}
|
|
|
|
func newKnownHosts(files []string, write string, warn func(string)) *knownHosts {
|
|
return &knownHosts{files: files, write: write, warn: warn, session: map[string][]ssh.PublicKey{}}
|
|
}
|
|
|
|
// db parses the existing known_hosts files; nil when there are none.
|
|
func (h *knownHosts) db() (ssh.HostKeyCallback, error) {
|
|
var files []string
|
|
for _, f := range h.files {
|
|
if _, err := os.Stat(f); err == nil {
|
|
files = append(files, f)
|
|
}
|
|
}
|
|
if len(files) == 0 {
|
|
return nil, nil
|
|
}
|
|
return knownhosts.New(files...)
|
|
}
|
|
|
|
// known returns every key on record for hostport (files, then session).
|
|
func (h *knownHosts) known(hostport string) []ssh.PublicKey {
|
|
var out []ssh.PublicKey
|
|
if cb, err := h.db(); err == nil && cb != nil {
|
|
var ke *knownhosts.KeyError
|
|
if err := cb(hostport, &net.TCPAddr{IP: net.IPv4zero}, probeKey()); errors.As(err, &ke) {
|
|
for _, k := range ke.Want {
|
|
out = append(out, k.Key)
|
|
}
|
|
}
|
|
}
|
|
h.mu.Lock()
|
|
out = append(out, h.session[knownhosts.Normalize(hostport)]...)
|
|
h.mu.Unlock()
|
|
return out
|
|
}
|
|
|
|
// algorithms lists host key algorithms for the key types on record, so the
|
|
// server is asked for a key we can actually verify (N-P1-4: Go prefers ECDSA,
|
|
// OpenSSH usually records ed25519). nil means "library defaults".
|
|
func (h *knownHosts) algorithms(hostport string) []string {
|
|
var algos []string
|
|
seen := map[string]bool{}
|
|
add := func(a string) {
|
|
if !seen[a] {
|
|
seen[a] = true
|
|
algos = append(algos, a)
|
|
}
|
|
}
|
|
for _, k := range h.known(hostport) {
|
|
switch t := k.Type(); t {
|
|
case ssh.KeyAlgoRSA:
|
|
add(ssh.KeyAlgoRSASHA512)
|
|
add(ssh.KeyAlgoRSASHA256)
|
|
add(ssh.KeyAlgoRSA)
|
|
default:
|
|
add(t)
|
|
}
|
|
}
|
|
return algos
|
|
}
|
|
|
|
func (h *knownHosts) sessionHas(hostport string, key ssh.PublicKey) bool {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
for _, k := range h.session[knownhosts.Normalize(hostport)] {
|
|
if string(k.Marshal()) == string(key.Marshal()) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (h *knownHosts) remember(hostport string, key ssh.PublicKey) {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
n := knownhosts.Normalize(hostport)
|
|
h.session[n] = append(h.session[n], key)
|
|
}
|
|
|
|
func (h *knownHosts) warnf(format string, args ...any) {
|
|
if h.warn != nil {
|
|
h.warn(fmt.Sprintf(format, args...))
|
|
}
|
|
}
|
|
|
|
// save appends a known_hosts line atomically (rewrite via temp copy). When
|
|
// the file belongs to another user (vcom under sudo) or cannot be written,
|
|
// the key is trusted for this process only and a warning is emitted
|
|
// (N-P2-14).
|
|
func (h *knownHosts) save(hostport string, key ssh.PublicKey) {
|
|
h.remember(hostport, key)
|
|
if h.write == "" {
|
|
h.warnf("host key for %s accepted for this session only (no known_hosts file configured)", hostport)
|
|
return
|
|
}
|
|
if foreignOwner(h.write) {
|
|
h.warnf("host key for %s accepted for this session only: %s belongs to another user", hostport, h.write)
|
|
return
|
|
}
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
if err := appendKnownHost(h.write, knownhosts.Line([]string{knownhosts.Normalize(hostport)}, key)); err != nil {
|
|
h.warnf("host key for %s accepted for this session only: %v", hostport, err)
|
|
}
|
|
}
|
|
|
|
func appendKnownHost(path, line string) error {
|
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
|
return err
|
|
}
|
|
perm := os.FileMode(0o600)
|
|
data, err := os.ReadFile(path)
|
|
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
|
return err
|
|
}
|
|
if fi, err := os.Stat(path); err == nil {
|
|
perm = fi.Mode().Perm()
|
|
}
|
|
if len(data) > 0 && data[len(data)-1] != '\n' {
|
|
data = append(data, '\n')
|
|
}
|
|
data = append(data, line+"\n"...)
|
|
return atomicwrite.WriteFile(path, data, perm)
|
|
}
|
|
|
|
// callback builds the HostKeyCallback for one dial. prompt wraps Prompter
|
|
// calls so the handshake deadline is paused while the user decides; onKey
|
|
// sees every key the server presents (also on later re-keys).
|
|
func (h *knownHosts) callback(ctx context.Context, ep Endpoint, p Prompter, prompt func(func() error) error, onKey func(HostIdentity)) ssh.HostKeyCallback {
|
|
return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
|
id := IdentityOf(key)
|
|
onKey(id)
|
|
if h.sessionHas(hostname, key) {
|
|
return nil
|
|
}
|
|
var wants []ssh.PublicKey
|
|
cb, err := h.db()
|
|
if err != nil {
|
|
return fmt.Errorf("known_hosts: %w", err)
|
|
}
|
|
if cb != nil {
|
|
err := cb(hostname, remote, key)
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
var ke *knownhosts.KeyError
|
|
if !errors.As(err, &ke) {
|
|
return err // revoked key, unreadable file, ...
|
|
}
|
|
for _, k := range ke.Want {
|
|
wants = append(wants, k.Key)
|
|
}
|
|
}
|
|
h.mu.Lock()
|
|
wants = append(wants, h.session[knownhosts.Normalize(hostname)]...)
|
|
h.mu.Unlock()
|
|
// Alarm only when a key of the same type is on record and differs; a
|
|
// key of a type we have no record for is merely unknown.
|
|
changed := false
|
|
known := make([]HostIdentity, 0, len(wants))
|
|
for _, k := range wants {
|
|
known = append(known, IdentityOf(k))
|
|
if k.Type() == key.Type() {
|
|
changed = true
|
|
}
|
|
}
|
|
herr := &HostKeyError{Host: hostname, Identity: id, Known: known, Changed: changed}
|
|
if p == nil {
|
|
return herr
|
|
}
|
|
var dec HostKeyDecision
|
|
if err := prompt(func() error {
|
|
var err error
|
|
dec, err = p.HostKey(ctx, ep, id, known, changed)
|
|
return err
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
switch dec {
|
|
case AcceptOnce:
|
|
h.remember(hostname, key)
|
|
return nil
|
|
case AcceptAndSave:
|
|
if changed {
|
|
// Replacing a stale line is left to `ssh-keygen -R`; trust the
|
|
// new key for this process only.
|
|
h.remember(hostname, key)
|
|
h.warnf("changed host key for %s accepted for this session only", hostname)
|
|
return nil
|
|
}
|
|
h.save(hostname, key)
|
|
return nil
|
|
default:
|
|
return herr
|
|
}
|
|
}
|
|
}
|