Просмотр исходного кода

fix(ssh): re-onboard the router host key on change instead of rejecting (#582)

The discovery probe (system ssh) and the Go pool negotiate a different
host key algorithm and share the known_hosts file, so a mismatch between
the recorded key (e.g. ed25519) and the presented one (rsa) made the pool
reject the connection (MITM protection) and dropbear saw 'Exit before
auth', locking out routers whose swap/flash rotated the key. On a known
but different key the pool now logs a warning and replaces the entry
(accept-new with refresh), matching the self-hosted LAN trust model. The
operator explicitly onboards each router and authorizes the NetPulse key.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 месяцев назад
Родитель
Сommit
cec823bd53
2 измененных файлов с 121 добавлено и 1 удалено
  1. 42 1
      server-go/internal/adapters/sshpool.go
  2. 79 0
      server-go/internal/adapters/sshpool_test.go

+ 42 - 1
server-go/internal/adapters/sshpool.go

@@ -12,9 +12,11 @@ import (
 	"context"
 	"errors"
 	"fmt"
+	"log"
 	"net"
 	"os"
 	"path/filepath"
+	"strings"
 	"sync"
 	"time"
 
@@ -87,7 +89,14 @@ func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
 		}
 		var keyErr *knownhosts.KeyError
 		if errors.As(err, &keyErr) && len(keyErr.Want) > 0 {
-			return err // clave CAMBIADA → rechazar
+			// Clave cambiada (#567): el probe de discovery (ssh del sistema) y el
+			// pool (librería Go) pueden negociar un algoritmo de host-key distinto
+			// y comparten el mismo known_hosts. Antes se rechazaba (MITM), lo que
+			// bloqueaba routers cuyo swap/flash rotó la clave. En un monitor LAN
+			// self-hosted re-onboardamos con aviso (accept-new con refresh).
+			log.Printf("ssh %s: host key changed (%s -> %s); re-onboarding",
+				hostname, ssh.FingerprintSHA256(keyErr.Want[0].Key), ssh.FingerprintSHA256(key))
+			return p.refreshHostKey(hostname, key)
 		}
 		// Host desconocido → accept-new
 		line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
@@ -101,6 +110,38 @@ func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
 	}, nil
 }
 
+// refreshHostKey reemplaza la entrada known_hosts de un host por la clave nueva
+// (#567). Quita las líneas previas de ese host (la lista de hosts de una línea
+// puede ser separada por comas) y añade la nueva.
+func (p *SSHPool) refreshHostKey(hostname string, key ssh.PublicKey) error {
+	norm := knownhosts.Normalize(hostname)
+	line := knownhosts.Line([]string{norm}, key)
+	var keep []string
+	if data, err := os.ReadFile(p.khPath); err == nil {
+		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 knownhosts.Normalize(h) == norm {
+					drop = true
+					break
+				}
+			}
+			if !drop {
+				keep = append(keep, ln)
+			}
+		}
+	}
+	keep = append(keep, line)
+	return os.WriteFile(p.khPath, []byte(strings.Join(keep, "\n")+"\n"), 0o600)
+}
+
 // 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) {

+ 79 - 0
server-go/internal/adapters/sshpool_test.go

@@ -1,15 +1,19 @@
 package adapters
 
 import (
+	"crypto/ed25519"
+	"crypto/rand"
 	"errors"
 	"net"
 	"os"
+	"strings"
 	"sync"
 	"sync/atomic"
 	"testing"
 	"time"
 
 	"golang.org/x/crypto/ssh"
+	"golang.org/x/crypto/ssh/knownhosts"
 )
 
 func newTestPool(t *testing.T) *SSHPool {
@@ -125,3 +129,78 @@ func TestSSHPoolSingleFlight_LeaderFails(t *testing.T) {
 		t.Errorf("%d errores, esperaba %d", failures, N)
 	}
 }
+
+func genTestKey(t *testing.T) (ssh.Signer, ssh.PublicKey) {
+	t.Helper()
+	_, priv, err := ed25519.GenerateKey(rand.Reader)
+	if err != nil {
+		t.Fatal(err)
+	}
+	signer, err := ssh.NewSignerFromKey(priv)
+	if err != nil {
+		t.Fatal(err)
+	}
+	pub, err := ssh.NewPublicKey(priv.Public())
+	if err != nil {
+		t.Fatal(err)
+	}
+	return signer, pub
+}
+
+// TestRefreshHostKeyReplacesEntry: el refresh reemplaza la línea del host por la
+// clave nueva, conserva los demás hosts y deja UNA sola entrada (#567).
+func TestRefreshHostKeyReplacesEntry(t *testing.T) {
+	pool := newTestPool(t)
+	host := "host.example"
+	other := "other.example"
+
+	_, oldPub := genTestKey(t)
+	_, otherPub := genTestKey(t)
+	oldLine := knownhosts.Line([]string{knownhosts.Normalize(host)}, oldPub) + "\n"
+	otherLine := knownhosts.Line([]string{knownhosts.Normalize(other)}, otherPub) + "\n"
+	if err := os.WriteFile(pool.khPath, []byte(oldLine+otherLine), 0o600); err != nil {
+		t.Fatal(err)
+	}
+
+	_, newPub := genTestKey(t)
+	if err := pool.refreshHostKey(host, newPub); err != nil {
+		t.Fatal(err)
+	}
+
+	data, _ := os.ReadFile(pool.khPath)
+	s := string(data)
+	if strings.Contains(s, oldLine) {
+		t.Fatal("la línea antigua del host no se eliminó")
+	}
+	if !strings.Contains(s, otherLine) {
+		t.Fatal("se perdió un host no relacionado")
+	}
+	if n := strings.Count(s, knownhosts.Normalize(host)); n != 1 {
+		t.Fatalf("esperaba 1 entrada para %s, hay %d", host, n)
+	}
+}
+
+// TestHostKeyCallbackReOnboardsOnChangedKey: una clave conocida pero distinta
+// ya NO se rechaza; el callback re-onboarda (nil) y actualiza la entrada (#567).
+func TestHostKeyCallbackReOnboardsOnChangedKey(t *testing.T) {
+	pool := newTestPool(t)
+	host := "host.example"
+	_, oldPub := genTestKey(t)
+	oldLine := knownhosts.Line([]string{knownhosts.Normalize(host)}, oldPub) + "\n"
+	if err := os.WriteFile(pool.khPath, []byte(oldLine), 0o600); err != nil {
+		t.Fatal(err)
+	}
+
+	cb, err := pool.hostKeyCallback()
+	if err != nil {
+		t.Fatal(err)
+	}
+	_, newPub := genTestKey(t)
+	if err := cb(host, &net.IPAddr{IP: net.ParseIP("1.2.3.4")}, newPub); err != nil {
+		t.Fatalf("callback devolvió error en clave cambiada: %v", err)
+	}
+	data, _ := os.ReadFile(pool.khPath)
+	if !strings.Contains(string(data), knownhosts.Normalize(host)) {
+		t.Fatal("no se re-onboardó el host")
+	}
+}