sshpool.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. dialTCP func(network, addr string, config *ssh.ClientConfig) (*ssh.Client, error)
  38. }
  39. type sshConn struct {
  40. client *ssh.Client
  41. dialing chan struct{}
  42. failures int
  43. notUntil time.Time
  44. }
  45. // NewSSHPool crea el pool cargando la clave privada (ed25519 sin passphrase).
  46. func NewSSHPool(keyPath string) (*SSHPool, error) {
  47. pem, err := os.ReadFile(keyPath)
  48. if err != nil {
  49. return nil, fmt.Errorf("leer clave SSH: %w", err)
  50. }
  51. signer, err := ssh.ParsePrivateKey(pem)
  52. if err != nil {
  53. return nil, fmt.Errorf("parsear clave SSH: %w", err)
  54. }
  55. return &SSHPool{
  56. keyPath: keyPath,
  57. signer: signer,
  58. khPath: sshkey.KnownHostsPath(keyPath),
  59. conns: map[string]*sshConn{},
  60. dialTCP: ssh.Dial,
  61. }, nil
  62. }
  63. // hostKeyCallback implementa accept-new sobre el known_hosts propio.
  64. func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
  65. if _, err := os.Stat(p.khPath); os.IsNotExist(err) {
  66. if err := os.MkdirAll(filepath.Dir(p.khPath), 0o700); err == nil {
  67. _ = os.WriteFile(p.khPath, nil, 0o600)
  68. }
  69. }
  70. checker, err := knownhosts.New(p.khPath)
  71. if err != nil {
  72. return nil, err
  73. }
  74. return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  75. err := checker(hostname, remote, key)
  76. if err == nil {
  77. return nil
  78. }
  79. var keyErr *knownhosts.KeyError
  80. if errors.As(err, &keyErr) && len(keyErr.Want) > 0 {
  81. return err // clave CAMBIADA → rechazar
  82. }
  83. // Host desconocido → accept-new
  84. line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
  85. f, ferr := os.OpenFile(p.khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
  86. if ferr != nil {
  87. return ferr
  88. }
  89. defer f.Close()
  90. _, ferr = f.WriteString(line + "\n")
  91. return ferr
  92. }, nil
  93. }
  94. // dial abre (o reabre) la conexión a un host respetando el backoff.
  95. // Single-flight por host: dos llamantes concurrentes comparten el mismo dial.
  96. func (p *SSHPool) dial(host string) (*ssh.Client, error) {
  97. p.mu.Lock()
  98. if p.closed {
  99. p.mu.Unlock()
  100. return nil, errors.New("ssh pool closed")
  101. }
  102. entry := p.conns[host]
  103. if entry == nil {
  104. entry = &sshConn{}
  105. p.conns[host] = entry
  106. }
  107. if entry.client != nil {
  108. c := entry.client
  109. p.mu.Unlock()
  110. return c, nil
  111. }
  112. if entry.dialing != nil {
  113. ch := entry.dialing
  114. p.mu.Unlock()
  115. <-ch
  116. p.mu.Lock()
  117. if entry.client != nil {
  118. c := entry.client
  119. p.mu.Unlock()
  120. return c, nil
  121. }
  122. p.mu.Unlock()
  123. return nil, errors.New("ssh dial failed")
  124. }
  125. if time.Now().Before(entry.notUntil) {
  126. p.mu.Unlock()
  127. return nil, fmt.Errorf("ssh %s: en backoff tras %d fallos", host, entry.failures)
  128. }
  129. entry.dialing = make(chan struct{})
  130. p.mu.Unlock()
  131. cb, err := p.hostKeyCallback()
  132. if err != nil {
  133. p.mu.Lock()
  134. close(entry.dialing)
  135. entry.dialing = nil
  136. p.mu.Unlock()
  137. return nil, err
  138. }
  139. cfg := &ssh.ClientConfig{
  140. User: "root",
  141. Auth: []ssh.AuthMethod{ssh.PublicKeys(p.signer)},
  142. HostKeyCallback: cb,
  143. Timeout: sshDialTimeout,
  144. }
  145. client, err := p.dialTCP("tcp", net.JoinHostPort(host, "22"), cfg)
  146. p.mu.Lock()
  147. close(entry.dialing)
  148. entry.dialing = nil
  149. if err != nil {
  150. entry.failures++
  151. backoff := sshBackoffBase << min(entry.failures-1, 4)
  152. if backoff > sshBackoffMax {
  153. backoff = sshBackoffMax
  154. }
  155. entry.notUntil = time.Now().Add(backoff)
  156. p.mu.Unlock()
  157. return nil, fmt.Errorf("ssh %s: %w", host, err)
  158. }
  159. entry.client = client
  160. entry.failures = 0
  161. entry.notUntil = time.Time{}
  162. p.mu.Unlock()
  163. return client, nil
  164. }
  165. // drop invalida la conexión de un host (la próxima llamada rediala).
  166. func (p *SSHPool) drop(host string) {
  167. p.mu.Lock()
  168. defer p.mu.Unlock()
  169. if e := p.conns[host]; e != nil && e.client != nil {
  170. _ = e.client.Close()
  171. e.client = nil
  172. }
  173. }
  174. // Run ejecuta cmd en host con timeout (por defecto 5 s, como el JS).
  175. // Una sesión fallida por canal roto invalida la conexión (reconexión).
  176. func (p *SSHPool) Run(host, cmd string, timeout time.Duration) (string, error) {
  177. if timeout <= 0 {
  178. timeout = sshDefaultTimeout
  179. }
  180. client, err := p.dial(host)
  181. if err != nil {
  182. return "", err
  183. }
  184. session, err := client.NewSession()
  185. if err != nil {
  186. p.drop(host)
  187. return "", fmt.Errorf("ssh %s: session: %w", host, err)
  188. }
  189. defer session.Close()
  190. type result struct {
  191. out []byte
  192. err error
  193. }
  194. ch := make(chan result, 1)
  195. go func() {
  196. out, err := session.Output(cmd)
  197. ch <- result{out, err}
  198. }()
  199. select {
  200. case res := <-ch:
  201. if res.err != nil {
  202. var ee *ssh.ExitError
  203. if !errors.As(res.err, &ee) {
  204. p.drop(host) // canal roto, no exit status
  205. }
  206. return "", fmt.Errorf("ssh %s: %w", host, res.err)
  207. }
  208. return string(res.out), nil
  209. case <-time.After(timeout):
  210. // Timeout: cerrar solo la sesión. NO dropear el cliente entero: el
  211. // pool permite sesiones concurrentes sobre el mismo router y un
  212. // comando lento no debe cortar las demás (issue #205).
  213. _ = session.Close()
  214. return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
  215. }
  216. }
  217. // RunCtx es Run con cancelación por contexto.
  218. func (p *SSHPool) RunCtx(ctx context.Context, host, cmd string, timeout time.Duration) (string, error) {
  219. if timeout <= 0 {
  220. timeout = sshDefaultTimeout
  221. }
  222. client, err := p.dial(host)
  223. if err != nil {
  224. return "", err
  225. }
  226. session, err := client.NewSession()
  227. if err != nil {
  228. p.drop(host)
  229. return "", fmt.Errorf("ssh %s: session: %w", host, err)
  230. }
  231. defer session.Close()
  232. type result struct {
  233. out []byte
  234. err error
  235. }
  236. ch := make(chan result, 1)
  237. go func() {
  238. out, err := session.Output(cmd)
  239. ch <- result{out, err}
  240. }()
  241. select {
  242. case res := <-ch:
  243. if res.err != nil {
  244. var ee *ssh.ExitError
  245. if !errors.As(res.err, &ee) {
  246. p.drop(host) // canal roto, no exit status
  247. }
  248. return "", fmt.Errorf("ssh %s: %w", host, res.err)
  249. }
  250. return string(res.out), nil
  251. case <-time.After(timeout):
  252. _ = session.Close()
  253. return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
  254. case <-ctx.Done():
  255. // Cancelación del cliente: cerrar la sesión para abortar el comando
  256. // remoto y liberar la goroutine (issue #204). Sin drop: es una
  257. // cancelación del llamador, no un fallo de la conexión.
  258. _ = session.Close()
  259. return "", ctx.Err()
  260. }
  261. }
  262. // Close cierra todas las conexiones del pool.
  263. func (p *SSHPool) Close() {
  264. p.mu.Lock()
  265. defer p.mu.Unlock()
  266. if p.closed {
  267. return
  268. }
  269. p.closed = true
  270. for _, e := range p.conns {
  271. if e.client != nil {
  272. _ = e.client.Close()
  273. e.client = nil
  274. }
  275. }
  276. }
  277. func min(a, b int) int {
  278. if a < b {
  279. return a
  280. }
  281. return b
  282. }