dawn.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. // dawn.go - módulo de orquestación "DAWN" (Fase 17.9).
  2. //
  3. // Instala/configura DAWN (Distributed AP WiFi Neighbor) y alinea los parámetros
  4. // de roaming 802.11k/v/r en los APs. El módulo es declarativo: compara el
  5. // estado detectado contra un baseline deseado y genera las Ops allowlistedas
  6. // necesarias.
  7. //
  8. // Baseline por defecto (verificada en red Mandor y documentada en DAWN):
  9. // - kicking=3, kicking_threshold=20, duration=150, min_number_to_kick=3,
  10. // bandwidth_threshold=6
  11. // - eval_auth_req=0, eval_assoc_req=0, eval_probe_req=0
  12. // - network_option=2, hostapd_dir=/var/run/hostapd
  13. // - 802.11k=1, 802.11v=1, 802.11r=1, bss_transition=1, ft_over_ds=0,
  14. // ft_psk_generate_local=1, mobility_domain común
  15. // - random_bssid=0 en todas las radios
  16. package orchestr
  17. import (
  18. "fmt"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "time"
  23. "github.com/gnacho/netpulse/agent/executor"
  24. )
  25. // DawnDesired es el estado deseado del módulo DAWN.
  26. type DawnDesired struct {
  27. Enabled bool `json:"enabled"`
  28. SSID string `json:"ssid,omitempty"` // SSID a gestionar; vacío = todas las de modo AP
  29. MobilityDomain string `json:"mobilityDomain,omitempty"` // p. ej. "2025"
  30. BroadcastIP string `json:"broadcastIp,omitempty"` // p. ej. "192.168.1.255"
  31. TCPPort string `json:"tcpPort,omitempty"` // default "1026"
  32. SharedKey string `json:"sharedKey,omitempty"` // clave compartida de la malla DAWN
  33. IV string `json:"iv,omitempty"` // IV de la malla DAWN
  34. Kicking string `json:"kicking,omitempty"` // default "3"
  35. KickingThreshold string `json:"kickingThreshold,omitempty"` // default "20"
  36. Duration string `json:"duration,omitempty"` // default "150"
  37. MinNumberToKick string `json:"minNumberToKick,omitempty"` // default "3"
  38. BandwidthThreshold string `json:"bandwidthThreshold,omitempty"` // default "6"
  39. EvalAuthReq string `json:"evalAuthReq,omitempty"` // default "0"
  40. EvalAssocReq string `json:"evalAssocReq,omitempty"` // default "0"
  41. EvalProbeReq string `json:"evalProbeReq,omitempty"` // default "0"
  42. IEEE80211K bool `json:"ieee80211k,omitempty"`
  43. IEEE80211R bool `json:"ieee80211r,omitempty"`
  44. IEEE80211V bool `json:"ieee80211v,omitempty"`
  45. BSSTransition bool `json:"bssTransition,omitempty"`
  46. FTOverDS bool `json:"ftOverDs,omitempty"`
  47. FTPskGenerateLocal bool `json:"ftPskGenerateLocal,omitempty"`
  48. }
  49. // DawnSSID describe una sección wifi-iface.
  50. type DawnSSID struct {
  51. Section string
  52. SSID string
  53. Mode string
  54. Device string
  55. IEEE80211K string
  56. IEEE80211R string
  57. IEEE80211V string
  58. BSSTransition string
  59. FTOverDS string
  60. FTPskGenerateLocal string
  61. MobilityDomain string
  62. }
  63. // DawnRadio describe una sección wifi-device.
  64. type DawnRadio struct {
  65. Section string
  66. RandomBSSID string
  67. }
  68. // DawnScenario describe el estado detectado de DAWN en un router.
  69. type DawnScenario struct {
  70. Manager string // apk | opkg | ""
  71. DawnInstalled bool
  72. DawnRunning bool
  73. WpadVariant string // basic | mbedtls | wolfssl | openssl | other | ""
  74. HostapdDirOK bool
  75. Global map[string]string
  76. SSIDs []DawnSSID
  77. Radios []DawnRadio
  78. }
  79. const probeDawnCmd = `echo '===PKG_MGR==='
  80. [ -x /usr/bin/apk ] && echo apk || echo opkg
  81. echo '===DAWN_INST==='
  82. [ -x /etc/init.d/dawn ] && echo yes || echo no
  83. echo '===DAWN_RUN==='
  84. /etc/init.d/dawn running >/dev/null 2>&1 && echo yes || echo no
  85. echo '===WPAD==='
  86. opkg list-installed 2>/dev/null | grep -E '^wpad-' || true
  87. apk list --installed 2>/dev/null | grep -E '^wpad-' || true
  88. echo '===HOSTAPD_DIR==='
  89. [ -d /var/run/hostapd ] && echo yes || echo no
  90. echo '===DAWN_UCI==='
  91. uci show dawn 2>/dev/null
  92. echo '===WIRELESS_UCI==='
  93. uci show wireless 2>/dev/null
  94. echo '===END==='`
  95. // DetectDawn ejecuta el probe combinado vía SSH y devuelve el escenario.
  96. func DetectDawn(run CommandRunner, host string) (DawnScenario, error) {
  97. out, err := run.Run(host, probeDawnCmd, 10*time.Second)
  98. if err != nil {
  99. return DawnScenario{}, err
  100. }
  101. return parseDawn(out), nil
  102. }
  103. func parseDawn(out string) DawnScenario {
  104. sc := DawnScenario{Global: map[string]string{}}
  105. sections := splitSections(out)
  106. sc.Manager = strings.TrimSpace(firstNonEmpty(sections["PKG_MGR"]))
  107. if sc.Manager == "" {
  108. sc.Manager = "opkg"
  109. }
  110. sc.DawnInstalled = strings.TrimSpace(firstNonEmpty(sections["DAWN_INST"])) == "yes"
  111. sc.DawnRunning = strings.TrimSpace(firstNonEmpty(sections["DAWN_RUN"])) == "yes"
  112. sc.HostapdDirOK = strings.TrimSpace(firstNonEmpty(sections["HOSTAPD_DIR"])) == "yes"
  113. sc.WpadVariant = parseWpadVariant(sections["WPAD"])
  114. for _, line := range sections["DAWN_UCI"] {
  115. line = strings.TrimSpace(line)
  116. if !strings.HasPrefix(line, "dawn.global.") {
  117. continue
  118. }
  119. rest := strings.TrimPrefix(line, "dawn.global.")
  120. parts := strings.SplitN(rest, "=", 2)
  121. if len(parts) != 2 {
  122. continue
  123. }
  124. key := parts[0]
  125. val := strings.Trim(parts[1], "'")
  126. sc.Global[key] = val
  127. }
  128. sc.SSIDs, sc.Radios = parseWirelessDawn(sections["WIRELESS_UCI"])
  129. return sc
  130. }
  131. var reWpadLine = regexp.MustCompile(`^wpad-([a-z]+)`)
  132. func parseWpadVariant(lines []string) string {
  133. for _, line := range lines {
  134. line = strings.ToLower(strings.TrimSpace(line))
  135. if m := reWpadLine.FindStringSubmatch(line); m != nil {
  136. return m[1]
  137. }
  138. }
  139. return ""
  140. }
  141. func parseWirelessDawn(lines []string) (ssids []DawnSSID, radios []DawnRadio) {
  142. uci := strings.Join(lines, "\n")
  143. for _, line := range lines {
  144. line = strings.TrimSpace(line)
  145. if !strings.HasPrefix(line, "wireless.") {
  146. continue
  147. }
  148. rest := strings.TrimPrefix(line, "wireless.")
  149. parts := strings.SplitN(rest, "=", 2)
  150. if len(parts) != 2 {
  151. continue
  152. }
  153. secFull := parts[0]
  154. typ := strings.Trim(parts[1], "'")
  155. if typ == "wifi-iface" {
  156. ssids = append(ssids, DawnSSID{
  157. Section: secFull,
  158. SSID: wirelessOpt(uci, secFull, "ssid"),
  159. Mode: wirelessOpt(uci, secFull, "mode"),
  160. Device: wirelessOpt(uci, secFull, "device"),
  161. IEEE80211K: wirelessOpt(uci, secFull, "ieee80211k"),
  162. IEEE80211R: wirelessOpt(uci, secFull, "ieee80211r"),
  163. IEEE80211V: wirelessOpt(uci, secFull, "ieee80211v"),
  164. BSSTransition: wirelessOpt(uci, secFull, "bss_transition"),
  165. FTOverDS: wirelessOpt(uci, secFull, "ft_over_ds"),
  166. FTPskGenerateLocal: wirelessOpt(uci, secFull, "ft_psk_generate_local"),
  167. MobilityDomain: wirelessOpt(uci, secFull, "mobility_domain"),
  168. })
  169. } else if typ == "wifi-device" {
  170. radios = append(radios, DawnRadio{
  171. Section: secFull,
  172. RandomBSSID: wirelessOpt(uci, secFull, "random_bssid"),
  173. })
  174. }
  175. }
  176. return
  177. }
  178. func wirelessOpt(uci, sec, opt string) string {
  179. prefix := "wireless." + sec + "." + opt + "="
  180. for _, line := range strings.Split(uci, "\n") {
  181. line = strings.TrimSpace(line)
  182. if strings.HasPrefix(line, prefix) {
  183. return strings.Trim(strings.TrimPrefix(line, prefix), "'")
  184. }
  185. }
  186. return ""
  187. }
  188. // DawnOps genera las Ops para reconciliar el estado deseado de DAWN.
  189. func DawnOps(desired DawnDesired, sc DawnScenario) []executor.Op {
  190. if !desired.Enabled {
  191. return dawnDisableOps(sc)
  192. }
  193. d := normalizeDawnDesired(desired)
  194. var ops []executor.Op
  195. // 1. Instalar DAWN si falta.
  196. if !sc.DawnInstalled {
  197. if sc.Manager == "apk" {
  198. ops = append(ops, executor.Op{Kind: "apk_install", Args: map[string]string{"package": "dawn"}, Desc: "Install DAWN (apk)"})
  199. ops = append(ops, executor.Op{Kind: "apk_install", Args: map[string]string{"package": "luci-app-dawn"}, Desc: "Install LuCI DAWN (apk)"})
  200. } else {
  201. ops = append(ops, executor.Op{Kind: "install", Args: map[string]string{"package": "dawn"}, Desc: "Install DAWN (opkg)"})
  202. ops = append(ops, executor.Op{Kind: "install", Args: map[string]string{"package": "luci-app-dawn"}, Desc: "Install LuCI DAWN (opkg)"})
  203. }
  204. }
  205. // 2. Asegurar wpad completo si solo hay wpad-basic/mini.
  206. if sc.WpadVariant == "basic" || sc.WpadVariant == "mini" || sc.WpadVariant == "" {
  207. pkg := "wpad-wolfssl"
  208. if sc.Manager == "apk" {
  209. pkg = "wpad-mbedtls"
  210. }
  211. ops = append(ops, executor.Op{Kind: installKind(sc.Manager), Args: map[string]string{"package": pkg}, Desc: "Install full wpad for DAWN"})
  212. }
  213. // 3. Asegurar la sección dawn.global (named) y options.
  214. if len(sc.Global) == 0 {
  215. ops = append(ops, executor.Op{Kind: "uci_set_named", Args: map[string]string{"config": "dawn", "section": "global", "type": "global"}, Desc: "Ensure DAWN global section"})
  216. }
  217. setDawnGlobalIfDiffers(&ops, sc, "kicking", d.Kicking)
  218. setDawnGlobalIfDiffers(&ops, sc, "kicking_threshold", d.KickingThreshold)
  219. setDawnGlobalIfDiffers(&ops, sc, "duration", d.Duration)
  220. setDawnGlobalIfDiffers(&ops, sc, "min_number_to_kick", d.MinNumberToKick)
  221. setDawnGlobalIfDiffers(&ops, sc, "bandwidth_threshold", d.BandwidthThreshold)
  222. setDawnGlobalIfDiffers(&ops, sc, "eval_auth_req", d.EvalAuthReq)
  223. setDawnGlobalIfDiffers(&ops, sc, "eval_assoc_req", d.EvalAssocReq)
  224. setDawnGlobalIfDiffers(&ops, sc, "eval_probe_req", d.EvalProbeReq)
  225. setDawnGlobalIfDiffers(&ops, sc, "network_option", "2")
  226. setDawnGlobalIfDiffers(&ops, sc, "hostapd_dir", "/var/run/hostapd")
  227. setDawnGlobalIfDiffers(&ops, sc, "set_hostapd_nr", "1")
  228. setDawnGlobalIfDiffers(&ops, sc, "rrm_mode", "pat")
  229. setDawnGlobalIfDiffers(&ops, sc, "tcp_port", d.TCPPort)
  230. setDawnGlobalIfDiffers(&ops, sc, "shared_key", d.SharedKey)
  231. setDawnGlobalIfDiffers(&ops, sc, "iv", d.IV)
  232. if d.BroadcastIP != "" {
  233. setDawnGlobalIfDiffers(&ops, sc, "broadcast_ip", d.BroadcastIP)
  234. }
  235. // 4. Wireless: aplicar baseline a cada SSID de modo AP.
  236. for _, s := range sc.SSIDs {
  237. if s.Mode != "ap" {
  238. continue
  239. }
  240. if d.SSID != "" && s.SSID != d.SSID {
  241. continue
  242. }
  243. sec := s.Section
  244. setWirelessBoolIfDiffers(&ops, s.IEEE80211K, sec, "ieee80211k", d.IEEE80211K, true)
  245. setWirelessBoolIfDiffers(&ops, s.IEEE80211R, sec, "ieee80211r", d.IEEE80211R, true)
  246. setWirelessBoolIfDiffers(&ops, s.IEEE80211V, sec, "ieee80211v", d.IEEE80211V, true)
  247. setWirelessBoolIfDiffers(&ops, s.BSSTransition, sec, "bss_transition", d.BSSTransition, true)
  248. setWirelessBoolIfDiffers(&ops, s.FTOverDS, sec, "ft_over_ds", d.FTOverDS, false)
  249. setWirelessBoolIfDiffers(&ops, s.FTPskGenerateLocal, sec, "ft_psk_generate_local", d.FTPskGenerateLocal, true)
  250. if d.MobilityDomain != "" && s.MobilityDomain != d.MobilityDomain {
  251. ops = append(ops, executor.Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": sec, "option": "mobility_domain", "value": d.MobilityDomain}, Desc: "Set mobility domain on " + sec})
  252. }
  253. }
  254. // 5. Radios: random_bssid=0.
  255. for _, r := range sc.Radios {
  256. if r.RandomBSSID != "0" {
  257. ops = append(ops, executor.Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": r.Section, "option": "random_bssid", "value": "0"}, Desc: "Disable random BSSID on " + r.Section})
  258. }
  259. }
  260. if len(ops) == 0 {
  261. return nil
  262. }
  263. ops = append(ops, executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "dawn"}, Desc: "Commit DAWN config"})
  264. ops = append(ops, executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "Commit wireless config"})
  265. ops = append(ops, executor.Op{Kind: "service", Args: map[string]string{"name": "dawn", "action": "enable"}, Desc: "Enable DAWN on boot"})
  266. ops = append(ops, executor.Op{Kind: "service", Args: map[string]string{"name": "dawn", "action": "start"}, Desc: "Start DAWN"})
  267. return ops
  268. }
  269. func setDawnGlobalIfDiffers(ops *[]executor.Op, sc DawnScenario, option, want string) {
  270. if want == "" {
  271. return
  272. }
  273. if sc.Global[option] == want {
  274. return
  275. }
  276. *ops = append(*ops, executor.Op{Kind: "uci_set", Args: map[string]string{"config": "dawn", "section": "global", "option": option, "value": want}, Desc: "Set DAWN " + option})
  277. }
  278. func setWirelessBoolIfDiffers(ops *[]executor.Op, current, sec, option string, want, defaultVal bool) {
  279. val := boolString(want, defaultVal)
  280. if current == val {
  281. return
  282. }
  283. *ops = append(*ops, executor.Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": sec, "option": option, "value": val}, Desc: "Set " + option + " on " + sec})
  284. }
  285. func boolString(want, defaultVal bool) string {
  286. if want || defaultVal {
  287. return "1"
  288. }
  289. return "0"
  290. }
  291. func dawnDisableOps(sc DawnScenario) []executor.Op {
  292. if !sc.DawnInstalled && len(sc.Global) == 0 {
  293. return nil
  294. }
  295. return []executor.Op{
  296. {Kind: "uci_set", Args: map[string]string{"config": "dawn", "section": "global", "option": "enabled", "value": "0"}, Desc: "Disable DAWN"},
  297. {Kind: "uci_commit", Args: map[string]string{"config": "dawn"}, Desc: "Commit DAWN config"},
  298. {Kind: "service", Args: map[string]string{"name": "dawn", "action": "stop"}, Desc: "Stop DAWN"},
  299. {Kind: "service", Args: map[string]string{"name": "dawn", "action": "disable"}, Desc: "Disable DAWN on boot"},
  300. }
  301. }
  302. func normalizeDawnDesired(d DawnDesired) DawnDesired {
  303. if d.Kicking == "" {
  304. d.Kicking = "3"
  305. }
  306. if d.KickingThreshold == "" {
  307. d.KickingThreshold = "20"
  308. }
  309. if d.Duration == "" {
  310. d.Duration = "150"
  311. }
  312. if d.MinNumberToKick == "" {
  313. d.MinNumberToKick = "3"
  314. }
  315. if d.BandwidthThreshold == "" {
  316. d.BandwidthThreshold = "6"
  317. }
  318. if d.EvalAuthReq == "" {
  319. d.EvalAuthReq = "0"
  320. }
  321. if d.EvalAssocReq == "" {
  322. d.EvalAssocReq = "0"
  323. }
  324. if d.EvalProbeReq == "" {
  325. d.EvalProbeReq = "0"
  326. }
  327. if d.TCPPort == "" {
  328. d.TCPPort = "1026"
  329. }
  330. return d
  331. }
  332. func installKind(manager string) string {
  333. if manager == "apk" {
  334. return "apk_install"
  335. }
  336. return "install"
  337. }
  338. // DawnHealthcheck verifica que DAWN responde y ve vecinos tras el apply.
  339. func DawnHealthcheck(run CommandRunner, host string) error {
  340. out, err := run.Run(host, "ubus call dawn get_network", 5*time.Second)
  341. if err != nil {
  342. return fmt.Errorf("dawn get_network failed: %w", err)
  343. }
  344. out = strings.TrimSpace(out)
  345. if out == "" || out == "{}" {
  346. return fmt.Errorf("dawn get_network returned empty mesh")
  347. }
  348. return nil
  349. }
  350. // DawnDriftWarnings devuelve advertencias de inconsistencia legibles para la UI.
  351. func DawnDriftWarnings(d DawnDesired, sc DawnScenario) []string {
  352. d = normalizeDawnDesired(d)
  353. var warns []string
  354. if !sc.DawnInstalled {
  355. warns = append(warns, "DAWN no está instalado")
  356. }
  357. if !sc.HostapdDirOK {
  358. warns = append(warns, "El directorio /var/run/hostapd no existe")
  359. }
  360. mdom := d.MobilityDomain
  361. for _, s := range sc.SSIDs {
  362. if s.Mode != "ap" {
  363. continue
  364. }
  365. if d.SSID != "" && s.SSID != d.SSID {
  366. continue
  367. }
  368. if mdom != "" && s.MobilityDomain != mdom {
  369. warns = append(warns, "Dominio de movilidad inconsistente en "+s.Section)
  370. }
  371. if s.IEEE80211K != "1" {
  372. warns = append(warns, "802.11k desactivado en "+s.Section)
  373. }
  374. if s.IEEE80211R != "1" {
  375. warns = append(warns, "802.11r desactivado en "+s.Section)
  376. }
  377. if s.IEEE80211V != "1" {
  378. warns = append(warns, "802.11v desactivado en "+s.Section)
  379. }
  380. }
  381. for _, r := range sc.Radios {
  382. if r.RandomBSSID != "0" {
  383. warns = append(warns, "random_bssid activo en "+r.Section)
  384. }
  385. }
  386. return warns
  387. }
  388. // DawnMethod devuelve active/inactive para la UI.
  389. func DawnMethod(sc DawnScenario) string {
  390. if sc.DawnRunning {
  391. return "active"
  392. }
  393. return "inactive"
  394. }
  395. // Int helpers para comparar valores numéricos si fuese necesario.
  396. func dawnInt(s string) int {
  397. v, _ := strconv.Atoi(strings.TrimSpace(s))
  398. return v
  399. }
  400. func validateDawnOps(ops []executor.Op) error {
  401. for _, op := range ops {
  402. if err := executor.Validate(op); err != nil {
  403. return fmt.Errorf("%s: %w", op.Desc, err)
  404. }
  405. }
  406. return nil
  407. }