sshpool.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. closed bool
  48. dialTCP func(network, addr string, config *ssh.ClientConfig) (*ssh.Client, error)
  49. }
  50. type sshConn struct {
  51. client *ssh.Client
  52. dialing chan struct{}
  53. failures int
  54. notUntil time.Time
  55. }
  56. // NewSSHPool crea el pool cargando la clave privada (ed25519 sin passphrase).
  57. func NewSSHPool(keyPath string) (*SSHPool, error) {
  58. pem, err := os.ReadFile(keyPath)
  59. if err != nil {
  60. return nil, fmt.Errorf("leer clave SSH: %w", err)
  61. }
  62. signer, err := ssh.ParsePrivateKey(pem)
  63. if err != nil {
  64. return nil, fmt.Errorf("parsear clave SSH: %w", err)
  65. }
  66. return &SSHPool{
  67. keyPath: keyPath,
  68. signer: signer,
  69. khPath: sshkey.KnownHostsPath(keyPath),
  70. conns: map[string]*sshConn{},
  71. dialTCP: ssh.Dial,
  72. }, nil
  73. }
  74. // hostKeyCallback implementa accept-new sobre el known_hosts propio.
  75. func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
  76. if _, err := os.Stat(p.khPath); os.IsNotExist(err) {
  77. if err := os.MkdirAll(filepath.Dir(p.khPath), 0o700); err == nil {
  78. _ = os.WriteFile(p.khPath, nil, 0o600)
  79. }
  80. }
  81. checker, err := knownhosts.New(p.khPath)
  82. if err != nil {
  83. return nil, err
  84. }
  85. return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  86. err := checker(hostname, remote, key)
  87. if err == nil {
  88. return nil
  89. }
  90. var keyErr *knownhosts.KeyError
  91. if errors.As(err, &keyErr) && len(keyErr.Want) > 0 {
  92. // Clave cambiada (#603): NO se auto-acepta. Una clave distinta en
  93. // un host ya conocido es un evento de seguridad (posible MITM);
  94. // el operador debe confirmar el re-onboard explícitamente tras
  95. // verificar fuera de banda (p. ej. tras un flash del router). El
  96. // error tipado alimenta el estado "host key changed" del router.
  97. oldFP := ""
  98. if len(keyErr.Want) > 0 {
  99. oldFP = ssh.FingerprintSHA256(keyErr.Want[0].Key)
  100. }
  101. newFP := ssh.FingerprintSHA256(key)
  102. log.Printf("ssh %s: host key changed (%s -> %s); re-onboard requerido", hostname, oldFP, newFP)
  103. return &HostKeyChangedError{Host: hostname, OldFP: oldFP, NewFP: newFP}
  104. }
  105. // Host desconocido → accept-new
  106. line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
  107. f, ferr := os.OpenFile(p.khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
  108. if ferr != nil {
  109. return ferr
  110. }
  111. defer f.Close()
  112. _, ferr = f.WriteString(line + "\n")
  113. return ferr
  114. }, nil
  115. }
  116. // HostKeyChangedError: el host presenta una clave distinta a la registrada en
  117. // known_hosts. No se auto-acepta: la conexión se rechaza hasta que el admin
  118. // confirme el re-onboard (RemoveHostKey + siguiente sondeo hace TOFU).
  119. type HostKeyChangedError struct {
  120. Host string
  121. OldFP string
  122. NewFP string
  123. }
  124. func (e *HostKeyChangedError) Error() string {
  125. return "ssh host key changed for " + e.Host + " (" + e.OldFP + " -> " + e.NewFP + "); re-onboard required"
  126. }
  127. // RemoveHostKey elimina la entrada known_hosts de un host (confirmación de
  128. // re-onboard #603). Quita las líneas previas de ese host (la lista de hosts
  129. // de una línea puede ser separada por comas); el siguiente sondeo la vuelve a
  130. // registrar con TOFU.
  131. func (p *SSHPool) RemoveHostKey(hostname string) error {
  132. norm := knownhosts.Normalize(hostname)
  133. var keep []string
  134. if data, err := os.ReadFile(p.khPath); err == nil {
  135. for _, ln := range strings.Split(string(data), "\n") {
  136. if strings.TrimSpace(ln) == "" {
  137. continue
  138. }
  139. fields := strings.Fields(ln)
  140. if len(fields) == 0 {
  141. continue
  142. }
  143. drop := false
  144. for _, h := range strings.Split(fields[0], ",") {
  145. if knownhosts.Normalize(h) == norm {
  146. drop = true
  147. break
  148. }
  149. }
  150. if !drop {
  151. keep = append(keep, ln)
  152. }
  153. }
  154. }
  155. return os.WriteFile(p.khPath, []byte(strings.Join(keep, "\n")+"\n"), 0o600)
  156. }
  157. // dial abre (o reabre) la conexión a un host respetando el backoff.
  158. // Single-flight por host: dos llamantes concurrentes comparten el mismo dial.
  159. func (p *SSHPool) dial(host string) (*ssh.Client, error) {
  160. p.mu.Lock()
  161. if p.closed {
  162. p.mu.Unlock()
  163. return nil, errors.New("ssh pool closed")
  164. }
  165. entry := p.conns[host]
  166. if entry == nil {
  167. entry = &sshConn{}
  168. p.conns[host] = entry
  169. }
  170. if entry.client != nil {
  171. c := entry.client
  172. p.mu.Unlock()
  173. return c, nil
  174. }
  175. if entry.dialing != nil {
  176. ch := entry.dialing
  177. p.mu.Unlock()
  178. <-ch
  179. p.mu.Lock()
  180. if entry.client != nil {
  181. c := entry.client
  182. p.mu.Unlock()
  183. return c, nil
  184. }
  185. p.mu.Unlock()
  186. return nil, errors.New("ssh dial failed")
  187. }
  188. if time.Now().Before(entry.notUntil) {
  189. p.mu.Unlock()
  190. return nil, fmt.Errorf("ssh %s: en backoff tras %d fallos", host, entry.failures)
  191. }
  192. entry.dialing = make(chan struct{})
  193. p.mu.Unlock()
  194. cb, err := p.hostKeyCallback()
  195. if err != nil {
  196. p.mu.Lock()
  197. close(entry.dialing)
  198. entry.dialing = nil
  199. p.mu.Unlock()
  200. return nil, err
  201. }
  202. cfg := &ssh.ClientConfig{
  203. User: "root",
  204. Auth: []ssh.AuthMethod{ssh.PublicKeys(p.signer)},
  205. HostKeyCallback: cb,
  206. Timeout: sshDialTimeout,
  207. }
  208. client, err := p.dialTCP("tcp", addrOf(host), cfg)
  209. p.mu.Lock()
  210. close(entry.dialing)
  211. entry.dialing = nil
  212. if err != nil {
  213. entry.failures++
  214. backoff := sshBackoffBase << min(entry.failures-1, 4)
  215. if backoff > sshBackoffMax {
  216. backoff = sshBackoffMax
  217. }
  218. entry.notUntil = time.Now().Add(backoff)
  219. p.mu.Unlock()
  220. return nil, fmt.Errorf("ssh %s: %w", host, err)
  221. }
  222. entry.client = client
  223. entry.failures = 0
  224. entry.notUntil = time.Time{}
  225. p.mu.Unlock()
  226. return client, nil
  227. }
  228. // drop invalida la conexión de un host (la próxima llamada rediala).
  229. func (p *SSHPool) drop(host string) {
  230. p.mu.Lock()
  231. defer p.mu.Unlock()
  232. if e := p.conns[host]; e != nil && e.client != nil {
  233. _ = e.client.Close()
  234. e.client = nil
  235. }
  236. }
  237. // Run ejecuta cmd en host con timeout (por defecto 5 s, como el JS).
  238. // Una sesión fallida por canal roto invalida la conexión (reconexión).
  239. func (p *SSHPool) Run(host, cmd string, timeout time.Duration) (string, error) {
  240. if timeout <= 0 {
  241. timeout = sshDefaultTimeout
  242. }
  243. client, err := p.dial(host)
  244. if err != nil {
  245. return "", err
  246. }
  247. session, err := client.NewSession()
  248. if err != nil {
  249. p.drop(host)
  250. return "", fmt.Errorf("ssh %s: session: %w", host, err)
  251. }
  252. defer session.Close()
  253. type result struct {
  254. out []byte
  255. err error
  256. }
  257. ch := make(chan result, 1)
  258. go func() {
  259. out, err := session.Output(cmd)
  260. ch <- result{out, err}
  261. }()
  262. select {
  263. case res := <-ch:
  264. if res.err != nil {
  265. var ee *ssh.ExitError
  266. if !errors.As(res.err, &ee) {
  267. p.drop(host) // canal roto, no exit status
  268. }
  269. return "", fmt.Errorf("ssh %s: %w", host, res.err)
  270. }
  271. return string(res.out), nil
  272. case <-time.After(timeout):
  273. // Timeout: cerrar solo la sesión. NO dropear el cliente entero: el
  274. // pool permite sesiones concurrentes sobre el mismo router y un
  275. // comando lento no debe cortar las demás (issue #205).
  276. _ = session.Close()
  277. return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
  278. }
  279. }
  280. // RunCtx es Run con cancelación por contexto.
  281. func (p *SSHPool) RunCtx(ctx context.Context, host, cmd string, timeout time.Duration) (string, error) {
  282. if timeout <= 0 {
  283. timeout = sshDefaultTimeout
  284. }
  285. client, err := p.dial(host)
  286. if err != nil {
  287. return "", err
  288. }
  289. session, err := client.NewSession()
  290. if err != nil {
  291. p.drop(host)
  292. return "", fmt.Errorf("ssh %s: session: %w", host, err)
  293. }
  294. defer session.Close()
  295. type result struct {
  296. out []byte
  297. err error
  298. }
  299. ch := make(chan result, 1)
  300. go func() {
  301. out, err := session.Output(cmd)
  302. ch <- result{out, err}
  303. }()
  304. select {
  305. case res := <-ch:
  306. if res.err != nil {
  307. var ee *ssh.ExitError
  308. if !errors.As(res.err, &ee) {
  309. p.drop(host) // canal roto, no exit status
  310. }
  311. return "", fmt.Errorf("ssh %s: %w", host, res.err)
  312. }
  313. return string(res.out), nil
  314. case <-time.After(timeout):
  315. _ = session.Close()
  316. return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
  317. case <-ctx.Done():
  318. // Cancelación del cliente: cerrar la sesión para abortar el comando
  319. // remoto y liberar la goroutine (issue #204). Sin drop: es una
  320. // cancelación del llamador, no un fallo de la conexión.
  321. _ = session.Close()
  322. return "", ctx.Err()
  323. }
  324. }
  325. // Close cierra todas las conexiones del pool.
  326. func (p *SSHPool) Close() {
  327. p.mu.Lock()
  328. defer p.mu.Unlock()
  329. if p.closed {
  330. return
  331. }
  332. p.closed = true
  333. for _, e := range p.conns {
  334. if e.client != nil {
  335. _ = e.client.Close()
  336. e.client = nil
  337. }
  338. }
  339. }
  340. func min(a, b int) int {
  341. if a < b {
  342. return a
  343. }
  344. return b
  345. }