4
0

executor.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. // Package executor — ejecutor sandboxeado de operaciones de escritura en el
  2. // router (Fase 10). El servidor envía una lista de Ops allowlistedas vía SSE;
  3. // el ejecutor las valida, hace snapshot, aplica en staging, commit, healthcheck
  4. // y rollback automático si falla.
  5. //
  6. // Allowlist estricta: cada Kind tiene un patrón regex por arg. Args que no
  7. // casan → rechazo inmediato. Shell libre PROHIBIDO.
  8. package executor
  9. import (
  10. "encoding/base64"
  11. "encoding/json"
  12. "fmt"
  13. "net"
  14. "os"
  15. "os/exec"
  16. "path/filepath"
  17. "regexp"
  18. "strings"
  19. "time"
  20. )
  21. // Op es una operación allowlistedada que el ejecutor puede aplicar.
  22. type Op struct {
  23. Kind string `json:"kind"` // uci_set|uci_delete|uci_add_list|uci_commit|service|install|wg_check
  24. Args map[string]string `json:"args"`
  25. Desc string `json:"desc"` // descripción humana para el diff
  26. }
  27. // ApplyResult es el resultado de ejecutar un plan.
  28. type ApplyResult struct {
  29. Status string `json:"status"` // applied|failed|rolled_back
  30. Op string `json:"op,omitempty"`
  31. Error string `json:"error,omitempty"`
  32. DurationMs int64 `json:"duration_ms"`
  33. Snapshot string `json:"snapshot,omitempty"` // configs afectados
  34. }
  35. // Runner ejecuta comandos en el router. Interfaz para inyectar fakes en tests.
  36. type Runner interface {
  37. Run(name string, args ...string) (stdout string, exitCode int)
  38. }
  39. // shellRunner usa exec.Command en producción.
  40. type shellRunner struct{}
  41. func (shellRunner) Run(name string, args ...string) (string, int) {
  42. out, err := exec.Command(name, args...).Output()
  43. code := 0
  44. if err != nil {
  45. if ee, ok := err.(*exec.ExitError); ok {
  46. code = ee.ExitCode()
  47. } else {
  48. code = -1
  49. }
  50. }
  51. return string(out), code
  52. }
  53. // patrones de validación por campo (sin shell metachars).
  54. var (
  55. reConfig = regexp.MustCompile(`^[a-z_]+$`)
  56. // section: nombre de sección (wifi-iface, interface, eth1) o referencia
  57. // `@tipo[idx]` / `@tipo[-1]`. Los dígitos cubren interfaces UCI reales
  58. // (eth1, wlan0, br-lan). `[-1]` referencia la ÚLTIMA sección del tipo —
  59. // usado tras un uci_add para setear los campos de la sección recién
  60. // creada (patrón OpenWrt estándar).
  61. reSection = regexp.MustCompile(`^(@[a-z0-9_-]+(\[\d+\]|\[-1\])|[a-z0-9_-]+)$`)
  62. reOption = regexp.MustCompile(`^[a-z0-9_]+$`)
  63. // value: alfanumérico + puntos, dos-puntos, barras, hashes, guiones.
  64. // Cubre IPs (192.168.1.1), DNS (1.1.1.1#3001), rutas, MACs, puertos.
  65. reValue = regexp.MustCompile(`^[a-zA-Z0-9_.:/#,-]+$`)
  66. reService = regexp.MustCompile(`^[a-z_-]+$`)
  67. reServiceAct = regexp.MustCompile(`^(restart|reload|enable|disable|start|stop)$`)
  68. rePackage = regexp.MustCompile(`^[a-z0-9_-]+$`)
  69. // Rutas de fichero permitidas para write_file/download/extract/chmod.
  70. // "/root" excluido a propósito (no hace falta para AdGuard y reduce la
  71. // superficie: .ssh/id_rsa etc. no deben ser escribibles).
  72. // Además del regex, Validate aplica filepath.Clean + rechazo de ".." a los
  73. // args marcados como path en opSpec (defense in depth: ".." casa el charset).
  74. reFilePath = regexp.MustCompile(`^/(etc|tmp|usr/bin|usr/lib|var/etc)/[A-Za-z0-9_./-]+$`)
  75. reDirPath = regexp.MustCompile(`^/(etc|tmp|usr/bin|usr/lib|opt|var/etc)/[A-Za-z0-9_./-]+$`)
  76. // Allowlist de dominios de descarga: SOLO releases oficiales de AdGuard.
  77. // Cualquier otra URL (incluida un attacker que controle el plan) se rechaza.
  78. reDownloadURL = regexp.MustCompile(`^https://github\.com/AdguardTeam/AdGuardHome/releases/download/v[0-9]+\.[0-9]+\.[0-9]+/AdGuardHome_linux_[a-z0-9]+\.tar\.gz$`)
  79. reMode = regexp.MustCompile(`^[0-7]{3,4}$`)
  80. // base64 estándar (sin newlines). La validación final la hace base64.Decode.
  81. reBase64 = regexp.MustCompile(`^[A-Za-z0-9+/]+={0,2}$`)
  82. // reBool: true|false (para flags como ownership_mode.enforce).
  83. reBool = regexp.MustCompile(`^(true|false)$`)
  84. // tcp_check: host (IPv4 o hostname simple) + puerto (1-65535).
  85. reHost = regexp.MustCompile(`^([0-9]{1,3}[.]){3}[0-9]{1,3}$|^[a-zA-Z0-9.-]{1,253}$`)
  86. // rePort valida 1-65535 sin ceros a la izquierda.
  87. rePort = regexp.MustCompile(`^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$`)
  88. )
  89. // opSpec define los args requeridos y su validación para cada Kind.
  90. type opSpec struct {
  91. required map[string]*regexp.Regexp
  92. build func(args map[string]string) (cmd string, cmdArgs []string)
  93. // exec, si está presente, reemplaza a build. Para Kinds que no son un
  94. // simple exec.Command (p. ej. write_file escribe el fichero en Go).
  95. exec func(run Runner, args map[string]string) int
  96. // pathArgs: args que son rutas de fichero/directorio. Validate les aplica
  97. // un check anti-traversal además del regex (filepath.Clean + sin "..").
  98. pathArgs []string
  99. configs func(args map[string]string) []string // UCI configs afectados (para snapshot)
  100. }
  101. var allowlist = map[string]opSpec{
  102. "uci_set": {
  103. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection, "option": reOption, "value": reValue},
  104. build: func(a map[string]string) (string, []string) {
  105. return "uci", []string{"set", fmt.Sprintf("%s.%s.%s=%s", a["config"], a["section"], a["option"], a["value"])}
  106. },
  107. configs: func(a map[string]string) []string { return []string{a["config"]} },
  108. },
  109. "uci_delete": {
  110. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection, "option": reOption},
  111. build: func(a map[string]string) (string, []string) {
  112. return "uci", []string{"delete", fmt.Sprintf("%s.%s.%s", a["config"], a["section"], a["option"])}
  113. },
  114. configs: func(a map[string]string) []string { return []string{a["config"]} },
  115. },
  116. "uci_add_list": {
  117. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection, "option": reOption, "value": reValue},
  118. build: func(a map[string]string) (string, []string) {
  119. return "uci", []string{"add_list", fmt.Sprintf("%s.%s.%s=%s", a["config"], a["section"], a["option"], a["value"])}
  120. },
  121. configs: func(a map[string]string) []string { return []string{a["config"]} },
  122. },
  123. "uci_commit": {
  124. required: map[string]*regexp.Regexp{"config": reConfig},
  125. build: func(a map[string]string) (string, []string) {
  126. return "uci", []string{"commit", a["config"]}
  127. },
  128. configs: func(a map[string]string) []string { return []string{a["config"]} },
  129. },
  130. // uci_add: crea una sección nueva. `uci add <config> <type>` imprime el
  131. // nombre; luego uci_set sobre @<type>[-1] setea sus campos. Necesario para
  132. // crear wifi-iface / network / firewall zone en módulos como WiFi guest.
  133. // type: nombre de sección (wifi-iface, interface, zone, forwarding).
  134. "uci_add": {
  135. required: map[string]*regexp.Regexp{"config": reConfig, "type": reSection},
  136. build: func(a map[string]string) (string, []string) {
  137. return "uci", []string{"add", a["config"], a["type"]}
  138. },
  139. configs: func(a map[string]string) []string { return []string{a["config"]} },
  140. },
  141. // uci_delete_section: borra una sección completa (`uci delete <cfg>.<sec>`),
  142. // a diferencia de uci_delete que quita una option. Útil para revertir un
  143. // módulo que creó secciones (guest network: quitar la wifi-iface, la
  144. // interface, la zone y el forwarding creados al habilitar).
  145. "uci_delete_section": {
  146. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection},
  147. build: func(a map[string]string) (string, []string) {
  148. return "uci", []string{"delete", a["config"] + "." + a["section"]}
  149. },
  150. configs: func(a map[string]string) []string { return []string{a["config"]} },
  151. },
  152. // uci_set_named: crea una SECCIÓN NOMBRADA de un tipo: `uci set
  153. // <config>.<section>=<type>`. Diferencia con uci_add (sección anónima):
  154. // las network interfaces se identifican por su nombre de sección
  155. // (network.guest=interface), mientras que wifi-iface/zone/forwarding
  156. // pueden ser anónimas (referenciadas por índice @tipo[i]).
  157. "uci_set_named": {
  158. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection, "type": reSection},
  159. build: func(a map[string]string) (string, []string) {
  160. return "uci", []string{"set", a["config"] + "." + a["section"] + "=" + a["type"]}
  161. },
  162. configs: func(a map[string]string) []string { return []string{a["config"]} },
  163. },
  164. // ownership_mode: activa/desactiva el modo de ownership UCI. Cuando
  165. // enforce=true, el executor rechaza tocar secciones que no estén
  166. // marcadas con np_managed=1, evitando que un módulo pise config ajena.
  167. // Debe ser la primera op del plan; en el executor actúa como no-op.
  168. "ownership_mode": {
  169. required: map[string]*regexp.Regexp{"enforce": reBool},
  170. exec: func(_ Runner, _ map[string]string) int { return 0 },
  171. configs: func(a map[string]string) []string { return nil },
  172. },
  173. // uci_set_managed: marca una sección como gestionada por NetPulse
  174. // (np_managed=1). Si la sección no existe, es un no-op: no queremos
  175. // crear secciones huérfanas solo por marcarlas.
  176. "uci_set_managed": {
  177. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection},
  178. exec: func(run Runner, a map[string]string) int {
  179. if !sectionExists(run, a["config"], a["section"]) {
  180. return 0
  181. }
  182. _, code := run.Run("uci", "set", fmt.Sprintf("%s.%s.np_managed=1", a["config"], a["section"]))
  183. return code
  184. },
  185. configs: func(a map[string]string) []string { return []string{a["config"]} },
  186. },
  187. "service": {
  188. required: map[string]*regexp.Regexp{"name": reService, "action": reServiceAct},
  189. build: func(a map[string]string) (string, []string) {
  190. return "/etc/init.d/" + a["name"], []string{a["action"]}
  191. },
  192. configs: func(a map[string]string) []string { return nil },
  193. },
  194. "install": {
  195. required: map[string]*regexp.Regexp{"package": rePackage},
  196. build: func(a map[string]string) (string, []string) {
  197. return "opkg", []string{"install", a["package"]}
  198. },
  199. configs: func(a map[string]string) []string { return nil },
  200. },
  201. // apk_install: OpenWrt 24+ usa apk en vez de opkg.
  202. "apk_install": {
  203. required: map[string]*regexp.Regexp{"package": rePackage},
  204. build: func(a map[string]string) (string, []string) {
  205. return "apk", []string{"add", a["package"]}
  206. },
  207. configs: func(a map[string]string) []string { return nil },
  208. },
  209. // apk_remove: desinstala un paquete con apk (OpenWrt 24+).
  210. "apk_remove": {
  211. required: map[string]*regexp.Regexp{"package": rePackage},
  212. build: func(a map[string]string) (string, []string) {
  213. return "apk", []string{"del", a["package"]}
  214. },
  215. configs: func(a map[string]string) []string { return nil },
  216. },
  217. // opkg_remove: desinstala un paquete con opkg (OpenWrt clásico).
  218. "opkg_remove": {
  219. required: map[string]*regexp.Regexp{"package": rePackage},
  220. build: func(a map[string]string) (string, []string) {
  221. return "opkg", []string{"remove", a["package"]}
  222. },
  223. configs: func(a map[string]string) []string { return nil },
  224. },
  225. // download: uclient-fetch (presente en OpenWrt por defecto) con allowlist
  226. // estricta de URL (solo releases oficiales de AdGuard). El dest se valida
  227. // con reFilePath. No shell libre: la URL va como arg, no interpolada.
  228. "download": {
  229. required: map[string]*regexp.Regexp{"url": reDownloadURL, "dest": reFilePath},
  230. pathArgs: []string{"dest"},
  231. build: func(a map[string]string) (string, []string) {
  232. return "uclient-fetch", []string{a["url"], "-O", a["dest"]}
  233. },
  234. configs: func(a map[string]string) []string { return nil },
  235. },
  236. // write_file: escribe contenido base64 a path. Se hace en Go (no shell)
  237. // para evitar inyección vía base64 -d | sh. Path sanitizado + re-chequeo.
  238. // Crea el directorio padre si no existe (MkdirAll, modo 0755) — necesario
  239. // para /etc/AdGuardHome/AdGuardHome.yaml donde el dir no existe aún.
  240. "write_file": {
  241. required: map[string]*regexp.Regexp{"path": reFilePath, "content_b64": reBase64},
  242. pathArgs: []string{"path"},
  243. exec: func(_ Runner, a map[string]string) int {
  244. path := a["path"]
  245. clean := filepath.Clean(path)
  246. if clean != path || !reFilePath.MatchString(clean) || strings.Contains(clean, "..") {
  247. return 1
  248. }
  249. data, err := base64.StdEncoding.DecodeString(a["content_b64"])
  250. if err != nil {
  251. return 1
  252. }
  253. if dir := filepath.Dir(clean); dir != "" && dir != "/" {
  254. if err := os.MkdirAll(dir, 0755); err != nil {
  255. return 1
  256. }
  257. }
  258. if err := os.WriteFile(clean, data, 0644); err != nil {
  259. return 1
  260. }
  261. return 0
  262. },
  263. configs: func(a map[string]string) []string { return nil },
  264. },
  265. // mv: mueve un fichero. src y dest en path allowlist. Necesario para el
  266. // escenario "binary" de AdGuard (extraer tarball y mover el binario a
  267. // /usr/bin/AdGuardHome).
  268. "mv": {
  269. required: map[string]*regexp.Regexp{"src": reFilePath, "dest": reFilePath},
  270. pathArgs: []string{"src", "dest"},
  271. build: func(a map[string]string) (string, []string) {
  272. return "mv", []string{a["src"], a["dest"]}
  273. },
  274. configs: func(a map[string]string) []string { return nil },
  275. },
  276. // extract_tarball: tar -xzf SRC -C DEST.
  277. "extract_tarball": {
  278. required: map[string]*regexp.Regexp{"src": reFilePath, "dest": reDirPath},
  279. pathArgs: []string{"src", "dest"},
  280. build: func(a map[string]string) (string, []string) {
  281. return "tar", []string{"-xzf", a["src"], "-C", a["dest"]}
  282. },
  283. configs: func(a map[string]string) []string { return nil },
  284. },
  285. // chmod: modo octal (3-4 dígitos) + path.
  286. "chmod": {
  287. required: map[string]*regexp.Regexp{"mode": reMode, "path": reFilePath},
  288. pathArgs: []string{"path"},
  289. build: func(a map[string]string) (string, []string) {
  290. return "chmod", []string{a["mode"], a["path"]}
  291. },
  292. configs: func(a map[string]string) []string { return nil },
  293. },
  294. // tcp_check: abre una conexión TCP al host:port. Éxito (exit 0) si conecta
  295. // dentro del budget; fallo (exit 1) si no. Es un healthcheck real de
  296. // servicio (el ping del executor solo confirma red). Usado por módulos que
  297. // abren puerto (AdGuard :3000, Tailscale, OpenVPN...): si el servicio no
  298. // levanta, esta op falla → el executor revierte staged.
  299. // Se hace en Go (no shell) para no depender de nc, que no siempre está en
  300. // OpenWrt stock. Reintenta durante tcpCheckBudget (10 s por defecto) cada
  301. // tcpCheckRetry: un servicio puede tardar unos segundos en abrir puerto
  302. // tras `service start` (AdGuard, Tailscale...).
  303. "tcp_check": {
  304. required: map[string]*regexp.Regexp{"host": reHost, "port": rePort},
  305. exec: func(_ Runner, a map[string]string) int {
  306. addr := net.JoinHostPort(a["host"], a["port"])
  307. start := time.Now()
  308. for time.Since(start) < tcpCheckBudget {
  309. conn, err := net.DialTimeout("tcp", addr, 2*time.Second)
  310. if err == nil {
  311. _ = conn.Close()
  312. return 0
  313. }
  314. time.Sleep(tcpCheckRetry)
  315. }
  316. return 1
  317. },
  318. configs: func(a map[string]string) []string { return nil },
  319. },
  320. // wg_check: healthcheck del módulo WireGuard (10.3). Ejecuta
  321. // `wg show <interface>`; exit 0 si el túnel está arriba en el kernel,
  322. // exit 1 si no existe o está caído. Al final del plan (tras el reload de
  323. // red), una fallo aquí significa que el apply aisló el túnel → el executor
  324. // restaura los snapshots (rollback real, ver Apply).
  325. "wg_check": {
  326. required: map[string]*regexp.Regexp{"interface": reSection},
  327. build: func(a map[string]string) (string, []string) {
  328. return "wg", []string{"show", a["interface"]}
  329. },
  330. configs: func(a map[string]string) []string { return nil },
  331. },
  332. // dawn_check: healthcheck del módulo DAWN. Ejecuta
  333. // `ubus call dawn get_network` y verifica que devuelva JSON no vacío
  334. // con vecinos. Si falla, el executor revierte los snapshots UCI.
  335. "dawn_check": {
  336. exec: func(run Runner, a map[string]string) int {
  337. out, code := run.Run("ubus", "call", "dawn", "get_network")
  338. if code != 0 {
  339. return code
  340. }
  341. out = strings.TrimSpace(out)
  342. if out == "" || out == "{}" {
  343. return 1
  344. }
  345. var v map[string]any
  346. if err := json.Unmarshal([]byte(out), &v); err != nil {
  347. return 1
  348. }
  349. if len(v) == 0 {
  350. return 1
  351. }
  352. return 0
  353. },
  354. configs: func(a map[string]string) []string { return nil },
  355. },
  356. // usteer_check: healthcheck del módulo usteer. Ejecuta
  357. // `ubus call usteer remote_hosts` y verifica que devuelva JSON no vacío.
  358. // Si falla, el executor revierte los snapshots UCI.
  359. "usteer_check": {
  360. exec: func(run Runner, a map[string]string) int {
  361. out, code := run.Run("ubus", "call", "usteer", "remote_hosts")
  362. if code != 0 {
  363. return code
  364. }
  365. out = strings.TrimSpace(out)
  366. if out == "" || out == "{}" {
  367. return 1
  368. }
  369. var v map[string]any
  370. if err := json.Unmarshal([]byte(out), &v); err != nil {
  371. return 1
  372. }
  373. if len(v) == 0 {
  374. return 1
  375. }
  376. return 0
  377. },
  378. configs: func(a map[string]string) []string { return nil },
  379. },
  380. // wifi_reload: aplica cambios en /etc/config/wireless sin reboot.
  381. "wifi_reload": {
  382. build: func(a map[string]string) (string, []string) {
  383. return "/sbin/wifi", []string{"reload"}
  384. },
  385. configs: func(a map[string]string) []string { return nil },
  386. },
  387. }
  388. // tcpCheckBudget / tcpCheckRetry controlan los reintentos del Kind tcp_check.
  389. // Son vars de paquete (no const) para poder acortarlos en tests.
  390. var (
  391. tcpCheckBudget = 10 * time.Second
  392. tcpCheckRetry = 500 * time.Millisecond
  393. )
  394. // Executor aplica Ops allowlistedas con snapshot + healthcheck + rollback.
  395. type Executor struct {
  396. run Runner
  397. now func() time.Time
  398. gwTarget string // IP del gateway para healthcheck (APs)
  399. wanTarget string // IP WAN para healthcheck (gateway)
  400. }
  401. // New crea un ejecutor. gwTarget/wanTarget se usan para el healthcheck
  402. // post-apply (al menos uno debe estar configurado).
  403. func New(gwTarget, wanTarget string) *Executor {
  404. return &Executor{run: shellRunner{}, now: time.Now, gwTarget: gwTarget, wanTarget: wanTarget}
  405. }
  406. // SetRunner inyecta un runner fake (tests).
  407. func (e *Executor) SetRunner(r Runner) { e.run = r }
  408. // SetClock inyecta un reloj (tests).
  409. func (e *Executor) SetClock(f func() time.Time) { e.now = f }
  410. // Validate comprueba que una Op pasa el allowlist sin ejecutarla.
  411. func Validate(op Op) error {
  412. spec, ok := allowlist[op.Kind]
  413. if !ok {
  414. return fmt.Errorf("kind %q no allowlistedado", op.Kind)
  415. }
  416. for arg, re := range spec.required {
  417. val, present := op.Args[arg]
  418. if !present || val == "" {
  419. return fmt.Errorf("arg %q requerido para %s", arg, op.Kind)
  420. }
  421. if !re.MatchString(val) {
  422. return fmt.Errorf("arg %q=%q no válido para %s (no casa con %s)", arg, val, op.Kind, re)
  423. }
  424. }
  425. // Defense in depth: args marcados como path no pueden contener ".." ni
  426. // resolverse a algo distinto tras filepath.Clean (p. ej. "/etc/../x").
  427. for _, arg := range spec.pathArgs {
  428. val := op.Args[arg]
  429. if strings.Contains(val, "..") || filepath.Clean(val) != val {
  430. return fmt.Errorf("arg %q=%q contiene traversal (..) para %s", arg, val, op.Kind)
  431. }
  432. }
  433. return nil
  434. }
  435. // Apply ejecuta una lista de Ops con snapshot, commit y healthcheck.
  436. // Devuelve applied si todo OK, rolled_back si el healthcheck falla, o
  437. // failed si alguna Op falla antes del commit.
  438. func (e *Executor) Apply(ops []Op) ApplyResult {
  439. start := e.now()
  440. // 1. Validar todas las Ops antes de tocar nada.
  441. for _, op := range ops {
  442. if err := Validate(op); err != nil {
  443. return ApplyResult{Status: "failed", Op: op.Desc, Error: err.Error(), DurationMs: ms(e.now(), start)}
  444. }
  445. }
  446. // 1b. Modo ownership: si hay una op ownership_mode con enforce=true,
  447. // las ops posteriores solo podrán tocar secciones marcadas como
  448. // np_managed=1. Esto evita que módulos distintos pisen config ajena.
  449. enforceOwnership := false
  450. for _, op := range ops {
  451. if op.Kind == "ownership_mode" && op.Args["enforce"] == "true" {
  452. enforceOwnership = true
  453. break
  454. }
  455. }
  456. // 2. Snapshot de los configs UCI afectados.
  457. affected := affectedConfigs(ops)
  458. snapshots := map[string]string{}
  459. for _, cfg := range affected {
  460. out, code := e.run.Run("uci", "export", cfg)
  461. if code == 0 && out != "" {
  462. snapshots[cfg] = out
  463. }
  464. }
  465. // 3. Ejecutar Ops (staged, sin commit aún).
  466. for _, op := range ops {
  467. if op.Kind == "ownership_mode" {
  468. // No-op en runtime: solo activa el flag en la fase de parseo.
  469. continue
  470. }
  471. if enforceOwnership {
  472. switch op.Kind {
  473. case "uci_add":
  474. // Crear sección anónima y marcarla como gestionada.
  475. cfg, secType := op.Args["config"], op.Args["type"]
  476. out, code := e.run.Run("uci", "add", cfg, secType)
  477. if code != 0 {
  478. e.revertStaged(affected)
  479. return ApplyResult{Status: "failed", Op: op.Desc, Error: fmt.Sprintf("uci_add exit %d", code), DurationMs: ms(e.now(), start)}
  480. }
  481. secName := strings.TrimSpace(out)
  482. if secName == "" {
  483. secName = fmt.Sprintf("@%s[-1]", secType)
  484. }
  485. if _, code := e.run.Run("uci", "set", fmt.Sprintf("%s.%s.np_managed=1", cfg, secName)); code != 0 {
  486. e.revertStaged(affected)
  487. return ApplyResult{Status: "failed", Op: op.Desc, Error: "uci_set_managed failed after uci_add", DurationMs: ms(e.now(), start)}
  488. }
  489. continue
  490. case "uci_set_named":
  491. cfg, sec, secType := op.Args["config"], op.Args["section"], op.Args["type"]
  492. if sectionExists(e.run, cfg, sec) {
  493. if err := ownershipCheck(e.run, cfg, sec); err != nil {
  494. e.revertStaged(affected)
  495. return ApplyResult{Status: "failed", Op: op.Desc, Error: err.Error(), DurationMs: ms(e.now(), start)}
  496. }
  497. }
  498. if _, code := e.run.Run("uci", "set", fmt.Sprintf("%s.%s=%s", cfg, sec, secType)); code != 0 {
  499. e.revertStaged(affected)
  500. return ApplyResult{Status: "failed", Op: op.Desc, Error: fmt.Sprintf("uci_set_named exit %d", code), DurationMs: ms(e.now(), start)}
  501. }
  502. if _, code := e.run.Run("uci", "set", fmt.Sprintf("%s.%s.np_managed=1", cfg, sec)); code != 0 {
  503. e.revertStaged(affected)
  504. return ApplyResult{Status: "failed", Op: op.Desc, Error: "uci_set_managed failed after uci_set_named", DurationMs: ms(e.now(), start)}
  505. }
  506. continue
  507. case "uci_set_managed":
  508. // Esta op permite marcar/takeover secciones sin comprobación.
  509. code := allowlist[op.Kind].exec(e.run, op.Args)
  510. if code != 0 {
  511. e.revertStaged(affected)
  512. return ApplyResult{Status: "failed", Op: op.Desc, Error: fmt.Sprintf("uci_set_managed exit %d", code), DurationMs: ms(e.now(), start)}
  513. }
  514. continue
  515. }
  516. // Ops que tocan una sección existente: uci_set, uci_delete,
  517. // uci_add_list, uci_delete_section.
  518. if cfg, sec, ok := opTargetConfigSection(op); ok {
  519. if err := ownershipCheck(e.run, cfg, sec); err != nil {
  520. e.revertStaged(affected)
  521. return ApplyResult{Status: "failed", Op: op.Desc, Error: err.Error(), DurationMs: ms(e.now(), start)}
  522. }
  523. }
  524. }
  525. spec := allowlist[op.Kind]
  526. var code int
  527. if spec.exec != nil {
  528. code = spec.exec(e.run, op.Args)
  529. } else {
  530. cmd, cmdArgs := spec.build(op.Args)
  531. _, code = e.run.Run(cmd, cmdArgs...)
  532. }
  533. if code != 0 {
  534. if op.Kind == "wg_check" || op.Kind == "dawn_check" || op.Kind == "usteer_check" {
  535. // Healthcheck del módulo: rollback real restaurando snapshots UCI
  536. // y relanzando los servicios afectados.
  537. for cfg, snap := range snapshots {
  538. e.run.Run("sh", "-c", fmt.Sprintf("echo '%s' | uci import", snap))
  539. e.run.Run("uci", "commit", cfg)
  540. }
  541. if op.Kind == "wg_check" {
  542. e.run.Run("/etc/init.d/network", "reload")
  543. }
  544. if op.Kind == "dawn_check" {
  545. e.run.Run("/etc/init.d/dawn", "restart")
  546. e.run.Run("/sbin/wifi", "reload")
  547. }
  548. if op.Kind == "usteer_check" {
  549. e.run.Run("/etc/init.d/usteer", "restart")
  550. e.run.Run("/sbin/wifi", "reload")
  551. }
  552. errKey := "wg_check_failed"
  553. if op.Kind == "dawn_check" {
  554. errKey = "dawn_check_failed"
  555. }
  556. if op.Kind == "usteer_check" {
  557. errKey = "usteer_check_failed"
  558. }
  559. return ApplyResult{Status: "rolled_back", Op: op.Desc, Error: errKey, Snapshot: strings.Join(affected, ","), DurationMs: ms(e.now(), start)}
  560. }
  561. // Revert staged changes y salir.
  562. e.revertStaged(affected)
  563. return ApplyResult{Status: "failed", Op: op.Desc, Error: fmt.Sprintf("%s exit %d", op.Kind, code), DurationMs: ms(e.now(), start)}
  564. }
  565. }
  566. // 4. Commit de cada config afectado.
  567. for _, cfg := range affected {
  568. e.run.Run("uci", "commit", cfg)
  569. }
  570. // 5. Healthcheck.
  571. if !e.healthcheck() {
  572. // ROLLBACK: restaurar snapshots.
  573. for cfg, snap := range snapshots {
  574. e.run.Run("sh", "-c", fmt.Sprintf("echo '%s' | uci import", snap))
  575. e.run.Run("uci", "commit", cfg)
  576. }
  577. return ApplyResult{Status: "rolled_back", Error: "healthcheck_failed", Snapshot: strings.Join(affected, ","), DurationMs: ms(e.now(), start)}
  578. }
  579. return ApplyResult{Status: "applied", Snapshot: strings.Join(affected, ","), DurationMs: ms(e.now(), start)}
  580. }
  581. func (e *Executor) revertStaged(configs []string) {
  582. for _, cfg := range configs {
  583. e.run.Run("uci", "revert", cfg)
  584. }
  585. }
  586. func (e *Executor) healthcheck() bool {
  587. target := e.wanTarget
  588. if target == "" {
  589. target = e.gwTarget
  590. }
  591. if target == "" {
  592. return true // sin target configurado: pasar (mejor falso negativo que bloquear)
  593. }
  594. _, code := e.run.Run("ping", "-c", "1", "-W", "3", target)
  595. return code == 0
  596. }
  597. func affectedConfigs(ops []Op) []string {
  598. seen := map[string]bool{}
  599. var out []string
  600. for _, op := range ops {
  601. spec, ok := allowlist[op.Kind]
  602. if !ok {
  603. continue
  604. }
  605. for _, cfg := range spec.configs(op.Args) {
  606. if cfg != "" && !seen[cfg] {
  607. seen[cfg] = true
  608. out = append(out, cfg)
  609. }
  610. }
  611. }
  612. return out
  613. }
  614. // sectionExists comprueba si una sección UCI existe (uci show cfg.sec).
  615. func sectionExists(run Runner, config, section string) bool {
  616. _, code := run.Run("uci", "show", fmt.Sprintf("%s.%s", config, section))
  617. return code == 0
  618. }
  619. // ownershipCheck devuelve error si la sección existe y no está marcada como
  620. // gestionada por NetPulse (np_managed=1). Si no existe, permite crearla.
  621. func ownershipCheck(run Runner, config, section string) error {
  622. if !sectionExists(run, config, section) {
  623. return nil
  624. }
  625. out, code := run.Run("uci", "get", fmt.Sprintf("%s.%s.np_managed", config, section))
  626. if code == 0 && strings.TrimSpace(out) == "1" {
  627. return nil
  628. }
  629. return fmt.Errorf("section_not_managed: %s.%s is not owned by NetPulse", config, section)
  630. }
  631. // opTargetConfigSection devuelve el config/section de ops que tocan una
  632. // sección UCI existente, para aplicar el ownership check.
  633. func opTargetConfigSection(op Op) (string, string, bool) {
  634. switch op.Kind {
  635. case "uci_set", "uci_delete", "uci_add_list", "uci_delete_section":
  636. return op.Args["config"], op.Args["section"], true
  637. }
  638. return "", "", false
  639. }
  640. func ms(now, start time.Time) int64 {
  641. return now.Sub(start).Milliseconds()
  642. }
  643. // MarshalOps serializa una lista de Ops a JSON (para enviar vía SSE).
  644. func MarshalOps(ops []Op) (string, error) {
  645. b, err := json.Marshal(ops)
  646. return string(b), err
  647. }
  648. // UnmarshalOps deserializa Ops desde JSON (en el agente, al recibir el SSE).
  649. func UnmarshalOps(data string) ([]Op, error) {
  650. var ops []Op
  651. err := json.Unmarshal([]byte(data), &ops)
  652. return ops, err
  653. }