From 8584a638f1d99bf3ce4ab049b5895e1cf895c439 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 23:27:58 +0300 Subject: [PATCH 1/4] feat(ssh): add sshconfig resolver and host store (2B.1) Resolve host aliases through ~/.ssh/config with kevinburke/ssh_config: HostName defaults to the alias, key=value syntax, Host * defaults, Include, quotes, several IdentityFile, '#' inside values (N-P1-5). Endpoint.Key includes the user (N-P2-3). Port the hosts.dat store with atomic writes and a base64 password field. Co-Authored-By: Claude Opus 5.5 --- go.mod | 1 + go.sum | 2 + .../ssh/internal/atomicwrite/atomicwrite.go | 48 + .../internal/atomicwrite/atomicwrite_test.go | 31 + internal/ssh/sshconfig/flatten.go | 199 ++++ internal/ssh/sshconfig/resolver.go | 391 ++++++++ internal/ssh/sshconfig/resolver_test.go | 285 ++++++ internal/ssh/sshconfig/store.go | 317 +++++++ internal/ssh/sshconfig/store_test.go | 102 ++ plans/rework/04-dev-log-B.md | 31 + .../kevinburke/ssh_config/.gitignore | 1 + .../github.com/kevinburke/ssh_config/.mailmap | 1 + .../kevinburke/ssh_config/AUTHORS.txt | 13 + .../kevinburke/ssh_config/CHANGELOG.md | 65 ++ .../github.com/kevinburke/ssh_config/LICENSE | 49 + .../github.com/kevinburke/ssh_config/Makefile | 34 + .../kevinburke/ssh_config/README.md | 92 ++ .../kevinburke/ssh_config/SECURITY.md | 63 ++ .../kevinburke/ssh_config/config.go | 878 ++++++++++++++++++ .../github.com/kevinburke/ssh_config/lexer.go | 240 +++++ .../kevinburke/ssh_config/parser.go | 270 ++++++ .../kevinburke/ssh_config/position.go | 25 + .../github.com/kevinburke/ssh_config/token.go | 49 + .../kevinburke/ssh_config/validators.go | 186 ++++ vendor/modules.txt | 3 + 25 files changed, 3376 insertions(+) create mode 100644 internal/ssh/internal/atomicwrite/atomicwrite.go create mode 100644 internal/ssh/internal/atomicwrite/atomicwrite_test.go create mode 100644 internal/ssh/sshconfig/flatten.go create mode 100644 internal/ssh/sshconfig/resolver.go create mode 100644 internal/ssh/sshconfig/resolver_test.go create mode 100644 internal/ssh/sshconfig/store.go create mode 100644 internal/ssh/sshconfig/store_test.go create mode 100644 plans/rework/04-dev-log-B.md create mode 100644 vendor/github.com/kevinburke/ssh_config/.gitignore create mode 100644 vendor/github.com/kevinburke/ssh_config/.mailmap create mode 100644 vendor/github.com/kevinburke/ssh_config/AUTHORS.txt create mode 100644 vendor/github.com/kevinburke/ssh_config/CHANGELOG.md create mode 100644 vendor/github.com/kevinburke/ssh_config/LICENSE create mode 100644 vendor/github.com/kevinburke/ssh_config/Makefile create mode 100644 vendor/github.com/kevinburke/ssh_config/README.md create mode 100644 vendor/github.com/kevinburke/ssh_config/SECURITY.md create mode 100644 vendor/github.com/kevinburke/ssh_config/config.go create mode 100644 vendor/github.com/kevinburke/ssh_config/lexer.go create mode 100644 vendor/github.com/kevinburke/ssh_config/parser.go create mode 100644 vendor/github.com/kevinburke/ssh_config/position.go create mode 100644 vendor/github.com/kevinburke/ssh_config/token.go create mode 100644 vendor/github.com/kevinburke/ssh_config/validators.go diff --git a/go.mod b/go.mod index f4ef489..7245dde 100644 --- a/go.mod +++ b/go.mod @@ -22,6 +22,7 @@ require ( github.com/charmbracelet/x/term v0.2.1 // indirect github.com/dlclark/regexp2 v1.11.5 // indirect github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/kevinburke/ssh_config v1.6.0 // indirect github.com/kr/fs v0.1.0 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect diff --git a/go.sum b/go.sum index 8e88b2c..717bc31 100644 --- a/go.sum +++ b/go.sum @@ -30,6 +30,8 @@ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= +github.com/kevinburke/ssh_config v1.6.0 h1:J1FBfmuVosPHf5GRdltRLhPJtJpTlMdKTBjRgTaQBFY= +github.com/kevinburke/ssh_config v1.6.0/go.mod h1:q2RIzfka+BXARoNexmF9gkxEX7DmvbW9P4hIVx2Kg4M= github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= diff --git a/internal/ssh/internal/atomicwrite/atomicwrite.go b/internal/ssh/internal/atomicwrite/atomicwrite.go new file mode 100644 index 0000000..cde81e0 --- /dev/null +++ b/internal/ssh/internal/atomicwrite/atomicwrite.go @@ -0,0 +1,48 @@ +// Package atomicwrite is a stop-gap atomic file writer for internal/ssh. +// +// TODO(2C.1): replace with internal/atomicfile.WriteFile once it is merged; +// this package exists only so that 2B can land independently of 2C. +package atomicwrite + +import ( + "os" + "path/filepath" +) + +// WriteFile writes data to path atomically: a temp file in the same +// directory is written, fsynced, renamed over path, and the directory is +// fsynced. Readers see either the old or the new content, never a prefix. +func WriteFile(path string, data []byte, perm os.FileMode) (err error) { + dir := filepath.Dir(path) + f, err := os.CreateTemp(dir, "."+filepath.Base(path)+".tmp-*") + if err != nil { + return err + } + tmp := f.Name() + defer func() { + if err != nil { + f.Close() + os.Remove(tmp) + } + }() + if err = f.Chmod(perm); err != nil { + return err + } + if _, err = f.Write(data); err != nil { + return err + } + if err = f.Sync(); err != nil { + return err + } + if err = f.Close(); err != nil { + return err + } + if err = os.Rename(tmp, path); err != nil { + return err + } + if d, derr := os.Open(dir); derr == nil { + d.Sync() // best effort: not every filesystem supports fsync on a directory + d.Close() + } + return nil +} diff --git a/internal/ssh/internal/atomicwrite/atomicwrite_test.go b/internal/ssh/internal/atomicwrite/atomicwrite_test.go new file mode 100644 index 0000000..b2c46d6 --- /dev/null +++ b/internal/ssh/internal/atomicwrite/atomicwrite_test.go @@ -0,0 +1,31 @@ +package atomicwrite + +import ( + "os" + "path/filepath" + "testing" +) + +func TestWriteFileReplacesAndCleansUp(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "f") + if err := os.WriteFile(p, []byte("old content"), 0o644); err != nil { + t.Fatal(err) + } + if err := WriteFile(p, []byte("new"), 0o600); err != nil { + t.Fatal(err) + } + b, err := os.ReadFile(p) + if err != nil || string(b) != "new" { + t.Fatalf("content = %q, %v", b, err) + } + if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o600 { + t.Errorf("mode = %v", fi.Mode().Perm()) + } + if ents, _ := os.ReadDir(dir); len(ents) != 1 { + t.Errorf("temp files left: %v", ents) + } + if err := WriteFile(filepath.Join(dir, "missing", "f"), nil, 0o600); err == nil { + t.Error("want error for missing directory") + } +} diff --git a/internal/ssh/sshconfig/flatten.go b/internal/ssh/sshconfig/flatten.go new file mode 100644 index 0000000..8ea3b20 --- /dev/null +++ b/internal/ssh/sshconfig/flatten.go @@ -0,0 +1,199 @@ +package sshconfig + +import ( + "fmt" + "os" + "path/filepath" + "sort" + "strings" +) + +// hashMark stands in for a literal '#' inside a value while the flattened +// config goes through kevinburke/ssh_config, whose lexer treats every '#' as +// the start of a comment. OpenSSH only starts a comment at a '#' that begins +// a word outside quotes (N-P1-5: "IdentityFile ~/.ssh/key#1"). +const hashMark = "" + +const maxIncludeDepth = 5 + +// flattener turns an ssh_config file and everything it Includes into a single +// text that kevinburke/ssh_config can parse without touching the disk: +// - comments are stripped with OpenSSH rules, literal '#' is escaped; +// - Include is inlined (relative to ~/.ssh), restoring the enclosing Host +// context after the included text, as OpenSSH does; +// - Host patterns are lowercased (OpenSSH matches host names +// case-insensitively; the alias is lowercased too before lookup); +// - "Match all" and "Match host a,b" become Host blocks; other Match +// criteria (user, exec, canonical, ...) become a block that never +// matches, instead of failing the whole file. +type flattener struct { + home string + b strings.Builder + explicit []string // non-wildcard Host names, in file order + seen map[string]bool + warnings []string +} + +func (f *flattener) warnf(format string, args ...any) { + f.warnings = append(f.warnings, fmt.Sprintf(format, args...)) +} + +func (f *flattener) file(path string, depth int) error { + data, err := os.ReadFile(path) + if err != nil { + return err + } + f.text(path, string(data), depth) + return nil +} + +func (f *flattener) text(path, data string, depth int) { + context := "" // current Host line written to the output, "" = implicit Host * + for n, raw := range strings.Split(data, "\n") { + line := strings.TrimSpace(stripComment(strings.TrimRight(raw, "\r"))) + if line == "" { + continue + } + kw, rest := splitKeyword(line) + switch strings.ToLower(kw) { + case "host": + pats := splitArgs(rest) + for i, p := range pats { + pats[i] = strings.ToLower(p) + if !strings.ContainsAny(p, "*?!") && !f.seen[pats[i]] { + f.seen[pats[i]] = true + f.explicit = append(f.explicit, p) + } + } + if len(pats) == 0 { + f.warnf("%s:%d: Host without patterns", path, n+1) + pats = []string{"!*"} + } + context = "Host " + strings.Join(pats, " ") + f.b.WriteString(context + "\n") + case "match": + context = f.match(path, n+1, rest) + f.b.WriteString(context + "\n") + case "include": + if depth >= maxIncludeDepth { + f.warnf("%s:%d: Include nested too deep, ignored", path, n+1) + continue + } + for _, pat := range splitArgs(rest) { + for _, m := range f.glob(pat) { + if err := f.file(m, depth+1); err != nil { + f.warnf("%s:%d: Include %s: %v", path, n+1, m, err) + } + } + } + // The included text may have opened its own Host blocks; the rest + // of this file continues in the block that contained the Include. + if context == "" { + f.b.WriteString("Host *\n") + } else { + f.b.WriteString(context + "\n") + } + default: + f.b.WriteString(kw + " " + strings.ReplaceAll(rest, "#", hashMark) + "\n") + } + } +} + +func (f *flattener) match(path string, line int, rest string) string { + fields := splitArgs(rest) + if len(fields) == 1 && strings.EqualFold(fields[0], "all") { + return "Host *" + } + if len(fields) == 2 && (strings.EqualFold(fields[0], "host") || strings.EqualFold(fields[0], "originalhost")) { + var pats []string + for _, p := range strings.Split(fields[1], ",") { + if p != "" { + pats = append(pats, strings.ToLower(p)) + } + } + if len(pats) > 0 { + return "Host " + strings.Join(pats, " ") + } + } + f.warnf("%s:%d: unsupported Match %q, block ignored", path, line, rest) + return "Host !*" +} + +func (f *flattener) glob(pat string) []string { + p := expandTilde(pat, f.home) + if !filepath.IsAbs(p) { + p = filepath.Join(f.home, ".ssh", p) + } + ms, err := filepath.Glob(p) + if err != nil { + f.warnf("Include %s: %v", pat, err) + return nil + } + sort.Strings(ms) + return ms +} + +// stripComment removes a trailing comment: a '#' that starts a word and is +// not inside double quotes (OpenSSH argv_split rules). +func stripComment(s string) string { + inQuote := false + for i := 0; i < len(s); i++ { + switch c := s[i]; { + case c == '"': + inQuote = !inQuote + case c == '#' && !inQuote && (i == 0 || s[i-1] == ' ' || s[i-1] == '\t'): + return s[:i] + } + } + return s +} + +// splitKeyword splits "Key value", "Key=value" and "Key = value". +func splitKeyword(line string) (kw, rest string) { + i := strings.IndexAny(line, " \t=") + if i < 0 { + return line, "" + } + kw, rest = line[:i], strings.TrimLeft(line[i:], " \t") + if strings.HasPrefix(rest, "=") { + rest = strings.TrimLeft(rest[1:], " \t") + } + return kw, rest +} + +// splitArgs splits on whitespace, honouring double quotes. +func splitArgs(s string) []string { + var out []string + var cur strings.Builder + inQuote, have := false, false + for _, r := range s { + switch { + case r == '"': + inQuote = !inQuote + have = true + case (r == ' ' || r == '\t') && !inQuote: + if have { + out = append(out, cur.String()) + cur.Reset() + have = false + } + default: + cur.WriteRune(r) + have = true + } + } + if have { + out = append(out, cur.String()) + } + return out +} + +func expandTilde(p, home string) string { + if p == "~" { + return home + } + if strings.HasPrefix(p, "~/") { + return filepath.Join(home, p[2:]) + } + return p +} diff --git a/internal/ssh/sshconfig/resolver.go b/internal/ssh/sshconfig/resolver.go new file mode 100644 index 0000000..593b563 --- /dev/null +++ b/internal/ssh/sshconfig/resolver.go @@ -0,0 +1,391 @@ +// Package sshconfig resolves host aliases into connection endpoints using +// ~/.ssh/config (parsed with github.com/kevinburke/ssh_config) and vcom's own +// encrypted host list (hosts.dat, see Store). +package sshconfig + +import ( + "errors" + "fmt" + "net" + "os" + "os/user" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + ssh_config "github.com/kevinburke/ssh_config" +) + +// DefaultPort is the SSH port used when none is configured. +const DefaultPort = 22 + +// Endpoint is everything needed to dial one host. +type Endpoint struct { + Alias string // as the user named the host + User string + Host string // HostName; the alias when the config has none (N-P1-5) + Port int + + IdentityFiles []string // absolute paths, in config order + IdentitiesOnly bool + + // ProxyJump hops, resolved through the same config. Dialing through them + // is stage 8; for now the field is informational. + ProxyJump []Endpoint + + ServerAliveInterval time.Duration + ServerAliveCountMax int + ConnectTimeout time.Duration + + // Password is set only for hosts added in vcom (hosts.dat). + Password string +} + +// port returns Port or DefaultPort. +func (e Endpoint) port() int { + if e.Port <= 0 { + return DefaultPort + } + return e.Port +} + +// Addr is "host:port" for dialing. +func (e Endpoint) Addr() string { + return net.JoinHostPort(e.Host, strconv.Itoa(e.port())) +} + +// Key is "user@host:port", the connection pool key. Aliases that resolve to +// the same user, host and port share a connection; different users never do +// (N-P2-3). +func (e Endpoint) Key() string { + return e.User + "@" + e.Addr() +} + +// Label is a short name for the UI: "user@alias". +func (e Endpoint) Label() string { + name := e.Alias + if name == "" { + name = e.Host + } + if e.User == "" { + return name + } + return e.User + "@" + name +} + +// Source tells where a host entry comes from. +type Source uint8 + +const ( + FromSSHConfig Source = iota // ~/.ssh/config + FromStore // hosts.dat (added in vcom) +) + +// HostEntry is one row of the host list. +type HostEntry struct { + Alias string + Source Source + User string + Host string + Port int +} + +// DisplayName is "alias (user@host[:port])". +func (h HostEntry) DisplayName() string { + addr := h.Host + if h.Port != 0 && h.Port != DefaultPort { + addr = net.JoinHostPort(h.Host, strconv.Itoa(h.Port)) + } + if h.User != "" { + addr = h.User + "@" + addr + } + return h.Alias + " (" + addr + ")" +} + +// Options configures a Resolver. +type Options struct { + // ConfigPath is the ssh config to read. "" means Home/.ssh/config; a + // missing file is not an error. + ConfigPath string + // Home is used for "~", relative Include and IdentityFile paths and the + // default config path. "" means os.UserHomeDir(). + Home string + // LocalUser is the default remote user. "" means the current user. + LocalUser string + // Store adds the hosts saved in vcom. May be nil. + Store *Store +} + +// Resolver answers host lookups. It is safe for concurrent use. +type Resolver struct { + opts Options + + mu sync.RWMutex + cfg *ssh_config.Config + explicit []string + warnings []string +} + +// NewResolver loads the ssh config. On a parse error the returned Resolver +// is still usable (it knows only the Store hosts) and the error is returned +// alongside it. +func NewResolver(o Options) (*Resolver, error) { + if o.Home == "" { + o.Home, _ = os.UserHomeDir() + } + if o.ConfigPath == "" && o.Home != "" { + o.ConfigPath = filepath.Join(o.Home, ".ssh", "config") + } + if o.LocalUser == "" { + o.LocalUser = currentUser() + } + r := &Resolver{opts: o} + return r, r.Reload() +} + +func currentUser() string { + if u, err := user.Current(); err == nil && u.Username != "" { + return u.Username + } + return os.Getenv("USER") +} + +// Reload re-reads the ssh config file. +func (r *Resolver) Reload() error { + f := &flattener{home: r.opts.Home, seen: map[string]bool{}} + var loadErr error + if r.opts.ConfigPath != "" { + if err := f.file(r.opts.ConfigPath, 0); err != nil && !errors.Is(err, os.ErrNotExist) { + loadErr = err + } + } + cfg, err := ssh_config.DecodeBytes([]byte(f.b.String())) + if err != nil { + cfg, _ = ssh_config.DecodeBytes(nil) + f.explicit = nil + loadErr = fmt.Errorf("parse %s: %w", r.opts.ConfigPath, err) + } + r.mu.Lock() + r.cfg, r.explicit, r.warnings = cfg, f.explicit, f.warnings + r.mu.Unlock() + return loadErr +} + +// Warnings lists non-fatal problems found by the last Reload (unsupported +// Match criteria, unreadable Include files). +func (r *Resolver) Warnings() []string { + r.mu.RLock() + defer r.mu.RUnlock() + return append([]string(nil), r.warnings...) +} + +// Hosts lists the explicit (non-pattern) Host names of the ssh config, then +// the Store hosts whose names are not in the config. +func (r *Resolver) Hosts() []HostEntry { + r.mu.RLock() + names := append([]string(nil), r.explicit...) + r.mu.RUnlock() + var out []HostEntry + seen := map[string]bool{} + for _, n := range names { + seen[strings.ToLower(n)] = true + ep, err := r.resolveConfig(n, 0) + if err != nil { + ep = Endpoint{Alias: n, Host: n} + } + out = append(out, HostEntry{Alias: n, Source: FromSSHConfig, User: ep.User, Host: ep.Host, Port: ep.Port}) + } + if r.opts.Store != nil { + for _, h := range r.opts.Store.Hosts() { + if seen[strings.ToLower(h.Name)] { + continue + } + seen[strings.ToLower(h.Name)] = true + ep := h.Endpoint(r.opts.LocalUser) + out = append(out, HostEntry{Alias: h.Name, Source: FromStore, User: ep.User, Host: ep.Host, Port: ep.Port}) + } + } + return out +} + +func (r *Resolver) isExplicit(alias string) bool { + r.mu.RLock() + defer r.mu.RUnlock() + for _, n := range r.explicit { + if strings.EqualFold(n, alias) { + return true + } + } + return false +} + +// Resolve turns an alias into an Endpoint. Hosts named explicitly in the ssh +// config win over Store hosts with the same name; anything else not in the +// Store is resolved through the config (wildcard blocks apply, HostName +// defaults to the alias). +func (r *Resolver) Resolve(alias string) (Endpoint, error) { + alias = strings.TrimSpace(alias) + if alias == "" { + return Endpoint{}, errors.New("sshconfig: empty host name") + } + if r.opts.Store != nil && !r.isExplicit(alias) { + if h, ok := r.opts.Store.Find(alias); ok { + return h.Endpoint(r.opts.LocalUser), nil + } + } + return r.resolveConfig(alias, 0) +} + +func (r *Resolver) get(alias, key string) string { + r.mu.RLock() + cfg := r.cfg + r.mu.RUnlock() + v, _ := cfg.Get(strings.ToLower(alias), key) + return strings.ReplaceAll(strings.TrimSpace(v), hashMark, "#") +} + +func (r *Resolver) getAll(alias, key string) []string { + r.mu.RLock() + cfg := r.cfg + r.mu.RUnlock() + vs, _ := cfg.GetAll(strings.ToLower(alias), key) + out := make([]string, 0, len(vs)) + for _, v := range vs { + out = append(out, strings.ReplaceAll(strings.TrimSpace(v), hashMark, "#")) + } + return out +} + +func (r *Resolver) resolveConfig(alias string, depth int) (Endpoint, error) { + ep := Endpoint{Alias: alias, Port: DefaultPort} + ep.User = r.get(alias, "User") + if ep.User == "" { + ep.User = r.opts.LocalUser + } + ep.Host = r.get(alias, "HostName") + if ep.Host == "" { + ep.Host = alias + } else { + ep.Host = r.expandTokens(ep.Host, alias, ep.User) + } + if p := r.get(alias, "Port"); p != "" { + n, err := strconv.Atoi(p) + if err != nil || n <= 0 || n > 65535 { + return Endpoint{}, fmt.Errorf("sshconfig: host %s: invalid Port %q", alias, p) + } + ep.Port = n + } + seen := map[string]bool{} + for _, id := range r.getAll(alias, "IdentityFile") { + if strings.EqualFold(id, "none") { + continue + } + p := r.expandPath(r.expandTokens(id, ep.Host, ep.User)) + if !seen[p] { + seen[p] = true + ep.IdentityFiles = append(ep.IdentityFiles, p) + } + } + ep.IdentitiesOnly = strings.EqualFold(r.get(alias, "IdentitiesOnly"), "yes") + if v := r.get(alias, "ServerAliveInterval"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + ep.ServerAliveInterval = time.Duration(n) * time.Second + } + } + if v := r.get(alias, "ServerAliveCountMax"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + ep.ServerAliveCountMax = n + } + } + if v := r.get(alias, "ConnectTimeout"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + ep.ConnectTimeout = time.Duration(n) * time.Second + } + } + if pj := r.get(alias, "ProxyJump"); pj != "" && !strings.EqualFold(pj, "none") { + if depth >= maxIncludeDepth { + return Endpoint{}, fmt.Errorf("sshconfig: host %s: ProxyJump chain too long", alias) + } + for _, hop := range strings.Split(pj, ",") { + h, err := r.parseHop(strings.TrimSpace(hop), depth+1) + if err != nil { + return Endpoint{}, fmt.Errorf("sshconfig: host %s: ProxyJump: %w", alias, err) + } + ep.ProxyJump = append(ep.ProxyJump, h) + } + } + return ep, nil +} + +// parseHop resolves one ProxyJump element "[user@]host[:port]". +func (r *Resolver) parseHop(hop string, depth int) (Endpoint, error) { + hop = strings.TrimPrefix(hop, "ssh://") + var u string + if i := strings.LastIndex(hop, "@"); i >= 0 { + u, hop = hop[:i], hop[i+1:] + } + host, port := hop, "" + if h, p, err := net.SplitHostPort(hop); err == nil { + host, port = h, p + } + if host == "" { + return Endpoint{}, errors.New("empty hop") + } + ep, err := r.resolveConfig(host, depth) + if err != nil { + return Endpoint{}, err + } + if u != "" { + ep.User = u + } + if port != "" { + n, err := strconv.Atoi(port) + if err != nil || n <= 0 || n > 65535 { + return Endpoint{}, fmt.Errorf("invalid port %q", port) + } + ep.Port = n + } + return ep, nil +} + +// expandTokens handles the ssh_config tokens that make sense here. +func (r *Resolver) expandTokens(s, host, remoteUser string) string { + if !strings.Contains(s, "%") { + return s + } + var b strings.Builder + for i := 0; i < len(s); i++ { + if s[i] != '%' || i+1 == len(s) { + b.WriteByte(s[i]) + continue + } + i++ + switch s[i] { + case '%': + b.WriteByte('%') + case 'h': + b.WriteString(host) + case 'd': + b.WriteString(r.opts.Home) + case 'u': + b.WriteString(r.opts.LocalUser) + case 'r': + b.WriteString(remoteUser) + default: + b.WriteByte('%') + b.WriteByte(s[i]) + } + } + return b.String() +} + +// expandPath expands "~" and makes relative paths relative to ~/.ssh. +func (r *Resolver) expandPath(p string) string { + p = expandTilde(p, r.opts.Home) + if !filepath.IsAbs(p) && r.opts.Home != "" { + p = filepath.Join(r.opts.Home, ".ssh", p) + } + return filepath.Clean(p) +} diff --git a/internal/ssh/sshconfig/resolver_test.go b/internal/ssh/sshconfig/resolver_test.go new file mode 100644 index 0000000..e08a91c --- /dev/null +++ b/internal/ssh/sshconfig/resolver_test.go @@ -0,0 +1,285 @@ +package sshconfig + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" +) + +// newTestResolver writes config text to home/.ssh/config and returns a +// Resolver over it. +func newTestResolver(t *testing.T, config string, store *Store) (*Resolver, string) { + t.Helper() + home := t.TempDir() + writeFile(t, filepath.Join(home, ".ssh", "config"), config) + r, err := NewResolver(Options{Home: home, LocalUser: "local", Store: store}) + if err != nil { + t.Fatalf("NewResolver: %v", err) + } + return r, home +} + +func writeFile(t *testing.T, p, s string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(s), 0o600); err != nil { + t.Fatal(err) + } +} + +func mustResolve(t *testing.T, r *Resolver, alias string) Endpoint { + t.Helper() + ep, err := r.Resolve(alias) + if err != nil { + t.Fatalf("Resolve(%q): %v", alias, err) + } + return ep +} + +// Ported from the testbed (B10): a Host without HostName dialed ":22", +// i.e. localhost; "HostName=10.0.0.1" was not parsed at all (N-P1-5). +func TestConfigNoHostName(t *testing.T) { + r, _ := newTestResolver(t, "Host myserver.example.com\n User bob\nHost alias\n HostName=10.0.0.1\n", nil) + ep := mustResolve(t, r, "myserver.example.com") + if ep.Host != "myserver.example.com" || ep.User != "bob" || ep.Port != 22 { + t.Errorf("no HostName: got %+v", ep) + } + if got := ep.Addr(); got != "myserver.example.com:22" { + t.Errorf("Addr = %q", got) + } + ep = mustResolve(t, r, "alias") + if ep.Host != "10.0.0.1" { + t.Errorf("HostName=10.0.0.1: got Host %q", ep.Host) + } + if ep.User != "local" { + t.Errorf("default user: got %q", ep.User) + } + for _, h := range r.Hosts() { + if h.Host == "" { + t.Errorf("host %q has empty Host", h.Alias) + } + } +} + +func TestConfigEqualsAndSpaces(t *testing.T) { + r, _ := newTestResolver(t, "Host a\n HostName = 10.0.0.2\n Port=2222\n User\tcarol\n", nil) + ep := mustResolve(t, r, "a") + if ep.Host != "10.0.0.2" || ep.Port != 2222 || ep.User != "carol" { + t.Errorf("got %+v", ep) + } +} + +func TestConfigHostStarDefaults(t *testing.T) { + cfg := `Host special + User alice + IdentityFile ~/.ssh/id_special + +Host * + User defuser + IdentityFile ~/.ssh/id_star + ServerAliveInterval 7 + ServerAliveCountMax 4 + ConnectTimeout 3 +` + r, home := newTestResolver(t, cfg, nil) + ep := mustResolve(t, r, "plain.example.com") + if ep.User != "defuser" { + t.Errorf("Host * User not applied: %q", ep.User) + } + if want := []string{filepath.Join(home, ".ssh", "id_star")}; !reflect.DeepEqual(ep.IdentityFiles, want) { + t.Errorf("IdentityFiles = %v, want %v", ep.IdentityFiles, want) + } + if ep.ServerAliveInterval != 7*time.Second || ep.ServerAliveCountMax != 4 || ep.ConnectTimeout != 3*time.Second { + t.Errorf("alive/timeout: %+v", ep) + } + ep = mustResolve(t, r, "special") + if ep.User != "alice" { + t.Errorf("first match must win: User %q", ep.User) + } + want := []string{filepath.Join(home, ".ssh", "id_special"), filepath.Join(home, ".ssh", "id_star")} + if !reflect.DeepEqual(ep.IdentityFiles, want) { + t.Errorf("IdentityFiles = %v, want %v", ep.IdentityFiles, want) + } + hosts := r.Hosts() + if len(hosts) != 1 || hosts[0].Alias != "special" { + t.Errorf("Hosts() must list only explicit hosts: %+v", hosts) + } +} + +func TestConfigMultipleIdentityFiles(t *testing.T) { + r, home := newTestResolver(t, "Host m\n IdentityFile ~/.ssh/one\n IdentityFile two\n IdentityFile /abs/three\n IdentityFile ~/.ssh/one\n IdentitiesOnly yes\n", nil) + ep := mustResolve(t, r, "m") + want := []string{filepath.Join(home, ".ssh", "one"), filepath.Join(home, ".ssh", "two"), "/abs/three"} + if !reflect.DeepEqual(ep.IdentityFiles, want) { + t.Errorf("IdentityFiles = %v, want %v", ep.IdentityFiles, want) + } + if !ep.IdentitiesOnly { + t.Error("IdentitiesOnly not parsed") + } +} + +func TestConfigQuotes(t *testing.T) { + r, home := newTestResolver(t, "Host q\n IdentityFile \"~/.ssh/my key\"\n HostName \"q.example.com\"\n", nil) + ep := mustResolve(t, r, "q") + if want := filepath.Join(home, ".ssh", "my key"); len(ep.IdentityFiles) != 1 || ep.IdentityFiles[0] != want { + t.Errorf("IdentityFiles = %v, want [%s]", ep.IdentityFiles, want) + } + if ep.Host != "q.example.com" { + t.Errorf("Host = %q", ep.Host) + } +} + +func TestConfigHashInValue(t *testing.T) { + cfg := "# leading comment\nHost h # trailing comment on Host\n IdentityFile ~/.ssh/key#1 # real comment\n User \"u#2\"\n" + r, home := newTestResolver(t, cfg, nil) + ep := mustResolve(t, r, "h") + if want := filepath.Join(home, ".ssh", "key#1"); len(ep.IdentityFiles) != 1 || ep.IdentityFiles[0] != want { + t.Errorf("IdentityFiles = %v, want [%s]", ep.IdentityFiles, want) + } + if ep.User != "u#2" { + t.Errorf("User = %q, want u#2", ep.User) + } +} + +func TestConfigInclude(t *testing.T) { + home := t.TempDir() + writeFile(t, filepath.Join(home, ".ssh", "conf.d", "10-work"), "Host work\n HostName work.example.com\n User worker\n") + writeFile(t, filepath.Join(home, ".ssh", "conf.d", "20-misc"), "Host misc\n Port 2200\n") + abs := filepath.Join(home, "elsewhere.conf") + writeFile(t, abs, "Host abs\n HostName 192.168.1.1\n") + cfg := "Include conf.d/*\nHost outer\n Include " + abs + "\n User outeruser\nHost *\n User fallback\n" + writeFile(t, filepath.Join(home, ".ssh", "config"), cfg) + r, err := NewResolver(Options{Home: home, LocalUser: "local"}) + if err != nil { + t.Fatal(err) + } + if ep := mustResolve(t, r, "work"); ep.Host != "work.example.com" || ep.User != "worker" { + t.Errorf("work: %+v", ep) + } + if ep := mustResolve(t, r, "misc"); ep.Port != 2200 || ep.User != "fallback" { + t.Errorf("misc: %+v", ep) + } + if ep := mustResolve(t, r, "abs"); ep.Host != "192.168.1.1" { + t.Errorf("abs: %+v", ep) + } + // Lines after an Include stay in the block that contained it. + if ep := mustResolve(t, r, "outer"); ep.User != "outeruser" { + t.Errorf("outer: User %q, want outeruser", ep.User) + } + var names []string + for _, h := range r.Hosts() { + names = append(names, h.Alias) + } + if want := []string{"work", "misc", "outer", "abs"}; !reflect.DeepEqual(names, want) { + t.Errorf("Hosts = %v, want %v", names, want) + } +} + +func TestConfigUnsupportedMatchIgnored(t *testing.T) { + cfg := "Match user root\n User ignored\nMatch host *.corp,10.*\n User corp\nHost x\n HostName x.example.com\n" + r, _ := newTestResolver(t, cfg, nil) + if ep := mustResolve(t, r, "x"); ep.User != "local" { + t.Errorf("unsupported Match applied: %+v", ep) + } + if ep := mustResolve(t, r, "a.corp"); ep.User != "corp" { + t.Errorf("Match host not applied: %+v", ep) + } + if len(r.Warnings()) != 1 { + t.Errorf("warnings = %v", r.Warnings()) + } +} + +func TestConfigCaseInsensitiveHost(t *testing.T) { + r, _ := newTestResolver(t, "Host MyBox\n HostName 10.1.1.1\n", nil) + if ep := mustResolve(t, r, "mybox"); ep.Host != "10.1.1.1" { + t.Errorf("got %+v", ep) + } + if ep := mustResolve(t, r, "MYBOX"); ep.Host != "10.1.1.1" || ep.Alias != "MYBOX" { + t.Errorf("got %+v", ep) + } +} + +func TestConfigInvalidPort(t *testing.T) { + r, _ := newTestResolver(t, "Host p\n Port abc\n", nil) + if _, err := r.Resolve("p"); err == nil { + t.Fatal("want error for invalid port") + } +} + +func TestConfigProxyJump(t *testing.T) { + r, _ := newTestResolver(t, "Host target\n ProxyJump admin@bastion:2022,hop2\nHost bastion\n HostName b.example.com\n", nil) + ep := mustResolve(t, r, "target") + if len(ep.ProxyJump) != 2 { + t.Fatalf("ProxyJump = %+v", ep.ProxyJump) + } + if h := ep.ProxyJump[0]; h.Host != "b.example.com" || h.User != "admin" || h.Port != 2022 { + t.Errorf("hop 1: %+v", h) + } + if h := ep.ProxyJump[1]; h.Host != "hop2" || h.Port != 22 { + t.Errorf("hop 2: %+v", h) + } +} + +func TestConfigMissingFile(t *testing.T) { + r, err := NewResolver(Options{Home: t.TempDir(), LocalUser: "me"}) + if err != nil { + t.Fatalf("missing config must not be an error: %v", err) + } + ep := mustResolve(t, r, "anything") + if ep.Host != "anything" || ep.User != "me" || ep.Port != 22 { + t.Errorf("got %+v", ep) + } +} + +// N-P2-3: SameAs ignored User, so two users on one host shared a client. +func TestEndpointKeyIncludesUser(t *testing.T) { + r, _ := newTestResolver(t, "Host a1\n HostName srv\n User alice\nHost a2\n HostName srv\n User alice\nHost b\n HostName srv\n User bob\n", nil) + a1, a2, b := mustResolve(t, r, "a1"), mustResolve(t, r, "a2"), mustResolve(t, r, "b") + if a1.Key() != a2.Key() { + t.Errorf("same user@host:port must share a key: %q vs %q", a1.Key(), a2.Key()) + } + if a1.Key() == b.Key() { + t.Errorf("different users must not share a key: %q", a1.Key()) + } + if !strings.HasPrefix(a1.Key(), "alice@") || a1.Key() != "alice@srv:22" { + t.Errorf("Key = %q", a1.Key()) + } + v6 := Endpoint{User: "u", Host: "::1", Port: 2222} + if v6.Key() != "u@[::1]:2222" { + t.Errorf("IPv6 key = %q", v6.Key()) + } +} + +func TestResolverStoreHosts(t *testing.T) { + st, err := OpenStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + if err := st.Put(StoredHost{Name: "mine", HostName: "10.9.9.9", Port: 2022, User: "me", Password: "secret"}); err != nil { + t.Fatal(err) + } + if err := st.Put(StoredHost{Name: "dup", HostName: "store.example.com"}); err != nil { + t.Fatal(err) + } + r, _ := newTestResolver(t, "Host dup\n HostName config.example.com\n", st) + ep := mustResolve(t, r, "mine") + if ep.Host != "10.9.9.9" || ep.Port != 2022 || ep.User != "me" || ep.Password != "secret" { + t.Errorf("store host: %+v", ep) + } + if ep := mustResolve(t, r, "dup"); ep.Host != "config.example.com" { + t.Errorf("ssh config must win over the store: %+v", ep) + } + hosts := r.Hosts() + if len(hosts) != 2 || hosts[0].Alias != "dup" || hosts[0].Source != FromSSHConfig || + hosts[1].Alias != "mine" || hosts[1].Source != FromStore { + t.Errorf("Hosts = %+v", hosts) + } + if got := hosts[1].DisplayName(); got != "mine (me@10.9.9.9:2022)" { + t.Errorf("DisplayName = %q", got) + } +} diff --git a/internal/ssh/sshconfig/store.go b/internal/ssh/sshconfig/store.go new file mode 100644 index 0000000..3869fcb --- /dev/null +++ b/internal/ssh/sshconfig/store.go @@ -0,0 +1,317 @@ +package sshconfig + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + + "vcom/internal/ssh/internal/atomicwrite" +) + +// File names inside the Store directory (compatible with vcom <= 0.2.x). +const ( + HostsFile = "hosts.dat" + KeyFile = ".hosts-key" +) + +// ErrHostNotFound is returned by Store.Remove for an unknown name. +var ErrHostNotFound = errors.New("sshconfig: host not found") + +// StoredHost is a host added in vcom. +type StoredHost struct { + Name string + HostName string + Port int // 0 = default + User string + Password string // plaintext in memory, encrypted on disk + IdentityFile string +} + +// Endpoint converts a stored host to an Endpoint; localUser is the default +// user. +func (h StoredHost) Endpoint(localUser string) Endpoint { + ep := Endpoint{ + Alias: h.Name, + User: h.User, + Host: h.HostName, + Port: h.Port, + Password: h.Password, + } + if ep.Host == "" { + ep.Host = h.Name + } + if ep.Port <= 0 { + ep.Port = DefaultPort + } + if ep.User == "" { + ep.User = localUser + } + if h.IdentityFile != "" { + ep.IdentityFiles = []string{h.IdentityFile} + } + return ep +} + +// Store is vcom's own host list: hosts.dat, AES-256-GCM encrypted with the +// key in .hosts-key (both in the vcom config directory). Every save is +// atomic. It is safe for concurrent use. +type Store struct { + path string + key []byte + + mu sync.Mutex + hosts []StoredHost +} + +// OpenStore loads dir/hosts.dat, creating the encryption key if there is +// none yet. A missing hosts.dat means an empty list. +func OpenStore(dir string) (*Store, error) { + if dir == "" { + return nil, errors.New("sshconfig: empty store directory") + } + key, err := loadOrCreateKey(filepath.Join(dir, KeyFile)) + if err != nil { + return nil, fmt.Errorf("sshconfig: hosts key: %w", err) + } + s := &Store{path: filepath.Join(dir, HostsFile), key: key} + if err := s.load(); err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + return s, nil +} + +func loadOrCreateKey(path string) ([]byte, error) { + data, err := os.ReadFile(path) + if err == nil { + key, derr := base64.StdEncoding.DecodeString(strings.TrimSpace(string(data))) + if derr == nil && len(key) == 32 { + return key, nil + } + // A damaged key must not be silently replaced: hosts.dat would become + // undecryptable for good. + return nil, fmt.Errorf("%s: invalid key", path) + } + if !errors.Is(err, os.ErrNotExist) { + return nil, err + } + key := make([]byte, 32) + if _, err := rand.Read(key); err != nil { + return nil, err + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return nil, err + } + if err := atomicwrite.WriteFile(path, []byte(base64.StdEncoding.EncodeToString(key)), 0o600); err != nil { + return nil, err + } + return key, nil +} + +// On-disk format (unchanged from vcom 0.2.x). +type storedHosts struct { + Hosts []storedHost `json:"hosts"` +} + +type storedHost struct { + Name string `json:"name"` + HostName string `json:"hostname"` + Port string `json:"port,omitempty"` + User string `json:"user,omitempty"` + Password string `json:"password,omitempty"` // encrypted + IdentityFile string `json:"identity_file,omitempty"` +} + +func (s *Store) load() error { + data, err := os.ReadFile(s.path) + if err != nil { + return err + } + plain, err := decrypt(data, s.key) + if err != nil { + return fmt.Errorf("sshconfig: decrypt %s: %w", s.path, err) + } + var st storedHosts + if err := json.Unmarshal(plain, &st); err != nil { + return fmt.Errorf("sshconfig: parse %s: %w", s.path, err) + } + hosts := make([]StoredHost, 0, len(st.Hosts)) + for _, h := range st.Hosts { + pw := decryptPassword(h.Password, s.key) + port, _ := strconv.Atoi(h.Port) + hosts = append(hosts, StoredHost{ + Name: h.Name, HostName: h.HostName, Port: port, User: h.User, + Password: pw, IdentityFile: h.IdentityFile, + }) + } + s.mu.Lock() + s.hosts = hosts + s.mu.Unlock() + return nil +} + +// save writes hosts.dat; the caller holds s.mu. +func (s *Store) save() error { + st := storedHosts{Hosts: make([]storedHost, 0, len(s.hosts))} + for _, h := range s.hosts { + pw := "" + if h.Password != "" { + enc, err := encrypt([]byte(h.Password), s.key) + if err != nil { + return err + } + pw = base64.StdEncoding.EncodeToString(enc) + } + port := "" + if h.Port > 0 { + port = strconv.Itoa(h.Port) + } + st.Hosts = append(st.Hosts, storedHost{ + Name: h.Name, HostName: h.HostName, Port: port, User: h.User, + Password: pw, IdentityFile: h.IdentityFile, + }) + } + data, err := json.Marshal(st) + if err != nil { + return err + } + enc, err := encrypt(data, s.key) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(s.path), 0o700); err != nil { + return err + } + return atomicwrite.WriteFile(s.path, enc, 0o600) +} + +// Hosts returns a copy of the stored hosts. +func (s *Store) Hosts() []StoredHost { + s.mu.Lock() + defer s.mu.Unlock() + return append([]StoredHost(nil), s.hosts...) +} + +// Find looks a host up by name (case-insensitive). +func (s *Store) Find(name string) (StoredHost, bool) { + s.mu.Lock() + defer s.mu.Unlock() + for _, h := range s.hosts { + if strings.EqualFold(h.Name, name) { + return h, true + } + } + return StoredHost{}, false +} + +// Put adds h, replacing a host with the same name, and saves. On a save +// error the in-memory list is left unchanged. +func (s *Store) Put(h StoredHost) error { + if strings.TrimSpace(h.Name) == "" { + return errors.New("sshconfig: host name is required") + } + s.mu.Lock() + defer s.mu.Unlock() + old := s.hosts + next := make([]StoredHost, 0, len(old)+1) + replaced := false + for _, x := range old { + if strings.EqualFold(x.Name, h.Name) { + next = append(next, h) + replaced = true + } else { + next = append(next, x) + } + } + if !replaced { + next = append(next, h) + } + s.hosts = next + if err := s.save(); err != nil { + s.hosts = old + return err + } + return nil +} + +// Remove deletes a host by name and saves. +func (s *Store) Remove(name string) error { + s.mu.Lock() + defer s.mu.Unlock() + old := s.hosts + next := make([]StoredHost, 0, len(old)) + for _, x := range old { + if !strings.EqualFold(x.Name, name) { + next = append(next, x) + } + } + if len(next) == len(old) { + return fmt.Errorf("%w: %s", ErrHostNotFound, name) + } + s.hosts = next + if err := s.save(); err != nil { + s.hosts = old + return err + } + return nil +} + +// decryptPassword reads the password field. vcom <= 0.2.x stored the raw +// ciphertext as a JSON string, which json.Marshal mangles (invalid UTF-8 +// becomes U+FFFD), so such passwords usually cannot be recovered; the field +// is now base64. Both forms are tried; failure yields "". +func decryptPassword(field string, key []byte) string { + if field == "" { + return "" + } + if raw, err := base64.StdEncoding.DecodeString(field); err == nil { + if p, err := decrypt(raw, key); err == nil { + return string(p) + } + } + if p, err := decrypt([]byte(field), key); err == nil { + return string(p) + } + return "" +} + +func encrypt(plaintext, key []byte) ([]byte, error) { + gcm, err := newGCM(key) + if err != nil { + return nil, err + } + nonce := make([]byte, gcm.NonceSize()) + if _, err := io.ReadFull(rand.Reader, nonce); err != nil { + return nil, err + } + return gcm.Seal(nonce, nonce, plaintext, nil), nil +} + +func decrypt(ciphertext, key []byte) ([]byte, error) { + gcm, err := newGCM(key) + if err != nil { + return nil, err + } + n := gcm.NonceSize() + if len(ciphertext) < n { + return nil, errors.New("ciphertext too short") + } + return gcm.Open(nil, ciphertext[:n], ciphertext[n:], nil) +} + +func newGCM(key []byte) (cipher.AEAD, error) { + block, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + return cipher.NewGCM(block) +} diff --git a/internal/ssh/sshconfig/store_test.go b/internal/ssh/sshconfig/store_test.go new file mode 100644 index 0000000..e0fbe8f --- /dev/null +++ b/internal/ssh/sshconfig/store_test.go @@ -0,0 +1,102 @@ +package sshconfig + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "testing" +) + +func TestStoreRoundTrip(t *testing.T) { + dir := filepath.Join(t.TempDir(), "vcom") + st, err := OpenStore(dir) + if err != nil { + t.Fatal(err) + } + h := StoredHost{Name: "box", HostName: "10.0.0.5", Port: 2200, User: "root", Password: "hunter2", IdentityFile: "/k"} + if err := st.Put(h); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(filepath.Join(dir, HostsFile)) + if err != nil { + t.Fatal(err) + } + if bytes.Contains(raw, []byte("hunter2")) || bytes.Contains(raw, []byte("10.0.0.5")) { + t.Fatal("hosts.dat must be encrypted") + } + for _, name := range []string{HostsFile, KeyFile} { + fi, err := os.Stat(filepath.Join(dir, name)) + if err != nil { + t.Fatal(err) + } + if fi.Mode().Perm() != 0o600 { + t.Errorf("%s mode = %v", name, fi.Mode().Perm()) + } + } + + st2, err := OpenStore(dir) + if err != nil { + t.Fatal(err) + } + got, ok := st2.Find("BOX") + if !ok || got != h { + t.Fatalf("reloaded = %+v (ok=%v), want %+v", got, ok, h) + } + + h.Password = "changed" + if err := st2.Put(h); err != nil { + t.Fatal(err) + } + if hs := st2.Hosts(); len(hs) != 1 || hs[0].Password != "changed" { + t.Errorf("Put must replace by name: %+v", hs) + } + if err := st2.Remove("box"); err != nil { + t.Fatal(err) + } + if err := st2.Remove("box"); !errors.Is(err, ErrHostNotFound) { + t.Errorf("Remove unknown: %v", err) + } + ents, _ := os.ReadDir(dir) + for _, e := range ents { + if e.Name() != HostsFile && e.Name() != KeyFile { + t.Errorf("leftover file %s (atomic write must clean up)", e.Name()) + } + } +} + +func TestStoreDamagedKeyNotReplaced(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, KeyFile), "not base64 !!") + if _, err := OpenStore(dir); err == nil { + t.Fatal("damaged key must be an error") + } + b, _ := os.ReadFile(filepath.Join(dir, KeyFile)) + if string(b) != "not base64 !!" { + t.Fatal("damaged key was overwritten") + } +} + +func TestStoreSaveFailureKeepsState(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root ignores directory permissions") + } + dir := t.TempDir() + st, err := OpenStore(dir) + if err != nil { + t.Fatal(err) + } + if err := st.Put(StoredHost{Name: "a"}); err != nil { + t.Fatal(err) + } + if err := os.Chmod(dir, 0o500); err != nil { + t.Fatal(err) + } + defer os.Chmod(dir, 0o700) + if err := st.Put(StoredHost{Name: "b"}); err == nil { + t.Fatal("Put into read-only dir must fail") + } + if hs := st.Hosts(); len(hs) != 1 || hs[0].Name != "a" { + t.Errorf("failed save changed state: %+v", hs) + } +} diff --git a/plans/rework/04-dev-log-B.md b/plans/rework/04-dev-log-B.md new file mode 100644 index 0000000..c3b8ed0 --- /dev/null +++ b/plans/rework/04-dev-log-B.md @@ -0,0 +1,31 @@ +# 04-B. Журнал разработчика B (сеть, `internal/ssh`): отклонения от плана + +Отдельный файл, чтобы не конфликтовать с `04-dev-log.md` при мерже. Ветка разработки — worktree от +`rework/stabilize`. + +## 2B.1 `ssh/sshconfig` + +- **Атомарная запись.** `internal/atomicfile` (2C.1) ещё нет, поэтому временно `internal/ssh/internal/atomicwrite` + (temp + fsync + rename + fsync каталога). Используется в `Store` и для known_hosts (2B.2). TODO: заменить на + `atomicfile.WriteFile` после мержа 2C.1 и удалить пакет. +- **kevinburke/ssh_config используется не напрямую по файлу.** Библиотека (v1.6.0) сама: (а) считает началом + комментария любой `#`, даже внутри значения и кавычек (`IdentityFile ~/.ssh/key#1` ломается — ровно N-P1-5); + (б) разрешает `Include` от `os/user.Current().HomeDir`, игнорируя `HOME` (ломает изоляцию тестов и sudo); + (в) падает на всём файле при `Match user/exec/canonical/...`; (г) сравнивает Host с учётом регистра. + Поэтому `flatten.go` склеивает конфиг и все `Include` в один текст: комментарии снимаются по правилам OpenSSH + (`#` в начале слова вне кавычек), оставшиеся `#` экранируются символом U+E000 и возвращаются после `Get`; + `Include` инлайнится (относительно `~/.ssh` из `Options.Home`, глубина ≤ 5), после вставки восстанавливается + объемлющий `Host`-контекст; `Match all` и `Match host a,b` → `Host`, остальные `Match` → блок, который + никогда не совпадает (+ `Warnings()`); шаблоны Host и alias приводятся к нижнему регистру. Библиотеке остаются + разбор строк, кавычки, `key=value` и сопоставление шаблонов (first match wins). +- **`NewResolver(Options)`** вместо `Resolver{}`: `Options{ConfigPath, Home, LocalUser, Store}` — чтобы `paths` + (2C) мог передать home вызвавшего пользователя под sudo, а тесты — временный каталог. Ошибка разбора не + фатальна: возвращается вместе с рабочим Resolver (знает только хосты из Store). +- **Store API:** `OpenStore(dir)`, `Hosts/Find/Put/Remove`; `Put` заменяет хост с тем же именем (раньше + `AddHost` дублировал). Формат hosts.dat совместим, **кроме поля password**: старый код писал сырой шифротекст + как JSON-строку, `json.Marshal` портил невалидный UTF-8 (→ U+FFFD), и сохранённые пароли после перезапуска + молча не расшифровывались. Теперь поле — base64 шифротекста; при чтении пробуются оба варианта. Повреждённый + `.hosts-key` больше не перезаписывается молча новым ключом (это делало hosts.dat нечитаемым навсегда) — ошибка. +- `Endpoint` дополнен `Addr()` и `Label()`; `ProxyJump` разбирается (`[user@]host[:port]`, хопы разрешаются через + тот же конфиг), но подключение через хопы — этап 8. `IdentityFile none` пропускается; токены `%h %d %u %r %%` + раскрываются в `HostName`/`IdentityFile`. diff --git a/vendor/github.com/kevinburke/ssh_config/.gitignore b/vendor/github.com/kevinburke/ssh_config/.gitignore new file mode 100644 index 0000000..46620af --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/.gitignore @@ -0,0 +1 @@ +/coverage.out diff --git a/vendor/github.com/kevinburke/ssh_config/.mailmap b/vendor/github.com/kevinburke/ssh_config/.mailmap new file mode 100644 index 0000000..253406b --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/.mailmap @@ -0,0 +1 @@ +Kevin Burke Kevin Burke diff --git a/vendor/github.com/kevinburke/ssh_config/AUTHORS.txt b/vendor/github.com/kevinburke/ssh_config/AUTHORS.txt new file mode 100644 index 0000000..7510398 --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/AUTHORS.txt @@ -0,0 +1,13 @@ +Carlos A Becker +Claude Opus 4.6 +Dustin Spicuzza +Eugene Terentev +Kevin Burke +Mark Nevill +Neil Williams +Scott Lessans +Sergey Lukjanov +Simon Josefsson +Wayne Ashley Berry +santosh653 <70637961+santosh653@users.noreply.github.com> +sio2boss diff --git a/vendor/github.com/kevinburke/ssh_config/CHANGELOG.md b/vendor/github.com/kevinburke/ssh_config/CHANGELOG.md new file mode 100644 index 0000000..8670983 --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/CHANGELOG.md @@ -0,0 +1,65 @@ +# Changes + +## Version 1.6 (released February 16, 2026) + +- Support `~` as the user's home directory in `Include` directives, matching +the behavior described in ssh_config(5). Thanks to Neil Williams for the report +(#31). + +- Strip surrounding double quotes from parsed values. OpenSSH allows values +like `IdentityFile "/path/to/file"`, but Get/GetAll previously returned the +quotes as literal characters. Quotes are now stripped from the returned value +while preserving the original text for faithful roundtripping via String() and +MarshalText(). Thanks to Furkan Türkal for the report (#61). + +- Default to a space before `#` in end-of-line comments. When a Host or KV is +created programmatically with an EOLComment, the output previously had no space +before the `#` (e.g. `Host foo#comment`). A single space is now inserted by +default. Thanks to Yonghui Cheng for the report (#50). + +## Version 1.5 (released February 14, 2026) + +- Implement Match support. Most of the Match spec is implemented, including +`Match host`, `Match originalhost`, `Match user`, `Match localuser`, and `Match +all`. `Match exec` is not yet implemented. + +- Add SECURITY.md + +- Add Dependabot configuration + +## Version 1.4 (released August 19, 2025) + +- Remove .gitattributes file (which was used to test different line endings, and +caused issues in some build environments). Store tests/dos-lines as CRLF in git +directly instead. + +## Version 1.3 (released February 20, 2025) + +- Add go.mod file (although this project has no dependencies). + +- config: add UserSettings.ConfigFinder + +- Various updates to CI and build environment + +## Version 1.2 (released March 31, 2022) + +- config: add DecodeBytes to directly read a byte array. + +- Strip trailing whitespace from Host declarations and key/value pairs. +Previously, if a Host declaration or a value had trailing whitespace, that +whitespace would have been included as part of the value. This led to unexpected +consequences. For example: + +``` +Host example # A comment + HostName example.com # Another comment +``` + +Prior to version 1.2, the value for Host would have been "example " and the +value for HostName would have been "example.com ". Both of these are +unintuitive. + +Instead, we strip the trailing whitespace in the configuration, which leads to +more intuitive behavior. + +- Add fuzz tests. diff --git a/vendor/github.com/kevinburke/ssh_config/LICENSE b/vendor/github.com/kevinburke/ssh_config/LICENSE new file mode 100644 index 0000000..b9a770a --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/LICENSE @@ -0,0 +1,49 @@ +Copyright (c) 2017 Kevin Burke. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +=================== + +The lexer and parser borrow heavily from github.com/pelletier/go-toml. The +license for that project is copied below. + +The MIT License (MIT) + +Copyright (c) 2013 - 2017 Thomas Pelletier, Eric Anderton + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/kevinburke/ssh_config/Makefile b/vendor/github.com/kevinburke/ssh_config/Makefile new file mode 100644 index 0000000..aa946eb --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/Makefile @@ -0,0 +1,34 @@ +BUMP_VERSION := $(GOPATH)/bin/bump_version +WRITE_MAILMAP := $(GOPATH)/bin/write_mailmap + +lint: + go vet ./... + go run honnef.co/go/tools/cmd/staticcheck@latest ./... + go run github.com/kevinburke/differ@latest gofmt -s -w . + +test: + @# the timeout helps guard against infinite recursion + go test -timeout=250ms ./... + +race-test: + go test -timeout=500ms -race ./... + +coverage: + go test -trimpath -timeout=250ms -coverprofile=coverage.out -covermode=atomic ./... + go tool cover -func=coverage.out + +$(BUMP_VERSION): + go get -u github.com/kevinburke/bump_version + +$(WRITE_MAILMAP): + go get -u github.com/kevinburke/write_mailmap + +release: test | $(BUMP_VERSION) + $(BUMP_VERSION) --tag-prefix=v minor config.go + +force: ; + +AUTHORS.txt: force | $(WRITE_MAILMAP) + $(WRITE_MAILMAP) > AUTHORS.txt + +authors: AUTHORS.txt diff --git a/vendor/github.com/kevinburke/ssh_config/README.md b/vendor/github.com/kevinburke/ssh_config/README.md new file mode 100644 index 0000000..705605e --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/README.md @@ -0,0 +1,92 @@ +# ssh_config + +This is a Go parser for `ssh_config` files. Importantly, this parser attempts +to preserve comments in a given file, so you can manipulate a `ssh_config` file +from a program, if your heart desires. + +It's designed to be used with the excellent +[x/crypto/ssh](https://golang.org/x/crypto/ssh) package, which handles SSH +negotiation but isn't very easy to configure. + +The `ssh_config` `Get()` and `GetStrict()` functions will attempt to read values +from `$HOME/.ssh/config` and fall back to `/etc/ssh/ssh_config`. The first +argument is the host name to match on, and the second argument is the key you +want to retrieve. + +```go +port := ssh_config.Get("myhost", "Port") +``` + +Certain directives can occur multiple times for a host (such as `IdentityFile`), +so you should use the `GetAll` or `GetAllStrict` directive to retrieve those +instead. + +```go +files := ssh_config.GetAll("myhost", "IdentityFile") +``` + +You can also load a config file and read values from it. + +```go +var config = ` +Host *.test + Compression yes +` + +cfg, err := ssh_config.Decode(strings.NewReader(config)) +fmt.Println(cfg.Get("example.test", "Port")) +``` + +Some SSH arguments have default values - for example, the default value for +`KeyboardAuthentication` is `"yes"`. If you call Get(), and no value for the +given Host/keyword pair exists in the config, we'll return a default for the +keyword if one exists. + +### Manipulating SSH config files + +Here's how you can manipulate an SSH config file, and then write it back to +disk. + +```go +f, _ := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "config")) +cfg, _ := ssh_config.Decode(f) +for _, host := range cfg.Hosts { + fmt.Println("patterns:", host.Patterns) + for _, node := range host.Nodes { + // Manipulate the nodes as you see fit, or use a type switch to + // distinguish between Empty, KV, and Include nodes. + fmt.Println(node.String()) + } +} + +// Print the config to stdout: +fmt.Println(cfg.String()) +``` + +## Spec compliance + +Wherever possible we try to implement the specification as documented in +the `ssh_config` manpage. Unimplemented features should be present in the +[issues][issues] list. + +Notably, the `Match` directive is currently unsupported. + +[issues]: https://github.com/kevinburke/ssh_config/issues + +## Errata + +This is the second [comment-preserving configuration parser][blog] I've written, after +[an /etc/hosts parser][hostsfile]. Eventually, I will write one for every Linux +file format. + +[blog]: https://kev.inburke.com/kevin/more-comment-preserving-configuration-parsers/ +[hostsfile]: https://github.com/kevinburke/hostsfile + +## Sponsorships + +Thank you very much to Tailscale and Indeed for sponsoring development of this +library. [Sponsors][sponsors] will get their names featured in the README. + +You can also reach out about a consulting engagement: https://burke.services + +[sponsors]: https://github.com/sponsors/kevinburke diff --git a/vendor/github.com/kevinburke/ssh_config/SECURITY.md b/vendor/github.com/kevinburke/ssh_config/SECURITY.md new file mode 100644 index 0000000..adc2c5a --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/SECURITY.md @@ -0,0 +1,63 @@ +# ssh_config security policy + +## Supported Versions + +As of September 2025, we're not aware of any security problems with ssh_config, +past or present. That said, we recommend always using the latest version of +ssh_config, and of the Go programming language, to ensure you have the most +recent security fixes. + +## Reporting a Vulnerability + +We take security vulnerabilities seriously. If you discover a security vulnerability in ssh_config, please report it responsibly by following these steps: + +### How to Report + +Please follow the instructions outlined here to report a vulnerability +privately: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability + +If these are insufficient - it is not hard to find Kevin's contact information +on the Internet. + +### What to Include + +When reporting a vulnerability, please include a clear description of the vulnerability, steps to reproduce the issue, the potential impact, as well as any fixes you might have. + +### Response Timeline + +I'll try to acknowledge and patch the issue as quickly as possible. + +Security advisories for this project will be published through: +- GitHub Security Advisories on this repository +- an Issue on this repository +- The project's release notes +- Go vulnerability databases + +If you are using `ssh_config` and would like to be on a "pre-release" +distribution list for coordinating releases, please contact Kevin directly. + +### Security Considerations + +When using ssh_config, please be aware of these security considerations. + +#### File System Access + +This library reads SSH configuration files from the file system. Try to ensure +proper file permissions on SSH config files (typically 600 or 644), and be +cautious when parsing config files from untrusted sources. + +#### Input Validation + +The parser handles user-provided SSH configuration data. While we try our best +to parse the data appropriately, malformed configuration files could potentially +cause issues. Please try to validate and sanitize any configuration data from +external sources. + +#### Dependencies + +This project does not have any third party dependencies. Please try to keep your +Go version up to date. + +## Acknowledgments + +We appreciate security researchers and users who responsibly disclose vulnerabilities. Contributors who report valid security issues will be acknowledged in our security advisories (unless they prefer to remain anonymous). diff --git a/vendor/github.com/kevinburke/ssh_config/config.go b/vendor/github.com/kevinburke/ssh_config/config.go new file mode 100644 index 0000000..6365b41 --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/config.go @@ -0,0 +1,878 @@ +// Package ssh_config provides tools for manipulating SSH config files. +// +// Importantly, this parser attempts to preserve comments in a given file, so +// you can manipulate a `ssh_config` file from a program, if your heart desires. +// +// The Get() and GetStrict() functions will attempt to read values from +// $HOME/.ssh/config, falling back to /etc/ssh/ssh_config. The first argument is +// the host name to match on ("example.com"), and the second argument is the key +// you want to retrieve ("Port"). The keywords are case insensitive. +// +// port := ssh_config.Get("myhost", "Port") +// +// You can also manipulate an SSH config file and then print it or write it back +// to disk. +// +// f, _ := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "config")) +// cfg, _ := ssh_config.Decode(f) +// for _, host := range cfg.Hosts { +// fmt.Println("patterns:", host.Patterns) +// for _, node := range host.Nodes { +// fmt.Println(node.String()) +// } +// } +// +// // Write the cfg back to disk: +// fmt.Println(cfg.String()) +package ssh_config + +import ( + "bytes" + "errors" + "fmt" + "io" + "os" + osuser "os/user" + "path/filepath" + "regexp" + "runtime" + "strings" + "sync" +) + +const version = "1.6.0" + +var _ = version + +type configFinder func() string + +// UserSettings checks ~/.ssh and /etc/ssh for configuration files. The config +// files are parsed and cached the first time Get() or GetStrict() is called. +type UserSettings struct { + IgnoreErrors bool + customConfig *Config + customConfigFinder configFinder + systemConfig *Config + systemConfigFinder configFinder + userConfig *Config + userConfigFinder configFinder + loadConfigs sync.Once + onceErr error +} + +func homedir() string { + user, err := osuser.Current() + if err == nil { + return user.HomeDir + } else { + return os.Getenv("HOME") + } +} + +func userConfigFinder() string { + return filepath.Join(homedir(), ".ssh", "config") +} + +// DefaultUserSettings is the default UserSettings and is used by Get and +// GetStrict. It checks both $HOME/.ssh/config and /etc/ssh/ssh_config for keys, +// and it will return parse errors (if any) instead of swallowing them. +var DefaultUserSettings = &UserSettings{ + IgnoreErrors: false, + systemConfigFinder: systemConfigFinder, + userConfigFinder: userConfigFinder, +} + +func systemConfigFinder() string { + return filepath.Join("/", "etc", "ssh", "ssh_config") +} + +func findVal(c *Config, alias, key string) (string, error) { + if c == nil { + return "", nil + } + val, err := c.Get(alias, key) + if err != nil || val == "" { + return "", err + } + if err := validate(key, val); err != nil { + return "", err + } + return val, nil +} + +func findAll(c *Config, alias, key string) ([]string, error) { + if c == nil { + return nil, nil + } + return c.GetAll(alias, key) +} + +// Get finds the first value for key within a declaration that matches the +// alias. Get returns the empty string if no value was found, or if IgnoreErrors +// is false and we could not parse the configuration file. Use GetStrict to +// disambiguate the latter cases. +// +// The match for key is case insensitive. +// +// Get is a wrapper around DefaultUserSettings.Get. +func Get(alias, key string) string { + return DefaultUserSettings.Get(alias, key) +} + +// GetAll retrieves zero or more directives for key for the given alias. GetAll +// returns nil if no value was found, or if IgnoreErrors is false and we could +// not parse the configuration file. Use GetAllStrict to disambiguate the +// latter cases. +// +// In most cases you want to use Get or GetStrict, which returns a single value. +// However, a subset of ssh configuration values (IdentityFile, for example) +// allow you to specify multiple directives. +// +// The match for key is case insensitive. +// +// GetAll is a wrapper around DefaultUserSettings.GetAll. +func GetAll(alias, key string) []string { + return DefaultUserSettings.GetAll(alias, key) +} + +// GetStrict finds the first value for key within a declaration that matches the +// alias. If key has a default value and no matching configuration is found, the +// default will be returned. For more information on default values and the way +// patterns are matched, see the manpage for ssh_config. +// +// The returned error will be non-nil if and only if a user's configuration file +// or the system configuration file could not be parsed, and u.IgnoreErrors is +// false. +// +// GetStrict is a wrapper around DefaultUserSettings.GetStrict. +func GetStrict(alias, key string) (string, error) { + return DefaultUserSettings.GetStrict(alias, key) +} + +// GetAllStrict retrieves zero or more directives for key for the given alias. +// +// In most cases you want to use Get or GetStrict, which returns a single value. +// However, a subset of ssh configuration values (IdentityFile, for example) +// allow you to specify multiple directives. +// +// The returned error will be non-nil if and only if a user's configuration file +// or the system configuration file could not be parsed, and u.IgnoreErrors is +// false. +// +// GetAllStrict is a wrapper around DefaultUserSettings.GetAllStrict. +func GetAllStrict(alias, key string) ([]string, error) { + return DefaultUserSettings.GetAllStrict(alias, key) +} + +// Get finds the first value for key within a declaration that matches the +// alias. Get returns the empty string if no value was found, or if IgnoreErrors +// is false and we could not parse the configuration file. Use GetStrict to +// disambiguate the latter cases. +// +// The match for key is case insensitive. +func (u *UserSettings) Get(alias, key string) string { + val, err := u.GetStrict(alias, key) + if err != nil { + return "" + } + return val +} + +// GetAll retrieves zero or more directives for key for the given alias. GetAll +// returns nil if no value was found, or if IgnoreErrors is false and we could +// not parse the configuration file. Use GetStrict to disambiguate the latter +// cases. +// +// The match for key is case insensitive. +func (u *UserSettings) GetAll(alias, key string) []string { + val, _ := u.GetAllStrict(alias, key) + return val +} + +// GetStrict finds the first value for key within a declaration that matches the +// alias. If key has a default value and no matching configuration is found, the +// default will be returned. For more information on default values and the way +// patterns are matched, see the manpage for ssh_config. +// +// error will be non-nil if and only if a user's configuration file or the +// system configuration file could not be parsed, and u.IgnoreErrors is false. +func (u *UserSettings) GetStrict(alias, key string) (string, error) { + u.doLoadConfigs() + //lint:ignore S1002 I prefer it this way + if u.onceErr != nil && u.IgnoreErrors == false { + return "", u.onceErr + } + // TODO this is getting repetitive + if u.customConfig != nil { + val, err := findVal(u.customConfig, alias, key) + if err != nil || val != "" { + return val, err + } + } + val, err := findVal(u.userConfig, alias, key) + if err != nil || val != "" { + return val, err + } + val2, err2 := findVal(u.systemConfig, alias, key) + if err2 != nil || val2 != "" { + return val2, err2 + } + return Default(key), nil +} + +// GetAllStrict retrieves zero or more directives for key for the given alias. +// If key has a default value and no matching configuration is found, the +// default will be returned. For more information on default values and the way +// patterns are matched, see the manpage for ssh_config. +// +// The returned error will be non-nil if and only if a user's configuration file +// or the system configuration file could not be parsed, and u.IgnoreErrors is +// false. +func (u *UserSettings) GetAllStrict(alias, key string) ([]string, error) { + u.doLoadConfigs() + //lint:ignore S1002 I prefer it this way + if u.onceErr != nil && u.IgnoreErrors == false { + return nil, u.onceErr + } + if u.customConfig != nil { + val, err := findAll(u.customConfig, alias, key) + if err != nil || val != nil { + return val, err + } + } + val, err := findAll(u.userConfig, alias, key) + if err != nil || val != nil { + return val, err + } + val2, err2 := findAll(u.systemConfig, alias, key) + if err2 != nil || val2 != nil { + return val2, err2 + } + // TODO: IdentityFile has multiple default values that we should return. + if def := Default(key); def != "" { + return []string{def}, nil + } + return []string{}, nil +} + +// ConfigFinder will invoke f to try to find a ssh config file in a custom +// location on disk, instead of in /etc/ssh or $HOME/.ssh. f should return the +// name of a file containing SSH configuration. +// +// ConfigFinder must be invoked before any calls to Get or GetStrict and panics +// if f is nil. Most users should not need to use this function. +func (u *UserSettings) ConfigFinder(f func() string) { + if f == nil { + panic("cannot call ConfigFinder with nil function") + } + u.customConfigFinder = f +} + +func (u *UserSettings) doLoadConfigs() { + u.loadConfigs.Do(func() { + var filename string + var err error + if u.customConfigFinder != nil { + filename = u.customConfigFinder() + u.customConfig, err = parseFile(filename) + // IsNotExist should be returned because a user specified this + // function - not existing likely means they made an error + if err != nil { + u.onceErr = err + } + return + } + if u.userConfigFinder == nil { + filename = userConfigFinder() + } else { + filename = u.userConfigFinder() + } + u.userConfig, err = parseFile(filename) + //lint:ignore S1002 I prefer it this way + if err != nil && os.IsNotExist(err) == false { + u.onceErr = err + return + } + if u.systemConfigFinder == nil { + filename = systemConfigFinder() + } else { + filename = u.systemConfigFinder() + } + u.systemConfig, err = parseFile(filename) + //lint:ignore S1002 I prefer it this way + if err != nil && os.IsNotExist(err) == false { + u.onceErr = err + return + } + }) +} + +func parseFile(filename string) (*Config, error) { + return parseWithDepth(filename, 0) +} + +func parseWithDepth(filename string, depth uint8) (*Config, error) { + b, err := os.ReadFile(filename) + if err != nil { + return nil, err + } + return decodeBytes(b, isSystem(filename), depth) +} + +func isSystem(filename string) bool { + // TODO: not sure this is the best way to detect a system repo + return strings.HasPrefix(filepath.Clean(filename), "/etc/ssh") +} + +// Decode reads r into a Config, or returns an error if r could not be parsed as +// an SSH config file. +func Decode(r io.Reader) (*Config, error) { + b, err := io.ReadAll(r) + if err != nil { + return nil, err + } + return decodeBytes(b, false, 0) +} + +// DecodeBytes reads b into a Config, or returns an error if r could not be +// parsed as an SSH config file. +func DecodeBytes(b []byte) (*Config, error) { + return decodeBytes(b, false, 0) +} + +func decodeBytes(b []byte, system bool, depth uint8) (c *Config, err error) { + defer func() { + if r := recover(); r != nil { + if _, ok := r.(runtime.Error); ok { + panic(r) + } + if e, ok := r.(error); ok && e == ErrDepthExceeded { + err = e + return + } + err = errors.New(r.(string)) + } + }() + + c = parseSSH(lexSSH(b), system, depth) + return c, err +} + +// Config represents an SSH config file. +type Config struct { + // A list of hosts to match against. The file begins with an implicit + // "Host *" declaration matching all hosts. + Hosts []*Host + depth uint8 + position Position +} + +// Get finds the first value in the configuration that matches the alias and +// contains key. Get returns the empty string if no value was found, or if the +// Config contains an invalid conditional Include value. +// +// The match for key is case insensitive. +func (c *Config) Get(alias, key string) (string, error) { + lowerKey := strings.ToLower(key) + for _, host := range c.Hosts { + if !host.Matches(alias) { + continue + } + for _, node := range host.Nodes { + switch t := node.(type) { + case *Empty: + continue + case *KV: + // "keys are case insensitive" per the spec + lkey := strings.ToLower(t.Key) + if lkey == lowerKey { + return t.Value, nil + } + case *Include: + val := t.Get(alias, key) + if val != "" { + return val, nil + } + default: + return "", fmt.Errorf("unknown Node type %v", t) + } + } + } + return "", nil +} + +// GetAll returns all values in the configuration that match the alias and +// contains key, or nil if none are present. +func (c *Config) GetAll(alias, key string) ([]string, error) { + lowerKey := strings.ToLower(key) + all := []string(nil) + for _, host := range c.Hosts { + if !host.Matches(alias) { + continue + } + for _, node := range host.Nodes { + switch t := node.(type) { + case *Empty: + continue + case *KV: + // "keys are case insensitive" per the spec + lkey := strings.ToLower(t.Key) + if lkey == lowerKey { + all = append(all, t.Value) + } + case *Include: + val, _ := t.GetAll(alias, key) + if len(val) > 0 { + all = append(all, val...) + } + default: + return nil, fmt.Errorf("unknown Node type %v", t) + } + } + } + + return all, nil +} + +// String returns a string representation of the Config file. +func (c Config) String() string { + return marshal(c).String() +} + +func (c Config) MarshalText() ([]byte, error) { + return marshal(c).Bytes(), nil +} + +func marshal(c Config) *bytes.Buffer { + var buf bytes.Buffer + for i := range c.Hosts { + buf.WriteString(c.Hosts[i].String()) + } + return &buf +} + +// Pattern is a pattern in a Host declaration. Patterns are read-only values; +// create a new one with NewPattern(). +type Pattern struct { + str string // Its appearance in the file, not the value that gets compiled. + regex *regexp.Regexp + not bool // True if this is a negated match +} + +// String prints the string representation of the pattern. +func (p Pattern) String() string { + if p.not { + return "!" + p.str + } + return p.str +} + +// Copied from regexp.go with * and ? removed. +var specialBytes = []byte(`\.+()|[]{}^$`) + +func special(b byte) bool { + return bytes.IndexByte(specialBytes, b) >= 0 +} + +// NewPattern creates a new Pattern for matching hosts. NewPattern("*") creates +// a Pattern that matches all hosts. +// +// From the manpage, a pattern consists of zero or more non-whitespace +// characters, `*' (a wildcard that matches zero or more characters), or `?' (a +// wildcard that matches exactly one character). For example, to specify a set +// of declarations for any host in the ".co.uk" set of domains, the following +// pattern could be used: +// +// Host *.co.uk +// +// The following pattern would match any host in the 192.168.0.[0-9] network range: +// +// Host 192.168.0.? +func NewPattern(s string) (*Pattern, error) { + if s == "" { + return nil, errors.New("ssh_config: empty pattern") + } + negated := false + if s[0] == '!' { + negated = true + s = s[1:] + } + var buf bytes.Buffer + buf.WriteByte('^') + for i := 0; i < len(s); i++ { + // A byte loop is correct because all metacharacters are ASCII. + switch b := s[i]; b { + case '*': + buf.WriteString(".*") + case '?': + buf.WriteString(".?") + default: + // borrowing from QuoteMeta here. + if special(b) { + buf.WriteByte('\\') + } + buf.WriteByte(b) + } + } + buf.WriteByte('$') + r, err := regexp.Compile(buf.String()) + if err != nil { + return nil, err + } + return &Pattern{str: s, regex: r, not: negated}, nil +} + +// Host describes a Host or Match directive and the keywords that follow it. +type Host struct { + // A list of host patterns that should match this host. + Patterns []*Pattern + // A Node is either a key/value pair or a comment line. + Nodes []Node + // EOLComment is the comment (if any) terminating the Host line. + EOLComment string + // Whitespace if any between the Host declaration and a trailing comment. + spaceBeforeComment string + + hasEquals bool + leadingSpace int // TODO: handle spaces vs tabs here. + // The file starts with an implicit "Host *" declaration. + implicit bool + // isMatch is true if this block was created by a Match directive. + isMatch bool + // matchKeyword stores the original text after "Match" (e.g. "Host" or + // "all") so we can round-trip correctly. + matchKeyword string +} + +// Matches returns true if the Host matches for the given alias. For +// a description of the rules that provide a match, see the manpage for +// ssh_config. +func (h *Host) Matches(alias string) bool { + found := false + for i := range h.Patterns { + if h.Patterns[i].regex.MatchString(alias) { + if h.Patterns[i].not { + // Negated match. "A pattern entry may be negated by prefixing + // it with an exclamation mark (`!'). If a negated entry is + // matched, then the Host entry is ignored, regardless of + // whether any other patterns on the line match. Negated matches + // are therefore useful to provide exceptions for wildcard + // matches." + return false + } + found = true + } + } + return found +} + +// String prints h as it would appear in a config file. Minor tweaks may be +// present in the whitespace in the printed file. +func (h *Host) String() string { + var buf strings.Builder + //lint:ignore S1002 I prefer to write it this way + if h.implicit == false { + buf.WriteString(strings.Repeat(" ", int(h.leadingSpace))) + if h.isMatch { + buf.WriteString("Match") + if h.hasEquals { + buf.WriteString(" = ") + } else { + buf.WriteString(" ") + } + buf.WriteString(h.matchKeyword) + if !strings.EqualFold(h.matchKeyword, "all") { + buf.WriteString(" ") + for i, pat := range h.Patterns { + buf.WriteString(pat.String()) + if i < len(h.Patterns)-1 { + buf.WriteString(" ") + } + } + } + } else { + buf.WriteString("Host") + if h.hasEquals { + buf.WriteString(" = ") + } else { + buf.WriteString(" ") + } + for i, pat := range h.Patterns { + buf.WriteString(pat.String()) + if i < len(h.Patterns)-1 { + buf.WriteString(" ") + } + } + } + if h.EOLComment != "" { + if h.spaceBeforeComment != "" { + buf.WriteString(h.spaceBeforeComment) + } else { + buf.WriteByte(' ') + } + buf.WriteByte('#') + buf.WriteString(h.EOLComment) + } + buf.WriteByte('\n') + } + for i := range h.Nodes { + buf.WriteString(h.Nodes[i].String()) + buf.WriteByte('\n') + } + return buf.String() +} + +// Node represents a line in a Config. +type Node interface { + Pos() Position + String() string +} + +// KV is a line in the config file that contains a key, a value, and possibly +// a comment. +type KV struct { + Key string + Value string + // Whitespace after the value but before any comment + spaceAfterValue string + Comment string + hasEquals bool + leadingSpace int // Space before the key. TODO handle spaces vs tabs. + position Position + // rawValue preserves the original value text (including surrounding double + // quotes, if any) so that String() can roundtrip the config file faithfully. + rawValue string +} + +// Pos returns k's Position. +func (k *KV) Pos() Position { + return k.position +} + +// String prints k as it was parsed in the config file. +func (k *KV) String() string { + if k == nil { + return "" + } + equals := " " + if k.hasEquals { + equals = " = " + } + val := k.Value + if k.rawValue != "" { + val = k.rawValue + } + line := strings.Repeat(" ", int(k.leadingSpace)) + k.Key + equals + val + if k.Comment != "" { + if k.spaceAfterValue != "" { + line += k.spaceAfterValue + } else { + line += " " + } + line += "#" + k.Comment + } else { + line += k.spaceAfterValue + } + return line +} + +// Empty is a line in the config file that contains only whitespace or comments. +type Empty struct { + Comment string + leadingSpace int // TODO handle spaces vs tabs. + position Position +} + +// Pos returns e's Position. +func (e *Empty) Pos() Position { + return e.position +} + +// String prints e as it was parsed in the config file. +func (e *Empty) String() string { + if e == nil { + return "" + } + if e.Comment == "" { + return "" + } + return fmt.Sprintf("%s#%s", strings.Repeat(" ", int(e.leadingSpace)), e.Comment) +} + +// Include holds the result of an Include directive, including the config files +// that have been parsed as part of that directive. At most 5 levels of Include +// statements will be parsed. +type Include struct { + // Comment is the contents of any comment at the end of the Include + // statement. + Comment string + // an include directive can include several different files, and wildcards + directives []string + + mu sync.Mutex + // 1:1 mapping between matches and keys in files array; matches preserves + // ordering + matches []string + // actual filenames are listed here + files map[string]*Config + leadingSpace int + position Position + depth uint8 + hasEquals bool +} + +const maxRecurseDepth = 5 + +// ErrDepthExceeded is returned if too many Include directives are parsed. +// Usually this indicates a recursive loop (an Include directive pointing to the +// file it contains). +var ErrDepthExceeded = errors.New("ssh_config: max recurse depth exceeded") + +func removeDups(arr []string) []string { + // Use map to record duplicates as we find them. + encountered := make(map[string]bool, len(arr)) + result := make([]string, 0) + + for v := range arr { + //lint:ignore S1002 I prefer it this way + if encountered[arr[v]] == false { + encountered[arr[v]] = true + result = append(result, arr[v]) + } + } + return result +} + +// NewInclude creates a new Include with a list of file globs to include. +// Configuration files are parsed greedily (e.g. as soon as this function runs). +// Any error encountered while parsing nested configuration files will be +// returned. +func NewInclude(directives []string, hasEquals bool, pos Position, comment string, system bool, depth uint8) (*Include, error) { + if depth > maxRecurseDepth { + return nil, ErrDepthExceeded + } + inc := &Include{ + Comment: comment, + directives: directives, + files: make(map[string]*Config), + position: pos, + leadingSpace: pos.Col - 1, + depth: depth, + hasEquals: hasEquals, + } + // no need for inc.mu.Lock() since nothing else can access this inc + matches := make([]string, 0) + for i := range directives { + var path string + if filepath.IsAbs(directives[i]) { + path = directives[i] + } else if system { + path = filepath.Join("/etc/ssh", directives[i]) + } else if strings.HasPrefix(directives[i], "~/") { + path = filepath.Join(homedir(), directives[i][2:]) + } else { + path = filepath.Join(homedir(), ".ssh", directives[i]) + } + theseMatches, err := filepath.Glob(path) + if err != nil { + return nil, err + } + matches = append(matches, theseMatches...) + } + matches = removeDups(matches) + inc.matches = matches + for i := range matches { + config, err := parseWithDepth(matches[i], depth) + if err != nil { + return nil, err + } + inc.files[matches[i]] = config + } + return inc, nil +} + +// Pos returns the position of the Include directive in the larger file. +func (i *Include) Pos() Position { + return i.position +} + +// Get finds the first value in the Include statement matching the alias and the +// given key. +func (inc *Include) Get(alias, key string) string { + inc.mu.Lock() + defer inc.mu.Unlock() + // TODO: we search files in any order which is not correct + for i := range inc.matches { + cfg := inc.files[inc.matches[i]] + if cfg == nil { + panic("nil cfg") + } + val, err := cfg.Get(alias, key) + if err == nil && val != "" { + return val + } + } + return "" +} + +// GetAll finds all values in the Include statement matching the alias and the +// given key. +func (inc *Include) GetAll(alias, key string) ([]string, error) { + inc.mu.Lock() + defer inc.mu.Unlock() + var vals []string + + // TODO: we search files in any order which is not correct + for i := range inc.matches { + cfg := inc.files[inc.matches[i]] + if cfg == nil { + panic("nil cfg") + } + val, err := cfg.GetAll(alias, key) + if err == nil && len(val) != 0 { + // In theory if SupportsMultiple was false for this key we could + // stop looking here. But the caller has asked us to find all + // instances of the keyword (and could use Get() if they wanted) so + // let's keep looking. + vals = append(vals, val...) + } + } + return vals, nil +} + +// String prints out a string representation of this Include directive. Note +// included Config files are not printed as part of this representation. +func (inc *Include) String() string { + equals := " " + if inc.hasEquals { + equals = " = " + } + line := fmt.Sprintf("%sInclude%s%s", strings.Repeat(" ", int(inc.leadingSpace)), equals, strings.Join(inc.directives, " ")) + if inc.Comment != "" { + line += " #" + inc.Comment + } + return line +} + +var matchAll *Pattern + +func init() { + var err error + matchAll, err = NewPattern("*") + if err != nil { + panic(err) + } +} + +func newConfig() *Config { + return &Config{ + Hosts: []*Host{ + { + implicit: true, + Patterns: []*Pattern{matchAll}, + Nodes: make([]Node, 0), + }, + }, + depth: 0, + } +} diff --git a/vendor/github.com/kevinburke/ssh_config/lexer.go b/vendor/github.com/kevinburke/ssh_config/lexer.go new file mode 100644 index 0000000..11680b4 --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/lexer.go @@ -0,0 +1,240 @@ +package ssh_config + +import ( + "bytes" +) + +// Define state functions +type sshLexStateFn func() sshLexStateFn + +type sshLexer struct { + inputIdx int + input []rune // Textual source + + buffer []rune // Runes composing the current token + tokens chan token + line int + col int + endbufferLine int + endbufferCol int +} + +func (s *sshLexer) lexComment(previousState sshLexStateFn) sshLexStateFn { + return func() sshLexStateFn { + growingString := "" + for next := s.peek(); next != '\n' && next != eof; next = s.peek() { + if next == '\r' && s.follow("\r\n") { + break + } + growingString += string(next) + s.next() + } + s.emitWithValue(tokenComment, growingString) + s.skip() + return previousState + } +} + +// lex the space after an equals sign in a function +func (s *sshLexer) lexRspace() sshLexStateFn { + for { + next := s.peek() + if !isSpace(next) { + break + } + s.skip() + } + return s.lexRvalue +} + +func (s *sshLexer) lexEquals() sshLexStateFn { + for { + next := s.peek() + if next == '=' { + s.emit(tokenEquals) + s.skip() + return s.lexRspace + } + // TODO error handling here; newline eof etc. + if !isSpace(next) { + break + } + s.skip() + } + return s.lexRvalue +} + +func (s *sshLexer) lexKey() sshLexStateFn { + growingString := "" + + for r := s.peek(); isKeyChar(r); r = s.peek() { + // simplified a lot here + if isSpace(r) || r == '=' { + s.emitWithValue(tokenKey, growingString) + s.skip() + return s.lexEquals + } + growingString += string(r) + s.next() + } + s.emitWithValue(tokenKey, growingString) + return s.lexEquals +} + +func (s *sshLexer) lexRvalue() sshLexStateFn { + growingString := "" + for { + next := s.peek() + switch next { + case '\r': + if s.follow("\r\n") { + s.emitWithValue(tokenString, growingString) + s.skip() + return s.lexVoid + } + case '\n': + s.emitWithValue(tokenString, growingString) + s.skip() + return s.lexVoid + case '#': + s.emitWithValue(tokenString, growingString) + s.skip() + return s.lexComment(s.lexVoid) + case eof: + s.next() + } + if next == eof { + break + } + growingString += string(next) + s.next() + } + s.emit(tokenEOF) + return nil +} + +func (s *sshLexer) read() rune { + r := s.peek() + if r == '\n' { + s.endbufferLine++ + s.endbufferCol = 1 + } else { + s.endbufferCol++ + } + s.inputIdx++ + return r +} + +func (s *sshLexer) next() rune { + r := s.read() + + if r != eof { + s.buffer = append(s.buffer, r) + } + return r +} + +func (s *sshLexer) lexVoid() sshLexStateFn { + for { + next := s.peek() + switch next { + case '#': + s.skip() + return s.lexComment(s.lexVoid) + case '\r': + fallthrough + case '\n': + s.emit(tokenEmptyLine) + s.skip() + continue + } + + if isSpace(next) { + s.skip() + } + + if isKeyStartChar(next) { + return s.lexKey + } + + // removed IsKeyStartChar and lexKey. probably will need to readd + + if next == eof { + s.next() + break + } + } + + s.emit(tokenEOF) + return nil +} + +func (s *sshLexer) ignore() { + s.buffer = make([]rune, 0) + s.line = s.endbufferLine + s.col = s.endbufferCol +} + +func (s *sshLexer) skip() { + s.next() + s.ignore() +} + +func (s *sshLexer) emit(t tokenType) { + s.emitWithValue(t, string(s.buffer)) +} + +func (s *sshLexer) emitWithValue(t tokenType, value string) { + tok := token{ + Position: Position{s.line, s.col}, + typ: t, + val: value, + } + s.tokens <- tok + s.ignore() +} + +func (s *sshLexer) peek() rune { + if s.inputIdx >= len(s.input) { + return eof + } + + r := s.input[s.inputIdx] + return r +} + +func (s *sshLexer) follow(next string) bool { + inputIdx := s.inputIdx + for _, expectedRune := range next { + if inputIdx >= len(s.input) { + return false + } + r := s.input[inputIdx] + inputIdx++ + if expectedRune != r { + return false + } + } + return true +} + +func (s *sshLexer) run() { + for state := s.lexVoid; state != nil; { + state = state() + } + close(s.tokens) +} + +func lexSSH(input []byte) chan token { + runes := bytes.Runes(input) + l := &sshLexer{ + input: runes, + tokens: make(chan token), + line: 1, + col: 1, + endbufferLine: 1, + endbufferCol: 1, + } + go l.run() + return l.tokens +} diff --git a/vendor/github.com/kevinburke/ssh_config/parser.go b/vendor/github.com/kevinburke/ssh_config/parser.go new file mode 100644 index 0000000..c524d0e --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/parser.go @@ -0,0 +1,270 @@ +package ssh_config + +import ( + "fmt" + "strings" + "unicode" +) + +type sshParser struct { + flow chan token + config *Config + tokensBuffer []token + currentTable []string + seenTableKeys []string + // /etc/ssh parser or local parser - used to find the default for relative + // filepaths in the Include directive + system bool + depth uint8 +} + +type sshParserStateFn func() sshParserStateFn + +// Formats and panics an error message based on a token +func (p *sshParser) raiseErrorf(tok *token, msg string) { + // TODO this format is ugly + panic(tok.Position.String() + ": " + msg) +} + +func (p *sshParser) raiseError(tok *token, err error) { + if err == ErrDepthExceeded { + panic(err) + } + // TODO this format is ugly + panic(tok.Position.String() + ": " + err.Error()) +} + +func (p *sshParser) run() { + for state := p.parseStart; state != nil; { + state = state() + } +} + +func (p *sshParser) peek() *token { + if len(p.tokensBuffer) != 0 { + return &(p.tokensBuffer[0]) + } + + tok, ok := <-p.flow + if !ok { + return nil + } + p.tokensBuffer = append(p.tokensBuffer, tok) + return &tok +} + +func (p *sshParser) getToken() *token { + if len(p.tokensBuffer) != 0 { + tok := p.tokensBuffer[0] + p.tokensBuffer = p.tokensBuffer[1:] + return &tok + } + tok, ok := <-p.flow + if !ok { + return nil + } + return &tok +} + +func (p *sshParser) parseStart() sshParserStateFn { + tok := p.peek() + + // end of stream, parsing is finished + if tok == nil { + return nil + } + + switch tok.typ { + case tokenComment, tokenEmptyLine: + return p.parseComment + case tokenKey: + return p.parseKV + case tokenEOF: + return nil + default: + p.raiseErrorf(tok, fmt.Sprintf("unexpected token %q\n", tok)) + } + return nil +} + +func (p *sshParser) parseKV() sshParserStateFn { + key := p.getToken() + hasEquals := false + val := p.getToken() + if val.typ == tokenEquals { + hasEquals = true + val = p.getToken() + } + comment := "" + tok := p.peek() + if tok == nil { + tok = &token{typ: tokenEOF} + } + if tok.typ == tokenComment && tok.Position.Line == val.Position.Line { + tok = p.getToken() + comment = tok.val + } + if strings.ToLower(key.val) == "match" { + return p.parseMatch(val, hasEquals, comment) + } + if strings.ToLower(key.val) == "host" { + strPatterns := strings.Split(val.val, " ") + patterns := make([]*Pattern, 0) + for i := range strPatterns { + if strPatterns[i] == "" { + continue + } + pat, err := NewPattern(strPatterns[i]) + if err != nil { + p.raiseErrorf(val, fmt.Sprintf("Invalid host pattern: %v", err)) + return nil + } + patterns = append(patterns, pat) + } + // val.val at this point could be e.g. "example.com " + hostval := strings.TrimRightFunc(val.val, unicode.IsSpace) + spaceBeforeComment := val.val[len(hostval):] + val.val = hostval + p.config.Hosts = append(p.config.Hosts, &Host{ + Patterns: patterns, + Nodes: make([]Node, 0), + EOLComment: comment, + spaceBeforeComment: spaceBeforeComment, + hasEquals: hasEquals, + }) + return p.parseStart + } + lastHost := p.config.Hosts[len(p.config.Hosts)-1] + if strings.ToLower(key.val) == "include" { + inc, err := NewInclude(strings.Split(val.val, " "), hasEquals, key.Position, comment, p.system, p.depth+1) + if err == ErrDepthExceeded { + p.raiseError(val, err) + return nil + } + if err != nil { + p.raiseErrorf(val, fmt.Sprintf("Error parsing Include directive: %v", err)) + return nil + } + lastHost.Nodes = append(lastHost.Nodes, inc) + return p.parseStart + } + shortval := strings.TrimRightFunc(val.val, unicode.IsSpace) + spaceAfterValue := val.val[len(shortval):] + unquoted := shortval + if len(shortval) >= 2 && shortval[0] == '"' && shortval[len(shortval)-1] == '"' { + unquoted = shortval[1 : len(shortval)-1] + } + kv := &KV{ + Key: key.val, + Value: unquoted, + rawValue: shortval, + spaceAfterValue: spaceAfterValue, + Comment: comment, + hasEquals: hasEquals, + leadingSpace: key.Position.Col - 1, + position: key.Position, + } + lastHost.Nodes = append(lastHost.Nodes, kv) + return p.parseStart +} + +func (p *sshParser) parseMatch(val *token, hasEquals bool, comment string) sshParserStateFn { + // val.val contains everything after "Match ", e.g. "Host *.example.com" + // or "all". + trimmed := strings.TrimRightFunc(val.val, unicode.IsSpace) + spaceBeforeComment := val.val[len(trimmed):] + fields := strings.Fields(trimmed) + if len(fields) == 0 { + p.raiseErrorf(val, "ssh_config: Match directive requires at least one criterion") + return nil + } + criterion := strings.ToLower(fields[0]) + + switch criterion { + case "all": + // "Match all" is equivalent to "Host *" — matches everything. + p.config.Hosts = append(p.config.Hosts, &Host{ + Patterns: []*Pattern{matchAll}, + Nodes: make([]Node, 0), + EOLComment: comment, + spaceBeforeComment: spaceBeforeComment, + hasEquals: hasEquals, + isMatch: true, + matchKeyword: fields[0], // preserve original case + }) + return p.parseStart + + case "host": + patterns := make([]*Pattern, 0) + for _, s := range fields[1:] { + if s == "" { + continue + } + pat, err := NewPattern(s) + if err != nil { + p.raiseErrorf(val, fmt.Sprintf("Invalid host pattern: %v", err)) + return nil + } + patterns = append(patterns, pat) + } + if len(patterns) == 0 { + p.raiseErrorf(val, "ssh_config: Match Host requires at least one pattern") + return nil + } + p.config.Hosts = append(p.config.Hosts, &Host{ + Patterns: patterns, + Nodes: make([]Node, 0), + EOLComment: comment, + spaceBeforeComment: spaceBeforeComment, + hasEquals: hasEquals, + isMatch: true, + matchKeyword: fields[0], // preserve original case + }) + return p.parseStart + + case "exec": + // Match Exec runs arbitrary commands. Supporting it would allow + // untrusted SSH config files to execute code on the parsing + // machine. Reject it explicitly. + p.raiseErrorf(val, "ssh_config: Match Exec is not supported") + return nil + + default: + p.raiseErrorf(val, fmt.Sprintf("ssh_config: unsupported Match criterion %q", criterion)) + return nil + } +} + +func (p *sshParser) parseComment() sshParserStateFn { + comment := p.getToken() + lastHost := p.config.Hosts[len(p.config.Hosts)-1] + lastHost.Nodes = append(lastHost.Nodes, &Empty{ + Comment: comment.val, + // account for the "#" as well + leadingSpace: comment.Position.Col - 2, + position: comment.Position, + }) + return p.parseStart +} + +func parseSSH(flow chan token, system bool, depth uint8) *Config { + // Ensure we consume tokens to completion even if parser exits early + defer func() { + for range flow { + } + }() + + result := newConfig() + result.position = Position{1, 1} + parser := &sshParser{ + flow: flow, + config: result, + tokensBuffer: make([]token, 0), + currentTable: make([]string, 0), + seenTableKeys: make([]string, 0), + system: system, + depth: depth, + } + parser.run() + return result +} diff --git a/vendor/github.com/kevinburke/ssh_config/position.go b/vendor/github.com/kevinburke/ssh_config/position.go new file mode 100644 index 0000000..e0b5e3f --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/position.go @@ -0,0 +1,25 @@ +package ssh_config + +import "fmt" + +// Position of a document element within a SSH document. +// +// Line and Col are both 1-indexed positions for the element's line number and +// column number, respectively. Values of zero or less will cause Invalid(), +// to return true. +type Position struct { + Line int // line within the document + Col int // column within the line +} + +// String representation of the position. +// Displays 1-indexed line and column numbers. +func (p Position) String() string { + return fmt.Sprintf("(%d, %d)", p.Line, p.Col) +} + +// Invalid returns whether or not the position is valid (i.e. with negative or +// null values) +func (p Position) Invalid() bool { + return p.Line <= 0 || p.Col <= 0 +} diff --git a/vendor/github.com/kevinburke/ssh_config/token.go b/vendor/github.com/kevinburke/ssh_config/token.go new file mode 100644 index 0000000..a0ecbb2 --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/token.go @@ -0,0 +1,49 @@ +package ssh_config + +import "fmt" + +type token struct { + Position + typ tokenType + val string +} + +func (t token) String() string { + switch t.typ { + case tokenEOF: + return "EOF" + } + return fmt.Sprintf("%q", t.val) +} + +type tokenType int + +const ( + eof = -(iota + 1) +) + +const ( + tokenError tokenType = iota + tokenEOF + tokenEmptyLine + tokenComment + tokenKey + tokenEquals + tokenString +) + +func isSpace(r rune) bool { + return r == ' ' || r == '\t' +} + +func isKeyStartChar(r rune) bool { + return !(isSpace(r) || r == '\r' || r == '\n' || r == eof) +} + +// I'm not sure that this is correct +func isKeyChar(r rune) bool { + // Keys start with the first character that isn't whitespace or [ and end + // with the last non-whitespace character before the equals sign. Keys + // cannot contain a # character." + return !(r == '\r' || r == '\n' || r == eof || r == '=') +} diff --git a/vendor/github.com/kevinburke/ssh_config/validators.go b/vendor/github.com/kevinburke/ssh_config/validators.go new file mode 100644 index 0000000..5977f90 --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/validators.go @@ -0,0 +1,186 @@ +package ssh_config + +import ( + "fmt" + "strconv" + "strings" +) + +// Default returns the default value for the given keyword, for example "22" if +// the keyword is "Port". Default returns the empty string if the keyword has no +// default, or if the keyword is unknown. Keyword matching is case-insensitive. +// +// Default values are provided by OpenSSH_7.4p1 on a Mac. +func Default(keyword string) string { + return defaults[strings.ToLower(keyword)] +} + +// Arguments where the value must be "yes" or "no" and *only* yes or no. +var yesnos = map[string]bool{ + strings.ToLower("BatchMode"): true, + strings.ToLower("CanonicalizeFallbackLocal"): true, + strings.ToLower("ChallengeResponseAuthentication"): true, + strings.ToLower("CheckHostIP"): true, + strings.ToLower("ClearAllForwardings"): true, + strings.ToLower("Compression"): true, + strings.ToLower("EnableSSHKeysign"): true, + strings.ToLower("ExitOnForwardFailure"): true, + strings.ToLower("ForwardAgent"): true, + strings.ToLower("ForwardX11"): true, + strings.ToLower("ForwardX11Trusted"): true, + strings.ToLower("GatewayPorts"): true, + strings.ToLower("GSSAPIAuthentication"): true, + strings.ToLower("GSSAPIDelegateCredentials"): true, + strings.ToLower("HostbasedAuthentication"): true, + strings.ToLower("IdentitiesOnly"): true, + strings.ToLower("KbdInteractiveAuthentication"): true, + strings.ToLower("NoHostAuthenticationForLocalhost"): true, + strings.ToLower("PasswordAuthentication"): true, + strings.ToLower("PermitLocalCommand"): true, + strings.ToLower("PubkeyAuthentication"): true, + strings.ToLower("RhostsRSAAuthentication"): true, + strings.ToLower("RSAAuthentication"): true, + strings.ToLower("StreamLocalBindUnlink"): true, + strings.ToLower("TCPKeepAlive"): true, + strings.ToLower("UseKeychain"): true, + strings.ToLower("UsePrivilegedPort"): true, + strings.ToLower("VisualHostKey"): true, +} + +var uints = map[string]bool{ + strings.ToLower("CanonicalizeMaxDots"): true, + strings.ToLower("CompressionLevel"): true, // 1 to 9 + strings.ToLower("ConnectionAttempts"): true, + strings.ToLower("ConnectTimeout"): true, + strings.ToLower("NumberOfPasswordPrompts"): true, + strings.ToLower("Port"): true, + strings.ToLower("ServerAliveCountMax"): true, + strings.ToLower("ServerAliveInterval"): true, +} + +func mustBeYesOrNo(lkey string) bool { + return yesnos[lkey] +} + +func mustBeUint(lkey string) bool { + return uints[lkey] +} + +func validate(key, val string) error { + lkey := strings.ToLower(key) + if mustBeYesOrNo(lkey) && (val != "yes" && val != "no") { + return fmt.Errorf("ssh_config: value for key %q must be 'yes' or 'no', got %q", key, val) + } + if mustBeUint(lkey) { + _, err := strconv.ParseUint(val, 10, 64) + if err != nil { + return fmt.Errorf("ssh_config: %v", err) + } + } + return nil +} + +var defaults = map[string]string{ + strings.ToLower("AddKeysToAgent"): "no", + strings.ToLower("AddressFamily"): "any", + strings.ToLower("BatchMode"): "no", + strings.ToLower("CanonicalizeFallbackLocal"): "yes", + strings.ToLower("CanonicalizeHostname"): "no", + strings.ToLower("CanonicalizeMaxDots"): "1", + strings.ToLower("ChallengeResponseAuthentication"): "yes", + strings.ToLower("CheckHostIP"): "yes", + // TODO is this still the correct cipher + strings.ToLower("Cipher"): "3des", + strings.ToLower("Ciphers"): "chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc", + strings.ToLower("ClearAllForwardings"): "no", + strings.ToLower("Compression"): "no", + strings.ToLower("CompressionLevel"): "6", + strings.ToLower("ConnectionAttempts"): "1", + strings.ToLower("ControlMaster"): "no", + strings.ToLower("EnableSSHKeysign"): "no", + strings.ToLower("EscapeChar"): "~", + strings.ToLower("ExitOnForwardFailure"): "no", + strings.ToLower("FingerprintHash"): "sha256", + strings.ToLower("ForwardAgent"): "no", + strings.ToLower("ForwardX11"): "no", + strings.ToLower("ForwardX11Timeout"): "20m", + strings.ToLower("ForwardX11Trusted"): "no", + strings.ToLower("GatewayPorts"): "no", + strings.ToLower("GlobalKnownHostsFile"): "/etc/ssh/ssh_known_hosts /etc/ssh/ssh_known_hosts2", + strings.ToLower("GSSAPIAuthentication"): "no", + strings.ToLower("GSSAPIDelegateCredentials"): "no", + strings.ToLower("HashKnownHosts"): "no", + strings.ToLower("HostbasedAuthentication"): "no", + + strings.ToLower("HostbasedKeyTypes"): "ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,ssh-rsa", + strings.ToLower("HostKeyAlgorithms"): "ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,ssh-rsa", + // HostName has a dynamic default (the value passed at the command line). + + strings.ToLower("IdentitiesOnly"): "no", + strings.ToLower("IdentityFile"): "~/.ssh/identity", + + // IPQoS has a dynamic default based on interactive or non-interactive + // sessions. + + strings.ToLower("KbdInteractiveAuthentication"): "yes", + + strings.ToLower("KexAlgorithms"): "curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1", + strings.ToLower("LogLevel"): "INFO", + strings.ToLower("MACs"): "umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1", + + strings.ToLower("NoHostAuthenticationForLocalhost"): "no", + strings.ToLower("NumberOfPasswordPrompts"): "3", + strings.ToLower("PasswordAuthentication"): "yes", + strings.ToLower("PermitLocalCommand"): "no", + strings.ToLower("Port"): "22", + + strings.ToLower("PreferredAuthentications"): "gssapi-with-mic,hostbased,publickey,keyboard-interactive,password", + strings.ToLower("Protocol"): "2", + strings.ToLower("ProxyUseFdpass"): "no", + strings.ToLower("PubkeyAcceptedKeyTypes"): "ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,ssh-rsa", + strings.ToLower("PubkeyAuthentication"): "yes", + strings.ToLower("RekeyLimit"): "default none", + strings.ToLower("RhostsRSAAuthentication"): "no", + strings.ToLower("RSAAuthentication"): "yes", + + strings.ToLower("ServerAliveCountMax"): "3", + strings.ToLower("ServerAliveInterval"): "0", + strings.ToLower("StreamLocalBindMask"): "0177", + strings.ToLower("StreamLocalBindUnlink"): "no", + strings.ToLower("StrictHostKeyChecking"): "ask", + strings.ToLower("TCPKeepAlive"): "yes", + strings.ToLower("Tunnel"): "no", + strings.ToLower("TunnelDevice"): "any:any", + strings.ToLower("UpdateHostKeys"): "no", + strings.ToLower("UseKeychain"): "no", + strings.ToLower("UsePrivilegedPort"): "no", + + strings.ToLower("UserKnownHostsFile"): "~/.ssh/known_hosts ~/.ssh/known_hosts2", + strings.ToLower("VerifyHostKeyDNS"): "no", + strings.ToLower("VisualHostKey"): "no", + strings.ToLower("XAuthLocation"): "/usr/X11R6/bin/xauth", +} + +// these identities are used for SSH protocol 2 +var defaultProtocol2Identities = []string{ + "~/.ssh/id_dsa", + "~/.ssh/id_ecdsa", + "~/.ssh/id_ed25519", + "~/.ssh/id_rsa", +} + +// these directives support multiple items that can be collected +// across multiple files +var pluralDirectives = map[string]bool{ + "CertificateFile": true, + "IdentityFile": true, + "DynamicForward": true, + "RemoteForward": true, + "SendEnv": true, + "SetEnv": true, +} + +// SupportsMultiple reports whether a directive can be specified multiple times. +func SupportsMultiple(key string) bool { + return pluralDirectives[strings.ToLower(key)] +} diff --git a/vendor/modules.txt b/vendor/modules.txt index f0061b2..bd128d8 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -45,6 +45,9 @@ github.com/dlclark/regexp2/syntax # github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f ## explicit; go 1.16 github.com/erikgeiser/coninput +# github.com/kevinburke/ssh_config v1.6.0 +## explicit; go 1.18 +github.com/kevinburke/ssh_config # github.com/kr/fs v0.1.0 ## explicit github.com/kr/fs From 94002e286f740d8fafa4d756c260ad3f3fe9d27f Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 23:33:26 +0300 Subject: [PATCH 2/4] feat(ssh): add conn dialer with bounded handshake, host keys and auth chain (2B.2) 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 --- internal/ssh/conn/auth.go | 263 +++++++++++++++++ internal/ssh/conn/dial.go | 235 ++++++++++++++++ internal/ssh/conn/dial_test.go | 452 ++++++++++++++++++++++++++++++ internal/ssh/conn/helpers_test.go | 384 +++++++++++++++++++++++++ internal/ssh/conn/hostkey.go | 272 ++++++++++++++++++ internal/ssh/conn/owner_other.go | 5 + internal/ssh/conn/owner_unix.go | 23 ++ internal/ssh/conn/prompter.go | 55 ++++ plans/rework/04-dev-log-B.md | 31 ++ 9 files changed, 1720 insertions(+) create mode 100644 internal/ssh/conn/auth.go create mode 100644 internal/ssh/conn/dial.go create mode 100644 internal/ssh/conn/dial_test.go create mode 100644 internal/ssh/conn/helpers_test.go create mode 100644 internal/ssh/conn/hostkey.go create mode 100644 internal/ssh/conn/owner_other.go create mode 100644 internal/ssh/conn/owner_unix.go create mode 100644 internal/ssh/conn/prompter.go diff --git a/internal/ssh/conn/auth.go b/internal/ssh/conn/auth.go new file mode 100644 index 0000000..a42fa7e --- /dev/null +++ b/internal/ssh/conn/auth.go @@ -0,0 +1,263 @@ +package conn + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "os" + "strings" + "sync" + "sync/atomic" + "time" + + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/agent" +) + +// agentConn is the process-wide connection to ssh-agent (N-P2-1: the old +// code opened a new socket per connect and never closed it). It is opened on +// first use, reopened after an error, and closed by dialer.close. +type agentConn struct { + sock string + + mu sync.Mutex + c net.Conn + ag agent.ExtendedAgent + dials atomic.Int32 // sockets opened, for tests +} + +// signers returns the agent's keys; no agent (or an agent error) yields nil. +func (a *agentConn) signers() []ssh.Signer { + if a == nil || a.sock == "" { + return nil + } + a.mu.Lock() + defer a.mu.Unlock() + if a.ag == nil { + c, err := net.DialTimeout("unix", a.sock, 2*time.Second) + if err != nil { + return nil + } + a.dials.Add(1) + a.c, a.ag = c, agent.NewClient(c) + } + ss, err := a.ag.Signers() + if err != nil { + a.c.Close() + a.c, a.ag = nil, nil + return nil + } + return ss +} + +func (a *agentConn) close() { + if a == nil { + return + } + a.mu.Lock() + defer a.mu.Unlock() + if a.c != nil { + a.c.Close() + a.c, a.ag = nil, nil + } +} + +// authMethods builds the auth chain (N-P2-2): public keys (explicit +// IdentityFiles, then agent keys, then default key files), password (stored +// or asked), keyboard-interactive (questions shown as they are, so 2FA +// works). x/crypto tries each method name once, so all keys go into one +// publickey method. +func (d *dialer) authMethods(ctx context.Context, ep Endpoint, prompt func(func() error) error) []ssh.AuthMethod { + methods := []ssh.AuthMethod{ssh.PublicKeysCallback(func() ([]ssh.Signer, error) { + return d.signers(ctx, ep, prompt), nil + })} + p := d.opts.Prompter + storedUsed := false // the handshake runs auth sequentially + if ep.Password != "" || p != nil { + methods = append(methods, ssh.PasswordCallback(func() (string, error) { + if ep.Password != "" && !storedUsed { + storedUsed = true + return ep.Password, nil + } + if p == nil { + return "", errors.New("password rejected") + } + var pw string + err := prompt(func() error { + var err error + pw, err = p.Password(ctx, ep) + return err + }) + return pw, err + })) + methods = append(methods, ssh.KeyboardInteractive(func(name, instruction string, qs []string, echo []bool) ([]string, error) { + if len(qs) == 0 { + return nil, nil + } + // A lone hidden question is the server's password prompt. + if ep.Password != "" && !storedUsed && len(qs) == 1 && !echo[0] { + storedUsed = true + return []string{ep.Password}, nil + } + if p == nil { + return nil, errors.New("keyboard-interactive: no way to ask the user") + } + instr := strings.TrimSpace(strings.TrimSpace(name) + "\n" + strings.TrimSpace(instruction)) + var answers []string + err := prompt(func() error { + var err error + answers, err = p.KeyboardInteractive(ctx, ep, instr, qs, echo) + return err + }) + if err == nil && len(answers) != len(qs) { + err = fmt.Errorf("keyboard-interactive: %d answers for %d questions", len(answers), len(qs)) + } + return answers, err + })) + } + return methods +} + +func (d *dialer) signers(ctx context.Context, ep Endpoint, prompt func(func() error) error) []ssh.Signer { + var out []ssh.Signer + seen := map[string]bool{} + add := func(s ssh.Signer) { + if s == nil { + return + } + k := string(s.PublicKey().Marshal()) + if !seen[k] { + seen[k] = true + out = append(out, s) + } + } + agentKeys := d.agent.signers() + inAgent := make(map[string]ssh.Signer, len(agentKeys)) + for _, s := range agentKeys { + inAgent[string(s.PublicKey().Marshal())] = s + } + for _, p := range ep.IdentityFiles { + add(d.loadKey(ctx, p, inAgent, prompt)) + } + if !ep.IdentitiesOnly { + for _, s := range agentKeys { + add(s) + } + for _, p := range d.opts.DefaultIdentityFiles { + add(d.loadKey(ctx, p, inAgent, prompt)) + } + } + return out +} + +// loadKey reads a private key. An encrypted key whose public half is known +// (embedded in the OpenSSH format or in path.pub) becomes a lazySigner: the +// passphrase is asked only if the server accepts the key. A key already +// unlocked in the agent is used from there. +func (d *dialer) loadKey(ctx context.Context, path string, inAgent map[string]ssh.Signer, prompt func(func() error) error) ssh.Signer { + data, err := os.ReadFile(path) + if err != nil { + return nil + } + s, err := ssh.ParsePrivateKey(data) + if err == nil { + return s + } + var pm *ssh.PassphraseMissingError + if !errors.As(err, &pm) { + d.warnf("identity %s: %v", path, err) + return nil + } + pub := pm.PublicKey + if pub == nil { + if b, err := os.ReadFile(path + ".pub"); err == nil { + pub, _, _, _, _ = ssh.ParseAuthorizedKey(b) + } + } + if pub != nil { + if as := inAgent[string(pub.Marshal())]; as != nil { + return as + } + } + if d.opts.Prompter == nil { + return nil + } + ls := &lazySigner{pub: pub, path: path, pem: data, ask: func() ([]byte, error) { + var pass []byte + err := prompt(func() error { + var err error + pass, err = d.opts.Prompter.Passphrase(ctx, path) + return err + }) + return pass, err + }} + if pub == nil { + // Without the public half the key cannot be offered lazily. + if _, err := ls.load(); err != nil { + d.warnf("identity %s: %v", path, err) + return nil + } + ls.pub = ls.s.PublicKey() + } + return ls +} + +// lazySigner decrypts a passphrase-protected key on first Sign. +type lazySigner struct { + pub ssh.PublicKey + path string + pem []byte + ask func() ([]byte, error) + + once sync.Once + s ssh.AlgorithmSigner + err error +} + +const passphraseAttempts = 3 + +func (l *lazySigner) load() (ssh.AlgorithmSigner, error) { + l.once.Do(func() { + for i := 0; i < passphraseAttempts; i++ { + pass, err := l.ask() + if err != nil { + l.err = err + return + } + s, err := ssh.ParsePrivateKeyWithPassphrase(l.pem, pass) + clear(pass) + if err != nil { + l.err = fmt.Errorf("identity %s: %w", l.path, err) + continue + } + as, ok := s.(ssh.AlgorithmSigner) + if !ok { + l.err = fmt.Errorf("identity %s: unsupported key type", l.path) + return + } + l.s, l.err = as, nil + return + } + }) + return l.s, l.err +} + +func (l *lazySigner) PublicKey() ssh.PublicKey { return l.pub } + +func (l *lazySigner) Sign(r io.Reader, data []byte) (*ssh.Signature, error) { + s, err := l.load() + if err != nil { + return nil, err + } + return s.Sign(r, data) +} + +func (l *lazySigner) SignWithAlgorithm(r io.Reader, data []byte, algo string) (*ssh.Signature, error) { + s, err := l.load() + if err != nil { + return nil, err + } + return s.SignWithAlgorithm(r, data, algo) +} diff --git a/internal/ssh/conn/dial.go b/internal/ssh/conn/dial.go new file mode 100644 index 0000000..13cc0a5 --- /dev/null +++ b/internal/ssh/conn/dial.go @@ -0,0 +1,235 @@ +package conn + +import ( + "context" + "errors" + "fmt" + "net" + "os" + "path/filepath" + "sync" + "sync/atomic" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" +) + +// DefaultHandshakeTimeout bounds TCP connect + kex + auth + SFTP init. +const DefaultHandshakeTimeout = 20 * time.Second + +// ErrHandshakeTimeout: the server accepted TCP but did not finish the +// handshake in time (N-P1-3). +var ErrHandshakeTimeout = errors.New("ssh handshake timed out") + +// DialOptions configures how connections are established. +type DialOptions struct { + Prompter Prompter + // HandshakeTimeout covers the whole path TCP + kex + auth + SFTP init, + // excluding time spent waiting for the Prompter. Default 20s. + HandshakeTimeout time.Duration + // Home is the home directory for the default known_hosts and identity + // files ("" = os.UserHomeDir()). + Home string + // KnownHostsFiles are read in order. nil means Home/.ssh/known_hosts and + // /etc/ssh/ssh_known_hosts. + KnownHostsFiles []string + // KnownHostsWrite receives AcceptAndSave lines. "" means the first of + // KnownHostsFiles (the default user file). Set to "-" for memory only. + KnownHostsWrite string + // AgentSocket is the ssh-agent socket. "" means $SSH_AUTH_SOCK; "-" + // disables the agent. + AgentSocket string + // DefaultIdentityFiles are tried when the endpoint does not set + // IdentitiesOnly. nil means Home/.ssh/id_{ed25519,ecdsa,rsa}. + DefaultIdentityFiles []string + // Warn receives non-fatal problems (host key kept in memory only, + // unreadable identity file). May be nil. + Warn func(msg string) +} + +func (o DialOptions) withDefaults() DialOptions { + if o.HandshakeTimeout <= 0 { + o.HandshakeTimeout = DefaultHandshakeTimeout + } + if o.Home == "" { + o.Home, _ = os.UserHomeDir() + } + ssh := filepath.Join(o.Home, ".ssh") + if o.KnownHostsFiles == nil { + o.KnownHostsFiles = []string{filepath.Join(ssh, "known_hosts"), "/etc/ssh/ssh_known_hosts"} + } + switch o.KnownHostsWrite { + case "": + if len(o.KnownHostsFiles) > 0 { + o.KnownHostsWrite = o.KnownHostsFiles[0] + } + case "-": + o.KnownHostsWrite = "" + } + switch o.AgentSocket { + case "": + o.AgentSocket = os.Getenv("SSH_AUTH_SOCK") + case "-": + o.AgentSocket = "" + } + if o.DefaultIdentityFiles == nil { + for _, n := range []string{"id_ed25519", "id_ecdsa", "id_rsa"} { + o.DefaultIdentityFiles = append(o.DefaultIdentityFiles, filepath.Join(ssh, n)) + } + } + return o +} + +// dialer establishes connections. One per Pool (i.e. per process): it owns +// the shared agent connection and the session-trusted host keys. +type dialer struct { + opts DialOptions + hosts *knownHosts + agent *agentConn + dials atomic.Int64 // successful TCP connects, for tests +} + +func newDialer(o DialOptions) *dialer { + o = o.withDefaults() + return &dialer{ + opts: o, + hosts: newKnownHosts(o.KnownHostsFiles, o.KnownHostsWrite, o.Warn), + agent: &agentConn{sock: o.AgentSocket}, + } +} + +func (d *dialer) close() { d.agent.close() } + +func (d *dialer) warnf(format string, args ...any) { + if d.opts.Warn != nil { + d.opts.Warn(fmt.Sprintf(format, args...)) + } +} + +// link is one established generation of a connection. +type link struct { + ssh *ssh.Client + sftp *sftp.Client + id HostIdentity + serverVersion string +} + +func (l *link) close() { + l.sftp.Close() + l.ssh.Close() +} + +// deadlineGate applies the handshake deadline to the raw connection and +// pauses it while the Prompter waits for the user. +type deadlineGate struct { + nc net.Conn + timeout time.Duration + mu sync.Mutex + done bool // handshake finished: never touch deadlines again +} + +func (g *deadlineGate) arm() { + g.mu.Lock() + defer g.mu.Unlock() + if !g.done { + g.nc.SetDeadline(time.Now().Add(g.timeout)) + } +} + +func (g *deadlineGate) finish() { + g.mu.Lock() + defer g.mu.Unlock() + g.done = true + g.nc.SetDeadline(time.Time{}) +} + +func (g *deadlineGate) prompt(fn func() error) error { + g.mu.Lock() + if !g.done { + g.nc.SetDeadline(time.Time{}) + } + g.mu.Unlock() + defer g.arm() + return fn() +} + +// sftpOptions: concurrent reads/writes so a transfer is not one packet per +// RTT (N-P1-6). +var sftpOptions = []sftp.ClientOption{ + sftp.UseConcurrentWrites(true), + sftp.UseConcurrentReads(true), + sftp.MaxConcurrentRequestsPerFile(64), +} + +// dial connects, verifies the host key, authenticates and starts SFTP. +// Cancelling ctx closes the socket at once; if the handshake still +// completes, the late client is closed here, never leaked (N-P1-3). +func (d *dialer) dial(ctx context.Context, ep Endpoint) (*link, error) { + timeout := d.opts.HandshakeTimeout + tcpTimeout := timeout + if ep.ConnectTimeout > 0 && ep.ConnectTimeout < tcpTimeout { + tcpTimeout = ep.ConnectTimeout + } + addr := ep.Addr() + nd := net.Dialer{Timeout: tcpTimeout} + nc, err := nd.DialContext(ctx, "tcp", addr) + if err != nil { + if ctx.Err() != nil { + return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err()) + } + return nil, fmt.Errorf("connect %s: %w", ep.Label(), err) + } + d.dials.Add(1) + gate := &deadlineGate{nc: nc, timeout: timeout} + gate.arm() + stop := context.AfterFunc(ctx, func() { nc.Close() }) + + var idMu sync.Mutex + var id HostIdentity + onKey := func(h HostIdentity) { + idMu.Lock() + defer idMu.Unlock() + if id.KeyType == "" { + id = h + } + } + cfg := &ssh.ClientConfig{ + User: ep.User, + Auth: d.authMethods(ctx, ep, gate.prompt), + HostKeyCallback: d.hosts.callback(ctx, ep, d.opts.Prompter, gate.prompt, onKey), + HostKeyAlgorithms: d.hosts.algorithms(addr), + } + fail := func(err error) (*link, error) { + stop() + nc.Close() + if ctx.Err() != nil { + return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err()) + } + if errors.Is(err, os.ErrDeadlineExceeded) { + return nil, fmt.Errorf("connect %s: %w after %v", ep.Label(), ErrHandshakeTimeout, timeout) + } + return nil, fmt.Errorf("connect %s: %w", ep.Label(), err) + } + sc, chans, reqs, err := ssh.NewClientConn(nc, addr, cfg) + if err != nil { + return fail(err) + } + client := ssh.NewClient(sc, chans, reqs) + sc2, err := sftp.NewClient(client, sftpOptions...) + if err != nil { + client.Close() + return fail(fmt.Errorf("sftp: %w", err)) + } + l := &link{ssh: client, sftp: sc2, serverVersion: string(client.ServerVersion())} + if !stop() { + // ctx fired while we were finishing: the caller is gone. + l.close() + return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err()) + } + gate.finish() + idMu.Lock() + l.id = id + idMu.Unlock() + return l, nil +} diff --git a/internal/ssh/conn/dial_test.go b/internal/ssh/conn/dial_test.go new file mode 100644 index 0000000..08c89d5 --- /dev/null +++ b/internal/ssh/conn/dial_test.go @@ -0,0 +1,452 @@ +package conn + +import ( + "bytes" + "context" + "crypto/rsa" + "errors" + "math/big" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "golang.org/x/crypto/ssh" + + "vcom/internal/testutil/sshtest" +) + +// N-P1-3: the server accepts TCP and then goes silent; the dial must fail +// within HandshakeTimeout (+1s slack), not hang. +func TestHandshakeTimeout(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := sshtest.NewProxy(t, srv.Addr) + px.Freeze(true) + const timeout = 300 * time.Millisecond + d := e.dialer(DialOptions{HandshakeTimeout: timeout}) + start := time.Now() + l, err := d.dial(context.Background(), endpointFor(px.Addr, srv.Password)) + el := time.Since(start) + if err == nil { + l.close() + t.Fatal("dial through a frozen proxy succeeded") + } + if !errors.Is(err, ErrHandshakeTimeout) { + t.Errorf("err = %v, want ErrHandshakeTimeout", err) + } + if el > timeout+time.Second { + t.Errorf("dial took %v, want <= %v", el, timeout+time.Second) + } + px.Freeze(false) + }) +} + +// N-P1-3: cancelling ctx mid-handshake returns at once; once the link +// unfreezes nothing is left behind (no client, no goroutines). +func TestDialCancelClosesLateClient(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := sshtest.NewProxy(t, srv.Addr) + px.Freeze(true) + d := e.dialer(DialOptions{HandshakeTimeout: 10 * time.Second}) + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(100*time.Millisecond, cancel) + start := time.Now() + l, err := d.dial(ctx, endpointFor(px.Addr, srv.Password)) + if err == nil { + l.close() + t.Fatal("cancelled dial succeeded") + } + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } + if el := time.Since(start); el > time.Second { + t.Errorf("cancel took %v", el) + } + px.Freeze(false) + // The proxy forwards the buffered handshake now; the server must see + // the client gone and drop the connection. + time.Sleep(100 * time.Millisecond) + }) +} + +// A prompt answered after the caller gave up must not produce a live client. +func TestDialCancelDuringPrompt(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := sshtest.Start(t, sshtest.Options{}) + ctx, cancel := context.WithCancel(context.Background()) + p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { + cancel() + time.Sleep(50 * time.Millisecond) + return AcceptOnce, nil // ignores ctx on purpose + }} + d := e.dialer(DialOptions{Prompter: p}) + l, err := d.dial(ctx, endpointFor(srv.Addr, srv.Password)) + if err == nil { + l.close() + t.Fatal("dial succeeded after cancel") + } + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v", err) + } + }) +} + +// The deadline is paused while the Prompter waits for the user. +func TestHandshakeDeadlinePausedDuringPrompt(t *testing.T) { + e := newEnv(t) + srv := sshtest.Start(t, sshtest.Options{}) + p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { + time.Sleep(400 * time.Millisecond) + return AcceptOnce, nil + }} + d := e.dialer(DialOptions{Prompter: p, HandshakeTimeout: 200 * time.Millisecond}) + l, err := d.dial(context.Background(), endpointFor(srv.Addr, srv.Password)) + if err != nil { + t.Fatalf("slow user answer must not time out the handshake: %v", err) + } + l.close() +} + +// Ported from the testbed (B9), N-P1-4: known_hosts has only the ed25519 +// key, the server offers ed25519+ECDSA; Go would pick ECDSA and raise a +// false "host key changed". +func TestHostKeyAlgoMismatch(t *testing.T) { + e := newEnv(t) + ed, ec := sshtest.GenKeys(t) + srv := sshtest.Start(t, sshtest.Options{HostKeys: []ssh.Signer{ec, ed}}) + e.trust(srv.Addr, ed.PublicKey()) + d := e.dialer(DialOptions{}) + l, err := d.dial(context.Background(), endpointFor(srv.Addr, srv.Password)) + if err != nil { + t.Fatalf("connect with a valid known ed25519 key: %v", err) + } + defer l.close() + if want := IdentityOf(ed.PublicKey()); l.id != want { + t.Errorf("identity = %+v, want %+v", l.id, want) + } + if got := d.hosts.algorithms(srv.Addr); len(got) != 1 || got[0] != ssh.KeyAlgoED25519 { + t.Errorf("algorithms = %v", got) + } +} + +func TestHostKeyAlgorithmsRSA(t *testing.T) { + e := newEnv(t) + _, ec := sshtest.GenKeys(t) + rsaPub, err := ssh.ParsePublicKey(testRSAPublicKeyWire(t)) + if err != nil { + t.Fatal(err) + } + e.trust("[h]:2222", rsaPub, ec.PublicKey()) + d := e.dialer(DialOptions{}) + got := d.hosts.algorithms("h:2222") + want := []string{ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256, ssh.KeyAlgoRSA, ssh.KeyAlgoECDSA256} + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Errorf("algorithms = %v, want %v", got, want) + } + if got := d.hosts.algorithms("other:22"); got != nil { + t.Errorf("unknown host algorithms = %v, want nil", got) + } +} + +func TestHostKeyChangedRejected(t *testing.T) { + e := newEnv(t) + ed, _ := sshtest.GenKeys(t) + stale, _ := sshtest.GenKeys(t) + srv := sshtest.Start(t, sshtest.Options{HostKeys: []ssh.Signer{ed}}) + e.trust(srv.Addr, stale.PublicKey()) + before, _ := os.ReadFile(e.kh) + + // No prompter: refused. + d := e.dialer(DialOptions{}) + _, err := d.dial(context.Background(), endpointFor(srv.Addr, srv.Password)) + if !errors.Is(err, ErrHostKeyChanged) { + t.Fatalf("err = %v, want ErrHostKeyChanged", err) + } + var hke *HostKeyError + if !errors.As(err, &hke) || !hke.Changed || len(hke.Known) != 1 || hke.Known[0] != IdentityOf(stale.PublicKey()) { + t.Errorf("HostKeyError = %+v", hke) + } + + // Prompter told about the change, rejects. + p := &fakePrompter{} + d = e.dialer(DialOptions{Prompter: p}) + _, err = d.dial(context.Background(), endpointFor(srv.Addr, srv.Password)) + if !errors.Is(err, ErrHostKeyChanged) { + t.Fatalf("err = %v, want ErrHostKeyChanged", err) + } + if len(p.hostKeys) != 1 || !p.hostKeys[0].changed { + t.Errorf("prompter calls = %+v, want one with changed=true", p.hostKeys) + } + after, _ := os.ReadFile(e.kh) + if !bytes.Equal(before, after) { + t.Error("known_hosts modified on a rejected changed key") + } +} + +// N-P2-14: an unknown host goes to the Prompter instead of silent TOFU. +func TestUnknownHostAsksPrompter(t *testing.T) { + e := newEnv(t) + srv := sshtest.Start(t, sshtest.Options{}) + ep := endpointFor(srv.Addr, srv.Password) + + t.Run("Reject", func(t *testing.T) { + p := &fakePrompter{} + _, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep) + if !errors.Is(err, ErrHostKeyRejected) { + t.Fatalf("err = %v, want ErrHostKeyRejected", err) + } + if n, _, _, _ := p.counts(); n != 1 || p.hostKeys[0].changed || len(p.hostKeys[0].known) != 0 { + t.Errorf("prompter calls = %+v", p.hostKeys) + } + if _, err := os.Stat(e.kh); !os.IsNotExist(err) { + t.Error("known_hosts written on Reject") + } + }) + + t.Run("NoPrompter", func(t *testing.T) { + _, err := e.dialer(DialOptions{}).dial(context.Background(), ep) + if !errors.Is(err, ErrHostKeyRejected) { + t.Fatalf("err = %v, want ErrHostKeyRejected", err) + } + }) + + t.Run("AcceptOnce", func(t *testing.T) { + p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { return AcceptOnce, nil }} + d := e.dialer(DialOptions{Prompter: p}) + for i := 0; i < 2; i++ { + l, err := d.dial(context.Background(), ep) + if err != nil { + t.Fatal(err) + } + l.close() + } + if n, _, _, _ := p.counts(); n != 1 { + t.Errorf("asked %d times, want once per process", n) + } + if _, err := os.Stat(e.kh); !os.IsNotExist(err) { + t.Error("known_hosts written on AcceptOnce") + } + }) + + t.Run("AcceptAndSave", func(t *testing.T) { + p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { return AcceptAndSave, nil }} + l, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep) + if err != nil { + t.Fatal(err) + } + l.close() + data, err := os.ReadFile(e.kh) + if err != nil || !strings.Contains(string(data), "127.0.0.1") { + t.Fatalf("known_hosts = %q, %v", data, err) + } + if fi, _ := os.Stat(e.kh); fi.Mode().Perm() != 0o600 { + t.Errorf("known_hosts mode %v", fi.Mode().Perm()) + } + // A fresh process (dialer) trusts it without asking. + l, err = e.dialer(DialOptions{}).dial(context.Background(), ep) + if err != nil { + t.Fatalf("saved key not trusted: %v", err) + } + l.close() + }) + + t.Run("MemoryOnlyWarns", func(t *testing.T) { + os.Remove(e.kh) + var warns []string + var mu sync.Mutex + p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { return AcceptAndSave, nil }} + d := e.dialer(DialOptions{Prompter: p, KnownHostsWrite: "-", Warn: func(s string) { + mu.Lock() + warns = append(warns, s) + mu.Unlock() + }}) + l, err := d.dial(context.Background(), ep) + if err != nil { + t.Fatal(err) + } + l.close() + if len(warns) != 1 || !strings.Contains(warns[0], "session only") { + t.Errorf("warnings = %q", warns) + } + if _, err := os.Stat(e.kh); !os.IsNotExist(err) { + t.Error("known_hosts written in memory-only mode") + } + }) +} + +// N-P2-2: a rejected IdentityFile used to end authentication; the agent +// must still be tried. +func TestAuthFallbackToAgentAfterIdentityRejected(t *testing.T) { + e := newEnv(t) + agentPriv, agentSigner := newKey(t) + otherPriv, _ := newKey(t) + idPath := filepath.Join(e.home, ".ssh", "id_other") + writeKey(t, idPath, otherPriv, "") + ag := startAgent(t, agentPriv) + srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{agentSigner.PublicKey()}}) + d := e.dialer(DialOptions{AgentSocket: ag.sock}) + ep := endpointFor(srv.Addr, "") + ep.IdentityFiles = []string{idPath, filepath.Join(e.home, ".ssh", "missing")} + l, err := d.dial(context.Background(), ep) + if err != nil { + t.Fatalf("agent key not tried after the identity file was rejected: %v", err) + } + l.close() + + // IdentitiesOnly: the agent key is not offered. + ep.IdentitiesOnly = true + if _, err := d.dial(context.Background(), ep); err == nil { + t.Fatal("IdentitiesOnly must not offer unrelated agent keys") + } +} + +func TestAuthDefaultIdentityAndPasswordFallback(t *testing.T) { + e := newEnv(t) + priv, signer := newKey(t) + writeKey(t, filepath.Join(e.home, ".ssh", "id_ed25519"), priv, "") + srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{signer.PublicKey()}}) + l, err := e.dialer(DialOptions{}).dial(context.Background(), endpointFor(srv.Addr, "")) + if err != nil { + t.Fatalf("default identity: %v", err) + } + l.close() + + // Password server: keys are offered and rejected, the prompter's password works. + srv2 := e.startTrusted(sshtest.Options{Password: "s3cret"}) + p := &fakePrompter{password: func(context.Context) (string, error) { return "s3cret", nil }} + l, err = e.dialer(DialOptions{Prompter: p}).dial(context.Background(), endpointFor(srv2.Addr, "")) + if err != nil { + t.Fatalf("prompted password: %v", err) + } + l.close() + if _, pw, _, _ := p.counts(); pw != 1 { + t.Errorf("password asked %d times", pw) + } +} + +// N-P2-2: keyboard-interactive questions reach the Prompter as they are +// (the old code answered every question, 2FA included, with the password). +func TestKeyboardInteractiveUsesPrompter(t *testing.T) { + e := newEnv(t) + qs := []string{"Password: ", "Verification code: "} + echo := []bool{false, true} + addr, hostKey := kiServer(t, qs, echo, []string{"pw", "123456"}) + e.trust(addr, hostKey) + p := &fakePrompter{ki: func([]string) ([]string, error) { return []string{"pw", "123456"}, nil }} + ep := endpointFor(addr, "pw") // the stored password must not answer the 2FA question + l, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep) + if err != nil { + t.Fatalf("keyboard-interactive: %v", err) + } + l.close() + if len(p.kiCalls) != 1 || strings.Join(p.kiCalls[0], "|") != strings.Join(qs, "|") || + p.kiEcho[0][0] || !p.kiEcho[0][1] { + t.Errorf("prompter saw %q echo %v", p.kiCalls, p.kiEcho) + } + if !strings.Contains(p.kiInstr[0], "Two factors please") { + t.Errorf("instruction = %q", p.kiInstr[0]) + } + + // A lone hidden question is answered with the stored password. + addr2, hostKey2 := kiServer(t, []string{"Password: "}, []bool{false}, []string{"pw"}) + e.trust(addr2, hostKey2) + p2 := &fakePrompter{} + l, err = e.dialer(DialOptions{Prompter: p2}).dial(context.Background(), endpointFor(addr2, "pw")) + if err != nil { + t.Fatalf("stored password via keyboard-interactive: %v", err) + } + l.close() + if _, _, ki, _ := p2.counts(); ki != 0 { + t.Errorf("prompter asked %d times", ki) + } +} + +// N-P2-1: one agent connection per process, not one per connect. +func TestAgentConnectionShared(t *testing.T) { + e := newEnv(t) + priv, signer := newKey(t) + ag := startAgent(t, priv) + srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{signer.PublicKey()}}) + d := newDialer(DialOptions{Home: e.home, AgentSocket: ag.sock, KnownHostsFiles: []string{e.kh}}) + ep := endpointFor(srv.Addr, "") + var wg sync.WaitGroup + errs := make(chan error, 6) + for i := 0; i < 6; i++ { + wg.Add(1) + go func() { + defer wg.Done() + l, err := d.dial(context.Background(), ep) + if err == nil { + l.close() + } + errs <- err + }() + } + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Fatal(err) + } + } + if n := ag.accepts.Load(); n != 1 { + t.Errorf("agent connections = %d, want 1", n) + } + d.close() + waitFor(t, 2*time.Second, "agent connection closed", func() bool { return ag.active.Load() == 0 }) +} + +// An encrypted key is decrypted only when the server accepts it. +func TestPassphraseAskedLazily(t *testing.T) { + e := newEnv(t) + accPriv, accSigner := newKey(t) + rejPriv, _ := newKey(t) + rej := filepath.Join(e.home, ".ssh", "id_rejected") + acc := filepath.Join(e.home, ".ssh", "id_accepted") + writeKey(t, rej, rejPriv, "one") + writeKey(t, acc, accPriv, "two") + srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{accSigner.PublicKey()}}) + tries := 0 + p := &fakePrompter{passphrase: func(path string) ([]byte, error) { + tries++ + if tries == 1 { + return []byte("wrong"), nil + } + return []byte("two"), nil + }} + ep := endpointFor(srv.Addr, "") + ep.IdentityFiles = []string{rej, acc} + l, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep) + if err != nil { + t.Fatalf("encrypted key: %v", err) + } + l.close() + for _, ph := range p.phrases { + if ph != acc { + t.Errorf("passphrase asked for %s (server never accepted it)", ph) + } + } + if len(p.phrases) != 2 { + t.Errorf("passphrase asked %d times, want 2 (one wrong attempt)", len(p.phrases)) + } +} + +// testRSAPublicKeyWire returns an RSA public key in wire format. Only the +// type matters here, so the modulus is arbitrary (no slow key generation). +func testRSAPublicKeyWire(t *testing.T) []byte { + t.Helper() + n := new(big.Int).Lsh(big.NewInt(1), 2047) + n.Add(n, big.NewInt(12345)) + pub, err := ssh.NewPublicKey(&rsa.PublicKey{N: n, E: 65537}) + if err != nil { + t.Fatal(err) + } + return pub.Marshal() +} diff --git a/internal/ssh/conn/helpers_test.go b/internal/ssh/conn/helpers_test.go new file mode 100644 index 0000000..91c4029 --- /dev/null +++ b/internal/ssh/conn/helpers_test.go @@ -0,0 +1,384 @@ +package conn + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "encoding/pem" + "errors" + "net" + "os" + "path/filepath" + "runtime" + "strconv" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/agent" + "golang.org/x/crypto/ssh/knownhosts" + + "vcom/internal/testutil/sshtest" +) + +// noLeak runs fn as a subtest (so its Cleanups run) and then checks that the +// goroutine count returns to the baseline within ±2. +func noLeak(t *testing.T, fn func(t *testing.T)) { + t.Helper() + runtime.GC() + base := runtime.NumGoroutine() + t.Run("body", fn) + deadline := time.Now().Add(5 * time.Second) + var n int + for time.Now().Before(deadline) { + n = runtime.NumGoroutine() + if n <= base+2 { + return + } + time.Sleep(20 * time.Millisecond) + } + buf := make([]byte, 1<<20) + buf = buf[:runtime.Stack(buf, true)] + t.Errorf("goroutines: base=%d after cleanup=%d\n%s", base, n, buf) +} + +// waitFor polls cond until it holds or d elapses. +func waitFor(t *testing.T, d time.Duration, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(d) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out after %v waiting for %s", d, what) + } + time.Sleep(5 * time.Millisecond) + } +} + +// env is an isolated HOME with helpers to dial the in-process server. +type env struct { + t *testing.T + home string + kh string // ~/.ssh/known_hosts +} + +func newEnv(t *testing.T) *env { + t.Helper() + home := sshtest.IsolatedHome(t) + return &env{t: t, home: home, kh: filepath.Join(home, ".ssh", "known_hosts")} +} + +// dialer returns a dialer rooted at the env HOME; the agent is disabled +// unless o.AgentSocket is set. +func (e *env) dialer(o DialOptions) *dialer { + if o.Home == "" { + o.Home = e.home + } + if o.AgentSocket == "" { + o.AgentSocket = "-" + } + if o.KnownHostsFiles == nil { + o.KnownHostsFiles = []string{e.kh} + } + d := newDialer(o) + e.t.Cleanup(d.close) + return d +} + +// trust writes known_hosts lines for addr. +func (e *env) trust(addr string, keys ...ssh.PublicKey) { + e.t.Helper() + var data []byte + for _, k := range keys { + data = append(data, knownhosts.Line([]string{knownhosts.Normalize(addr)}, k)+"\n"...) + } + if err := os.WriteFile(e.kh, data, 0o600); err != nil { + e.t.Fatal(err) + } +} + +func endpointFor(addr, password string) Endpoint { + host, port, _ := net.SplitHostPort(addr) + p, _ := strconv.Atoi(port) + return Endpoint{Alias: "test", User: "u", Host: host, Port: p, Password: password} +} + +// startTrusted starts a server whose host keys are in known_hosts. +func (e *env) startTrusted(o sshtest.Options) *sshtest.Server { + srv := sshtest.Start(e.t, o) + var pubs []ssh.PublicKey + for _, k := range srv.HostKeys { + pubs = append(pubs, k.PublicKey()) + } + e.trust(srv.Addr, pubs...) + return srv +} + +func (l *link) closeOnCleanup(t *testing.T) *link { + t.Cleanup(l.close) + return l +} + +// fakePrompter records calls and answers with the configured functions. +type fakePrompter struct { + mu sync.Mutex + hostKeys []hostKeyCall + passwords int + kiCalls [][]string + kiEcho [][]bool + kiInstr []string + phrases []string + + hostKey func(ctx context.Context, changed bool) (HostKeyDecision, error) + password func(ctx context.Context) (string, error) + ki func(qs []string) ([]string, error) + passphrase func(path string) ([]byte, error) +} + +type hostKeyCall struct { + id HostIdentity + known []HostIdentity + changed bool +} + +func (p *fakePrompter) HostKey(ctx context.Context, ep Endpoint, id HostIdentity, known []HostIdentity, changed bool) (HostKeyDecision, error) { + p.mu.Lock() + p.hostKeys = append(p.hostKeys, hostKeyCall{id, known, changed}) + p.mu.Unlock() + if p.hostKey == nil { + return Reject, nil + } + return p.hostKey(ctx, changed) +} + +func (p *fakePrompter) Password(ctx context.Context, ep Endpoint) (string, error) { + p.mu.Lock() + p.passwords++ + p.mu.Unlock() + if p.password == nil { + return "", errors.New("no password") + } + return p.password(ctx) +} + +func (p *fakePrompter) KeyboardInteractive(ctx context.Context, ep Endpoint, instr string, qs []string, echo []bool) ([]string, error) { + p.mu.Lock() + p.kiCalls = append(p.kiCalls, append([]string(nil), qs...)) + p.kiEcho = append(p.kiEcho, append([]bool(nil), echo...)) + p.kiInstr = append(p.kiInstr, instr) + p.mu.Unlock() + if p.ki == nil { + return nil, errors.New("no answers") + } + return p.ki(qs) +} + +func (p *fakePrompter) Passphrase(ctx context.Context, path string) ([]byte, error) { + p.mu.Lock() + p.phrases = append(p.phrases, path) + p.mu.Unlock() + if p.passphrase == nil { + return nil, errors.New("no passphrase") + } + return p.passphrase(path) +} + +func (p *fakePrompter) counts() (hostKeys, passwords, ki, phrases int) { + p.mu.Lock() + defer p.mu.Unlock() + return len(p.hostKeys), p.passwords, len(p.kiCalls), len(p.phrases) +} + +// newKey returns a fresh ed25519 private key and its signer. +func newKey(t *testing.T) (ed25519.PrivateKey, ssh.Signer) { + t.Helper() + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + s, err := ssh.NewSignerFromKey(priv) + if err != nil { + t.Fatal(err) + } + return priv, s +} + +// writeKey stores priv in OpenSSH format (encrypted when passphrase != ""). +func writeKey(t *testing.T, path string, priv ed25519.PrivateKey, passphrase string) { + t.Helper() + var blk *pem.Block + var err error + if passphrase == "" { + blk, err = ssh.MarshalPrivateKey(priv, "test") + } else { + blk, err = ssh.MarshalPrivateKeyWithPassphrase(priv, "test", []byte(passphrase)) + } + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, pem.EncodeToMemory(blk), 0o600); err != nil { + t.Fatal(err) + } +} + +// fakeAgent serves an in-memory keyring on a unix socket. +type fakeAgent struct { + sock string + accepts atomic.Int32 + active atomic.Int32 +} + +func startAgent(t *testing.T, keys ...ed25519.PrivateKey) *fakeAgent { + t.Helper() + kr := agent.NewKeyring() + for _, k := range keys { + if err := kr.Add(agent.AddedKey{PrivateKey: k}); err != nil { + t.Fatal(err) + } + } + dir, err := os.MkdirTemp("", "agent") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + a := &fakeAgent{sock: filepath.Join(dir, "s")} + ln, err := net.Listen("unix", a.sock) + if err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + var mu sync.Mutex + var conns []net.Conn + wg.Add(1) + go func() { + defer wg.Done() + for { + c, err := ln.Accept() + if err != nil { + return + } + a.accepts.Add(1) + a.active.Add(1) + mu.Lock() + conns = append(conns, c) + mu.Unlock() + wg.Add(1) + go func() { + defer wg.Done() + defer a.active.Add(-1) + agent.ServeAgent(kr, c) + c.Close() + }() + } + }() + t.Cleanup(func() { + ln.Close() + mu.Lock() + for _, c := range conns { + c.Close() + } + mu.Unlock() + wg.Wait() + }) + return a +} + +// kiServer is a minimal SSH server that only allows keyboard-interactive +// auth with the given questions; answers must equal want. It serves SFTP so +// the full dial path succeeds. +func kiServer(t *testing.T, questions []string, echo []bool, want []string) (string, ssh.PublicKey) { + t.Helper() + ed, _ := sshtest.GenKeys(t) + cfg := &ssh.ServerConfig{ + KeyboardInteractiveCallback: func(_ ssh.ConnMetadata, ch ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) { + ans, err := ch("vcom-test", "Two factors please", questions, echo) + if err != nil { + return nil, err + } + if len(ans) != len(want) { + return nil, errors.New("wrong answer count") + } + for i := range want { + if ans[i] != want[i] { + return nil, errors.New("wrong answer") + } + } + return nil, nil + }, + } + cfg.AddHostKey(ed) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + var mu sync.Mutex + var conns []net.Conn + wg.Add(1) + go func() { + defer wg.Done() + for { + nc, err := ln.Accept() + if err != nil { + return + } + mu.Lock() + conns = append(conns, nc) + mu.Unlock() + wg.Add(1) + go func() { + defer wg.Done() + defer nc.Close() + sc, chans, reqs, err := ssh.NewServerConn(nc, cfg) + if err != nil { + return + } + defer sc.Close() + go ssh.DiscardRequests(reqs) + for nch := range chans { + ch, creqs, err := nch.Accept() + if err != nil { + continue + } + wg.Add(1) + go func() { + defer wg.Done() + defer ch.Close() + for req := range creqs { + if req.Type == "subsystem" { + req.Reply(true, nil) + srv, err := sftp.NewServer(ch) + if err != nil { + return + } + go func() { + for range creqs { + } + }() + srv.Serve() + srv.Close() + return + } + req.Reply(false, nil) + } + }() + } + }() + } + }() + t.Cleanup(func() { + ln.Close() + mu.Lock() + for _, c := range conns { + c.Close() + } + mu.Unlock() + wg.Wait() + }) + return ln.Addr().String(), ed.PublicKey() +} diff --git a/internal/ssh/conn/hostkey.go b/internal/ssh/conn/hostkey.go new file mode 100644 index 0000000..b931098 --- /dev/null +++ b/internal/ssh/conn/hostkey.go @@ -0,0 +1,272 @@ +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 + } + } +} diff --git a/internal/ssh/conn/owner_other.go b/internal/ssh/conn/owner_other.go new file mode 100644 index 0000000..1b2ac6d --- /dev/null +++ b/internal/ssh/conn/owner_other.go @@ -0,0 +1,5 @@ +//go:build !unix + +package conn + +func foreignOwner(string) bool { return false } diff --git a/internal/ssh/conn/owner_unix.go b/internal/ssh/conn/owner_unix.go new file mode 100644 index 0000000..0ecb125 --- /dev/null +++ b/internal/ssh/conn/owner_unix.go @@ -0,0 +1,23 @@ +//go:build unix + +package conn + +import ( + "os" + "path/filepath" + "syscall" +) + +// foreignOwner reports whether path (or, if it does not exist, its parent +// directory) belongs to a user other than the effective one, e.g. the +// invoking user's ~/.ssh while vcom runs under sudo. +func foreignOwner(path string) bool { + fi, err := os.Stat(path) + if err != nil { + if fi, err = os.Stat(filepath.Dir(path)); err != nil { + return false + } + } + st, ok := fi.Sys().(*syscall.Stat_t) + return ok && int(st.Uid) != os.Geteuid() +} diff --git a/internal/ssh/conn/prompter.go b/internal/ssh/conn/prompter.go new file mode 100644 index 0000000..6795c33 --- /dev/null +++ b/internal/ssh/conn/prompter.go @@ -0,0 +1,55 @@ +// Package conn owns SSH connections: dialing with a bounded handshake, +// host-key verification, authentication, keepalive, reconnect, remote exec +// and a reference-counted pool. Nothing outside the Pool closes a +// connection. +package conn + +import ( + "context" + "crypto/sha256" + "encoding/base64" + + "golang.org/x/crypto/ssh" + + "vcom/internal/ssh/sshconfig" +) + +// Endpoint is the resolved host to dial. +type Endpoint = sshconfig.Endpoint + +// HostIdentity identifies a server host key. +type HostIdentity struct { + KeyType string // e.g. "ssh-ed25519" + FingerprintSHA256 string // "SHA256:..." as printed by ssh-keygen -l +} + +// IdentityOf returns the identity of a public key. +func IdentityOf(k ssh.PublicKey) HostIdentity { + sum := sha256.Sum256(k.Marshal()) + return HostIdentity{ + KeyType: k.Type(), + FingerprintSHA256: "SHA256:" + base64.RawStdEncoding.EncodeToString(sum[:]), + } +} + +// HostKeyDecision is the answer to an unknown or changed host key. +type HostKeyDecision uint8 + +const ( + Reject HostKeyDecision = iota // refuse to connect + AcceptOnce // trust for this process only + AcceptAndSave // trust and append to known_hosts +) + +// Prompter asks the user. The UI implements it via jobs.Ask; every method +// must return promptly when ctx is cancelled. A nil Prompter rejects unknown +// host keys and offers no interactive authentication. +type Prompter interface { + // HostKey is called for a key that is not in known_hosts. changed is + // true when known_hosts has a different key of the same type (possible + // MITM); known lists the keys known_hosts has for the host. + HostKey(ctx context.Context, ep Endpoint, id HostIdentity, known []HostIdentity, changed bool) (HostKeyDecision, error) + Password(ctx context.Context, ep Endpoint) (string, error) + KeyboardInteractive(ctx context.Context, ep Endpoint, instruction string, questions []string, echo []bool) ([]string, error) + Passphrase(ctx context.Context, keyPath string) ([]byte, error) +} diff --git a/plans/rework/04-dev-log-B.md b/plans/rework/04-dev-log-B.md index c3b8ed0..e92edea 100644 --- a/plans/rework/04-dev-log-B.md +++ b/plans/rework/04-dev-log-B.md @@ -29,3 +29,34 @@ - `Endpoint` дополнен `Addr()` и `Label()`; `ProxyJump` разбирается (`[user@]host[:port]`, хопы разрешаются через тот же конфиг), но подключение через хопы — этап 8. `IdentityFile none` пропускается; токены `%h %d %u %r %%` раскрываются в `HostName`/`IdentityFile`. + +## 2B.2 `ssh/conn` Dialer + +- **Dialer не экспортируется.** Внутренний `dialer` (один на Pool, т.е. на процесс: держит общее соединение с + агентом и принятые на сессию host keys) настраивается через `DialOptions{Prompter, HandshakeTimeout, Home, + KnownHostsFiles, KnownHostsWrite, AgentSocket, DefaultIdentityFiles, Warn}`; `PoolOptions` встраивает + `DialOptions` (2B.4). Снаружи соединение получают только через `Pool.Acquire`. +- **Дедлайн handshake на паузе, пока ждём Prompter** (host key, пароль, KI, passphrase): иначе пользователь, + думающий дольше 20 с, получал бы таймаут. После ответа таймер взводится заново на полный `HandshakeTimeout`. + `ConnectTimeout` из ssh_config ограничивает только TCP connect (как в OpenSSH). +- **SFTP:** `sftp.NewClient(sshClient, UseConcurrentWrites, UseConcurrentReads, MaxConcurrentRequestsPerFile(64))` + вместо `NewClientPipe` — те же опции, меньше кода; ожидание VERSION идёт под тем же дедлайном. +- **Порядок ключей:** явные `IdentityFile` (если ключ уже есть в агенте — подпись агентом) → остальные ключи агента → + `~/.ssh/id_{ed25519,ecdsa,rsa}` (последние два шага — только без `IdentitiesOnly`). В дизайне агент стоял первым; + явный ключ первым ближе к OpenSSH и не съедает `MaxAuthTries` сервера ключами агента. Все ключи — в одном + методе `publickey` (x/crypto пробует каждое имя метода один раз; два `PublicKeys` подряд — второй игнорируется). +- **Зашифрованный ключ:** если известна публичная половина (встроена в формат OpenSSH или лежит в `.pub`), + passphrase спрашивается только когда сервер принял ключ (lazy signer), до 3 попыток. Отмена в Prompter + прерывает аутентификацию целиком (так устроен x/crypto: ошибка подписи = ошибка auth). +- **Пароль/KI:** пароль из hosts.dat используется один раз (метод `password` или одиночный скрытый вопрос KI); + всё остальное — через Prompter как есть (2FA). Без Prompter и без пароля эти методы не предлагаются. +- **Host key.** Неизвестный ключ без Prompter → отказ (`ErrHostKeyRejected`), а не молчаливый TOFU. Ключ другого + типа, чем записанные, — «неизвестный» (`changed=false`, `known` заполнен). Изменившийся ключ того же типа → + Prompter с `changed=true`; Reject → `*HostKeyError` (unwrap → `ErrHostKeyChanged`); AcceptOnce/AcceptAndSave для + изменившегося ключа → доверие только на сессию (строку в known_hosts не переписываем, это `ssh-keygen -R`). + Ошибка — тип `*HostKeyError{Host, Identity, Known, Changed}` для UI. +- **sudo / known_hosts:** если файл (или каталог, если файла нет) принадлежит не эффективному uid, либо запись не + удалась, либо `KnownHostsWrite: "-"`, ключ доверяется только в памяти и вызывается `Warn`. Чтение по умолчанию + ещё и из `/etc/ssh/ssh_known_hosts`. +- Тест `TestKeyboardInteractiveUsesPrompter` использует свой мини-сервер в `helpers_test.go` (у `sshtest` нет KI); + `sshtest` не трогал, чтобы не выходить из своей зоны. From 351970078f18e88c0d5ebb6a2bd8ccd561fc1677 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 23:37:01 +0300 Subject: [PATCH 3/4] feat(ssh): add Conn with keepalive, states, reconnect and exec (2B.3) Keepalive with a per-reply timeout marks a frozen link Lost and closes it so hung SFTP calls fail with ErrConnLost (N-P1-2). Reconnect installs a new generation in the same Conn. Exec takes a ctx (SIGKILL + close on cancel) and an output limit (N-P2-15, N-P1-7). Co-Authored-By: Claude Opus 5.5 --- internal/ssh/conn/conn.go | 360 ++++++++++++++++++++++++++++++ internal/ssh/conn/conn_test.go | 290 ++++++++++++++++++++++++ internal/ssh/conn/exec.go | 195 ++++++++++++++++ internal/ssh/conn/helpers_test.go | 17 ++ internal/ssh/conn/keepalive.go | 83 +++++++ plans/rework/04-dev-log-B.md | 23 ++ 6 files changed, 968 insertions(+) create mode 100644 internal/ssh/conn/conn.go create mode 100644 internal/ssh/conn/conn_test.go create mode 100644 internal/ssh/conn/exec.go create mode 100644 internal/ssh/conn/keepalive.go diff --git a/internal/ssh/conn/conn.go b/internal/ssh/conn/conn.go new file mode 100644 index 0000000..3edda48 --- /dev/null +++ b/internal/ssh/conn/conn.go @@ -0,0 +1,360 @@ +package conn + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "sync" + "sync/atomic" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" +) + +var ( + // ErrConnLost: the connection died (keepalive timeout, network cut, + // server gone). The operation may be retried after Reconnect. sftpfs maps + // it to vfs.ErrConnLost. + ErrConnLost = errors.New("connection lost") + // ErrClosed: the connection was closed by the pool. + ErrClosed = errors.New("connection closed") +) + +// State of a Conn. +type State uint32 + +const ( + Connecting State = iota + Ready + Lost + Closed +) + +func (s State) String() string { + switch s { + case Connecting: + return "connecting" + case Ready: + return "ready" + case Lost: + return "lost" + case Closed: + return "closed" + } + return fmt.Sprintf("State(%d)", uint32(s)) +} + +// Event reports a state change (ConnStateChanged). main forwards it to the +// UI with program.Send; it is called from connection goroutines and must not +// block. +type Event struct { + Key string // Endpoint.Key() + State State + Gen uint64 // generation the state refers to + Err error // why the connection was lost (Lost), nil otherwise +} + +// Defaults for keepalive (§3.4). +const ( + DefaultKeepaliveInterval = 15 * time.Second + DefaultKeepaliveTimeout = 10 * time.Second + DefaultKeepaliveMaxMiss = 2 +) + +// ConnOptions tune liveness detection of one connection. +type ConnOptions struct { + KeepaliveInterval time.Duration // default 15s, or Endpoint.ServerAliveInterval + KeepaliveTimeout time.Duration // per keepalive reply; default 10s + KeepaliveMaxMiss int // default 2, or Endpoint.ServerAliveCountMax + OnEvent func(Event) +} + +func (o ConnOptions) withDefaults(ep Endpoint) ConnOptions { + if o.KeepaliveInterval <= 0 { + o.KeepaliveInterval = ep.ServerAliveInterval + } + if o.KeepaliveInterval <= 0 { + o.KeepaliveInterval = DefaultKeepaliveInterval + } + if o.KeepaliveTimeout <= 0 { + o.KeepaliveTimeout = DefaultKeepaliveTimeout + } + if o.KeepaliveMaxMiss <= 0 { + o.KeepaliveMaxMiss = ep.ServerAliveCountMax + } + if o.KeepaliveMaxMiss <= 0 { + o.KeepaliveMaxMiss = DefaultKeepaliveMaxMiss + } + return o +} + +// ConnCaps are server capabilities detected at connect time. +type ConnCaps struct { + PosixRename bool // posix-rename@openssh.com: atomic Rename(Replace) + Fsync bool // fsync@openssh.com + StatVFS bool // statvfs@openssh.com + Hardlink bool // hardlink@openssh.com +} + +// Conn is one logical connection to an endpoint. Its fields are never reset: +// the current *sftp.Client sits in an atomic pointer and, once the +// connection dies, keeps returning errors instead of disappearing (N-P0-8). +// Reconnect installs a new generation in the same Conn, so leases stay +// valid. Only the Pool closes a Conn. +type Conn struct { + d *dialer + ep Endpoint + key string + opts ConnOptions + + state atomic.Uint32 + gen atomic.Uint64 + sftp atomic.Pointer[sftp.Client] + cur atomic.Pointer[generation] + + mu sync.Mutex // serializes state transitions + lostBy error + + reconnectMu sync.Mutex // one reconnect at a time + + execMu sync.Mutex + execKnown bool + execOK bool + + wg sync.WaitGroup // per-generation goroutines +} + +// generation is one live link plus its lifetime signal. +type generation struct { + *link + gen uint64 + caps ConnCaps + done chan struct{} // closed when the link has ended +} + +func newGeneration(l *link, gen uint64) *generation { + g := &generation{link: l, gen: gen, done: make(chan struct{})} + _, g.caps.PosixRename = l.sftp.HasExtension("posix-rename@openssh.com") + _, g.caps.Fsync = l.sftp.HasExtension("fsync@openssh.com") + _, g.caps.StatVFS = l.sftp.HasExtension("statvfs@openssh.com") + _, g.caps.Hardlink = l.sftp.HasExtension("hardlink@openssh.com") + return g +} + +// connect dials ep and returns a Ready Conn with keepalive running. +func (d *dialer) connect(ctx context.Context, ep Endpoint, o ConnOptions) (*Conn, error) { + c := &Conn{d: d, ep: ep, key: ep.Key(), opts: o.withDefaults(ep)} + c.state.Store(uint32(Connecting)) + l, err := d.dial(ctx, ep) + if err != nil { + c.state.Store(uint32(Closed)) + return nil, err + } + c.mu.Lock() + c.install(l) + c.mu.Unlock() + c.emit(Event{Key: c.key, State: Ready, Gen: c.gen.Load()}) + return c, nil +} + +// install makes l the current generation; c.mu is held. +func (c *Conn) install(l *link) { + gen := c.gen.Add(1) + g := newGeneration(l, gen) + c.cur.Store(g) + c.sftp.Store(l.sftp) + c.lostBy = nil + c.state.Store(uint32(Ready)) + c.wg.Add(2) + go func() { + defer c.wg.Done() + err := l.ssh.Wait() + close(g.done) + if err == nil { + err = io.EOF + } + c.lose(g, err) + }() + go func() { + defer c.wg.Done() + c.keepalive(g) + }() +} + +// lose marks generation g as Lost (if it is still current and Ready) and +// closes its SSH client, failing every pending request at once. +func (c *Conn) lose(g *generation, why error) { + c.mu.Lock() + if c.cur.Load() != g || c.State() != Ready { + c.mu.Unlock() + return + } + c.lostBy = fmt.Errorf("%w: %v", ErrConnLost, why) + c.state.Store(uint32(Lost)) + err := c.lostBy + c.mu.Unlock() + g.ssh.Close() + g.sftp.Close() + c.emit(Event{Key: c.key, State: Lost, Gen: g.gen, Err: err}) +} + +func (c *Conn) emit(e Event) { + if c.opts.OnEvent != nil { + c.opts.OnEvent(e) + } +} + +// State returns the current state. +func (c *Conn) State() State { return State(c.state.Load()) } + +// Gen is the generation number; it grows with every successful Reconnect. +func (c *Conn) Gen() uint64 { return c.gen.Load() } + +// Key is the pool key (Endpoint.Key()). +func (c *Conn) Key() string { return c.key } + +// Endpoint returns the endpoint this connection was dialed with. +func (c *Conn) Endpoint() Endpoint { return c.ep } + +// Err explains the current state: why it was lost, ErrClosed, or nil. +func (c *Conn) Err() error { + switch c.State() { + case Closed: + return ErrClosed + case Lost, Connecting: + c.mu.Lock() + defer c.mu.Unlock() + if c.lostBy != nil { + return c.lostBy + } + return ErrConnLost + } + return nil +} + +// Client returns the SFTP client of the current generation, or an error +// wrapping ErrConnLost / ErrClosed when the connection is not Ready. The +// client is safe for concurrent use; after the connection dies its calls +// fail (map them with MapErr). +func (c *Conn) Client() (*sftp.Client, error) { + if err := c.Err(); err != nil { + return nil, err + } + return c.sftp.Load(), nil +} + +// SSH returns the SSH client of the current generation (for exec and port +// forwarding), with the same rules as Client. +func (c *Conn) SSH() (*ssh.Client, error) { + if err := c.Err(); err != nil { + return nil, err + } + return c.cur.Load().ssh, nil +} + +// Identity is the host key of the server; it does not change across +// reconnects (a different key fails the reconnect). +func (c *Conn) Identity() HostIdentity { return c.cur.Load().id } + +// ServerVersion is the server's SSH version banner, e.g. +// "SSH-2.0-OpenSSH_9.6" (sftpfs uses it for the symlink argument order). +func (c *Conn) ServerVersion() string { return c.cur.Load().serverVersion } + +// Caps returns the SFTP extensions of the current generation. Exec support +// is probed separately (ExecSupported) because it needs a round trip. +func (c *Conn) Caps() ConnCaps { return c.cur.Load().caps } + +// MapErr turns errors caused by a dead connection into ErrConnLost (wrapped, +// so the original stays visible); other errors are returned unchanged. +func (c *Conn) MapErr(err error) error { + if err == nil || errors.Is(err, ErrConnLost) || errors.Is(err, ErrClosed) { + return err + } + if errors.Is(err, sftp.ErrSSHFxConnectionLost) || errors.Is(err, net.ErrClosed) { + return fmt.Errorf("%w: %v", ErrConnLost, err) + } + if st := c.State(); st != Ready && (errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF)) { + if st == Closed { + return fmt.Errorf("%w: %v", ErrClosed, err) + } + return fmt.Errorf("%w: %v", ErrConnLost, err) + } + return err +} + +// ErrIdentityChanged: on reconnect the server presented a different host key +// than the original connection (the Volume would no longer be the same). +var ErrIdentityChanged = errors.New("server host key differs from the original connection") + +// Reconnect dials a new generation if the connection is Lost. It is a +// single attempt (Pool.Reconnect adds backoff); concurrent calls are +// serialized and a call on a Ready connection is a no-op. Operations started +// on the old generation keep failing with ErrConnLost. +func (c *Conn) Reconnect(ctx context.Context) error { + c.reconnectMu.Lock() + defer c.reconnectMu.Unlock() + c.mu.Lock() + switch c.State() { + case Closed: + c.mu.Unlock() + return ErrClosed + case Ready: + c.mu.Unlock() + return nil + } + c.state.Store(uint32(Connecting)) + gen := c.gen.Load() + c.mu.Unlock() + c.emit(Event{Key: c.key, State: Connecting, Gen: gen}) + + l, err := c.d.dial(ctx, c.ep) + if err == nil && l.id != c.Identity() { + l.close() + err = fmt.Errorf("reconnect %s: %w (was %s, now %s)", c.ep.Label(), ErrIdentityChanged, + c.Identity().FingerprintSHA256, l.id.FingerprintSHA256) + } + c.mu.Lock() + if c.State() == Closed { + c.mu.Unlock() + if err == nil { + l.close() + } + return ErrClosed + } + if err != nil { + c.lostBy = fmt.Errorf("%w: %v", ErrConnLost, err) + c.state.Store(uint32(Lost)) + lostBy := c.lostBy + c.mu.Unlock() + c.emit(Event{Key: c.key, State: Lost, Gen: gen, Err: lostBy}) + return err + } + c.install(l) + gen = c.gen.Load() + c.mu.Unlock() + c.emit(Event{Key: c.key, State: Ready, Gen: gen}) + return nil +} + +// close shuts the connection down for good and waits for its goroutines. +// Only the Pool calls it. +func (c *Conn) close() { + c.mu.Lock() + if c.State() == Closed { + c.mu.Unlock() + return + } + c.state.Store(uint32(Closed)) + g := c.cur.Load() + c.mu.Unlock() + if g != nil { + g.close() + } + c.wg.Wait() + if g != nil { + c.emit(Event{Key: c.key, State: Closed, Gen: g.gen}) + } +} diff --git a/internal/ssh/conn/conn_test.go b/internal/ssh/conn/conn_test.go new file mode 100644 index 0000000..c1925c4 --- /dev/null +++ b/internal/ssh/conn/conn_test.go @@ -0,0 +1,290 @@ +package conn + +import ( + "context" + "errors" + "strings" + "sync" + "testing" + "time" + + "vcom/internal/testutil/sshtest" +) + +// events collects Conn events. +type events struct { + mu sync.Mutex + ev []Event +} + +func (e *events) add(ev Event) { + e.mu.Lock() + e.ev = append(e.ev, ev) + e.mu.Unlock() +} + +func (e *events) has(s State) bool { + e.mu.Lock() + defer e.mu.Unlock() + for _, ev := range e.ev { + if ev.State == s { + return true + } + } + return false +} + +func (e *events) last() Event { + e.mu.Lock() + defer e.mu.Unlock() + if len(e.ev) == 0 { + return Event{} + } + return e.ev[len(e.ev)-1] +} + +// fastKeepalive makes liveness tests take well under a second. +var fastKeepalive = ConnOptions{ + KeepaliveInterval: 100 * time.Millisecond, + KeepaliveTimeout: 100 * time.Millisecond, + KeepaliveMaxMiss: 2, +} + +func (e *env) connect(addr, password string, o ConnOptions) *Conn { + e.t.Helper() + c, err := e.dialer(DialOptions{}).connect(context.Background(), endpointFor(addr, password), o) + if err != nil { + e.t.Fatalf("connect: %v", err) + } + e.t.Cleanup(c.close) + return c +} + +// Ported from the testbed (B6, TestFreezeHangs), N-P1-2: a frozen link was +// never noticed and calls hung forever. Now keepalive marks it Lost within +// interval*(miss+1)+timeout and the hung ReadDir returns ErrConnLost. +func TestFreezeDetectedAsLost(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + var ev events + o := fastKeepalive + o.OnEvent = ev.add + c := e.connect(px.Addr, srv.Password, o) + sc, err := c.Client() + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + if _, err := sc.ReadDir(dir); err != nil { + t.Fatal(err) + } + + px.Freeze(true) + defer px.Freeze(false) + start := time.Now() + res := make(chan error, 1) + go func() { + _, err := sc.ReadDir(dir) + res <- c.MapErr(err) + }() + bound := o.KeepaliveInterval*time.Duration(o.KeepaliveMaxMiss+1) + o.KeepaliveTimeout + waitFor(t, bound+500*time.Millisecond, "state Lost", func() bool { return c.State() == Lost }) + t.Logf("lost after %v (bound %v)", time.Since(start), bound) + select { + case err := <-res: + if !errors.Is(err, ErrConnLost) { + t.Errorf("hung ReadDir: err = %v, want ErrConnLost", err) + } + case <-time.After(time.Second): + t.Fatal("hung ReadDir did not return after Lost") + } + if !ev.has(Lost) || ev.last().Err == nil || !errors.Is(ev.last().Err, ErrConnLost) { + t.Errorf("events = %+v", ev.ev) + } + if _, err := c.Client(); !errors.Is(err, ErrConnLost) { + t.Errorf("Client() after Lost: %v", err) + } + }) +} + +func TestReconnectAfterCut(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + var ev events + o := ConnOptions{KeepaliveInterval: time.Hour, OnEvent: ev.add} + c := e.connect(px.Addr, srv.Password, o) + dir := t.TempDir() + gen := c.Gen() + id := c.Identity() + + px.CutAfter(1) + sc, _ := c.Client() + _, err := sc.ReadDir(dir) + if err == nil { + t.Fatal("ReadDir across a cut succeeded") + } + if !errors.Is(c.MapErr(err), ErrConnLost) { + t.Errorf("err = %v, want ErrConnLost", c.MapErr(err)) + } + waitFor(t, 2*time.Second, "state Lost", func() bool { return c.State() == Lost }) + + if err := c.Reconnect(context.Background()); err != nil { + t.Fatalf("Reconnect: %v", err) + } + if c.State() != Ready || c.Gen() != gen+1 || c.Identity() != id { + t.Errorf("after reconnect: state %v gen %d (was %d) id %+v", c.State(), c.Gen(), gen, c.Identity()) + } + sc2, err := c.Client() + if err != nil { + t.Fatal(err) + } + if _, err := sc2.ReadDir(dir); err != nil { + t.Fatalf("ReadDir after reconnect: %v", err) + } + // The old generation's client stays dead. + if _, err := sc.ReadDir(dir); !errors.Is(c.MapErr(err), ErrConnLost) { + t.Errorf("old-generation client: %v", err) + } + if err := c.Reconnect(context.Background()); err != nil { + t.Errorf("Reconnect on a Ready conn must be a no-op: %v", err) + } + if !ev.has(Connecting) || ev.last().State != Ready { + t.Errorf("events = %+v", ev.ev) + } + c.close() + if err := c.Reconnect(context.Background()); !errors.Is(err, ErrClosed) { + t.Errorf("Reconnect after close: %v", err) + } + if _, err := c.Client(); !errors.Is(err, ErrClosed) { + t.Errorf("Client after close: %v", err) + } + }) +} + +func TestReconnectFailsWhileServerDown(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + c := e.connect(px.Addr, srv.Password, ConnOptions{KeepaliveInterval: time.Hour}) + px.Freeze(true) + defer px.Freeze(false) + px.KillAll() + waitFor(t, 2*time.Second, "state Lost", func() bool { return c.State() == Lost }) + c.d.opts.HandshakeTimeout = 200 * time.Millisecond + if err := c.Reconnect(context.Background()); err == nil { + t.Fatal("reconnect through a frozen link succeeded") + } + if c.State() != Lost { + t.Errorf("state = %v, want Lost", c.State()) + } +} + +func TestProbeMarksLost(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + c := e.connect(px.Addr, srv.Password, ConnOptions{KeepaliveInterval: time.Hour}) + if err := c.Probe(context.Background(), time.Second); err != nil { + t.Fatalf("probe on a live link: %v", err) + } + px.Freeze(true) + defer px.Freeze(false) + if err := c.Probe(context.Background(), 100*time.Millisecond); !errors.Is(err, ErrConnLost) { + t.Fatalf("probe on a frozen link: %v", err) + } + if c.State() != Lost { + t.Errorf("state = %v", c.State()) + } +} + +// N-P2-15 / N-P1-7: Exec had no ctx and no timeout. +func TestExecCancelKills(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + c := e.connect(srv.Addr, srv.Password, ConnOptions{}) + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(100*time.Millisecond, cancel) + start := time.Now() + _, _, err := c.Exec(ctx, []string{"sleep", "60"}, 0) + if el := time.Since(start); el > time.Second { + t.Errorf("cancel took %v", el) + } + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v", err) + } + // The connection is still usable. + out, code, err := c.Exec(context.Background(), []string{"echo", "it's ok"}, 0) + if err != nil || code != 0 || string(out) != "it's ok\n" { + t.Errorf("exec after cancel: %q %d %v", out, code, err) + } +} + +func TestExecOutputLimit(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + c := e.connect(srv.Addr, srv.Password, ConnOptions{}) + start := time.Now() + out, _, err := c.Exec(context.Background(), []string{"yes"}, 1000) + if !errors.Is(err, ErrOutputLimit) { + t.Fatalf("err = %v, want ErrOutputLimit", err) + } + if len(out) != 1000 || !strings.HasPrefix(string(out), "y\ny\n") { + t.Errorf("output: %d bytes", len(out)) + } + if el := time.Since(start); el > 2*time.Second { + t.Errorf("limited exec took %v", el) + } +} + +func TestExecExitStatus(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + c := e.connect(srv.Addr, srv.Password, ConnOptions{}) + out, code, err := c.Exec(context.Background(), []string{"sh", "-c", "echo out; echo bad >&2; exit 3"}, 0) + var ee *ExitError + if !errors.As(err, &ee) || code != 3 || ee.Code != 3 || strings.TrimSpace(ee.Stderr) != "bad" || string(out) != "out\n" { + t.Errorf("out=%q code=%d err=%v", out, code, err) + } + if !c.ExecSupported(context.Background()) { + t.Error("ExecSupported = false on a server with exec") + } +} + +func TestExecSupportedNoExec(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{NoExec: true}) + c := e.connect(srv.Addr, srv.Password, ConnOptions{}) + if c.ExecSupported(context.Background()) { + t.Error("ExecSupported = true with ForceCommand internal-sftp") + } + if _, err := c.Client(); err != nil { + t.Errorf("a refused exec must not break the connection: %v", err) + } +} + +func TestQuote(t *testing.T) { + got := Quote([]string{"cp", "-r", "a b", "it's", "", "x;rm -rf /", "/ok/path_1.txt"}) + want := `cp -r 'a b' 'it'\''s' '' 'x;rm -rf /' /ok/path_1.txt` + if got != want { + t.Errorf("Quote = %s\nwant %s", got, want) + } +} + +func TestConnInfo(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + c := e.connect(srv.Addr, srv.Password, ConnOptions{}) + if c.Identity().FingerprintSHA256 == "" || !strings.HasPrefix(c.ServerVersion(), "SSH-2.0-") { + t.Errorf("identity %+v version %q", c.Identity(), c.ServerVersion()) + } + if !c.Caps().PosixRename { + t.Logf("caps: %+v", c.Caps()) + } + if c.Key() != "u@"+srv.Addr { + t.Errorf("Key = %q", c.Key()) + } +} diff --git a/internal/ssh/conn/exec.go b/internal/ssh/conn/exec.go new file mode 100644 index 0000000..f1e1ef0 --- /dev/null +++ b/internal/ssh/conn/exec.go @@ -0,0 +1,195 @@ +package conn + +import ( + "bytes" + "context" + "errors" + "fmt" + "strings" + "sync" + + "golang.org/x/crypto/ssh" +) + +// DefaultExecLimit caps the captured stdout of Exec (§3.4). +const DefaultExecLimit = 1 << 20 + +// stderrLimit caps the stderr kept for ExitError. +const stderrLimit = 4 << 10 + +// ErrOutputLimit: the command printed more than the limit; it was killed +// and the output truncated (N-P2-15). +var ErrOutputLimit = errors.New("command output exceeds limit") + +// ExitError is a non-zero exit status. +type ExitError struct { + Code int + Stderr string // first 4 KiB +} + +func (e *ExitError) Error() string { + msg := strings.TrimSpace(e.Stderr) + if msg == "" { + return fmt.Sprintf("remote command exited with status %d", e.Code) + } + return fmt.Sprintf("remote command exited with status %d: %s", e.Code, msg) +} + +// Quote joins argv into a POSIX shell command line, quoting every argument +// that is not made of safe characters only. +func Quote(argv []string) string { + parts := make([]string, len(argv)) + for i, a := range argv { + parts[i] = quoteArg(a) + } + return strings.Join(parts, " ") +} + +func quoteArg(a string) string { + if a == "" { + return "''" + } + safe := true + for _, r := range a { + if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("-_./=:,+@%", r)) { + safe = false + break + } + } + if safe { + return a + } + return "'" + strings.ReplaceAll(a, "'", `'\''`) + "'" +} + +// limitWriter keeps at most limit bytes and calls overflow once when more +// arrive. +type limitWriter struct { + mu sync.Mutex + buf bytes.Buffer + limit int64 + over bool + overflow func() +} + +func (w *limitWriter) Write(p []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + if w.over { + return 0, ErrOutputLimit + } + room := w.limit - int64(w.buf.Len()) + if int64(len(p)) <= room { + return w.buf.Write(p) + } + w.buf.Write(p[:room]) + w.over = true + if w.overflow != nil { + go w.overflow() + } + return int(room), ErrOutputLimit +} + +func (w *limitWriter) bytes() ([]byte, bool) { + w.mu.Lock() + defer w.mu.Unlock() + return append([]byte(nil), w.buf.Bytes()...), w.over +} + +// Exec runs argv on the server (arguments are shell-quoted) and returns its +// stdout (at most limit bytes; <= 0 means DefaultExecLimit) and exit code. +// A non-zero exit returns *ExitError along with the code. Cancelling ctx +// sends SIGKILL and closes the session immediately (N-P1-7); output over +// the limit kills the command and returns ErrOutputLimit with the +// truncated output. Code is -1 when there is no exit status. +func (c *Conn) Exec(ctx context.Context, argv []string, limit int64) ([]byte, int, error) { + if len(argv) == 0 { + return nil, -1, errors.New("exec: empty command") + } + if limit <= 0 { + limit = DefaultExecLimit + } + client, err := c.SSH() + if err != nil { + return nil, -1, err + } + if err := ctx.Err(); err != nil { + return nil, -1, err + } + + var ( + mu sync.Mutex + sess *ssh.Session + killed bool + ) + kill := func() { + mu.Lock() + defer mu.Unlock() + killed = true + if sess != nil { + sess.Signal(ssh.SIGKILL) + sess.Close() + } + } + stdout := &limitWriter{limit: limit, overflow: kill} + stderr := &limitWriter{limit: stderrLimit} + type result struct{ err error } + done := make(chan result, 1) + go func() { + s, err := client.NewSession() + if err != nil { + done <- result{c.MapErr(err)} + return + } + mu.Lock() + if killed { + mu.Unlock() + s.Close() + done <- result{context.Canceled} + return + } + sess = s + mu.Unlock() + defer s.Close() + s.Stdout, s.Stderr = stdout, stderr + done <- result{s.Run(Quote(argv))} + }() + + var r result + select { + case r = <-done: + case <-ctx.Done(): + kill() + return nil, -1, ctx.Err() + } + out, over := stdout.bytes() + if over { + return out, -1, fmt.Errorf("%w (%d bytes)", ErrOutputLimit, limit) + } + if r.err == nil { + return out, 0, nil + } + var ee *ssh.ExitError + if errors.As(r.err, &ee) { + se, _ := stderr.bytes() + return out, ee.ExitStatus(), &ExitError{Code: ee.ExitStatus(), Stderr: string(se)} + } + return out, -1, c.MapErr(r.err) +} + +// ExecSupported reports whether the server runs commands (false for +// `ForceCommand internal-sftp`). Probed with `true`; only a definite answer +// is cached (a cancelled or lost probe is retried next time). +func (c *Conn) ExecSupported(ctx context.Context) bool { + c.execMu.Lock() + defer c.execMu.Unlock() + if c.execKnown { + return c.execOK + } + _, code, err := c.Exec(ctx, []string{"true"}, 64) + if ctx.Err() != nil || errors.Is(err, ErrConnLost) || errors.Is(err, ErrClosed) { + return false + } + c.execKnown, c.execOK = true, err == nil && code == 0 + return c.execOK +} diff --git a/internal/ssh/conn/helpers_test.go b/internal/ssh/conn/helpers_test.go index 91c4029..347b3fa 100644 --- a/internal/ssh/conn/helpers_test.go +++ b/internal/ssh/conn/helpers_test.go @@ -105,6 +105,23 @@ func endpointFor(addr, password string) Endpoint { return Endpoint{Alias: "test", User: "u", Host: host, Port: p, Password: password} } +// proxy starts a proxy in front of srv and trusts srv's keys at the proxy +// address too. +func (e *env) proxy(srv *sshtest.Server) *sshtest.Proxy { + px := sshtest.NewProxy(e.t, srv.Addr) + old, _ := os.ReadFile(e.kh) + var pubs []ssh.PublicKey + for _, k := range srv.HostKeys { + pubs = append(pubs, k.PublicKey()) + } + e.trust(px.Addr, pubs...) + added, _ := os.ReadFile(e.kh) + if err := os.WriteFile(e.kh, append(old, added...), 0o600); err != nil { + e.t.Fatal(err) + } + return px +} + // startTrusted starts a server whose host keys are in known_hosts. func (e *env) startTrusted(o sshtest.Options) *sshtest.Server { srv := sshtest.Start(e.t, o) diff --git a/internal/ssh/conn/keepalive.go b/internal/ssh/conn/keepalive.go new file mode 100644 index 0000000..c78c874 --- /dev/null +++ b/internal/ssh/conn/keepalive.go @@ -0,0 +1,83 @@ +package conn + +import ( + "context" + "errors" + "fmt" + "time" +) + +// errKeepalive is the reason recorded when keepalives go unanswered. +var errKeepalive = errors.New("no reply to keepalive") + +// keepalive sends keepalive@openssh.com every interval. KeepaliveMaxMiss +// unanswered requests in a row (each waits KeepaliveTimeout) close the SSH +// client: every pending request fails at once and the state becomes Lost +// (N-P1-2). Worst-case detection: interval*(maxMiss+1) + timeout. +func (c *Conn) keepalive(g *generation) { + t := time.NewTicker(c.opts.KeepaliveInterval) + defer t.Stop() + miss := 0 + for { + select { + case <-g.done: + return + case <-t.C: + } + if c.ping(g, c.opts.KeepaliveTimeout) { + miss = 0 + continue + } + miss++ + if miss >= c.opts.KeepaliveMaxMiss { + c.lose(g, fmt.Errorf("%w (%d × %v)", errKeepalive, miss, c.opts.KeepaliveTimeout)) + return + } + } +} + +// ping sends one keepalive and reports whether a reply (any reply: OpenSSH +// and x/crypto servers answer "failure" to unknown global requests) arrived +// within timeout. A request stuck on a dead link finishes when the client +// is closed (it is not tracked in c.wg: Probe may run concurrently with +// close, and WaitGroup.Add must not race with Wait). +func (c *Conn) ping(g *generation, timeout time.Duration) bool { + res := make(chan error, 1) + go func() { + _, _, err := g.ssh.SendRequest("keepalive@openssh.com", true, nil) + res <- err + }() + timer := time.NewTimer(timeout) + defer timer.Stop() + select { + case err := <-res: + return err == nil + case <-timer.C: + return false + case <-g.done: + return false + } +} + +// Probe is the operation watchdog (§3.4): when an SFTP call has hung for a +// long time, sftpfs sends an out-of-band keepalive. No reply within timeout +// marks the connection Lost (closing it, so the hung call returns) and +// returns ErrConnLost. ctx only bounds the wait; it does not mark anything. +func (c *Conn) Probe(ctx context.Context, timeout time.Duration) error { + if err := c.Err(); err != nil { + return err + } + g := c.cur.Load() + ok := make(chan bool, 1) + go func() { ok <- c.ping(g, timeout) }() + select { + case alive := <-ok: + if alive { + return nil + } + c.lose(g, fmt.Errorf("%w (probe, %v)", errKeepalive, timeout)) + return c.Err() + case <-ctx.Done(): + return ctx.Err() + } +} diff --git a/plans/rework/04-dev-log-B.md b/plans/rework/04-dev-log-B.md index e92edea..9dd0697 100644 --- a/plans/rework/04-dev-log-B.md +++ b/plans/rework/04-dev-log-B.md @@ -60,3 +60,26 @@ ещё и из `/etc/ssh/ssh_known_hosts`. - Тест `TestKeyboardInteractiveUsesPrompter` использует свой мини-сервер в `helpers_test.go` (у `sshtest` нет KI); `sshtest` не трогал, чтобы не выходить из своей зоны. + +## 2B.3 `ssh/conn` Conn + +- **`ErrConnLost`/`ErrClosed` живут в `conn`**, а не в `vfs`: `conn` не может импортировать `vfs` (его пишет + разработчик A, и `sftpfs → conn` — обратное направление). `sftpfs` (2B.5) маппит `conn.ErrConnLost` → + `vfs.ErrConnLost`. Для классификации ошибок SFTP есть `(*Conn).MapErr(err)`: `sftp.ErrSSHFxConnectionLost`, + `net.ErrClosed` → `ErrConnLost` всегда; `io.EOF`/`ErrUnexpectedEOF` — только если состояние уже не `Ready` + (EOF чтения файла — не обрыв). +- **`Conn.Close` не экспортирован** (`close()`), закрывает только Pool — по D3/§3.3 это гарантия на уровне API, а не + дисциплины. +- **Смерть обнаруживается двумя путями:** keepalive (`interval × (maxMiss+1) + timeout` в худшем случае) и + `ssh.Client.Wait()` (обрыв TCP/`CutAfter` → `Lost` сразу, без ожидания keepalive). +- **Watchdog операций** (§3.4) разделён: `Conn.Probe(ctx, timeout)` — внеочередной keepalive, нет ответа → `Lost`; + решение «вызов висит дольше 30 с» принимает `sftpfs.call` (2B.5). +- **`Reconnect` — одна попытка** на уровне `Conn` (backoff — в `Pool.Reconnect`, 2B.4); вызовы сериализуются, на + `Ready` — no-op. Новый host key при переподключении → ошибка `ErrIdentityChanged` (иначе `Volume()` = отпечаток + ключа перестал бы быть правдой). События: `Connecting` → `Ready`/`Lost`, и `Closed` при закрытии пулом. +- **Exec:** `Exec(ctx, argv, limit) ([]byte, int, error)` — аргументы экранируются (`conn.Quote`), ненулевой код → + `*ExitError{Code, Stderr(≤4 КиБ)}` вместе с кодом; превышение лимита убивает команду (`SIGKILL` + закрытие + сессии) и возвращает усечённый вывод с `ErrOutputLimit`. `Caps()` не содержит `Exec` (нужен round trip), вместо + этого `ExecSupported(ctx)` — проба `true`, кэшируется только определённый ответ. +- Тест-сервер `sshtest` не обрабатывает `signal`; отмена проверяется по клиенту (возврат < 1 с, соединение живо), + процесс `sleep` на стороне стенда добивается при остановке сервера. From c328fff867230881acba856b078f2eaa9ac6d464 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sun, 1 Nov 2026 03:51:51 +0300 Subject: [PATCH 4/4] feat(ssh): add refcounted connection Pool and Lease (2B.4) Panels, jobs and previews hold Leases; only the pool closes a connection, after IdleClose without leases or on Close, so concurrent use and release cannot race (N-P0-8) and a mirror keeps its connection when the other panel leaves (N-P1-12). Concurrent Acquires of one user@host:port share a single dial (N-P2-8); Reconnect retries with backoff. Co-Authored-By: Claude Opus 5.5 --- internal/ssh/conn/conn_test.go | 13 +- internal/ssh/conn/pool.go | 328 +++++++++++++++++++++++++++++++ internal/ssh/conn/pool_test.go | 339 +++++++++++++++++++++++++++++++++ plans/rework/04-dev-log-B.md | 17 ++ 4 files changed, 694 insertions(+), 3 deletions(-) create mode 100644 internal/ssh/conn/pool.go create mode 100644 internal/ssh/conn/pool_test.go diff --git a/internal/ssh/conn/conn_test.go b/internal/ssh/conn/conn_test.go index c1925c4..cb2561b 100644 --- a/internal/ssh/conn/conn_test.go +++ b/internal/ssh/conn/conn_test.go @@ -34,6 +34,12 @@ func (e *events) has(s State) bool { return false } +func (e *events) snapshot() []Event { + e.mu.Lock() + defer e.mu.Unlock() + return append([]Event(nil), e.ev...) +} + func (e *events) last() Event { e.mu.Lock() defer e.mu.Unlock() @@ -100,8 +106,9 @@ func TestFreezeDetectedAsLost(t *testing.T) { case <-time.After(time.Second): t.Fatal("hung ReadDir did not return after Lost") } - if !ev.has(Lost) || ev.last().Err == nil || !errors.Is(ev.last().Err, ErrConnLost) { - t.Errorf("events = %+v", ev.ev) + waitFor(t, time.Second, "Lost event", func() bool { return ev.has(Lost) }) + if ev.last().Err == nil || !errors.Is(ev.last().Err, ErrConnLost) { + t.Errorf("events = %+v", ev.snapshot()) } if _, err := c.Client(); !errors.Is(err, ErrConnLost) { t.Errorf("Client() after Lost: %v", err) @@ -153,7 +160,7 @@ func TestReconnectAfterCut(t *testing.T) { t.Errorf("Reconnect on a Ready conn must be a no-op: %v", err) } if !ev.has(Connecting) || ev.last().State != Ready { - t.Errorf("events = %+v", ev.ev) + t.Errorf("events = %+v", ev.snapshot()) } c.close() if err := c.Reconnect(context.Background()); !errors.Is(err, ErrClosed) { diff --git a/internal/ssh/conn/pool.go b/internal/ssh/conn/pool.go new file mode 100644 index 0000000..dcf4692 --- /dev/null +++ b/internal/ssh/conn/pool.go @@ -0,0 +1,328 @@ +package conn + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "time" + + "github.com/pkg/sftp" +) + +// ErrPoolClosed is returned by Acquire after Pool.Close. +var ErrPoolClosed = errors.New("connection pool closed") + +// DefaultIdleClose is how long a connection without leases stays open. +const DefaultIdleClose = 60 * time.Second + +// DefaultReconnectBackoff: delays between Pool.Reconnect attempts (5 tries). +var DefaultReconnectBackoff = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second} + +// PoolOptions configure a Pool. +type PoolOptions struct { + DialOptions // Prompter, HandshakeTimeout, known_hosts, agent, ... + + KeepaliveInterval time.Duration // 15s (or ServerAliveInterval) + KeepaliveTimeout time.Duration // 10s + KeepaliveMaxMiss int // 2 (or ServerAliveCountMax) + // IdleClose closes a connection this long after its last lease is + // released. Default 60s; negative closes immediately. + IdleClose time.Duration + // ReconnectBackoff are the delays between Reconnect attempts; attempts + // = len+1. nil means DefaultReconnectBackoff (1,2,4,8s). + ReconnectBackoff []time.Duration + // OnEvent receives connection state changes (main forwards them with + // program.Send). Called from pool goroutines; must not block. + OnEvent func(Event) +} + +// Pool shares one connection per Endpoint.Key() among panels, jobs, +// previews and size counters. Each user holds a Lease; the pool alone +// closes connections: when the last lease has been released for IdleClose, +// or on Close (N-P0-8, N-P1-12). It is safe for concurrent use. +type Pool struct { + d *dialer + opts PoolOptions + + mu sync.Mutex + closed bool + entries map[string]*entry + inflight map[string]*call + wg sync.WaitGroup // dial goroutines and idle closes +} + +type entry struct { + key string + conn *Conn + refs int + idle *time.Timer + seq uint64 // invalidates stale idle timers +} + +// call is one in-flight dial shared by every concurrent Acquire of a key. +type call struct { + done chan struct{} + waiters int + cancel context.CancelFunc + e *entry + err error +} + +// NewPool creates a pool. +func NewPool(o PoolOptions) *Pool { + if o.IdleClose == 0 { + o.IdleClose = DefaultIdleClose + } + if o.ReconnectBackoff == nil { + o.ReconnectBackoff = DefaultReconnectBackoff + } + return &Pool{ + d: newDialer(o.DialOptions), + opts: o, + entries: map[string]*entry{}, + inflight: map[string]*call{}, + } +} + +func (p *Pool) connOptions() ConnOptions { + return ConnOptions{ + KeepaliveInterval: p.opts.KeepaliveInterval, + KeepaliveTimeout: p.opts.KeepaliveTimeout, + KeepaliveMaxMiss: p.opts.KeepaliveMaxMiss, + OnEvent: p.opts.OnEvent, + } +} + +// Acquire returns a lease on the connection for ep, dialing it if needed. +// Concurrent Acquires of the same key share one dial (N-P2-8: a double +// Enter makes one connection). A Lost connection gets one reconnect +// attempt. If every waiter gives up (ctx), the dial is cancelled; a dial +// that still completes is parked idle and closed after IdleClose. +func (p *Pool) Acquire(ctx context.Context, ep Endpoint) (*Lease, error) { + key := ep.Key() + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return nil, ErrPoolClosed + } + if e := p.entries[key]; e != nil { + l := p.lease(e) + p.mu.Unlock() + if e.conn.State() == Lost { + if err := e.conn.Reconnect(ctx); err != nil { + l.Release() + return nil, err + } + } + return l, nil + } + c := p.inflight[key] + if c == nil { + dctx, cancel := context.WithCancel(context.Background()) + c = &call{done: make(chan struct{}), cancel: cancel} + p.inflight[key] = c + p.wg.Add(1) + go p.dial(dctx, key, ep, c) + } + c.waiters++ + p.mu.Unlock() + + select { + case <-c.done: + case <-ctx.Done(): + p.mu.Lock() + c.waiters-- + select { + case <-c.done: + // Finished concurrently: the entry may now have no users. + if c.e != nil && c.e.refs == 0 { + p.startIdle(c.e) + } + default: + if c.waiters == 0 { + c.cancel() + } + } + p.mu.Unlock() + return nil, ctx.Err() + } + if c.err != nil { + return nil, c.err + } + p.mu.Lock() + defer p.mu.Unlock() + if p.closed || p.entries[key] != c.e { + return nil, ErrPoolClosed + } + return p.lease(c.e), nil +} + +func (p *Pool) dial(ctx context.Context, key string, ep Endpoint, c *call) { + defer p.wg.Done() + conn, err := p.d.connect(ctx, ep, p.connOptions()) + c.cancel() + p.mu.Lock() + delete(p.inflight, key) + if err == nil && p.closed { + err = ErrPoolClosed + p.mu.Unlock() + conn.close() + p.mu.Lock() + } + c.err = err + if err == nil { + c.e = &entry{key: key, conn: conn} + p.entries[key] = c.e + if c.waiters == 0 { + p.startIdle(c.e) // everyone gave up; keep briefly, then close + } + } + close(c.done) + p.mu.Unlock() +} + +// lease takes a reference on e; p.mu is held. +func (p *Pool) lease(e *entry) *Lease { + e.refs++ + e.seq++ + if e.idle != nil { + e.idle.Stop() + e.idle = nil + } + return &Lease{p: p, e: e} +} + +// startIdle schedules e to close after IdleClose; p.mu is held. +func (p *Pool) startIdle(e *entry) { + e.seq++ + seq := e.seq + if e.idle != nil { + e.idle.Stop() + } + fire := func() { + p.mu.Lock() + if e.seq != seq || e.refs != 0 || p.entries[e.key] != e { + p.mu.Unlock() + return + } + delete(p.entries, e.key) + // The entry was still registered, so Close has not started waiting: + // this Add cannot race with p.wg.Wait. + p.wg.Add(1) + p.mu.Unlock() + defer p.wg.Done() + e.conn.close() + } + if p.opts.IdleClose < 0 { + e.idle = nil + go fire() + return + } + e.idle = time.AfterFunc(p.opts.IdleClose, fire) +} + +func (p *Pool) release(e *entry) { + p.mu.Lock() + defer p.mu.Unlock() + e.refs-- + if e.refs == 0 && !p.closed && p.entries[e.key] == e { + p.startIdle(e) + } +} + +// Reconnect re-dials a Lost connection with backoff (1,2,4,8s between at +// most 5 attempts by default). A Ready connection is left alone. Host key +// problems and ctx cancellation stop the retries. +func (p *Pool) Reconnect(ctx context.Context, key string) error { + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return ErrPoolClosed + } + e := p.entries[key] + p.mu.Unlock() + if e == nil { + return ErrClosed + } + var err error + for i := 0; ; i++ { + if err = e.conn.Reconnect(ctx); err == nil { + return nil + } + if errors.Is(err, ErrClosed) || errors.Is(err, ErrHostKeyChanged) || + errors.Is(err, ErrHostKeyRejected) || errors.Is(err, ErrIdentityChanged) || ctx.Err() != nil { + return err + } + if i >= len(p.opts.ReconnectBackoff) { + return err + } + t := time.NewTimer(p.opts.ReconnectBackoff[i]) + select { + case <-t.C: + case <-ctx.Done(): + t.Stop() + return ctx.Err() + } + } +} + +// Close closes every connection, cancels pending dials and waits for them. +// Leases stay safe to use: their calls fail with ErrClosed. +func (p *Pool) Close() error { + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return nil + } + p.closed = true + var conns []*Conn + for k, e := range p.entries { + if e.idle != nil { + e.idle.Stop() + } + e.seq++ + conns = append(conns, e.conn) + delete(p.entries, k) + } + for _, c := range p.inflight { + c.cancel() + } + p.mu.Unlock() + for _, c := range conns { + c.close() + } + p.wg.Wait() + p.d.close() + return nil +} + +// Lease is one user's reference to a pooled connection. Release it when +// done; it is idempotent. A lease stays safe to use after the connection +// died or the pool closed: calls return errors, never panic. +type Lease struct { + p *Pool + e *entry + released atomic.Bool +} + +// Conn returns the leased connection. +func (l *Lease) Conn() *Conn { return l.e.conn } + +// Client is shorthand for Conn().Client(). +func (l *Lease) Client() (*sftp.Client, error) { return l.e.conn.Client() } + +// Acquire takes another reference to the same connection (mirror panel, +// background job). Release each lease separately. +func (l *Lease) Acquire() *Lease { + l.p.mu.Lock() + defer l.p.mu.Unlock() + return l.p.lease(l.e) +} + +// Release drops this reference; the second and later calls do nothing. +func (l *Lease) Release() { + if l.released.CompareAndSwap(false, true) { + l.p.release(l.e) + } +} diff --git a/internal/ssh/conn/pool_test.go b/internal/ssh/conn/pool_test.go new file mode 100644 index 0000000..91a1a1d --- /dev/null +++ b/internal/ssh/conn/pool_test.go @@ -0,0 +1,339 @@ +package conn + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" + + "vcom/internal/testutil/sshtest" +) + +func (e *env) pool(o PoolOptions) *Pool { + e.t.Helper() + if o.Home == "" { + o.Home = e.home + } + if o.AgentSocket == "" { + o.AgentSocket = "-" + } + if o.KnownHostsFiles == nil { + o.KnownHostsFiles = []string{e.kh} + } + p := NewPool(o) + e.t.Cleanup(func() { p.Close() }) + return p +} + +func (p *Pool) entryCount() int { + p.mu.Lock() + defer p.mu.Unlock() + return len(p.entries) +} + +func mustAcquire(t *testing.T, p *Pool, ep Endpoint) *Lease { + t.Helper() + l, err := p.Acquire(context.Background(), ep) + if err != nil { + t.Fatalf("Acquire: %v", err) + } + return l +} + +// Ported from TestCloseRace (B5), N-P0-8: Close raced with running calls +// and could call a method on a nil *sftp.Client. Leases are used, released, +// re-acquired and the pool closed concurrently under -race. +func TestLeaseReleaseRace(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + p := e.pool(PoolOptions{IdleClose: 10 * time.Millisecond}) + ep := endpointFor(srv.Addr, srv.Password) + base := mustAcquire(t, p, ep) + dir := t.TempDir() + + var wg sync.WaitGroup + panicked := make(chan any, 8) + worker := func(fn func(i int)) { + wg.Add(1) + go func() { + defer wg.Done() + defer func() { + if r := recover(); r != nil { + panicked <- r + } + }() + for i := 0; i < 300; i++ { + fn(i) + } + }() + } + for w := 0; w < 3; w++ { + worker(func(int) { + l := base.Acquire() + defer l.Release() + defer l.Release() // idempotent + if sc, err := l.Client(); err == nil { + _, err := sc.ReadDir(dir) + if err != nil && !errors.Is(l.Conn().MapErr(err), ErrClosed) && !errors.Is(l.Conn().MapErr(err), ErrConnLost) { + t.Errorf("ReadDir: %v", err) + } + } + }) + } + worker(func(int) { + if l, err := p.Acquire(context.Background(), ep); err == nil { + l.Conn().State() + l.Release() + } + }) + worker(func(i int) { + switch i { + case 0: + time.Sleep(50 * time.Millisecond) // let the readers get going + case 1: + p.Close() + } + }) + wg.Wait() + close(panicked) + for r := range panicked { + t.Fatalf("panic: %v", r) + } + if _, err := base.Client(); !errors.Is(err, ErrClosed) { + t.Errorf("Client after pool Close: %v", err) + } + if _, err := p.Acquire(context.Background(), ep); !errors.Is(err, ErrPoolClosed) { + t.Errorf("Acquire after Close: %v", err) + } + base.Release() + }) +} + +// N-P2-8: a double Enter made two connections. +func TestAcquireSingleflight(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + px.SetDelay(20 * time.Millisecond) // keep the dial in flight while all callers arrive + p := e.pool(PoolOptions{}) + ep := endpointFor(px.Addr, srv.Password) + const n = 10 + leases := make([]*Lease, n) + errs := make([]error, n) + var wg sync.WaitGroup + for i := 0; i < n; i++ { + wg.Add(1) + go func() { + defer wg.Done() + leases[i], errs[i] = p.Acquire(context.Background(), ep) + }() + } + wg.Wait() + for i := 0; i < n; i++ { + if errs[i] != nil { + t.Fatal(errs[i]) + } + if leases[i].Conn() != leases[0].Conn() { + t.Error("leases on different connections") + } + } + if d := p.d.dials.Load(); d != 1 { + t.Errorf("dials = %d, want 1", d) + } + // Same user@host:port through another alias shares the connection. + ep2 := ep + ep2.Alias = "other-alias" + l := mustAcquire(t, p, ep2) + if l.Conn() != leases[0].Conn() || p.d.dials.Load() != 1 { + t.Error("alias with the same key did not share the connection") + } +} + +// Every caller gave up: the dial is cancelled and nothing stays open. +func TestAcquireAllWaitersGone(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + px.Freeze(true) + p := e.pool(PoolOptions{}) + ep := endpointFor(px.Addr, srv.Password) + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + start := time.Now() + if _, err := p.Acquire(ctx, ep); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("err = %v", err) + } + if el := time.Since(start); el > time.Second { + t.Errorf("Acquire returned after %v", el) + } + waitFor(t, 2*time.Second, "in-flight dial gone", func() bool { + p.mu.Lock() + defer p.mu.Unlock() + return len(p.inflight) == 0 && len(p.entries) == 0 + }) + px.Freeze(false) + }) +} + +func TestIdleClose(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + var ev events + p := e.pool(PoolOptions{IdleClose: 150 * time.Millisecond, OnEvent: ev.add}) + ep := endpointFor(srv.Addr, srv.Password) + l := mustAcquire(t, p, ep) + c := l.Conn() + l.Release() + l = mustAcquire(t, p, ep) // within IdleClose: reused + if l.Conn() != c || p.d.dials.Load() != 1 { + t.Fatal("connection not reused within IdleClose") + } + time.Sleep(300 * time.Millisecond) + if c.State() != Ready { + t.Fatal("connection with a live lease was closed") + } + l.Release() + waitFor(t, 2*time.Second, "idle close", func() bool { return ev.has(Closed) && p.entryCount() == 0 }) + if c.State() != Closed { + t.Errorf("state = %v", c.State()) + } + l = mustAcquire(t, p, ep) + if l.Conn() == c || p.d.dials.Load() != 2 { + t.Error("expected a fresh connection after idle close") + } + l.Release() +} + +// N-P1-12: mirror shared one client and a second mirror closed it. +func TestMirrorLeaseSurvivesRelease(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + p := e.pool(PoolOptions{IdleClose: -1}) + left := mustAcquire(t, p, endpointFor(srv.Addr, srv.Password)) + right := left.Acquire() // mirror + left.Release() + left.Release() + left.Release() // over-release must not steal right's reference + sc, err := right.Client() + if err != nil { + t.Fatalf("mirror lease broken: %v", err) + } + if _, err := sc.ReadDir(t.TempDir()); err != nil { + t.Fatalf("ReadDir on mirror: %v", err) + } + c := right.Conn() + right.Release() + waitFor(t, 2*time.Second, "close after last release", func() bool { return c.State() == Closed }) +} + +func TestAcquireReconnectsLost(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + p := e.pool(PoolOptions{}) + ep := endpointFor(px.Addr, srv.Password) + l := mustAcquire(t, p, ep) + defer l.Release() + px.KillAll() + waitFor(t, 2*time.Second, "Lost", func() bool { return l.Conn().State() == Lost }) + l2 := mustAcquire(t, p, ep) + defer l2.Release() + if l2.Conn() != l.Conn() || l.Conn().State() != Ready || l.Conn().Gen() != 2 { + t.Errorf("state %v gen %d", l.Conn().State(), l.Conn().Gen()) + } + if _, err := l.Client(); err != nil { + t.Errorf("old lease after reconnect: %v", err) + } +} + +func TestPoolReconnectBackoff(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + var mu sync.Mutex + connecting := 0 + p := e.pool(PoolOptions{ + ReconnectBackoff: []time.Duration{10 * time.Millisecond, 10 * time.Millisecond}, + OnEvent: func(ev Event) { + if ev.State == Connecting { + mu.Lock() + connecting++ + mu.Unlock() + } + }, + }) + ep := endpointFor(px.Addr, srv.Password) + l := mustAcquire(t, p, ep) + defer l.Release() + px.Freeze(true) + px.KillAll() + waitFor(t, 2*time.Second, "Lost", func() bool { return l.Conn().State() == Lost }) + p.d.opts.HandshakeTimeout = 100 * time.Millisecond + if err := p.Reconnect(context.Background(), ep.Key()); err == nil { + t.Fatal("reconnect through a frozen link succeeded") + } + mu.Lock() + if connecting != 3 { + t.Errorf("attempts = %d, want 3", connecting) + } + mu.Unlock() + px.Freeze(false) + if err := p.Reconnect(context.Background(), ep.Key()); err != nil { + t.Fatalf("reconnect after recovery: %v", err) + } + if l.Conn().State() != Ready { + t.Errorf("state = %v", l.Conn().State()) + } + if err := p.Reconnect(context.Background(), "nobody@nowhere:22"); !errors.Is(err, ErrClosed) { + t.Errorf("unknown key: %v", err) + } +} + +func TestPoolCloseCancelsDial(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + px.Freeze(true) + p := e.pool(PoolOptions{}) + res := make(chan error, 1) + go func() { + _, err := p.Acquire(context.Background(), endpointFor(px.Addr, srv.Password)) + res <- err + }() + waitFor(t, time.Second, "dial in flight", func() bool { return p.d.dials.Load() == 1 }) + start := time.Now() + p.Close() + select { + case err := <-res: + if err == nil { + t.Fatal("Acquire succeeded on a closed pool") + } + case <-time.After(2 * time.Second): + t.Fatal("Acquire still blocked after Close") + } + if el := time.Since(start); el > time.Second { + t.Errorf("Close took %v", el) + } + px.Freeze(false) + }) +} + +func TestPoolDifferentUsersSeparate(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + p := e.pool(PoolOptions{}) + a := endpointFor(srv.Addr, srv.Password) + b := a + b.User = "other" + la, lb := mustAcquire(t, p, a), mustAcquire(t, p, b) + defer la.Release() + defer lb.Release() + if la.Conn() == lb.Conn() { + t.Error(fmt.Sprintf("users %s and %s share a connection", a.User, b.User)) + } +} diff --git a/plans/rework/04-dev-log-B.md b/plans/rework/04-dev-log-B.md index 9dd0697..78bf3b5 100644 --- a/plans/rework/04-dev-log-B.md +++ b/plans/rework/04-dev-log-B.md @@ -83,3 +83,20 @@ этого `ExecSupported(ctx)` — проба `true`, кэшируется только определённый ответ. - Тест-сервер `sshtest` не обрабатывает `signal`; отмена проверяется по клиенту (возврат < 1 с, соединение живо), процесс `sleep` на стороне стенда добивается при остановке сервера. + +## 2B.4 `ssh/conn` Pool + Lease + +- **`NewPool(PoolOptions)`** вместо `NewPool(resolver, opts)`: `Acquire` получает уже разрешённый `Endpoint`, + резолвер пулу не нужен (UI вызывает `resolver.Resolve(alias)`, затем `pool.Acquire`). `PoolOptions` встраивает + `DialOptions` и добавляет `ReconnectBackoff []time.Duration` (по умолчанию 1,2,4,8 с между ≤ 5 попытками; в + тестах — миллисекунды). +- **`Lease.FS()` нет** — `conn` не может импортировать `vfs`/`sftpfs` (цикл `sftpfs → conn`). В 2B.5 будет + `sftpfs.New(lease)`. Вместо этого у Lease есть `Conn()` и сокращение `Client()`. +- **Singleflight с отменой:** dial идёт в контексте пула; каждый ждущий `Acquire` уходит по своему ctx; когда ушли + все — dial отменяется. Если dial всё же завершился без ждущих, соединение паркуется и закрывается через + `IdleClose` (не утекает). `Pool.Close` отменяет текущие dial и ждёт их goroutine. +- **`Acquire` на `Lost`-соединении** делает одну попытку `Reconnect` с ctx вызывающего (повторный Enter на хост + после сна ноутбука). Ошибки host key (`ErrHostKeyChanged/Rejected`, `ErrIdentityChanged`) прекращают backoff. +- `IdleClose < 0` — закрыть сразу после последнего `Release`. `Release` идемпотентен на уровне каждой аренды: + лишние вызовы не отбирают чужие ссылки. После `Pool.Close` аренды безопасны: `Client()` → `ErrClosed`, + `Acquire` → `ErrPoolClosed`.