RF Sentinel (RFSentinel): free, open-source police detector app for Android. Spots police body cams, Flock ALPR cameras, AirTag trackers, Remote ID drones, smart glasses and fake cell towers from Bluetooth LE and WiFi. No root.
Kotlin airtagalprandroidandroid-autoanti-surveillancebluetooth-low-energybody-cameracounter-surveillancedrone-detectionflock-safetyimsi-catcher-detectorpolice-detectorpolice-scannerprivacyremote-idrtl-sdrsdrsurveillance-detectiontracker-detectionwifi
USB WiFi: beacon clock uptime, security, WiFi generation, antenna streams, country, connected devices and data heard on device pages and History; a router's frames no longer give its clients its signal
CIS-C0afb00bd12311
diff --git a/app/src/main/java/com/rfsentinel/app/detect/Advert.kt b/app/src/main/java/com/rfsentinel/app/detect/Advert.ktindex 6ba8736..7c4c339 100644--- a/app/src/main/java/com/rfsentinel/app/detect/Advert.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/Advert.kt@@ -49,7 +49,13 @@ class Advert(/** FlipDeFlock's probe skeleton hash of a client's probe requests (USB adapter). */val probeSkeleton: Long? = null,/** Its latest run of wildcard probes (USB adapter): how steadily it probes ([ProbeBehaviour]). */- val probeRun: ProbeBehaviour.Run? = null+ val probeRun: ProbeBehaviour.Run? = null,+ /** The access point a client talks to (USB adapter). */+ val bssid: String? = null,+ /** When an access point's WiFi came up, from its beacon clock (USB adapter). */+ val upSince: Long? = null,+ /** Data bytes it sent while the USB adapter heard it. */+ val dataBytes: Long = 0)val isBle get() = source == Source.BLEdiff --git a/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt b/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.ktindex 30be96b..4f5de89 100644--- a/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt@@ -523,6 +523,8 @@ object DeviceIntel {ap.deviceName?.let { facts += "AP device name (WPS)" to it }ap.deviceKind?.let { facts += "Device kind (WPS)" to it }ap.ciscoApName?.let { facts += "Cisco AP name" to it }+ ap.streams?.let { facts += "Antenna streams" to "${it}x$it" }+ ap.country?.let { facts += "Country set in router" to it }if (ap.equipmentVendors.isNotEmpty()) facts += "Equipment maker (vendor IEs)" to ap.equipmentVendors.joinToString { shortVendor(it) }if (ap.chipsetVendors.isNotEmpty()) facts += "WiFi chipset (vendor IEs)" to ap.chipsetVendors.joinToString { shortVendor(it) }diff --git a/app/src/main/java/com/rfsentinel/app/detect/HackerWatch.kt b/app/src/main/java/com/rfsentinel/app/detect/HackerWatch.ktindex 18b1ed4..4cced9d 100644--- a/app/src/main/java/com/rfsentinel/app/detect/HackerWatch.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/HackerWatch.kt@@ -169,7 +169,7 @@ object HackerWatch {/*** Same network name from two different makers' hardware that disagree on security (one* open, one protected): one of them isn't what it claims to be. Mesh nodes and dual-band- * boxes share a maker and are never flagged. Phone scans only (they report security).+ * boxes share a maker and are never flagged. Only sightings that read the security (phone scan, USB adapter).*/@Synchronizedfun evilTwin(a: Advert): Hit? {diff --git a/app/src/main/java/com/rfsentinel/app/detect/WifiFingerprint.kt b/app/src/main/java/com/rfsentinel/app/detect/WifiFingerprint.ktindex 9398f59..82baca6 100644--- a/app/src/main/java/com/rfsentinel/app/detect/WifiFingerprint.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/WifiFingerprint.kt@@ -26,7 +26,11 @@ object WifiFingerprint {val deviceKind: String? = null,val ciscoApName: String? = null,/** IEEE registrants of vendor-specific IE OUIs (chipset / equipment makers). */- val ieVendors: List<String> = emptyList()+ val ieVendors: List<String> = emptyList(),+ /** Spatial streams its radio receives (2 = 2x2 MIMO). */+ val streams: Int? = null,+ /** The country its WiFi is set for (Country element). */+ val country: String? = null) {/** e.g. "NETGEAR R7000" or "TP-Link Archer AX55", null when WPS said nothing useful. */val model: String?@@ -72,7 +76,15 @@ object WifiFingerprint {.distinct().mapNotNull { oui -> VendorDb.macVendor(oui.chunked(2).joinToString(":") + ":00:00:00") }.distinct()- return info.copy(ieVendors = owners)+ // VHT MCS map: 2 bits a stream, 3 = not supported; else HT's per-stream MCS masks (bytes 3-6).+ val vht = ies.firstOrNull { it.first == 191 && it.second.size >= 6 }?.second?.let { d ->+ val map = Bytes.u8(d, 4) or (Bytes.u8(d, 5) shl 8)+ (0 until 8).count { (map shr (2 * it)) and 3 != 3 }+ }+ val ht = ies.firstOrNull { it.first == 45 && it.second.size >= 7 }?.second?.let { d -> (3..6).count { d[it].toInt() != 0 } }+ val country = ies.firstOrNull { it.first == 7 && it.second.size >= 2 }?.second+ ?.let { String(it, 0, 2, Charsets.US_ASCII) }?.takeIf { c -> c.all { it in 'A'..'Z' } }+ return info.copy(ieVendors = owners, streams = (vht ?: ht)?.takeIf { it in 1..8 }, country = country)}private fun isWps(d: ByteArray) = d.size >= 4 && d[0] == WPS_OUI[0] && d[1] == WPS_OUI[1] && d[2] == WPS_OUI[2] && d[3] == 0x04.toByte()diff --git a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.ktindex 99dd96e..e5e8ec3 100644--- a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt+++ b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt@@ -46,6 +46,8 @@ object DeviceRegistry {/** Weight of each new RSSI reading (0..1): 0.3 settles in about a second of adverts. */private const val RSSI_SMOOTHING = 0.3private const val SMOOTH_RESET_MS = 10_000L+ /** A client heard talking to a network within this long still counts as connected to it. */+ private const val CONNECTED_MS = 5 * 60_000Lprivate const val ROTATION_WINDOW_MS = 30_000L/** Pinpointing: readings kept per flagged device, their spacing, and how often the fit is redone. */private const val LOCATE_MAX = 400@@ -137,6 +139,13 @@ object DeviceRegistry {var locatedAt = 0Lvar readingsSinceFit = 0var broadcast: GeoSample? = null+ // From a USB WiFi adapter, kept apart from [advert] so the phone's own scan doesn't wipe them:+ /** When its WiFi came up (beacon clock). */+ var upSince: Long? = null+ /** The access point this client talks to. */+ var joined: String? = null+ /** Data it sent while the adapter heard it. */+ var dataBytes = 0L}private val tracks = ConcurrentHashMap<String, Track>()@@ -177,6 +186,11 @@ object DeviceRegistry {t.hits = mergeHits(t, hits, now)remoteId?.let { t.remoteId = it }broadcast?.let { t.broadcast = it }+ a.wifi?.let { w ->+ w.upSince?.let { t.upSince = it }+ w.bssid?.let { t.joined = it }+ if (w.dataBytes > 0) t.dataBytes = w.dataBytes+ }// Smooth for the displayed signal, distance and radar; a jump after a pause is taken as is.t.smoothRssi = if (t.smoothRssi.isNaN() || now - t.lastSeen > SMOOTH_RESET_MS) a.rssi.toDouble()else t.smoothRssi + RSSI_SMOOTHING * (a.rssi - t.smoothRssi)@@ -474,7 +488,7 @@ object DeviceRegistry {listOfNotNull(t.linkedFrom?.let { "Previous address" to "$it (address rotated, same advert fingerprint)" },t.role?.let { "Patrol-kit role" to it }- ) + if (full && Advert.Source.WIFI in t.sources) sameApFacts(t) else emptyList(),+ ) + if (full && Advert.Source.WIFI in t.sources) sameApFacts(t) + usbWifiFacts(t) else emptyList(),hits = t.hits,rssi = t.rssi,bestRssi = t.bestRssi,@@ -508,6 +522,40 @@ object DeviceRegistry {}?.let { DeviceIntel.hiddenOnType(it) }}+ /**+ * What a USB adapter in monitor mode heard: how long the router's WiFi had been on, which network a+ * device talks to and which devices talk to a network, and how much data. Saved with the page (History).+ */+ private fun usbWifiFacts(t: Track): List<Pair<String, String>> {+ val out = mutableListOf<Pair<String, String>>()+ t.upSince?.let {+ val at = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.SHORT, java.text.DateFormat.SHORT).format(java.util.Date(it))+ out += "WiFi on for" to "${upFor(t.lastSeen - it)} when last heard, since $at (beacon clock: usually since power-on)"+ }+ t.joined?.let { ap ->+ out += "Connected to" to (tracks[ap]?.name?.let { "\"$it\" ($ap)" } ?: ap)+ }+ // Read without locking the others, like [hiddenRouterType]: this runs under [t]'s lock.+ val clients = tracks.values.filter { o -> o !== t && o.joined == t.mac && t.lastSeen - o.lastSeen < CONNECTED_MS }+ if (clients.isNotEmpty()) out += "Devices connected" to "${clients.size}: " + clients.take(8).joinToString("; ") { o ->+ o.identity.type + (o.vendor?.let { " - ${DeviceIntel.shortVendor(it)}" } ?: "") + " (${o.mac})"+ } + if (clients.size > 8) "; +${clients.size - 8} more" else ""+ if (t.dataBytes > 0) out += "Data heard by USB adapter" to when {+ t.dataBytes < 1_000_000 -> "${(t.dataBytes + 999) / 1000} KB"+ else -> String.format(java.util.Locale.US, "%.1f MB", t.dataBytes / 1e6)+ }+ return out+ }++ private fun upFor(ms: Long): String {+ val min = (ms / 60_000).coerceAtLeast(0)+ return when {+ min < 60 -> "$min min"+ min < 48 * 60 -> "${min / 60} h ${min % 60} min"+ else -> "${min / 1440} days"+ }+ }+/*** Other networks broadcast by the same access point (see* [WifiFingerprint.sameAccessPoint]). For a hidden network this usuallydiff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex 33cc2f5..4b97d23 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -848,9 +848,11 @@ class ScanForegroundService : Service() {// A client has no network name; its WPS device name or model says what it is.mac = mac, source = Advert.Source.WIFI, rssi = m.rssi, name = m.ssid ?: m.wps?.label,addressType = com.rfsentinel.app.detect.AddressType.ofWifi(mac),- wifi = Advert.WifiInfo(m.frequencyMhz, "", null, emptyList(), client = !m.isAccessPoint,+ wifi = Advert.WifiInfo(m.frequencyMhz, m.capabilities, m.standard, m.infoElements, client = !m.isAccessPoint,wildcardProbe = m.wildcardProbe, flockProbeIe = m.flockProbeIe, probeSkeleton = m.probeSkeleton,- probeRun = m.probeRun),+ probeRun = m.probeRun,+ bssid = m.bssid?.takeIf { !m.isAccessPoint }?.let { com.rfsentinel.app.util.MacUtil.normalize(it) }?.takeIf { it != mac },+ upSince = m.upSince, dataBytes = m.dataBytes),timestamp = now)linkOutbox?.add(LinkCodec.Sighting(LinkCodec.KIND_USB, a, probed = m.probedSsids, fingerprint = m.fingerprint, hidden = m.hiddenNetwork))diff --git a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.ktindex 39298f7..d5e6484 100644--- a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt@@ -27,6 +27,12 @@ class MonitorFrames {var wildcard = false; var flockIe = false/** How steadily it sends wildcard probes ([com.rfsentinel.app.detect.ProbeBehaviour]). */var probeRate: com.rfsentinel.app.detect.ProbeBehaviour.Counter? = null+ /** An access point's latest beacon elements (refreshed every [IES_REFRESH_MS]) and its "protected" capability bit. */+ var ies: List<Pair<Int, ByteArray>>? = null; var iesAt = 0L; var privacy = false+ /** When its WiFi started, from the beacon clock (TSF, microseconds since the radio came up). */+ var upSince: Long? = null+ /** Data-frame bytes it sent while heard. */+ var dataBytes = 0L// Per-window counters for driver diagnostics (debug builds).var winHits = 0; var winMeasured = 0; var winMax = -128; var winSum = 0Lvar winOfdm = 0; var winA = -128; var winB = -128@@ -59,10 +65,12 @@ class MonitorFrames {val a1 = d + 4; val a2 = d + 10; val a3 = d + 16val check = AntennaCheck.listeningif (check) AntennaCheck.frame(b, a2, rssi, pathA, pathB, now)- fun touch(at: Int, ap: Boolean, ch: Int = channel): Sighting? {+ // [sent]: the device transmitted this frame, so its signal is this device's (not so for the receiver of a router's frame).+ fun touch(at: Int, ap: Boolean, ch: Int = channel, sent: Boolean = true): Sighting? {if (!isReal(b, at)) return nullval m = mac(b, at)val s = sightings.getOrPut(m) { Sighting(m, ap) }+ val rssi = rssi.takeIf { sent }// Strongest reading of the last couple of seconds, so a device that drove off fades.if (rssi != null && (!s.measured || rssi > s.rssi || now - s.rssiAt > RSSI_WINDOW_MS)) {s.rssi = rssi; s.rssiAt = now; s.measured = true@@ -70,7 +78,7 @@ class MonitorFrames {s.channel = ch; s.lastSeen = nows.winHits++if (rssi != null) { s.winMeasured++; s.winSum += rssi; if (rssi > s.winMax) s.winMax = rssi }- if (pathA != null || pathB != null) {+ if (sent && (pathA != null || pathB != null)) {s.winOfdm++pathA?.let { if (it > s.winA) s.winA = it }; pathB?.let { if (it > s.winB) s.winB = it }}@@ -94,6 +102,13 @@ class MonitorFrames {else if (it.ssid == null) it.ssid = nameif (it.ssid == null) pendingNames.remove(it.mac)?.let { n -> it.ssid = n }ies.wps?.let { w -> it.wps = w }+ // Fixed fields: the 8-byte beacon clock (microseconds since its WiFi came up), interval, capability info.+ val tsf = (0 until 8).fold(0L) { acc, k -> acc or (u8(d + 24 + k).toLong() shl (8 * k)) }+ if (tsf in 1 until MAX_TSF_US) it.upSince = now - tsf / 1000+ if (it.ies == null || now - it.iesAt > IES_REFRESH_MS) {+ it.ies = elements(b, d + 36, ProbeIntel.withoutFcs(b, d, end)); it.iesAt = now+ it.privacy = (u8(d + 34) and 0x10) != 0+ }if (check) AntennaCheck.heardAp(it.mac, it.ssid, it.channel, rssi, now)}// One transmitter answering under many network names: a Karma / PineAP fake access point.@@ -127,10 +142,15 @@ class MonitorFrames {if (captureClients) touch(a2, ap = false)?.let { it.bssid = mac(b, a3) }}}- 2 -> if (captureClients) when {- toDs == 1 && fromDs == 0 -> touch(a2, ap = false)?.let { it.bssid = mac(b, a1) }- toDs == 0 && fromDs == 1 -> touch(a1, ap = false)?.let { it.bssid = mac(b, a2) }- else -> touch(a2, ap = false)+ 2 -> {+ val size = end - d+ if (captureClients) when {+ toDs == 1 && fromDs == 0 -> touch(a2, ap = false)?.let { it.bssid = mac(b, a1); it.dataBytes += size }+ toDs == 0 && fromDs == 1 -> touch(a1, ap = false, sent = false)?.let { it.bssid = mac(b, a2) }+ else -> touch(a2, ap = false)+ }+ // Sent by the router to one of its devices.+ if (toDs == 0 && fromDs == 1) sightings[mac(b, a2)]?.let { it.dataBytes += size }}}}@@ -186,7 +206,12 @@ class MonitorFrames {hiddenNetwork = s.hidden,wildcardProbe = s.wildcard,flockProbeIe = s.flockIe,- probeRun = s.probeRate?.run()+ probeRun = s.probeRate?.run(),+ infoElements = s.ies.orEmpty(),+ capabilities = s.ies?.let { capabilities(it, s.privacy) } ?: "",+ standard = s.ies?.let { standard(it) },+ upSince = s.upSince,+ dataBytes = s.dataBytes)}sightings.entries.removeAll { now - it.value.lastSeen > pruneMs }@@ -260,6 +285,63 @@ class MonitorFrames {fun validSsid(s: String) = s.isNotEmpty() && s.length <= 32 && s.none { it < ' ' || it == '�' }private const val MAX_PROBED = 16+ private const val IES_REFRESH_MS = 10_000L+ /** A beacon clock past 5 years is junk (a corrupt frame), not uptime. */+ private const val MAX_TSF_US = 5L * 365 * 86_400 * 1_000_000++ /** The elements of a frame body as (id, payload), like Android's scan results; an extension element (255) keeps its extension ID as first byte. */+ internal fun elements(b: ByteArray, from: Int, end: Int): List<Pair<Int, ByteArray>> {+ val out = ArrayList<Pair<Int, ByteArray>>()+ var i = from+ while (i + 2 <= end) {+ val len = b[i + 1].toInt() and 0xff+ if (i + 2 + len > end) break+ out += (b[i].toInt() and 0xff) to b.copyOfRange(i + 2, i + 2 + len)+ i += 2 + len+ }+ return out+ }++ /** Android's scan-result security text ("[RSN-PSK][ESS]") from the RSN / WPA elements, so a USB sighting reads like the phone's own. */+ internal fun capabilities(ies: List<Pair<Int, ByteArray>>, privacy: Boolean): String {+ val rsn = ies.firstOrNull { it.first == 48 }?.second+ val wpa = ies.firstOrNull { (id, d) -> id == 221 && d.size >= 4 && d[0].toInt() == 0 && d[1].toInt() == 0x50 &&+ (d[2].toInt() and 0xff) == 0xF2 && d[3].toInt() == 1 }?.second+ val parts = listOfNotNull(wpa?.let { "[WPA-${akms(it, 4) ?: "?"}]" }, rsn?.let { "[RSN-${akms(it, 0) ?: "?"}]" })+ return when {+ parts.isNotEmpty() -> parts.joinToString("") + "[ESS]"+ privacy -> "[WEP][ESS]"+ else -> "[ESS]"+ }+ }++ // Key management suites (IEEE 802.11 table 9-151; the WPA element uses 1 and 2 the same way).+ private val AKM = mapOf(1 to "EAP", 3 to "EAP", 5 to "EAP", 11 to "EAP", 12 to "EAP", 13 to "EAP",+ 2 to "PSK", 4 to "PSK", 6 to "PSK", 8 to "SAE", 9 to "SAE", 24 to "SAE", 25 to "SAE", 18 to "OWE")++ /** "PSK", "PSK+SAE", "EAP"... from an RSN body at [start]: version, group cipher, pairwise ciphers, then the key management list. */+ private fun akms(d: ByteArray, start: Int): String? {+ fun u16(i: Int) = (d[i].toInt() and 0xff) or ((d[i + 1].toInt() and 0xff) shl 8)+ var i = start + 6+ if (i + 2 > d.size) return null+ i += 2 + 4 * u16(i)+ if (i + 2 > d.size) return null+ val n = u16(i); i += 2+ return (0 until n).mapNotNull { k -> d.getOrNull(i + 4 * k + 3)?.let { AKM[it.toInt() and 0xff] } }+ .distinct().joinToString("+").ifEmpty { null }+ }++ /** The WiFi generation its beacon announces, in the phone scan's words. */+ internal fun standard(ies: List<Pair<Int, ByteArray>>): String {+ fun ext(id: Int) = ies.any { it.first == 255 && it.second.isNotEmpty() && (it.second[0].toInt() and 0xff) == id }+ return when {+ ext(108) -> "WiFi 7 (802.11be)"+ ext(35) -> "WiFi 6 (802.11ax)"+ ies.any { it.first == 191 } -> "WiFi 5 (802.11ac)"+ ies.any { it.first == 45 } -> "WiFi 4 (802.11n)"+ else -> "Legacy (802.11a/b/g)"+ }+ }/** Centre frequency of a 20 MHz WiFi channel, 0 when unknown; a 6 GHz channel comes as its MHz already. */fun frequencyOf(ch: Int): Int = when (ch) {diff --git a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.ktindex 64be470..52f9a85 100644--- a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt@@ -36,7 +36,15 @@ data class MonitorSighting(/** Its probe requests carried the Wi-Fi Alliance element Flock cameras send ([MonitorFrames.Ies.flockIe]). */val flockProbeIe: Boolean = false,/** Its latest run of wildcard probes: how steadily it probes ([com.rfsentinel.app.detect.ProbeBehaviour]). */- val probeRun: com.rfsentinel.app.detect.ProbeBehaviour.Run? = null+ val probeRun: com.rfsentinel.app.detect.ProbeBehaviour.Run? = null,+ /** An access point's beacon elements, security text and WiFi generation, read like the phone's own scan. */+ val infoElements: List<Pair<Int, ByteArray>> = emptyList(),+ val capabilities: String = "",+ val standard: String? = null,+ /** When its WiFi came up, from the beacon clock. */+ val upSince: Long? = null,+ /** Data bytes it sent while heard. */+ val dataBytes: Long = 0)/**diff --git a/app/src/test/java/com/rfsentinel/app/usb/MonitorBeaconIntelTest.kt b/app/src/test/java/com/rfsentinel/app/usb/MonitorBeaconIntelTest.ktnew file mode 100644index 0000000..a2c92db--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/usb/MonitorBeaconIntelTest.kt@@ -0,0 +1,111 @@+package com.rfsentinel.app.usb++import com.rfsentinel.app.detect.Advert+import com.rfsentinel.app.detect.DeviceIntel+import com.rfsentinel.app.detect.WifiFingerprint+import com.rfsentinel.app.service.DeviceRegistry+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class MonitorBeaconIntelTest {++ private fun mac(s: String) = s.split(":").map { it.toInt(16).toByte() }.toByteArray()+ private fun ie(id: Int, vararg v: Int) = byteArrayOf(id.toByte(), v.size.toByte()) + v.map { it.toByte() }.toByteArray()++ private val ap = "00:30:44:11:22:33"+ private val laptop = "3c:22:fb:00:00:02"+ private val hours3 = 3L * 3600 * 1_000_000++ /** A beacon: clock [tsf] (µs), capability [cap], then [elements]. */+ private fun beacon(tsf: Long, cap: Int, elements: ByteArray): ByteArray {+ val h = ByteArray(24); h[0] = 0x80.toByte()+ mac("ff:ff:ff:ff:ff:ff").copyInto(h, 4); mac(ap).copyInto(h, 10); mac(ap).copyInto(h, 16)+ val fixed = ByteArray(12)+ for (k in 0 until 8) fixed[k] = (tsf shr (8 * k)).toByte()+ fixed[8] = 100; fixed[10] = cap.toByte()+ return h + fixed + ie(0, *"IBR900-233".map { it.code }.toIntArray()) + elements+ }++ private fun data(toDs: Boolean, a1: String, a2: String, size: Int): ByteArray {+ val h = ByteArray(size); h[0] = 0x08; h[1] = if (toDs) 0x01 else 0x02+ mac(a1).copyInto(h, 4); mac(a2).copyInto(h, 10); mac(ap).copyInto(h, 16)+ return h+ }++ // RSN: version 1, group CCMP, 1 pairwise CCMP, 2 key managements PSK + SAE.+ private val rsnPskSae = ie(48, 1, 0, 0, 0x0F, 0xAC, 4, 1, 0, 0, 0x0F, 0xAC, 4, 2, 0, 0, 0x0F, 0xAC, 2, 0, 0x0F, 0xAC, 8)+ // HT capabilities: info, A-MPDU, MCS set with 2 streams.+ private val ht2 = ie(45, *IntArray(26).also { it[3] = 0xFF; it[4] = 0xFF })+ // VHT capabilities: info, then RX MCS map 0xFFFA (streams 1-2).+ private val vht2 = ie(191, 0, 0, 0, 0, 0xFA, 0xFF, 0, 0, 0xFA, 0xFF, 0, 0)++ @Test+ fun beaconGivesUptimeSecurityGenerationStreamsAndCountry() {+ val t = MonitorFrames()+ val now = 10_000_000L+ val b = beacon(hours3, 0x11, rsnPskSae + ht2 + vht2 + ie(7, 'U'.code, 'S'.code, 0x20))+ t.frame(b, 0, b.size, 36, -60, now)+ val s = t.drain(now, 5000).single()+ assertEquals(now - hours3 / 1000, s.upSince)+ assertEquals("[RSN-PSK+SAE][ESS]", s.capabilities)+ assertEquals("WPA3", DeviceIntel.security(s.capabilities))+ assertEquals("WiFi 5 (802.11ac)", s.standard)+ val info = WifiFingerprint.parse(s.infoElements)+ assertEquals(2, info.streams)+ assertEquals("US", info.country)+ }++ @Test+ fun securityTextMatchesThePhoneScan() {+ val eap = ie(48, 1, 0, 0, 0x0F, 0xAC, 4, 1, 0, 0, 0x0F, 0xAC, 4, 1, 0, 0, 0x0F, 0xAC, 1).let { MonitorFrames.elements(it, 0, it.size) }+ assertTrue(MonitorFrames.capabilities(eap, true).contains("EAP"))+ assertEquals("WEP (insecure)", DeviceIntel.security(MonitorFrames.capabilities(emptyList(), true)))+ assertEquals("Open (no password)", DeviceIntel.security(MonitorFrames.capabilities(emptyList(), false)))+ // A broken element still reads as protected, never as open.+ assertEquals("WPA2", DeviceIntel.security(MonitorFrames.capabilities(listOf(48 to byteArrayOf(1, 0)), true)))+ }++ @Test+ fun clientsAreLinkedAndTheRoutersFramesDontLendThemItsSignal() {+ val t = MonitorFrames()+ val b = beacon(hours3, 0x11, rsnPskSae)+ t.frame(b, 0, b.size, 36, -40, 0)+ val up = data(true, ap, laptop, 300)+ t.frame(up, 0, up.size, 36, -85, 10)+ val down = data(false, laptop, ap, 1500)+ t.frame(down, 0, down.size, 36, -40, 20)+ val byMac = t.drain(20, 5000).associateBy { it.mac }+ val client = byMac.getValue(laptop)+ assertEquals(ap, client.bssid)+ assertEquals(-85, client.rssi) // not the router's -40+ assertEquals(300L, client.dataBytes)+ assertEquals(1500L, byMac.getValue(ap).dataBytes)+ }++ @Test+ fun devicePageShowsTheLinkBothWaysAndTheUptime() {+ DeviceRegistry.startSession()+ try {+ val now = System.currentTimeMillis()+ val apMac = "00:30:44:11:22:33"; val clientMac = "3C:22:FB:00:00:02"+ DeviceRegistry.report(Advert(apMac, Advert.Source.WIFI, -60, "IBR900-233",+ wifi = Advert.WifiInfo(5180, "[RSN-PSK][ESS]", null, emptyList(), upSince = now - 3 * 3_600_000L, dataBytes = 2_500_000)),+ emptyList(), DeviceIntel.Identity("Vehicle / cellular router", emptyList()), "CradlePoint, Inc", null, null, now)+ DeviceRegistry.report(Advert(clientMac, Advert.Source.WIFI, -70, null,+ wifi = Advert.WifiInfo(5180, "", null, emptyList(), client = true, bssid = apMac)),+ emptyList(), DeviceIntel.Identity("Laptop", emptyList()), "Panasonic", null, null, now)+ // The phone's own scan of the router (no USB fields) doesn't wipe them.+ DeviceRegistry.report(Advert(apMac, Advert.Source.WIFI, -60, "IBR900-233",+ wifi = Advert.WifiInfo(5180, "[RSN-PSK][ESS]", null, emptyList())),+ emptyList(), DeviceIntel.Identity("Vehicle / cellular router", emptyList()), "CradlePoint, Inc", null, null, now)+ val router = DeviceRegistry.get(apMac)!!.facts.toMap()+ assertTrue(router["WiFi on for"]!!.startsWith("3 h 0 min"))+ assertEquals("1: Laptop - Panasonic ($clientMac)", router["Devices connected"])+ assertEquals("2.5 MB", router["Data heard by USB adapter"])+ assertEquals("\"IBR900-233\" ($apMac)", DeviceRegistry.get(clientMac)!!.facts.toMap()["Connected to"])+ } finally {+ DeviceRegistry.clear()+ }+ }+}