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 <noreply@anthropic.com>
This commit is contained in:
parent
945ae80c73
commit
8584a638f1
25 changed files with 3376 additions and 0 deletions
1
go.mod
1
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
|
||||
|
|
|
|||
2
go.sum
2
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=
|
||||
|
|
|
|||
48
internal/ssh/internal/atomicwrite/atomicwrite.go
Normal file
48
internal/ssh/internal/atomicwrite/atomicwrite.go
Normal file
|
|
@ -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
|
||||
}
|
||||
31
internal/ssh/internal/atomicwrite/atomicwrite_test.go
Normal file
31
internal/ssh/internal/atomicwrite/atomicwrite_test.go
Normal file
|
|
@ -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")
|
||||
}
|
||||
}
|
||||
199
internal/ssh/sshconfig/flatten.go
Normal file
199
internal/ssh/sshconfig/flatten.go
Normal file
|
|
@ -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
|
||||
}
|
||||
391
internal/ssh/sshconfig/resolver.go
Normal file
391
internal/ssh/sshconfig/resolver.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
285
internal/ssh/sshconfig/resolver_test.go
Normal file
285
internal/ssh/sshconfig/resolver_test.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
317
internal/ssh/sshconfig/store.go
Normal file
317
internal/ssh/sshconfig/store.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
102
internal/ssh/sshconfig/store_test.go
Normal file
102
internal/ssh/sshconfig/store_test.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
31
plans/rework/04-dev-log-B.md
Normal file
31
plans/rework/04-dev-log-B.md
Normal file
|
|
@ -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`.
|
||||
1
vendor/github.com/kevinburke/ssh_config/.gitignore
generated
vendored
Normal file
1
vendor/github.com/kevinburke/ssh_config/.gitignore
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
/coverage.out
|
||||
1
vendor/github.com/kevinburke/ssh_config/.mailmap
generated
vendored
Normal file
1
vendor/github.com/kevinburke/ssh_config/.mailmap
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
Kevin Burke <kevin@burke.dev> Kevin Burke <kev@inburke.com>
|
||||
13
vendor/github.com/kevinburke/ssh_config/AUTHORS.txt
generated
vendored
Normal file
13
vendor/github.com/kevinburke/ssh_config/AUTHORS.txt
generated
vendored
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
Carlos A Becker <caarlos0@gmail.com>
|
||||
Claude Opus 4.6 <noreply@anthropic.com>
|
||||
Dustin Spicuzza <dustin@virtualroadside.com>
|
||||
Eugene Terentev <eugene@terentev.net>
|
||||
Kevin Burke <kevin@burke.dev>
|
||||
Mark Nevill <nev@improbable.io>
|
||||
Neil Williams <neil@reddit.com>
|
||||
Scott Lessans <slessans@gmail.com>
|
||||
Sergey Lukjanov <me@slukjanov.name>
|
||||
Simon Josefsson <simon@josefsson.org>
|
||||
Wayne Ashley Berry <wayneashleyberry@gmail.com>
|
||||
santosh653 <70637961+santosh653@users.noreply.github.com>
|
||||
sio2boss <sio2boss@users.noreply.github.com>
|
||||
65
vendor/github.com/kevinburke/ssh_config/CHANGELOG.md
generated
vendored
Normal file
65
vendor/github.com/kevinburke/ssh_config/CHANGELOG.md
generated
vendored
Normal file
|
|
@ -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.
|
||||
49
vendor/github.com/kevinburke/ssh_config/LICENSE
generated
vendored
Normal file
49
vendor/github.com/kevinburke/ssh_config/LICENSE
generated
vendored
Normal file
|
|
@ -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.
|
||||
34
vendor/github.com/kevinburke/ssh_config/Makefile
generated
vendored
Normal file
34
vendor/github.com/kevinburke/ssh_config/Makefile
generated
vendored
Normal file
|
|
@ -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
|
||||
92
vendor/github.com/kevinburke/ssh_config/README.md
generated
vendored
Normal file
92
vendor/github.com/kevinburke/ssh_config/README.md
generated
vendored
Normal file
|
|
@ -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
|
||||
63
vendor/github.com/kevinburke/ssh_config/SECURITY.md
generated
vendored
Normal file
63
vendor/github.com/kevinburke/ssh_config/SECURITY.md
generated
vendored
Normal file
|
|
@ -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).
|
||||
878
vendor/github.com/kevinburke/ssh_config/config.go
generated
vendored
Normal file
878
vendor/github.com/kevinburke/ssh_config/config.go
generated
vendored
Normal file
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
240
vendor/github.com/kevinburke/ssh_config/lexer.go
generated
vendored
Normal file
240
vendor/github.com/kevinburke/ssh_config/lexer.go
generated
vendored
Normal file
|
|
@ -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
|
||||
}
|
||||
270
vendor/github.com/kevinburke/ssh_config/parser.go
generated
vendored
Normal file
270
vendor/github.com/kevinburke/ssh_config/parser.go
generated
vendored
Normal file
|
|
@ -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
|
||||
}
|
||||
25
vendor/github.com/kevinburke/ssh_config/position.go
generated
vendored
Normal file
25
vendor/github.com/kevinburke/ssh_config/position.go
generated
vendored
Normal file
|
|
@ -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
|
||||
}
|
||||
49
vendor/github.com/kevinburke/ssh_config/token.go
generated
vendored
Normal file
49
vendor/github.com/kevinburke/ssh_config/token.go
generated
vendored
Normal file
|
|
@ -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 == '=')
|
||||
}
|
||||
186
vendor/github.com/kevinburke/ssh_config/validators.go
generated
vendored
Normal file
186
vendor/github.com/kevinburke/ssh_config/validators.go
generated
vendored
Normal file
|
|
@ -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)]
|
||||
}
|
||||
3
vendor/modules.txt
vendored
3
vendor/modules.txt
vendored
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue