reinstall.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. // Package reinstall: construcción del script de instalación del agente
  2. // netpulse-agent en un router OpenWrt (#246, #457, #463). Lo comparten el
  3. // handler manual (POST /api/agents/{slug}/reinstall) y el supervisor del
  4. // rearmer (escalado restart → reinstall), de ahí su propio paquete: httpapi
  5. // importa rearmer y ninguno de los dos puede importar al otro.
  6. package reinstall
  7. import (
  8. "strconv"
  9. "strings"
  10. "github.com/gnacho/netpulse/server-go/internal/agentbin"
  11. )
  12. // Trust is how an agent reaches the server over HTTPS. FORK.
  13. //
  14. // The zero value leaves the script behaving as before. With a CA, the script
  15. // writes the root to the router - over the SSH session it runs in, whose host
  16. // key the server has verified - and downloads verify the server against it,
  17. // so the agent token in the request header is not handed to whoever answers.
  18. // The binary's sha256 was always checked; this protects the token.
  19. type Trust struct {
  20. ServerURL string // replaces the URL given to Script, e.g. https://host:443
  21. ServerFP string // written as NETPULSE_SERVER_FP: what the agent pins
  22. CAPEM []byte // the root to verify downloads with
  23. }
  24. // caPath is where the router keeps the root.
  25. const caPath = "/etc/netpulse-ca.pem"
  26. // Script construye el POSIX sh que se ejecuta en el router: instala el
  27. // agente completo (binario verificado por sha256, config .env, init procd
  28. // con self-heal) de forma idempotente. Ya NO instala el watchdog con cron
  29. // (#851): si el agente crashea en bucle, un reinicio a ciegas no lo arregla
  30. // y ensucia el log; la detección efectiva es el dead-man del servidor. La
  31. // caída puntual la cubre el respawn de procd; el binario tras sysupgrade lo
  32. // restaura el self-heal del init.
  33. // digests mapa arch→sha256 del binario embebido; un arch sin digest queda
  34. // sin verificación (build dev) en lugar de bloquear.
  35. // serverFP es el SPKI pin del server (#851): si serverURL es https y el
  36. // server lo pudo derivar (ServerFP), va en el .env para que el agente no
  37. // entre en bucle fatal de "HTTPS requiere NETPULSE_SERVER_FP"; vacío = el
  38. // comportamiento previo (env sin FP).
  39. //
  40. // FORK: trust, when given, is how the agent should reach the server now -
  41. // the HTTPS address with the private CA - and wins over serverURL and
  42. // serverFP; its root is written to the router to verify downloads with.
  43. // TargetsFor: resuelve los objetivos de sonda para un slug desde la tabla de
  44. // routers (#1204): la unidad gateway hace ping a internet; el resto, al
  45. // gateway (su IP de la tabla). Sin gateway declarado no se escribe nada.
  46. type RouterRow struct {
  47. ID string
  48. Host string
  49. IsGateway bool
  50. // AgentInterval (#1476): cadencia de push del agente en segundos. 0 =
  51. // default del agente.
  52. AgentInterval int
  53. }
  54. func TargetsFor(routers []RouterRow, slug string) WanTargets {
  55. gwIP := ""
  56. for _, rc := range routers {
  57. if rc.IsGateway && rc.ID != slug {
  58. gwIP = rc.Host
  59. }
  60. }
  61. for _, rc := range routers {
  62. if rc.ID != slug {
  63. continue
  64. }
  65. if rc.IsGateway {
  66. return WanTargets{WanTarget: "1.1.1.1", Interval: rc.AgentInterval}
  67. }
  68. if gwIP != "" {
  69. return WanTargets{GwTarget: gwIP, Interval: rc.AgentInterval}
  70. }
  71. }
  72. return WanTargets{}
  73. }
  74. func Script(slug, token, serverURL, serverFP string, digests map[string]string, trust ...Trust) string {
  75. return ScriptWithTargets(slug, token, serverURL, serverFP, digests, WanTargets{}, trust...)
  76. }
  77. // WanTargets (#1204): la sonda de latencia del agente solo corre con
  78. // NETPULSE_WAN_TARGET (gateway) o NETPULSE_GW_TARGET (APs) en su env, y el
  79. // instalador histórico las dejaba comentadas: ninguna instalación las tenía
  80. // y las tarjetas de latencia se quedaban sin datos para siempre. El server
  81. // sabe qué unidad es el gateway: resuelve los objetivos y el script escribe
  82. // las líneas ACTIVAS. Unidades ya instaladas: un reinstall desde la UI las
  83. // estrena.
  84. type WanTargets struct {
  85. WanTarget string // gateway: ping a internet (p. ej. "1.1.1.1"); vacío = comentada
  86. GwTarget string // APs: IP del gateway para el ping; vacío = comentada
  87. // Interval (#1476): cadencia de push del agente en segundos. 0 deja el
  88. // default del agente (30 s) y borra la clave de la config UCI.
  89. Interval int
  90. }
  91. // progressBlock define los dos avisos que usan los scripts. Va en el
  92. // preámbulo y ANTES de cualquier llamada: estaba dentro de envRewriteBlock y
  93. // el script llamaba a say() en la detección de arquitectura, así que el
  94. // reinstall moría con "say: not found" (#1894).
  95. const progressBlock = `warn() { echo "netpulse-agent: $*" >&2; }
  96. say() { echo "netpulse-agent: $*"; }
  97. `
  98. // caSetupBlock escribe (o borra) la raíz de la CA en el router. Without a
  99. // root, one left from an earlier install (a CA since replaced) would make
  100. // every https download fail against it.
  101. func caSetupBlock(tr Trust) string {
  102. if len(tr.CAPEM) == 0 {
  103. return "\nrm -f " + caPath + "\n"
  104. }
  105. return `
  106. # FORK: the server's root, to verify downloads with (written over this SSH
  107. # session, so it is the server's own)
  108. cat > ` + caPath + ` <<'CAEOF'
  109. ` + strings.TrimSpace(string(tr.CAPEM)) + `
  110. CAEOF
  111. chmod 644 ` + caPath + `
  112. `
  113. }
  114. // envRewriteBlock regenera /etc/netpulse-agent.env con las vars gestionadas
  115. // actuales, conservando las NETPULSE_* del usuario (#851). Usa las vars de
  116. // entorno del script anfitrión: SERVER, SLUG, TOKEN y SERVER_FP.
  117. //
  118. // #1558: el env sale con NETPULSE_SCAN_INTERVAL=0 activo. El scan periódico
  119. // de vecinos saca la radio del canal y puede tirar clientes sensibles a
  120. // beacons (#1557); la vista de canales pide el scan bajo demanda (#1561). Un
  121. // valor que ya esté en el env gana, para no pisar un override manual (#851).
  122. func envRewriteBlock(targets WanTargets) string {
  123. return `# #1853: escribir la config no puede abortar el reinstall. El env se
  124. # compone en un temporal y solo se pone en su sitio si salio entero, asi que un
  125. # /etc lleno o de solo lectura conserva el anterior en vez de dejarlo a medias.
  126. USER_VARS=""
  127. SCAN_VALUE="0"
  128. if [ -f "$ENV_FILE" ]; then
  129. prev_scan=$(grep -E '^NETPULSE_SCAN_INTERVAL=' "$ENV_FILE" | tail -n 1) || prev_scan=""
  130. if [ -n "$prev_scan" ]; then SCAN_VALUE=${prev_scan#NETPULSE_SCAN_INTERVAL=}; fi
  131. USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+=' "$ENV_FILE" | grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN|WAN_TARGET|GW_TARGET|SCAN_INTERVAL)=') || true
  132. fi
  133. ENV_TMP="$ENV_FILE.new.$$"
  134. write_env() {
  135. cat > "$ENV_TMP" <<EOF
  136. # netpulse-agent — config (generado por reinstall)
  137. NETPULSE_SERVER=$SERVER
  138. NETPULSE_SLUG=$SLUG
  139. NETPULSE_TOKEN=$TOKEN
  140. # NETPULSE_SERVER_FP=<sha256> # server SPKI pin (https), filled by the installer
  141. # NETPULSE_INTERVAL=30 # segundos entre pushes
  142. # NETPULSE_SCAN_INTERVAL: "0" = no periodic scans (on demand from
  143. # "Channel analysis"), "30m" or another value re-enables them.
  144. NETPULSE_SCAN_INTERVAL=$SCAN_VALUE
  145. ` + func() string {
  146. wanLine := "# NETPULSE_WAN_TARGET=1.1.1.1 # solo si este equipo es el gateway"
  147. if targets.WanTarget != "" {
  148. wanLine = "NETPULSE_WAN_TARGET=" + targets.WanTarget
  149. }
  150. gwLine := "# NETPULSE_GW_TARGET=192.168.8.1 # ping al gateway (APs)"
  151. if targets.GwTarget != "" {
  152. gwLine = "NETPULSE_GW_TARGET=" + targets.GwTarget
  153. }
  154. return wanLine + "\n" + gwLine
  155. }() + `
  156. # NETPULSE_HEARTBEAT_FILE=/tmp/netpulse-agent.heartbeat
  157. EOF
  158. # #851: con server https el agente exige el SPKI pin; vacío = http plano o
  159. # el server no pudo derivarlo (se comporta como antes).
  160. if [ -n "$SERVER_FP" ]; then
  161. echo "NETPULSE_SERVER_FP=$SERVER_FP" >> "$ENV_TMP" || return 1
  162. fi
  163. if [ -n "$USER_VARS" ]; then
  164. printf '%s\n' "$USER_VARS" >> "$ENV_TMP" || return 1
  165. fi
  166. chmod 600 "$ENV_TMP" || return 1
  167. mv -f "$ENV_TMP" "$ENV_FILE" || return 1
  168. }
  169. if ! write_env; then
  170. rm -f "$ENV_TMP"
  171. warn "could not write $ENV_FILE, keeping the previous one"
  172. fi
  173. `
  174. }
  175. // uciConfigBlock (#1476) sincroniza la configuración nativa del paquete con
  176. // el env que acaba de escribir envRewriteBlock. /etc/config/netpulse-agent es
  177. // un conffile, así que sobrevive a sysupgrade, y el init procd del paquete lee
  178. // UCI (#1772): sin este bloque un reinstall dejaba el env al día y la config
  179. // nativa con el token viejo. Solo actúa si el fichero existe, es decir, si el
  180. // router tiene el paquete instalado; una instalación por ficheros sueltos
  181. // sigue funcionando con el env. No toca `interval`: no lo gestiona el
  182. // reinstall y pisarlo borraría un ajuste del usuario. Los campos opcionales
  183. // vacíos se borran para no dejar un target falso.
  184. func uciConfigBlock(targets WanTargets) string {
  185. return `UCI_CFG=/etc/config/netpulse-agent
  186. if [ -f "$UCI_CFG" ] && command -v uci >/dev/null 2>&1; then
  187. uci -q set netpulse-agent.main.server="$SERVER" || true
  188. uci -q set netpulse-agent.main.slug="$SLUG" || true
  189. uci -q set netpulse-agent.main.token="$TOKEN" || true
  190. if [ -n "$SERVER_FP" ]; then
  191. uci -q set netpulse-agent.main.server_fp="$SERVER_FP" || true
  192. else
  193. uci -q delete netpulse-agent.main.server_fp || true
  194. fi
  195. uci -q set netpulse-agent.main.scan_interval="$SCAN_VALUE" || true
  196. ` + func() string {
  197. out := ""
  198. if targets.WanTarget != "" {
  199. out += "\tuci -q set netpulse-agent.main.wan_target=\"" + targets.WanTarget + "\" || true\n"
  200. } else {
  201. out += "\tuci -q delete netpulse-agent.main.wan_target || true\n"
  202. }
  203. if targets.GwTarget != "" {
  204. out += "\tuci -q set netpulse-agent.main.gw_target=\"" + targets.GwTarget + "\" || true\n"
  205. } else {
  206. out += "\tuci -q delete netpulse-agent.main.gw_target || true\n"
  207. }
  208. // #1476: el intervalo es un ajuste por router. 0 vuelve al default
  209. // del agente, así que se borra la clave en vez de escribir un cero.
  210. if targets.Interval > 0 {
  211. out += "\tuci -q set netpulse-agent.main.interval=\"" + strconv.Itoa(targets.Interval) + "\" || true\n"
  212. } else {
  213. out += "\tuci -q delete netpulse-agent.main.interval || true\n"
  214. }
  215. return out
  216. }() + ` uci -q commit netpulse-agent || true
  217. fi
  218. `
  219. }
  220. // preserveOnSysupgrade (#1476) añade los ficheros del agente a
  221. // /etc/sysupgrade.conf. OpenWrt solo conserva en una actualización de imagen los
  222. // conffiles declarados por los paquetes instalados, lo listado en ese fichero y
  223. // /lib/upgrade/keep.d/*; el init y el env los escribe este script como ficheros
  224. // sueltos, así que sin esta lista desaparecen y el self-heal nunca llega a
  225. // correr, porque lo que se pierde es el punto de entrada. Idempotente (no
  226. // duplica líneas) y el mismo gesto que firmware.EnsureStackPreserved (owut).
  227. const preserveOnSysupgrade = `
  228. # Preservar el agente en sysupgrade (#1476): mismo gesto que el flujo owut.
  229. P=/etc/sysupgrade.conf
  230. touch "$P" 2>/dev/null || true
  231. ensure_sysupgrade() { grep -qxF "$1" "$P" 2>/dev/null || echo "$1" >> "$P" 2>/dev/null || true; }
  232. ensure_sysupgrade /usr/sbin/netpulse-agent
  233. ensure_sysupgrade /etc/netpulse-agent.env
  234. ensure_sysupgrade /etc/init.d/netpulse-agent
  235. for f in /etc/rc.d/*netpulse-agent*; do [ -e "$f" ] && ensure_sysupgrade "$f"; done
  236. # Conffile y defaults del paquete: en una instalación por paquete OpenWrt los
  237. # conserva por sí solo, pero declararlos aquí cubre el caso de un router que
  238. # recibió el paquete y luego un reinstall por SSH.
  239. for f in /etc/config/netpulse-agent /etc/uci-defaults/90-netpulse-agent; do
  240. [ -e "$f" ] && ensure_sysupgrade "$f"
  241. done
  242. true
  243. `
  244. // EnvScript (#1294) es la variante LIGERA del script de instalación: NO
  245. // descarga binario ni toca el init; solo reescribe la CA raíz y
  246. // /etc/netpulse-agent.env (rotando el token) y reinicia el agente para que
  247. // relea el env. Es lo que convierte un cambio de TLS/HTTPS en un despliegue
  248. // de un clic: enable HTTPS → re-emit → toda la flota SSH-reachable migra sin
  249. // reinstalar a mano. Mismos gestos de trust que ScriptWithTargets.
  250. func EnvScript(slug, token, serverURL, serverFP string, targets WanTargets, trust ...Trust) string {
  251. var tr Trust
  252. if len(trust) > 0 {
  253. tr = trust[0]
  254. }
  255. if tr.ServerURL != "" {
  256. serverURL = tr.ServerURL
  257. }
  258. if tr.ServerFP != "" {
  259. serverFP = tr.ServerFP
  260. }
  261. return `#!/bin/sh
  262. set -e
  263. INIT=/etc/init.d/netpulse-agent
  264. ENV_FILE=/etc/netpulse-agent.env
  265. SERVER="` + serverURL + `"
  266. SLUG="` + slug + `"
  267. TOKEN="` + token + `"
  268. SERVER_FP="` + serverFP + `"
  269. ` + progressBlock + caSetupBlock(tr) + envRewriteBlock(targets) + uciConfigBlock(targets) + preserveOnSysupgrade + `
  270. # Releer el env: el agente lo lee del fichero en cada arranque (#1287), así
  271. # que basta un restart del init procd (respawn inmediato).
  272. if [ -f "$INIT" ]; then
  273. "$INIT" restart >/dev/null 2>&1 || true
  274. fi
  275. `
  276. }
  277. func ScriptWithTargets(slug, token, serverURL, serverFP string, digests map[string]string, targets WanTargets, trust ...Trust) string {
  278. var tr Trust
  279. if len(trust) > 0 {
  280. tr = trust[0]
  281. }
  282. if tr.ServerURL != "" {
  283. serverURL = tr.ServerURL
  284. }
  285. if tr.ServerFP != "" {
  286. serverFP = tr.ServerFP
  287. }
  288. caSetup := caSetupBlock(tr)
  289. return `#!/bin/sh
  290. set -e
  291. INIT=/etc/init.d/netpulse-agent
  292. BIN=/usr/sbin/netpulse-agent
  293. ENV_FILE=/etc/netpulse-agent.env
  294. SERVER="` + serverURL + `"
  295. SLUG="` + slug + `"
  296. TOKEN="` + token + `"
  297. SERVER_FP="` + serverFP + `"
  298. ` + progressBlock + caSetup + `
  299. # FORK: verify https downloads against the server's root when there is one
  300. CURL_TLS=""; WGET_TLS=""
  301. if [ -f ` + caPath + ` ]; then CURL_TLS="--cacert ` + caPath + `"; WGET_TLS="--ca-certificate=` + caPath + `"; fi
  302. # Detectar arquitectura del router y el digest esperado del binario embebido
  303. ARCH=$(uname -m)
  304. case "$ARCH" in
  305. aarch64|arm64) GOARCH=arm64; SHA256="` + digests["arm64"] + `" ;;
  306. armv7l|armv7|armhf|arm) GOARCH=arm; SHA256="` + digests["arm"] + `" ;;
  307. x86_64|amd64) GOARCH=amd64; SHA256="` + digests["amd64"] + `" ;;
  308. mips)
  309. # uname -m dice "mips" para AMBOS endianness: el byte EI_DATA (5º del
  310. # ELF) decide. head|tail|tr en vez de "od -t": busybox no lo garantiza.
  311. case "$(head -c 6 /bin/sh | tail -c 1 | tr '\001\002' '12')" in
  312. 1) GOARCH=mipsle; SHA256="` + digests["mipsle"] + `" ;;
  313. 2) GOARCH=mips; SHA256="` + digests["mips"] + `" ;;
  314. *) echo "could not detect the endianness of $ARCH" >&2; exit 20 ;;
  315. esac ;;
  316. *) echo "unsupported arch: $ARCH" >&2; exit 20 ;;
  317. esac
  318. say "architecture $ARCH ($GOARCH)"
  319. # #1476: si el router habla opkg o apk, instala el paquete que sirve el propio
  320. # servidor. Deja binario, init y /etc/config/netpulse-agent, que es conffile y
  321. # sobrevive a un sysupgrade. El .ipk lo compone el servidor al vuelo desde el
  322. # binario embebido; el .apk lo firma el CI y solo esta si el operador lo dejo
  323. # junto al binario. Cualquier fallo (sin gestor, descarga rota, paquete
  324. # rechazado) cae al camino de ficheros sueltos de abajo: el paquete es una
  325. # mejora, no un requisito.
  326. PKG_OK=0
  327. PKG_URL="$SERVER/api/agents/$SLUG/package?arch=$GOARCH"
  328. pkg_fetch() {
  329. if command -v curl >/dev/null 2>&1; then
  330. curl -fsSL $CURL_TLS --connect-timeout 10 -m 600 -H "Authorization: Bearer $TOKEN" "$1" -o "$2" 2>/dev/null
  331. else
  332. wget -q $WGET_TLS -T 60 -O "$2" --header="Authorization: Bearer $TOKEN" "$1" 2>/dev/null
  333. fi
  334. }
  335. if command -v opkg >/dev/null 2>&1; then
  336. pkg_fetch "$PKG_URL&format=ipk" /tmp/netpulse-agent.ipk || rm -f /tmp/netpulse-agent.ipk
  337. if [ -s /tmp/netpulse-agent.ipk ] && opkg install --force-reinstall /tmp/netpulse-agent.ipk >/dev/null 2>&1; then
  338. PKG_OK=1
  339. else
  340. echo "netpulse-agent: the .ipk package did not install, continuing with the loose files" >&2
  341. fi
  342. rm -f /tmp/netpulse-agent.ipk
  343. elif command -v apk >/dev/null 2>&1; then
  344. pkg_fetch "$PKG_URL&format=apk" /tmp/netpulse-agent.apk || rm -f /tmp/netpulse-agent.apk
  345. if [ -s /tmp/netpulse-agent.apk ] && apk add --allow-untrusted /tmp/netpulse-agent.apk >/dev/null 2>&1; then
  346. PKG_OK=1
  347. else
  348. echo "netpulse-agent: the .apk package did not install, continuing with the loose files" >&2
  349. fi
  350. rm -f /tmp/netpulse-agent.apk
  351. fi
  352. if [ "$PKG_OK" = "1" ]; then say "package installed"; else say "no package, installing the loose binary"; fi
  353. if [ "$PKG_OK" != "1" ]; then
  354. # Descargar el binario del propio server (auth por token)
  355. # #1737: sin estos mensajes el fallo llega como "Process exited with status
  356. # 1" y nada mas. wget -q no imprime su motivo, asi que la descarga fallida
  357. # por wget era completamente muda.
  358. if command -v curl >/dev/null 2>&1; then
  359. curl -fsSL $CURL_TLS --connect-timeout 10 -m 600 -H "Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH" -o /tmp/netpulse-agent.new || { echo "netpulse-agent: could not download the binary from $SERVER (curl)" >&2; exit 22; }
  360. else
  361. wget -q $WGET_TLS -T 60 -O /tmp/netpulse-agent.new --header="Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH" || { echo "netpulse-agent: could not download the binary from $SERVER (wget)" >&2; exit 22; }
  362. fi
  363. # Verificación sha256 contra el digest embebido (#463); vacío = sin verificar
  364. if [ -n "$SHA256" ]; then
  365. GOT=$(sha256sum /tmp/netpulse-agent.new | awk '{print $1}')
  366. [ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)" >&2; exit 21; }
  367. fi
  368. chmod 0755 /tmp/netpulse-agent.new
  369. say "binary downloaded and verified"
  370. # #1853: el servicio se para AQUI, con el binario ya descargado y verificado.
  371. # Pararlo antes dejaba el router sin agente si la descarga fallaba. Hay que
  372. # pararlo igualmente: /tmp es tmpfs y /usr es overlay, asi que mv escribe el
  373. # destino y un binario en ejecucion da ETXTBSY. Si el reemplazo falla, se
  374. # vuelve a arrancar el anterior en vez de dejarlo caido.
  375. [ -f "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
  376. if ! mv -f /tmp/netpulse-agent.new "$BIN"; then
  377. echo "netpulse-agent: could not replace $BIN, restarting the previous agent" >&2
  378. [ -f "$INIT" ] && "$INIT" start >/dev/null 2>&1 || true
  379. exit 23
  380. fi
  381. fi
  382. # Config (chmod 600). El rewrite toca SOLO las vars gestionadas (SERVER,
  383. # SLUG, TOKEN, SERVER_FP, WAN_TARGET, GW_TARGET): las NETPULSE_* del usuario
  384. # (p. ej. NETPULSE_SCAN_INTERVAL=0) se conservan tal cual (#851).
  385. ` + envRewriteBlock(targets) + uciConfigBlock(targets) + `
  386. if [ "$PKG_OK" != "1" ]; then
  387. # Init procd con self-heal (#457): un sysupgrade no conserva los ficheros
  388. # sueltos, así que el binario, el init y el env se añaden a
  389. # /etc/sysupgrade.conf (#1476); si aun así falta el binario al arrancar se
  390. # descarga del server con este env.
  391. INIT_TMP="/tmp/netpulse-agent.init.$$"
  392. # #1853: el init se escribe en un temporal y se mueve solo si salio entero, para
  393. # no dejar /etc/init.d a medias si el disco esta lleno.
  394. if cat > "$INIT_TMP" <<'INITEOF'
  395. #!/bin/sh /etc/rc.common
  396. # netpulse-agent — agente nativo NetPulse para OpenWrt, con self-heal.
  397. # Config en /etc/netpulse-agent.env (chmod 600); procd reinicia si cambia.
  398. START=99
  399. STOP=10
  400. USE_PROCD=1
  401. ENV_FILE=/etc/netpulse-agent.env
  402. BIN=/usr/sbin/netpulse-agent
  403. [ -x "$BIN" ] || BIN=/tmp/netpulse-agent
  404. selfheal_binary() {
  405. [ -x "$BIN" ] && return 0
  406. [ -f "$ENV_FILE" ] || return 1
  407. . "$ENV_FILE" 2>/dev/null
  408. [ -n "${NETPULSE_SERVER:-}" ] && [ -n "${NETPULSE_TOKEN:-}" ] && [ -n "${NETPULSE_SLUG:-}" ] || return 1
  409. case "${NETPULSE_SERVER%%:*}" in
  410. https|HTTPS) ;;
  411. *)
  412. [ "${NETPULSE_ALLOW_INSECURE_COMMANDS:-}" = "1" ] || {
  413. logger -t netpulse-agent "self-heal: HTTP without NETPULSE_ALLOW_INSECURE_COMMANDS=1, binary not downloaded"
  414. return 1
  415. }
  416. ;;
  417. esac
  418. case "$(uname -m)" in
  419. aarch64|arm64) local ARCH=arm64 ;;
  420. armv7l|armv7|armhf|arm) local ARCH=arm ;;
  421. x86_64|amd64) local ARCH=amd64 ;;
  422. mips)
  423. case "$(head -c 6 /bin/sh | tail -c 1 | tr '\001\002' '12')" in
  424. 1) local ARCH=mipsle ;;
  425. 2) local ARCH=mips ;;
  426. *) return 1 ;;
  427. esac ;;
  428. *) return 1 ;;
  429. esac
  430. local url tmp hdr digest sum
  431. url="${NETPULSE_SERVER%/}/api/agents/${NETPULSE_SLUG}/binary?arch=${ARCH}"
  432. logger -t netpulse-agent "self-heal: binary missing, downloading from $NETPULSE_SERVER"
  433. tmp=/tmp/netpulse-agent.$$
  434. hdr=/tmp/netpulse-agent.hdr.$$
  435. local ctls="" wtls=""
  436. if [ -f /etc/netpulse-ca.pem ]; then ctls="--cacert /etc/netpulse-ca.pem"; wtls="--ca-certificate=/etc/netpulse-ca.pem"; fi
  437. if command -v curl >/dev/null 2>&1; then
  438. curl -fsSL $ctls -m 120 -D "$hdr" -H "Authorization: Bearer $NETPULSE_TOKEN" -o "$tmp" "$url" || { rm -f "$tmp" "$hdr"; return 1; }
  439. else
  440. wget -S $wtls -T 60 -O "$tmp" --header="Authorization: Bearer $NETPULSE_TOKEN" "$url" 2>"$hdr" || { rm -f "$tmp" "$hdr"; return 1; }
  441. fi
  442. digest=$(grep -i '^[[:space:]]*x-checksum-sha256:' "$hdr" 2>/dev/null | tail -n 1 | tr -d '\r' | awk '{print $2}')
  443. rm -f "$hdr"
  444. case "$digest" in
  445. ""|*[!0123456789abcdefABCDEF]*)
  446. logger -t netpulse-agent "self-heal: no valid X-Checksum-Sha256, binary discarded"
  447. rm -f "$tmp"
  448. return 1 ;;
  449. esac
  450. [ "${#digest}" -eq 64 ] || { logger -t netpulse-agent "self-heal: digest with invalid length, binary discarded"; rm -f "$tmp"; return 1; }
  451. sum=$(sha256sum "$tmp" 2>/dev/null | awk '{print $1}')
  452. if [ -z "$sum" ] || [ "$(printf '%s' "$sum" | tr 'A-F' 'a-f')" != "$(printf '%s' "$digest" | tr 'A-F' 'a-f')" ]; then
  453. logger -t netpulse-agent "self-heal: SHA-256 mismatch, binary discarded"
  454. rm -f "$tmp"
  455. return 1
  456. fi
  457. chmod 0755 "$tmp" && mv "$tmp" /usr/sbin/netpulse-agent || { rm -f "$tmp"; return 1; }
  458. logger -t netpulse-agent "self-heal: binary restored"
  459. BIN=/usr/sbin/netpulse-agent
  460. return 0
  461. }
  462. # (#879) self-heal: tras un sysupgrade /etc sobrevive pero el binario del
  463. # watchdog no: si quedó la entrada de cron del antiguo watchdog, retirarla
  464. # (cron loguearía un comando inexistente cada 2 min).
  465. cleanup_stale_watchdog_cron() {
  466. [ -f /usr/sbin/netpulse-watchdog ] && return 0
  467. crontab -l 2>/dev/null | grep -q netpulse-watchdog || return 0
  468. ( crontab -l 2>/dev/null | grep -v netpulse-watchdog ) | crontab - 2>/dev/null || true
  469. logger -t netpulse-agent "orphan watchdog cron entry removed (#879)"
  470. }
  471. # #1857: si el binario no está y el self-heal no lo trae, no se registra la
  472. # instancia. procd arrancaría una ruta inexistente, reintentaría y se
  473. # rendiría, dejando el servicio como arrancado y el agente muerto sin más
  474. # rastro que una línea en el log.
  475. start_service() {
  476. cleanup_stale_watchdog_cron
  477. if ! selfheal_binary; then
  478. logger -t netpulse-agent "self-heal: could not restore the binary, the service will not start"
  479. return 0
  480. fi
  481. procd_open_instance netpulse-agent
  482. procd_set_param command "$BIN"
  483. procd_set_param respawn "${respawn_threshold:-3600}" "${respawn_timeout:-5}" "${respawn_retry:-5}"
  484. procd_set_param stdout 1
  485. procd_set_param stderr 1
  486. procd_set_param file /etc/netpulse-agent.env
  487. procd_close_instance
  488. }
  489. INITEOF
  490. then
  491. chmod 0755 "$INIT_TMP" && mv -f "$INIT_TMP" "$INIT" || { rm -f "$INIT_TMP"; warn "could not install $INIT"; }
  492. else
  493. rm -f "$INIT_TMP"
  494. warn "could not prepare $INIT"
  495. fi
  496. fi
  497. # #851: el watchdog cron YA NO se instala (un reinicio a ciegas de un crash
  498. # loop no arregla nada y ensucia el log; la detección es el dead-man del
  499. # servidor). Si el router viene de una instalación que sí lo tenía, limpiarlo.
  500. rm -f /usr/sbin/netpulse-watchdog || warn "could not remove /usr/sbin/netpulse-watchdog"
  501. if [ -f /etc/crontabs/root ]; then
  502. sed -i '/netpulse-watchdog/d' /etc/crontabs/root || warn "could not clean the watchdog cron entry"
  503. fi
  504. # #1853: de aqui al final nada puede abortar en silencio: el binario nuevo ya
  505. # esta en su sitio y el servicio sigue parado, asi que se avisa y se arranca.
  506. "$INIT" enable >/dev/null 2>&1 || warn "could not enable $INIT"
  507. ` + preserveOnSysupgrade + `
  508. if ! "$INIT" restart >/dev/null 2>&1; then
  509. warn "the agent did not start after the reinstall, check $INIT"
  510. exit 24
  511. fi
  512. say "agent started"
  513. `
  514. }
  515. // TokenPushScript construye el POSIX sh que rota el token en CALIENTE: solo
  516. // reescribe el token en /etc/netpulse-agent.env (conservando server, slug,
  517. // FP del pin SPKI y las NETPULSE_* del usuario) y reinicia el servicio. No
  518. // descarga binario ni toca el init: es la versión ligera de reinstall para
  519. // cuando el token cambia pero el binario y la config ya están bien (rotate
  520. // "en caliente").
  521. func TokenPushScript(slug, token string) string {
  522. return `#!/bin/sh
  523. set -e
  524. ENV_FILE=/etc/netpulse-agent.env
  525. INIT=/etc/init.d/netpulse-agent
  526. # El env debe existir: el router ya tenía el agente instalado.
  527. [ -f "$ENV_FILE" ] || { echo "netpulse-agent.env does not exist, token not updated" >&2; exit 30; }
  528. # Conservar el server y el slug del env existente para no romper la config.
  529. SERVER=$(sed -n 's/^NETPULSE_SERVER=//p' "$ENV_FILE" | head -n1)
  530. SLUG=$(sed -n 's/^NETPULSE_SLUG=//p' "$ENV_FILE" | head -n1)
  531. # #851: conservar también el FP del pin SPKI y las NETPULSE_* no gestionadas
  532. # (p. ej. NETPULSE_SCAN_INTERVAL=0); si se pierden, el agente cae en bucle
  533. # fatal (https sin FP) o pierde la config del usuario. TOKEN y PAIRING_TOKEN
  534. # se descartan a propósito: el token rota y un pairing token residual ya no
  535. # aplica una vez emparejado.
  536. FP=$(sed -n 's/^NETPULSE_SERVER_FP=//p' "$ENV_FILE" | head -n1)
  537. USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+=' "$ENV_FILE" | grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN)=') || true
  538. [ -n "$SLUG" ] || { echo "netpulse-agent.env has no NETPULSE_SLUG" >&2; exit 31; }
  539. umask 077
  540. cat > "$ENV_FILE.tmp" <<EOF
  541. NETPULSE_SERVER=$SERVER
  542. NETPULSE_SLUG=$SLUG
  543. NETPULSE_TOKEN=` + token + `
  544. EOF
  545. if [ -n "$FP" ]; then
  546. echo "NETPULSE_SERVER_FP=$FP" >> "$ENV_FILE.tmp"
  547. fi
  548. if [ -n "$USER_VARS" ]; then
  549. printf '%s\n' "$USER_VARS" >> "$ENV_FILE.tmp"
  550. fi
  551. chmod 600 "$ENV_FILE.tmp"
  552. # Swap atómico: el proceso vivo sigue leyendo el archivo íntegro.
  553. mv -f "$ENV_FILE.tmp" "$ENV_FILE"
  554. # #1816: el init del paquete lee UCI primero y solo cae al env si el token de
  555. # UCI está vacío. Rotar solo el env dejaba el token viejo en
  556. # /etc/config/netpulse-agent y el agente respondía 401 para siempre. Se
  557. # sincronizan también server y slug: si UCI apunta a un servidor antiguo, el
  558. # token nuevo tampoco sirve.
  559. UCI_CFG=/etc/config/netpulse-agent
  560. if [ -f "$UCI_CFG" ] && command -v uci >/dev/null 2>&1; then
  561. uci -q set netpulse-agent.main.server="$SERVER" || true
  562. uci -q set netpulse-agent.main.slug="$SLUG" || true
  563. uci -q set netpulse-agent.main.token=` + token + ` || true
  564. uci -q commit netpulse-agent || true
  565. fi
  566. # procd rearma solito por el file (procd_set_param file), pero por
  567. # determinismo reiniciamos el servicio explícitamente.
  568. [ -x "$INIT" ] && "$INIT" restart >/dev/null 2>&1 || true
  569. `
  570. }
  571. // Digests devuelve los sha256 de los binarios de agente embebidos (cadena
  572. // vacía si el arch no tiene binario).
  573. func Digests() map[string]string {
  574. return map[string]string{
  575. "arm64": agentbin.Digest("arm64"),
  576. "arm": agentbin.Digest("arm"),
  577. "amd64": agentbin.Digest("amd64"),
  578. "mipsle": agentbin.Digest("mipsle"),
  579. "mips": agentbin.Digest("mips"),
  580. }
  581. }