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
Drone Remote ID over Wi-Fi Aware (NAN)
CIS-C0f9f27016da51
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 20c6423..33c463f 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -26,6 +26,8 @@<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /><uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />+ <!-- Android 13+: Wi-Fi Aware (drone Remote ID over NAN). -->+ <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" /><uses-permission android:name="android.permission.FOREGROUND_SERVICE" /><uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />diff --git a/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt b/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.ktindex b693507..dd4e887 100644--- a/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt@@ -41,6 +41,9 @@ object DeviceIntel {0x0B to "Just used", 0x0D to "Driving", 0x0E to "On a call")+ /** The standard of a drone's Remote ID heard over Wi-Fi Aware (NAN) rather than in a beacon. */+ const val WIFI_AWARE = "Wi-Fi Aware (NAN)"+/** Meshtastic's BLE service (Meshtastic firmware / app protocol docs). */private val MESHTASTIC_SERVICE = java.util.UUID.fromString("6ba1b218-15a8-461f-9fa8-5dcae273eafd")private const val MESH_NODE = "Mesh radio node (Meshtastic / MeshCore LoRa)"@@ -272,6 +275,7 @@ object DeviceIntel {val ssid = a.nameval type = when {w?.client == true -> "WiFi device (laptop, phone or camera on a network)"+ w?.standard == WIFI_AWARE -> "Drone Remote ID over Wi-Fi Aware"ssid.isNullOrEmpty() -> "Hidden WiFi network"TRAIN_SSID.containsMatchIn(ssid) -> "Train WiFi (passenger rail)"Regex("iphone|androidap|galaxy|pixel|hotspot|'s phone", RegexOption.IGNORE_CASE).containsMatchIn(ssid) -> "Phone hotspot"diff --git a/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt b/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.ktindex 229a47c..b485bb5 100644--- a/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt@@ -505,6 +505,8 @@ object SignatureEngine {Hit(Category.DRONE, "Drone broadcasting its French electronic ID (WiFi)", 95,"French \"signalement électronique\" vendor information element (OUI 6A:5C:35) in the WiFi beacon","Arrêté of 27 December 2019 (France); github.com/khancyr/droneID_FR")+ else if (a.wifi?.standard == DeviceIntel.WIFI_AWARE) Hit(Category.DRONE, "Drone broadcasting Remote ID (Wi-Fi Aware)", 95,+ "ASTM F3411 Remote ID message pack in a Wi-Fi Aware (NAN) service discovery", ASTM)else Hit(Category.DRONE, "Drone broadcasting Remote ID (WiFi)", 95,"ASTM F3411 vendor information element (OUI FA:0B:BC) in the WiFi beacon", ASTM)}diff --git a/app/src/main/java/com/rfsentinel/app/service/NanRemoteId.kt b/app/src/main/java/com/rfsentinel/app/service/NanRemoteId.ktnew file mode 100644index 0000000..c54f04d--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/service/NanRemoteId.kt@@ -0,0 +1,140 @@+package com.rfsentinel.app.service++import android.annotation.SuppressLint+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.content.pm.PackageManager+import android.net.wifi.aware.AttachCallback+import android.net.wifi.aware.DiscoverySessionCallback+import android.net.wifi.aware.PeerHandle+import android.net.wifi.aware.SubscribeConfig+import android.net.wifi.aware.SubscribeDiscoverySession+import android.net.wifi.aware.WifiAwareManager+import android.net.wifi.aware.WifiAwareSession+import android.os.Build+import android.os.Handler+import android.os.Looper+import android.util.Log+import com.rfsentinel.app.detect.Advert++/**+ * Drone Remote ID over Wi-Fi Aware (NAN), the WiFi transport many EU drones and newer DJI models+ * use, which a phone can't hear by ordinary WiFi scanning (after OpenDroneID's receiver-android,+ * Apache-2.0: written anew here). A passive subscription to the "org.opendroneid.remoteid"+ * service: listen only, nothing is published or sent to the drone.+ *+ * Each discovery's service info is [message counter][message pack], the same bytes that follow+ * the OUI and type in a Remote ID WiFi beacon, so each one is handed on as a WiFi advert carrying+ * that vendor element and goes through the usual WiFi Remote ID decoding. Wi-Fi Aware gives no+ * address or signal strength: each peer gets a stable made-up local address, and a nominal signal.+ */+class NanRemoteId(private val context: Context, private val onAdvert: (Advert) -> Unit) {++ private val handler = Handler(Looper.getMainLooper())+ private var session: WifiAwareSession? = null+ private var subscription: SubscribeDiscoverySession? = null+ private var running = false+ private var receiverOn = false+ /** Made-up addresses per peer (peer handles only mean something within a subscription). */+ private val peers = HashMap<Int, String>()++ private val stateReceiver = object : BroadcastReceiver() {+ override fun onReceive(c: Context, i: Intent) { if (running) { close(); attach() } }+ }++ fun start() {+ if (running || !supported(context)) return+ running = true+ runCatching {+ androidx.core.content.ContextCompat.registerReceiver(context, stateReceiver,+ IntentFilter(WifiAwareManager.ACTION_WIFI_AWARE_STATE_CHANGED), androidx.core.content.ContextCompat.RECEIVER_NOT_EXPORTED)+ receiverOn = true+ }+ attach()+ }++ fun stop() {+ running = false+ if (receiverOn) { runCatching { context.unregisterReceiver(stateReceiver) }; receiverOn = false }+ close()+ }++ private fun close() {+ runCatching { subscription?.close() }; subscription = null+ runCatching { session?.close() }; session = null+ peers.clear()+ }++ @SuppressLint("MissingPermission") // location (and nearby-WiFi on 13+) checked by the caller and on attach+ private fun attach() {+ val mgr = context.getSystemService(Context.WIFI_AWARE_SERVICE) as? WifiAwareManager ?: return+ if (!mgr.isAvailable) return // WiFi off: the state broadcast retries+ try {+ mgr.attach(object : AttachCallback() {+ override fun onAttached(s: WifiAwareSession) {+ if (!running) { s.close(); return }+ session = s+ subscribe(s)+ }+ override fun onAttachFailed() { Log.w(TAG, "Wi-Fi Aware attach failed") }+ }, handler)+ } catch (e: SecurityException) {+ Log.w(TAG, "Wi-Fi Aware not allowed: ${e.message}")+ }+ }++ @SuppressLint("MissingPermission")+ private fun subscribe(s: WifiAwareSession) {+ val config = SubscribeConfig.Builder()+ .setServiceName(SERVICE)+ .setSubscribeType(SubscribeConfig.SUBSCRIBE_TYPE_PASSIVE)+ .build()+ try {+ s.subscribe(config, object : DiscoverySessionCallback() {+ override fun onSubscribeStarted(sub: SubscribeDiscoverySession) {+ subscription = sub+ Log.i(TAG, "Listening for drone Remote ID over Wi-Fi Aware")+ }+ override fun onServiceDiscovered(peer: PeerHandle, info: ByteArray?, filter: List<ByteArray>?) {+ info?.let { onInfo(peer, it) }+ }+ override fun onSessionTerminated() { subscription = null }+ }, handler)+ } catch (e: SecurityException) {+ Log.w(TAG, "Wi-Fi Aware subscribe not allowed: ${e.message}")+ }+ }++ private fun onInfo(peer: PeerHandle, info: ByteArray) {+ if (info.size < 1 + com.rfsentinel.app.detect.RemoteId.MESSAGE_SIZE) return+ val mac = peers.getOrPut(peer.hashCode()) { madeUpAddress(peer.hashCode()) }+ onAdvert(advert(mac, info, System.currentTimeMillis()))+ }++ companion object {+ private const val TAG = "NanRemoteId"+ /** The ASTM F3411 Wi-Fi NAN service name. */+ const val SERVICE = "org.opendroneid.remoteid"+ /** Wi-Fi Aware discovery is on channel 6. */+ private const val NAN_MHZ = 2437+ /** No signal strength comes with a discovery. */+ private const val NOMINAL_RSSI = -75++ fun supported(context: Context): Boolean =+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&+ context.packageManager.hasSystemFeature(PackageManager.FEATURE_WIFI_AWARE)++ /** A WiFi advert carrying [info] as a Remote ID vendor element (OUI FA:0B:BC, type 0x0D). */+ internal fun advert(mac: String, info: ByteArray, now: Long): Advert {+ val ie = byteArrayOf(0xFA.toByte(), 0x0B, 0xBC.toByte(), 0x0D) + info+ return Advert(mac = mac, source = Advert.Source.WIFI, rssi = NOMINAL_RSSI, name = null,+ wifi = Advert.WifiInfo(NAN_MHZ, "", com.rfsentinel.app.detect.DeviceIntel.WIFI_AWARE, listOf(221 to ie)), timestamp = now)+ }++ /** A locally administered address for a peer, stable while its handle is. */+ internal fun madeUpAddress(id: Int): String =+ "0E:4E:" + (0 until 4).joinToString(":") { "%02X".format((id ushr (24 - 8 * it)) and 0xFF) }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex 6519e00..9b58f6e 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -167,6 +167,8 @@ class ScanForegroundService : Service() {private lateinit var bleEngine: BleScanEngineprivate lateinit var wifiEngine: WifiScanEngine+ /** Drone Remote ID over Wi-Fi Aware, on phones that have it. */+ private var nanRemoteId: NanRemoteId? = nullprivate val classified = ConcurrentHashMap<String, Classified>()private val lastAlerted = ConcurrentHashMap<String, Long>()@@ -314,6 +316,9 @@ class ScanForegroundService : Service() {// Re-evaluated on every start command, so Settings changes apply live.if (Prefs.bleEnabled(this)) { bleEngine.stop(); startBle() } else stopBle()if (Prefs.wifiEnabled(this)) startWifiPolling() else stopWifiPolling()+ if (Prefs.categoryEnabled(this, Category.DRONE) && NanRemoteId.supported(this) && nearbyWifiAllowed()) {+ if (nanRemoteId == null) nanRemoteId = NanRemoteId(this) { a -> pipeline.post { processPhone(a) } }.also { it.start() }+ } else { nanRemoteId?.stop(); nanRemoteId = null }// ESP32 boards on USB (OUI-Spy / GhostESP / Marauder): their reports join the same pipeline.com.rfsentinel.app.esp.EspBoards.start(this) { list -> pipeline.post { list.forEach(::processEsp) } }// A USB WiFi adapter in monitor mode (e.g. AWUS036ACS): access points and client devices.@@ -448,6 +453,10 @@ class ScanForegroundService : Service() {}}+ /** Wi-Fi Aware needs location, and the nearby-WiFi permission from Android 13. */+ private fun nearbyWifiAllowed() = hasFineLocation() && (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||+ ContextCompat.checkSelfPermission(this, android.Manifest.permission.NEARBY_WIFI_DEVICES) == PackageManager.PERMISSION_GRANTED)+private fun stopWifiPolling() {wifiPollJob?.cancel()wifiEngine.stop()@@ -1365,6 +1374,7 @@ class ScanForegroundService : Service() {com.rfsentinel.app.esp.HeardBy.usb.clear()com.rfsentinel.app.usb.ProbeIntel.clear()com.rfsentinel.app.data.ProbeLog.flush(this)+ nanRemoteId?.stop()bleEngine.stop()wifiEngine.stop()if (btStateReceiverRegistered) {diff --git a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.ktindex bcb8e5e..777dd7f 100644--- a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt@@ -312,8 +312,11 @@ class SetupActivity : AppCompatActivity() {}}if (missing.isEmpty() && optionalMissing.isNotEmpty()) {- para("Notifications are off - alerts will still sound, but won't appear in the notification shade.", small = true)- button("Allow notifications") { permissionLauncher.launch(optionalMissing.toTypedArray()) }+ val noAlerts = android.Manifest.permission.POST_NOTIFICATIONS in optionalMissing+ if (noAlerts) para("Notifications are off - alerts will still sound, but won't appear in the notification shade.", small = true)+ if (android.Manifest.permission.NEARBY_WIFI_DEVICES in optionalMissing)+ para("Nearby WiFi devices is off - drones sending their Remote ID over Wi-Fi Aware won't be heard.", small = true)+ button(if (noAlerts && optionalMissing.size == 1) "Allow notifications" else "Allow") { permissionLauncher.launch(optionalMissing.toTypedArray()) }}para("Tip: in Android's battery settings, set RF Sentinel to \"Unrestricted\" so scanning keeps running in your pocket.", small = true)knownCamerasNearMe()diff --git a/app/src/main/java/com/rfsentinel/app/util/Permissions.kt b/app/src/main/java/com/rfsentinel/app/util/Permissions.ktindex 49f09e3..7ea7899 100644--- a/app/src/main/java/com/rfsentinel/app/util/Permissions.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Permissions.kt@@ -20,9 +20,15 @@ object Permissions {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) add(Manifest.permission.BLUETOOTH_SCAN)}- /** Nice to have: without it scanning still works, alerts just aren't shown. */+ /**+ * Nice to have: without notifications scanning still works, alerts just aren't shown;+ * without nearby WiFi devices (Android 13+) drones' Remote ID over Wi-Fi Aware isn't heard.+ */fun optional(): List<String> = buildList {- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) add(Manifest.permission.POST_NOTIFICATIONS)+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ add(Manifest.permission.POST_NOTIFICATIONS)+ add(Manifest.permission.NEARBY_WIFI_DEVICES)+ }}fun missingRequired(context: Context): List<String> = required().filterNot { granted(context, it) }diff --git a/app/src/test/java/com/rfsentinel/app/service/NanRemoteIdTest.kt b/app/src/test/java/com/rfsentinel/app/service/NanRemoteIdTest.ktnew file mode 100644index 0000000..12095b3--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/service/NanRemoteIdTest.kt@@ -0,0 +1,35 @@+package com.rfsentinel.app.service++import com.rfsentinel.app.detect.Category+import com.rfsentinel.app.detect.DeviceIntel+import com.rfsentinel.app.detect.RemoteId+import com.rfsentinel.app.detect.SignatureEngine+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class NanRemoteIdTest {++ /** A Basic ID message: type 0, serial-number ID type, multirotor, then the ID text. */+ private fun basicId(id: String): ByteArray {+ val m = ByteArray(RemoteId.MESSAGE_SIZE)+ m[0] = 0x02 // message type 0 (Basic ID), protocol version 2+ m[1] = ((1 shl 4) or 2).toByte() // ID type 1 (serial), UA type 2 (helicopter / multirotor)+ id.toByteArray().copyInto(m, 2)+ return m+ }++ @Test+ fun aNanDiscoveryGoesThroughTheWifiRemoteIdPath() {+ // Service info: [counter][message pack: 0xF2, message size 25, count 1, message]+ val info = byteArrayOf(7, 0xF2.toByte(), 25, 1) + basicId("1581F5FJD123")+ val a = NanRemoteId.advert(NanRemoteId.madeUpAddress(0x12345678), info, 0L)+ assertEquals("0E:4E:12:34:56:78", a.mac)+ val hit = SignatureEngine.classify(a).first()+ assertEquals(Category.DRONE, hit.category)+ assertTrue(hit.label.contains("Wi-Fi Aware"))+ val ie = a.wifi!!.infoElements.first().second+ assertEquals("1581F5FJD123", RemoteId.decodeWifiIe(ie, null)?.uasId)+ assertEquals("Drone Remote ID over Wi-Fi Aware", DeviceIntel.identify(a, null).type)+ }+}