sshpool.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. "net"
  15. "os"
  16. "path/filepath"
  17. "sync"
  18. "time"
  19. "github.com/gnacho/netpulse/server-go/internal/sshkey"
  20. "golang.org/x/crypto/ssh"
  21. "golang.org/x/crypto/ssh/knownhosts"
  22. )
  23. const (
  24. sshDialTimeout = 4 * time.Second // ConnectTimeout=4 del JS
  25. sshDefaultTimeout = 5 * time.Second // SSH_TIMEOUT_MS del JS
  26. sshBackoffBase = 30 * time.Second
  27. sshBackoffMax = 5 * time.Minute
  28. )
  29. // SSHPool gestiona conexiones persistentes a los routers.
  30. type SSHPool struct {
  31. keyPath string
  32. signer ssh.Signer
  33. khPath string
  34. mu sync.Mutex
  35. conns map[string]*sshConn
  36. closed bool
  37. }
  38. type sshConn struct {
  39. client *ssh.Client
  40. failures int
  41. notUntil time.Time
  42. }
  43. // NewSSHPool crea el pool cargando la clave privada (ed25519 sin passphrase).
  44. func NewSSHPool(keyPath string) (*SSHPool, error) {
  45. pem, err := os.ReadFile(keyPath)
  46. if err != nil {
  47. return nil, fmt.Errorf("leer clave SSH: %w", err)
  48. }
  49. signer, err := ssh.ParsePrivateKey(pem)
  50. if err != nil {
  51. return nil, fmt.Errorf("parsear clave SSH: %w", err)
  52. }
  53. return &SSHPool{
  54. keyPath: keyPath,
  55. signer: signer,
  56. khPath: sshkey.KnownHostsPath(keyPath),
  57. conns: map[string]*sshConn{},
  58. }, nil
  59. }
  60. // hostKeyCallback implementa accept-new sobre el known_hosts propio.
  61. func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
  62. if _, err := os.Stat(p.khPath); os.IsNotExist(err) {
  63. if err := os.MkdirAll(filepath.Dir(p.khPath), 0o700); err == nil {
  64. _ = os.WriteFile(p.khPath, nil, 0o600)
  65. }
  66. }
  67. checker, err := knownhosts.New(p.khPath)
  68. if err != nil {
  69. return nil, err
  70. }
  71. return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  72. err := checker(hostname, remote, key)
  73. if err == nil {
  74. return nil
  75. }
  76. var keyErr *knownhosts.KeyError
  77. if errors.As(err, &keyErr) && len(keyErr.Want) > 0 {
  78. return err // clave CAMBIADA → rechazar
  79. }
  80. // Host desconocido → accept-new
  81. line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
  82. f, ferr := os.OpenFile(p.khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
  83. if ferr != nil {
  84. return ferr
  85. }
  86. defer f.Close()
  87. _, ferr = f.WriteString(line + "\n")
  88. return ferr
  89. }, nil
  90. }
  91. // dial abre (o reabre) la conexión a un host respetando el backoff.
  92. func (p *SSHPool) dial(host string) (*ssh.Client, error) {
  93. p.mu.Lock()
  94. entry := p.conns[host]
  95. if entry == nil {
  96. entry = &sshConn{}
  97. p.conns[host] = entry
  98. }
  99. if entry.client != nil {
  100. c := entry.client
  101. p.mu.Unlock()
  102. return c, nil
  103. }
  104. if time.Now().Before(entry.notUntil) {
  105. p.mu.Unlock()
  106. return nil, fmt.Errorf("ssh %s: en backoff tras %d fallos", host, entry.failures)
  107. }
  108. p.mu.Unlock()
  109. cb, err := p.hostKeyCallback()
  110. if err != nil {
  111. return nil, err
  112. }
  113. cfg := &ssh.ClientConfig{
  114. User: "root",
  115. Auth: []ssh.AuthMethod{ssh.PublicKeys(p.signer)},
  116. HostKeyCallback: cb,
  117. Timeout: sshDialTimeout,
  118. }
  119. client, err := ssh.Dial("tcp", net.JoinHostPort(host, "22"), cfg)
  120. p.mu.Lock()
  121. defer p.mu.Unlock()
  122. if err != nil {
  123. entry.failures++
  124. backoff := sshBackoffBase << min(entry.failures-1, 4)
  125. if backoff > sshBackoffMax {
  126. backoff = sshBackoffMax
  127. }
  128. entry.notUntil = time.Now().Add(backoff)
  129. return nil, fmt.Errorf("ssh %s: %w", host, err)
  130. }
  131. entry.client = client
  132. entry.failures = 0
  133. entry.notUntil = time.Time{}
  134. return client, nil
  135. }
  136. // drop invalida la conexión de un host (la próxima llamada rediala).
  137. func (p *SSHPool) drop(host string) {
  138. p.mu.Lock()
  139. defer p.mu.Unlock()
  140. if e := p.conns[host]; e != nil && e.client != nil {
  141. _ = e.client.Close()
  142. e.client = nil
  143. }
  144. }
  145. // Run ejecuta cmd en host con timeout (por defecto 5 s, como el JS).
  146. // Una sesión fallida por canal roto invalida la conexión (reconexión).
  147. func (p *SSHPool) Run(host, cmd string, timeout time.Duration) (string, error) {
  148. if timeout <= 0 {
  149. timeout = sshDefaultTimeout
  150. }
  151. client, err := p.dial(host)
  152. if err != nil {
  153. return "", err
  154. }
  155. session, err := client.NewSession()
  156. if err != nil {
  157. p.drop(host)
  158. return "", fmt.Errorf("ssh %s: session: %w", host, err)
  159. }
  160. defer session.Close()
  161. type result struct {
  162. out []byte
  163. err error
  164. }
  165. ch := make(chan result, 1)
  166. go func() {
  167. out, err := session.Output(cmd)
  168. ch <- result{out, err}
  169. }()
  170. select {
  171. case res := <-ch:
  172. if res.err != nil {
  173. var ee *ssh.ExitError
  174. if !errors.As(res.err, &ee) {
  175. p.drop(host) // canal roto, no exit status
  176. }
  177. return "", fmt.Errorf("ssh %s: %w", host, res.err)
  178. }
  179. return string(res.out), nil
  180. case <-time.After(timeout):
  181. _ = session.Close()
  182. p.drop(host)
  183. return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
  184. }
  185. }
  186. // RunCtx es Run con cancelación por contexto.
  187. func (p *SSHPool) RunCtx(ctx context.Context, host, cmd string, timeout time.Duration) (string, error) {
  188. type res struct {
  189. out string
  190. err error
  191. }
  192. ch := make(chan res, 1)
  193. go func() {
  194. out, err := p.Run(host, cmd, timeout)
  195. ch <- res{out, err}
  196. }()
  197. select {
  198. case r := <-ch:
  199. return r.out, r.err
  200. case <-ctx.Done():
  201. return "", ctx.Err()
  202. }
  203. }
  204. // Close cierra todas las conexiones del pool.
  205. func (p *SSHPool) Close() {
  206. p.mu.Lock()
  207. defer p.mu.Unlock()
  208. if p.closed {
  209. return
  210. }
  211. p.closed = true
  212. for _, e := range p.conns {
  213. if e.client != nil {
  214. _ = e.client.Close()
  215. e.client = nil
  216. }
  217. }
  218. }
  219. func min(a, b int) int {
  220. if a < b {
  221. return a
  222. }
  223. return b
  224. }