executor.go 17 KB

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