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

fix(ssh): require explicit confirmation to re-onboard a changed host key (#603) (#609)

On a known host whose key changed, the pool previously auto-refreshed the
known_hosts entry (accept-new with refresh), silently negating the MITM
protection (#567/#582). In a public project that may not always run on a
trusted LAN, a changed host key is a security event: the pool now rejects
the connection and marks the router 'unreachable/hostKeyChanged'. An admin
must explicitly confirm the re-onboard (POST /api/routers/{id}/accept-host-key),
which removes the known_hosts entry and re-runs TOFU on the next poll.
Adds a warning banner + confirm button in the router detail when the host
key changed. Host key type note: it is whichever the router's dropbear
presents (ssh-rsa in our OpenWrt fleet); NetPulse does not force RSA.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 месяцев назад
Родитель
Сommit
01b04eedeb

+ 5 - 0
app/public/locales/en/translation.json

@@ -562,6 +562,11 @@
     },
     "notFound": "Router not found",
     "notFoundDesc": "There is no device with the identifier \"{{id}}\".",
+    "hostKeyTitle": "SSH host key changed",
+    "hostKeyBody": "The SSH host key presented by this device no longer matches the recorded one. To protect against a man-in-the-middle attack, NetPulse has blocked the connection. If you just reinstalled or flashed the device, confirm the new key to reconnect.",
+    "hostKeyConfirm": "Confirm new key",
+    "hostKeyBusy": "Confirming…",
+    "hostKeyDone": "Key accepted: reconnecting…",
     "perf": {
       "chartAria": "{{label}} of {{name}}, range {{range}}. Current value {{value}} {{unit}}.",
       "maxTemp": "max {{temp}} °C",

+ 5 - 0
app/public/locales/es/translation.json

@@ -562,6 +562,11 @@
     },
     "notFound": "Router no encontrado",
     "notFoundDesc": "No existe ningún equipo con el identificador «{{id}}».",
+    "hostKeyTitle": "Clave SSH del equipo cambiada",
+    "hostKeyBody": "La clave SSH que presenta este equipo no coincide con la registrada. Para protegerte de un posible ataque de intermediario (MITM), NetPulse ha bloqueado la conexión. Si acabas de reinstalar o flashear el equipo, confirma la nueva clave para volver a conectarte.",
+    "hostKeyConfirm": "Confirmar nueva clave",
+    "hostKeyBusy": "Confirmando…",
+    "hostKeyDone": "Clave aceptada: reconectando…",
     "perf": {
       "chartAria": "{{label}} de {{name}}, rango {{range}}. Valor actual {{value}} {{unit}}.",
       "maxTemp": "máx {{temp}} °C",

+ 6 - 0
app/src/data/types.ts

@@ -39,6 +39,12 @@ export interface Router {
   status: Status
   /** Salud 0–100 */
   health: number
+  /**
+   * #603: el router responde pero su host key SSH no casa con la registrada.
+   * La conexión se rechaza (posible MITM) hasta que el admin confirme el
+   * re-onboard explícito (POST /api/routers/{id}/accept-host-key).
+   */
+  hostKeyChanged?: boolean
   /**
    * #441: false cuando la fuente del router no puede reportar métricas de
    * sistema (switch SNMP o pusher beacon/scraper). En ese caso cpu/ram/temp

+ 47 - 1
app/src/pages/RouterDetail.tsx

@@ -1,11 +1,12 @@
 import { useEffect, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link, useLocation, useParams } from 'react-router'
-import { AlertTriangle, ArrowLeft, Gauge, Router as RouterIcon } from 'lucide-react'
+import { AlertTriangle, ArrowLeft, Gauge, Router as RouterIcon, ShieldAlert } from 'lucide-react'
 import { motion, useReducedMotion } from 'framer-motion'
 import { relTime } from '@/i18n'
 import { useNetPulse } from '@/data/DataProvider'
 import type { RouterDetailData } from '@/data/DataProvider'
+import { useAuth } from '@/data/AuthContext'
 import { AdGuardPanel } from '@/components/routers/AdGuardPanel'
 import { BackhaulPanel } from '@/components/routers/BackhaulPanel'
 import { PortPanel } from '@/components/routers/PortPanel'
@@ -25,10 +26,26 @@ export default function RouterDetail() {
   const { id = '' } = useParams()
   const location = useLocation()
   const reduce = useReducedMotion()
+  const auth = useAuth()
+  const isAdmin = auth?.role === 'admin'
   const { routers, alerts, getRouterDetail } = useNetPulse()
   const router = routers.find((r) => r.id === id)
   const isGateway = router?.roleBadge === 'Principal'
   const [detail, setDetail] = useState<RouterDetailData | null>(null)
+  const [hkBusy, setHkBusy] = useState(false)
+  const [hkDone, setHkDone] = useState(false)
+
+  // #603: confirmación explícita del re-onboard tras una host key cambiada.
+  async function handleAcceptHostKey() {
+    if (hkBusy) return
+    setHkBusy(true)
+    try {
+      const res = await fetch(`/api/routers/${encodeURIComponent(id)}/accept-host-key`, { method: 'POST' })
+      if (res.status === 202 || res.status === 200) setHkDone(true)
+    } finally {
+      setHkBusy(false)
+    }
+  }
 
   // Detalle vivo del backend (extras: radios, bocas LAN con dispositivo, info)
   // NO se nullea al refrescar ni se sustituye si no cambia nada: evita
@@ -94,6 +111,35 @@ export default function RouterDetail() {
         <RouterDetailHeader router={router} />
       </div>
 
+      {/* #603: host key cambiada → requiere re-onboard explícito (MITM) */}
+      {router.hostKeyChanged && (
+        <motion.div
+          initial={reduce ? false : { opacity: 0, y: -8 }}
+          animate={{ opacity: 1, y: 0 }}
+          transition={{ duration: 0.3, ease: 'easeOut', delay: 0.35 }}
+          className="lg:col-span-12"
+        >
+          <div role="alert" className="flex items-start gap-3 rounded-2xl border border-danger/50 bg-danger/10 px-5 py-4">
+            <ShieldAlert className="mt-0.5 h-5 w-5 shrink-0 text-danger" strokeWidth={1.75} />
+            <div className="min-w-0 flex-1">
+              <div className="text-sm font-semibold text-danger">{t('routerDetail.hostKeyTitle')}</div>
+              <p className="mt-0.5 text-sm text-text-secondary">{t('routerDetail.hostKeyBody')}</p>
+              {hkDone && <p className="mt-1 text-sm font-medium text-ok">{t('routerDetail.hostKeyDone')}</p>}
+            </div>
+            {isAdmin && !hkDone && (
+              <button
+                type="button"
+                onClick={() => void handleAcceptHostKey()}
+                disabled={hkBusy}
+                className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-danger/40 bg-canvas px-3 py-2 text-sm font-semibold text-danger transition-colors hover:border-danger disabled:opacity-50"
+              >
+                {hkBusy ? t('routerDetail.hostKeyBusy') : t('routerDetail.hostKeyConfirm')}
+              </button>
+            )}
+          </div>
+        </motion.div>
+      )}
+
       {/* Banner contextual (Patio) */}
       {router.status === 'warn' && router.hotMetric === 'temp' && (
         <motion.div

+ 57 - 3
server-go/internal/adapters/live.go

@@ -1210,6 +1210,10 @@ func (l *Live) offlineRouter(cfg RouterConfig) Router {
 		r.Status = "unreachable"
 		r.AccessMissing = true
 	}
+	if l.hostKeyChanged(cfg.ID) {
+		r.Status = "unreachable"
+		r.HostKeyChanged = true
+	}
 	return r
 }
 
@@ -1222,6 +1226,44 @@ func (l *Live) accessMissing(routerID string) bool {
 	return isAccessError(l.lastErr[routerID])
 }
 
+// hostKeyChanged: el último fallo de sondeo fue una clave SSH distinta a la
+// registrada (issue #603). El router está vivo; la conexión se rechaza hasta
+// que el admin confirme el re-onboard.
+func (l *Live) hostKeyChanged(routerID string) bool {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	return isHostKeyError(l.lastErr[routerID])
+}
+
+// AcceptHostKey confirma el re-onboard de un router tras una host key cambiada
+// (#603): borra su entrada known_hosts (siguiente sondeo = TOFU) y resetea el
+// error para que el router deje de mostrarse como "host key changed".
+func (l *Live) AcceptHostKey(routerID string) error {
+	if l.pool == nil {
+		return errors.New("ssh pool no configurado")
+	}
+	l.mu.Lock()
+	var host string
+	for _, c := range l.routers {
+		if c.ID == routerID {
+			host = c.Host
+			break
+		}
+	}
+	l.mu.Unlock()
+	if host == "" {
+		return fmt.Errorf("router %q no configurado", routerID)
+	}
+	if err := l.pool.RemoveHostKey(host); err != nil {
+		return err
+	}
+	l.mu.Lock()
+	delete(l.lastErr, routerID)
+	l.failCount[routerID] = 0
+	l.mu.Unlock()
+	return nil
+}
+
 // isAccessError: ¿el error indica que el router RESPONDE pero el acceso
 // SSH/ubus no está configurado? (handshake SSH que rechaza la clave del
 // servidor). Un fallo de conexión (refused/timeout/red) NO es un fallo de
@@ -1245,6 +1287,17 @@ func isAccessError(err error) bool {
 	return false
 }
 
+// isHostKeyError: el router responde pero su host key no casa con la
+// registrada (issue #603). No es un fallo de acceso ni una caída: requiere
+// confirmación explícita de re-onboard.
+func isHostKeyError(err error) bool {
+	if err == nil {
+		return false
+	}
+	var hk *HostKeyChangedError
+	return errors.As(err, &hk) || strings.Contains(strings.ToLower(err.Error()), "re-onboard required")
+}
+
 // pollAll sondea todos los routers en paralelo (Promise.allSettled).
 func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 	l.mu.Lock()
@@ -1309,9 +1362,10 @@ func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 		// Alerta solo tras 2 fallos seguidos (un fallo suelto no es una caída).
 		// issue #257: un fallo de ACCESO (SSH responde pero la clave no está
 		// autorizada) no es una caída — el router está vivo; la UI lo marca
-		// como "sin acceso" y no merece una alerta crítica de offline.
-		accessErr := isAccessError(res.err)
-		if fails >= 2 && l.lastStatus[res.cfg.ID] != "offline" && !accessErr {
+		// como "sin acceso" y no merece una alerta crítica de offline. Igual
+		// para una host key cambiada (#603): requiere re-onboard, no es offline.
+		quietErr := isAccessError(res.err) || isHostKeyError(res.err)
+		if fails >= 2 && l.lastStatus[res.cfg.ID] != "offline" && !quietErr {
 			name := res.cfg.Name
 			if name == "" {
 				name = res.cfg.Host

+ 30 - 14
server-go/internal/adapters/sshpool.go

@@ -89,14 +89,18 @@ func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
 		}
 		var keyErr *knownhosts.KeyError
 		if errors.As(err, &keyErr) && len(keyErr.Want) > 0 {
-			// 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)
+			// 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("ssh %s: host key changed (%s -> %s); re-onboard requerido", hostname, oldFP, newFP)
+			return &HostKeyChangedError{Host: hostname, OldFP: oldFP, NewFP: newFP}
 		}
 		// Host desconocido → accept-new
 		line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
@@ -110,12 +114,25 @@ 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 {
+// 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"
+}
+
+// RemoveHostKey elimina la entrada 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.
+func (p *SSHPool) RemoveHostKey(hostname string) 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") {
@@ -138,7 +155,6 @@ func (p *SSHPool) refreshHostKey(hostname string, key ssh.PublicKey) error {
 			}
 		}
 	}
-	keep = append(keep, line)
 	return os.WriteFile(p.khPath, []byte(strings.Join(keep, "\n")+"\n"), 0o600)
 }
 

+ 16 - 17
server-go/internal/adapters/sshpool_test.go

@@ -147,9 +147,9 @@ func genTestKey(t *testing.T) (ssh.Signer, ssh.PublicKey) {
 	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) {
+// TestRemoveHostKeyEliminaEntrada: RemoveHostKey quita la línea del host,
+// conserva los demás hosts y deja el fichero sin esa entrada (#603).
+func TestRemoveHostKeyEliminaEntrada(t *testing.T) {
 	pool := newTestPool(t)
 	host := "host.example"
 	other := "other.example"
@@ -162,27 +162,24 @@ func TestRefreshHostKeyReplacesEntry(t *testing.T) {
 		t.Fatal(err)
 	}
 
-	_, newPub := genTestKey(t)
-	if err := pool.refreshHostKey(host, newPub); err != nil {
+	if err := pool.RemoveHostKey(host); 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, knownhosts.Normalize(host)) {
+		t.Fatal("la entrada 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) {
+// TestHostKeyCallbackRejectsChangedKey: una clave conocida pero distinta NO se
+// acepta en silencio: el callback devuelve HostKeyChangedError y no toca el
+// known_hosts (#603). El re-onboard es una confirmación explícita del admin.
+func TestHostKeyCallbackRejectsChangedKey(t *testing.T) {
 	pool := newTestPool(t)
 	host := "host.example"
 	_, oldPub := genTestKey(t)
@@ -196,11 +193,13 @@ func TestHostKeyCallbackReOnboardsOnChangedKey(t *testing.T) {
 		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)
+	err = cb(host+":22", &net.TCPAddr{IP: net.ParseIP("1.2.3.4"), Port: 22}, newPub)
+	var hk *HostKeyChangedError
+	if !errors.As(err, &hk) {
+		t.Fatalf("clave cambiada debería devolver HostKeyChangedError, obtuve: %v", err)
 	}
 	data, _ := os.ReadFile(pool.khPath)
-	if !strings.Contains(string(data), knownhosts.Normalize(host)) {
-		t.Fatal("no se re-onboardó el host")
+	if !strings.Contains(string(data), oldLine) {
+		t.Fatal("el known_hosts no debería tocarse al rechazar la clave cambiada")
 	}
 }

+ 13 - 9
server-go/internal/adapters/types.go

@@ -168,19 +168,23 @@ type Router struct {
 	// AccessMissing: el router responde pero el acceso SSH/ubus no está
 	// configurado (clave del servidor no autorizada) — issue #257. La UI lo
 	// pinta como "sin acceso" en vez de "offline" (config issue, no power).
-	AccessMissing bool      `json:"accessMissing,omitempty"`
+	AccessMissing bool `json:"accessMissing,omitempty"`
+	// HostKeyChanged: el host presenta una clave SSH distinta a la registrada
+	// (issue #603). Se rechaza la conexión (posible MITM) hasta que el admin
+	// confirme el re-onboard explícito tras verificar fuera de banda.
+	HostKeyChanged bool `json:"hostKeyChanged,omitempty"`
 	// VitalsAvailable: false cuando la fuente de datos del router no puede
 	// reportar métricas de sistema (#441): switches sondeados por SNMP (#309)
 	// o pushers externos por beacon/scraper (#291). En ese caso CPU/RAM/Temp
 	// van a null y la UI no los pinta. Ausente = vitals disponibles.
-	VitalsAvailable *bool  `json:"vitalsAvailable,omitempty"`
-	CPU             *int   `json:"cpu"`
-	RAM             *int   `json:"ram"`
-	Temp            *int   `json:"temp"`
-	Uptime        string    `json:"uptime"` // "<d>d <h>h" | "—"
-	Clients       int       `json:"clients"`
-	HotMetric     string    `json:"hotMetric,omitempty"` // "temp" solo si temp>65
-	Sparkline     []float64 `json:"sparkline"`
+	VitalsAvailable *bool     `json:"vitalsAvailable,omitempty"`
+	CPU             *int      `json:"cpu"`
+	RAM             *int      `json:"ram"`
+	Temp            *int      `json:"temp"`
+	Uptime          string    `json:"uptime"` // "<d>d <h>h" | "—"
+	Clients         int       `json:"clients"`
+	HotMetric       string    `json:"hotMetric,omitempty"` // "temp" solo si temp>65
+	Sparkline       []float64 `json:"sparkline"`
 	// Backhaul: medio del uplink del router ("cable"|"wifi"). Ausente =
 	// cable/desconocido (router sin wifi o sonda no disponible).
 	Backhaul string `json:"backhaul,omitempty"`

+ 36 - 0
server-go/internal/httpapi/hostkey.go

@@ -0,0 +1,36 @@
+package httpapi
+
+// hostkey.go — confirmación explícita de re-onboard SSH tras una host key
+// cambiada (issue #603). La conexión a un host con clave distinta se rechaza
+// (posible MITM); este endpoint, admin-only, borra la entrada known_hosts y
+// fuerza un sondeo para que la nueva clave se registre con TOFU.
+
+import (
+	"net/http"
+)
+
+// handleAcceptHostKey: POST /api/routers/{id}/accept-host-key (admin).
+func (s *server) handleAcceptHostKey(w http.ResponseWriter, r *http.Request) {
+	id := r.PathValue("id")
+	if id == "" {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	acc, ok := s.adapter.(interface {
+		AcceptHostKey(routerID string) error
+	})
+	if !ok {
+		writeError(w, http.StatusServiceUnavailable, "unavailable", "el adapter no soporta aceptar host key")
+		return
+	}
+	if err := acc.AcceptHostKey(id); err != nil {
+		writeError(w, http.StatusNotFound, "not_found", err.Error())
+		return
+	}
+	// Sondeo inmediato: al no quedar entrada, el dial vuelve a hacer TOFU y el
+	// router recupera el estado online si la clave nueva es legítima.
+	if s.pollNow != nil {
+		s.pollNow()
+	}
+	writeJSON(w, http.StatusAccepted, map[string]any{"ok": true})
+}

+ 2 - 1
server-go/internal/httpapi/server.go

@@ -36,13 +36,13 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/configbackup"
 	"github.com/gnacho/netpulse/server-go/internal/db"
 	"github.com/gnacho/netpulse/server-go/internal/firmware"
-	"github.com/gnacho/netpulse/server-go/internal/speedtest"
 	"github.com/gnacho/netpulse/server-go/internal/internethealth"
 	"github.com/gnacho/netpulse/server-go/internal/orchestr"
 	"github.com/gnacho/netpulse/server-go/internal/pathanalysis"
 	"github.com/gnacho/netpulse/server-go/internal/presence"
 	"github.com/gnacho/netpulse/server-go/internal/rearmer"
 	"github.com/gnacho/netpulse/server-go/internal/security"
+	"github.com/gnacho/netpulse/server-go/internal/speedtest"
 	"github.com/gnacho/netpulse/server-go/internal/sse"
 	"github.com/gnacho/netpulse/server-go/internal/staticspa"
 	"github.com/gnacho/netpulse/server-go/internal/updater"
@@ -316,6 +316,7 @@ func NewHandler(d Deps) http.Handler {
 	mux.HandleFunc("GET /api/device-events", s.handleDeviceEvents)
 	mux.HandleFunc("GET /api/adguard/clients", s.handleAdguardClients)
 	mux.HandleFunc("GET /api/routers/{id}/ports/{portId}/series", s.handlePortSeries)
+	mux.Handle("POST /api/routers/{id}/accept-host-key", auth.RequireAdmin(http.HandlerFunc(s.handleAcceptHostKey)))
 	mux.HandleFunc("GET /api/devices/{mac}/traffic", s.handleDeviceTraffic)
 	mux.HandleFunc("GET /api/system/info", s.handleSystemInfo)
 	mux.HandleFunc("GET /api/reports/weekly", s.handleWeeklyReport)