4
0

executor.go 28 KB

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