Răsfoiți Sursa

fix(openwrt): make the on-box package work on OpenWrt 21.02 (#1712)

* fix(openwrt): make the on-box package work on OpenWrt 21.02 (#1701)

* chore(test): shorten fixture password and ignore the historical gitleaks finding
Nacho 1 lună în urmă
părinte
comite
eaffb8a323

+ 3 - 0
.gitleaksignore

@@ -12,3 +12,6 @@ c4cd4538a3187d7fa8e0b0fe2bdd5d95aafe245c:server-go/internal/httpapi/migrate_e2e_
 4f148778c2f94962f8a9f50f8942e6eb974d9ed2:server-go/internal/orchestr/dawn_test.go:generic-api-key:36
 4f148778c2f94962f8a9f50f8942e6eb974d9ed2:server-go/internal/orchestr/dawn_test.go:generic-api-key:36
 4f148778c2f94962f8a9f50f8942e6eb974d9ed2:server-go/internal/orchestr/dawn_test.go:generic-api-key:135
 4f148778c2f94962f8a9f50f8942e6eb974d9ed2:server-go/internal/orchestr/dawn_test.go:generic-api-key:135
 4f148778c2f94962f8a9f50f8942e6eb974d9ed2:server-go/internal/orchestr/dawn_test.go:generic-api-key:192
 4f148778c2f94962f8a9f50f8942e6eb974d9ed2:server-go/internal/orchestr/dawn_test.go:generic-api-key:192
+
+# Test fixture password (not a real secret): 12 chars like the rest of the login fixtures
+0fd67095b177b06a25bb95f9d1fdfb059b6e5068:server-go/internal/httpapi/users_uci_password_test.go:generic-api-key:24

+ 8 - 0
CHANGELOG.md

@@ -10,6 +10,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 ### Added
 ### Added
 
 
 - Inactive agents in the fleet table now offer Rearm, Reinstall and the copyable install command next to Remove, so a rejected token (HTTP 401 after a reboot or a server move) can be fixed without removing the agent or losing its history. NetGrip rows offer Rearm only and external pushers keep Remove only.
 - Inactive agents in the fleet table now offer Rearm, Reinstall and the copyable install command next to Remove, so a rejected token (HTTP 401 after a reboot or a server move) can be fixed without removing the agent or losing its history. NetGrip rows offer Rearm only and external pushers keep Remove only.
+- The on-box server init script now refuses to start when its data dir is not a real mount (default overlay paths excluded), so an unmounted USB stick can no longer leave a fresh SQLite database on flash. It also moves to `START=99` to let USB mounts settle first.
 
 
 ### Changed
 ### Changed
 
 
@@ -18,6 +19,13 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 ### Fixed
 ### Fixed
 
 
 - The greeting line on the Overview ("N important alerts") now counts the same alerts as the bell and the Alerts page (unread, level-filtered), instead of the health score breakdown. A health penalty without a visible alert, such as a down VPN peer with the vpn category set to "Nada", used to leave a phantom counter that could not be cleared from anywhere (#1707).
 - The greeting line on the Overview ("N important alerts") now counts the same alerts as the bell and the Alerts page (unread, level-filtered), instead of the health score breakdown. A health penalty without a visible alert, such as a down VPN peer with the vpn category set to "Nada", used to leave a phantom counter that could not be cleared from anywhere (#1707).
+- OpenWrt 21.02 on-box package (GL.iNet GL-MT6000 report): the `.ipk` now installs `/etc/init.d/netpulse`, the agent init and the uci-defaults scripts as executable (`0755`), and the packaging scripts verify the modes inside the built `.ipk`.
+- OpenWrt 21.02 on-box package: the procd init now uses ONE `procd_set_param env` call with all variables (in 21.02 each extra call overwrote the previous one, so `NETPULSE_ONBOX` and `DATA_DIR` never reached the process), and `stdout`/`stderr` are set as boolean params so server logs show up in `logread`.
+- Gateway autodetection no longer picks the ISP-side (public or CGNAT) address on an on-box server: when the default route's via is not a private LAN address, the gateway is the router itself and its LAN IP is taken from the private subnet route. Dedicated LAN servers keep the previous behavior.
+- The server generates its SSH keypair in-process (crypto/ed25519 + x/crypto/ssh) instead of calling `ssh-keygen`: on OpenWrt 21.02 the available keygen is Dropbear's and writes a format crypto/ssh cannot parse, which silently degraded the server to the demo dataset. An existing unparseable key is backed up and regenerated, and the public key fingerprint is computed in-process.
+- The default on-box port is now 3100 instead of 3000, which collides with the AdGuard Home UI shipped by GL.iNet firmware. Existing installs keep their configured port.
+- The initial bootstrap password is removed from UCI after a password change, so the generated plaintext no longer stays in `/etc/config/netpulse` forever.
+- README: `DEMO_MODE=1` requires `AUTH_PASS` even in demo mode, and the settings section holding the SSH public key is called Fleet (formerly documented as Network).
 
 
 ## [2.49.4] - 2026-10-30
 ## [2.49.4] - 2026-10-30
 
 

+ 3 - 2
README.es.md

@@ -198,7 +198,7 @@ primer arranque por descubrimiento LAN (barrido TCP :22 con fingerprinting
 ubus/GL-UI).
 ubus/GL-UI).
 
 
 **3. Autoriza la clave SSH.** El servidor generó su propio par de claves en
 **3. Autoriza la clave SSH.** El servidor generó su propio par de claves en
-el primer arranque. Copia la clave pública desde **Ajustes → Red** y, en cada
+el primer arranque. Copia la clave pública desde **Ajustes → Flota** y, en cada
 router que quieras monitorizar, añádela:
 router que quieras monitorizar, añádela:
 
 
 ```sh
 ```sh
@@ -218,8 +218,9 @@ de abajo). Asuswrt/Merlin utiliza el pusher externo descrito en esa sección.
 pantalla de inicio / Instalar app) y activa Web Push en Ajustes: las alertas
 pantalla de inicio / Instalar app) y activa Web Push en Ajustes: las alertas
 llegan al móvil aunque la pestaña esté cerrada.
 llegan al móvil aunque la pestaña esté cerrada.
 
 
-¿Prefieres verla primero en tu propio hardware? `DEMO_MODE=1 ./netpulse`
+¿Prefieres verla primero en tu propio hardware? `DEMO_MODE=1 AUTH_PASS=elige-una ./netpulse`
 levanta la misma app con una red de muestra de 67 dispositivos, sin routers.
 levanta la misma app con una red de muestra de 67 dispositivos, sin routers.
+`AUTH_PASS` es obligatoria también en modo demo: protege la sesión web.
 
 
 <details>
 <details>
 <summary><strong>Otras vías de instalación</strong></summary>
 <summary><strong>Otras vías de instalación</strong></summary>

+ 4 - 3
README.md

@@ -190,7 +190,7 @@ password and the gateway is already there: NetPulse finds it on first boot
 via LAN discovery (a TCP :22 sweep with ubus/GL-UI fingerprinting).
 via LAN discovery (a TCP :22 sweep with ubus/GL-UI fingerprinting).
 
 
 **3. Authorize the SSH key.** The server generated its own keypair on first
 **3. Authorize the SSH key.** The server generated its own keypair on first
-boot. Copy the public key from **Settings → Network** and, on each router you
+boot. Copy the public key from **Settings → Fleet** and, on each router you
 want to monitor, append it:
 want to monitor, append it:
 
 
 ```sh
 ```sh
@@ -210,8 +210,9 @@ uses the external pusher described there.
 screen / Install app) and enable Web Push in Settings: alerts reach your
 screen / Install app) and enable Web Push in Settings: alerts reach your
 phone even with the tab closed.
 phone even with the tab closed.
 
 
-Prefer to see it on your own hardware first? `DEMO_MODE=1 ./netpulse` runs
-the same app with a 67-device sample network, no routers needed.
+Prefer to see it on your own hardware first? `DEMO_MODE=1 AUTH_PASS=choose-one ./netpulse` runs
+the same app with a 67-device sample network, no routers needed. `AUTH_PASS`
+is required even in demo mode: it protects the web session.
 
 
 <details>
 <details>
 <summary><strong>Other install paths</strong></summary>
 <summary><strong>Other install paths</strong></summary>

+ 4 - 1
deploy/openwrt/netpulse-agent/files/netpulse-agent.init

@@ -83,7 +83,10 @@ start_service() {
 
 
 	procd_open_instance
 	procd_open_instance
 	procd_set_param command "$PROG"
 	procd_set_param command "$PROG"
-	procd_set_param stdout stderr  # logs vía procd a syslog
+	# Booleanos explícitos: "procd_set_param stdout stderr" no es válido y en
+	# OpenWrt 21.02 deja los logs sin redirigir a syslog (#1701).
+	procd_set_param stdout 1
+	procd_set_param stderr 1
 	procd_set_param respawn 3600 3600 0  # respawn con backoff de 1h (#851: ya sin watchdog cron)
 	procd_set_param respawn 3600 3600 0  # respawn con backoff de 1h (#851: ya sin watchdog cron)
 	procd_close_instance
 	procd_close_instance
 }
 }

+ 8 - 3
deploy/openwrt/netpulse-server/files/netpulse-server.config

@@ -4,11 +4,16 @@
 # Tras editar: /etc/init.d/netpulse reload + restart
 # Tras editar: /etc/init.d/netpulse reload + restart
 
 
 config server 'server'
 config server 'server'
-	# Puerto HTTP(S) del servidor (default 3000)
-	option port '3000'
+	# Puerto HTTP(S) del servidor. 3100 por defecto: en el firmware GL.iNet
+	# la UI de AdGuard Home ya usa 3000 (#1701). Cámbialo si el puerto
+	# está libre en tu equipo.
+	option port '3100'
 
 
-	# Directorio de datos (SQLite). Default: overlay.
+	# Directorio de datos (SQLite). Default: overlay (flash).
 	# Si hay USB montado: option data_dir '/mnt/netpulse-data'
 	# Si hay USB montado: option data_dir '/mnt/netpulse-data'
+	# Cualquier ruta fuera del overlay debe estar MONTADA al arrancar: el
+	# servicio se niega a arrancar sobre una ruta sin montaje para no
+	# crear la base de datos en flash (#1701).
 	option data_dir '/usr/local/netpulse-data'
 	option data_dir '/usr/local/netpulse-data'
 
 
 	# Usuario admin inicial (default: admin; la contraseña se genera en
 	# Usuario admin inicial (default: admin; la contraseña se genera en

+ 3 - 1
deploy/openwrt/netpulse-server/files/netpulse-server.defaults

@@ -7,7 +7,9 @@
 # Crear la sección server si no existe
 # Crear la sección server si no existe
 if ! uci -q get netpulse.server >/dev/null 2>&1; then
 if ! uci -q get netpulse.server >/dev/null 2>&1; then
 	uci -q set netpulse.server=server
 	uci -q set netpulse.server=server
-	uci -q set netpulse.server.port=3000
+	# 3100 en vez de 3000: la UI de AdGuard Home del firmware GL.iNet ya
+	# escucha en 3000 (#1701).
+	uci -q set netpulse.server.port=3100
 	uci -q set netpulse.server.data_dir=/usr/local/netpulse-data
 	uci -q set netpulse.server.data_dir=/usr/local/netpulse-data
 	uci -q set netpulse.server.auth_user=admin
 	uci -q set netpulse.server.auth_user=admin
 	uci -q commit netpulse
 	uci -q commit netpulse

+ 51 - 9
deploy/openwrt/netpulse-server/files/netpulse-server.init

@@ -1,31 +1,73 @@
 #!/bin/sh /etc/rc.common
 #!/bin/sh /etc/rc.common
-# netpulse-server — procd init script (Fase 9 R1)
+# netpulse-server - procd init script (Fase 9 R1)
 # Arranca el servidor NetPulse en modo on-box con config UCI.
 # Arranca el servidor NetPulse en modo on-box con config UCI.
+#
+# Compatibilidad OpenWrt 21.02 (#1701):
+#   - UNA sola llamada procd_set_param env con todas las variables: en 21.02
+#     cada llamada adicional pisa la anterior y solo sobrevive la ultima.
+#   - stdout y stderr son parametros booleanos ("1"), no palabras clave.
+#   - START=99 para dar tiempo a los montajes USB (block mount) antes de
+#     arrancar, mas una guardia que se niega a arrancar si data_dir apunta a
+#     un montaje ausente (evita crear la base de datos en flash).
 
 
-START=95
+START=99
 USE_PROCD=1
 USE_PROCD=1
 
 
 PROG=/usr/sbin/netpulse
 PROG=/usr/sbin/netpulse
 DATA_DIR=/usr/local/netpulse-data
 DATA_DIR=/usr/local/netpulse-data
+# 3000 colisiona con la UI de AdGuard Home del firmware GL.iNet (#1701)
+DEFAULT_PORT=3100
+
+# resolve_mount imprime el punto de montaje mas profundo que contiene a dir
+# ("/" si dir vive en el overlay raiz).
+resolve_mount() {
+	local dir="$1"
+	while [ "$dir" != "/" ]; do
+		if grep -qs " $dir " /proc/mounts; then
+			echo "$dir"
+			return 0
+		fi
+		dir="$(dirname "$dir")"
+	done
+	echo "/"
+}
 
 
 start_service() {
 start_service() {
-	# data_dir: overlay por defecto; USB si está montado
+	# data_dir: overlay por defecto; USB si esta montado
 	local data_dir
 	local data_dir
 	data_dir=$(uci -q get netpulse.server.data_dir 2>/dev/null)
 	data_dir=$(uci -q get netpulse.server.data_dir 2>/dev/null)
 	[ -z "$data_dir" ] && data_dir="$DATA_DIR"
 	[ -z "$data_dir" ] && data_dir="$DATA_DIR"
+	data_dir="${data_dir%/}"
+
+	# data_dir fuera del overlay por defecto: exigir un montaje real (#1701).
+	# Sin esta guardia, mkdir -p crearia el directorio (y la base de datos)
+	# en flash cuando el USB todavia no esta montado, y el servidor fallaria
+	# silenciosamente a escribir en el sitio previsto.
+	if [ "$data_dir" != "$DATA_DIR" ]; then
+		local mnt
+		mnt=$(resolve_mount "$data_dir")
+		if [ "$mnt" = "/" ]; then
+			echo "netpulse: data_dir '$data_dir' no esta sobre un montaje; no arranco para no escribir la base en flash"
+			logger -t netpulse "data_dir '$data_dir' no esta sobre un montaje; servicio no arrancado (monta el USB y ejecuta /etc/init.d/netpulse start)"
+			return 1
+		fi
+	fi
 	mkdir -p "$data_dir"
 	mkdir -p "$data_dir"
 
 
 	local port
 	local port
 	port=$(uci -q get netpulse.server.port 2>/dev/null)
 	port=$(uci -q get netpulse.server.port 2>/dev/null)
-	[ -z "$port" ] && port=3000
+	[ -z "$port" ] && port="$DEFAULT_PORT"
 
 
 	procd_open_instance
 	procd_open_instance
 	procd_set_param command "$PROG"
 	procd_set_param command "$PROG"
-	procd_set_param env NETPULSE_ONBOX=1
-	procd_set_param env DATA_DIR="$data_dir"
-	procd_set_param env PORT="$port"
-	procd_set_param stdout stderr  # logs vía procd a syslog
-	procd_set_param respawn 3600 5 0  # respawn tras crash (máx 5 en 1h)
+	# Una unica llamada env: en OpenWrt 21.02 cada llamada extra pisaria la
+	# anterior y al proceso solo le llegaria la ultima variable (#1701).
+	procd_set_param env NETPULSE_ONBOX=1 DATA_DIR="$data_dir" PORT="$port"
+	# Booleanos explicitos: "procd_set_param stdout stderr" no es valido y
+	# deja los logs sin redirigir a syslog en 21.02 (#1701).
+	procd_set_param stdout 1
+	procd_set_param stderr 1
+	procd_set_param respawn 3600 5 0  # respawn tras crash (max 5 en 1h)
 	procd_close_instance
 	procd_close_instance
 }
 }
 
 

+ 9 - 2
deploy/openwrt/package-server.sh

@@ -62,9 +62,12 @@ PKG_DIR="$WORK_DIR/netpulse-pkg"
 mkdir -p "$PKG_DIR/CONTROL" "$PKG_DIR/usr/sbin" "$PKG_DIR/etc/init.d" "$PKG_DIR/etc/config" "$PKG_DIR/etc/uci-defaults"
 mkdir -p "$PKG_DIR/CONTROL" "$PKG_DIR/usr/sbin" "$PKG_DIR/etc/init.d" "$PKG_DIR/etc/config" "$PKG_DIR/etc/uci-defaults"
 
 
 cp "$WORK_DIR/netpulse" "$PKG_DIR/usr/sbin/netpulse"
 cp "$WORK_DIR/netpulse" "$PKG_DIR/usr/sbin/netpulse"
-cp "$REPO_ROOT/deploy/openwrt/netpulse-server/files/netpulse-server.init" "$PKG_DIR/etc/init.d/netpulse"
+# Init script and uci-defaults MUST be 0755 (#1701): ipkg-build does not fix
+# permissions, and a 0644 init script fails with "Permission denied" during
+# uci-defaults on GL.iNet/OpenWrt 21.02, so the service never gets enabled.
+install -m 0755 "$REPO_ROOT/deploy/openwrt/netpulse-server/files/netpulse-server.init" "$PKG_DIR/etc/init.d/netpulse"
 cp "$REPO_ROOT/deploy/openwrt/netpulse-server/files/netpulse-server.config" "$PKG_DIR/etc/config/netpulse"
 cp "$REPO_ROOT/deploy/openwrt/netpulse-server/files/netpulse-server.config" "$PKG_DIR/etc/config/netpulse"
-cp "$REPO_ROOT/deploy/openwrt/netpulse-server/files/netpulse-server.defaults" "$PKG_DIR/etc/uci-defaults/95-netpulse-server"
+install -m 0755 "$REPO_ROOT/deploy/openwrt/netpulse-server/files/netpulse-server.defaults" "$PKG_DIR/etc/uci-defaults/95-netpulse-server"
 
 
 cat > "$PKG_DIR/CONTROL/control" << CTRL
 cat > "$PKG_DIR/CONTROL/control" << CTRL
 Package: netpulse
 Package: netpulse
@@ -108,6 +111,10 @@ if [ "$FORMAT" = "ipk" ]; then
   echo "  Building .ipk..."
   echo "  Building .ipk..."
   "$SDK_DIR/scripts/ipkg-build" "$PKG_DIR" "$OUT_DIR"
   "$SDK_DIR/scripts/ipkg-build" "$PKG_DIR" "$OUT_DIR"
   echo "  IPK: $(ls "$OUT_DIR"/netpulse_*.ipk 2>/dev/null || echo 'NOT FOUND')"
   echo "  IPK: $(ls "$OUT_DIR"/netpulse_*.ipk 2>/dev/null || echo 'NOT FOUND')"
+  verify_ipk_modes "$OUT_DIR"/netpulse_*.ipk \
+    "usr/sbin/netpulse=755" \
+    "etc/init.d/netpulse=755" \
+    "etc/uci-defaults/95-netpulse-server=755"
 
 
 elif [ "$FORMAT" = "apk" ]; then
 elif [ "$FORMAT" = "apk" ]; then
   echo "  Building .apk via SDK..."
   echo "  Building .apk via SDK..."

+ 9 - 2
deploy/openwrt/package.sh

@@ -70,9 +70,12 @@ PKG_DIR="$WORK_DIR/netpulse-agent-pkg"
 mkdir -p "$PKG_DIR/CONTROL" "$PKG_DIR/usr/sbin" "$PKG_DIR/etc/init.d" "$PKG_DIR/etc/config" "$PKG_DIR/etc/uci-defaults"
 mkdir -p "$PKG_DIR/CONTROL" "$PKG_DIR/usr/sbin" "$PKG_DIR/etc/init.d" "$PKG_DIR/etc/config" "$PKG_DIR/etc/uci-defaults"
 
 
 cp "$WORK_DIR/netpulse-agent" "$PKG_DIR/usr/sbin/netpulse-agent"
 cp "$WORK_DIR/netpulse-agent" "$PKG_DIR/usr/sbin/netpulse-agent"
-cp "$REPO_ROOT/deploy/openwrt/netpulse-agent/files/netpulse-agent.init" "$PKG_DIR/etc/init.d/netpulse-agent"
+# Init script and uci-defaults MUST be 0755 (#1701): ipkg-build does not fix
+# permissions, and a 0644 init script cannot be started or enabled on the
+# router.
+install -m 0755 "$REPO_ROOT/deploy/openwrt/netpulse-agent/files/netpulse-agent.init" "$PKG_DIR/etc/init.d/netpulse-agent"
 cp "$REPO_ROOT/deploy/openwrt/netpulse-agent/files/netpulse-agent.config" "$PKG_DIR/etc/config/netpulse-agent"
 cp "$REPO_ROOT/deploy/openwrt/netpulse-agent/files/netpulse-agent.config" "$PKG_DIR/etc/config/netpulse-agent"
-cp "$REPO_ROOT/deploy/openwrt/netpulse-agent/files/netpulse-agent.defaults" "$PKG_DIR/etc/uci-defaults/90-netpulse-agent"
+install -m 0755 "$REPO_ROOT/deploy/openwrt/netpulse-agent/files/netpulse-agent.defaults" "$PKG_DIR/etc/uci-defaults/90-netpulse-agent"
 
 
 # CONTROL files
 # CONTROL files
 cat > "$PKG_DIR/CONTROL/control" << CTRL
 cat > "$PKG_DIR/CONTROL/control" << CTRL
@@ -120,6 +123,10 @@ if [ "$FORMAT" = "ipk" ]; then
   echo "  Building .ipk..."
   echo "  Building .ipk..."
   "$SDK_DIR/scripts/ipkg-build" "$PKG_DIR" "$OUT_DIR"
   "$SDK_DIR/scripts/ipkg-build" "$PKG_DIR" "$OUT_DIR"
   echo "  IPK: $(ls "$OUT_DIR"/netpulse-agent_*.ipk)"
   echo "  IPK: $(ls "$OUT_DIR"/netpulse-agent_*.ipk)"
+  verify_ipk_modes "$OUT_DIR"/netpulse-agent_*.ipk \
+    "usr/sbin/netpulse-agent=755" \
+    "etc/init.d/netpulse-agent=755" \
+    "etc/uci-defaults/90-netpulse-agent=755"
 
 
 elif [ "$FORMAT" = "apk" ]; then
 elif [ "$FORMAT" = "apk" ]; then
   echo "  Building .apk via SDK..."
   echo "  Building .apk via SDK..."

+ 35 - 0
deploy/openwrt/sdk.sh

@@ -58,3 +58,38 @@ download_verified_sdk() {
 
 
   printf '%s\n' "$work_dir/${name%.tar.zst}"
   printf '%s\n' "$work_dir/${name%.tar.zst}"
 }
 }
+
+# verify_ipk_modes <ipk> <path>=<octal-mode>... checks that the packaged files
+# carry the expected permission bits inside data.tar.gz (#1701: ipkg-build
+# does not fix permissions, and a non-executable /etc/init.d script breaks
+# enable/start on the router). Uses ar + tar, both present on CI hosts.
+verify_ipk_modes() {
+  local ipk="$1"
+  shift
+  local spec path want got line
+  if [ ! -f "$ipk" ]; then
+    echo "ERROR: verify_ipk_modes: ipk not found: $ipk" >&2
+    exit 1
+  fi
+  echo "  Verifying packaged file modes in $(basename "$ipk")..."
+  for spec in "$@"; do
+    path="${spec%%=*}"
+    want="${spec##*=}"
+    got="$(ar p "$ipk" data.tar.gz | tar -tvzf - 2>/dev/null \
+      | awk -v p="$path" '$NF ~ ("(^|/)" p "$") {print $1; exit}')"
+    if [ -z "$got" ]; then
+      echo "ERROR: $path not found inside the ipk" >&2
+      exit 1
+    fi
+    case "$want" in
+      755) line="rwxr-xr-x" ;;
+      644) line="rw-r--r--" ;;
+      *) echo "ERROR: verify_ipk_modes: unsupported mode $want" >&2; exit 1 ;;
+    esac
+    if [ "$got" != "-$line" ]; then
+      echo "ERROR: $path has mode $got, want -$line ($want)" >&2
+      exit 1
+    fi
+    echo "    $path: $got OK"
+  done
+}

+ 23 - 0
server-go/internal/config/uci.go

@@ -187,6 +187,29 @@ func uciRun(ctx context.Context, args ...string) error {
 	return nil
 	return nil
 }
 }
 
 
+// ClearUCIAuthPass borra netpulse.server.auth_pass de UCI si existe (#1701).
+// Se llama cuando un usuario cambia su contraseña desde la UI: la contraseña
+// inicial del bootstrap R4 ya no aporta nada (el hash vive en la DB) y no
+// debe seguir en texto plano en /etc/config/netpulse. Si el admin borra su
+// cuenta de datos (sysupgrade), el bootstrap genera una nueva y la muestra
+// por logread. Fail-soft como el resto del puente UCI: sin `uci` (CT/Docker)
+// devuelve error y el caller decide (log y seguir).
+func ClearUCIAuthPass() error {
+	if _, err := exec.LookPath("uci"); err != nil {
+		return fmt.Errorf("uci no disponible: %w", err)
+	}
+	ctx, cancel := context.WithTimeout(context.Background(), uciExecTimeout)
+	defer cancel()
+	// Idempotente: si la opción no existe, no hay nada que hacer.
+	if err := exec.CommandContext(ctx, "uci", "-q", "get", "netpulse.server.auth_pass").Run(); err != nil {
+		return nil
+	}
+	if err := uciRun(ctx, "delete", "netpulse.server.auth_pass"); err != nil {
+		return err
+	}
+	return uciRun(ctx, "commit", "netpulse")
+}
+
 // ---------------------------------------------------------------------------
 // ---------------------------------------------------------------------------
 // Bootstrap R4 — contraseña inicial del admin on-box
 // Bootstrap R4 — contraseña inicial del admin on-box
 // ---------------------------------------------------------------------------
 // ---------------------------------------------------------------------------

+ 20 - 0
server-go/internal/httpapi/users.go

@@ -12,18 +12,36 @@ package httpapi
 
 
 import (
 import (
 	"database/sql"
 	"database/sql"
+	"log"
 	"net/http"
 	"net/http"
+	"os"
 	"regexp"
 	"regexp"
 	"strconv"
 	"strconv"
 	"strings"
 	"strings"
 	"unicode/utf8"
 	"unicode/utf8"
 
 
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/config"
 	"github.com/gnacho/netpulse/server-go/internal/db"
 	"github.com/gnacho/netpulse/server-go/internal/db"
 )
 )
 
 
 var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
 var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
 
 
+// clearUCIBootstrapPassword (#1701): tras un cambio de contraseña correcto,
+// la contraseña inicial generada en el bootstrap on-box deja de ser útil
+// (el hash vive en la DB) y no debe seguir en texto plano en
+// /etc/config/netpulse. Best-effort y solo en on-box: sin uci (CT/Docker)
+// no hace nada; si el borrado falla se queda registrada en el log pero el
+// cambio de contraseña ya se aplicó.
+func clearUCIBootstrapPassword() {
+	if os.Getenv("NETPULSE_ONBOX") != "1" {
+		return
+	}
+	if err := config.ClearUCIAuthPass(); err != nil {
+		log.Printf("[netpulse] aviso: no se pudo borrar auth_pass de UCI tras el cambio de contraseña: %v", err)
+	}
+}
+
 // parseUserID replica Number(:id): no numérico → NaN → no encontrado (404).
 // parseUserID replica Number(:id): no numérico → NaN → no encontrado (404).
 func parseUserID(s string) (float64, bool) {
 func parseUserID(s string) (float64, bool) {
 	n, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
 	n, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
@@ -257,6 +275,7 @@ func (s *server) handleMyPassword(w http.ResponseWriter, r *http.Request) {
 		return
 		return
 	}
 	}
 	_, _ = s.db.Exec("UPDATE users SET pass_hash = ? WHERE id = ?", newHash, me.ID)
 	_, _ = s.db.Exec("UPDATE users SET pass_hash = ? WHERE id = ?", newHash, me.ID)
+	clearUCIBootstrapPassword()
 	if current := auth.SessionIDFromRequest(s.db, s.secret, r); current != "" {
 	if current := auth.SessionIDFromRequest(s.db, s.secret, r); current != "" {
 		_, _ = s.db.Exec("DELETE FROM sessions WHERE user_id = ? AND id <> ?", me.ID, current)
 		_, _ = s.db.Exec("DELETE FROM sessions WHERE user_id = ? AND id <> ?", me.ID, current)
 	} else {
 	} else {
@@ -294,6 +313,7 @@ func (s *server) handleSetPassword(w http.ResponseWriter, r *http.Request) {
 		return
 		return
 	}
 	}
 	_, _ = s.db.Exec("UPDATE users SET pass_hash = ? WHERE id = ?", hash, target.ID)
 	_, _ = s.db.Exec("UPDATE users SET pass_hash = ? WHERE id = ?", hash, target.ID)
+	clearUCIBootstrapPassword()
 	auth.DestroyUserSessions(s.db, target.ID) // fuerza re-login
 	auth.DestroyUserSessions(s.db, target.ID) // fuerza re-login
 	w.WriteHeader(http.StatusNoContent)
 	w.WriteHeader(http.StatusNoContent)
 }
 }

+ 66 - 0
server-go/internal/httpapi/users_uci_password_test.go

@@ -0,0 +1,66 @@
+package httpapi_test
+
+import (
+	"net/http"
+	"strconv"
+	"strings"
+	"testing"
+)
+
+// TestPasswordChangeWithOnboxEnvStillSucceeds (#1701): tras un cambio de
+// contraseña correcto el servidor intenta borrar auth_pass de UCI (bootstrap
+// on-box). En un entorno sin el binario uci (test, CT, Docker) el intento es
+// best-effort: ambas rutas (propia y admin) deben devolver 204 igualmente.
+func TestPasswordChangeWithOnboxEnvStillSucceeds(t *testing.T) {
+	t.Setenv("NETPULSE_ONBOX", "1")
+	ts := makeUpgradeTestServer(t)
+
+	status, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	if status != 204 {
+		t.Fatalf("login: %d", status)
+	}
+
+	// Ruta admin: crear usuario y cambiar SU contraseña.
+	req, _ := http.NewRequest("POST", ts.URL+"/api/users", strings.NewReader(`{"username":"ux1701","password":"secreto12345"}`))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("POST /api/users: %v", err)
+	}
+	if res.StatusCode != http.StatusCreated {
+		t.Fatalf("POST /api/users: %d, want 201", res.StatusCode)
+	}
+	created := readJSON(t, res)
+	user, _ := created["user"].(map[string]any)
+	if user == nil {
+		t.Fatal("la respuesta de POST /api/users no lleva user")
+	}
+	userID, _ := user["id"].(float64)
+	targetURL := ts.URL + "/api/users/" + strconv.FormatFloat(userID, 'f', -1, 64) + "/password"
+	putBody := `{"password":"otraclave123"}`
+	req, _ = http.NewRequest("PUT", targetURL, strings.NewReader(putBody))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Cookie", "session="+cookie)
+	res2, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("PUT /api/users/{id}/password: %v", err)
+	}
+	defer res2.Body.Close()
+	if res2.StatusCode != http.StatusNoContent {
+		t.Fatalf("PUT /api/users/{id}/password: %d, want 204", res2.StatusCode)
+	}
+
+	// Ruta propia: PUT /api/auth/password.
+	req, _ = http.NewRequest("PUT", ts.URL+"/api/auth/password", strings.NewReader(`{"current":"test123456","password":"propia1701ok"}`))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Cookie", "session="+cookie)
+	res3, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("PUT /api/auth/password: %v", err)
+	}
+	defer res3.Body.Close()
+	if res3.StatusCode != http.StatusNoContent {
+		t.Fatalf("PUT /api/auth/password: %d, want 204", res3.StatusCode)
+	}
+}

+ 167 - 0
server-go/internal/openwrtpkg/init_test.go

@@ -0,0 +1,167 @@
+// Package openwrtpkg guarda los checks de empaquetado OpenWrt. Es un
+// paquete solo-de-tests: valida los ficheros reales de deploy/openwrt
+// (init scripts, uci-defaults y los scripts que generan el .ipk/.apk)
+// contra las reglas de compatibilidad de OpenWrt 21.02 documentadas en la
+// issue #1701, para que ninguna regresión vuelva a llegar a un .ipk roto.
+package openwrtpkg
+
+import (
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+)
+
+const repoRel = "../../.."
+
+func readRepoFile(t *testing.T, rel string) string {
+	t.Helper()
+	raw, err := os.ReadFile(filepath.Join(repoRel, rel))
+	if err != nil {
+		t.Fatalf("read %s: %v", rel, err)
+	}
+	return string(raw)
+}
+
+func countOccurrences(s, needle string) int {
+	return strings.Count(s, needle)
+}
+
+// codeLines devuelve el script sin líneas de comentario ni líneas vacías:
+// los checks son sobre código ejecutable, no sobre los comentarios que lo
+// explican.
+func codeLines(t *testing.T, src string) string {
+	t.Helper()
+	var out []string
+	for _, ln := range strings.Split(src, "\n") {
+		trimmed := strings.TrimSpace(ln)
+		if trimmed == "" || strings.HasPrefix(trimmed, "#") {
+			continue
+		}
+		out = append(out, ln)
+	}
+	return strings.Join(out, "\n")
+}
+
+// TestServerInitOpenWrt21Compat (#1701): el init del servidor on-box debe
+// cumplir las reglas de procd de OpenWrt 21.02 (GL.iNet GL-MT6000 del
+// reporte): una sola llamada env, stdout/stderr booleanos, arranque tardío
+// y guardia de montaje para no crear la base de datos en flash.
+func TestServerInitOpenWrt21Compat(t *testing.T) {
+	const rel = "deploy/openwrt/netpulse-server/files/netpulse-server.init"
+	src := readRepoFile(t, rel)
+	code := codeLines(t, src)
+
+	if !strings.Contains(code, "START=99") {
+		t.Error("START debe ser 99 para dejar montar los USB antes del arranque")
+	}
+	if got := countOccurrences(code, "procd_set_param env"); got != 1 {
+		t.Errorf("procd_set_param env aparece %d veces, want 1 (en 21.02 cada llamada extra pisa la anterior)", got)
+	}
+	envLine := ""
+	for _, ln := range strings.Split(code, "\n") {
+		if strings.Contains(ln, "procd_set_param env") {
+			envLine = ln
+		}
+	}
+	for _, want := range []string{"NETPULSE_ONBOX=1", "DATA_DIR=", "PORT="} {
+		if !strings.Contains(envLine, want) {
+			t.Errorf("la unica llamada env debe incluir %s: %q", want, envLine)
+		}
+	}
+	if strings.Contains(code, "procd_set_param stdout stderr") {
+		t.Error(`"procd_set_param stdout stderr" no es valido en 21.02; usa stdout 1 / stderr 1`)
+	}
+	if !strings.Contains(code, "procd_set_param stdout 1") || !strings.Contains(code, "procd_set_param stderr 1") {
+		t.Error("falta procd_set_param stdout 1 / stderr 1 (logs en logread)")
+	}
+
+	// Guardia de montaje: la comprobacion de /proc/mounts y el fallo temprano
+	// deben aparecer ANTES del mkdir, o mkdir crearia el dir en flash.
+	guard := strings.Index(src, "/proc/mounts")
+	mkdir := strings.Index(src, `mkdir -p "$data_dir"`)
+	if guard < 0 {
+		t.Error("falta la guardia de montaje (/proc/mounts)")
+	}
+	if mkdir < 0 {
+		t.Error("falta mkdir -p del data_dir")
+	}
+	if guard >= 0 && mkdir >= 0 && guard > mkdir {
+		t.Error("la guardia de montaje debe ejecutarse antes de mkdir -p")
+	}
+	if !strings.Contains(src, "logger -t netpulse") {
+		t.Error("el rechazo de arranque debe quedar en syslog (logger -t netpulse)")
+	}
+}
+
+// TestServerPortDefaultsAgree (#1701): init, uci-defaults y config embarcado
+// deben anunciar el mismo puerto por defecto (3100: el 3000 colisiona con la
+// UI de AdGuard Home del firmware GL.iNet).
+func TestServerPortDefaultsAgree(t *testing.T) {
+	files := map[string]string{
+		"deploy/openwrt/netpulse-server/files/netpulse-server.init":     "DEFAULT_PORT=3100",
+		"deploy/openwrt/netpulse-server/files/netpulse-server.defaults": "netpulse.server.port=3100",
+		"deploy/openwrt/netpulse-server/files/netpulse-server.config":   "option port '3100'",
+	}
+	for rel, want := range files {
+		if src := readRepoFile(t, rel); !strings.Contains(src, want) {
+			t.Errorf("%s: falta %q (puerto por defecto 3100)", rel, want)
+		}
+	}
+}
+
+// TestAgentInitOpenWrt21Compat (#1701): el init del agente comparte las
+// reglas de procd de 21.02.
+func TestAgentInitOpenWrt21Compat(t *testing.T) {
+	const rel = "deploy/openwrt/netpulse-agent/files/netpulse-agent.init"
+	code := codeLines(t, readRepoFile(t, rel))
+
+	if strings.Contains(code, "procd_set_param stdout stderr") {
+		t.Error(`"procd_set_param stdout stderr" no es valido en 21.02; usa stdout 1 / stderr 1`)
+	}
+	if !strings.Contains(code, "procd_set_param stdout 1") || !strings.Contains(code, "procd_set_param stderr 1") {
+		t.Error("falta procd_set_param stdout 1 / stderr 1 (logs en logread)")
+	}
+	if got := countOccurrences(code, "procd_set_param env"); got > 1 {
+		t.Errorf("procd_set_param env aparece %d veces, maximo 1 (en 21.02 cada llamada extra pisa la anterior)", got)
+	}
+}
+
+// TestPackageScriptsStageExecutableInit (#1701): los scripts de empaquetado
+// ipk deben instalar init y uci-defaults con modo 0755 (ipkg-build NO
+// corrige permisos: con 0644 el enable/start falla con Permission denied) y
+// verificar los modos dentro del .ipk resultante.
+func TestPackageScriptsStageExecutableInit(t *testing.T) {
+	type want struct {
+		install string
+		verify  string
+	}
+	cases := map[string]want{
+		"deploy/openwrt/package-server.sh": {
+			install: "install -m 0755 \"$REPO_ROOT/deploy/openwrt/netpulse-server/files/netpulse-server.init\"",
+			verify:  "etc/init.d/netpulse=755",
+		},
+		"deploy/openwrt/package.sh": {
+			install: "install -m 0755 \"$REPO_ROOT/deploy/openwrt/netpulse-agent/files/netpulse-agent.init\"",
+			verify:  "etc/init.d/netpulse-agent=755",
+		},
+	}
+	for rel, w := range cases {
+		src := readRepoFile(t, rel)
+		if !strings.Contains(src, w.install) {
+			t.Errorf("%s: el init debe empaquetarse con install -m 0755", rel)
+		}
+		if !strings.Contains(src, w.verify) {
+			t.Errorf("%s: falta la verificación verify_ipk_modes de %s", rel, w.verify)
+		}
+		if !strings.Contains(src, "verify_ipk_modes") {
+			t.Errorf("%s: falta la llamada a verify_ipk_modes", rel)
+		}
+	}
+
+	// El helper compartido existe en sdk.sh (sourceado por ambos scripts).
+	sdk := readRepoFile(t, "deploy/openwrt/sdk.sh")
+	if !strings.Contains(sdk, "verify_ipk_modes() {") {
+		t.Error("deploy/openwrt/sdk.sh: falta la función verify_ipk_modes")
+	}
+}

+ 84 - 0
server-go/internal/routerstore/gateway_test.go

@@ -0,0 +1,84 @@
+package routerstore
+
+import "testing"
+
+// gatewayIPFromRoutes elige la gateway LAN a partir de `ip -4 route show`.
+// Los escenarios reproducen el reporte de la issue #1701: en on-box la via
+// por defecto es la del ISP (publica o CGNAT) y la gateway LAN real es el
+// propio router; en un servidor dedicado la via privada ES la gateway.
+func TestGatewayIPFromRoutes(t *testing.T) {
+	cases := []struct {
+		name  string
+		table string
+		want  string
+	}{
+		{
+			name: "dedicated server private via wins",
+			table: `default via 192.168.1.1 dev eth0 proto static src 192.168.1.226
+192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.226
+`,
+			want: "192.168.1.1",
+		},
+		{
+			name: "on-box CGNAT via falls back to LAN self IP",
+			table: `default via 100.66.120.1 dev eth1
+100.66.120.1 dev eth1 scope link src 100.66.120.7
+192.168.1.0/24 dev br-lan proto kernel scope link src 192.168.1.1
+`,
+			want: "192.168.1.1",
+		},
+		{
+			name: "on-box public via falls back to LAN self IP",
+			table: `default via 81.34.12.7 dev eth1
+81.34.12.7 dev eth1 scope link src 81.34.12.7
+192.168.8.0/24 dev br-lan proto kernel scope link src 192.168.8.1
+`,
+			want: "192.168.8.1",
+		},
+		{
+			name: "on-box pppoe default without via uses LAN self IP",
+			table: `default dev pppoe-wan scope link
+192.168.1.0/24 dev br-lan proto kernel scope link src 192.168.1.1
+`,
+			want: "192.168.1.1",
+		},
+		{
+			name: "docker bridge keeps the RFC1918 gateway",
+			// Limitacion conocida (#1701): desde un contenedor en red bridge
+			// la unica gateway visible es la del puente; no se puede saber la
+			// gateway real de la LAN del host.
+			table: `default via 172.16.6.1 dev eth0
+172.16.6.0/24 dev eth0 proto kernel scope link src 172.16.6.4
+`,
+			want: "172.16.6.1",
+		},
+		{
+			name: "multi-WAN private via preferred over public",
+			table: `default via 1.2.3.4 dev eth1 metric 1
+default via 192.168.14.1 dev eth2 metric 20
+192.168.14.0/24 dev eth2 proto kernel scope link src 192.168.14.10
+`,
+			want: "192.168.14.1",
+		},
+		{
+			name:  "empty table",
+			table: "",
+			want:  "",
+		},
+		{
+			name: "no private route anywhere keeps the default via",
+			table: `default via 203.0.113.1 dev eth1
+203.0.113.0/24 dev eth1 proto kernel scope link src 203.0.113.9
+`,
+			want: "203.0.113.1",
+		},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			got := gatewayIPFromRoutes([]byte(tc.table))
+			if got != tc.want {
+				t.Fatalf("gatewayIPFromRoutes() = %q, want %q", got, tc.want)
+			}
+		})
+	}
+}

+ 61 - 6
server-go/internal/routerstore/routerstore.go

@@ -10,6 +10,7 @@ import (
 	"database/sql"
 	"database/sql"
 	"encoding/json"
 	"encoding/json"
 	"log"
 	"log"
+	"net"
 	"os/exec"
 	"os/exec"
 	"regexp"
 	"regexp"
 	"strings"
 	"strings"
@@ -389,19 +390,73 @@ func UpdateRouter(db *sql.DB, id string, in UpdateInput) (adapters.RouterConfig,
 // Autodetección de la puerta de enlace
 // Autodetección de la puerta de enlace
 // ---------------------------------------------------------------------------
 // ---------------------------------------------------------------------------
 
 
-var defaultViaRe = regexp.MustCompile(`default via (\d+\.\d+\.\d+\.\d+)`)
+var (
+	routeViaRe    = regexp.MustCompile(`via (\d+\.\d+\.\d+\.\d+)`)
+	routeSubnetRe = regexp.MustCompile(`^(\d+\.\d+\.\d+\.\d+)/\d+`)
+	routeSrcRe    = regexp.MustCompile(`src (\d+\.\d+\.\d+\.\d+)`)
+)
 
 
-// DetectGatewayIP devuelve la IP de la puerta de enlace por defecto del
+// DetectGatewayIP devuelve la IP de la puerta de enlace LAN por defecto del
 // servidor ("" si no se sabe).
 // servidor ("" si no se sabe).
+//
+// Dos escenarios (#1701):
+//   - Servidor dedicado en la LAN: la ruta por defecto sale por una via
+//     privada (RFC1918) y esa es la gateway.
+//   - Servidor on-box (el propio router): la via por defecto es pública o
+//     CGNAT (la del ISP), que NO es la gateway LAN; la gateway es el propio
+//     router y se toma la IP fuente de la primera ruta de subred privada.
+//     Con via pública/CGNAT y sin subred privada, devuelve "" (antes
+//     devolvía la dirección del ISP y generaba "Gateway offline" falso).
 func DetectGatewayIP() string {
 func DetectGatewayIP() string {
-	out, err := exec.Command("ip", "route", "show", "default").Output()
+	out, err := exec.Command("ip", "-4", "route", "show").Output()
 	if err != nil {
 	if err != nil {
 		return ""
 		return ""
 	}
 	}
-	if m := defaultViaRe.FindSubmatch(out); m != nil {
-		return string(m[1])
+	return gatewayIPFromRoutes(out)
+}
+
+// gatewayIPFromRoutes elige la gateway a partir de la salida de
+// `ip -4 route show`. Es pura para poder probarla sin `ip`.
+func gatewayIPFromRoutes(out []byte) string {
+	var viaFallback string
+	for _, line := range strings.Split(string(out), "\n") {
+		fields := strings.Fields(line)
+		if len(fields) == 0 {
+			continue
+		}
+		if fields[0] == "default" {
+			if m := routeViaRe.FindStringSubmatch(line); m != nil {
+				ip := net.ParseIP(m[1])
+				if ip != nil && ip.IsPrivate() {
+					return m[1]
+				}
+				if viaFallback == "" {
+					viaFallback = m[1]
+				}
+			}
+			continue
+		}
+	}
+	// Ninguna via privada: on-box o sin via (pppoe). La gateway LAN es el
+	// propio router: src de la primera ruta de subred privada.
+	for _, line := range strings.Split(string(out), "\n") {
+		fields := strings.Fields(line)
+		if len(fields) == 0 || fields[0] == "default" {
+			continue
+		}
+		if !routeSubnetRe.MatchString(fields[0]) {
+			continue
+		}
+		m := routeSrcRe.FindStringSubmatch(line)
+		if m == nil {
+			continue
+		}
+		ip := net.ParseIP(m[1])
+		if ip != nil && ip.IsPrivate() {
+			return m[1]
+		}
 	}
 	}
-	return ""
+	return viaFallback
 }
 }
 
 
 var glinetModelRe = regexp.MustCompile(`(?i)GL[.-]?iNet|GL-[A-Z]`)
 var glinetModelRe = regexp.MustCompile(`(?i)GL[.-]?iNet|GL-[A-Z]`)

+ 67 - 17
server-go/internal/sshkey/sshkey.go

@@ -6,13 +6,16 @@ package sshkey
 
 
 import (
 import (
 	"bytes"
 	"bytes"
+	"crypto/ed25519"
+	"crypto/rand"
 	"encoding/base64"
 	"encoding/base64"
+	"encoding/pem"
 	"fmt"
 	"fmt"
 	"io"
 	"io"
+	"log"
 	"os"
 	"os"
 	"os/exec"
 	"os/exec"
 	"path/filepath"
 	"path/filepath"
-	"regexp"
 	"strings"
 	"strings"
 	"time"
 	"time"
 
 
@@ -37,18 +40,35 @@ func KnownHostsPath(keyPath string) string {
 	return filepath.Join(filepath.Dir(keyPath), "known_hosts")
 	return filepath.Join(filepath.Dir(keyPath), "known_hosts")
 }
 }
 
 
-// EnsureKeypair garantiza que existe el par de claves en keyPath
-// (ssh-keygen -t ed25519 -N ” -C netpulse); best-effort en permisos.
+// EnsureKeypair garantiza que existe un par de claves USABLE en keyPath
+// (par ed25519 en formato OpenSSH). Best-effort en permisos.
 // Si no existe y hay un backup previo (<keyPath>.bak.<epoch>), lo restaura
 // Si no existe y hay un backup previo (<keyPath>.bak.<epoch>), lo restaura
 // en lugar de generar un par nuevo (defensa contra perdida accidental de
 // en lugar de generar un par nuevo (defensa contra perdida accidental de
 // .ssh/ durante updates, issue #425).
 // .ssh/ durante updates, issue #425).
+// Si existe pero crypto/ssh no puede leerlo (p. ej. la escribio el
+// ssh-keygen de Dropbear que trae OpenWrt 21.02: formato propio, issue
+// #1701), se respalda y se regenera en proceso: la clave rota nunca pudo
+// firmar nada, asi que no hay emparejamientos funcionales que invalidar.
 func EnsureKeypair(keyPath string) error {
 func EnsureKeypair(keyPath string) error {
 	if keyExists(keyPath) {
 	if keyExists(keyPath) {
-		return nil
+		if privateParses(keyPath) {
+			return nil
+		}
+		log.Printf("[netpulse] sshkey: la clave en %s no es legible por crypto/ssh (formato externo, tipicamente Dropbear de OpenWrt 21.02); se respalda como .bak.<epoch> y se regenera en proceso (#1701)", keyPath)
+		bak := fmt.Sprintf("%s.bak.%d", keyPath, time.Now().Unix())
+		if err := os.Rename(keyPath, bak); err != nil {
+			return err
+		}
+		if _, err := os.Stat(keyPath + ".pub"); err == nil {
+			_ = os.Rename(keyPath+".pub", bak+".pub")
+		}
+		return generateKeypair(keyPath)
 	}
 	}
 	// Intentar restaurar desde backup antes de generar clave nueva.
 	// Intentar restaurar desde backup antes de generar clave nueva.
 	if restored, _ := restoreLatestBackup(keyPath); restored {
 	if restored, _ := restoreLatestBackup(keyPath); restored {
-		return nil
+		if privateParses(keyPath) {
+			return nil
+		}
 	}
 	}
 	return generateKeypair(keyPath)
 	return generateKeypair(keyPath)
 }
 }
@@ -135,22 +155,20 @@ type PublicKey struct {
 	Fingerprint string `json:"fingerprint"`
 	Fingerprint string `json:"fingerprint"`
 }
 }
 
 
-var fpRe = regexp.MustCompile(`^\d+\s+(\S+)`)
-
-// GetPublicKey lee la clave pública y su fingerprint (ssh-keygen -lf, 2º
-// campo). Devuelve (nil, nil) si no se puede leer (→ 500 no_key).
+// GetPublicKey lee la clave pública y calcula su fingerprint EN PROCESO
+// (SHA-256, el mismo formato que ssh-keygen -lf de OpenSSH moderno). Sin
+// ssh-keygen: el de Dropbear en OpenWrt 21.02 no soporta -lf y dejaba el
+// fingerprint vacío en la UI de pairing (#1701). Devuelve (nil, nil) si no
+// se puede leer (→ 500 no_key).
 func GetPublicKey(keyPath string) *PublicKey {
 func GetPublicKey(keyPath string) *PublicKey {
 	data, err := os.ReadFile(keyPath + ".pub")
 	data, err := os.ReadFile(keyPath + ".pub")
 	if err != nil {
 	if err != nil {
 		return nil
 		return nil
 	}
 	}
 	pub := strings.TrimSpace(string(data))
 	pub := strings.TrimSpace(string(data))
-	out, err := exec.Command("ssh-keygen", "-lf", keyPath+".pub").Output()
 	fp := ""
 	fp := ""
-	if err == nil {
-		if m := fpRe.FindStringSubmatch(strings.TrimSpace(string(out))); m != nil {
-			fp = m[1]
-		}
+	if key, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pub)); err == nil {
+		fp = ssh.FingerprintSHA256(key)
 	}
 	}
 	return &PublicKey{PublicKey: pub, Fingerprint: fp}
 	return &PublicKey{PublicKey: pub, Fingerprint: fp}
 }
 }
@@ -183,19 +201,51 @@ func RotateKeypair(keyPath string) (*PublicKey, error) {
 	return key, nil
 	return key, nil
 }
 }
 
 
+// generateKeypair crea el par de claves EN PROCESO (crypto/ed25519 +
+// x/crypto/ssh), sin ejecutar ssh-keygen. El ssh-keygen disponible en
+// OpenWrt es el de Dropbear y en 21.02 escribe un formato que crypto/ssh
+// no puede leer: el servidor "tenia" clave pero el pool SSH fallaba y el
+// arranque caia en dataset demo sin aviso claro (#1701).
 func generateKeypair(keyPath string) error {
 func generateKeypair(keyPath string) error {
 	if err := os.MkdirAll(filepath.Dir(keyPath), 0o700); err != nil {
 	if err := os.MkdirAll(filepath.Dir(keyPath), 0o700); err != nil {
 		return err
 		return err
 	}
 	}
-	cmd := exec.Command("ssh-keygen", "-t", "ed25519", "-f", keyPath, "-N", "", "-C", "netpulse", "-q")
-	if out, err := cmd.CombinedOutput(); err != nil {
-		return &ExecError{What: "ssh-keygen", Err: err, Out: string(out)}
+	_, priv, err := ed25519.GenerateKey(rand.Reader)
+	if err != nil {
+		return err
+	}
+	block, err := ssh.MarshalPrivateKey(priv, "netpulse")
+	if err != nil {
+		return err
+	}
+	privPEM := pem.EncodeToMemory(block)
+	sshPub, err := ssh.NewPublicKey(priv.Public())
+	if err != nil {
+		return err
+	}
+	pubLine := strings.TrimSuffix(string(ssh.MarshalAuthorizedKey(sshPub)), "\n") + " netpulse\n"
+	if err := os.WriteFile(keyPath, privPEM, 0o600); err != nil {
+		return err
+	}
+	if err := os.WriteFile(keyPath+".pub", []byte(pubLine), 0o644); err != nil {
+		return err
 	}
 	}
 	_ = os.Chmod(filepath.Dir(keyPath), 0o700)
 	_ = os.Chmod(filepath.Dir(keyPath), 0o700)
 	_ = os.Chmod(keyPath, 0o600)
 	_ = os.Chmod(keyPath, 0o600)
 	return nil
 	return nil
 }
 }
 
 
+// privateParses comprueba que crypto/ssh puede leer la clave privada en
+// keyPath (el mismo parser que usa el pool SSH para sondear).
+func privateParses(keyPath string) bool {
+	data, err := os.ReadFile(keyPath)
+	if err != nil {
+		return false
+	}
+	_, err = ssh.ParseRawPrivateKey(data)
+	return err == nil
+}
+
 // khEntry es una línea de known_hosts desesquematizada: host(s) y host key.
 // khEntry es una línea de known_hosts desesquematizada: host(s) y host key.
 type khEntry struct {
 type khEntry struct {
 	hosts []string
 	hosts []string

+ 114 - 0
server-go/internal/sshkey/sshkey_test.go

@@ -1,13 +1,16 @@
 package sshkey
 package sshkey
 
 
 import (
 import (
+	"bytes"
 	"crypto/ecdsa"
 	"crypto/ecdsa"
 	"crypto/ed25519"
 	"crypto/ed25519"
 	"crypto/elliptic"
 	"crypto/elliptic"
 	"crypto/rand"
 	"crypto/rand"
 	"crypto/rsa"
 	"crypto/rsa"
+	"encoding/pem"
 	"os"
 	"os"
 	"path/filepath"
 	"path/filepath"
+	"strings"
 	"testing"
 	"testing"
 
 
 	"golang.org/x/crypto/ssh"
 	"golang.org/x/crypto/ssh"
@@ -80,6 +83,117 @@ func TestRestoreLatestBackupIgnoresIncomplete(t *testing.T) {
 	}
 	}
 }
 }
 
 
+// TestGeneratedKeyIsOpenSSHFormatInProcess (#1701): la clave se genera en
+// proceso (sin ssh-keygen) en formato OpenSSH, que es el mismo formato que
+// el pool SSH puede leer. En OpenWrt 21.02 el ssh-keygen disponible es el
+// de Dropbear y escribe un formato que crypto/ssh rechaza.
+func TestGeneratedKeyIsOpenSSHFormatInProcess(t *testing.T) {
+	dir := t.TempDir()
+	keyPath := filepath.Join(dir, "id_ed25519")
+
+	if err := EnsureKeypair(keyPath); err != nil {
+		t.Fatalf("EnsureKeypair falló: %v", err)
+	}
+	privPEM, err := os.ReadFile(keyPath)
+	if err != nil {
+		t.Fatalf("read private key: %v", err)
+	}
+	block, _ := pem.Decode(privPEM)
+	if block == nil {
+		t.Fatal("la clave privada no es PEM")
+	}
+	if block.Type != "OPENSSH PRIVATE KEY" {
+		t.Fatalf("tipo PEM = %q, want OPENSSH PRIVATE KEY", block.Type)
+	}
+	if !privateParses(keyPath) {
+		t.Fatal("crypto/ssh no puede leer la clave generada en proceso")
+	}
+	pubRaw, err := os.ReadFile(keyPath + ".pub")
+	if err != nil {
+		t.Fatalf("read pub: %v", err)
+	}
+	if !strings.Contains(string(pubRaw), "netpulse") {
+		t.Fatalf("la clave pública debería llevar el comentario netpulse: %s", pubRaw)
+	}
+	info, err := os.Stat(keyPath)
+	if err != nil {
+		t.Fatalf("stat private: %v", err)
+	}
+	if info.Mode().Perm() != 0o600 {
+		t.Fatalf("permisos de la clave privada = %v, want 0600", info.Mode().Perm())
+	}
+}
+
+// TestEnsureKeypairRegeneratesUnparseableKey (#1701): una clave existente en
+// formato ilegible (como la que dejó el ssh-keygen de Dropbear en el
+// GL-MT6000 del reportero: 83 bytes sin PEM) se respalda y se regenera en
+// proceso en lugar de quedarse para siempre rota.
+func TestEnsureKeypairRegeneratesUnparseableKey(t *testing.T) {
+	dir := t.TempDir()
+	keyPath := filepath.Join(dir, "id_ed25519")
+
+	// 83 bytes arbitrarios, no-PEM: patrón del reporte (Dropbear 21.02).
+	broken := bytes.Repeat([]byte{0xde, 0xad}, 41)
+	broken = append(broken, 0xbe)
+	if err := os.WriteFile(keyPath, broken, 0o600); err != nil {
+		t.Fatalf("write broken key: %v", err)
+	}
+	if err := os.WriteFile(keyPath+".pub", []byte("ssh-ed25519 AAAAtesting dropbear\n"), 0o644); err != nil {
+		t.Fatalf("write broken pub: %v", err)
+	}
+
+	if err := EnsureKeypair(keyPath); err != nil {
+		t.Fatalf("EnsureKeypair con clave rota falló: %v", err)
+	}
+	if !privateParses(keyPath) {
+		t.Fatal("la clave no se regeneró en formato legible")
+	}
+	// El par roto queda respaldado como .bak.<epoch> (la .pub como .bak.<epoch>.pub).
+	entries, err := os.ReadDir(dir)
+	if err != nil {
+		t.Fatalf("readdir: %v", err)
+	}
+	baks := 0
+	for _, e := range entries {
+		name := e.Name()
+		if strings.HasPrefix(name, filepath.Base(keyPath)+".bak.") && !strings.HasSuffix(name, ".pub") {
+			baks++
+		}
+	}
+	if baks != 1 {
+		t.Fatalf("se esperaba 1 backup de la clave rota, hay %d", baks)
+	}
+	pubRaw, err := os.ReadFile(keyPath + ".pub")
+	if err != nil {
+		t.Fatalf("read regenerated pub: %v", err)
+	}
+	if strings.Contains(string(pubRaw), "dropbear") {
+		t.Fatalf("la clave pública rota no fue reemplazada: %s", pubRaw)
+	}
+}
+
+// TestGetPublicKeyFingerprintInProcess (#1701): el fingerprint se calcula en
+// proceso (SHA-256, formato OpenSSH moderno) sin depender de ssh-keygen, que
+// en OpenWrt 21.02 (Dropbear) no soporta -lf y dejaba el campo vacío.
+func TestGetPublicKeyFingerprintInProcess(t *testing.T) {
+	dir := t.TempDir()
+	keyPath := filepath.Join(dir, "id_ed25519")
+
+	if err := EnsureKeypair(keyPath); err != nil {
+		t.Fatalf("EnsureKeypair falló: %v", err)
+	}
+	key := GetPublicKey(keyPath)
+	if key == nil {
+		t.Fatal("GetPublicKey devolvió nil")
+	}
+	if key.Fingerprint == "" {
+		t.Fatal("fingerprint vacío: sigue dependiendo de ssh-keygen -lf")
+	}
+	if !strings.HasPrefix(key.Fingerprint, "SHA256:") {
+		t.Fatalf("fingerprint = %q, want prefijo SHA256:", key.Fingerprint)
+	}
+}
+
 // genPubKey genera una clave pública de un tipo concreto para los tests de
 // genPubKey genera una clave pública de un tipo concreto para los tests de
 // merge (los tipos ed25519/ecdsa/rsa generan claves distintas entre sí).
 // merge (los tipos ed25519/ecdsa/rsa generan claves distintas entre sí).
 func genPubKey(t *testing.T, kind string) ssh.PublicKey {
 func genPubKey(t *testing.T, kind string) ssh.PublicKey {