Files
move-data-nas/internal/sshmanager/knownhosts.go
T
darroyo 84b185be39 Phase A-E: stability, security, observability, and test coverage
Phase A - Stability:
- Engine.Start(): recovers orphaned jobs (running/queued/waking_up) after crash
- Engine.Stop(): graceful shutdown - cancels all in-flight jobs and waits
- Queue keyed by jobID (not syncPairID): cancel now targets exact job
- Local rsync uses jobCtx (context.Background() replaced)
- Migrations wrapped in transactions; checksums stored

Phase B - Security:
- admin/admin default removed: SYNCSERVER_ADMIN_PASSWORD required on first run
- Path validation: rejects .., leading -, null bytes in sync pair paths
- Rsync flags allowlist: dangerous flags blocked (--rsync-path, -e, --files-from)
- Shell concat in RunRemote replaced with proper sh -c escaping
- knownhosts: replaced custom parser with golang.org/x/crypto/ssh/knownhosts
- RequireAdmin wired: machine CRUD, SSH key ops, settings require admin role
- deploy-keys: uses authorized_keys only (no private key upload)
- Hardcoded /var/lib/syncserver/ssh paths replaced with cfg.SSHDir()

Phase C - Operational:
- /readyz health check: DB query + SSH dir accessibility
- /metrics endpoint: Prometheus text format (jobs, queue, machines)
- Event struct JSON tags: job_id, machine_id, type (snake_case)
- EventBus broadcast: fanned out to all subscribers
- SQLite VACUUM INTO backup: scheduled before cleanup if BackupDir set
- Filesystem job log cleanup: removes .log files for purged jobs
- Backup retention: old backups auto-purged

Phase D - Frontend:
- Schedules page: REST API + full CRUD UI for cron schedules
- Dashboard: cancel button for running/queued jobs
- JobDetail: server-side log download via API
- Settings: displays data_dir from server
- 404 page: proper NotFound component

Phase E - Tests:
- auth_test.go: JWT, bcrypt, middleware, seed (18 tests)
- models_test.go: Job, Machine, SyncPair, Schedule repos (18 tests)
- go test -race: no data races found
2026-07-19 22:14:30 -04:00

170 lines
3.6 KiB
Go

package sshmanager
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
)
type KnownHost struct {
Host string
Port int
KeyType string
Fingerprint string
}
func NewKnownHostsCallback(knownHostsPath string, strictHostKeyChecking bool) (ssh.HostKeyCallback, error) {
if !strictHostKeyChecking {
return ssh.InsecureIgnoreHostKey(), nil
}
if knownHostsPath == "" {
return ssh.InsecureIgnoreHostKey(), nil
}
_, err := os.Stat(knownHostsPath)
if os.IsNotExist(err) {
return ssh.InsecureIgnoreHostKey(), nil
}
if err != nil {
return nil, err
}
return knownhosts.New(knownHostsPath)
}
func EnsureKnownHosts(sshDir string) (string, error) {
path := filepath.Join(sshDir, "known_hosts")
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDONLY, 0644)
if err != nil {
return "", err
}
f.Close()
return path, nil
}
// AddKnownHost stores the host key in standard ssh known_hosts format (hostname keytype base64key).
// NOTE: Existing entries in known_hosts may need to be regenerated if they were stored in a different format.
func AddKnownHost(sshDir, host string, port int, keyData []byte) error {
path := filepath.Join(sshDir, "known_hosts")
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()
addr := host
if port != 22 {
addr = fmt.Sprintf("[%s]:%d", host, port)
}
pubKey, err := ssh.ParsePublicKey(keyData)
if err != nil {
return fmt.Errorf("parsing host key: %w", err)
}
line := fmt.Sprintf("%s %s\n", addr, strings.TrimSpace(string(ssh.MarshalAuthorizedKey(pubKey))))
if _, err := f.WriteString(line); err != nil {
return err
}
return nil
}
func parseHostPort(entry string) (string, int) {
if strings.HasPrefix(entry, "[") {
var h string
var p int
if n, _ := fmt.Sscanf(entry, "[%[^]]]:%d", &h, &p); n == 2 {
return h, p
}
}
parts := strings.Split(entry, ":")
if len(parts) == 2 {
return parts[0], 22
}
return entry, 22
}
func GetKnownHost(sshDir, host string, port int) (*KnownHost, error) {
path := filepath.Join(sshDir, "known_hosts")
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
var targetAddr string
if port != 22 {
targetAddr = fmt.Sprintf("[%s]:%d", host, port)
} else {
targetAddr = host
}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
parts := strings.Fields(line)
if len(parts) < 2 {
continue
}
h, p := parseHostPort(parts[0])
if (h == host || parts[0] == targetAddr) && p == port {
return &KnownHost{
Host: h,
Port: p,
KeyType: parts[1],
Fingerprint: parts[1] + " " + parts[2],
}, nil
}
}
return nil, nil
}
func HasKnownHost(sshDir, host string, port int) (bool, error) {
kh, err := GetKnownHost(sshDir, host, port)
if err != nil {
return false, err
}
return kh != nil, nil
}
func RemoveKnownHost(sshDir, host string, port int) error {
path := filepath.Join(sshDir, "known_hosts")
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
var lines []string
targetAddr := host
if port != 22 {
targetAddr = fmt.Sprintf("[%s]:%d", host, port)
}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
h, p := parseHostPort(line)
if h == host && p == port {
continue
}
if line == targetAddr {
continue
}
lines = append(lines, line)
}
tmp := path + ".tmp"
wf, err := os.Create(tmp)
if err != nil {
return err
}
for _, l := range lines {
wf.WriteString(l + "\n")
}
wf.Close()
return os.Rename(tmp, path)
}