device_actions.go 26 KB

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