guestwifi.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // guestwifi.go — módulo de orquestación "WiFi guest aislada" (Fase 17.2).
  2. //
  3. // Crea (o elimina) una red WiFi guest aislada en un router OpenWrt: una
  4. // wifi-iface en modo AP con isolate, una network estática en subred propia
  5. // (192.168.8.0/24) y una zona de firewall que solo permite salir a WAN.
  6. // Todo se hace con Ops allowlistedas del executor (uci_add/uci_set/...).
  7. package orchestr
  8. import (
  9. "fmt"
  10. "strings"
  11. "time"
  12. "github.com/gnacho/netpulse/agent/executor"
  13. )
  14. // guestSSIDDefault es el SSID por defecto de la red guest.
  15. const guestSSIDDefault = "NetPulse-Guest"
  16. // guestIP / guestMask: subred propia de la guest (no choca con la LAN /24).
  17. const (
  18. guestIP = "192.168.8.1"
  19. guestMask = "255.255.255.0"
  20. )
  21. // GuestWiFiDesired es el estado deseado del módulo.
  22. type GuestWiFiDesired struct {
  23. Enabled bool `json:"enabled"`
  24. SSID string `json:"ssid"`
  25. Password string `json:"password"`
  26. // Band: "2g" | "5g" | "auto". Vacío/auto → el primer radio disponible.
  27. Band string `json:"band"`
  28. // AllowNonGateway: permitir en un router no-gateway (mismo patrón que
  29. // AdGuard, #120). Default solo gateway.
  30. AllowNonGateway bool `json:"allowNonGateway,omitempty"`
  31. }
  32. // GuestWiFiScenario es lo que detecta el probe en el router.
  33. type GuestWiFiScenario struct {
  34. // Radio2G / Radio5G: nombre del radio (radio0, radio1) por banda. Vacío si
  35. // el router no tiene esa banda.
  36. Radio2G string
  37. Radio5G string
  38. // GuestPresent: ya existe una wifi-iface con el SSID guest.
  39. GuestPresent bool
  40. // GuestIfaceIdx: referencia a la wifi-iface guest existente (para disable).
  41. GuestIfaceIdx string
  42. // GuestZoneIdx / GuestFwdIdx: secciones firewall guest existentes.
  43. GuestZoneIdx string
  44. GuestFwdIdx string
  45. }
  46. // probeGuestWiFiCmd lee el estado de wireless/network/firewall. Una sola sesión.
  47. const probeGuestWiFiCmd = `echo '===WIRELESS==='
  48. uci show wireless
  49. echo '===NETWORK==='
  50. uci show network
  51. echo '===FIREWALL==='
  52. uci show firewall
  53. echo '===END==='`
  54. // DetectGuestWiFi ejecuta el probe y devuelve el escenario.
  55. func DetectGuestWiFi(run CommandRunner, host string) (GuestWiFiScenario, error) {
  56. out, err := run.Run(host, probeGuestWiFiCmd, 8*time.Second)
  57. if err != nil {
  58. return GuestWiFiScenario{}, err
  59. }
  60. return parseGuestWiFi(out), nil
  61. }
  62. // parseGuestWiFi extrae radios, wifi-ifaces y secciones guest del output.
  63. // Función pura (testeable sin SSH).
  64. func parseGuestWiFi(out string) GuestWiFiScenario {
  65. sc := GuestWiFiScenario{}
  66. sections := splitSections(out)
  67. wireless := strings.Join(sections["WIRELESS"], "\n")
  68. network := strings.Join(sections["NETWORK"], "\n")
  69. firewall := strings.Join(sections["FIREWALL"], "\n")
  70. // Radios y su banda + wifi-ifaces en orden de aparición.
  71. radioBand := map[string]string{}
  72. var wifiIfaces []string
  73. for _, line := range strings.Split(wireless, "\n") {
  74. line = strings.TrimSpace(line)
  75. if strings.HasPrefix(line, "wireless.") {
  76. rest := strings.TrimPrefix(line, "wireless.")
  77. if strings.Contains(rest, "=wifi-device") {
  78. name := strings.TrimSuffix(rest, "=wifi-device")
  79. radioBand[name] = ""
  80. continue
  81. }
  82. if strings.Contains(rest, "=wifi-iface") {
  83. name := strings.TrimSuffix(rest, "=wifi-iface")
  84. wifiIfaces = append(wifiIfaces, name)
  85. continue
  86. }
  87. // banda: wireless.radioX.band='2g'
  88. if dot := strings.Index(rest, "."); dot > 0 {
  89. sec, field := rest[:dot], rest[dot+1:]
  90. if _, ok := radioBand[sec]; ok && strings.HasPrefix(field, "band=") {
  91. radioBand[sec] = strings.Trim(strings.TrimPrefix(field, "band="), "'")
  92. }
  93. }
  94. }
  95. }
  96. for name, band := range radioBand {
  97. switch band {
  98. case "2g":
  99. if sc.Radio2G == "" {
  100. sc.Radio2G = name
  101. }
  102. case "5g":
  103. if sc.Radio5G == "" {
  104. sc.Radio5G = name
  105. }
  106. }
  107. }
  108. // ¿Existe ya una wifi-iface guest (por ssid)?
  109. for i, name := range wifiIfaces {
  110. for _, line := range strings.Split(wireless, "\n") {
  111. line = strings.TrimSpace(line)
  112. if strings.HasPrefix(line, "wireless."+name+".ssid=") {
  113. ssid := strings.Trim(strings.TrimPrefix(line, "wireless."+name+".ssid="), "'")
  114. if ssid == guestSSIDDefault {
  115. sc.GuestPresent = true
  116. sc.GuestIfaceIdx = fmt.Sprintf("@wifi-iface[%d]", i)
  117. }
  118. }
  119. }
  120. }
  121. // Firewall: zone name=guest y forwarding src=guest.
  122. sc.GuestZoneIdx = guestFirewallIndex(firewall, "zone", "guest")
  123. sc.GuestFwdIdx = guestForwardingIndex(firewall)
  124. _ = network // (la network guest se borra por nombre "guest", sin índice)
  125. return sc
  126. }
  127. // guestFirewallIndex busca la sección @type[i] cuyo name coincide.
  128. func guestFirewallIndex(firewall, typ, nameWanted string) string {
  129. prefix := "firewall.@" + typ + "["
  130. for _, line := range strings.Split(firewall, "\n") {
  131. line = strings.TrimSpace(line)
  132. if !strings.HasPrefix(line, prefix) || !strings.Contains(line, ".name='") {
  133. continue
  134. }
  135. rest := strings.TrimPrefix(line, "firewall.@")
  136. idx := ""
  137. for _, r := range rest {
  138. if r == ']' {
  139. break
  140. }
  141. if r >= '0' && r <= '9' {
  142. idx += string(r)
  143. }
  144. }
  145. name := strings.Trim(strings.TrimPrefix(line, "firewall.@"+typ+"["+idx+"].name="), "'")
  146. if name == nameWanted {
  147. return "@" + typ + "[" + idx + "]"
  148. }
  149. }
  150. return ""
  151. }
  152. // guestForwardingIndex busca el forwarding con src=guest.
  153. func guestForwardingIndex(firewall string) string {
  154. prefix := "firewall.@forwarding["
  155. for _, line := range strings.Split(firewall, "\n") {
  156. line = strings.TrimSpace(line)
  157. if !strings.HasPrefix(line, prefix) {
  158. continue
  159. }
  160. if strings.Contains(line, "src='guest'") {
  161. rest := strings.TrimPrefix(line, "firewall.@")
  162. idx := ""
  163. for _, r := range rest {
  164. if r == ']' {
  165. break
  166. }
  167. if r >= '0' && r <= '9' {
  168. idx += string(r)
  169. }
  170. }
  171. return "@forwarding[" + idx + "]"
  172. }
  173. }
  174. return ""
  175. }
  176. // GuestWiFiOps genera las Ops para activar/desactivar la guest.
  177. func GuestWiFiOps(desired GuestWiFiDesired, sc GuestWiFiScenario) []executor.Op {
  178. if !desired.Enabled {
  179. return guestWiFiDisableOps(sc)
  180. }
  181. ssid := desired.SSID
  182. if ssid == "" {
  183. ssid = guestSSIDDefault
  184. }
  185. radio := sc.Radio2G
  186. switch {
  187. case desired.Band == "5g" && sc.Radio5G != "":
  188. radio = sc.Radio5G
  189. case desired.Band == "2g" && sc.Radio2G != "":
  190. radio = sc.Radio2G
  191. case sc.Radio2G == "" && sc.Radio5G != "":
  192. radio = sc.Radio5G
  193. }
  194. password := desired.Password
  195. if password == "" {
  196. password = "changeme123"
  197. }
  198. ops := []executor.Op{
  199. {Kind: "uci_add", Args: map[string]string{"config": "wireless", "type": "wifi-iface"}, Desc: "Create guest wifi-iface"},
  200. {Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "device", "value": radio}, Desc: "Bind guest iface to radio"},
  201. {Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "mode", "value": "ap"}, Desc: "Guest iface mode AP"},
  202. {Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "ssid", "value": ssid}, Desc: "Set guest SSID"},
  203. {Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "encryption", "value": "psk2"}, Desc: "Guest WPA2 encryption"},
  204. {Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "key", "value": password}, Desc: "Set guest password"},
  205. {Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "network", "value": "guest"}, Desc: "Bind guest iface to guest network"},
  206. {Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "isolate", "value": "1"}, Desc: "Isolate guest clients"},
  207. {Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "Commit wireless"},
  208. {Kind: "uci_set_named", Args: map[string]string{"config": "network", "section": "guest", "type": "interface"}, Desc: "Create guest network interface"},
  209. {Kind: "uci_set", Args: map[string]string{"config": "network", "section": "guest", "option": "proto", "value": "static"}, Desc: "Guest static IP"},
  210. {Kind: "uci_set", Args: map[string]string{"config": "network", "section": "guest", "option": "ipaddr", "value": guestIP}, Desc: "Guest gateway IP"},
  211. {Kind: "uci_set", Args: map[string]string{"config": "network", "section": "guest", "option": "netmask", "value": guestMask}, Desc: "Guest netmask"},
  212. {Kind: "uci_commit", Args: map[string]string{"config": "network"}, Desc: "Commit network"},
  213. {Kind: "uci_add", Args: map[string]string{"config": "firewall", "type": "zone"}, Desc: "Create guest firewall zone"},
  214. {Kind: "uci_set", Args: map[string]string{"config": "firewall", "section": "@zone[-1]", "option": "name", "value": "guest"}, Desc: "Name guest zone"},
  215. {Kind: "uci_set", Args: map[string]string{"config": "firewall", "section": "@zone[-1]", "option": "network", "value": "guest"}, Desc: "Zone network guest"},
  216. {Kind: "uci_set", Args: map[string]string{"config": "firewall", "section": "@zone[-1]", "option": "input", "value": "REJECT"}, Desc: "Zone input REJECT"},
  217. {Kind: "uci_set", Args: map[string]string{"config": "firewall", "section": "@zone[-1]", "option": "output", "value": "ACCEPT"}, Desc: "Zone output ACCEPT"},
  218. {Kind: "uci_set", Args: map[string]string{"config": "firewall", "section": "@zone[-1]", "option": "forward", "value": "REJECT"}, Desc: "Zone forward REJECT"},
  219. {Kind: "uci_add", Args: map[string]string{"config": "firewall", "type": "forwarding"}, Desc: "Create guest forwarding"},
  220. {Kind: "uci_set", Args: map[string]string{"config": "firewall", "section": "@forwarding[-1]", "option": "src", "value": "guest"}, Desc: "Forwarding src guest"},
  221. {Kind: "uci_set", Args: map[string]string{"config": "firewall", "section": "@forwarding[-1]", "option": "dest", "value": "wan"}, Desc: "Forwarding dest wan"},
  222. {Kind: "uci_commit", Args: map[string]string{"config": "firewall"}, Desc: "Commit firewall"},
  223. {Kind: "service", Args: map[string]string{"name": "network", "action": "reload"}, Desc: "Reload network (applies wifi)"},
  224. {Kind: "service", Args: map[string]string{"name": "firewall", "action": "reload"}, Desc: "Reload firewall"},
  225. }
  226. return ops
  227. }
  228. // guestWiFiDisableOps revierte el enable: borra las secciones creadas.
  229. func guestWiFiDisableOps(sc GuestWiFiScenario) []executor.Op {
  230. ops := []executor.Op{}
  231. if sc.GuestIfaceIdx != "" {
  232. ops = append(ops, executor.Op{Kind: "uci_delete_section", Args: map[string]string{"config": "wireless", "section": sc.GuestIfaceIdx}, Desc: "Remove guest wifi-iface"})
  233. }
  234. ops = append(ops, executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "Commit wireless"})
  235. ops = append(ops, executor.Op{Kind: "uci_delete_section", Args: map[string]string{"config": "network", "section": "guest"}, Desc: "Remove guest network"})
  236. ops = append(ops, executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "network"}, Desc: "Commit network"})
  237. if sc.GuestZoneIdx != "" {
  238. ops = append(ops, executor.Op{Kind: "uci_delete_section", Args: map[string]string{"config": "firewall", "section": sc.GuestZoneIdx}, Desc: "Remove guest zone"})
  239. }
  240. if sc.GuestFwdIdx != "" {
  241. ops = append(ops, executor.Op{Kind: "uci_delete_section", Args: map[string]string{"config": "firewall", "section": sc.GuestFwdIdx}, Desc: "Remove guest forwarding"})
  242. }
  243. ops = append(ops, executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "firewall"}, Desc: "Commit firewall"})
  244. ops = append(ops, executor.Op{Kind: "service", Args: map[string]string{"name": "network", "action": "reload"}, Desc: "Reload network"})
  245. ops = append(ops, executor.Op{Kind: "service", Args: map[string]string{"name": "firewall", "action": "reload"}, Desc: "Reload firewall"})
  246. return ops
  247. }
  248. // validateGuestWiFiOps valida cada op contra el executor (usado en tests).
  249. func validateGuestWiFiOps(ops []executor.Op) error {
  250. for _, op := range ops {
  251. if err := executor.Validate(op); err != nil {
  252. return fmt.Errorf("%s: %w", op.Desc, err)
  253. }
  254. }
  255. return nil
  256. }