ソースを参照

fix(agents): serve the right agent arch or fail loudly (#1367)

The UI one-liner pre-downloaded /binary without ?arch= and the handler silently defaulted to arm64, so MIPS routers got an aarch64 binary from the UI install flow. The endpoint now requires an explicit arch (400 without it), the one-liner delegates arch detection and download to install-agent.sh (server-first with X-Checksum-Sha256 verification, GitHub fallback), and a new --ca-file option carries the pinned CA root. Suite 48/48, end-to-end smoke with a real mipsle ELF.

Closes #1367
Nacho 1 ヶ月 前
親
コミット
f70fa1c03c

+ 58 - 22
install-agent.sh

@@ -22,6 +22,8 @@
 #                   y obtiene el token real automáticamente; Fase 9 R3)
 #   --server-fp X   SHA-256 SPKI del servidor en hex (https). Opcional: si no
 #                   se pasa, el script lo deriva del propio certificado (#851)
+#   --ca-file X     PEM de la CA del server (https con CA propia): se usa como
+#                   --cacert en la descarga del binario desde el server (#1367)
 #   --ssh-user X    usuario SSH del router (default: root)
 #   --ssh-key X     ruta a la identidad privada SSH (opción -i). OBLIGATORIA en
 #                   el server para routers que solo autorizan la llave del
@@ -50,7 +52,7 @@ ENV_FILE="/etc/netpulse-agent.env"
 INIT_NAME="netpulse-agent"
 INIT_DST="/etc/init.d/$INIT_NAME"
 
-HOST=""; SERVER=""; SLUG=""; TOKEN=""; PAIRING_TOKEN=""; SERVER_FP=""; SSH_USER="root"; SSH_KEY=""; BINARY=""; NETPULSE_VERSION=""; USE_TMP=0; UNINSTALL=0; UPDATE_NETGRIP=0; NETGRIP_FORCE=0
+HOST=""; SERVER=""; SLUG=""; TOKEN=""; PAIRING_TOKEN=""; SERVER_FP=""; CA_FILE=""; SSH_USER="root"; SSH_KEY=""; BINARY=""; NETPULSE_VERSION=""; USE_TMP=0; UNINSTALL=0; UPDATE_NETGRIP=0; NETGRIP_FORCE=0
 
 if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
     C_G=$(printf '\033[32m'); C_R=$(printf '\033[31m'); C_Y=$(printf '\033[33m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
@@ -78,6 +80,8 @@ while [ "$#" -gt 0 ]; do
         --pairing-token=*)  PAIRING_TOKEN="${1#*=}"; shift ;;
         --server-fp)        SERVER_FP="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
         --server-fp=*)      SERVER_FP="${1#*=}"; shift ;;
+        --ca-file)          CA_FILE="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
+        --ca-file=*)        CA_FILE="${1#*=}"; shift ;;
         --ssh-user)         SSH_USER="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
         --ssh-user=*)       SSH_USER="${1#*=}"; shift ;;
         --ssh-key)          SSH_KEY="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
@@ -274,28 +278,60 @@ else
     else fatal 21 "necesito curl o wget"; fi
     fetch_to() { $FETCH "$1" > "$2"; }
     command -v sha256sum >/dev/null 2>&1 || fatal 21 "falta sha256sum"
-    if [ -z "$NETPULSE_VERSION" ]; then
-        info "resolviendo última release"
-        NETPULSE_VERSION=$($FETCH "https://api.github.com/repos/$GH_REPO/releases/latest" \
-            | grep -oE '"tag_name"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | cut -d'"' -f4) \
-            || fatal 31 "no pude resolver la última release; usa --version=X.Y.Z"
+    # ------------------------------------------------------------- server --
+    # #1367: el binario sale del PROPIO server con la arch detectada arriba.
+    # Antes el one-liner pre-descargaba sin ?arch= y el handler defaulteaba
+    # a arm64: un router MIPS recibía un binario aarch64. Aquí la verdad es
+    # del router (uname + EI_DATA) y el handler exige la arch explícita.
+    # sha256 verificado contra la cabecera X-Checksum-Sha256 del server (#284);
+    # GitHub queda como fallback (dev sin binarios embebidos, sin curl o con
+    # --version explícita, que pide esa release concreta).
+    if [ -z "$NETPULSE_VERSION" ] && [ -n "$TOKEN" ] && command -v curl >/dev/null 2>&1; then
+        CA_ARGS=""
+        [ -n "$CA_FILE" ] && CA_ARGS="--cacert $CA_FILE"
+        info "descargando netpulse-agent ($GOARCH) de $SERVER"
+        if curl -fsSL $CA_ARGS --connect-timeout 10 --retry 3 \
+                -H "Authorization: Bearer $TOKEN" -D "$TMP/headers" \
+                "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH" -o "$TMP/$BIN_NAME" \
+                && [ -s "$TMP/$BIN_NAME" ]; then
+            SUM_REF=$(grep -i '^x-checksum-sha256:' "$TMP/headers" | tr -d '\r' | awk '{print $2}')
+            if [ -n "$SUM_REF" ]; then
+                SUM_FILE=$(sha256sum "$TMP/$BIN_NAME" | awk '{print $1}')
+                [ "$SUM_FILE" = "$SUM_REF" ] || fatal 33 "sha256 NO COINCIDE (server, arch $GOARCH)"
+                ok "sha256 verificado (server)"
+            else
+                warn "el server no envió X-Checksum-Sha256; sin verificación de suma"
+            fi
+        else
+            warn "descarga del server falló; pruebo con la release de GitHub"
+            rm -f "$TMP/$BIN_NAME"
+        fi
+    fi
+
+    if [ ! -s "$TMP/$BIN_NAME" ]; then
+        if [ -z "$NETPULSE_VERSION" ]; then
+            info "resolviendo última release"
+            NETPULSE_VERSION=$($FETCH "https://api.github.com/repos/$GH_REPO/releases/latest" \
+                | grep -oE '"tag_name"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | cut -d'"' -f4) \
+                || fatal 31 "no pude resolver la última release; usa --version=X.Y.Z"
+        fi
+        VERSION_NORM=$(echo "$NETPULSE_VERSION" | sed 's/^v//')
+        case "$NETPULSE_VERSION" in
+            v*) NETPULSE_TAG="$NETPULSE_VERSION" ;;
+            *)  NETPULSE_TAG="v$NETPULSE_VERSION" ;;
+        esac
+        ASSET="${BIN_NAME}_${VERSION_NORM}_linux_${GOARCH}.tar.gz"
+        BASE_URL="https://github.com/$GH_REPO/releases/download/$NETPULSE_TAG"
+        info "descargando $ASSET"
+        fetch_to "$BASE_URL/$ASSET" "$TMP/$ASSET" || fatal 32 "descarga falló: $BASE_URL/$ASSET"
+        fetch_to "$BASE_URL/checksums.txt" "$TMP/checksums.txt" || fatal 32 "checksums.txt no está en $NETPULSE_VERSION"
+        SUM_FILE=$(sha256sum "$TMP/$ASSET" | awk '{print $1}')
+        SUM_REF=$(grep "  $ASSET\$" "$TMP/checksums.txt" | awk '{print $1}')
+        [ -n "$SUM_REF" ] || fatal 33 "$ASSET no está en checksums.txt"
+        [ "$SUM_FILE" = "$SUM_REF" ] || fatal 33 "sha256 NO COINCIDE para $ASSET"
+        ok "sha256 verificado"
+        tar -xzf "$TMP/$ASSET" -C "$TMP"
     fi
-    VERSION_NORM=$(echo "$NETPULSE_VERSION" | sed 's/^v//')
-    case "$NETPULSE_VERSION" in
-        v*) NETPULSE_TAG="$NETPULSE_VERSION" ;;
-        *)  NETPULSE_TAG="v$NETPULSE_VERSION" ;;
-    esac
-    ASSET="${BIN_NAME}_${VERSION_NORM}_linux_${GOARCH}.tar.gz"
-    BASE_URL="https://github.com/$GH_REPO/releases/download/$NETPULSE_TAG"
-    info "descargando $ASSET"
-    fetch_to "$BASE_URL/$ASSET" "$TMP/$ASSET" || fatal 32 "descarga falló: $BASE_URL/$ASSET"
-    fetch_to "$BASE_URL/checksums.txt" "$TMP/checksums.txt" || fatal 32 "checksums.txt no está en $NETPULSE_VERSION"
-    SUM_FILE=$(sha256sum "$TMP/$ASSET" | awk '{print $1}')
-    SUM_REF=$(grep "  $ASSET\$" "$TMP/checksums.txt" | awk '{print $1}')
-    [ -n "$SUM_REF" ] || fatal 33 "$ASSET no está en checksums.txt"
-    [ "$SUM_FILE" = "$SUM_REF" ] || fatal 33 "sha256 NO COINCIDE para $ASSET"
-    ok "sha256 verificado"
-    tar -xzf "$TMP/$ASSET" -C "$TMP"
 fi
 [ -s "$TMP/$BIN_NAME" ] || fatal 34 "no hay binario que instalar"
 

+ 19 - 11
server-go/internal/httpapi/agent.go

@@ -308,9 +308,16 @@ func (s *server) handleAgentBinary(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusUnauthorized, "unauthorized")
 		return
 	}
+	// #1367: sin default silencioso. El default arm64 hizo que un router
+	// MIPS instalado con el one-liner recibiera un binario aarch64 (exec
+	// format error) sin ningún aviso. Todos los consumidores automáticos
+	// (reinstall, self-heal, self-upgrade) mandan arch explícita; si falta,
+	// se pide en vez de adivinar.
 	arch := r.URL.Query().Get("arch")
 	if arch == "" {
-		arch = "arm64"
+		writeError(w, http.StatusBadRequest, "invalid_request",
+			"falta ?arch= (amd64, arm64, armv7, mips, mipsle)")
+		return
 	}
 	f, err := agentbin.Open(arch)
 	if err != nil {
@@ -463,8 +470,11 @@ func (s *server) agentBaseURL(r *http.Request) string {
 
 // agentInstallLine: one-liner de instalación vía SSH desde esta máquina.
 // El host del router se resuelve de la tabla routers si el slug existe.
-// Fase 6.2: el binario se descarga del propio servidor con el token del agente
-// en vez de GitHub, eliminando la dependencia de internet y el token en argv.
+// Fase 6.2: el binario lo sirve el propio servidor, eliminando la
+// dependencia de GitHub. #1367: el one-liner ya NO pre-descarga el binario
+// (sin arch no puede acertar en MIPS); install-agent.sh detecta la
+// arquitectura del router por SSH y descarga del server con ?arch= (verdad
+// del router, no del servidor), con GitHub como fallback.
 func (s *server) agentInstallLine(r *http.Request, slug, token string) string {
 	host := "<ip-del-router>"
 	if s.db != nil {
@@ -485,23 +495,21 @@ func (s *server) agentInstallLine(r *http.Request, slug, token string) string {
 	}
 	// FORK: with HTTPS on, the line points the agent at it and pins the
 	// root; the root travels inside the line - copied from the admin's own
-	// session - so the binary download, token included, is verified too.
-	caArg, fpArg := "", ""
+	// session - so the download of the binary from the server, token
+	// included, is verified too (install-agent.sh lo usa vía --ca-file).
+	caArg, fpArg, caFileArg := "", "", ""
 	if tr := tlsmode.AgentTrust(s.tlsMgr, s.fingerprint, server); tr.ServerURL != "" {
 		server = tr.ServerURL
 		pemEsc := strings.ReplaceAll(strings.TrimSpace(string(tr.CAPEM)), "\n", `\n`)
 		caArg = fmt.Sprintf("NPCA=$(mktemp) && printf '%%b' '%s\\n' > \"$NPCA\" && ", pemEsc)
+		caFileArg = ` --ca-file="$NPCA"`
 		fpArg = " --server-fp=" + tr.ServerFP
 	} else if tr.ServerFP != "" {
 		fpArg = " --server-fp=" + tr.ServerFP
 	}
-	curlCA := ""
-	if caArg != "" {
-		curlCA = ` --cacert "$NPCA"`
-	}
 	return fmt.Sprintf(
-		"%scurl -fsSL%s -H 'Authorization: Bearer %s' %s/api/agents/%s/binary -o /tmp/netpulse-agent && curl -fsSL https://raw.githubusercontent.com/gnacho/netpulse/main/install-agent.sh | sh -s -- --binary=/tmp/netpulse-agent --host=%s --server=%s --slug=%s --token=%s%s%s",
-		caArg, curlCA, token, server, slug, host, server, slug, token, fpArg, sshKeyArg)
+		"%scurl -fsSL https://raw.githubusercontent.com/gnacho/netpulse/main/install-agent.sh | sh -s -- --host=%s --server=%s --slug=%s --token=%s%s%s%s",
+		caArg, host, server, slug, token, caFileArg, fpArg, sshKeyArg)
 }
 
 // agentListItem: lo que ve la UI — NUNCA el token ni su hash.

+ 110 - 0
server-go/internal/httpapi/agent_binary_test.go

@@ -0,0 +1,110 @@
+// agent_binary_test.go — #1367: el endpoint de binario del agente no debe
+// defaultear a arm64 en silencio cuando falta ?arch=, y el one-liner de
+// instalación no debe pre-descargar el binario (la detección de arquitectura
+// la hace install-agent.sh contra el router, que es quien la sabe).
+package httpapi_test
+
+import (
+	"io"
+	"net/http"
+	"strings"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/agentbin"
+)
+
+// getBinary hace GET /api/agents/<slug>/binary autenticado con el token del
+// agente; query se añade tal cual ("" o "?arch=mipsle").
+func getBinary(t *testing.T, ts *agentTestServer, slug, token, query string) *http.Response {
+	t.Helper()
+	url := ts.URL + "/api/agents/" + slug + "/binary" + query
+	req, _ := http.NewRequest("GET", url, nil)
+	req.Header.Set("Authorization", "Bearer "+token)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("GET %s: %v", url, err)
+	}
+	return res
+}
+
+func createTokenFor(t *testing.T, ts *agentTestServer, slug string) string {
+	t.Helper()
+	status, token, _ := createAgentToken(t, ts, slug)
+	if status != 201 {
+		t.Fatalf("create token %s: %d", slug, status)
+	}
+	return token
+}
+
+// #1367: sin ?arch= el server servía arm64 en silencio; un router MIPS que
+// instalara con el one-liner recibía un binario aarch64 (exec format error).
+// El default silencioso es la causa del reporte: ahora se exige la arch.
+func TestAgentBinaryRequiresArch(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	token := createTokenFor(t, ts, "mipsbox")
+	res := getBinary(t, ts, "mipsbox", token, "")
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusBadRequest {
+		body, _ := io.ReadAll(res.Body)
+		t.Fatalf("sin ?arch= quiero 400 pidiendo la arch, tengo %d: %s", res.StatusCode, body)
+	}
+}
+
+// Con ?arch= explícita el binario servido debe ser el de ESA arquitectura
+// (Content-Disposition y sha256 presentes), no el default.
+func TestAgentBinaryServesRequestedArch(t *testing.T) {
+	if !agentbin.HasBinaries() {
+		t.Skip("sin binarios embebidos (árbol dev sin agentbin/agents)")
+	}
+	ts := makeAgentTestServer(t)
+	token := createTokenFor(t, ts, "mipsbox")
+	res := getBinary(t, ts, "mipsbox", token, "?arch=mipsle")
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusOK {
+		body, _ := io.ReadAll(res.Body)
+		t.Fatalf("?arch=mipsle quiero 200, tengo %d: %s", res.StatusCode, body)
+	}
+	if cd := res.Header.Get("Content-Disposition"); !strings.Contains(cd, "mipsle") {
+		t.Fatalf("Content-Disposition = %q, quiero mipsle", cd)
+	}
+	if res.Header.Get("X-Checksum-Sha256") == "" {
+		t.Fatal("falta la cabecera X-Checksum-Sha256")
+	}
+	head := make([]byte, 4)
+	if _, err := io.ReadFull(res.Body, head); err != nil {
+		t.Fatalf("leer body: %v", err)
+	}
+	if string(head) != "\x7fELF" {
+		t.Fatalf("el body no es un ELF: %x", head)
+	}
+}
+
+// Arch desconocida: 404 (comportamiento preexistente, se fija como contrato).
+func TestAgentBinaryUnknownArch(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	token := createTokenFor(t, ts, "mipsbox")
+	res := getBinary(t, ts, "mipsbox", token, "?arch=sparc")
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusNotFound {
+		t.Fatalf("?arch=sparc quiero 404, tengo %d", res.StatusCode)
+	}
+}
+
+// #1367: el one-liner NO debe pre-descargar el binario (sin arch no puede
+// acertar en MIPS); debe delegar en install-agent.sh, que detecta la arch
+// del router por SSH y descarga del propio server con ?arch=.
+func TestInstallLineDelegatesBinaryToInstaller(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	_, _, install := createAgentToken(t, ts, "rt1")
+	if strings.Contains(install, "/api/agents/") {
+		t.Fatalf("el one-liner no debe descargar el binario: %s", install)
+	}
+	if !strings.Contains(install, "install-agent.sh") {
+		t.Fatalf("el one-liner debe invocar install-agent.sh: %s", install)
+	}
+	for _, want := range []string{"--slug=rt1", "--token=", "--server="} {
+		if !strings.Contains(install, want) {
+			t.Fatalf("falta %s en el one-liner: %s", want, install)
+		}
+	}
+}

+ 4 - 1
server-go/internal/httpapi/https_settings_test.go

@@ -408,7 +408,10 @@ func TestTheInstallLineCarriesTheRoot(t *testing.T) {
 	}
 	_, _, line := createAgentToken(t, ts, "test-router-2")
 	wantServer := fmt.Sprintf("--server=https://192.168.50.2:%d", mgr.Status().Port)
-	for _, want := range []string{`--cacert "$NPCA"`, "NPCA=$(mktemp)", "--server-fp=" + mgr.Fingerprint(), wantServer} {
+	// #1367: la CA sigue viajando en la línea, pero ya no como --cacert del
+	// one-liner (que ya no descarga el binario): va como --ca-file para que
+	// install-agent.sh la use en la descarga server-side del binario.
+	for _, want := range []string{`--ca-file="$NPCA"`, "NPCA=$(mktemp)", "--server-fp=" + mgr.Fingerprint(), wantServer} {
 		if !strings.Contains(line, want) {
 			t.Fatalf("install line lacks %q:\n%s", want, line)
 		}