device_actions.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. // device_actions.go — acciones directas sobre routers para un dispositivo
  2. // (issue #439): reserva DHCP estática en el gateway y bloqueo MAC en el router
  3. // de atache. Escriben /etc/config/dhcp y /etc/config/firewall vía SSH
  4. // (SSHRunner, fakeable en tests) usando uci, con `uci commit` como límite
  5. // atómico y rollback si el reinicio del servicio falla (sin config a medias).
  6. package httpapi
  7. import (
  8. "fmt"
  9. "log"
  10. "net"
  11. "net/http"
  12. "regexp"
  13. "strings"
  14. "time"
  15. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  16. )
  17. // Techos para los comandos uci sobre SSH (show = lectura, apply = escritura
  18. // + commit + reload). Son límites fijos del ejecutor, no configurables.
  19. const (
  20. uciShowTimeout = 10 * time.Second
  21. uciApplyTimeout = 20 * time.Second
  22. )
  23. var reUciLine = regexp.MustCompile(`^([a-z0-9_]+)\.([^=]+)=(.*)$`)
  24. var reUciQuoted = regexp.MustCompile(`^'(.*)'$`)
  25. // reDhcpHostname: hostname DNS (etiquetas alfanuméricas con guiones internos,
  26. // separadas por puntos). dnsmasq registra el `name` de la sección host en su
  27. // DNS local, así que cualquier otra cosa (espacios, acentos, metacaracteres)
  28. // no es un hostname válido y se rechaza (#693).
  29. var reDhcpHostname = regexp.MustCompile(`^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$`)
  30. // uciValue devuelve el valor sin comillas de una línea `cfg.sect.opt='val'`.
  31. func uciValue(raw string) string {
  32. if m := reUciQuoted.FindStringSubmatch(raw); m != nil {
  33. return m[1]
  34. }
  35. return raw
  36. }
  37. // uciQuote escapa v para incrustarlo sin riesgo entre comillas simples de un
  38. // comando uci: la única forma de salir de '...' es otra comilla simple, que se
  39. // neutraliza cerrando, escapándola con backslash y reabriendo (secuencia
  40. // POSIX clásica de cierre-escape-apertura). Sin esto, un hostname tipo
  41. // `x'; cmd; echo '` inyecta comandos que corren como root en el router vía
  42. // SSH (#693).
  43. func uciQuote(v string) string {
  44. return strings.ReplaceAll(v, "'", `'\''`)
  45. }
  46. // uciSetCmd construye `uci set <cfg>.<sect>.<opt>='<valor escapado>'`. Todo
  47. // valor dinámico de un comando uci pasa por aquí (#693).
  48. func uciSetCmd(cfg, sect, opt, value string) string {
  49. return fmt.Sprintf("uci set %s.%s.%s='%s'", cfg, sect, opt, uciQuote(value))
  50. }
  51. // validDHCPHostname acepta vacío (= no tocar el name; el alta usará la MAC) o
  52. // un hostname DNS de hasta 253 caracteres (#693).
  53. func validDHCPHostname(h string) bool {
  54. if h == "" {
  55. return true
  56. }
  57. if len(h) > 253 {
  58. return false
  59. }
  60. return reDhcpHostname.MatchString(h)
  61. }
  62. // gatewayHost devuelve el host SSH del gateway (router con is_gateway), o ""
  63. // si no hay gateway configurado o es agent-only. El gateway es quien sirve
  64. // DHCP (dnsmasq), así que es el target por defecto de las reservas de lease.
  65. func (s *server) gatewayHost() string {
  66. for _, r := range routerstore.ListRouters(s.db.DB) {
  67. if r.IsGateway && !r.AgentOnly && r.Host != "" {
  68. return r.SSHAddr()
  69. }
  70. }
  71. return ""
  72. }
  73. // leaseRouterResolver lo implementa el adapter live para decir qué router
  74. // reportó la MAC en su tabla de leases DHCP (issue #537). La demo no lo
  75. // implementa → la reserva cae al gateway, como antes.
  76. type leaseRouterResolver interface {
  77. RouterServingDHCP(mac string) string
  78. }
  79. // reservationTargetHost resuelve DÓNDE vive la reserva DHCP de un dispositivo
  80. // (issue #537): no siempre en el gateway global. Un dispositivo cuya IP la
  81. // concede un router con su propio dnsmasq (p. ej. una LAN separada tras un AP
  82. // con DHCP propio) debe reservarse en ESE router, que es quien reportó su
  83. // lease. Orden:
  84. // 1. Router que reportó la MAC en leases (RouterServingDHCP), si el adapter
  85. // lo soporta y el router es alcanzable por SSH.
  86. // 2. Fallback: el gateway (red gestionada clásica con un solo servidor DHCP).
  87. func (s *server) reservationTargetHost(mac string) string {
  88. if lr, ok := s.adapter.(leaseRouterResolver); ok {
  89. if routerID := lr.RouterServingDHCP(mac); routerID != "" {
  90. if host := s.hostOfRouter(routerID); host != "" {
  91. return host
  92. }
  93. }
  94. }
  95. return s.gatewayHost()
  96. }
  97. // uciShow ejecuta `uci show <config>` en un host y devuelve líneas parseables.
  98. func (s *server) uciShow(host, config string) ([]string, error) {
  99. if s.pool == nil {
  100. return nil, fmt.Errorf("no SSH pool")
  101. }
  102. out, err := s.pool.Run(host, fmt.Sprintf("uci show %s", config), uciShowTimeout)
  103. if err != nil {
  104. return nil, err
  105. }
  106. return strings.Split(out, "\n"), nil
  107. }
  108. // runUCICommands encadena comandos uci + `uci commit <config>` en UNA sesión
  109. // SSH. `uci commit` es el límite atómico: si un `uci set/delete` falla antes,
  110. // el `&&` corta y /etc/config queda intacto (staging descartado).
  111. func (s *server) runUCICommands(host, config string, commands []string) error {
  112. if s.pool == nil {
  113. return fmt.Errorf("no SSH pool")
  114. }
  115. script := strings.Join(append(commands, "uci commit "+config), " && ")
  116. _, err := s.pool.Run(host, script, uciApplyTimeout)
  117. return err
  118. }
  119. // reloadService reinicia el servicio procd que aplica la config commitada.
  120. func (s *server) reloadService(host, service string) error {
  121. if s.pool == nil {
  122. return fmt.Errorf("no SSH pool")
  123. }
  124. _, err := s.pool.Run(host, "/etc/init.d/"+service+" restart", uciApplyTimeout)
  125. return err
  126. }
  127. // ---------------------------------------------------------------------------
  128. // Reserva DHCP (host sections de /etc/config/dhcp)
  129. // ---------------------------------------------------------------------------
  130. // dhcpHost representa una sección host de dhcp UCI.
  131. type dhcpHost struct {
  132. Section string
  133. Name string
  134. MAC string
  135. IP string
  136. }
  137. // uciTypeSections devuelve el conjunto de secciones de un config cuya línea de
  138. // tipo (`cfg.<section>=<type>`) coincide con el tipo pedido.
  139. func uciTypeSections(lines []string, config, typ string) map[string]bool {
  140. sections := map[string]bool{}
  141. for _, raw := range lines {
  142. line := strings.TrimSpace(raw)
  143. m := reUciLine.FindStringSubmatch(line)
  144. if m == nil || m[1] != config {
  145. continue
  146. }
  147. if strings.Index(m[2], ".") >= 0 {
  148. continue // es una opción, no la línea de tipo
  149. }
  150. if uciValue(m[3]) == typ {
  151. sections[m[2]] = true
  152. }
  153. }
  154. return sections
  155. }
  156. // parseDhcpHosts parsea `uci show dhcp` y devuelve SOLO las secciones de tipo
  157. // host (named `dhcp.np_host_x=host` y anónimas `dhcp.@host[0]=host`), filtrando
  158. // el ruido de @dnsmasq[0], lan, wan, etc.
  159. func parseDhcpHosts(lines []string) []*dhcpHost {
  160. hostSections := uciTypeSections(lines, "dhcp", "host")
  161. var hosts []*dhcpHost
  162. bySection := map[string]*dhcpHost{}
  163. for _, raw := range lines {
  164. line := strings.TrimSpace(raw)
  165. if line == "" {
  166. continue
  167. }
  168. m := reUciLine.FindStringSubmatch(line)
  169. if m == nil || m[1] != "dhcp" {
  170. continue
  171. }
  172. dot := strings.Index(m[2], ".")
  173. if dot < 0 {
  174. continue
  175. }
  176. section, option := m[2][:dot], m[2][dot+1:]
  177. if !hostSections[section] {
  178. continue
  179. }
  180. h := bySection[section]
  181. if h == nil {
  182. h = &dhcpHost{Section: section}
  183. bySection[section] = h
  184. hosts = append(hosts, h)
  185. }
  186. switch option {
  187. case "name":
  188. h.Name = uciValue(m[3])
  189. case "mac":
  190. h.MAC = uciValue(m[3])
  191. case "ip":
  192. h.IP = uciValue(m[3])
  193. }
  194. }
  195. return hosts
  196. }
  197. // findDhcpHost busca una sección host cuya MAC coincida (sin importar el
  198. // formato; admite varias MACs separadas por coma/espacio en una misma sección).
  199. func findDhcpHost(hosts []*dhcpHost, mac string) *dhcpHost {
  200. macNorm := normalizeMAC(mac)
  201. for _, h := range hosts {
  202. for _, m := range strings.FieldsFunc(h.MAC, func(r rune) bool { return r == ',' || r == ' ' }) {
  203. if normalizeMAC(m) == macNorm {
  204. return h
  205. }
  206. }
  207. }
  208. return nil
  209. }
  210. // dhcpHostSection es el nombre de sección determinista para la reserva de una
  211. // MAC (uci set dhcp.np_host_<mac12>=host).
  212. func dhcpHostSection(mac string) string {
  213. return "np_host_" + strings.ReplaceAll(mac, ":", "")
  214. }
  215. // handleDeviceReservationGet devuelve la reserva DHCP estática de un dispositivo.
  216. func (s *server) handleDeviceReservationGet(w http.ResponseWriter, r *http.Request) {
  217. mac := normalizeMAC(r.PathValue("mac"))
  218. if len(mac) != 17 {
  219. writeError(w, http.StatusBadRequest, "invalid_mac")
  220. return
  221. }
  222. host := s.reservationTargetHost(mac)
  223. if host == "" {
  224. writeError(w, http.StatusBadRequest, "no_gateway")
  225. return
  226. }
  227. lines, err := s.uciShow(host, "dhcp")
  228. if err != nil {
  229. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  230. return
  231. }
  232. hosts := parseDhcpHosts(lines)
  233. if h := findDhcpHost(hosts, mac); h != nil {
  234. writeJSON(w, http.StatusOK, map[string]any{
  235. "reserved": true,
  236. "ip": h.IP,
  237. "name": h.Name,
  238. })
  239. return
  240. }
  241. writeJSON(w, http.StatusOK, map[string]any{"reserved": false})
  242. }
  243. // handleDeviceReservationPut crea o actualiza una reserva DHCP estática.
  244. // Idempotente (misma MAC+IP → no-op). Rechaza con 409 si OTRA MAC ya tiene
  245. // reservada la IP pedida.
  246. func (s *server) handleDeviceReservationPut(w http.ResponseWriter, r *http.Request) {
  247. mac := normalizeMAC(r.PathValue("mac"))
  248. if len(mac) != 17 {
  249. writeError(w, http.StatusBadRequest, "invalid_mac")
  250. return
  251. }
  252. var body struct {
  253. IP string `json:"ip"`
  254. Hostname string `json:"hostname"`
  255. }
  256. if st := readJSONBody(w, r, &body); st != 0 {
  257. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  258. return
  259. }
  260. if net.ParseIP(body.IP) == nil {
  261. writeError(w, http.StatusBadRequest, "invalid_ip")
  262. return
  263. }
  264. if !validDHCPHostname(body.Hostname) {
  265. writeError(w, http.StatusBadRequest, "invalid_hostname",
  266. "el hostname debe ser un nombre DNS válido (letras, dígitos, guiones y puntos)")
  267. return
  268. }
  269. host := s.reservationTargetHost(mac)
  270. if host == "" {
  271. writeError(w, http.StatusBadRequest, "no_gateway")
  272. return
  273. }
  274. lines, err := s.uciShow(host, "dhcp")
  275. if err != nil {
  276. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  277. return
  278. }
  279. hosts := parseDhcpHosts(lines)
  280. // Conflicto: otra MAC (distinta de ésta) ya tiene esa IP reservada.
  281. for _, h := range hosts {
  282. if h.IP != body.IP {
  283. continue
  284. }
  285. if findDhcpHost([]*dhcpHost{h}, mac) != nil {
  286. continue // es la sección de esta misma MAC (update idempotente)
  287. }
  288. writeError(w, http.StatusConflict, "ip_conflict",
  289. fmt.Sprintf("la IP %s ya está reservada para %s", body.IP, h.MAC))
  290. return
  291. }
  292. existing := findDhcpHost(hosts, mac)
  293. var apply, rollback []string
  294. if existing != nil {
  295. oldIP := existing.IP
  296. apply = append(apply, uciSetCmd("dhcp", existing.Section, "ip", body.IP))
  297. if body.Hostname != "" && body.Hostname != existing.Name {
  298. apply = append(apply, uciSetCmd("dhcp", existing.Section, "name", body.Hostname))
  299. }
  300. rollback = append(rollback, uciSetCmd("dhcp", existing.Section, "ip", oldIP))
  301. } else {
  302. section := dhcpHostSection(mac)
  303. name := body.Hostname
  304. if name == "" {
  305. name = mac
  306. }
  307. apply = append(apply,
  308. fmt.Sprintf("uci set dhcp.%s=host", section),
  309. uciSetCmd("dhcp", section, "name", name),
  310. uciSetCmd("dhcp", section, "mac", mac),
  311. uciSetCmd("dhcp", section, "ip", body.IP),
  312. )
  313. rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s", section))
  314. }
  315. // Dry-run (#754): devolver el plan sin ejecutar nada en el router.
  316. if r.URL.Query().Get("dry_run") == "1" {
  317. writeDevicePlan(w, mac, host, apply, rollback)
  318. return
  319. }
  320. if err := s.runUCICommands(host, "dhcp", apply); err != nil {
  321. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  322. return
  323. }
  324. if err := s.reloadService(host, "dnsmasq"); err != nil {
  325. if rbErr := s.runUCICommands(host, "dhcp", rollback); rbErr != nil {
  326. log.Printf("[netpulse] reservation rollback for %s failed: %v", mac, rbErr)
  327. }
  328. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  329. return
  330. }
  331. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac, "ip": body.IP})
  332. }
  333. // handleDeviceReservationHostnamePut aplica el nombre visible de NetPulse como
  334. // hostname de la reserva DHCP del dispositivo (#800): si la MAC ya tiene
  335. // reserva se actualiza solo el `name` (la IP no se toca); si no, se crea la
  336. // reserva con la IP actual del dispositivo. El hostname debe ser DNS válido y
  337. // NO vacío (#693): es el objetivo de la acción, no un opcional. La UI deriva
  338. // el hostname del nombre visible y deshabilita la acción si no es aplicable.
  339. func (s *server) handleDeviceReservationHostnamePut(w http.ResponseWriter, r *http.Request) {
  340. mac := normalizeMAC(r.PathValue("mac"))
  341. if len(mac) != 17 {
  342. writeError(w, http.StatusBadRequest, "invalid_mac")
  343. return
  344. }
  345. var body struct {
  346. IP string `json:"ip"`
  347. Hostname string `json:"hostname"`
  348. }
  349. if st := readJSONBody(w, r, &body); st != 0 {
  350. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  351. return
  352. }
  353. // A diferencia del PUT de reserva, aquí el hostname ES el objetivo de la
  354. // acción: vacío no significa "no tocar", significa petición sin sentido.
  355. if body.Hostname == "" || !validDHCPHostname(body.Hostname) {
  356. writeError(w, http.StatusBadRequest, "invalid_hostname",
  357. "el hostname debe ser un nombre DNS válido (letras, dígitos, guiones y puntos)")
  358. return
  359. }
  360. if net.ParseIP(body.IP) == nil {
  361. writeError(w, http.StatusBadRequest, "invalid_ip")
  362. return
  363. }
  364. host := s.reservationTargetHost(mac)
  365. if host == "" {
  366. writeError(w, http.StatusBadRequest, "no_gateway")
  367. return
  368. }
  369. lines, err := s.uciShow(host, "dhcp")
  370. if err != nil {
  371. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  372. return
  373. }
  374. hosts := parseDhcpHosts(lines)
  375. // Conflicto: otra MAC (distinta de ésta) ya tiene esa IP reservada.
  376. for _, h := range hosts {
  377. if h.IP != body.IP {
  378. continue
  379. }
  380. if findDhcpHost([]*dhcpHost{h}, mac) != nil {
  381. continue // es la sección de esta misma MAC
  382. }
  383. writeError(w, http.StatusConflict, "ip_conflict",
  384. fmt.Sprintf("la IP %s ya está reservada para %s", body.IP, h.MAC))
  385. return
  386. }
  387. existing := findDhcpHost(hosts, mac)
  388. var apply, rollback []string
  389. created := false
  390. if existing != nil {
  391. if existing.Name == body.Hostname {
  392. // No-op idempotente: el router ya tiene exactamente ese hostname.
  393. writeJSON(w, http.StatusOK, map[string]any{
  394. "ok": true, "mac": mac, "ip": existing.IP, "noop": true,
  395. })
  396. return
  397. }
  398. apply = append(apply, uciSetCmd("dhcp", existing.Section, "name", body.Hostname))
  399. if existing.Name != "" {
  400. rollback = append(rollback, uciSetCmd("dhcp", existing.Section, "name", existing.Name))
  401. } else {
  402. rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s.name", existing.Section))
  403. }
  404. } else {
  405. created = true
  406. section := dhcpHostSection(mac)
  407. apply = append(apply,
  408. fmt.Sprintf("uci set dhcp.%s=host", section),
  409. uciSetCmd("dhcp", section, "name", body.Hostname),
  410. uciSetCmd("dhcp", section, "mac", mac),
  411. uciSetCmd("dhcp", section, "ip", body.IP),
  412. )
  413. rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s", section))
  414. }
  415. // Dry-run (#754): devolver el plan sin ejecutar nada en el router.
  416. if r.URL.Query().Get("dry_run") == "1" {
  417. writeDevicePlan(w, mac, host, apply, rollback)
  418. return
  419. }
  420. if err := s.runUCICommands(host, "dhcp", apply); err != nil {
  421. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  422. return
  423. }
  424. if err := s.reloadService(host, "dnsmasq"); err != nil {
  425. if rbErr := s.runUCICommands(host, "dhcp", rollback); rbErr != nil {
  426. log.Printf("[netpulse] hostname reservation rollback for %s failed: %v", mac, rbErr)
  427. }
  428. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  429. return
  430. }
  431. writeJSON(w, http.StatusOK, map[string]any{
  432. "ok": true, "mac": mac, "ip": body.IP, "created": created,
  433. })
  434. }
  435. // writeDevicePlan responde un dry-run (#754): comandos que SE EJECUTARÍAN
  436. // (apply) y su plan de vuelta (rollback), sin tocar el router.
  437. func writeDevicePlan(w http.ResponseWriter, mac, host string, apply, rollback []string) {
  438. writeJSON(w, http.StatusOK, map[string]any{
  439. "ok": true,
  440. "dryRun": true,
  441. "mac": mac,
  442. "host": host,
  443. "apply": apply,
  444. "rollback": rollback,
  445. })
  446. }
  447. // handleDeviceReservationDelete elimina la reserva DHCP estática.
  448. func (s *server) handleDeviceReservationDelete(w http.ResponseWriter, r *http.Request) {
  449. mac := normalizeMAC(r.PathValue("mac"))
  450. if len(mac) != 17 {
  451. writeError(w, http.StatusBadRequest, "invalid_mac")
  452. return
  453. }
  454. host := s.reservationTargetHost(mac)
  455. if host == "" {
  456. writeError(w, http.StatusBadRequest, "no_gateway")
  457. return
  458. }
  459. lines, err := s.uciShow(host, "dhcp")
  460. if err != nil {
  461. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  462. return
  463. }
  464. hosts := parseDhcpHosts(lines)
  465. h := findDhcpHost(hosts, mac)
  466. if h == nil {
  467. writeError(w, http.StatusNotFound, "not_reserved")
  468. return
  469. }
  470. // Rollback = re-crear la sección tal cual estaba (si el reload falla).
  471. var rollback []string
  472. rollback = append(rollback, fmt.Sprintf("uci set dhcp.%s=host", h.Section))
  473. if h.Name != "" {
  474. rollback = append(rollback, uciSetCmd("dhcp", h.Section, "name", h.Name))
  475. }
  476. if h.MAC != "" {
  477. rollback = append(rollback, uciSetCmd("dhcp", h.Section, "mac", h.MAC))
  478. }
  479. if h.IP != "" {
  480. rollback = append(rollback, uciSetCmd("dhcp", h.Section, "ip", h.IP))
  481. }
  482. apply := []string{fmt.Sprintf("uci delete dhcp.%s", h.Section)}
  483. if err := s.runUCICommands(host, "dhcp", apply); err != nil {
  484. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  485. return
  486. }
  487. if err := s.reloadService(host, "dnsmasq"); err != nil {
  488. if rbErr := s.runUCICommands(host, "dhcp", rollback); rbErr != nil {
  489. log.Printf("[netpulse] reservation deletion rollback for %s failed: %v", mac, rbErr)
  490. }
  491. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  492. return
  493. }
  494. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac})
  495. }
  496. // ---------------------------------------------------------------------------
  497. // Bloqueo de dispositivo (rule de /etc/config/firewall, fw4)
  498. // ---------------------------------------------------------------------------
  499. // firewallRule representa una sección rule de firewall UCI.
  500. type firewallRule struct {
  501. Section string
  502. Name string
  503. SrcMAC string
  504. Target string
  505. }
  506. // parseFirewallRules parsea `uci show firewall` y devuelve las reglas (named
  507. // `firewall.np_block_x=rule` y anónimas `firewall.@rule[0]=rule`).
  508. func parseFirewallRules(lines []string) []*firewallRule {
  509. ruleSections := uciTypeSections(lines, "firewall", "rule")
  510. var rules []*firewallRule
  511. bySection := map[string]*firewallRule{}
  512. for _, raw := range lines {
  513. line := strings.TrimSpace(raw)
  514. if line == "" {
  515. continue
  516. }
  517. m := reUciLine.FindStringSubmatch(line)
  518. if m == nil || m[1] != "firewall" {
  519. continue
  520. }
  521. dot := strings.Index(m[2], ".")
  522. if dot < 0 {
  523. continue
  524. }
  525. section, option := m[2][:dot], m[2][dot+1:]
  526. if !ruleSections[section] {
  527. continue
  528. }
  529. r := bySection[section]
  530. if r == nil {
  531. r = &firewallRule{Section: section}
  532. bySection[section] = r
  533. rules = append(rules, r)
  534. }
  535. switch option {
  536. case "name":
  537. r.Name = uciValue(m[3])
  538. case "src_mac":
  539. r.SrcMAC = uciValue(m[3])
  540. case "target":
  541. r.Target = uciValue(m[3])
  542. }
  543. }
  544. return rules
  545. }
  546. // blockRuleSection es el nombre de sección determinista para el bloqueo de una
  547. // MAC (uci set firewall.np_block_<mac12>=rule).
  548. func blockRuleSection(mac string) string {
  549. return "np_block_" + strings.ReplaceAll(mac, ":", "")
  550. }
  551. // blockRuleName es el nombre legible de la regla (mostrado en LuCI).
  552. func blockRuleName(mac string) string {
  553. return "np-block-" + strings.ReplaceAll(mac, ":", "")
  554. }
  555. // findBlockRule busca la regla de bloqueo de una MAC: por sección determinista
  556. // o por nombre legado (reglas anónimas `@rule[N]` con name='np-block-<mac>').
  557. func findBlockRule(rules []*firewallRule, mac string) *firewallRule {
  558. section := blockRuleSection(mac)
  559. name := blockRuleName(mac)
  560. for _, r := range rules {
  561. if r.Section == section || r.Name == name {
  562. return r
  563. }
  564. }
  565. return nil
  566. }
  567. // blockRuleApply/blockRuleRollback construyen los comandos uci de la regla
  568. // fw4. Forma mínima correcta (drop de tráfico reenviado desde la MAC, sin
  569. // romper su lease DHCP, que es input al router): src=lan, dest=*, target=DROP,
  570. // src_mac=<mac>.
  571. func blockRuleApply(section, mac string) []string {
  572. return []string{
  573. fmt.Sprintf("uci set firewall.%s=rule", section),
  574. uciSetCmd("firewall", section, "name", blockRuleName(mac)),
  575. fmt.Sprintf("uci set firewall.%s.src='lan'", section),
  576. fmt.Sprintf("uci set firewall.%s.dest='*'", section),
  577. fmt.Sprintf("uci set firewall.%s.target='DROP'", section),
  578. uciSetCmd("firewall", section, "src_mac", mac),
  579. }
  580. }
  581. func blockRuleRollback(section string) []string {
  582. return []string{fmt.Sprintf("uci delete firewall.%s", section)}
  583. }
  584. // handleDeviceBlockGet indica si un dispositivo está bloqueado.
  585. func (s *server) handleDeviceBlockGet(w http.ResponseWriter, r *http.Request) {
  586. mac := normalizeMAC(r.PathValue("mac"))
  587. if len(mac) != 17 {
  588. writeError(w, http.StatusBadRequest, "invalid_mac")
  589. return
  590. }
  591. routerID := r.URL.Query().Get("router")
  592. if routerID == "" {
  593. writeError(w, http.StatusBadRequest, "missing_router")
  594. return
  595. }
  596. host := s.hostOfRouter(routerID)
  597. if host == "" {
  598. writeError(w, http.StatusBadRequest, "no_router")
  599. return
  600. }
  601. lines, err := s.uciShow(host, "firewall")
  602. if err != nil {
  603. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  604. return
  605. }
  606. rules := parseFirewallRules(lines)
  607. blocked := findBlockRule(rules, mac) != nil
  608. writeJSON(w, http.StatusOK, map[string]any{"blocked": blocked})
  609. }
  610. // handleDeviceBlockPut bloquea un dispositivo añadiendo una regla de firewall.
  611. func (s *server) handleDeviceBlockPut(w http.ResponseWriter, r *http.Request) {
  612. mac := normalizeMAC(r.PathValue("mac"))
  613. if len(mac) != 17 {
  614. writeError(w, http.StatusBadRequest, "invalid_mac")
  615. return
  616. }
  617. var body struct {
  618. RouterID string `json:"router"`
  619. }
  620. if st := readJSONBody(w, r, &body); st != 0 {
  621. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  622. return
  623. }
  624. if body.RouterID == "" {
  625. writeError(w, http.StatusBadRequest, "missing_router")
  626. return
  627. }
  628. host := s.hostOfRouter(body.RouterID)
  629. if host == "" {
  630. writeError(w, http.StatusBadRequest, "no_router")
  631. return
  632. }
  633. lines, err := s.uciShow(host, "firewall")
  634. if err != nil {
  635. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  636. return
  637. }
  638. rules := parseFirewallRules(lines)
  639. if findBlockRule(rules, mac) != nil {
  640. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac, "already": true})
  641. return
  642. }
  643. section := blockRuleSection(mac)
  644. // Dry-run (#754): plan sin ejecutar (el check de "ya bloqueado" sí corre:
  645. // es lectura uci show, no escribe nada).
  646. if r.URL.Query().Get("dry_run") == "1" {
  647. writeDevicePlan(w, mac, host, blockRuleApply(section, mac), blockRuleRollback(section))
  648. return
  649. }
  650. if err := s.runUCICommands(host, "firewall", blockRuleApply(section, mac)); err != nil {
  651. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  652. return
  653. }
  654. if err := s.reloadService(host, "firewall"); err != nil {
  655. if rbErr := s.runUCICommands(host, "firewall", blockRuleRollback(section)); rbErr != nil {
  656. log.Printf("[netpulse] block rollback for %s failed: %v", mac, rbErr)
  657. }
  658. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  659. return
  660. }
  661. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac})
  662. }
  663. // handleDeviceBlockDelete desbloquea un dispositivo.
  664. func (s *server) handleDeviceBlockDelete(w http.ResponseWriter, r *http.Request) {
  665. mac := normalizeMAC(r.PathValue("mac"))
  666. if len(mac) != 17 {
  667. writeError(w, http.StatusBadRequest, "invalid_mac")
  668. return
  669. }
  670. var body struct {
  671. RouterID string `json:"router"`
  672. }
  673. if st := readJSONBody(w, r, &body); st != 0 {
  674. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  675. return
  676. }
  677. if body.RouterID == "" {
  678. writeError(w, http.StatusBadRequest, "missing_router")
  679. return
  680. }
  681. host := s.hostOfRouter(body.RouterID)
  682. if host == "" {
  683. writeError(w, http.StatusBadRequest, "no_router")
  684. return
  685. }
  686. lines, err := s.uciShow(host, "firewall")
  687. if err != nil {
  688. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  689. return
  690. }
  691. rules := parseFirewallRules(lines)
  692. br := findBlockRule(rules, mac)
  693. if br == nil {
  694. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac, "already": true})
  695. return
  696. }
  697. apply := []string{fmt.Sprintf("uci delete firewall.%s", br.Section)}
  698. rollback := []string{fmt.Sprintf("uci set firewall.%s=rule", br.Section)}
  699. if br.Name != "" {
  700. rollback = append(rollback, uciSetCmd("firewall", br.Section, "name", br.Name))
  701. }
  702. if br.SrcMAC != "" {
  703. rollback = append(rollback, uciSetCmd("firewall", br.Section, "src_mac", br.SrcMAC))
  704. }
  705. if br.Target != "" {
  706. rollback = append(rollback, uciSetCmd("firewall", br.Section, "target", br.Target))
  707. }
  708. if err := s.runUCICommands(host, "firewall", apply); err != nil {
  709. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  710. return
  711. }
  712. if err := s.reloadService(host, "firewall"); err != nil {
  713. if rbErr := s.runUCICommands(host, "firewall", rollback); rbErr != nil {
  714. log.Printf("[netpulse] unblock rollback for %s failed: %v", mac, rbErr)
  715. }
  716. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  717. return
  718. }
  719. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac})
  720. }