communicate: live GBA bootstrap via stub-linked TelephonyManager API
- Commit
47a255df0daac95a99d2e7e5c017fb339e73ea9f- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-26 23:48 UTC (2 months ago)
- Parents
a6b03f4
Diff
communicate/src/main/AndroidManifest.xml
diff --git a/communicate/src/main/AndroidManifest.xml b/communicate/src/main/AndroidManifest.xmlindex 4430c18586..1bed82f365 100644--- a/communicate/src/main/AndroidManifest.xml+++ b/communicate/src/main/AndroidManifest.xml@@ -11,6 +11,8 @@ <uses-permission android:name="android.permission.WRITE_SMS" /> <uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" />+ <!-- Granted by the SMS role (internal|role): single-reg SIP delegate + GBA bootstrap. -->+ <uses-permission android:name="android.permission.PERFORM_IMS_SINGLE_REGISTRATION" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransferHttp.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransferHttp.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransferHttp.ktindex b747acdd1c..005fe2bd4c 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransferHttp.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransferHttp.kt@@ -60,10 +60,10 @@ object RcsFileTransferHttp { .firstOrNull { it.key.equals("WWW-Authenticate", ignoreCase = true) } ?.value?.firstOrNull() ?: return@runCatching null- // 2. Authenticated multipart POST (tid + File). GBA-shaped creds- // when a privileged build injected them, else the plain-digest- // fallback (empty password). Live GBA bootstrapping is unreachable- // from a non-privileged app (hidden API blocklist — see RcsGbaAuth).+ // 2. Authenticated multipart POST (tid + File). Credentials, in+ // preference order: live GBA bootstrap ([RcsGbaBootstrap], needs+ // the SMS-role permission), injected creds (privileged push /+ // tests), then the plain-digest fallback (empty password). val boundary = "rcsft${UUID.randomUUID().toString().replace("-", "").take(16)}" val tid = UUID.randomUUID().toString() val multipart = buildMultipart(@@ -73,7 +73,8 @@ object RcsFileTransferHttp { mime = attachment.mimeType, bytes = bytes, )- val gba = RcsGbaAuth.injected+ val gba = RcsGbaBootstrap.bootstrap(context, server, force = false)+ ?: RcsGbaAuth.injected val auth = digestAuthHeader( challenge = challenge, method = "POST",@@ -83,7 +84,7 @@ object RcsFileTransferHttp { android.util.Base64.encodeToString(it.key, android.util.Base64.NO_WRAP) }.orEmpty(), )- val response = NetworkClient.performRequest(+ var response = NetworkClient.performRequest( url = server, method = "POST", headers = mapOf(@@ -94,6 +95,35 @@ object RcsFileTransferHttp { body = multipart, useSystemTrust = true, )+ // 401 with a live bootstrap available: force re-bootstrapping and+ // retry once (mirrors TestRcsApp's GbaRequestExecutor).+ if (response.status == 401) {+ val fresh = RcsGbaBootstrap.bootstrap(context, server, force = true)+ if (fresh != null) {+ val retryAuth = digestAuthHeader(+ challenge = response.headers.entries+ .firstOrNull { it.key.equals("WWW-Authenticate", ignoreCase = true) }+ ?.value?.firstOrNull() ?: challenge,+ method = "POST",+ uri = server,+ username = fresh.btId,+ password = android.util.Base64.encodeToString(+ fresh.key, android.util.Base64.NO_WRAP,+ ),+ )+ response = NetworkClient.performRequest(+ url = server,+ method = "POST",+ headers = mapOf(+ "Content-Type" to "multipart/form-data; boundary=$boundary",+ "Authorization" to retryAuth,+ "User-Agent" to "Communicate-RCS/1.0",+ ),+ body = multipart,+ useSystemTrust = true,+ )+ }+ } if (!response.isSuccess) return@runCatching null // Server answers with the file URL (plain or XML-wrapped). Regex("https?://[^\\s\"'<>]+").find(response.body)?.value
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaAuth.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaAuth.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaAuth.ktindex 1b9839ac8f..3108a6d92b 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaAuth.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaAuth.kt@@ -4,27 +4,19 @@ package com.vayunmathur.communicate.data.rcs * GBA-shaped credentials + digest auth for FT-over-HTTP (3GPP TS 33.220 / * RFC 2617). *- * Why there is no live GBA bootstrap here: TestRcsApp's- * `GbaAuthenticationProvider` calls- * `TelephonyManager.bootstrapAuthenticationRequest` directly, but that API is- * `@SystemApi`/hidden — absent from the compile SDK, and the request path- * goes through the internal `ITelephony.getITelephony()`, which is on the- * hidden-API blocklist (enforced at runtime on Android 12+, and a lint error- * on this target SDK). The callback is a hidden *class*, not an interface, so- * the Proxy bridge used in [RcsHiddenApi] cannot reach it either. A- * non-privileged app cannot bootstrap GBA keys, full stop.+ * Live bootstrapping lives in [RcsGbaBootstrap] (stub-linked+ * `TelephonyManager.bootstrapAuthenticationRequest`, SMS-role permission).+ * This object holds:+ * - [GbaCredentials]: bootstrapped NAF credentials (btId + key), from live+ * bootstrap or privileged injection ([injected]).+ * - [digestResponse]/[digestAuthorizationHeader]: the qop=auth construction+ * both the GBA and the plain-digest paths share, unit-tested against the+ * RFC 2617 known-answer vector. *- * What this object does instead:- * - [GbaCredentials] carries bootstrapped NAF credentials (btId + key) for- * the day a privileged path provides them (system-permission build, carrier- * service injection). [RcsFileTransferHttp] prefers them when set.- * - [digestResponse] is the qop=auth response hash both the GBA and the- * plain-digest paths share, unit-tested against the RFC 2617 known-answer- * vector.- *- * Until then uploads use the plain-digest fallback (empty password), exactly- * like a client whose GBA challenge fails — the server either accepts or the- * upload degrades, never crashes.+ * When bootstrapping is unavailable (no privilege, modem refusal), uploads+ * use the plain-digest fallback (empty password), exactly like a client+ * whose GBA challenge fails — the server either accepts or the upload+ * degrades, never crashes. */ object RcsGbaAuth { /** Bootstrapped NAF credentials: digest username + raw key. */
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaBootstrap.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaBootstrap.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaBootstrap.ktnew file mode 100644index 0000000000..e6992db807--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaBootstrap.kt@@ -0,0 +1,176 @@+package com.vayunmathur.communicate.data.rcs++import android.content.Context+import android.net.Uri+import android.telephony.CarrierConfigManager+import android.telephony.SubscriptionManager+import android.telephony.TelephonyManager+import android.telephony.gba.TlsParams+import android.telephony.gba.UaSecurityProtocolIdentifier+import android.telephony.`TelephonyManager$BootstrapAuthenticationCallback`+import android.util.Log+import java.util.concurrent.Executor+import java.util.concurrent.Executors+import kotlin.coroutines.resume+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.withTimeoutOrNull++/**+ * Live GBA bootstrapping (3GPP TS 33.220) for FT-over-HTTP digest auth.+ *+ * Mirrors TestRcsApp's `GbaAuthenticationProvider.provideCredentials`, rebuilt+ * without Guava/Apache-Http: carrier-config UA security params →+ * `UaSecurityProtocolIdentifier` → `TelephonyManager.+ * bootstrapAuthenticationRequest` → btId + key as the digest+ * username/password (base64 key, exactly like the reference+ * `GbaCredentials`).+ *+ * Reachability (verified against the SDK jar + AOSP main):+ * - `android.telephony.gba.*` is absent from `android.jar`, so same-FQN+ * `compileOnly` stubs (`library:rcs-stubs`) provide the compile surface+ * and the framework provides the runtime classes — the same mechanism as+ * the existing `SipDelegateManager` path. No reflection on the data path.+ * - The request method itself lives on the SDK-visible `TelephonyManager`,+ * so one reflective `getMethod` bridges it (identical precedent to+ * `RcsHiddenApi.sipDelegateManager` — lint-clean).+ * - The callback is a hidden *class*: subclassing (not Proxy) via the+ * `$`-named stub, with virtual dispatch at runtime.+ * - Permission is `PERFORM_IMS_SINGLE_REGISTRATION` (`internal|role`,+ * SMS-role granted — declared in the manifest; TestRcsApp documents the+ * same grant).+ *+ * Every failure (no privilege, hidden-API denial, modem refusal, timeout)+ * returns null and the uploader degrades to [RcsGbaAuth.injected] / plain+ * digest. Never throws.+ */+object RcsGbaBootstrap {+ private const val TAG = "RcsGbaBootstrap"++ /** Bound on the modem round trip (bootstrap can take seconds). */+ private const val TIMEOUT_MS = 30_000L++ // Carrier-config key strings (hidden constants; AOSP values verified).+ private const val KEY_ORG = "gba_ua_security_organization_int"+ private const val KEY_PROTOCOL = "gba_ua_security_protocol_int"+ private const val KEY_CIPHER_SUITE = "gba_ua_tls_cipher_suite_int"++ private val executor: Executor = Executors.newSingleThreadExecutor()++ /**+ * Bootstrap NAF credentials for [nafUrl] (the FT content-server URI).+ * [force] re-bootstraps even with cached keys (post-401 retry, mirroring+ * TestRcsApp's `GbaRequestExecutor`). Null on any failure.+ */+ suspend fun bootstrap(context: Context, nafUrl: String, force: Boolean): RcsGbaAuth.GbaCredentials? {+ if (!RcsFeature.enabled || nafUrl.isBlank()) return null+ return withTimeoutOrNull(TIMEOUT_MS) {+ suspendCancellableCoroutine { cont ->+ val done: (RcsGbaAuth.GbaCredentials?) -> Unit = { creds ->+ if (cont.isActive) cont.resume(creds)+ }+ runCatching {+ requestBootstrap(context.applicationContext, nafUrl, force, done)+ }.onFailure {+ Log.w(TAG, "GBA bootstrap setup failed", it)+ done(null)+ }+ }+ }+ }++ private fun requestBootstrap(+ context: Context,+ nafUrl: String,+ force: Boolean,+ done: (RcsGbaAuth.GbaCredentials?) -> Unit,+ ) {+ val subId = SubscriptionManager.getDefaultSmsSubscriptionId()+ if (!SubscriptionManager.isValidSubscriptionId(subId)) {+ done(null)+ return+ }+ val tm = context.getSystemService(TelephonyManager::class.java)?.let { base ->+ runCatching { base.createForSubscriptionId(subId) }.getOrNull() ?: base+ } ?: run {+ done(null)+ return+ }+ val spId = buildSecurityProtocolId(context, subId) ?: run {+ done(null)+ return+ }+ val callback = object : `TelephonyManager$BootstrapAuthenticationCallback`() {+ override fun onKeysAvailable(gbaKey: ByteArray, transactionId: String) {+ if (gbaKey.isEmpty() || transactionId.isBlank()) {+ done(null)+ } else {+ done(RcsGbaAuth.GbaCredentials(btId = transactionId, key = gbaKey))+ }+ }++ override fun onAuthenticationFailure(reason: Int) {+ Log.w(TAG, "GBA authentication failure reason=$reason")+ done(null)+ }+ }+ // One reflective hop: the method is @SystemApi/hidden on the+ // SDK-visible TelephonyManager (same precedent as RcsHiddenApi).+ val method = tm.javaClass.getMethod(+ "bootstrapAuthenticationRequest",+ Int::class.javaPrimitiveType,+ Uri::class.java,+ UaSecurityProtocolIdentifier::class.java,+ Boolean::class.javaPrimitiveType,+ Executor::class.java,+ `TelephonyManager$BootstrapAuthenticationCallback`::class.java,+ )+ try {+ method.invoke(+ tm,+ TelephonyManager.APPTYPE_ISIM,+ Uri.parse(nafUrl),+ spId,+ force,+ executor,+ callback,+ )+ } catch (e: java.lang.reflect.InvocationTargetException) {+ // Framework-side refusal (no privilege, modem error): degrade.+ Log.w(TAG, "GBA request refused", e.cause ?: e)+ done(null)+ }+ }++ /**+ * Build the UA security protocol id from carrier config (TestRcsApp+ * `GbaAuthenticationProvider` logic): org/protocol/cipher-suite ints,+ * defaulting the NULL suite to AES_128_CBC_SHA. Null when the config is+ * unreadable.+ */+ private fun buildSecurityProtocolId(context: Context, subId: Int): UaSecurityProtocolIdentifier? {+ return runCatching {+ val ccm = context.getSystemService(CarrierConfigManager::class.java)+ ?: return null+ val bundle = runCatching {+ ccm.getConfigForSubId(subId, KEY_ORG, KEY_PROTOCOL, KEY_CIPHER_SUITE)+ }.getOrNull() ?: return null+ val org = bundle.getInt(KEY_ORG, UaSecurityProtocolIdentifier.ORG_NONE)+ val protocol = bundle.getInt(+ KEY_PROTOCOL,+ UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_HTTP_DIGEST_AUTHENTICATION,+ )+ var suite = bundle.getInt(KEY_CIPHER_SUITE, TlsParams.TLS_NULL_WITH_NULL_NULL)+ if (suite == TlsParams.TLS_NULL_WITH_NULL_NULL) {+ suite = TlsParams.TLS_RSA_WITH_AES_128_CBC_SHA+ }+ UaSecurityProtocolIdentifier.Builder()+ .setOrg(org)+ .setProtocol(protocol)+ .setTlsCipherSuite(suite)+ .build()+ }.getOrElse {+ Log.w(TAG, "GBA security-protocol build failed", it)+ null+ }+ }+}
library/rcs-stubs/src/main/java/android/telephony/TelephonyManager$BootstrapAuthenticationCallback.java
diff --git a/library/rcs-stubs/src/main/java/android/telephony/TelephonyManager$BootstrapAuthenticationCallback.java b/library/rcs-stubs/src/main/java/android/telephony/TelephonyManager$BootstrapAuthenticationCallback.javanew file mode 100644index 0000000000..8b0c367751--- /dev/null+++ b/library/rcs-stubs/src/main/java/android/telephony/TelephonyManager$BootstrapAuthenticationCallback.java@@ -0,0 +1,29 @@+package android.telephony;++/**+ * Compile-only stub of the framework's {@code @SystemApi} nested class+ * {@code android.telephony.TelephonyManager.BootstrapAuthenticationCallback}.+ *+ * The outer {@code TelephonyManager} ships in the public SDK (so it cannot+ * be stubbed — the SDK bootclasspath wins), but this nested callback is+ * {@code @hide} and absent from {@code android.jar}. Declared here as a+ * top-level class whose binary name matches the framework nested class, so+ * compile-time references link and runtime links against the real framework+ * class. Kotlin callers import it with backticks:+ * {@code import android.telephony.`TelephonyManager$BootstrapAuthenticationCallback`}.+ *+ * Not packaged; the real class is provided by the framework at runtime.+ */+public class TelephonyManager$BootstrapAuthenticationCallback {+ public TelephonyManager$BootstrapAuthenticationCallback() {+ throw new RuntimeException("Stub");+ }++ public void onKeysAvailable(byte[] gbaKey, String transactionId) {+ throw new RuntimeException("Stub");+ }++ public void onAuthenticationFailure(int reason) {+ throw new RuntimeException("Stub");+ }+}
library/rcs-stubs/src/main/java/android/telephony/gba/TlsParams.java
diff --git a/library/rcs-stubs/src/main/java/android/telephony/gba/TlsParams.java b/library/rcs-stubs/src/main/java/android/telephony/gba/TlsParams.javanew file mode 100644index 0000000000..b8c171ad98--- /dev/null+++ b/library/rcs-stubs/src/main/java/android/telephony/gba/TlsParams.java@@ -0,0 +1,15 @@+package android.telephony.gba;++/**+ * Compile-only stub of the framework's {@code @SystemApi}+ * {@code android.telephony.gba.TlsParams}. Mirrors the AOSP constants used+ * for GBA bootstrapping. Not packaged; the real class is provided by the+ * framework at runtime.+ */+public class TlsParams {+ public static final int TLS_NULL_WITH_NULL_NULL = 0x0000;+ public static final int TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F;+ public static final int TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C;++ public @interface TlsCipherSuite {}+}
library/rcs-stubs/src/main/java/android/telephony/gba/UaSecurityProtocolIdentifier.java
diff --git a/library/rcs-stubs/src/main/java/android/telephony/gba/UaSecurityProtocolIdentifier.java b/library/rcs-stubs/src/main/java/android/telephony/gba/UaSecurityProtocolIdentifier.javanew file mode 100644index 0000000000..c8469f6a65--- /dev/null+++ b/library/rcs-stubs/src/main/java/android/telephony/gba/UaSecurityProtocolIdentifier.java@@ -0,0 +1,44 @@+package android.telephony.gba;++/**+ * Compile-only stub of the framework's {@code @SystemApi}+ * {@code android.telephony.gba.UaSecurityProtocolIdentifier}. Mirrors the+ * AOSP surface used for GBA bootstrapping (org/protocol/cipher-suite+ * constants + Builder). Not packaged; the real class is provided by the+ * framework at runtime.+ */+public final class UaSecurityProtocolIdentifier {+ public static final int ORG_NONE = 0;+ public static final int ORG_3GPP = 0x01;+ public static final int ORG_3GPP2 = 0x02;+ public static final int ORG_OMA = 0x03;+ public static final int ORG_GSMA = 0x04;+ public static final int ORG_LOCAL = 0xFF;++ public static final int UA_SECURITY_PROTOCOL_3GPP_HTTP_DIGEST_AUTHENTICATION = 2;++ public @interface OrganizationCode {}+ public @interface UaSecurityProtocol3gpp {}++ public static final class Builder {+ public Builder() {+ throw new RuntimeException("Stub");+ }++ public Builder setOrg(@OrganizationCode int orgCode) {+ throw new RuntimeException("Stub");+ }++ public Builder setProtocol(@UaSecurityProtocol3gpp int protocol) {+ throw new RuntimeException("Stub");+ }++ public Builder setTlsCipherSuite(@TlsParams.TlsCipherSuite int cs) {+ throw new RuntimeException("Stub");+ }++ public UaSecurityProtocolIdentifier build() {+ throw new RuntimeException("Stub");+ }+ }+}