vcom/internal/ssh/sshconfig/resolver.go

392 lines
10 KiB
Go
Raw Normal View History

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