vcom/internal/ssh/sshconfig/store.go
vrubelroman 8584a638f1 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>
2026-10-31 23:27:58 +03:00

317 lines
7.5 KiB
Go

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