impostor_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. package adapters
  2. // impostor_test.go — #1358: alerta wifi-ssid-impostor desde wifi_scans +
  3. // BSSIDs/SSIDs propios del registry. BD real en dir temporal (wifi_scans
  4. // la crea db.Open), engine en memoria (l.engine de NewLive).
  5. import (
  6. "testing"
  7. "time"
  8. "github.com/gnacho/netpulse/agent/probe"
  9. "github.com/gnacho/netpulse/server-go/internal/db"
  10. )
  11. // newImpostorLive: Live con db real (wifi_scans) y registry con la flota
  12. // mínima: un agente ("ap1") cuyo SSID propio es "temiscira".
  13. func newImpostorLive(t *testing.T) (*Live, *AgentRegistry) {
  14. t.Helper()
  15. d, err := db.Open(t.TempDir())
  16. if err != nil {
  17. t.Fatalf("db.Open: %v", err)
  18. }
  19. t.Cleanup(func() { d.Close() })
  20. reg := NewAgentRegistry(90 * time.Second)
  21. reg.Ingest(&probe.Payload{
  22. Router: "ap1",
  23. Version: "3.0.16",
  24. Ts: time.Now().Unix(),
  25. Data: probe.PayloadData{
  26. Wireless: &probe.WirelessData{
  27. OwnBssids: []probe.OwnBSSID{
  28. {Iface: "wlan0", BSSID: "AA:BB:CC:00:00:01", SSID: "temiscira"},
  29. },
  30. },
  31. },
  32. })
  33. l := NewLive(nil, d, []RouterConfig{{ID: "ap1", Name: "AP Uno"}}, nil)
  34. l.SetAgents(reg)
  35. return l, reg
  36. }
  37. // insertScan: sighting directo en wifi_scans (lo que haría SaveScan).
  38. func insertScan(t *testing.T, l *Live, routerID, bssid, ssid string, ts time.Time) {
  39. t.Helper()
  40. _, err := l.db.Exec(
  41. `INSERT INTO wifi_scans (router_id, iface, bssid, ssid, channel, freq, signal_dbm, width_mhz, ts)
  42. VALUES (?, 'wlan0', ?, ?, 6, 2437, -55, 20, ?)`,
  43. routerID, bssid, ssid, ts.Unix())
  44. if err != nil {
  45. t.Fatalf("insert scan: %v", err)
  46. }
  47. }
  48. func impostorAlerts(l *Live) []AlertEvent {
  49. var out []AlertEvent
  50. for _, a := range l.engine.List() {
  51. if a.Type == "wifi-ssid-impostor" {
  52. out = append(out, a)
  53. }
  54. }
  55. return out
  56. }
  57. func TestImpostorSingleSightingDoesNotAlert(t *testing.T) {
  58. l, _ := newImpostorLive(t)
  59. now := time.Now()
  60. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:01", "temiscira", now)
  61. l.EvalSsidImpostors()
  62. if got := impostorAlerts(l); len(got) != 0 {
  63. t.Fatalf("un sighting suelto no debe alertar; alertas: %+v", got)
  64. }
  65. }
  66. func TestImpostorConfirmedAfterDwell(t *testing.T) {
  67. l, _ := newImpostorLive(t)
  68. now := time.Now()
  69. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:02", "temiscira", now.Add(-30*time.Minute))
  70. l.EvalSsidImpostors()
  71. if got := impostorAlerts(l); len(got) != 0 {
  72. t.Fatalf("un solo scan real aunque sea viejo no debe alertar")
  73. }
  74. // Segundo scan real (otro ts) separado >= dwell: confirma.
  75. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:02", "temiscira", now)
  76. l.EvalSsidImpostors()
  77. got := impostorAlerts(l)
  78. if len(got) != 1 {
  79. t.Fatalf("dwell cumplido debe alertar una vez; alertas: %d", len(got))
  80. }
  81. a := got[0]
  82. if !a.Urgent || a.Severity != "critical" || a.Category != "clients" {
  83. t.Fatalf("severidad/categoría/urgencia: %+v", a)
  84. }
  85. if a.Vars["bssid"] != "DE:AD:BE:EF:00:02" || a.Vars["ssid"] != "temiscira" || a.Vars["router"] != "AP Uno" {
  86. t.Fatalf("vars: %+v", a.Vars)
  87. }
  88. // Re-evaluar con la misma evidencia NO duplica (ID estable + tracking).
  89. l.EvalSsidImpostors()
  90. if got := impostorAlerts(l); len(got) != 1 {
  91. t.Fatalf("re-evaluación no debe duplicar; alertas: %d", len(got))
  92. }
  93. }
  94. func TestImpostorOwnBssidIgnored(t *testing.T) {
  95. l, _ := newImpostorLive(t)
  96. now := time.Now()
  97. // BSSID propio (del registry) anunciando el SSID propio: normal.
  98. insertScan(t, l, "ap1", "AA:BB:CC:00:00:01", "temiscira", now.Add(-40*time.Minute))
  99. insertScan(t, l, "ap1", "aa:bb:cc:00:00:01", "temiscira", now) // minúsculas
  100. l.EvalSsidImpostors()
  101. if got := impostorAlerts(l); len(got) != 0 {
  102. t.Fatalf("BSSID propio no es impostor; alertas: %+v", got)
  103. }
  104. }
  105. func TestImpostorForeignSsidIgnored(t *testing.T) {
  106. l, _ := newImpostorLive(t)
  107. now := time.Now()
  108. // SSID que no es de la flota: vecino normal.
  109. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:03", "wifi-del-vecino", now.Add(-40*time.Minute))
  110. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:03", "wifi-del-vecino", now)
  111. l.EvalSsidImpostors()
  112. if got := impostorAlerts(l); len(got) != 0 {
  113. t.Fatalf("SSID ajeno no alerta; alertas: %+v", got)
  114. }
  115. }
  116. // #1402: la unidad cuyo payload no trae ownBssids (y no se sondea por SSH)
  117. // se reconoce por routers.mac: su bridge MAC y sus radios derivadas (+1/+2)
  118. // no deben alertar como impostor. Un BSSID realmente ajeno SÍ sigue alertando.
  119. func TestImpostorFleetMacSeeded(t *testing.T) {
  120. l, _ := newImpostorLive(t)
  121. // Unidad de flota sin agente: solo su MAC conocida en routers.mac.
  122. if _, err := l.db.Exec(
  123. `INSERT INTO routers (id, name, host, type, created_at, mac) VALUES ('ap2', 'AP Dos', '192.168.8.3', 'openwrt', 1, 'aa:bb:cc:00:10:00')`,
  124. ); err != nil {
  125. t.Fatalf("insert router: %v", err)
  126. }
  127. now := time.Now()
  128. // Radio = mac+1 anunciando el SSID de la flota: propia, no impostor.
  129. insertScan(t, l, "ap1", "AA:BB:CC:00:10:01", "temiscira", now.Add(-40*time.Minute))
  130. insertScan(t, l, "ap1", "AA:BB:CC:00:10:01", "temiscira", now)
  131. l.EvalSsidImpostors()
  132. if got := impostorAlerts(l); len(got) != 0 {
  133. t.Fatalf("radio derivada de routers.mac no es impostor; alertas: %+v", got)
  134. }
  135. // BSSID realmente ajeno: la regla sigue viva.
  136. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:09", "temiscira", now.Add(-40*time.Minute))
  137. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:09", "temiscira", now)
  138. l.EvalSsidImpostors()
  139. if got := impostorAlerts(l); len(got) != 1 {
  140. t.Fatalf("BSSID ajeno debía alertar; alertas: %+v", got)
  141. }
  142. }
  143. func TestImpostorSamePayloadFrozenDoesNotConfirm(t *testing.T) {
  144. l, _ := newImpostorLive(t)
  145. now := time.Now()
  146. // El mismo scan (mismo ts) duplicado por re-push del payload congelado:
  147. // NO son dos scans reales.
  148. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:04", "temiscira", now.Add(-30*time.Minute))
  149. insertScan(t, l, "ap2", "DE:AD:BE:EF:00:04", "temiscira", now.Add(-30*time.Minute))
  150. l.EvalSsidImpostors()
  151. if got := impostorAlerts(l); len(got) != 0 {
  152. t.Fatalf("mismo ts en dos routers no confirma; alertas: %+v", got)
  153. }
  154. }
  155. func TestImpostorAutoResolve(t *testing.T) {
  156. l, _ := newImpostorLive(t)
  157. now := time.Now()
  158. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:05", "temiscira", now.Add(-90*time.Minute))
  159. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:05", "temiscira", now.Add(-60*time.Minute))
  160. l.EvalSsidImpostors()
  161. if got := impostorAlerts(l); len(got) != 1 {
  162. t.Fatalf("debió alertar (dwell cumplido y reciente); alertas: %d", len(got))
  163. }
  164. // Pasan >impostorRecent sin nuevos sightings: resolve. La ventana de la
  165. // query usa el reloj real; simulamos el paso del tiempo retirando la
  166. // evidencia (equivale a que los scans envejecieron fuera de la ventana).
  167. _, _ = l.db.Exec(`DELETE FROM wifi_scans`)
  168. l.EvalSsidImpostors()
  169. if l.engine.Has("alert-ssid-impostor-DE:AD:BE:EF:00:05") {
  170. t.Fatal("impostor desaparecido debe auto-resolverse")
  171. }
  172. if len(l.impostorActive) != 0 {
  173. t.Fatalf("tracking residual: %+v", l.impostorActive)
  174. }
  175. }
  176. func TestLocalSsids(t *testing.T) {
  177. reg := NewAgentRegistry(90 * time.Second)
  178. reg.Ingest(&probe.Payload{
  179. Router: "ap1", Version: "3.0.16", Ts: time.Now().Unix(),
  180. Data: probe.PayloadData{
  181. Wireless: &probe.WirelessData{
  182. OwnBssids: []probe.OwnBSSID{
  183. {Iface: "wlan0", BSSID: "AA:BB:CC:00:00:01", SSID: "temiscira"},
  184. {Iface: "wlan1", BSSID: "AA:BB:CC:00:00:02", SSID: "temiscira-guest"},
  185. {Iface: "wlan2", BSSID: "AA:BB:CC:00:00:03", SSID: ""}, // sin SSID: fuera
  186. },
  187. },
  188. Dawn: &probe.DawnData{SSIDs: map[string]probe.DawnSSID{
  189. "temiscira": {APs: []probe.DawnAP{{BSSID: "AA:BB:CC:00:00:01", Local: true}}},
  190. "vecina": {APs: []probe.DawnAP{{BSSID: "11:22:33:44:55:66", Local: false}}}, // no local: fuera
  191. }},
  192. },
  193. })
  194. got := reg.LocalSsids()
  195. want := map[string]bool{"temiscira": true, "temiscira-guest": true}
  196. if len(got) != len(want) {
  197. t.Fatalf("LocalSsids = %v", got)
  198. }
  199. for _, s := range got {
  200. if !want[s] {
  201. t.Fatalf("SSID inesperado: %q (got %v)", s, got)
  202. }
  203. }
  204. }
  205. func TestImpostorAlertUsesLatestSighting(t *testing.T) {
  206. l, _ := newImpostorLive(t)
  207. now := time.Now()
  208. // El sighting RECIENTE insertado primero (rowid menor: la BD lo
  209. // devuelve antes sin ORDER BY). Sin inicializar router/señal en la
  210. // creación del tracking, la alerta salía con esos campos vacíos.
  211. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:06", "temiscira", now)
  212. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:06", "temiscira", now.Add(-30*time.Minute))
  213. l.EvalSsidImpostors()
  214. got := impostorAlerts(l)
  215. if len(got) != 1 {
  216. t.Fatalf("debió alertar; alertas: %d", len(got))
  217. }
  218. if got[0].Vars["router"] != "AP Uno" || got[0].Vars["signal"] != "-55" {
  219. t.Fatalf("vars deben ser del sighting más reciente: %+v", got[0].Vars)
  220. }
  221. }
  222. func TestImpostorApprovedDoesNotAlert(t *testing.T) {
  223. l, _ := newImpostorLive(t)
  224. now := time.Now()
  225. // #1400: BSSID aprobado a mano (AP UniFi ajeno a la flota NetPulse).
  226. if err := l.ApproveImpostorBssid("de:ad:be:ef:00:10"); err != nil {
  227. t.Fatalf("approve: %v", err)
  228. }
  229. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:10", "temiscira", now.Add(-40*time.Minute))
  230. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:10", "temiscira", now)
  231. l.EvalSsidImpostors()
  232. if got := impostorAlerts(l); len(got) != 0 {
  233. t.Fatalf("BSSID aprobado no debe alertar; alertas: %+v", got)
  234. }
  235. if got := l.ImpostorApproved(); len(got) != 1 || got[0] != "DE:AD:BE:EF:00:10" {
  236. t.Fatalf("ImpostorApproved = %v", got)
  237. }
  238. }
  239. func TestImpostorApproveResolvesActiveAlert(t *testing.T) {
  240. l, _ := newImpostorLive(t)
  241. now := time.Now()
  242. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:11", "temiscira", now.Add(-40*time.Minute))
  243. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:11", "temiscira", now)
  244. l.EvalSsidImpostors()
  245. if got := impostorAlerts(l); len(got) != 1 {
  246. t.Fatalf("debió alertar; alertas: %d", len(got))
  247. }
  248. if err := l.ApproveImpostorBssid("DE:AD:BE:EF:00:11"); err != nil {
  249. t.Fatalf("approve: %v", err)
  250. }
  251. if got := impostorAlerts(l); len(got) != 0 {
  252. t.Fatalf("aprobar debe resolver la alerta activa; alertas: %+v", got)
  253. }
  254. if len(l.impostorActive) != 0 {
  255. t.Fatalf("tracking residual tras aprobar: %+v", l.impostorActive)
  256. }
  257. // Re-evaluar con la evidencia intacta: no re-alerta (aprobado).
  258. l.EvalSsidImpostors()
  259. if got := impostorAlerts(l); len(got) != 0 {
  260. t.Fatalf("aprobado no debe re-alertar; alertas: %+v", got)
  261. }
  262. }
  263. func TestImpostorRevokeReAlerts(t *testing.T) {
  264. l, _ := newImpostorLive(t)
  265. now := time.Now()
  266. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:12", "temiscira", now.Add(-40*time.Minute))
  267. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:12", "temiscira", now)
  268. if err := l.ApproveImpostorBssid("DE:AD:BE:EF:00:12"); err != nil {
  269. t.Fatalf("approve: %v", err)
  270. }
  271. l.EvalSsidImpostors()
  272. if got := impostorAlerts(l); len(got) != 0 {
  273. t.Fatalf("aprobado no debe alertar; alertas: %+v", got)
  274. }
  275. l.RevokeImpostorBssid("DE:AD:BE:EF:00:12")
  276. if got := l.ImpostorApproved(); len(got) != 0 {
  277. t.Fatalf("revoke debe vaciar la lista; got %v", got)
  278. }
  279. l.EvalSsidImpostors()
  280. if got := impostorAlerts(l); len(got) != 1 {
  281. t.Fatalf("revocado y visible debe re-alertar; alertas: %d", len(got))
  282. }
  283. }
  284. func TestImpostorApproveInvalidBssid(t *testing.T) {
  285. l, _ := newImpostorLive(t)
  286. for _, bad := range []string{"", "no-es-mac", "DE:AD:BE:EF:00", "zz:zz:zz:zz:zz:zz"} {
  287. if err := l.ApproveImpostorBssid(bad); err == nil {
  288. t.Fatalf("bssid inválido %q debe dar error", bad)
  289. }
  290. }
  291. if got := l.ImpostorApproved(); len(got) != 0 {
  292. t.Fatalf("ningún inválido debe entrar en la lista; got %v", got)
  293. }
  294. }
  295. func TestImpostorAllowlistPersistsAcrossRestart(t *testing.T) {
  296. l, _ := newImpostorLive(t)
  297. if err := l.ApproveImpostorBssid("DE:AD:BE:EF:00:13"); err != nil {
  298. t.Fatalf("approve: %v", err)
  299. }
  300. // Simula un reinicio: Live NUEVO sobre la misma BD (mismo dir).
  301. dir := t.TempDir() // dummy para no confundir; la BD real es la de l
  302. _ = dir
  303. d2 := l.db // misma BD abierta
  304. l2 := NewLive(nil, d2, []RouterConfig{{ID: "ap1", Name: "AP Uno"}}, nil)
  305. if got := l2.ImpostorApproved(); len(got) != 1 || got[0] != "DE:AD:BE:EF:00:13" {
  306. t.Fatalf("la lista debe sobrevivir al reinicio; got %v", got)
  307. }
  308. }
  309. func TestImpostorRuleDisabledNoAlerts(t *testing.T) {
  310. l, _ := newImpostorLive(t)
  311. now := time.Now()
  312. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:20", "temiscira", now.Add(-40*time.Minute))
  313. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:20", "temiscira", now)
  314. l.SetImpostorRuleEnabled(false)
  315. if l.ImpostorRuleEnabled() {
  316. t.Fatal("la regla debe quedar desactivada")
  317. }
  318. l.EvalSsidImpostors()
  319. if got := impostorAlerts(l); len(got) != 0 {
  320. t.Fatalf("regla desactivada no debe alertar; alertas: %+v", got)
  321. }
  322. // Persistencia: un Live nuevo sobre la misma BD arranca desactivado.
  323. l2 := NewLive(nil, l.db, []RouterConfig{{ID: "ap1", Name: "AP Uno"}}, nil)
  324. if l2.ImpostorRuleEnabled() {
  325. t.Fatal("el interruptor debe sobrevivir al reinicio")
  326. }
  327. }
  328. func TestImpostorRuleDisableResolvesActive(t *testing.T) {
  329. l, _ := newImpostorLive(t)
  330. now := time.Now()
  331. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:21", "temiscira", now.Add(-40*time.Minute))
  332. insertScan(t, l, "ap1", "DE:AD:BE:EF:00:21", "temiscira", now)
  333. l.EvalSsidImpostors()
  334. if got := impostorAlerts(l); len(got) != 1 {
  335. t.Fatalf("debió alertar; alertas: %d", len(got))
  336. }
  337. l.SetImpostorRuleEnabled(false)
  338. if got := impostorAlerts(l); len(got) != 0 {
  339. t.Fatalf("desactivar debe resolver las activas; alertas: %+v", got)
  340. }
  341. if len(l.impostorActive) != 0 {
  342. t.Fatalf("tracking residual tras desactivar: %+v", l.impostorActive)
  343. }
  344. // Re-activar: la evidencia sigue ahí, vuelve a alertar.
  345. l.SetImpostorRuleEnabled(true)
  346. l.EvalSsidImpostors()
  347. if got := impostorAlerts(l); len(got) != 1 {
  348. t.Fatalf("re-activar debe re-alertar con evidencia vigente; alertas: %d", len(got))
  349. }
  350. }