sshpool.go 18 KB

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