| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612 |
- // sshpool.go — Pool de conexiones SSH persistentes (equivalente Go del
- // ControlMaster/ControlPersist del JS, SPEC §7.2): UNA conexión por router,
- // reutilizada entre ticks del poller, con reconexión automática y backoff
- // exponencial (30 s base, máx 5 min) para no martillear un router caído.
- //
- // known_hosts con semántica accept-new junto a la clave (como el JS):
- // host desconocido → se acepta y se anota; host conocido con clave distinta
- // → se rechaza (posible MITM).
- package adapters
- import (
- "context"
- "errors"
- "fmt"
- "io"
- "log"
- "net"
- "os"
- "path/filepath"
- "strings"
- "sync"
- "time"
- "github.com/gnacho/netpulse/server-go/internal/sshkey"
- "golang.org/x/crypto/ssh"
- "golang.org/x/crypto/ssh/knownhosts"
- )
- const (
- sshDialTimeout = 4 * time.Second // ConnectTimeout=4 del JS
- sshDefaultTimeout = 5 * time.Second // SSH_TIMEOUT_MS del JS
- sshBackoffBase = 30 * time.Second
- sshBackoffMax = 5 * time.Minute
- )
- // addrOf devuelve el destino `host:port` para conectar. Los callers pasan el
- // host ya con puerto (RouterConfig.SSHAddr, issue #605); si vienen sin puerto
- // (back-compat) se asume 22.
- func addrOf(host string) string {
- if _, _, err := net.SplitHostPort(host); err == nil {
- return host
- }
- return net.JoinHostPort(host, "22")
- }
- // poolKey es la clave del pool para un host. El mismo router llega unas veces
- // como "test-gw.lan" y otras como "test-gw.lan:22" (RouterConfig.SSHAddr), y
- // con el string tal cual el pool abría DOS conexiones al mismo equipo, una por
- // clave y cada una con su handshake (#1893). El puerto por defecto no
- // distingue hosts, así que no forma parte de la clave; uno no estándar sí.
- func poolKey(host string) string {
- if h, port, err := net.SplitHostPort(host); err == nil && port == "22" {
- return h
- }
- return host
- }
- // SSHPool gestiona conexiones persistentes a los routers.
- type SSHPool struct {
- keyPath string
- signer ssh.Signer
- khPath string
- mu sync.Mutex
- conns map[string]*sshConn
- creds map[string]sshCred
- closed bool
- dialTCP func(network, addr string, config *ssh.ClientConfig) (*ssh.Client, error)
- closeClient func(*ssh.Client) error
- }
- // sshCred es la credencial de contraseña registrada para un host
- // (#1708): las integraciones ssh con fichero compañero <slug>.sshpass
- // conectan por contraseña mientras la credencial esté registrada; el resto
- // de destinos siguen con la llave del servidor.
- type sshCred struct {
- user string
- password string
- }
- func (p *SSHPool) closeSSHClient(c *ssh.Client) error {
- if c == nil {
- return nil
- }
- if p.closeClient != nil {
- return p.closeClient(c)
- }
- return c.Close()
- }
- type sshConn struct {
- client *ssh.Client
- dialing chan struct{}
- failures int
- notUntil time.Time
- }
- // NewSSHPool crea el pool cargando la clave privada (ed25519 sin passphrase).
- func NewSSHPool(keyPath string) (*SSHPool, error) {
- pem, err := os.ReadFile(keyPath)
- if err != nil {
- return nil, fmt.Errorf("leer clave SSH: %w", err)
- }
- signer, err := ssh.ParsePrivateKey(pem)
- if err != nil {
- return nil, fmt.Errorf("parsear clave SSH: %w", err)
- }
- return &SSHPool{
- keyPath: keyPath,
- signer: signer,
- khPath: sshkey.KnownHostsPath(keyPath),
- conns: map[string]*sshConn{},
- creds: map[string]sshCred{},
- dialTCP: ssh.Dial,
- }, nil
- }
- // SetPassword registra (o borra, con password vacía) la credencial de
- // contraseña de un host (#1708). Mientras haya credencial, el dial de ese
- // host autentica por contraseña con el usuario dado y la llave del servidor
- // queda aparcada. Un cambio de credencial tira la conexión cacheada y el
- // backoff del host: la siguiente llamada reconecta con el valor nuevo, sin
- // esperar el enfriamiento de un fallo ya resuelto.
- func (p *SSHPool) SetPassword(host, user, password string) {
- host = poolKey(host)
- p.mu.Lock()
- defer p.mu.Unlock()
- old, had := p.creds[host]
- if password == "" {
- if !had {
- return
- }
- delete(p.creds, host)
- } else {
- if had && old.user == user && old.password == password {
- return
- }
- if p.creds == nil {
- p.creds = map[string]sshCred{}
- }
- p.creds[host] = sshCred{user: user, password: password}
- }
- if e := p.conns[host]; e != nil {
- if e.client != nil {
- _ = p.closeSSHClient(e.client)
- e.client = nil
- }
- e.failures = 0
- e.notUntil = time.Time{}
- }
- }
- // hostKeyCallback implementa accept-new sobre el known_hosts propio.
- func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
- if _, err := os.Stat(p.khPath); os.IsNotExist(err) {
- if err := os.MkdirAll(filepath.Dir(p.khPath), 0o700); err == nil {
- _ = os.WriteFile(p.khPath, nil, 0o600)
- }
- }
- // #2014: una sola línea ilegible hace que knownhosts.New rechace el
- // fichero entero, y con él el SSH a TODAS las unidades. Se descarta antes
- // de cargarlo: el fichero también lo escriben procesos ssh externos, que
- // no pueden tomar el lock del paquete.
- if dropped, serr := sshkey.SanitizeKnownHosts(p.khPath); serr != nil {
- log.Printf("[netpulse:ssh] saneando %s: %v", p.khPath, serr)
- } else if dropped > 0 {
- log.Printf("[netpulse:ssh] %d unreadable known_hosts line(s) dropped from %s (#2014)", dropped, p.khPath)
- }
- checker, err := knownhosts.New(p.khPath)
- if err != nil {
- return nil, err
- }
- return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
- err := checker(hostname, remote, key)
- if err == nil {
- return nil
- }
- var keyErr *knownhosts.KeyError
- if errors.As(err, &keyErr) && len(keyErr.Want) > 0 {
- // Clave cambiada (#603): NO se auto-acepta. Una clave distinta en
- // un host ya conocido es un evento de seguridad (posible MITM);
- // el operador debe confirmar el re-onboard explícitamente tras
- // verificar fuera de banda (p. ej. tras un flash del router). El
- // error tipado alimenta el estado "host key changed" del router.
- oldFP := ""
- if len(keyErr.Want) > 0 {
- oldFP = ssh.FingerprintSHA256(keyErr.Want[0].Key)
- }
- newFP := ssh.FingerprintSHA256(key)
- log.Printf("[netpulse:ssh] %s: host key changed (%s -> %s), re-onboard required", hostname, oldFP, newFP)
- return &HostKeyChangedError{Host: hostname, OldFP: oldFP, NewFP: newFP}
- }
- // Host desconocido → accept-new
- line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
- return sshkey.AppendKnownHosts(p.khPath, []string{line})
- }, nil
- }
- // HostKeyChangedError: el host presenta una clave distinta a la registrada en
- // known_hosts. No se auto-acepta: la conexión se rechaza hasta que el admin
- // confirme el re-onboard (RemoveHostKey + siguiente sondeo hace TOFU).
- type HostKeyChangedError struct {
- Host string
- OldFP string
- NewFP string
- }
- func (e *HostKeyChangedError) Error() string {
- return "ssh host key changed for " + e.Host + " (" + e.OldFP + " -> " + e.NewFP + "); re-onboard required"
- }
- // SSHAuthError: el host rechazó la autenticación SSH (contraseña o llave
- // rechazadas por el servidor). Va con código de error propio en la API
- // (ssh_auth_failed, #1708) para que la UI pida revisar la contraseña en vez
- // de un fallo genérico de conexión.
- type SSHAuthError struct {
- Host string
- Err error
- }
- func (e *SSHAuthError) Error() string {
- return "ssh " + e.Host + ": authentication rejected: " + e.Err.Error()
- }
- func (e *SSHAuthError) Unwrap() error { return e.Err }
- // isSSHAuthError reconoce el rechazo de autenticación del handshake. La
- // librería no exporta un tipo para esto y el texto es estable en x/crypto
- // ("ssh: unable to authenticate, attempted methods ...").
- func isSSHAuthError(err error) bool {
- return err != nil && strings.Contains(err.Error(), "ssh: unable to authenticate")
- }
- // remoteExited distingue el fallo de un comando que SÍ se ejecutó en el router
- // (exit status distinto de cero: `wg: unknown command`, binario ausente) de
- // no haber podido ejecutar nada (credencial rechazada, host en backoff,
- // timeout de dial, sesión rota). Quien interprete un error para deducir una
- // capacidad del router tiene que preguntar esto primero: un dial fallido no
- // dice nada del router, solo de nuestro acceso (#2041).
- func remoteExited(err error) bool {
- var ee *ssh.ExitError
- return err != nil && errors.As(err, &ee)
- }
- // RemoveHostKey elimina las entradas known_hosts de un host (confirmación de
- // re-onboard #603). Quita las líneas previas de ese host (la lista de hosts
- // de una línea puede ser separada por comas); el siguiente sondeo la vuelve a
- // registrar con TOFU.
- // Los candidatos son varias formas del mismo destino (#1524): la dirección
- // SSH completa (SSHAddr, que Normalize convierte a [host]:puerto en puertos
- // no estándar) y el host pelado, porque entradas anteriores a un cambio de
- // puerto pueden vivir sin él. Normalizar cada campo de la línea evita depender
- // de cómo se escribió cada entrada.
- func (p *SSHPool) RemoveHostKey(hostnames ...string) error {
- norms := make(map[string]bool, len(hostnames))
- for _, h := range hostnames {
- if h == "" {
- continue
- }
- norms[knownhosts.Normalize(h)] = true
- }
- var keep []string
- dropped := 0
- // #2014: lectura y reescritura bajo el lock del paquete y con rename
- // atómico. Antes era ReadFile + os.WriteFile (truncate en sitio): un
- // append concurrente caía entre el truncate y la escritura y dejaba una
- // línea a medias, que tumbaba el SSH de toda la flota.
- err := sshkey.UpdateKnownHosts(p.khPath, func(data []byte) ([]byte, error) {
- for _, ln := range strings.Split(string(data), "\n") {
- if strings.TrimSpace(ln) == "" {
- continue
- }
- fields := strings.Fields(ln)
- if len(fields) == 0 {
- continue
- }
- drop := false
- for _, h := range strings.Split(fields[0], ",") {
- if norms[knownhosts.Normalize(h)] {
- drop = true
- break
- }
- }
- if !drop {
- keep = append(keep, ln)
- continue
- }
- dropped++
- }
- if dropped == 0 {
- return data, nil
- }
- return []byte(strings.Join(keep, "\n") + "\n"), nil
- })
- return err
- }
- // dial abre (o reabre) la conexión a un host respetando el backoff.
- // Single-flight por host: dos llamantes concurrentes comparten el mismo dial.
- func (p *SSHPool) dial(host string) (*ssh.Client, error) {
- host = poolKey(host)
- p.mu.Lock()
- if p.closed {
- p.mu.Unlock()
- return nil, errors.New("ssh pool closed")
- }
- entry := p.conns[host]
- if entry == nil {
- entry = &sshConn{}
- p.conns[host] = entry
- }
- if entry.client != nil {
- c := entry.client
- p.mu.Unlock()
- return c, nil
- }
- if entry.dialing != nil {
- ch := entry.dialing
- p.mu.Unlock()
- <-ch
- p.mu.Lock()
- if entry.client != nil {
- c := entry.client
- p.mu.Unlock()
- return c, nil
- }
- p.mu.Unlock()
- return nil, errors.New("ssh dial failed")
- }
- if time.Now().Before(entry.notUntil) {
- p.mu.Unlock()
- return nil, fmt.Errorf("ssh %s: in backoff after %d failures", host, entry.failures)
- }
- entry.dialing = make(chan struct{})
- p.mu.Unlock()
- cb, err := p.hostKeyCallback()
- if err != nil {
- p.mu.Lock()
- close(entry.dialing)
- entry.dialing = nil
- p.mu.Unlock()
- return nil, err
- }
- // Credencial registrada para este host (#1708): contraseña con el
- // usuario de la integración en vez de la llave del servidor. Se lee bajo
- // lock para no competir con SetPassword.
- p.mu.Lock()
- cred, hasCred := p.creds[host]
- p.mu.Unlock()
- cfg := &ssh.ClientConfig{
- User: "root",
- Auth: []ssh.AuthMethod{ssh.PublicKeys(p.signer)},
- HostKeyCallback: cb,
- Timeout: sshDialTimeout,
- }
- if hasCred {
- cfg.User = cred.user
- cfg.Auth = []ssh.AuthMethod{ssh.Password(cred.password)}
- }
- client, err := p.dialTCP("tcp", addrOf(host), cfg)
- p.mu.Lock()
- close(entry.dialing)
- entry.dialing = nil
- if err != nil {
- entry.failures++
- backoff := sshBackoffBase << min(entry.failures-1, 4)
- if backoff > sshBackoffMax {
- backoff = sshBackoffMax
- }
- entry.notUntil = time.Now().Add(backoff)
- // #1893: un "Exit before auth" en dropbear no se podía cruzar con nada,
- // porque el server no decía a qué host llamaba ni por qué fallaba. El
- // motivo real (host key, auth, timeout, red) va al log del sistema con
- // el host y el número de fallos; se registra el primero y cada diez
- // para que una unidad apagada no sature el journal.
- if entry.failures == 1 || entry.failures%10 == 0 {
- log.Printf("[netpulse:ssh] dial %s (user=%s): %v (failure %d, backoff %s)", host, cfg.User, err, entry.failures, backoff)
- }
- p.mu.Unlock()
- if isSSHAuthError(err) {
- return nil, &SSHAuthError{Host: host, Err: err}
- }
- return nil, fmt.Errorf("ssh %s: %w", host, err)
- }
- if p.closed {
- p.mu.Unlock()
- _ = p.closeSSHClient(client)
- return nil, errors.New("ssh pool closed")
- }
- // #1893: toda conexión NUEVA queda registrada. Si algo está marcando el
- // ciclo de sondeo con conexiones que mueren antes de autenticar, aquí se
- // ve el ritmo real de dials por host en vez de suponerlo.
- if entry.failures > 0 {
- log.Printf("[netpulse:ssh] %s: connection recovered after %d dial failures", host, entry.failures)
- }
- log.Printf("[netpulse:ssh] %s: new connection established (user=%s)", host, cfg.User)
- entry.client = client
- entry.failures = 0
- entry.notUntil = time.Time{}
- p.mu.Unlock()
- return client, nil
- }
- // drop invalida la conexión de un host (la próxima llamada rediala).
- func (p *SSHPool) drop(host string) {
- host = poolKey(host)
- p.mu.Lock()
- defer p.mu.Unlock()
- if e := p.conns[host]; e != nil && e.client != nil {
- // #1893: el descarte explica la reconexión siguiente; sin esta línea un
- // dial nuevo no se puede distinguir de una fuga de conexiones.
- log.Printf("[netpulse:ssh] %s: connection discarded, next command will redial", host)
- _ = p.closeSSHClient(e.client)
- e.client = nil
- }
- }
- // sshErrDetail (#1737) saca el motivo real de un comando remoto fallido.
- // session.Output descarta el stderr salvo que se le de un destino, y antes se
- // tiraba: un reinstall fallido solo decia "Process exited with status 1" y el
- // motivo (curl, wget, uci) se quedaba en el router. Se devuelve la ULTIMA
- // linea no vacia y recortada, que es la que explica el fallo sin arrastrar el
- // ruido del script entero.
- // mergeScriptOutput junta stdout y stderr en el orden en que se leen: primero
- // lo que el script escribio a la salida normal, despues sus avisos. El journal
- // y la caja de la UI enseñan este texto tal cual (#1894).
- func mergeScriptOutput(stdout, stderr string) string {
- if stderr == "" {
- return stdout
- }
- if stdout != "" && !strings.HasSuffix(stdout, "\n") {
- stdout += "\n"
- }
- return stdout + stderr
- }
- func sshErrDetail(stderr string) string {
- if stderr == "" {
- return ""
- }
- lines := strings.Split(strings.TrimRight(stderr, "\n"), "\n")
- for i := len(lines) - 1; i >= 0; i-- {
- line := strings.TrimSpace(lines[i])
- if line == "" {
- continue
- }
- if len(line) > 300 {
- line = line[:300] + "..."
- }
- return line
- }
- return ""
- }
- // Run ejecuta cmd en host con timeout (por defecto 5 s, como el JS).
- // Una sesión fallida por canal roto invalida la conexión (reconexión).
- func (p *SSHPool) Run(host, cmd string, timeout time.Duration) (string, error) {
- return p.run(host, cmd, nil, timeout, false)
- }
- // RunScript ejecuta un script POSIX por stdin con `sh -s` (#1737). Dropbear
- // limita el tamaño de cada string del paquete a MAX_CMD_LEN (9000 bytes) y
- // aborta la conexión con "String too long": el cliente SSH solo ve EOF, sin
- // exit status ni stderr. El script de reinstalación pasa de 14 KB por argv, así
- // que el comando completo viaja por stdin y en argv solo va `sh -s`.
- // #1894: el script de reinstalación cuenta todo lo que hace por stderr
- // (`warn()` y los `echo ... >&2`), y el pool devolvía solo stdout. Con
- // mergeStderr la salida que viaja al journal y a la UI lleva las dos, y se
- // devuelve también cuando el script falla: es justo cuando hace falta.
- func (p *SSHPool) RunScript(host, script string, timeout time.Duration) (string, error) {
- return p.run(host, "sh -s", strings.NewReader(script), timeout, true)
- }
- // run abre una sesión, ejecuta cmd (alimentando stdin si no es nil) y devuelve
- // stdout. Comparte el manejo de stderr, drop por canal roto y timeout entre
- // Run y RunScript.
- func (p *SSHPool) run(host, cmd string, stdin io.Reader, timeout time.Duration, mergeStderr bool) (string, error) {
- if timeout <= 0 {
- timeout = sshDefaultTimeout
- }
- client, err := p.dial(host)
- if err != nil {
- return "", err
- }
- session, err := client.NewSession()
- if err != nil {
- p.drop(host)
- return "", fmt.Errorf("ssh %s: session: %w", host, err)
- }
- defer session.Close()
- session.Stdin = stdin
- type result struct {
- out []byte
- err error
- stderr string
- }
- ch := make(chan result, 1)
- go func() {
- var errBuf strings.Builder
- session.Stderr = &errBuf
- out, err := session.Output(cmd)
- ch <- result{out, err, errBuf.String()}
- }()
- select {
- case res := <-ch:
- body := string(res.out)
- if mergeStderr {
- body = mergeScriptOutput(body, res.stderr)
- }
- if res.err != nil {
- var ee *ssh.ExitError
- if !errors.As(res.err, &ee) {
- p.drop(host) // canal roto, no exit status
- }
- // #1894: la salida se devuelve aunque el comando falle. Antes se
- // tiraba, y con ella el motivo real del fallo.
- if msg := sshErrDetail(res.stderr); msg != "" {
- return body, fmt.Errorf("ssh %s: %w: %s", host, res.err, msg)
- }
- return body, fmt.Errorf("ssh %s: %w", host, res.err)
- }
- return body, nil
- case <-time.After(timeout):
- // Timeout: cerrar solo la sesión. NO dropear el cliente entero: el
- // pool permite sesiones concurrentes sobre el mismo router y un
- // comando lento no debe cortar las demás (issue #205).
- _ = session.Close()
- return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
- }
- }
- // RunCtx es Run con cancelación por contexto.
- func (p *SSHPool) RunCtx(ctx context.Context, host, cmd string, timeout time.Duration) (string, error) {
- if timeout <= 0 {
- timeout = sshDefaultTimeout
- }
- client, err := p.dial(host)
- if err != nil {
- return "", err
- }
- session, err := client.NewSession()
- if err != nil {
- p.drop(host)
- return "", fmt.Errorf("ssh %s: session: %w", host, err)
- }
- defer session.Close()
- type result struct {
- out []byte
- err error
- stderr string
- }
- ch := make(chan result, 1)
- go func() {
- var errBuf strings.Builder
- session.Stderr = &errBuf
- out, err := session.Output(cmd)
- ch <- result{out, err, errBuf.String()}
- }()
- select {
- case res := <-ch:
- if res.err != nil {
- var ee *ssh.ExitError
- if !errors.As(res.err, &ee) {
- p.drop(host) // canal roto, no exit status
- }
- // #1894: misma razón que en run(), la salida vuelve con el error.
- if msg := sshErrDetail(res.stderr); msg != "" {
- return string(res.out), fmt.Errorf("ssh %s: %w: %s", host, res.err, msg)
- }
- return string(res.out), fmt.Errorf("ssh %s: %w", host, res.err)
- }
- return string(res.out), nil
- case <-time.After(timeout):
- _ = session.Close()
- return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
- case <-ctx.Done():
- // Cancelación del cliente: cerrar la sesión para abortar el comando
- // remoto y liberar la goroutine (issue #204). Sin drop: es una
- // cancelación del llamador, no un fallo de la conexión.
- _ = session.Close()
- return "", ctx.Err()
- }
- }
- // Close cierra todas las conexiones del pool.
- func (p *SSHPool) Close() {
- p.mu.Lock()
- defer p.mu.Unlock()
- if p.closed {
- return
- }
- p.closed = true
- for _, e := range p.conns {
- if e.client != nil {
- _ = p.closeSSHClient(e.client)
- e.client = nil
- }
- }
- }
- func min(a, b int) int {
- if a < b {
- return a
- }
- return b
- }
|