executor.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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-z_]+$`)
  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. // tcp_check: host (IPv4 o hostname simple) + puerto (1-65535).
  83. reHost = regexp.MustCompile(`^([0-9]{1,3}[.]){3}[0-9]{1,3}$|^[a-zA-Z0-9.-]{1,253}$`)
  84. // rePort valida 1-65535 sin ceros a la izquierda.
  85. 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])$`)
  86. )
  87. // opSpec define los args requeridos y su validación para cada Kind.
  88. type opSpec struct {
  89. required map[string]*regexp.Regexp
  90. build func(args map[string]string) (cmd string, cmdArgs []string)
  91. // exec, si está presente, reemplaza a build. Para Kinds que no son un
  92. // simple exec.Command (p. ej. write_file escribe el fichero en Go).
  93. exec func(run Runner, args map[string]string) int
  94. // pathArgs: args que son rutas de fichero/directorio. Validate les aplica
  95. // un check anti-traversal además del regex (filepath.Clean + sin "..").
  96. pathArgs []string
  97. configs func(args map[string]string) []string // UCI configs afectados (para snapshot)
  98. }
  99. var allowlist = map[string]opSpec{
  100. "uci_set": {
  101. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection, "option": reOption, "value": reValue},
  102. build: func(a map[string]string) (string, []string) {
  103. return "uci", []string{"set", fmt.Sprintf("%s.%s.%s=%s", a["config"], a["section"], a["option"], a["value"])}
  104. },
  105. configs: func(a map[string]string) []string { return []string{a["config"]} },
  106. },
  107. "uci_delete": {
  108. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection, "option": reOption},
  109. build: func(a map[string]string) (string, []string) {
  110. return "uci", []string{"delete", fmt.Sprintf("%s.%s.%s", a["config"], a["section"], a["option"])}
  111. },
  112. configs: func(a map[string]string) []string { return []string{a["config"]} },
  113. },
  114. "uci_add_list": {
  115. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection, "option": reOption, "value": reValue},
  116. build: func(a map[string]string) (string, []string) {
  117. return "uci", []string{"add_list", fmt.Sprintf("%s.%s.%s=%s", a["config"], a["section"], a["option"], a["value"])}
  118. },
  119. configs: func(a map[string]string) []string { return []string{a["config"]} },
  120. },
  121. "uci_commit": {
  122. required: map[string]*regexp.Regexp{"config": reConfig},
  123. build: func(a map[string]string) (string, []string) {
  124. return "uci", []string{"commit", a["config"]}
  125. },
  126. configs: func(a map[string]string) []string { return []string{a["config"]} },
  127. },
  128. // uci_add: crea una sección nueva. `uci add <config> <type>` imprime el
  129. // nombre; luego uci_set sobre @<type>[-1] setea sus campos. Necesario para
  130. // crear wifi-iface / network / firewall zone en módulos como WiFi guest.
  131. // type: nombre de sección (wifi-iface, interface, zone, forwarding).
  132. "uci_add": {
  133. required: map[string]*regexp.Regexp{"config": reConfig, "type": reSection},
  134. build: func(a map[string]string) (string, []string) {
  135. return "uci", []string{"add", a["config"], a["type"]}
  136. },
  137. configs: func(a map[string]string) []string { return []string{a["config"]} },
  138. },
  139. // uci_delete_section: borra una sección completa (`uci delete <cfg>.<sec>`),
  140. // a diferencia de uci_delete que quita una option. Útil para revertir un
  141. // módulo que creó secciones (guest network: quitar la wifi-iface, la
  142. // interface, la zone y el forwarding creados al habilitar).
  143. "uci_delete_section": {
  144. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection},
  145. build: func(a map[string]string) (string, []string) {
  146. return "uci", []string{"delete", a["config"] + "." + a["section"]}
  147. },
  148. configs: func(a map[string]string) []string { return []string{a["config"]} },
  149. },
  150. // uci_set_named: crea una SECCIÓN NOMBRADA de un tipo: `uci set
  151. // <config>.<section>=<type>`. Diferencia con uci_add (sección anónima):
  152. // las network interfaces se identifican por su nombre de sección
  153. // (network.guest=interface), mientras que wifi-iface/zone/forwarding
  154. // pueden ser anónimas (referenciadas por índice @tipo[i]).
  155. "uci_set_named": {
  156. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection, "type": reSection},
  157. build: func(a map[string]string) (string, []string) {
  158. return "uci", []string{"set", a["config"] + "." + a["section"] + "=" + a["type"]}
  159. },
  160. configs: func(a map[string]string) []string { return []string{a["config"]} },
  161. },
  162. "service": {
  163. required: map[string]*regexp.Regexp{"name": reService, "action": reServiceAct},
  164. build: func(a map[string]string) (string, []string) {
  165. return "/etc/init.d/" + a["name"], []string{a["action"]}
  166. },
  167. configs: func(a map[string]string) []string { return nil },
  168. },
  169. "install": {
  170. required: map[string]*regexp.Regexp{"package": rePackage},
  171. build: func(a map[string]string) (string, []string) {
  172. return "opkg", []string{"install", a["package"]}
  173. },
  174. configs: func(a map[string]string) []string { return nil },
  175. },
  176. // apk_install: OpenWrt 24+ usa apk en vez de opkg.
  177. "apk_install": {
  178. required: map[string]*regexp.Regexp{"package": rePackage},
  179. build: func(a map[string]string) (string, []string) {
  180. return "apk", []string{"add", a["package"]}
  181. },
  182. configs: func(a map[string]string) []string { return nil },
  183. },
  184. // download: uclient-fetch (presente en OpenWrt por defecto) con allowlist
  185. // estricta de URL (solo releases oficiales de AdGuard). El dest se valida
  186. // con reFilePath. No shell libre: la URL va como arg, no interpolada.
  187. "download": {
  188. required: map[string]*regexp.Regexp{"url": reDownloadURL, "dest": reFilePath},
  189. pathArgs: []string{"dest"},
  190. build: func(a map[string]string) (string, []string) {
  191. return "uclient-fetch", []string{a["url"], "-O", a["dest"]}
  192. },
  193. configs: func(a map[string]string) []string { return nil },
  194. },
  195. // write_file: escribe contenido base64 a path. Se hace en Go (no shell)
  196. // para evitar inyección vía base64 -d | sh. Path sanitizado + re-chequeo.
  197. // Crea el directorio padre si no existe (MkdirAll, modo 0755) — necesario
  198. // para /etc/AdGuardHome/AdGuardHome.yaml donde el dir no existe aún.
  199. "write_file": {
  200. required: map[string]*regexp.Regexp{"path": reFilePath, "content_b64": reBase64},
  201. pathArgs: []string{"path"},
  202. exec: func(_ Runner, a map[string]string) int {
  203. path := a["path"]
  204. clean := filepath.Clean(path)
  205. if clean != path || !reFilePath.MatchString(clean) || strings.Contains(clean, "..") {
  206. return 1
  207. }
  208. data, err := base64.StdEncoding.DecodeString(a["content_b64"])
  209. if err != nil {
  210. return 1
  211. }
  212. if dir := filepath.Dir(clean); dir != "" && dir != "/" {
  213. if err := os.MkdirAll(dir, 0755); err != nil {
  214. return 1
  215. }
  216. }
  217. if err := os.WriteFile(clean, data, 0644); err != nil {
  218. return 1
  219. }
  220. return 0
  221. },
  222. configs: func(a map[string]string) []string { return nil },
  223. },
  224. // mv: mueve un fichero. src y dest en path allowlist. Necesario para el
  225. // escenario "binary" de AdGuard (extraer tarball y mover el binario a
  226. // /usr/bin/AdGuardHome).
  227. "mv": {
  228. required: map[string]*regexp.Regexp{"src": reFilePath, "dest": reFilePath},
  229. pathArgs: []string{"src", "dest"},
  230. build: func(a map[string]string) (string, []string) {
  231. return "mv", []string{a["src"], a["dest"]}
  232. },
  233. configs: func(a map[string]string) []string { return nil },
  234. },
  235. // extract_tarball: tar -xzf SRC -C DEST.
  236. "extract_tarball": {
  237. required: map[string]*regexp.Regexp{"src": reFilePath, "dest": reDirPath},
  238. pathArgs: []string{"src", "dest"},
  239. build: func(a map[string]string) (string, []string) {
  240. return "tar", []string{"-xzf", a["src"], "-C", a["dest"]}
  241. },
  242. configs: func(a map[string]string) []string { return nil },
  243. },
  244. // chmod: modo octal (3-4 dígitos) + path.
  245. "chmod": {
  246. required: map[string]*regexp.Regexp{"mode": reMode, "path": reFilePath},
  247. pathArgs: []string{"path"},
  248. build: func(a map[string]string) (string, []string) {
  249. return "chmod", []string{a["mode"], a["path"]}
  250. },
  251. configs: func(a map[string]string) []string { return nil },
  252. },
  253. // tcp_check: abre una conexión TCP al host:port. Éxito (exit 0) si conecta
  254. // dentro del budget; fallo (exit 1) si no. Es un healthcheck real de
  255. // servicio (el ping del executor solo confirma red). Usado por módulos que
  256. // abren puerto (AdGuard :3000, Tailscale, OpenVPN...): si el servicio no
  257. // levanta, esta op falla → el executor revierte staged.
  258. // Se hace en Go (no shell) para no depender de nc, que no siempre está en
  259. // OpenWrt stock. Reintenta durante tcpCheckBudget (10 s por defecto) cada
  260. // tcpCheckRetry: un servicio puede tardar unos segundos en abrir puerto
  261. // tras `service start` (AdGuard, Tailscale...).
  262. "tcp_check": {
  263. required: map[string]*regexp.Regexp{"host": reHost, "port": rePort},
  264. exec: func(_ Runner, a map[string]string) int {
  265. addr := net.JoinHostPort(a["host"], a["port"])
  266. start := time.Now()
  267. for time.Since(start) < tcpCheckBudget {
  268. conn, err := net.DialTimeout("tcp", addr, 2*time.Second)
  269. if err == nil {
  270. _ = conn.Close()
  271. return 0
  272. }
  273. time.Sleep(tcpCheckRetry)
  274. }
  275. return 1
  276. },
  277. configs: func(a map[string]string) []string { return nil },
  278. },
  279. // wg_check: healthcheck del módulo WireGuard (10.3). Ejecuta
  280. // `wg show <interface>`; exit 0 si el túnel está arriba en el kernel,
  281. // exit 1 si no existe o está caído. Al final del plan (tras el reload de
  282. // red), una fallo aquí significa que el apply aisló el túnel → el executor
  283. // restaura los snapshots (rollback real, ver Apply).
  284. "wg_check": {
  285. required: map[string]*regexp.Regexp{"interface": reSection},
  286. build: func(a map[string]string) (string, []string) {
  287. return "wg", []string{"show", a["interface"]}
  288. },
  289. configs: func(a map[string]string) []string { return nil },
  290. },
  291. }
  292. // tcpCheckBudget / tcpCheckRetry controlan los reintentos del Kind tcp_check.
  293. // Son vars de paquete (no const) para poder acortarlos en tests.
  294. var (
  295. tcpCheckBudget = 10 * time.Second
  296. tcpCheckRetry = 500 * time.Millisecond
  297. )
  298. // Executor aplica Ops allowlistedas con snapshot + healthcheck + rollback.
  299. type Executor struct {
  300. run Runner
  301. now func() time.Time
  302. gwTarget string // IP del gateway para healthcheck (APs)
  303. wanTarget string // IP WAN para healthcheck (gateway)
  304. }
  305. // New crea un ejecutor. gwTarget/wanTarget se usan para el healthcheck
  306. // post-apply (al menos uno debe estar configurado).
  307. func New(gwTarget, wanTarget string) *Executor {
  308. return &Executor{run: shellRunner{}, now: time.Now, gwTarget: gwTarget, wanTarget: wanTarget}
  309. }
  310. // SetRunner inyecta un runner fake (tests).
  311. func (e *Executor) SetRunner(r Runner) { e.run = r }
  312. // SetClock inyecta un reloj (tests).
  313. func (e *Executor) SetClock(f func() time.Time) { e.now = f }
  314. // Validate comprueba que una Op pasa el allowlist sin ejecutarla.
  315. func Validate(op Op) error {
  316. spec, ok := allowlist[op.Kind]
  317. if !ok {
  318. return fmt.Errorf("kind %q no allowlistedado", op.Kind)
  319. }
  320. for arg, re := range spec.required {
  321. val, present := op.Args[arg]
  322. if !present || val == "" {
  323. return fmt.Errorf("arg %q requerido para %s", arg, op.Kind)
  324. }
  325. if !re.MatchString(val) {
  326. return fmt.Errorf("arg %q=%q no válido para %s (no casa con %s)", arg, val, op.Kind, re)
  327. }
  328. }
  329. // Defense in depth: args marcados como path no pueden contener ".." ni
  330. // resolverse a algo distinto tras filepath.Clean (p. ej. "/etc/../x").
  331. for _, arg := range spec.pathArgs {
  332. val := op.Args[arg]
  333. if strings.Contains(val, "..") || filepath.Clean(val) != val {
  334. return fmt.Errorf("arg %q=%q contiene traversal (..) para %s", arg, val, op.Kind)
  335. }
  336. }
  337. return nil
  338. }
  339. // Apply ejecuta una lista de Ops con snapshot, commit y healthcheck.
  340. // Devuelve applied si todo OK, rolled_back si el healthcheck falla, o
  341. // failed si alguna Op falla antes del commit.
  342. func (e *Executor) Apply(ops []Op) ApplyResult {
  343. start := e.now()
  344. // 1. Validar todas las Ops antes de tocar nada.
  345. for _, op := range ops {
  346. if err := Validate(op); err != nil {
  347. return ApplyResult{Status: "failed", Op: op.Desc, Error: err.Error(), DurationMs: ms(e.now(), start)}
  348. }
  349. }
  350. // 2. Snapshot de los configs UCI afectados.
  351. affected := affectedConfigs(ops)
  352. snapshots := map[string]string{}
  353. for _, cfg := range affected {
  354. out, code := e.run.Run("uci", "export", cfg)
  355. if code == 0 && out != "" {
  356. snapshots[cfg] = out
  357. }
  358. }
  359. // 3. Ejecutar Ops (staged, sin commit aún).
  360. for _, op := range ops {
  361. spec := allowlist[op.Kind]
  362. var code int
  363. if spec.exec != nil {
  364. code = spec.exec(e.run, op.Args)
  365. } else {
  366. cmd, cmdArgs := spec.build(op.Args)
  367. _, code = e.run.Run(cmd, cmdArgs...)
  368. }
  369. if code != 0 {
  370. if op.Kind == "wg_check" {
  371. // Healthcheck del módulo WireGuard: el túnel no levantó tras el
  372. // apply. Rollback real: restaurar los snapshots UCI (uci import)
  373. // y relanzar la red con la config previa.
  374. for cfg, snap := range snapshots {
  375. e.run.Run("sh", "-c", fmt.Sprintf("echo '%s' | uci import", snap))
  376. e.run.Run("uci", "commit", cfg)
  377. }
  378. e.run.Run("/etc/init.d/network", "reload")
  379. return ApplyResult{Status: "rolled_back", Op: op.Desc, Error: "wg_check_failed", Snapshot: strings.Join(affected, ","), DurationMs: ms(e.now(), start)}
  380. }
  381. // Revert staged changes y salir.
  382. e.revertStaged(affected)
  383. return ApplyResult{Status: "failed", Op: op.Desc, Error: fmt.Sprintf("%s exit %d", op.Kind, code), DurationMs: ms(e.now(), start)}
  384. }
  385. }
  386. // 4. Commit de cada config afectado.
  387. for _, cfg := range affected {
  388. e.run.Run("uci", "commit", cfg)
  389. }
  390. // 5. Healthcheck.
  391. if !e.healthcheck() {
  392. // ROLLBACK: restaurar snapshots.
  393. for cfg, snap := range snapshots {
  394. e.run.Run("sh", "-c", fmt.Sprintf("echo '%s' | uci import", snap))
  395. e.run.Run("uci", "commit", cfg)
  396. }
  397. return ApplyResult{Status: "rolled_back", Error: "healthcheck_failed", Snapshot: strings.Join(affected, ","), DurationMs: ms(e.now(), start)}
  398. }
  399. return ApplyResult{Status: "applied", Snapshot: strings.Join(affected, ","), DurationMs: ms(e.now(), start)}
  400. }
  401. func (e *Executor) revertStaged(configs []string) {
  402. for _, cfg := range configs {
  403. e.run.Run("uci", "revert", cfg)
  404. }
  405. }
  406. func (e *Executor) healthcheck() bool {
  407. target := e.wanTarget
  408. if target == "" {
  409. target = e.gwTarget
  410. }
  411. if target == "" {
  412. return true // sin target configurado: pasar (mejor falso negativo que bloquear)
  413. }
  414. _, code := e.run.Run("ping", "-c", "1", "-W", "3", target)
  415. return code == 0
  416. }
  417. func affectedConfigs(ops []Op) []string {
  418. seen := map[string]bool{}
  419. var out []string
  420. for _, op := range ops {
  421. spec, ok := allowlist[op.Kind]
  422. if !ok {
  423. continue
  424. }
  425. for _, cfg := range spec.configs(op.Args) {
  426. if cfg != "" && !seen[cfg] {
  427. seen[cfg] = true
  428. out = append(out, cfg)
  429. }
  430. }
  431. }
  432. return out
  433. }
  434. func ms(now, start time.Time) int64 {
  435. return now.Sub(start).Milliseconds()
  436. }
  437. // MarshalOps serializa una lista de Ops a JSON (para enviar vía SSE).
  438. func MarshalOps(ops []Op) (string, error) {
  439. b, err := json.Marshal(ops)
  440. return string(b), err
  441. }
  442. // UnmarshalOps deserializa Ops desde JSON (en el agente, al recibir el SSE).
  443. func UnmarshalOps(data string) ([]Op, error) {
  444. var ops []Op
  445. err := json.Unmarshal([]byte(data), &ops)
  446. return ops, err
  447. }