executor.go 27 KB

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