sshpool.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. // sshpool.go — Pool de conexiones SSH persistentes (equivalente Go del
  2. // ControlMaster/ControlPersist del JS, SPEC §7.2): UNA conexión por router,
  3. // reutilizada entre ticks del poller, con reconexión automática y backoff
  4. // exponencial (30 s base, máx 5 min) para no martillear un router caído.
  5. //
  6. // known_hosts con semántica accept-new junto a la clave (como el JS):
  7. // host desconocido → se acepta y se anota; host conocido con clave distinta
  8. // → se rechaza (posible MITM).
  9. package adapters
  10. import (
  11. "context"
  12. "errors"
  13. "fmt"
  14. "log"
  15. "net"
  16. "os"
  17. "path/filepath"
  18. "strings"
  19. "sync"
  20. "time"
  21. "github.com/gnacho/netpulse/server-go/internal/sshkey"
  22. "golang.org/x/crypto/ssh"
  23. "golang.org/x/crypto/ssh/knownhosts"
  24. )
  25. const (
  26. sshDialTimeout = 4 * time.Second // ConnectTimeout=4 del JS
  27. sshDefaultTimeout = 5 * time.Second // SSH_TIMEOUT_MS del JS
  28. sshBackoffBase = 30 * time.Second
  29. sshBackoffMax = 5 * time.Minute
  30. )
  31. // addrOf devuelve el destino `host:port` para conectar. Los callers pasan el
  32. // host ya con puerto (RouterConfig.SSHAddr, issue #605); si vienen sin puerto
  33. // (back-compat) se asume 22.
  34. func addrOf(host string) string {
  35. if _, _, err := net.SplitHostPort(host); err == nil {
  36. return host
  37. }
  38. return net.JoinHostPort(host, "22")
  39. }
  40. // SSHPool gestiona conexiones persistentes a los routers.
  41. type SSHPool struct {
  42. keyPath string
  43. signer ssh.Signer
  44. khPath string
  45. mu sync.Mutex
  46. conns map[string]*sshConn
  47. creds map[string]sshCred
  48. closed bool
  49. dialTCP func(network, addr string, config *ssh.ClientConfig) (*ssh.Client, error)
  50. closeClient func(*ssh.Client) error
  51. }
  52. // sshCred es la credencial de contraseña registrada para un host
  53. // (#1708): las integraciones ssh con fichero compañero <slug>.sshpass
  54. // conectan por contraseña mientras la credencial esté registrada; el resto
  55. // de destinos siguen con la llave del servidor.
  56. type sshCred struct {
  57. user string
  58. password string
  59. }
  60. func (p *SSHPool) closeSSHClient(c *ssh.Client) error {
  61. if c == nil {
  62. return nil
  63. }
  64. if p.closeClient != nil {
  65. return p.closeClient(c)
  66. }
  67. return c.Close()
  68. }
  69. type sshConn struct {
  70. client *ssh.Client
  71. dialing chan struct{}
  72. failures int
  73. notUntil time.Time
  74. }
  75. // NewSSHPool crea el pool cargando la clave privada (ed25519 sin passphrase).
  76. func NewSSHPool(keyPath string) (*SSHPool, error) {
  77. pem, err := os.ReadFile(keyPath)
  78. if err != nil {
  79. return nil, fmt.Errorf("leer clave SSH: %w", err)
  80. }
  81. signer, err := ssh.ParsePrivateKey(pem)
  82. if err != nil {
  83. return nil, fmt.Errorf("parsear clave SSH: %w", err)
  84. }
  85. return &SSHPool{
  86. keyPath: keyPath,
  87. signer: signer,
  88. khPath: sshkey.KnownHostsPath(keyPath),
  89. conns: map[string]*sshConn{},
  90. creds: map[string]sshCred{},
  91. dialTCP: ssh.Dial,
  92. }, nil
  93. }
  94. // SetPassword registra (o borra, con password vacía) la credencial de
  95. // contraseña de un host (#1708). Mientras haya credencial, el dial de ese
  96. // host autentica por contraseña con el usuario dado y la llave del servidor
  97. // queda aparcada. Un cambio de credencial tira la conexión cacheada y el
  98. // backoff del host: la siguiente llamada reconecta con el valor nuevo, sin
  99. // esperar el enfriamiento de un fallo ya resuelto.
  100. func (p *SSHPool) SetPassword(host, user, password string) {
  101. p.mu.Lock()
  102. defer p.mu.Unlock()
  103. old, had := p.creds[host]
  104. if password == "" {
  105. if !had {
  106. return
  107. }
  108. delete(p.creds, host)
  109. } else {
  110. if had && old.user == user && old.password == password {
  111. return
  112. }
  113. if p.creds == nil {
  114. p.creds = map[string]sshCred{}
  115. }
  116. p.creds[host] = sshCred{user: user, password: password}
  117. }
  118. if e := p.conns[host]; e != nil {
  119. if e.client != nil {
  120. _ = p.closeSSHClient(e.client)
  121. e.client = nil
  122. }
  123. e.failures = 0
  124. e.notUntil = time.Time{}
  125. }
  126. }
  127. // hostKeyCallback implementa accept-new sobre el known_hosts propio.
  128. func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
  129. if _, err := os.Stat(p.khPath); os.IsNotExist(err) {
  130. if err := os.MkdirAll(filepath.Dir(p.khPath), 0o700); err == nil {
  131. _ = os.WriteFile(p.khPath, nil, 0o600)
  132. }
  133. }
  134. checker, err := knownhosts.New(p.khPath)
  135. if err != nil {
  136. return nil, err
  137. }
  138. return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  139. err := checker(hostname, remote, key)
  140. if err == nil {
  141. return nil
  142. }
  143. var keyErr *knownhosts.KeyError
  144. if errors.As(err, &keyErr) && len(keyErr.Want) > 0 {
  145. // Clave cambiada (#603): NO se auto-acepta. Una clave distinta en
  146. // un host ya conocido es un evento de seguridad (posible MITM);
  147. // el operador debe confirmar el re-onboard explícitamente tras
  148. // verificar fuera de banda (p. ej. tras un flash del router). El
  149. // error tipado alimenta el estado "host key changed" del router.
  150. oldFP := ""
  151. if len(keyErr.Want) > 0 {
  152. oldFP = ssh.FingerprintSHA256(keyErr.Want[0].Key)
  153. }
  154. newFP := ssh.FingerprintSHA256(key)
  155. log.Printf("ssh %s: host key changed (%s -> %s); re-onboard requerido", hostname, oldFP, newFP)
  156. return &HostKeyChangedError{Host: hostname, OldFP: oldFP, NewFP: newFP}
  157. }
  158. // Host desconocido → accept-new
  159. line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
  160. f, ferr := os.OpenFile(p.khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
  161. if ferr != nil {
  162. return ferr
  163. }
  164. defer f.Close()
  165. _, ferr = f.WriteString(line + "\n")
  166. return ferr
  167. }, nil
  168. }
  169. // HostKeyChangedError: el host presenta una clave distinta a la registrada en
  170. // known_hosts. No se auto-acepta: la conexión se rechaza hasta que el admin
  171. // confirme el re-onboard (RemoveHostKey + siguiente sondeo hace TOFU).
  172. type HostKeyChangedError struct {
  173. Host string
  174. OldFP string
  175. NewFP string
  176. }
  177. func (e *HostKeyChangedError) Error() string {
  178. return "ssh host key changed for " + e.Host + " (" + e.OldFP + " -> " + e.NewFP + "); re-onboard required"
  179. }
  180. // SSHAuthError: el host rechazó la autenticación SSH (contraseña o llave
  181. // rechazadas por el servidor). Va con código de error propio en la API
  182. // (ssh_auth_failed, #1708) para que la UI pida revisar la contraseña en vez
  183. // de un fallo genérico de conexión.
  184. type SSHAuthError struct {
  185. Host string
  186. Err error
  187. }
  188. func (e *SSHAuthError) Error() string {
  189. return "ssh " + e.Host + ": authentication rejected: " + e.Err.Error()
  190. }
  191. func (e *SSHAuthError) Unwrap() error { return e.Err }
  192. // isSSHAuthError reconoce el rechazo de autenticación del handshake. La
  193. // librería no exporta un tipo para esto y el texto es estable en x/crypto
  194. // ("ssh: unable to authenticate, attempted methods ...").
  195. func isSSHAuthError(err error) bool {
  196. return err != nil && strings.Contains(err.Error(), "ssh: unable to authenticate")
  197. }
  198. // RemoveHostKey elimina las entradas known_hosts de un host (confirmación de
  199. // re-onboard #603). Quita las líneas previas de ese host (la lista de hosts
  200. // de una línea puede ser separada por comas); el siguiente sondeo la vuelve a
  201. // registrar con TOFU.
  202. // Los candidatos son varias formas del mismo destino (#1524): la dirección
  203. // SSH completa (SSHAddr, que Normalize convierte a [host]:puerto en puertos
  204. // no estándar) y el host pelado, porque entradas anteriores a un cambio de
  205. // puerto pueden vivir sin él. Normalizar cada campo de la línea evita depender
  206. // de cómo se escribió cada entrada.
  207. func (p *SSHPool) RemoveHostKey(hostnames ...string) error {
  208. norms := make(map[string]bool, len(hostnames))
  209. for _, h := range hostnames {
  210. if h == "" {
  211. continue
  212. }
  213. norms[knownhosts.Normalize(h)] = true
  214. }
  215. var keep []string
  216. if data, err := os.ReadFile(p.khPath); err == nil {
  217. for _, ln := range strings.Split(string(data), "\n") {
  218. if strings.TrimSpace(ln) == "" {
  219. continue
  220. }
  221. fields := strings.Fields(ln)
  222. if len(fields) == 0 {
  223. continue
  224. }
  225. drop := false
  226. for _, h := range strings.Split(fields[0], ",") {
  227. if norms[knownhosts.Normalize(h)] {
  228. drop = true
  229. break
  230. }
  231. }
  232. if !drop {
  233. keep = append(keep, ln)
  234. }
  235. }
  236. }
  237. return os.WriteFile(p.khPath, []byte(strings.Join(keep, "\n")+"\n"), 0o600)
  238. }
  239. // dial abre (o reabre) la conexión a un host respetando el backoff.
  240. // Single-flight por host: dos llamantes concurrentes comparten el mismo dial.
  241. func (p *SSHPool) dial(host string) (*ssh.Client, error) {
  242. p.mu.Lock()
  243. if p.closed {
  244. p.mu.Unlock()
  245. return nil, errors.New("ssh pool closed")
  246. }
  247. entry := p.conns[host]
  248. if entry == nil {
  249. entry = &sshConn{}
  250. p.conns[host] = entry
  251. }
  252. if entry.client != nil {
  253. c := entry.client
  254. p.mu.Unlock()
  255. return c, nil
  256. }
  257. if entry.dialing != nil {
  258. ch := entry.dialing
  259. p.mu.Unlock()
  260. <-ch
  261. p.mu.Lock()
  262. if entry.client != nil {
  263. c := entry.client
  264. p.mu.Unlock()
  265. return c, nil
  266. }
  267. p.mu.Unlock()
  268. return nil, errors.New("ssh dial failed")
  269. }
  270. if time.Now().Before(entry.notUntil) {
  271. p.mu.Unlock()
  272. return nil, fmt.Errorf("ssh %s: en backoff tras %d fallos", host, entry.failures)
  273. }
  274. entry.dialing = make(chan struct{})
  275. p.mu.Unlock()
  276. cb, err := p.hostKeyCallback()
  277. if err != nil {
  278. p.mu.Lock()
  279. close(entry.dialing)
  280. entry.dialing = nil
  281. p.mu.Unlock()
  282. return nil, err
  283. }
  284. // Credencial registrada para este host (#1708): contraseña con el
  285. // usuario de la integración en vez de la llave del servidor. Se lee bajo
  286. // lock para no competir con SetPassword.
  287. p.mu.Lock()
  288. cred, hasCred := p.creds[host]
  289. p.mu.Unlock()
  290. cfg := &ssh.ClientConfig{
  291. User: "root",
  292. Auth: []ssh.AuthMethod{ssh.PublicKeys(p.signer)},
  293. HostKeyCallback: cb,
  294. Timeout: sshDialTimeout,
  295. }
  296. if hasCred {
  297. cfg.User = cred.user
  298. cfg.Auth = []ssh.AuthMethod{ssh.Password(cred.password)}
  299. }
  300. client, err := p.dialTCP("tcp", addrOf(host), cfg)
  301. p.mu.Lock()
  302. close(entry.dialing)
  303. entry.dialing = nil
  304. if err != nil {
  305. entry.failures++
  306. backoff := sshBackoffBase << min(entry.failures-1, 4)
  307. if backoff > sshBackoffMax {
  308. backoff = sshBackoffMax
  309. }
  310. entry.notUntil = time.Now().Add(backoff)
  311. p.mu.Unlock()
  312. if isSSHAuthError(err) {
  313. return nil, &SSHAuthError{Host: host, Err: err}
  314. }
  315. return nil, fmt.Errorf("ssh %s: %w", host, err)
  316. }
  317. if p.closed {
  318. p.mu.Unlock()
  319. _ = p.closeSSHClient(client)
  320. return nil, errors.New("ssh pool closed")
  321. }
  322. entry.client = client
  323. entry.failures = 0
  324. entry.notUntil = time.Time{}
  325. p.mu.Unlock()
  326. return client, nil
  327. }
  328. // drop invalida la conexión de un host (la próxima llamada rediala).
  329. func (p *SSHPool) drop(host string) {
  330. p.mu.Lock()
  331. defer p.mu.Unlock()
  332. if e := p.conns[host]; e != nil && e.client != nil {
  333. _ = p.closeSSHClient(e.client)
  334. e.client = nil
  335. }
  336. }
  337. // Run ejecuta cmd en host con timeout (por defecto 5 s, como el JS).
  338. // Una sesión fallida por canal roto invalida la conexión (reconexión).
  339. func (p *SSHPool) Run(host, cmd string, timeout time.Duration) (string, error) {
  340. if timeout <= 0 {
  341. timeout = sshDefaultTimeout
  342. }
  343. client, err := p.dial(host)
  344. if err != nil {
  345. return "", err
  346. }
  347. session, err := client.NewSession()
  348. if err != nil {
  349. p.drop(host)
  350. return "", fmt.Errorf("ssh %s: session: %w", host, err)
  351. }
  352. defer session.Close()
  353. type result struct {
  354. out []byte
  355. err error
  356. }
  357. ch := make(chan result, 1)
  358. go func() {
  359. out, err := session.Output(cmd)
  360. ch <- result{out, err}
  361. }()
  362. select {
  363. case res := <-ch:
  364. if res.err != nil {
  365. var ee *ssh.ExitError
  366. if !errors.As(res.err, &ee) {
  367. p.drop(host) // canal roto, no exit status
  368. }
  369. return "", fmt.Errorf("ssh %s: %w", host, res.err)
  370. }
  371. return string(res.out), nil
  372. case <-time.After(timeout):
  373. // Timeout: cerrar solo la sesión. NO dropear el cliente entero: el
  374. // pool permite sesiones concurrentes sobre el mismo router y un
  375. // comando lento no debe cortar las demás (issue #205).
  376. _ = session.Close()
  377. return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
  378. }
  379. }
  380. // RunCtx es Run con cancelación por contexto.
  381. func (p *SSHPool) RunCtx(ctx context.Context, host, cmd string, timeout time.Duration) (string, error) {
  382. if timeout <= 0 {
  383. timeout = sshDefaultTimeout
  384. }
  385. client, err := p.dial(host)
  386. if err != nil {
  387. return "", err
  388. }
  389. session, err := client.NewSession()
  390. if err != nil {
  391. p.drop(host)
  392. return "", fmt.Errorf("ssh %s: session: %w", host, err)
  393. }
  394. defer session.Close()
  395. type result struct {
  396. out []byte
  397. err error
  398. }
  399. ch := make(chan result, 1)
  400. go func() {
  401. out, err := session.Output(cmd)
  402. ch <- result{out, err}
  403. }()
  404. select {
  405. case res := <-ch:
  406. if res.err != nil {
  407. var ee *ssh.ExitError
  408. if !errors.As(res.err, &ee) {
  409. p.drop(host) // canal roto, no exit status
  410. }
  411. return "", fmt.Errorf("ssh %s: %w", host, res.err)
  412. }
  413. return string(res.out), nil
  414. case <-time.After(timeout):
  415. _ = session.Close()
  416. return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
  417. case <-ctx.Done():
  418. // Cancelación del cliente: cerrar la sesión para abortar el comando
  419. // remoto y liberar la goroutine (issue #204). Sin drop: es una
  420. // cancelación del llamador, no un fallo de la conexión.
  421. _ = session.Close()
  422. return "", ctx.Err()
  423. }
  424. }
  425. // Close cierra todas las conexiones del pool.
  426. func (p *SSHPool) Close() {
  427. p.mu.Lock()
  428. defer p.mu.Unlock()
  429. if p.closed {
  430. return
  431. }
  432. p.closed = true
  433. for _, e := range p.conns {
  434. if e.client != nil {
  435. _ = p.closeSSHClient(e.client)
  436. e.client = nil
  437. }
  438. }
  439. }
  440. func min(a, b int) int {
  441. if a < b {
  442. return a
  443. }
  444. return b
  445. }