install-agent.sh 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. #!/bin/sh
  2. # =============================================================================
  3. # NetPulse Agent - one-liner installer (OpenWrt, over SSH from this machine)
  4. #
  5. # Installs the native netpulse-agent on an OpenWrt router/AP: copies the
  6. # binary (arm64/armv7/mipsle/mips), writes /etc/netpulse-agent.env (chmod
  7. # 600) and installs the procd service (respawn), enabled and started. Adds
  8. # the binary, the init script and the env file to /etc/sysupgrade.conf so
  9. # they survive a firmware upgrade (#1476).
  10. #
  11. # Usage (the token is generated by POST /api/agents and shown ONCE):
  12. # sh install-agent.sh --host 192.168.8.3 \
  13. # --server http://192.168.8.1:3000 --slug patio --token <64-hex>
  14. # sh install-agent.sh --host 192.168.8.3 --server ... --slug ... --token ... \
  15. # --binary ./netpulse-agent # local binary (no download)
  16. # sh install-agent.sh --host 192.168.8.3 --uninstall
  17. #
  18. # Options:
  19. # --host X router IP/host (required)
  20. # --server X NetPulse server URL (required unless --uninstall)
  21. # --slug X unit slug in NetPulse (required unless --uninstall)
  22. # --token X unit token (required unless --uninstall and --pairing-token)
  23. # --pairing-token X pairing token (bootstrap: the agent contacts the server
  24. # and gets the real token by itself, phase 9 R3)
  25. # --server-fp X server SPKI SHA-256 in hex (https). Optional: without it
  26. # the script derives it from the certificate (#851)
  27. # --ca-file X PEM of the server CA (https with a private CA): used as
  28. # --cacert when downloading the binary from the server (#1367)
  29. # --ssh-user X router SSH user (default: root)
  30. # --ssh-key X path to the SSH private identity (-i). REQUIRED on the
  31. # server for routers that only authorize the NetPulse key
  32. # (the one Settings shows), it is passed to ssh/scp.
  33. # --binary X local binary to copy (default: download the release)
  34. # --version X.Y.Z version to download (default: latest)
  35. # --tmp installs the binary in /tmp (RAM) instead of /usr/sbin,
  36. # for units with little flash. NOTE: /tmp is lost on reboot,
  37. # so the script has to run again after one (documented
  38. # variant of the SPEC, the .ipk lands in increment 2)
  39. # --uninstall stops and removes the service, binary and config
  40. # --update-netgrip if NetGrip is found on the router, update the NetGrip
  41. # panel to its latest release (apk/ipk from GitHub) instead
  42. # of only handing over the config (--force allows downgrades)
  43. #
  44. # Note: every option accepts `--opt value` and `--opt=value` (#571).
  45. #
  46. # Requirements: ssh/scp to the router (OpenWrt with dropbear), curl or wget.
  47. # =============================================================================
  48. set -eu
  49. GH_REPO="gnacho/netpulse"
  50. BIN_NAME="netpulse-agent"
  51. ENV_FILE="/etc/netpulse-agent.env"
  52. INIT_NAME="netpulse-agent"
  53. INIT_DST="/etc/init.d/$INIT_NAME"
  54. 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
  55. if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
  56. 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')
  57. else C_G=""; C_R=""; C_Y=""; C_B=""; C_0=""; fi
  58. info() { printf '%s--%s %s\n' "$C_B" "$C_0" "$*"; }
  59. ok() { printf '%s✓%s %s\n' "$C_G" "$C_0" "$*"; }
  60. warn() { printf '%s!%s %s\n' "$C_Y" "$C_0" "$*" >&2; }
  61. fatal() { _c=$1; shift; printf '%s✗ %s%s\n' "$C_R" "$*" "$C_0" >&2; exit "$_c"; }
  62. usage() { sed -n '2,/^# Requirements/p' "$0" | sed '$d'; exit 0; }
  63. # #571: acepta tanto `--opt value` como `--opt=value` (el copy-command de la app
  64. # y la cabecera de ayuda usan la forma con espacio).
  65. while [ "$#" -gt 0 ]; do
  66. case "$1" in
  67. --host) HOST="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
  68. --host=*) HOST="${1#*=}"; shift ;;
  69. --server) SERVER="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
  70. --server=*) SERVER="${1#*=}"; shift ;;
  71. --slug) SLUG="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
  72. --slug=*) SLUG="${1#*=}"; shift ;;
  73. --token) TOKEN="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
  74. --token=*) TOKEN="${1#*=}"; shift ;;
  75. --pairing-token) PAIRING_TOKEN="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
  76. --pairing-token=*) PAIRING_TOKEN="${1#*=}"; shift ;;
  77. --server-fp) SERVER_FP="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
  78. --server-fp=*) SERVER_FP="${1#*=}"; shift ;;
  79. --ca-file) CA_FILE="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
  80. --ca-file=*) CA_FILE="${1#*=}"; shift ;;
  81. --ssh-user) SSH_USER="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
  82. --ssh-user=*) SSH_USER="${1#*=}"; shift ;;
  83. --ssh-key) SSH_KEY="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
  84. --ssh-key=*) SSH_KEY="${1#*=}"; shift ;;
  85. --binary) BINARY="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
  86. --binary=*) BINARY="${1#*=}"; shift ;;
  87. --version) NETPULSE_VERSION="${2-}"; [ "$#" -ge 2 ] && shift 2 || shift ;;
  88. --version=*) NETPULSE_VERSION="${1#*=}"; shift ;;
  89. --tmp) USE_TMP=1; shift ;;
  90. --uninstall) UNINSTALL=1; shift ;;
  91. --update-netgrip) UPDATE_NETGRIP=1; shift ;;
  92. --force) NETGRIP_FORCE=1; shift ;;
  93. -h|--help) usage ;;
  94. *) fatal 10 "unknown option: $1 (try --help)" ;;
  95. esac
  96. done
  97. [ -n "$HOST" ] || fatal 11 "missing --host (router IP)"
  98. SSH="$SSH_USER@$HOST"
  99. # #572: identidad SSH explícita (p. ej. la llave de routers del server). Si no
  100. # se pasa, el cliente usa la default (~/.ssh/id_*) como antes.
  101. SSH_IDENT_ARGS=""
  102. if [ -n "$SSH_KEY" ]; then SSH_IDENT_ARGS="-i $SSH_KEY"; fi
  103. command -v ssh >/dev/null 2>&1 || fatal 12 "ssh is required"
  104. command -v scp >/dev/null 2>&1 || fatal 12 "scp is required"
  105. # --------------------------------------------------------------- uninstall --
  106. if [ "$UNINSTALL" -eq 1 ]; then
  107. info "uninstalling $BIN_NAME from $SSH"
  108. ssh $SSH_IDENT_ARGS "$SSH" "
  109. $INIT_DST stop 2>/dev/null || true
  110. $INIT_DST disable 2>/dev/null || true
  111. rm -f $INIT_DST $ENV_FILE /usr/sbin/$BIN_NAME /tmp/$BIN_NAME
  112. rm -f /usr/sbin/netpulse-watchdog /tmp/netpulse-agent.heartbeat
  113. # quitar la línea del watchdog del crontab (si existe)
  114. if [ -f /etc/crontabs/root ]; then
  115. sed -i '/netpulse-watchdog/d' /etc/crontabs/root
  116. fi
  117. # (#1476) retirar del sysupgrade.conf las entradas de la instalación
  118. if [ -r /etc/sysupgrade.conf ]; then
  119. grep -vxF -e /usr/sbin/$BIN_NAME -e $ENV_FILE -e $INIT_DST /etc/sysupgrade.conf 2>/dev/null \
  120. | grep -vE '^/etc/rc\.d/[^/]*$INIT_NAME\$' > /tmp/np-sysupgrade.conf || true
  121. mv /tmp/np-sysupgrade.conf /etc/sysupgrade.conf
  122. fi
  123. "
  124. ok "$BIN_NAME uninstalled from $HOST"
  125. exit 0
  126. fi
  127. [ -n "$SERVER" ] || fatal 11 "missing --server (NetPulse URL)"
  128. [ -n "$SLUG" ] || fatal 11 "missing --slug"
  129. # Token: obligatorio --token o --pairing-token (no ambos)
  130. if [ -z "$TOKEN" ] && [ -z "$PAIRING_TOKEN" ]; then
  131. fatal 11 "missing --token (or --pairing-token for bootstrap)"
  132. fi
  133. SERVER="${SERVER%/}"
  134. # ------------------------------------------------------- TLS fingerprint ---
  135. # HTTPS exige pinning SPKI: el agente falla en bucle fatal sin
  136. # NETPULSE_SERVER_FP (#851). Si no se pasó --server-fp, lo derivamos del
  137. # propio certificado del servidor: quien instala ya confía en ese servidor
  138. # (le entrega el token) y este paso es puramente mecánico.
  139. case "$SERVER" in
  140. https://*)
  141. SERVER_FP=$(printf '%s' "$SERVER_FP" | sed -e 's|^sha256/||' -e 's|[^0-9a-fA-F]||g' | tr 'A-F' 'a-f')
  142. if [ -z "$SERVER_FP" ]; then
  143. HOSTPORT=${SERVER#https://}
  144. HOSTPORT=${HOSTPORT%%/*}
  145. SNI=${HOSTPORT%%:*}
  146. case "$HOSTPORT" in *:*) : ;; *) HOSTPORT="$HOSTPORT:443" ;; esac
  147. info "deriving NETPULSE_SERVER_FP from the certificate of $SERVER"
  148. if command -v openssl >/dev/null 2>&1; then
  149. SERVER_FP=$(echo | openssl s_client -connect "$HOSTPORT" -servername "$SNI" 2>/dev/null \
  150. | openssl x509 -pubkey -noout 2>/dev/null \
  151. | openssl pkey -pubin -outform DER 2>/dev/null \
  152. | { command -v sha256sum >/dev/null 2>&1 && sha256sum || shasum -a 256; } \
  153. | cut -d' ' -f1)
  154. fi
  155. [ -n "$SERVER_FP" ] || fatal 14 "HTTPS server without --server-fp and could not derive it (is openssl available? is the SNI right?). Get the sha256 SPKI of the certificate and retry with --server-fp X"
  156. ok "NETPULSE_SERVER_FP=$SERVER_FP"
  157. fi
  158. ;;
  159. esac
  160. # Preflight con la MISMA identidad que el resto del script: sin
  161. # $SSH_IDENT_ARGS el chequeo caía a ~/.ssh/id_* y fallaba aunque --ssh-key
  162. # fuera la válida (#1472). BatchMode=yes a propósito: el instalador es no
  163. # interactivo y la contraseña NUNCA basta; hay que autorizar la clave
  164. # pública en el router (dropbear: /etc/dropbear/authorized_keys).
  165. ssh $SSH_IDENT_ARGS -o ConnectTimeout=8 -o BatchMode=yes "$SSH" true || {
  166. PUB="${SSH_KEY:-~/.ssh/id_ed25519.pub}"
  167. fatal 13 "no key-based SSH to $SSH (the installer is not interactive, a password is no use). Authorize the public key on the router and retry: ssh-copy-id -i $PUB $SSH"
  168. }
  169. # Preflight del canal (#1654): el router tiene que alcanzar el MISMO $SERVER
  170. # que luego se escribe en el entorno del agente. Sin esto, un puerto cerrado o
  171. # un esquema equivocado (https cuando el router solo llega a http) se descubre
  172. # al final, con el agente ya instalado y sin poder conectar. Se comprueba sin
  173. # validar el certificado a propósito: de la identidad del servidor se encarga
  174. # el pinning SPKI (NETPULSE_SERVER_FP).
  175. info "checking that $HOST reaches $SERVER"
  176. ssh $SSH_IDENT_ARGS "$SSH" "if command -v curl >/dev/null 2>&1; then curl -fsSk --connect-timeout 5 -m 10 -o /dev/null '$SERVER/api/health'; elif command -v wget >/dev/null 2>&1; then wget -q --no-check-certificate -T 10 -O /dev/null '$SERVER/api/health'; else exit 3; fi" || {
  177. fatal 15 "the router cannot reach $SERVER/api/health. Check that the host and the port are reachable from the router network. With TLS on the server the URL is https and the router must reach that port. To use another URL in the agents, set NETPULSE_AGENT_URL on the server (the LAN one, for instance)"
  178. }
  179. # ----------------------------------------------------- netgrip handoff --
  180. # Si el router ya corre NetGrip, su agente EMBEBIDO cubre el sondeo: no se
  181. # instala el standalone. Se le entrega la config (sin pisar la existente) y
  182. # opcionalmente se actualiza el propio NetGrip (--update-netgrip).
  183. if ssh $SSH_IDENT_ARGS "$SSH" '[ -x /usr/sbin/netgrip ] || [ -f /etc/init.d/netgrip ]'; then
  184. info "NetGrip found on $HOST, its embedded agent already covers this router"
  185. # Token line igual que el flujo normal
  186. if [ -n "$PAIRING_TOKEN" ]; then
  187. HANDOFF_TOKEN="NETPULSE_PAIRING_TOKEN=$PAIRING_TOKEN"
  188. else
  189. HANDOFF_TOKEN="NETPULSE_TOKEN=$TOKEN"
  190. fi
  191. HANDOFF_FP=""
  192. [ -n "$SERVER_FP" ] && HANDOFF_FP="NETPULSE_SERVER_FP=$SERVER_FP"
  193. ssh $SSH_IDENT_ARGS "$SSH" "NG_ENV=/etc/netgrip/netpulse.env sh -s" <<HANDOFF
  194. set -eu
  195. if [ ! -f "\$NG_ENV" ]; then
  196. mkdir -p /etc/netgrip
  197. {
  198. echo "# managed by netgrip; netpulse embedded agent config"
  199. echo "NETPULSE_SERVER=$SERVER"
  200. echo "NETPULSE_SLUG=$SLUG"
  201. echo "$HANDOFF_TOKEN"
  202. ${HANDOFF_FP:+echo "$HANDOFF_FP"}
  203. echo "NETPULSE_ENABLED=1"
  204. } > "\$NG_ENV"
  205. chmod 600 "\$NG_ENV"
  206. echo "config-written"
  207. else
  208. echo "existing-config-kept"
  209. fi
  210. HANDOFF
  211. if [ "$UPDATE_NETGRIP" -eq 1 ]; then
  212. # Versión instalada (registry apk/opkg; vacío si es binario manual)
  213. CUR=$(ssh $SSH_IDENT_ARGS "$SSH" "(apk info netgrip 2>/dev/null || opkg status netgrip 2>/dev/null | sed -n 's/^Version: //p') | head -1")
  214. if command -v curl >/dev/null 2>&1; then FETCH="curl -fsSL --retry 3 --connect-timeout 10"
  215. elif command -v wget >/dev/null 2>&1; then FETCH="wget -q -O-"
  216. else fatal 21 "curl or wget is required"; fi
  217. NG_TAG=$($FETCH "https://api.github.com/repos/gnacho/netgrip/releases/latest" \
  218. | grep -oE '"tag_name"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | cut -d'"' -f4) || fatal 41 "could not resolve the latest NetGrip release"
  219. NG_VER=$(echo "$NG_TAG" | sed 's/^v//')
  220. ARCH=$(ssh $SSH_IDENT_ARGS "$SSH" uname -m)
  221. case "$ARCH" in
  222. aarch64|arm64) NG_ARCH=arm64 ;;
  223. *) fatal 20 "NetGrip only publishes arm64 builds (router: $ARCH)" ;;
  224. esac
  225. if ssh $SSH_IDENT_ARGS "$SSH" command -v apk >/dev/null 2>&1; then
  226. NG_ASSET="netgrip-${NG_VER}-r1-${NG_ARCH}.apk"; NG_INST="apk add --allow-untrusted /tmp/netgrip-update.pkg"
  227. else
  228. NG_ASSET="netgrip_${NG_VER}-1_aarch64_cortex-a53.ipk"; NG_INST="opkg install /tmp/netgrip-update.pkg"
  229. fi
  230. NG_URL="https://github.com/gnacho/netgrip/releases/download/${NG_TAG}/${NG_ASSET}"
  231. info "updating NetGrip to $NG_TAG (installed: ${CUR:-unknown})"
  232. if [ -n "$CUR" ] && [ "$NETGRIP_FORCE" -ne 1 ]; then
  233. CUR_V=$(echo "$CUR" | sed 's/^netgrip-//; s/ description:.*//; s/-r[0-9]*$//')
  234. if [ "$CUR_V" = "$NG_VER" ]; then
  235. ok "NetGrip is already on $NG_VER, nothing to do (use --force to reinstall)"
  236. ssh $SSH_IDENT_ARGS "$SSH" "/etc/init.d/netgrip restart >/dev/null 2>&1 || true"
  237. ok "embedded agent rearmed (slug $SLUG)"
  238. exit 0
  239. fi
  240. OLDEST=$(printf '%s\n%s\n' "$CUR_V" "$NG_VER" | sort -V | head -1)
  241. if [ "$OLDEST" = "$NG_VER" ]; then
  242. warn "release $NG_TAG is OLDER than the installed one ($CUR_V), the router runs an unreleased build"
  243. fatal 43 "downgrade refused (use --force if you really want it)"
  244. fi
  245. fi
  246. $FETCH "$NG_URL" -o "$TMP/netgrip-update.pkg" || fatal 42 "download failed: $NG_URL"
  247. scp -Oq $SSH_IDENT_ARGS "$TMP/netgrip-update.pkg" "$SSH:/tmp/netgrip-update.pkg"
  248. ssh $SSH_IDENT_ARGS "$SSH" "$NG_INST && rm -f /tmp/netgrip-update.pkg"
  249. ok "NetGrip updated to $NG_TAG"
  250. fi
  251. ssh $SSH_IDENT_ARGS "$SSH" "/etc/init.d/netgrip restart >/dev/null 2>&1 || true"
  252. ok "NetGrip embedded agent rearmed (server $SERVER, slug $SLUG)"
  253. info "the standalone agent is NOT installed on routers running NetGrip"
  254. exit 0
  255. fi
  256. # ------------------------------------------------------------------ binario --
  257. BIN_DST="/usr/sbin/$BIN_NAME"
  258. [ "$USE_TMP" -eq 1 ] && BIN_DST="/tmp/$BIN_NAME"
  259. TMP=$(mktemp -d) || fatal 34 "mktemp failed"
  260. cleanup() { rm -rf "$TMP"; }
  261. trap cleanup EXIT INT TERM
  262. if [ -n "$BINARY" ]; then
  263. [ -f "$BINARY" ] || fatal 30 "local binary not found: $BINARY"
  264. cp "$BINARY" "$TMP/$BIN_NAME"
  265. info "using the local binary: $BINARY"
  266. else
  267. ARCH=$(ssh $SSH_IDENT_ARGS "$SSH" uname -m) || fatal 31 "could not detect the architecture of $HOST"
  268. case "$ARCH" in
  269. aarch64|arm64) GOARCH=arm64 ;;
  270. armv7l|armv7) GOARCH=armv7 ;;
  271. mips)
  272. # uname -m dice "mips" para AMBOS endianness. El byte EI_DATA
  273. # (5º del ELF del sistema) decide: 0x01 = little (mipsle,
  274. # MT7621/ramips), 0x02 = big (mips, ath79). head|tail|tr en vez
  275. # de "od -t": busybox od no garantiza -t/-j/-N (#488).
  276. END=$(ssh $SSH_IDENT_ARGS "$SSH" 'head -c 6 /bin/sh | tail -c 1 | tr "\001\002" "12"')
  277. case "$END" in
  278. 1) GOARCH=mipsle ;;
  279. 2) GOARCH=mips ;;
  280. *) fatal 20 "could not detect the MIPS endianness of $HOST" ;;
  281. esac ;;
  282. *) fatal 20 "unsupported architecture: $ARCH (releases: arm64, armv7, mipsle, mips)" ;;
  283. esac
  284. if command -v curl >/dev/null 2>&1; then FETCH="curl -fsSL --retry 3 --connect-timeout 10"
  285. elif command -v wget >/dev/null 2>&1; then FETCH="wget -q -O-"
  286. else fatal 21 "curl or wget is required"; fi
  287. fetch_to() { $FETCH "$1" > "$2"; }
  288. command -v sha256sum >/dev/null 2>&1 || fatal 21 "sha256sum is missing"
  289. # ------------------------------------------------------------- server --
  290. # #1367: el binario sale del PROPIO server con la arch detectada arriba.
  291. # Antes el one-liner pre-descargaba sin ?arch= y el handler defaulteaba
  292. # a arm64: un router MIPS recibía un binario aarch64. Aquí la verdad es
  293. # del router (uname + EI_DATA) y el handler exige la arch explícita.
  294. # sha256 verificado contra la cabecera X-Checksum-Sha256 del server (#284);
  295. # GitHub queda como fallback (dev sin binarios embebidos, sin curl o con
  296. # --version explícita, que pide esa release concreta).
  297. if [ -z "$NETPULSE_VERSION" ] && [ -n "$TOKEN" ] && command -v curl >/dev/null 2>&1; then
  298. CA_ARGS=""
  299. [ -n "$CA_FILE" ] && CA_ARGS="--cacert $CA_FILE"
  300. info "downloading netpulse-agent ($GOARCH) from $SERVER"
  301. if curl -fsSL $CA_ARGS --connect-timeout 10 --retry 3 \
  302. -H "Authorization: Bearer $TOKEN" -D "$TMP/headers" \
  303. "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH" -o "$TMP/$BIN_NAME" \
  304. && [ -s "$TMP/$BIN_NAME" ]; then
  305. SUM_REF=$(grep -i '^x-checksum-sha256:' "$TMP/headers" | tr -d '\r' | awk '{print $2}')
  306. if [ -n "$SUM_REF" ]; then
  307. SUM_FILE=$(sha256sum "$TMP/$BIN_NAME" | awk '{print $1}')
  308. [ "$SUM_FILE" = "$SUM_REF" ] || fatal 33 "sha256 MISMATCH (server, arch $GOARCH)"
  309. ok "sha256 verified (server)"
  310. else
  311. warn "the server sent no X-Checksum-Sha256, no checksum verification"
  312. fi
  313. else
  314. warn "download from the server failed, trying the GitHub release"
  315. rm -f "$TMP/$BIN_NAME"
  316. fi
  317. fi
  318. if [ ! -s "$TMP/$BIN_NAME" ]; then
  319. if [ -z "$NETPULSE_VERSION" ]; then
  320. info "resolving the latest release"
  321. NETPULSE_VERSION=$($FETCH "https://api.github.com/repos/$GH_REPO/releases/latest" \
  322. | grep -oE '"tag_name"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | cut -d'"' -f4) \
  323. || fatal 31 "could not resolve the latest release, use --version=X.Y.Z"
  324. fi
  325. VERSION_NORM=$(echo "$NETPULSE_VERSION" | sed 's/^v//')
  326. case "$NETPULSE_VERSION" in
  327. v*) NETPULSE_TAG="$NETPULSE_VERSION" ;;
  328. *) NETPULSE_TAG="v$NETPULSE_VERSION" ;;
  329. esac
  330. ASSET="${BIN_NAME}_${VERSION_NORM}_linux_${GOARCH}.tar.gz"
  331. BASE_URL="https://github.com/$GH_REPO/releases/download/$NETPULSE_TAG"
  332. info "descargando $ASSET"
  333. fetch_to "$BASE_URL/$ASSET" "$TMP/$ASSET" || fatal 32 "download failed: $BASE_URL/$ASSET"
  334. fetch_to "$BASE_URL/checksums.txt" "$TMP/checksums.txt" || fatal 32 "checksums.txt is not in $NETPULSE_VERSION"
  335. SUM_FILE=$(sha256sum "$TMP/$ASSET" | awk '{print $1}')
  336. SUM_REF=$(grep " $ASSET\$" "$TMP/checksums.txt" | awk '{print $1}')
  337. [ -n "$SUM_REF" ] || fatal 33 "$ASSET is not in checksums.txt"
  338. [ "$SUM_FILE" = "$SUM_REF" ] || fatal 33 "sha256 MISMATCH for $ASSET"
  339. ok "sha256 verified"
  340. tar -xzf "$TMP/$ASSET" -C "$TMP"
  341. fi
  342. fi
  343. [ -s "$TMP/$BIN_NAME" ] || fatal 34 "no binary to install"
  344. # ------------------------------------------------------------------ install --
  345. info "copying the binary to $SSH:$BIN_DST"
  346. # Reinstalación: si hay una versión previa en marcha, parar el servicio ANTES
  347. # del scp — el proceso vivo tiene el binario abierto y la copia falla con
  348. # "Text file busy". El servicio se reactiva al final (enable + restart).
  349. ssh $SSH_IDENT_ARGS "$SSH" "/etc/init.d/$INIT_NAME stop >/dev/null 2>&1 || true"
  350. # -O: protocolo SCP legacy — dropbear (OpenWrt) no tiene sftp-server y el
  351. # scp de OpenSSH ≥9 usa SFTP por defecto → "connection closed" sin esto.
  352. # Copia atómica (#1654): se escribe un temporal EN EL MISMO directorio y se
  353. # renombra. Escribir directo sobre $BIN_DST deja un binario truncado si la
  354. # copia se corta, y un fallo del scp en el destino (overlay recién montado tras
  355. # un sysupgrade responde "file handle stale") se pierde entre el ruido de la
  356. # salida. Aquí cualquier fallo aborta con el código y el motivo a la vista.
  357. BIN_TMP="$BIN_DST.new"
  358. scp -Oq $SSH_IDENT_ARGS "$TMP/$BIN_NAME" "$SSH:$BIN_TMP" \
  359. || fatal 35 "could not copy the binary to $BIN_TMP on the router (check free space with 'df -h /' and that $BIN_DST is writable)"
  360. ssh $SSH_IDENT_ARGS "$SSH" "chmod 0755 $BIN_TMP && mv -f $BIN_TMP $BIN_DST" \
  361. || { ssh $SSH_IDENT_ARGS "$SSH" "rm -f $BIN_TMP" || true; fatal 36 "copied $BIN_TMP but could not move it to $BIN_DST on the router"; }
  362. ok "binary at $BIN_DST"
  363. # Config (chmod 600: el token solo lo lee root)
  364. info "writing $ENV_FILE (chmod 600)"
  365. # Construir la línea de token: PAIRING_TOKEN (bootstrap) o TOKEN (normal)
  366. if [ -n "$PAIRING_TOKEN" ]; then
  367. TOKEN_LINE="NETPULSE_PAIRING_TOKEN=$PAIRING_TOKEN"
  368. else
  369. TOKEN_LINE="NETPULSE_TOKEN=$TOKEN"
  370. fi
  371. # Server fingerprint (si se proporciona)
  372. FP_LINE=""
  373. if [ -n "$SERVER_FP" ]; then
  374. FP_LINE="NETPULSE_SERVER_FP=$SERVER_FP"
  375. fi
  376. # #851: conservar las NETPULSE_* del usuario que este script no gestiona
  377. # (p. ej. NETPULSE_WAN_TARGET): el rewrite toca solo las gestionadas
  378. # (SERVER/SLUG/TOKEN/SERVER_FP/PAIRING_TOKEN/SCAN_INTERVAL).
  379. # #1558: el scan periódico de vecinos sale APAGADO. Sacar la radio del canal
  380. # puede tirar clientes sensibles a beacons (#1557) y la vista de canales pide
  381. # el scan bajo demanda (#1561). Si el env ya trae NETPULSE_SCAN_INTERVAL, ese
  382. # valor manda (#851), también al reinstalar desde la UI.
  383. PREV_SCAN=$(ssh $SSH_IDENT_ARGS "$SSH" "grep -E '^NETPULSE_SCAN_INTERVAL=' $ENV_FILE 2>/dev/null | tail -n 1") || PREV_SCAN=""
  384. SCAN_LINE="NETPULSE_SCAN_INTERVAL=0"
  385. if [ -n "$PREV_SCAN" ]; then SCAN_LINE="$PREV_SCAN"; fi
  386. USER_VARS=$(ssh $SSH_IDENT_ARGS "$SSH" "grep -E '^NETPULSE_[A-Z0-9_]+=' $ENV_FILE 2>/dev/null | grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN|SCAN_INTERVAL)='") || USER_VARS=""
  387. ssh $SSH_IDENT_ARGS "$SSH" "cat > $ENV_FILE && chmod 600 $ENV_FILE" <<EOF
  388. # netpulse-agent — config (generado por install-agent.sh)
  389. NETPULSE_SERVER=$SERVER
  390. NETPULSE_SLUG=$SLUG
  391. $TOKEN_LINE
  392. $FP_LINE
  393. # defaults (líneas comentadas; descomenta para cambiar):
  394. # NETPULSE_INTERVAL=30 # segundos entre pushes
  395. # NETPULSE_SCAN_INTERVAL: "0" = sin scans periódicos (bajo demanda desde
  396. # "Análisis de canales"); "30m" u otro valor los reactiva.
  397. $SCAN_LINE
  398. # NETPULSE_WAN_TARGET=1.1.1.1 # solo si este equipo es el gateway
  399. # NETPULSE_GW_TARGET=192.168.8.1 # ping al gateway (APs)
  400. # NETPULSE_HEARTBEAT_FILE=/tmp/netpulse-agent.heartbeat
  401. EOF
  402. if [ -n "$USER_VARS" ]; then
  403. printf '%s\n' "$USER_VARS" | ssh $SSH_IDENT_ARGS "$SSH" "cat >> $ENV_FILE"
  404. fi
  405. ok "config written"
  406. # Servicio procd (respawn + self-heal del binario tras sysupgrade)
  407. info "installing the procd service"
  408. SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
  409. if [ -f "$SCRIPT_DIR/agent/deploy/$INIT_NAME.init" ]; then
  410. scp -Oq $SSH_IDENT_ARGS "$SCRIPT_DIR/agent/deploy/$INIT_NAME.init" "$SSH:$INIT_DST"
  411. else
  412. # Instalación vía curl|sh (sin repo a mano): init embebido — es el MISMO
  413. # contenido que agent/deploy/netpulse-agent.init (mantener ambos a la par).
  414. ssh $SSH_IDENT_ARGS "$SSH" "cat > $INIT_DST" <<'INITEOF'
  415. #!/bin/sh /etc/rc.common
  416. # netpulse-agent — agente nativo NetPulse para OpenWrt (SPEC-AGENTE-PILOTO §2)
  417. START=99
  418. STOP=10
  419. USE_PROCD=1
  420. ENV_FILE=/etc/netpulse-agent.env
  421. BIN=/usr/sbin/netpulse-agent
  422. [ -x "$BIN" ] || BIN=/tmp/netpulse-agent
  423. # Self-heal: un sysupgrade NO conserva los ficheros sueltos (solo conffiles
  424. # de paquetes, /etc/sysupgrade.conf y keep.d), por eso el instalador añade
  425. # binario, init y env a /etc/sysupgrade.conf (#1476). Si aun así falta el
  426. # binario al arrancar se descarga del server con el env (mismo criterio que el
  427. # reinstall del server; #851 retiró el watchdog cron, esto cubre el boot).
  428. selfheal_binary() {
  429. [ -x "$BIN" ] && return 0
  430. [ -f "$ENV_FILE" ] || return 1
  431. . "$ENV_FILE" 2>/dev/null
  432. [ -n "${NETPULSE_SERVER:-}" ] && [ -n "${NETPULSE_TOKEN:-}" ] && [ -n "${NETPULSE_SLUG:-}" ] || return 1
  433. case "${NETPULSE_SERVER%%:*}" in
  434. https|HTTPS) ;;
  435. *)
  436. [ "${NETPULSE_ALLOW_INSECURE_COMMANDS:-}" = "1" ] || {
  437. logger -t netpulse-agent "self-heal: HTTP without NETPULSE_ALLOW_INSECURE_COMMANDS=1, binary not downloaded"
  438. return 1
  439. }
  440. ;;
  441. esac
  442. case "$(uname -m)" in
  443. aarch64|arm64) local ARCH=arm64 ;;
  444. armv7l|armv7|armhf|arm) local ARCH=arm ;;
  445. x86_64|amd64) local ARCH=amd64 ;;
  446. mips)
  447. case "$(head -c 6 /bin/sh | tail -c 1 | tr '\001\002' '12')" in
  448. 1) local ARCH=mipsle ;;
  449. 2) local ARCH=mips ;;
  450. *) return 1 ;;
  451. esac ;;
  452. *) return 1 ;;
  453. esac
  454. local url tmp hdr digest sum
  455. url="${NETPULSE_SERVER%/}/api/agents/${NETPULSE_SLUG}/binary?arch=${ARCH}"
  456. logger -t netpulse-agent "self-heal: binary missing, downloading from $NETPULSE_SERVER"
  457. tmp=/tmp/netpulse-agent.$$
  458. hdr=/tmp/netpulse-agent.hdr.$$
  459. if command -v curl >/dev/null 2>&1; then
  460. curl -fsSL -m 120 -D "$hdr" -H "Authorization: Bearer $NETPULSE_TOKEN" -o "$tmp" "$url" || { rm -f "$tmp" "$hdr"; return 1; }
  461. else
  462. wget -S -T 60 -O "$tmp" --header="Authorization: Bearer $NETPULSE_TOKEN" "$url" 2>"$hdr" || { rm -f "$tmp" "$hdr"; return 1; }
  463. fi
  464. digest=$(grep -i '^[[:space:]]*x-checksum-sha256:' "$hdr" 2>/dev/null | tail -n 1 | tr -d '\r' | awk '{print $2}')
  465. rm -f "$hdr"
  466. case "$digest" in
  467. ""|*[!0123456789abcdefABCDEF]*)
  468. logger -t netpulse-agent "self-heal: no valid X-Checksum-Sha256, binary discarded"
  469. rm -f "$tmp"
  470. return 1 ;;
  471. esac
  472. [ "${#digest}" -eq 64 ] || { logger -t netpulse-agent "self-heal: digest with invalid length, binary discarded"; rm -f "$tmp"; return 1; }
  473. sum=$(sha256sum "$tmp" 2>/dev/null | awk '{print $1}')
  474. if [ -z "$sum" ] || [ "$(printf '%s' "$sum" | tr 'A-F' 'a-f')" != "$(printf '%s' "$digest" | tr 'A-F' 'a-f')" ]; then
  475. logger -t netpulse-agent "self-heal: SHA-256 mismatch, binary discarded"
  476. rm -f "$tmp"
  477. return 1
  478. fi
  479. chmod 0755 "$tmp" && mv "$tmp" /usr/sbin/netpulse-agent || { rm -f "$tmp"; return 1; }
  480. logger -t netpulse-agent "self-heal: binary restored"
  481. BIN=/usr/sbin/netpulse-agent
  482. return 0
  483. }
  484. # (#879) self-heal: tras un sysupgrade /etc sobrevive pero el binario del
  485. # watchdog no: si quedó la entrada de cron del antiguo watchdog, retirarla
  486. # (cron loguearía un comando inexistente cada 2 min).
  487. cleanup_stale_watchdog_cron() {
  488. [ -f /usr/sbin/netpulse-watchdog ] && return 0
  489. crontab -l 2>/dev/null | grep -q netpulse-watchdog || return 0
  490. ( crontab -l 2>/dev/null | grep -v netpulse-watchdog ) | crontab - 2>/dev/null || true
  491. logger -t netpulse-agent "orphan watchdog cron entry removed (#879)"
  492. }
  493. start_service() {
  494. cleanup_stale_watchdog_cron
  495. selfheal_binary || logger -t netpulse-agent "self-heal: could not restore the binary"
  496. procd_open_instance netpulse-agent
  497. procd_set_param command "$BIN"
  498. procd_set_param respawn "${respawn_threshold:-3600}" "${respawn_timeout:-5}" "${respawn_retry:-5}"
  499. procd_set_param stdout 1
  500. procd_set_param stderr 1
  501. procd_set_param file /etc/netpulse-agent.env
  502. procd_close_instance
  503. }
  504. INITEOF
  505. fi
  506. ssh $SSH_IDENT_ARGS "$SSH" "chmod 0755 $INIT_DST && $INIT_DST enable && $INIT_DST restart"
  507. ok "service $INIT_NAME enabled and started"
  508. # ------------------------------------------------------- sysupgrade (#1476) --
  509. # OpenWrt solo conserva en una actualización de imagen los conffiles de los
  510. # paquetes instalados, lo listado en /etc/sysupgrade.conf y
  511. # /lib/upgrade/keep.d/*. El init y el env que escribe este instalador son
  512. # ficheros sueltos: sin esta lista desaparecen al actualizar y el self-heal del
  513. # init nunca llega a correr, porque lo que se pierde es el punto de entrada.
  514. # Mismo gesto que el flujo owut (firmware.EnsureStackPreserved), idempotente.
  515. info "preserving the agent in /etc/sysupgrade.conf (#1476)"
  516. ssh $SSH_IDENT_ARGS "$SSH" "P=/etc/sysupgrade.conf; touch \$P; ensure() { grep -qxF \"\$1\" \$P 2>/dev/null || echo \"\$1\" >> \$P; }; ensure /usr/sbin/$BIN_NAME; ensure $ENV_FILE; ensure $INIT_DST; for f in /etc/rc.d/*$INIT_NAME*; do [ -e \"\$f\" ] && ensure \"\$f\"; done; true" \
  517. || warn "could not update /etc/sysupgrade.conf, the agent will not survive a firmware upgrade"
  518. # ------------------------------------------------- lldpd en puertos físicos (#1369) --
  519. # lldpd bound al bridge (br-lan) no recibe vecinos en varios targets
  520. # (qualcommax nss-dp verificado; DSA probable): los frames LLDP nunca suben
  521. # al listener del bridge master y la topología queda sin evidencia directa
  522. # sin avisar. Si lldpd está instalado y su binding es SOLO bridge, lo pasamos
  523. # a los puertos físicos (patrón OpenWrt estándar). Idempotente: un binding
  524. # que ya incluye puertos físicos (lan*/wan/eth*) no se toca. NO instalamos
  525. # lldpd aquí: instalar paquetes es decisión del usuario (el agente detecta
  526. # lldpd solo si ya está).
  527. if ssh $SSH_IDENT_ARGS "$SSH" "command -v lldpcli >/dev/null 2>&1"; then
  528. LLDP_IF=$(ssh $SSH_IDENT_ARGS "$SSH" "uci -q get lldpd.config.interface 2>/dev/null")
  529. if printf '%s' "$LLDP_IF" | grep -qE '(^|,)[[:space:]]*(lan|wan|eth)'; then
  530. ok "lldpd already listens on physical ports (${LLDP_IF:-auto})"
  531. else
  532. ssh $SSH_IDENT_ARGS "$SSH" "uci set lldpd.config.interface='lan*,wan' && uci commit lldpd && /etc/init.d/lldpd restart >/dev/null 2>&1" \
  533. && ok "lldpd reconfigured, listening on physical ports (lan*,wan)${LLDP_IF:+ - before: $LLDP_IF}" \
  534. || warn "could not reconfigure lldpd, by hand: uci set lldpd.config.interface='lan*,wan' && uci commit lldpd && /etc/init.d/lldpd restart"
  535. fi
  536. else
  537. info "lldpd not installed, no direct LLDP evidence (with 'opkg install lldpd' you enable it, then run this installer again and it moves it to the physical ports)"
  538. fi
  539. # Watchdog cron: NO se instala (#851). Si el agente crashea en bucle, un
  540. # reinicio a ciegas cada 2 min no lo arregla y ensucia el log; la detección
  541. # efectiva es el dead-man del servidor (alerta) y el crash puntual lo cubre
  542. # el respawn de procd. Además se limpia la entrada si venimos de una
  543. # instalación previa que sí lo programaba.
  544. ssh $SSH_IDENT_ARGS "$SSH" "
  545. rm -f /usr/sbin/netpulse-watchdog
  546. if [ -f /etc/crontabs/root ]; then
  547. sed -i '/netpulse-watchdog/d' /etc/crontabs/root
  548. fi
  549. "
  550. ok "watchdog cron not installed (legacy entry removed)"
  551. sleep 2
  552. if ssh $SSH_IDENT_ARGS "$SSH" "logread -e $INIT_NAME" 2>/dev/null | tail -2 | grep -q .; then
  553. info "last syslog lines:"
  554. ssh $SSH_IDENT_ARGS "$SSH" "logread -e $INIT_NAME | tail -2" || true
  555. fi
  556. printf '\n%s================ %s installed ================%s\n' "$C_G" "$BIN_NAME" "$C_0"
  557. printf 'Router: %s (slug: %s)\n' "$HOST" "$SLUG"
  558. printf 'Binary: %s%s\n' "$BIN_DST" "$( [ "$USE_TMP" -eq 1 ] && echo ' (/tmp variant: lost on reboot, run the installer again after one)' || true)"
  559. printf 'Config: %s (chmod 600, edit it and run /etc/init.d/%s restart)\n' "$ENV_FILE" "$INIT_NAME"
  560. printf 'Server: %s\n' "$SERVER"
  561. printf 'Logs: ssh %s logread -e %s\n' "$SSH" "$INIT_NAME"
  562. printf 'Check: GET %s/api/agents (last_seen + version within 15 s)\n' "$SERVER"
  563. printf '%s================================================%s\n\n' "$C_G" "$C_0"