sshpool.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. "io"
  15. "log"
  16. "net"
  17. "os"
  18. "path/filepath"
  19. "strings"
  20. "sync"
  21. "time"
  22. "github.com/gnacho/netpulse/server-go/internal/sshkey"
  23. "golang.org/x/crypto/ssh"
  24. "golang.org/x/crypto/ssh/knownhosts"
  25. )
  26. const (
  27. sshDialTimeout = 4 * time.Second // ConnectTimeout=4 del JS
  28. sshDefaultTimeout = 5 * time.Second // SSH_TIMEOUT_MS del JS
  29. sshBackoffBase = 30 * time.Second
  30. sshBackoffMax = 5 * time.Minute
  31. )
  32. // addrOf devuelve el destino `host:port` para conectar. Los callers pasan el
  33. // host ya con puerto (RouterConfig.SSHAddr, issue #605); si vienen sin puerto
  34. // (back-compat) se asume 22.
  35. func addrOf(host string) string {
  36. if _, _, err := net.SplitHostPort(host); err == nil {
  37. return host
  38. }
  39. return net.JoinHostPort(host, "22")
  40. }
  41. // SSHPool gestiona conexiones persistentes a los routers.
  42. type SSHPool struct {
  43. keyPath string
  44. signer ssh.Signer
  45. khPath string
  46. mu sync.Mutex
  47. conns map[string]*sshConn
  48. creds map[string]sshCred
  49. closed bool
  50. dialTCP func(network, addr string, config *ssh.ClientConfig) (*ssh.Client, error)
  51. closeClient func(*ssh.Client) error
  52. }
  53. // sshCred es la credencial de contraseña registrada para un host
  54. // (#1708): las integraciones ssh con fichero compañero <slug>.sshpass
  55. // conectan por contraseña mientras la credencial esté registrada; el resto
  56. // de destinos siguen con la llave del servidor.
  57. type sshCred struct {
  58. user string
  59. password string
  60. }
  61. func (p *SSHPool) closeSSHClient(c *ssh.Client) error {
  62. if c == nil {
  63. return nil
  64. }
  65. if p.closeClient != nil {
  66. return p.closeClient(c)
  67. }
  68. return c.Close()
  69. }
  70. type sshConn struct {
  71. client *ssh.Client
  72. dialing chan struct{}
  73. failures int
  74. notUntil time.Time
  75. }
  76. // NewSSHPool crea el pool cargando la clave privada (ed25519 sin passphrase).
  77. func NewSSHPool(keyPath string) (*SSHPool, error) {
  78. pem, err := os.ReadFile(keyPath)
  79. if err != nil {
  80. return nil, fmt.Errorf("leer clave SSH: %w", err)
  81. }
  82. signer, err := ssh.ParsePrivateKey(pem)
  83. if err != nil {
  84. return nil, fmt.Errorf("parsear clave SSH: %w", err)
  85. }
  86. return &SSHPool{
  87. keyPath: keyPath,
  88. signer: signer,
  89. khPath: sshkey.KnownHostsPath(keyPath),
  90. conns: map[string]*sshConn{},
  91. creds: map[string]sshCred{},
  92. dialTCP: ssh.Dial,
  93. }, nil
  94. }
  95. // SetPassword registra (o borra, con password vacía) la credencial de
  96. // contraseña de un host (#1708). Mientras haya credencial, el dial de ese
  97. // host autentica por contraseña con el usuario dado y la llave del servidor
  98. // queda aparcada. Un cambio de credencial tira la conexión cacheada y el
  99. // backoff del host: la siguiente llamada reconecta con el valor nuevo, sin
  100. // esperar el enfriamiento de un fallo ya resuelto.
  101. func (p *SSHPool) SetPassword(host, user, password string) {
  102. p.mu.Lock()
  103. defer p.mu.Unlock()
  104. old, had := p.creds[host]
  105. if password == "" {
  106. if !had {
  107. return
  108. }
  109. delete(p.creds, host)
  110. } else {
  111. if had && old.user == user && old.password == password {
  112. return
  113. }
  114. if p.creds == nil {
  115. p.creds = map[string]sshCred{}
  116. }
  117. p.creds[host] = sshCred{user: user, password: password}
  118. }
  119. if e := p.conns[host]; e != nil {
  120. if e.client != nil {
  121. _ = p.closeSSHClient(e.client)
  122. e.client = nil
  123. }
  124. e.failures = 0
  125. e.notUntil = time.Time{}
  126. }
  127. }
  128. // hostKeyCallback implementa accept-new sobre el known_hosts propio.
  129. func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
  130. if _, err := os.Stat(p.khPath); os.IsNotExist(err) {
  131. if err := os.MkdirAll(filepath.Dir(p.khPath), 0o700); err == nil {
  132. _ = os.WriteFile(p.khPath, nil, 0o600)
  133. }
  134. }
  135. checker, err := knownhosts.New(p.khPath)
  136. if err != nil {
  137. return nil, err
  138. }
  139. return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  140. err := checker(hostname, remote, key)
  141. if err == nil {
  142. return nil
  143. }
  144. var keyErr *knownhosts.KeyError
  145. if errors.As(err, &keyErr) && len(keyErr.Want) > 0 {
  146. // Clave cambiada (#603): NO se auto-acepta. Una clave distinta en
  147. // un host ya conocido es un evento de seguridad (posible MITM);
  148. // el operador debe confirmar el re-onboard explícitamente tras
  149. // verificar fuera de banda (p. ej. tras un flash del router). El
  150. // error tipado alimenta el estado "host key changed" del router.
  151. oldFP := ""
  152. if len(keyErr.Want) > 0 {
  153. oldFP = ssh.FingerprintSHA256(keyErr.Want[0].Key)
  154. }
  155. newFP := ssh.FingerprintSHA256(key)
  156. log.Printf("ssh %s: host key changed (%s -> %s); re-onboard requerido", hostname, oldFP, newFP)
  157. return &HostKeyChangedError{Host: hostname, OldFP: oldFP, NewFP: newFP}
  158. }
  159. // Host desconocido → accept-new
  160. line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
  161. f, ferr := os.OpenFile(p.khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
  162. if ferr != nil {
  163. return ferr
  164. }
  165. defer f.Close()
  166. _, ferr = f.WriteString(line + "\n")
  167. return ferr
  168. }, nil
  169. }
  170. // HostKeyChangedError: el host presenta una clave distinta a la registrada en
  171. // known_hosts. No se auto-acepta: la conexión se rechaza hasta que el admin
  172. // confirme el re-onboard (RemoveHostKey + siguiente sondeo hace TOFU).
  173. type HostKeyChangedError struct {
  174. Host string
  175. OldFP string
  176. NewFP string
  177. }
  178. func (e *HostKeyChangedError) Error() string {
  179. return "ssh host key changed for " + e.Host + " (" + e.OldFP + " -> " + e.NewFP + "); re-onboard required"
  180. }
  181. // SSHAuthError: el host rechazó la autenticación SSH (contraseña o llave
  182. // rechazadas por el servidor). Va con código de error propio en la API
  183. // (ssh_auth_failed, #1708) para que la UI pida revisar la contraseña en vez
  184. // de un fallo genérico de conexión.
  185. type SSHAuthError struct {
  186. Host string
  187. Err error
  188. }
  189. func (e *SSHAuthError) Error() string {
  190. return "ssh " + e.Host + ": authentication rejected: " + e.Err.Error()
  191. }
  192. func (e *SSHAuthError) Unwrap() error { return e.Err }
  193. // isSSHAuthError reconoce el rechazo de autenticación del handshake. La
  194. // librería no exporta un tipo para esto y el texto es estable en x/crypto
  195. // ("ssh: unable to authenticate, attempted methods ...").
  196. func isSSHAuthError(err error) bool {
  197. return err != nil && strings.Contains(err.Error(), "ssh: unable to authenticate")
  198. }
  199. // RemoveHostKey elimina las entradas known_hosts de un host (confirmación de
  200. // re-onboard #603). Quita las líneas previas de ese host (la lista de hosts
  201. // de una línea puede ser separada por comas); el siguiente sondeo la vuelve a
  202. // registrar con TOFU.
  203. // Los candidatos son varias formas del mismo destino (#1524): la dirección
  204. // SSH completa (SSHAddr, que Normalize convierte a [host]:puerto en puertos
  205. // no estándar) y el host pelado, porque entradas anteriores a un cambio de
  206. // puerto pueden vivir sin él. Normalizar cada campo de la línea evita depender
  207. // de cómo se escribió cada entrada.
  208. func (p *SSHPool) RemoveHostKey(hostnames ...string) error {
  209. norms := make(map[string]bool, len(hostnames))
  210. for _, h := range hostnames {
  211. if h == "" {
  212. continue
  213. }
  214. norms[knownhosts.Normalize(h)] = true
  215. }
  216. var keep []string
  217. if data, err := os.ReadFile(p.khPath); err == nil {
  218. for _, ln := range strings.Split(string(data), "\n") {
  219. if strings.TrimSpace(ln) == "" {
  220. continue
  221. }
  222. fields := strings.Fields(ln)
  223. if len(fields) == 0 {
  224. continue
  225. }
  226. drop := false
  227. for _, h := range strings.Split(fields[0], ",") {
  228. if norms[knownhosts.Normalize(h)] {
  229. drop = true
  230. break
  231. }
  232. }
  233. if !drop {
  234. keep = append(keep, ln)
  235. }
  236. }
  237. }
  238. return os.WriteFile(p.khPath, []byte(strings.Join(keep, "\n")+"\n"), 0o600)
  239. }
  240. // dial abre (o reabre) la conexión a un host respetando el backoff.
  241. // Single-flight por host: dos llamantes concurrentes comparten el mismo dial.
  242. func (p *SSHPool) dial(host string) (*ssh.Client, error) {
  243. p.mu.Lock()
  244. if p.closed {
  245. p.mu.Unlock()
  246. return nil, errors.New("ssh pool closed")
  247. }
  248. entry := p.conns[host]
  249. if entry == nil {
  250. entry = &sshConn{}
  251. p.conns[host] = entry
  252. }
  253. if entry.client != nil {
  254. c := entry.client
  255. p.mu.Unlock()
  256. return c, nil
  257. }
  258. if entry.dialing != nil {
  259. ch := entry.dialing
  260. p.mu.Unlock()
  261. <-ch
  262. p.mu.Lock()
  263. if entry.client != nil {
  264. c := entry.client
  265. p.mu.Unlock()
  266. return c, nil
  267. }
  268. p.mu.Unlock()
  269. return nil, errors.New("ssh dial failed")
  270. }
  271. if time.Now().Before(entry.notUntil) {
  272. p.mu.Unlock()
  273. return nil, fmt.Errorf("ssh %s: en backoff tras %d fallos", host, entry.failures)
  274. }
  275. entry.dialing = make(chan struct{})
  276. p.mu.Unlock()
  277. cb, err := p.hostKeyCallback()
  278. if err != nil {
  279. p.mu.Lock()
  280. close(entry.dialing)
  281. entry.dialing = nil
  282. p.mu.Unlock()
  283. return nil, err
  284. }
  285. // Credencial registrada para este host (#1708): contraseña con el
  286. // usuario de la integración en vez de la llave del servidor. Se lee bajo
  287. // lock para no competir con SetPassword.
  288. p.mu.Lock()
  289. cred, hasCred := p.creds[host]
  290. p.mu.Unlock()
  291. cfg := &ssh.ClientConfig{
  292. User: "root",
  293. Auth: []ssh.AuthMethod{ssh.PublicKeys(p.signer)},
  294. HostKeyCallback: cb,
  295. Timeout: sshDialTimeout,
  296. }
  297. if hasCred {
  298. cfg.User = cred.user
  299. cfg.Auth = []ssh.AuthMethod{ssh.Password(cred.password)}
  300. }
  301. client, err := p.dialTCP("tcp", addrOf(host), cfg)
  302. p.mu.Lock()
  303. close(entry.dialing)
  304. entry.dialing = nil
  305. if err != nil {
  306. entry.failures++
  307. backoff := sshBackoffBase << min(entry.failures-1, 4)
  308. if backoff > sshBackoffMax {
  309. backoff = sshBackoffMax
  310. }
  311. entry.notUntil = time.Now().Add(backoff)
  312. // #1893: un "Exit before auth" en dropbear no se podía cruzar con nada,
  313. // porque el server no decía a qué host llamaba ni por qué fallaba. El
  314. // motivo real (host key, auth, timeout, red) va al log del sistema con
  315. // el host y el número de fallos; se registra el primero y cada diez
  316. // para que una unidad apagada no sature el journal.
  317. if entry.failures == 1 || entry.failures%10 == 0 {
  318. log.Printf("[netpulse:ssh] dial %s (user=%s): %v (fallo %d, backoff %s)", host, cfg.User, err, entry.failures, backoff)
  319. }
  320. p.mu.Unlock()
  321. if isSSHAuthError(err) {
  322. return nil, &SSHAuthError{Host: host, Err: err}
  323. }
  324. return nil, fmt.Errorf("ssh %s: %w", host, err)
  325. }
  326. if p.closed {
  327. p.mu.Unlock()
  328. _ = p.closeSSHClient(client)
  329. return nil, errors.New("ssh pool closed")
  330. }
  331. // #1893: toda conexión NUEVA queda registrada. Si algo está marcando el
  332. // ciclo de sondeo con conexiones que mueren antes de autenticar, aquí se
  333. // ve el ritmo real de dials por host en vez de suponerlo.
  334. if entry.failures > 0 {
  335. log.Printf("[netpulse:ssh] %s: conexión recuperada tras %d fallos de dial", host, entry.failures)
  336. }
  337. log.Printf("[netpulse:ssh] %s: nueva conexión establecida (user=%s)", host, cfg.User)
  338. entry.client = client
  339. entry.failures = 0
  340. entry.notUntil = time.Time{}
  341. p.mu.Unlock()
  342. return client, nil
  343. }
  344. // drop invalida la conexión de un host (la próxima llamada rediala).
  345. func (p *SSHPool) drop(host string) {
  346. p.mu.Lock()
  347. defer p.mu.Unlock()
  348. if e := p.conns[host]; e != nil && e.client != nil {
  349. // #1893: el descarte explica la reconexión siguiente; sin esta línea un
  350. // dial nuevo no se puede distinguir de una fuga de conexiones.
  351. log.Printf("[netpulse:ssh] %s: conexión descartada, el próximo comando rediala", host)
  352. _ = p.closeSSHClient(e.client)
  353. e.client = nil
  354. }
  355. }
  356. // sshErrDetail (#1737) saca el motivo real de un comando remoto fallido.
  357. // session.Output descarta el stderr salvo que se le de un destino, y antes se
  358. // tiraba: un reinstall fallido solo decia "Process exited with status 1" y el
  359. // motivo (curl, wget, uci) se quedaba en el router. Se devuelve la ULTIMA
  360. // linea no vacia y recortada, que es la que explica el fallo sin arrastrar el
  361. // ruido del script entero.
  362. // mergeScriptOutput junta stdout y stderr en el orden en que se leen: primero
  363. // lo que el script escribio a la salida normal, despues sus avisos. El journal
  364. // y la caja de la UI enseñan este texto tal cual (#1894).
  365. func mergeScriptOutput(stdout, stderr string) string {
  366. if stderr == "" {
  367. return stdout
  368. }
  369. if stdout != "" && !strings.HasSuffix(stdout, "\n") {
  370. stdout += "\n"
  371. }
  372. return stdout + stderr
  373. }
  374. func sshErrDetail(stderr string) string {
  375. if stderr == "" {
  376. return ""
  377. }
  378. lines := strings.Split(strings.TrimRight(stderr, "\n"), "\n")
  379. for i := len(lines) - 1; i >= 0; i-- {
  380. line := strings.TrimSpace(lines[i])
  381. if line == "" {
  382. continue
  383. }
  384. if len(line) > 300 {
  385. line = line[:300] + "..."
  386. }
  387. return line
  388. }
  389. return ""
  390. }
  391. // Run ejecuta cmd en host con timeout (por defecto 5 s, como el JS).
  392. // Una sesión fallida por canal roto invalida la conexión (reconexión).
  393. func (p *SSHPool) Run(host, cmd string, timeout time.Duration) (string, error) {
  394. return p.run(host, cmd, nil, timeout, false)
  395. }
  396. // RunScript ejecuta un script POSIX por stdin con `sh -s` (#1737). Dropbear
  397. // limita el tamaño de cada string del paquete a MAX_CMD_LEN (9000 bytes) y
  398. // aborta la conexión con "String too long": el cliente SSH solo ve EOF, sin
  399. // exit status ni stderr. El script de reinstalación pasa de 14 KB por argv, así
  400. // que el comando completo viaja por stdin y en argv solo va `sh -s`.
  401. // #1894: el script de reinstalación cuenta todo lo que hace por stderr
  402. // (`warn()` y los `echo ... >&2`), y el pool devolvía solo stdout. Con
  403. // mergeStderr la salida que viaja al journal y a la UI lleva las dos, y se
  404. // devuelve también cuando el script falla: es justo cuando hace falta.
  405. func (p *SSHPool) RunScript(host, script string, timeout time.Duration) (string, error) {
  406. return p.run(host, "sh -s", strings.NewReader(script), timeout, true)
  407. }
  408. // run abre una sesión, ejecuta cmd (alimentando stdin si no es nil) y devuelve
  409. // stdout. Comparte el manejo de stderr, drop por canal roto y timeout entre
  410. // Run y RunScript.
  411. func (p *SSHPool) run(host, cmd string, stdin io.Reader, timeout time.Duration, mergeStderr bool) (string, error) {
  412. if timeout <= 0 {
  413. timeout = sshDefaultTimeout
  414. }
  415. client, err := p.dial(host)
  416. if err != nil {
  417. return "", err
  418. }
  419. session, err := client.NewSession()
  420. if err != nil {
  421. p.drop(host)
  422. return "", fmt.Errorf("ssh %s: session: %w", host, err)
  423. }
  424. defer session.Close()
  425. session.Stdin = stdin
  426. type result struct {
  427. out []byte
  428. err error
  429. stderr string
  430. }
  431. ch := make(chan result, 1)
  432. go func() {
  433. var errBuf strings.Builder
  434. session.Stderr = &errBuf
  435. out, err := session.Output(cmd)
  436. ch <- result{out, err, errBuf.String()}
  437. }()
  438. select {
  439. case res := <-ch:
  440. body := string(res.out)
  441. if mergeStderr {
  442. body = mergeScriptOutput(body, res.stderr)
  443. }
  444. if res.err != nil {
  445. var ee *ssh.ExitError
  446. if !errors.As(res.err, &ee) {
  447. p.drop(host) // canal roto, no exit status
  448. }
  449. // #1894: la salida se devuelve aunque el comando falle. Antes se
  450. // tiraba, y con ella el motivo real del fallo.
  451. if msg := sshErrDetail(res.stderr); msg != "" {
  452. return body, fmt.Errorf("ssh %s: %w: %s", host, res.err, msg)
  453. }
  454. return body, fmt.Errorf("ssh %s: %w", host, res.err)
  455. }
  456. return body, nil
  457. case <-time.After(timeout):
  458. // Timeout: cerrar solo la sesión. NO dropear el cliente entero: el
  459. // pool permite sesiones concurrentes sobre el mismo router y un
  460. // comando lento no debe cortar las demás (issue #205).
  461. _ = session.Close()
  462. return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
  463. }
  464. }
  465. // RunCtx es Run con cancelación por contexto.
  466. func (p *SSHPool) RunCtx(ctx context.Context, host, cmd string, timeout time.Duration) (string, error) {
  467. if timeout <= 0 {
  468. timeout = sshDefaultTimeout
  469. }
  470. client, err := p.dial(host)
  471. if err != nil {
  472. return "", err
  473. }
  474. session, err := client.NewSession()
  475. if err != nil {
  476. p.drop(host)
  477. return "", fmt.Errorf("ssh %s: session: %w", host, err)
  478. }
  479. defer session.Close()
  480. type result struct {
  481. out []byte
  482. err error
  483. stderr string
  484. }
  485. ch := make(chan result, 1)
  486. go func() {
  487. var errBuf strings.Builder
  488. session.Stderr = &errBuf
  489. out, err := session.Output(cmd)
  490. ch <- result{out, err, errBuf.String()}
  491. }()
  492. select {
  493. case res := <-ch:
  494. if res.err != nil {
  495. var ee *ssh.ExitError
  496. if !errors.As(res.err, &ee) {
  497. p.drop(host) // canal roto, no exit status
  498. }
  499. // #1894: misma razón que en run(), la salida vuelve con el error.
  500. if msg := sshErrDetail(res.stderr); msg != "" {
  501. return string(res.out), fmt.Errorf("ssh %s: %w: %s", host, res.err, msg)
  502. }
  503. return string(res.out), fmt.Errorf("ssh %s: %w", host, res.err)
  504. }
  505. return string(res.out), nil
  506. case <-time.After(timeout):
  507. _ = session.Close()
  508. return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
  509. case <-ctx.Done():
  510. // Cancelación del cliente: cerrar la sesión para abortar el comando
  511. // remoto y liberar la goroutine (issue #204). Sin drop: es una
  512. // cancelación del llamador, no un fallo de la conexión.
  513. _ = session.Close()
  514. return "", ctx.Err()
  515. }
  516. }
  517. // Close cierra todas las conexiones del pool.
  518. func (p *SSHPool) Close() {
  519. p.mu.Lock()
  520. defer p.mu.Unlock()
  521. if p.closed {
  522. return
  523. }
  524. p.closed = true
  525. for _, e := range p.conns {
  526. if e.client != nil {
  527. _ = p.closeSSHClient(e.client)
  528. e.client = nil
  529. }
  530. }
  531. }
  532. func min(a, b int) int {
  533. if a < b {
  534. return a
  535. }
  536. return b
  537. }