| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792 |
- // device_actions.go — acciones directas sobre routers para un dispositivo
- // (issue #439): reserva DHCP estática en el gateway y bloqueo MAC en el router
- // de atache. Escriben /etc/config/dhcp y /etc/config/firewall vía SSH
- // (SSHRunner, fakeable en tests) usando uci, con `uci commit` como límite
- // atómico y rollback si el reinicio del servicio falla (sin config a medias).
- package httpapi
- import (
- "fmt"
- "log"
- "net"
- "net/http"
- "regexp"
- "strings"
- "time"
- "github.com/gnacho/netpulse/agent/macaddr"
- "github.com/gnacho/netpulse/server-go/internal/routerstore"
- )
- // Techos para los comandos uci sobre SSH (show = lectura, apply = escritura
- // + commit + reload). Son límites fijos del ejecutor, no configurables.
- const (
- uciShowTimeout = 10 * time.Second
- uciApplyTimeout = 20 * time.Second
- )
- var reUciLine = regexp.MustCompile(`^([a-z0-9_]+)\.([^=]+)=(.*)$`)
- var reUciQuoted = regexp.MustCompile(`^'(.*)'$`)
- // reDhcpHostname: hostname DNS (etiquetas alfanuméricas con guiones internos,
- // separadas por puntos). dnsmasq registra el `name` de la sección host en su
- // DNS local, así que cualquier otra cosa (espacios, acentos, metacaracteres)
- // no es un hostname válido y se rechaza (#693).
- 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])?)*$`)
- // uciValue devuelve el valor sin comillas de una línea `cfg.sect.opt='val'`.
- func uciValue(raw string) string {
- if m := reUciQuoted.FindStringSubmatch(raw); m != nil {
- return m[1]
- }
- return raw
- }
- // uciQuote escapa v para incrustarlo sin riesgo entre comillas simples de un
- // comando uci: la única forma de salir de '...' es otra comilla simple, que se
- // neutraliza cerrando, escapándola con backslash y reabriendo (secuencia
- // POSIX clásica de cierre-escape-apertura). Sin esto, un hostname tipo
- // `x'; cmd; echo '` inyecta comandos que corren como root en el router vía
- // SSH (#693).
- func uciQuote(v string) string {
- return strings.ReplaceAll(v, "'", `'\''`)
- }
- // uciSetCmd construye `uci set <cfg>.<sect>.<opt>='<valor escapado>'`. Todo
- // valor dinámico de un comando uci pasa por aquí (#693).
- func uciSetCmd(cfg, sect, opt, value string) string {
- return fmt.Sprintf("uci set %s.%s.%s='%s'", cfg, sect, opt, uciQuote(value))
- }
- // validDHCPHostname acepta vacío (= no tocar el name; el alta usará la MAC) o
- // un hostname DNS de hasta 253 caracteres (#693).
- func validDHCPHostname(h string) bool {
- if h == "" {
- return true
- }
- if len(h) > 253 {
- return false
- }
- return reDhcpHostname.MatchString(h)
- }
- // gatewayHost devuelve el host SSH del gateway (router con is_gateway), o ""
- // si no hay gateway configurado o es agent-only. El gateway es quien sirve
- // DHCP (dnsmasq), así que es el target por defecto de las reservas de lease.
- func (s *server) gatewayHost() string {
- for _, r := range routerstore.ListRouters(s.db.DB) {
- if r.IsGateway && !r.AgentOnly && r.Host != "" {
- return r.SSHAddr()
- }
- }
- return ""
- }
- // leaseRouterResolver lo implementa el adapter live para decir qué router
- // reportó la MAC en su tabla de leases DHCP (issue #537). La demo no lo
- // implementa → la reserva cae al gateway, como antes.
- type leaseRouterResolver interface {
- RouterServingDHCP(mac string) string
- }
- // reservationTargetHost resuelve DÓNDE vive la reserva DHCP de un dispositivo
- // (issue #537): no siempre en el gateway global. Un dispositivo cuya IP la
- // concede un router con su propio dnsmasq (p. ej. una LAN separada tras un AP
- // con DHCP propio) debe reservarse en ESE router, que es quien reportó su
- // lease. Orden:
- // 1. Router que reportó la MAC en leases (RouterServingDHCP), si el adapter
- // lo soporta y el router es alcanzable por SSH.
- // 2. Fallback: el gateway (red gestionada clásica con un solo servidor DHCP).
- func (s *server) reservationTargetHost(mac string) string {
- if lr, ok := s.adapter.(leaseRouterResolver); ok {
- if routerID := lr.RouterServingDHCP(mac); routerID != "" {
- if host := s.hostOfRouter(routerID); host != "" {
- return host
- }
- }
- }
- return s.gatewayHost()
- }
- // uciShow ejecuta `uci show <config>` en un host y devuelve líneas parseables.
- func (s *server) uciShow(host, config string) ([]string, error) {
- if s.pool == nil {
- return nil, fmt.Errorf("no SSH pool")
- }
- out, err := s.pool.Run(host, fmt.Sprintf("uci show %s", config), uciShowTimeout)
- if err != nil {
- return nil, err
- }
- return strings.Split(out, "\n"), nil
- }
- // runUCICommands encadena comandos uci + `uci commit <config>` en UNA sesión
- // SSH. `uci commit` es el límite atómico: si un `uci set/delete` falla antes,
- // el `&&` corta y /etc/config queda intacto (staging descartado).
- func (s *server) runUCICommands(host, config string, commands []string) error {
- if s.pool == nil {
- return fmt.Errorf("no SSH pool")
- }
- script := strings.Join(append(commands, "uci commit "+config), " && ")
- _, err := s.pool.Run(host, script, uciApplyTimeout)
- return err
- }
- // reloadService reinicia el servicio procd que aplica la config commitada.
- func (s *server) reloadService(host, service string) error {
- if s.pool == nil {
- return fmt.Errorf("no SSH pool")
- }
- _, err := s.pool.Run(host, "/etc/init.d/"+service+" restart", uciApplyTimeout)
- return err
- }
- // ---------------------------------------------------------------------------
- // Reserva DHCP (host sections de /etc/config/dhcp)
- // ---------------------------------------------------------------------------
- // dhcpHost representa una sección host de dhcp UCI.
- type dhcpHost struct {
- Section string
- Name string
- MAC string
- IP string
- }
- // uciTypeSections devuelve el conjunto de secciones de un config cuya línea de
- // tipo (`cfg.<section>=<type>`) coincide con el tipo pedido.
- func uciTypeSections(lines []string, config, typ string) map[string]bool {
- sections := map[string]bool{}
- for _, raw := range lines {
- line := strings.TrimSpace(raw)
- m := reUciLine.FindStringSubmatch(line)
- if m == nil || m[1] != config {
- continue
- }
- if strings.Index(m[2], ".") >= 0 {
- continue // es una opción, no la línea de tipo
- }
- if uciValue(m[3]) == typ {
- sections[m[2]] = true
- }
- }
- return sections
- }
- // parseDhcpHosts parsea `uci show dhcp` y devuelve SOLO las secciones de tipo
- // host (named `dhcp.np_host_x=host` y anónimas `dhcp.@host[0]=host`), filtrando
- // el ruido de @dnsmasq[0], lan, wan, etc.
- func parseDhcpHosts(lines []string) []*dhcpHost {
- hostSections := uciTypeSections(lines, "dhcp", "host")
- var hosts []*dhcpHost
- bySection := map[string]*dhcpHost{}
- for _, raw := range lines {
- line := strings.TrimSpace(raw)
- if line == "" {
- continue
- }
- m := reUciLine.FindStringSubmatch(line)
- if m == nil || m[1] != "dhcp" {
- continue
- }
- dot := strings.Index(m[2], ".")
- if dot < 0 {
- continue
- }
- section, option := m[2][:dot], m[2][dot+1:]
- if !hostSections[section] {
- continue
- }
- h := bySection[section]
- if h == nil {
- h = &dhcpHost{Section: section}
- bySection[section] = h
- hosts = append(hosts, h)
- }
- switch option {
- case "name":
- h.Name = uciValue(m[3])
- case "mac":
- h.MAC = uciValue(m[3])
- case "ip":
- h.IP = uciValue(m[3])
- }
- }
- return hosts
- }
- // uciMAC es la forma de una MAC canónica en el router: las secciones, nombres
- // y opciones UCI que escribe netpulse van en minúsculas, y así casan las reglas
- // ya existentes.
- func uciMAC(mac string) string {
- return strings.ToLower(mac)
- }
- // findDhcpHost busca una sección host cuya MAC coincida (sin importar el
- // formato; admite varias MACs separadas por coma/espacio en una misma sección).
- // Una `list mac` sale de `uci show` como 'aa:…' 'bb:…' y uciValue solo quita
- // las comillas de fuera, así que también se corta por las comillas.
- func findDhcpHost(hosts []*dhcpHost, mac string) *dhcpHost {
- macNorm := macaddr.Normalize(mac)
- if macNorm == "" {
- return nil
- }
- for _, h := range hosts {
- for _, m := range strings.FieldsFunc(h.MAC, func(r rune) bool { return r == ',' || r == ' ' || r == '\'' || r == '"' }) {
- if macaddr.Normalize(m) == macNorm {
- return h
- }
- }
- }
- return nil
- }
- // dhcpHostSection es el nombre de sección determinista para la reserva de una
- // MAC (uci set dhcp.np_host_<mac12>=host).
- func dhcpHostSection(mac string) string {
- return "np_host_" + strings.ReplaceAll(uciMAC(mac), ":", "")
- }
- // handleDeviceReservationGet devuelve la reserva DHCP estática de un dispositivo.
- func (s *server) handleDeviceReservationGet(w http.ResponseWriter, r *http.Request) {
- mac := macaddr.Normalize(r.PathValue("mac"))
- if mac == "" {
- writeError(w, http.StatusBadRequest, "invalid_mac")
- return
- }
- host := s.reservationTargetHost(mac)
- if host == "" {
- writeError(w, http.StatusBadRequest, "no_gateway")
- return
- }
- lines, err := s.uciShow(host, "dhcp")
- if err != nil {
- writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
- return
- }
- hosts := parseDhcpHosts(lines)
- if h := findDhcpHost(hosts, mac); h != nil {
- writeJSON(w, http.StatusOK, map[string]any{
- "reserved": true,
- "ip": h.IP,
- "name": h.Name,
- })
- return
- }
- writeJSON(w, http.StatusOK, map[string]any{"reserved": false})
- }
- // handleDeviceReservationPut crea o actualiza una reserva DHCP estática.
- // Idempotente (misma MAC+IP → no-op). Rechaza con 409 si OTRA MAC ya tiene
- // reservada la IP pedida.
- func (s *server) handleDeviceReservationPut(w http.ResponseWriter, r *http.Request) {
- // #2112: uci show + commit + restart del servicio en la unidad antes de responder.
- setLongWriteDeadline(w, deviceActionWriteCeiling)
- mac := macaddr.Normalize(r.PathValue("mac"))
- if mac == "" {
- writeError(w, http.StatusBadRequest, "invalid_mac")
- return
- }
- var body struct {
- IP string `json:"ip"`
- Hostname string `json:"hostname"`
- }
- if st := readJSONBody(w, r, &body); st != 0 {
- writeBodyError(w, st, "invalid_body", "body JSON inválido")
- return
- }
- if net.ParseIP(body.IP) == nil {
- writeError(w, http.StatusBadRequest, "invalid_ip")
- return
- }
- if !validDHCPHostname(body.Hostname) {
- writeError(w, http.StatusBadRequest, "invalid_hostname",
- "el hostname debe ser un nombre DNS válido (letras, dígitos, guiones y puntos)")
- return
- }
- host := s.reservationTargetHost(mac)
- if host == "" {
- writeError(w, http.StatusBadRequest, "no_gateway")
- return
- }
- lines, err := s.uciShow(host, "dhcp")
- if err != nil {
- writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
- return
- }
- hosts := parseDhcpHosts(lines)
- // Conflicto: otra MAC (distinta de ésta) ya tiene esa IP reservada.
- for _, h := range hosts {
- if h.IP != body.IP {
- continue
- }
- if findDhcpHost([]*dhcpHost{h}, mac) != nil {
- continue // es la sección de esta misma MAC (update idempotente)
- }
- writeError(w, http.StatusConflict, "ip_conflict",
- fmt.Sprintf("la IP %s ya está reservada para %s", body.IP, h.MAC))
- return
- }
- existing := findDhcpHost(hosts, mac)
- var apply, rollback []string
- if existing != nil {
- oldIP := existing.IP
- apply = append(apply, uciSetCmd("dhcp", existing.Section, "ip", body.IP))
- if body.Hostname != "" && body.Hostname != existing.Name {
- apply = append(apply, uciSetCmd("dhcp", existing.Section, "name", body.Hostname))
- }
- rollback = append(rollback, uciSetCmd("dhcp", existing.Section, "ip", oldIP))
- } else {
- section := dhcpHostSection(mac)
- name := body.Hostname
- if name == "" {
- name = uciMAC(mac)
- }
- apply = append(apply,
- fmt.Sprintf("uci set dhcp.%s=host", section),
- uciSetCmd("dhcp", section, "name", name),
- uciSetCmd("dhcp", section, "mac", uciMAC(mac)),
- uciSetCmd("dhcp", section, "ip", body.IP),
- )
- rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s", section))
- }
- // Dry-run (#754): devolver el plan sin ejecutar nada en el router.
- if r.URL.Query().Get("dry_run") == "1" {
- writeDevicePlan(w, mac, host, apply, rollback)
- return
- }
- if err := s.runUCICommands(host, "dhcp", apply); err != nil {
- writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
- return
- }
- if err := s.reloadService(host, "dnsmasq"); err != nil {
- if rbErr := s.runUCICommands(host, "dhcp", rollback); rbErr != nil {
- log.Printf("[netpulse] reservation rollback for %s failed: %v", mac, rbErr)
- }
- writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
- return
- }
- writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac, "ip": body.IP})
- }
- // handleDeviceReservationHostnamePut aplica el nombre visible de NetPulse como
- // hostname de la reserva DHCP del dispositivo (#800): si la MAC ya tiene
- // reserva se actualiza solo el `name` (la IP no se toca); si no, se crea la
- // reserva con la IP actual del dispositivo. El hostname debe ser DNS válido y
- // NO vacío (#693): es el objetivo de la acción, no un opcional. La UI deriva
- // el hostname del nombre visible y deshabilita la acción si no es aplicable.
- func (s *server) handleDeviceReservationHostnamePut(w http.ResponseWriter, r *http.Request) {
- // #2112: uci show + commit + restart del servicio en la unidad antes de responder.
- setLongWriteDeadline(w, deviceActionWriteCeiling)
- mac := macaddr.Normalize(r.PathValue("mac"))
- if mac == "" {
- writeError(w, http.StatusBadRequest, "invalid_mac")
- return
- }
- var body struct {
- IP string `json:"ip"`
- Hostname string `json:"hostname"`
- }
- if st := readJSONBody(w, r, &body); st != 0 {
- writeBodyError(w, st, "invalid_body", "body JSON inválido")
- return
- }
- // A diferencia del PUT de reserva, aquí el hostname ES el objetivo de la
- // acción: vacío no significa "no tocar", significa petición sin sentido.
- if body.Hostname == "" || !validDHCPHostname(body.Hostname) {
- writeError(w, http.StatusBadRequest, "invalid_hostname",
- "el hostname debe ser un nombre DNS válido (letras, dígitos, guiones y puntos)")
- return
- }
- if net.ParseIP(body.IP) == nil {
- writeError(w, http.StatusBadRequest, "invalid_ip")
- return
- }
- host := s.reservationTargetHost(mac)
- if host == "" {
- writeError(w, http.StatusBadRequest, "no_gateway")
- return
- }
- lines, err := s.uciShow(host, "dhcp")
- if err != nil {
- writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
- return
- }
- hosts := parseDhcpHosts(lines)
- // Conflicto: otra MAC (distinta de ésta) ya tiene esa IP reservada.
- for _, h := range hosts {
- if h.IP != body.IP {
- continue
- }
- if findDhcpHost([]*dhcpHost{h}, mac) != nil {
- continue // es la sección de esta misma MAC
- }
- writeError(w, http.StatusConflict, "ip_conflict",
- fmt.Sprintf("la IP %s ya está reservada para %s", body.IP, h.MAC))
- return
- }
- existing := findDhcpHost(hosts, mac)
- var apply, rollback []string
- created := false
- if existing != nil {
- if existing.Name == body.Hostname {
- // No-op idempotente: el router ya tiene exactamente ese hostname.
- writeJSON(w, http.StatusOK, map[string]any{
- "ok": true, "mac": mac, "ip": existing.IP, "noop": true,
- })
- return
- }
- apply = append(apply, uciSetCmd("dhcp", existing.Section, "name", body.Hostname))
- if existing.Name != "" {
- rollback = append(rollback, uciSetCmd("dhcp", existing.Section, "name", existing.Name))
- } else {
- rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s.name", existing.Section))
- }
- } else {
- created = true
- section := dhcpHostSection(mac)
- apply = append(apply,
- fmt.Sprintf("uci set dhcp.%s=host", section),
- uciSetCmd("dhcp", section, "name", body.Hostname),
- uciSetCmd("dhcp", section, "mac", uciMAC(mac)),
- uciSetCmd("dhcp", section, "ip", body.IP),
- )
- rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s", section))
- }
- // Dry-run (#754): devolver el plan sin ejecutar nada en el router.
- if r.URL.Query().Get("dry_run") == "1" {
- writeDevicePlan(w, mac, host, apply, rollback)
- return
- }
- if err := s.runUCICommands(host, "dhcp", apply); err != nil {
- writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
- return
- }
- if err := s.reloadService(host, "dnsmasq"); err != nil {
- if rbErr := s.runUCICommands(host, "dhcp", rollback); rbErr != nil {
- log.Printf("[netpulse] hostname reservation rollback for %s failed: %v", mac, rbErr)
- }
- writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
- return
- }
- writeJSON(w, http.StatusOK, map[string]any{
- "ok": true, "mac": mac, "ip": body.IP, "created": created,
- })
- }
- // writeDevicePlan responde un dry-run (#754): comandos que SE EJECUTARÍAN
- // (apply) y su plan de vuelta (rollback), sin tocar el router.
- func writeDevicePlan(w http.ResponseWriter, mac, host string, apply, rollback []string) {
- writeJSON(w, http.StatusOK, map[string]any{
- "ok": true,
- "dryRun": true,
- "mac": mac,
- "host": host,
- "apply": apply,
- "rollback": rollback,
- })
- }
- // handleDeviceReservationDelete elimina la reserva DHCP estática.
- func (s *server) handleDeviceReservationDelete(w http.ResponseWriter, r *http.Request) {
- // #2112: uci show + commit + restart del servicio en la unidad antes de responder.
- setLongWriteDeadline(w, deviceActionWriteCeiling)
- mac := macaddr.Normalize(r.PathValue("mac"))
- if mac == "" {
- writeError(w, http.StatusBadRequest, "invalid_mac")
- return
- }
- host := s.reservationTargetHost(mac)
- if host == "" {
- writeError(w, http.StatusBadRequest, "no_gateway")
- return
- }
- lines, err := s.uciShow(host, "dhcp")
- if err != nil {
- writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
- return
- }
- hosts := parseDhcpHosts(lines)
- h := findDhcpHost(hosts, mac)
- if h == nil {
- writeError(w, http.StatusNotFound, "not_reserved")
- return
- }
- // Rollback = re-crear la sección tal cual estaba (si el reload falla).
- var rollback []string
- rollback = append(rollback, fmt.Sprintf("uci set dhcp.%s=host", h.Section))
- if h.Name != "" {
- rollback = append(rollback, uciSetCmd("dhcp", h.Section, "name", h.Name))
- }
- if h.MAC != "" {
- rollback = append(rollback, uciSetCmd("dhcp", h.Section, "mac", h.MAC))
- }
- if h.IP != "" {
- rollback = append(rollback, uciSetCmd("dhcp", h.Section, "ip", h.IP))
- }
- apply := []string{fmt.Sprintf("uci delete dhcp.%s", h.Section)}
- if err := s.runUCICommands(host, "dhcp", apply); err != nil {
- writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
- return
- }
- if err := s.reloadService(host, "dnsmasq"); err != nil {
- if rbErr := s.runUCICommands(host, "dhcp", rollback); rbErr != nil {
- log.Printf("[netpulse] reservation deletion rollback for %s failed: %v", mac, rbErr)
- }
- writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
- return
- }
- writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac})
- }
- // ---------------------------------------------------------------------------
- // Bloqueo de dispositivo (rule de /etc/config/firewall, fw4)
- // ---------------------------------------------------------------------------
- // firewallRule representa una sección rule de firewall UCI.
- type firewallRule struct {
- Section string
- Name string
- SrcMAC string
- Target string
- }
- // parseFirewallRules parsea `uci show firewall` y devuelve las reglas (named
- // `firewall.np_block_x=rule` y anónimas `firewall.@rule[0]=rule`).
- func parseFirewallRules(lines []string) []*firewallRule {
- ruleSections := uciTypeSections(lines, "firewall", "rule")
- var rules []*firewallRule
- bySection := map[string]*firewallRule{}
- for _, raw := range lines {
- line := strings.TrimSpace(raw)
- if line == "" {
- continue
- }
- m := reUciLine.FindStringSubmatch(line)
- if m == nil || m[1] != "firewall" {
- continue
- }
- dot := strings.Index(m[2], ".")
- if dot < 0 {
- continue
- }
- section, option := m[2][:dot], m[2][dot+1:]
- if !ruleSections[section] {
- continue
- }
- r := bySection[section]
- if r == nil {
- r = &firewallRule{Section: section}
- bySection[section] = r
- rules = append(rules, r)
- }
- switch option {
- case "name":
- r.Name = uciValue(m[3])
- case "src_mac":
- r.SrcMAC = uciValue(m[3])
- case "target":
- r.Target = uciValue(m[3])
- }
- }
- return rules
- }
- // blockRuleSection es el nombre de sección determinista para el bloqueo de una
- // MAC (uci set firewall.np_block_<mac12>=rule).
- func blockRuleSection(mac string) string {
- return "np_block_" + strings.ReplaceAll(uciMAC(mac), ":", "")
- }
- // blockRuleName es el nombre legible de la regla (mostrado en LuCI).
- func blockRuleName(mac string) string {
- return "np-block-" + strings.ReplaceAll(uciMAC(mac), ":", "")
- }
- // findBlockRule busca la regla de bloqueo de una MAC: por sección determinista
- // o por nombre legado (reglas anónimas `@rule[N]` con name='np-block-<mac>').
- func findBlockRule(rules []*firewallRule, mac string) *firewallRule {
- section := blockRuleSection(mac)
- name := blockRuleName(mac)
- for _, r := range rules {
- if r.Section == section || r.Name == name {
- return r
- }
- }
- return nil
- }
- // blockRuleApply/blockRuleRollback construyen los comandos uci de la regla
- // fw4. Forma mínima correcta (drop de tráfico reenviado desde la MAC, sin
- // romper su lease DHCP, que es input al router): src=lan, dest=*, target=DROP,
- // src_mac=<mac>.
- func blockRuleApply(section, mac string) []string {
- return []string{
- fmt.Sprintf("uci set firewall.%s=rule", section),
- uciSetCmd("firewall", section, "name", blockRuleName(mac)),
- fmt.Sprintf("uci set firewall.%s.src='lan'", section),
- fmt.Sprintf("uci set firewall.%s.dest='*'", section),
- fmt.Sprintf("uci set firewall.%s.target='DROP'", section),
- uciSetCmd("firewall", section, "src_mac", uciMAC(mac)),
- }
- }
- func blockRuleRollback(section string) []string {
- return []string{fmt.Sprintf("uci delete firewall.%s", section)}
- }
- // handleDeviceBlockGet indica si un dispositivo está bloqueado.
- func (s *server) handleDeviceBlockGet(w http.ResponseWriter, r *http.Request) {
- mac := macaddr.Normalize(r.PathValue("mac"))
- if mac == "" {
- writeError(w, http.StatusBadRequest, "invalid_mac")
- return
- }
- routerID := r.URL.Query().Get("router")
- if routerID == "" {
- writeError(w, http.StatusBadRequest, "missing_router")
- return
- }
- host := s.hostOfRouter(routerID)
- if host == "" {
- writeError(w, http.StatusBadRequest, "no_router")
- return
- }
- lines, err := s.uciShow(host, "firewall")
- if err != nil {
- writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
- return
- }
- rules := parseFirewallRules(lines)
- blocked := findBlockRule(rules, mac) != nil
- writeJSON(w, http.StatusOK, map[string]any{"blocked": blocked})
- }
- // handleDeviceBlockPut bloquea un dispositivo añadiendo una regla de firewall.
- func (s *server) handleDeviceBlockPut(w http.ResponseWriter, r *http.Request) {
- // #2112: uci show + commit + restart del servicio en la unidad antes de responder.
- setLongWriteDeadline(w, deviceActionWriteCeiling)
- mac := macaddr.Normalize(r.PathValue("mac"))
- if mac == "" {
- writeError(w, http.StatusBadRequest, "invalid_mac")
- return
- }
- var body struct {
- RouterID string `json:"router"`
- }
- if st := readJSONBody(w, r, &body); st != 0 {
- writeBodyError(w, st, "invalid_body", "body JSON inválido")
- return
- }
- if body.RouterID == "" {
- writeError(w, http.StatusBadRequest, "missing_router")
- return
- }
- host := s.hostOfRouter(body.RouterID)
- if host == "" {
- writeError(w, http.StatusBadRequest, "no_router")
- return
- }
- lines, err := s.uciShow(host, "firewall")
- if err != nil {
- writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
- return
- }
- rules := parseFirewallRules(lines)
- if findBlockRule(rules, mac) != nil {
- writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac, "already": true})
- return
- }
- section := blockRuleSection(mac)
- // Dry-run (#754): plan sin ejecutar (el check de "ya bloqueado" sí corre:
- // es lectura uci show, no escribe nada).
- if r.URL.Query().Get("dry_run") == "1" {
- writeDevicePlan(w, mac, host, blockRuleApply(section, mac), blockRuleRollback(section))
- return
- }
- if err := s.runUCICommands(host, "firewall", blockRuleApply(section, mac)); err != nil {
- writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
- return
- }
- if err := s.reloadService(host, "firewall"); err != nil {
- if rbErr := s.runUCICommands(host, "firewall", blockRuleRollback(section)); rbErr != nil {
- log.Printf("[netpulse] block rollback for %s failed: %v", mac, rbErr)
- }
- writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
- return
- }
- writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac})
- }
- // handleDeviceBlockDelete desbloquea un dispositivo.
- func (s *server) handleDeviceBlockDelete(w http.ResponseWriter, r *http.Request) {
- // #2112: uci show + commit + restart del servicio en la unidad antes de responder.
- setLongWriteDeadline(w, deviceActionWriteCeiling)
- mac := macaddr.Normalize(r.PathValue("mac"))
- if mac == "" {
- writeError(w, http.StatusBadRequest, "invalid_mac")
- return
- }
- var body struct {
- RouterID string `json:"router"`
- }
- if st := readJSONBody(w, r, &body); st != 0 {
- writeBodyError(w, st, "invalid_body", "body JSON inválido")
- return
- }
- if body.RouterID == "" {
- writeError(w, http.StatusBadRequest, "missing_router")
- return
- }
- host := s.hostOfRouter(body.RouterID)
- if host == "" {
- writeError(w, http.StatusBadRequest, "no_router")
- return
- }
- lines, err := s.uciShow(host, "firewall")
- if err != nil {
- writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
- return
- }
- rules := parseFirewallRules(lines)
- br := findBlockRule(rules, mac)
- if br == nil {
- writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac, "already": true})
- return
- }
- apply := []string{fmt.Sprintf("uci delete firewall.%s", br.Section)}
- rollback := []string{fmt.Sprintf("uci set firewall.%s=rule", br.Section)}
- if br.Name != "" {
- rollback = append(rollback, uciSetCmd("firewall", br.Section, "name", br.Name))
- }
- if br.SrcMAC != "" {
- rollback = append(rollback, uciSetCmd("firewall", br.Section, "src_mac", br.SrcMAC))
- }
- if br.Target != "" {
- rollback = append(rollback, uciSetCmd("firewall", br.Section, "target", br.Target))
- }
- if err := s.runUCICommands(host, "firewall", apply); err != nil {
- writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
- return
- }
- if err := s.reloadService(host, "firewall"); err != nil {
- if rbErr := s.runUCICommands(host, "firewall", rollback); rbErr != nil {
- log.Printf("[netpulse] unblock rollback for %s failed: %v", mac, rbErr)
- }
- writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
- return
- }
- writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac})
- }
|