share: bound peer-controlled parsing and guard launches
- Commit
f592990a26d5d089ae8910f18fee7c3747793bae- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-19 01:55 UTC (17 days ago)
- Parents
e3c54c3
Crash paths reachable from nearby peers, other apps and the OS: - BinaryPlist.readArray/readDict computed count * refSize in Int; a crafted bplist (refSize 8, count 2^29) wraps the product to a small value, passes the bounds check, then allocates a list/map sized by the raw count -> OutOfMemoryError, an Error that escapes every caller's catch (Exception) in the AirDrop ask/discover handlers. All length math is now Long. - Rust BYTES reassembly in session_part2 extended bytes_recvs with no total cap; a post-handshake peer streaming non-final chunks grows it until allocation failure aborts the process. Cap a reassembled sharing frame at MAX_FRAME_LEN and drop overruns. - ShareViewModel.handleShareIntent used the erased-generic getParcelableArrayListExtra pre-API-33; an ArrayList<String> in EXTRA_STREAM from any app passed the empty check and threw ClassCastException on first element use. Filter to real Uris. - ShareReceiveController.start let listen()/advertise() throws (bind, TLS) escape into an uncaught launch and left advertising wedged true; AirDrop startReceiving rethrew into the same scope. Both are now caught, logged and reset for a later retry. - ShareSaveActivity and ShareSendContent launched document pickers bare; a build without DocumentsUI throws ActivityNotFoundException. Both launches are now guarded. - ShareNative/ShareNativeDiscovery loaded share_nearby in a throwing init block: on a broken install the first failure made every later access throw NoClassDefFoundError, which the call sites' catch (UnsatisfiedLinkError) cannot match, and the BLE endpoint parsing and TcpTransport session-creation sites were unguarded. The load is now non-fatal and those sites guard the resulting UnsatisfiedLinkError (session creation surfaces an IOException the callers already catch). Verification: ./gradlew :share:testDevUnitTest and ./check share (run after this commit).
Diff
share/src/main/java/com/vayunmathur/share/domain/airdrop/BinaryPlist.kt
diff --git a/share/src/main/java/com/vayunmathur/share/domain/airdrop/BinaryPlist.kt b/share/src/main/java/com/vayunmathur/share/domain/airdrop/BinaryPlist.ktindex 7adeedfc8f..0f21f6dafd 100644--- a/share/src/main/java/com/vayunmathur/share/domain/airdrop/BinaryPlist.kt+++ b/share/src/main/java/com/vayunmathur/share/domain/airdrop/BinaryPlist.kt@@ -214,15 +214,15 @@ object BinaryPlist { 0x3 -> readReal(pos + 1, 8) 0x4 -> { val (len, start) = countAt(pos, info)- bytes.copyOfRange(start, checkedEnd(start, len))+ bytes.copyOfRange(start, checkedEnd(start, len.toLong())) } 0x5 -> { val (len, start) = countAt(pos, info)- String(bytes, start, checkedEnd(start, len) - start, Charsets.US_ASCII)+ String(bytes, start, checkedEnd(start, len.toLong()) - start, Charsets.US_ASCII) } 0x6 -> { val (len, start) = countAt(pos, info)- String(bytes, start, checkedEnd(start, len * 2) - start, Charsets.UTF_16BE)+ String(bytes, start, checkedEnd(start, len.toLong() * 2) - start, Charsets.UTF_16BE) } 0x8 -> readSized(pos + 1, info + 1) 0xA -> readArray(pos, info)@@ -243,13 +243,17 @@ object BinaryPlist { private fun readArray(pos: Int, info: Int): List<Any?> { val (count, start) = countAt(pos, info)- checkedEnd(start, count * refSize)+ // Long math: count * refSize in Int wraps (e.g. 2^29 * 8 == 0), which+ // let a crafted body pass the bounds check and then allocate a list+ // sized by the un-wrapped count -> OutOfMemoryError, an Error that+ // escapes every caller's catch (Exception).+ checkedEnd(start, count.toLong() * refSize) return List(count) { i -> readObject(readSized(start + i * refSize, refSize)) } } private fun readDict(pos: Int, info: Int): Map<String, Any?> { val (count, start) = countAt(pos, info)- checkedEnd(start, count * refSize * 2)+ checkedEnd(start, count.toLong() * refSize * 2) val map = LinkedHashMap<String, Any?>(count) for (i in 0 until count) { val key = readObject(readSized(start + i * refSize, refSize)) as? String@@ -269,7 +273,7 @@ object BinaryPlist { return count.toInt() to pos + 2 + size } - private fun checkedEnd(start: Int, len: Int): Int {+ private fun checkedEnd(start: Int, len: Long): Int { val end = start.toLong() + len if (len < 0 || end > offsetTableOffset) throw FormatException("object overruns") return end.toInt()
share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.kt
diff --git a/share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.kt b/share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.ktindex 3a8ebae461..e63c299750 100644--- a/share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.kt+++ b/share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.kt@@ -8,6 +8,7 @@ import com.vayunmathur.share.platform.IncomingTransfer import com.vayunmathur.share.platform.ReceivedFile import com.vayunmathur.share.platform.ReceivedFileStore import java.io.File+import java.io.IOException import java.io.OutputStream import java.net.InetAddress import java.net.InetSocketAddress@@ -225,12 +226,24 @@ class TcpTransport( // The side that dialled the socket is the Nearby Connections initiator: it sends // CONNECTION_REQUEST and drives UKEY2 as the client. The endpoint info and id are // the advertised ones, so the peer sees the identity it discovered.- val session = ShareSession(- localName = localName,- localEndpointInfo = localEndpointInfo,- localEndpointId = localEndpointId,- isInitiator = !incoming,- )+ // Native session creation throws UnsatisfiedLinkError (an Error, so the+ // callers' catch (Exception) misses it) when the .so cannot load; surface+ // it as an IOException they already handle.+ val session = try {+ ShareSession(+ localName = localName,+ localEndpointInfo = localEndpointInfo,+ localEndpointId = localEndpointId,+ isInitiator = !incoming,+ )+ } catch (e: LinkageError) {+ try {+ socket.close()+ } catch (_: Exception) {+ // Already broken; the failure below is the useful one.+ }+ throw IOException("native share library unavailable", e)+ } val conn = Connection( socket = socket, session = session,
share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt b/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.ktindex e10c80fa85..c1a3c86779 100644--- a/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt@@ -244,8 +244,12 @@ class ShareViewModel( val uris = if (Build.VERSION.SDK_INT >= 33) { intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri::class.java) } else {+ // The deprecated overload is erased-generic: any app can send an+ // ArrayList<String> in this extra, and the first element use would+ // throw ClassCastException. Keep only real Uris. @Suppress("DEPRECATION")- intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM)+ intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)+ ?.filterIsInstance<Uri>() } if (!uris.isNullOrEmpty()) setOutgoingUris(uris) }
share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.kt b/share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.ktindex 7718c89a30..2ec878758d 100644--- a/share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.kt@@ -101,7 +101,12 @@ class BleDiscoveryManager(private val context: Context) { val data = parseAdvertisementBytes(serviceData) ?: return null // `data` nests the Sharing blob inside the Nearby Connections envelope; the // envelope is what carries the peer's endpoint id.- val endpointInfo = ShareNativeDiscovery.nativeParseBleEndpointInfo(data) ?: run {+ val endpointInfo = try {+ ShareNativeDiscovery.nativeParseBleEndpointInfo(data)+ } catch (e: UnsatisfiedLinkError) {+ Log.error(TAG, "libshare_nearby unavailable — cannot parse endpoint info", e)+ return null+ } ?: run { Log.dev( TAG, "skipping $addr: not a NearbySharing endpoint payload (" +@@ -408,7 +413,12 @@ class BleDiscoveryManager(private val context: Context) { val payload = decodeAdvertisedPayload(serviceData, addr) ?: return null // Key on the advertised endpoint id, which is also what the mDNS leg // reports, so one device does not appear twice.- val endpointId = ShareNativeDiscovery.nativeParseBleEndpointId(payload.data) ?: addr+ val endpointId = try {+ ShareNativeDiscovery.nativeParseBleEndpointId(payload.data)+ } catch (e: UnsatisfiedLinkError) {+ Log.error(TAG, "libshare_nearby unavailable — cannot parse endpoint id", e)+ null+ } ?: addr return NearbyDevice( endpointId = endpointId, // Both names come from bytes already in hand: the endpoint-info blob, then
share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveController.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveController.kt b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveController.ktindex 2ff17c4f0e..5a816cc646 100644--- a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveController.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveController.kt@@ -247,6 +247,9 @@ object ShareReceiveController { * handles and partial files all go — but *posted notifications do*, so a stale Request * notification would offer an Accept that can never work. */+ // Startup spans socket, TLS and NSD/BLE layers, which throw undocumented+ // RuntimeExceptions as well as IOExceptions; both catches stay broad by design.+ @Suppress("TooGenericExceptionCaught") fun start(context: Context) { val app = context.applicationContext val p = ensure(app)@@ -268,16 +271,30 @@ object ShareReceiveController { if (swept > 0) Log.status(TAG, "swept $swept orphaned staged file(s)") // Before listen(), so a socket accepted immediately announces the identity we are // about to advertise rather than the transport's construction-time one.- p.transport.setLocalIdentity(localName, endpointInfo, p.endpointId)- val port = p.transport.listen()- // The WIFI_LAN port under _FC9F5ED42C8A._tcp, endpoint info in the `n` TXT- // attribute — the record a Quick Share device lists us from.- p.nsd.advertise(p.endpointId, endpointInfo, port)- // The same blob inside a Nearby Connections BleAdvertisement under 0xFEF3.- p.ble.startAdvertising(p.endpointId, endpointInfo)- Log.status(TAG, "receiving as \"$localName\" on port $port")+ try {+ p.transport.setLocalIdentity(localName, endpointInfo, p.endpointId)+ val port = p.transport.listen()+ // The WIFI_LAN port under _FC9F5ED42C8A._tcp, endpoint info in the `n` TXT+ // attribute — the record a Quick Share device lists us from.+ p.nsd.advertise(p.endpointId, endpointInfo, port)+ // The same blob inside a Nearby Connections BleAdvertisement under 0xFEF3.+ p.ble.startAdvertising(p.endpointId, endpointInfo)+ Log.status(TAG, "receiving as \"$localName\" on port $port")+ } catch (e: Exception) {+ // Bind/TLS/advertise failures must not crash the receive service or+ // wedge `advertising` on: a later start() retries from scratch.+ advertising = false+ Log.error(TAG, "failed to start receiving", e)+ return+ }+ }+ scope.launch {+ try {+ p.airDrop.startReceiving()+ } catch (e: Exception) {+ Log.error(TAG, "failed to start AirDrop receiving", e)+ } }- scope.launch { p.airDrop.startReceiving() } } /**
share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.kt b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.ktindex 5a9ff56fc2..f199b3f886 100644--- a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.kt@@ -1,5 +1,6 @@ package com.vayunmathur.share.platform.receive +import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Build@@ -100,15 +101,21 @@ class ShareSaveActivity : ComponentActivity() { return } val name = displayName(next)- creator.launch(- Intent(Intent.ACTION_CREATE_DOCUMENT).apply {- addCategory(Intent.CATEGORY_OPENABLE)- // Per file, from its own name: a batch can mix a photo and a PDF, and the picker- // uses the type to choose a default location and a sensible extension.- type = ReceivedFileStore.mimeTypeOf(name)- putExtra(Intent.EXTRA_TITLE, name)- }- )+ // A build without DocumentsUI has no handler for CREATE_DOCUMENT.+ try {+ creator.launch(+ Intent(Intent.ACTION_CREATE_DOCUMENT).apply {+ addCategory(Intent.CATEGORY_OPENABLE)+ // Per file, from its own name: a batch can mix a photo and a PDF, and the picker+ // uses the type to choose a default location and a sensible extension.+ type = ReceivedFileStore.mimeTypeOf(name)+ putExtra(Intent.EXTRA_TITLE, name)+ }+ )+ } catch (_: ActivityNotFoundException) {+ Log.status(TAG, "no document picker on this device")+ finish()+ } } /** The staged file's name. These are our own `FileProvider` URIs, so it is the last segment. */
share/src/main/java/com/vayunmathur/share/protocol/ShareNative.kt
diff --git a/share/src/main/java/com/vayunmathur/share/protocol/ShareNative.kt b/share/src/main/java/com/vayunmathur/share/protocol/ShareNative.ktindex 252d94026c..be8170c3cb 100644--- a/share/src/main/java/com/vayunmathur/share/protocol/ShareNative.kt+++ b/share/src/main/java/com/vayunmathur/share/protocol/ShareNative.kt@@ -118,7 +118,15 @@ internal object ShareNative { external fun nativeDestroy(handle: Long) init {- System.loadLibrary("share_nearby")+ // Do not let a missing/ABI-mismatched .so fail class initialization: that+ // turns every later access into NoClassDefFoundError, which the call sites'+ // catch (UnsatisfiedLinkError) cannot match. A failed load leaves the class+ // usable; native calls then throw UnsatisfiedLinkError, which they do catch.+ try {+ System.loadLibrary("share_nearby")+ } catch (_: UnsatisfiedLinkError) {+ // Native calls fail individually and are handled at their call sites.+ } } /** `p000\eanu.java:8` — the device type `:share` advertises. */
share/src/main/java/com/vayunmathur/share/protocol/ShareNativeDiscovery.kt
diff --git a/share/src/main/java/com/vayunmathur/share/protocol/ShareNativeDiscovery.kt b/share/src/main/java/com/vayunmathur/share/protocol/ShareNativeDiscovery.ktindex fc4953c385..f0f6242fcf 100644--- a/share/src/main/java/com/vayunmathur/share/protocol/ShareNativeDiscovery.kt+++ b/share/src/main/java/com/vayunmathur/share/protocol/ShareNativeDiscovery.kt@@ -156,6 +156,14 @@ internal object ShareNativeDiscovery { external fun nativeParsePresenceAdvertName(advertBytes: ByteArray): String? init {- System.loadLibrary("share_nearby")+ // Do not let a missing/ABI-mismatched .so fail class initialization: that+ // turns every later access into NoClassDefFoundError, which the call sites'+ // catch (UnsatisfiedLinkError) cannot match. A failed load leaves the class+ // usable; native calls then throw UnsatisfiedLinkError, which they do catch.+ try {+ System.loadLibrary("share_nearby")+ } catch (_: UnsatisfiedLinkError) {+ // Native calls fail individually and are handled at their call sites.+ } } }
share/src/main/java/com/vayunmathur/share/ui/ShareSendContent.kt
diff --git a/share/src/main/java/com/vayunmathur/share/ui/ShareSendContent.kt b/share/src/main/java/com/vayunmathur/share/ui/ShareSendContent.ktindex 54e48a28ed..f228729c52 100644--- a/share/src/main/java/com/vayunmathur/share/ui/ShareSendContent.kt+++ b/share/src/main/java/com/vayunmathur/share/ui/ShareSendContent.kt@@ -1,4 +1,5 @@ package com.vayunmathur.share.ui+import android.content.ActivityNotFoundException import android.net.Uri import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts@@ -61,7 +62,14 @@ fun ShareSendContent( OutgoingFilesCard( uris = uiState.outgoingUris, displayNames = uiState.outgoingDisplayNames,- onPickFiles = { pickerLauncher.launch(arrayOf("*/*")) },+ onPickFiles = {+ // A build without DocumentsUI has no handler for the picker.+ try {+ pickerLauncher.launch(arrayOf("*/*"))+ } catch (_: ActivityNotFoundException) {+ // Nothing to pick with on this device; the screen stays.+ }+ }, onClear = actions::clearOutgoing, ) }
share/src/main/rust/src/session_part2.rs
diff --git a/share/src/main/rust/src/session_part2.rs b/share/src/main/rust/src/session_part2.rsindex d2f1f56890..b173dfe25b 100644--- a/share/src/main/rust/src/session_part2.rs+++ b/share/src/main/rust/src/session_part2.rs@@ -41,6 +41,18 @@ impl Session { let have = self.bytes_recvs.entry(payload_id).or_default(); let gap = offset > have.len(); if offset == have.len() {+ // Unbounded reassembly lets a peer grow this buffer with non-final+ // chunks until allocation failure aborts the process. A sharing+ // frame is a control message; one frame's cap is generous for it.+ if have.len().saturating_add(chunk.body().len()) > frame::MAX_FRAME_LEN {+ let have_len = have.len();+ let _ = self.bytes_recvs.remove(&payload_id);+ self.note(format!(+ "BYTES {payload_id} over frame cap: have {have_len}, chunk {}",+ chunk.body().len()+ ));+ return 0;+ } have.extend_from_slice(chunk.body()); } if gap {