Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / RcsGbaBootstrap.kt

RcsGbaBootstrap.kt187 lines · 7.7 KiBRaw
1package com.vayunmathur.communicate.data.rcs
2
3import androidx.core.net.toUri
4import android.content.Context
5import android.net.Uri
6import android.telephony.CarrierConfigManager
7import android.telephony.SubscriptionManager
8import android.telephony.TelephonyManager
9import android.telephony.gba.TlsParams
10import android.telephony.gba.UaSecurityProtocolIdentifier
11import android.telephony.`TelephonyManager$BootstrapAuthenticationCallback`
12import com.vayunmathur.library.log.Log
13import java.util.concurrent.Executor
14import java.util.concurrent.Executors
15import kotlin.coroutines.resume
16import kotlinx.coroutines.suspendCancellableCoroutine
17import kotlinx.coroutines.withTimeoutOrNull
18
19/**
20 * Live GBA bootstrapping (3GPP TS 33.220) for FT-over-HTTP digest auth.
21 *
22 * Mirrors TestRcsApp's `GbaAuthenticationProvider.provideCredentials`, rebuilt
23 * without Guava/Apache-Http: carrier-config UA security params →
24 * `UaSecurityProtocolIdentifier` → `TelephonyManager.
25 * bootstrapAuthenticationRequest` → btId + key as the digest
26 * username/password (base64 key, exactly like the reference
27 * `GbaCredentials`).
28 *
29 * Reachability (verified against the SDK jar + AOSP main):
30 * - `android.telephony.gba.*` is absent from `android.jar`, so same-FQN
31 * `compileOnly` stubs (`library:aosp-stubs`) provide the compile surface
32 * and the framework provides the runtime classes — the same mechanism as
33 * the existing `SipDelegateManager` path. No reflection on the data path.
34 * - The request method itself lives on the SDK-visible `TelephonyManager`,
35 * so one reflective `getMethod` bridges it (identical precedent to
36 * `RcsHiddenApi.sipDelegateManager` — lint-clean).
37 * - The callback is a hidden *class*: subclassing (not Proxy) via the
38 * `$`-named stub, with virtual dispatch at runtime.
39 * - Permission is `PERFORM_IMS_SINGLE_REGISTRATION` (`internal|role`,
40 * SMS-role granted — declared in the manifest; TestRcsApp documents the
41 * same grant).
42 *
43 * Every failure (no privilege, hidden-API denial, modem refusal, timeout)
44 * returns null and the uploader degrades to [RcsGbaAuth.injected] / plain
45 * digest. Never throws.
46 */
47object RcsGbaBootstrap {
48 private const val TAG = "RcsGbaBootstrap"
49
50 /** Bound on the modem round trip (bootstrap can take seconds). */
51 private const val TIMEOUT_MS = 30_000L
52
53 // Carrier-config key strings (hidden constants; AOSP values verified).
54 private const val KEY_ORG = "gba_ua_security_organization_int"
55 private const val KEY_PROTOCOL = "gba_ua_security_protocol_int"
56 private const val KEY_CIPHER_SUITE = "gba_ua_tls_cipher_suite_int"
57
58 private val executor: Executor = Executors.newSingleThreadExecutor()
59
60 /**
61 * Bootstrap NAF credentials for [nafUrl] (the FT content-server URI).
62 * [force] re-bootstraps even with cached keys (post-401 retry, mirroring
63 * TestRcsApp's `GbaRequestExecutor`). Null on any failure.
64 */
65 suspend fun bootstrap(context: Context, nafUrl: String, force: Boolean): RcsGbaAuth.GbaCredentials? {
66 if (!RcsFeature.enabled || nafUrl.isBlank()) return null
67 return withTimeoutOrNull(TIMEOUT_MS) {
68 suspendCancellableCoroutine { cont ->
69 val done: (RcsGbaAuth.GbaCredentials?) -> Unit = { creds ->
70 if (cont.isActive) cont.resume(creds)
71 }
72 runCatching {
73 requestBootstrap(context.applicationContext, nafUrl, force, done)
74 }.onFailure {
75 Log.status(TAG, "GBA bootstrap setup failed", it)
76 done(null)
77 }
78 }
79 }
80 }
81
82 private fun requestBootstrap(
83 context: Context,
84 nafUrl: String,
85 force: Boolean,
86 done: (RcsGbaAuth.GbaCredentials?) -> Unit,
87 ) {
88 val subId = SubscriptionManager.getDefaultSmsSubscriptionId()
89 if (!SubscriptionManager.isValidSubscriptionId(subId)) {
90 done(null)
91 return
92 }
93 val tm = context.getSystemService(TelephonyManager::class.java)?.let { base ->
94 runCatching { base.createForSubscriptionId(subId) }.getOrNull() ?: base
95 } ?: run {
96 done(null)
97 return
98 }
99 val spId = buildSecurityProtocolId(context, subId) ?: run {
100 done(null)
101 return
102 }
103 val callback = object : `TelephonyManager$BootstrapAuthenticationCallback`() {
104 override fun onKeysAvailable(gbaKey: ByteArray, transactionId: String) {
105 if (gbaKey.isEmpty() || transactionId.isBlank()) {
106 done(null)
107 } else {
108 done(RcsGbaAuth.GbaCredentials(btId = transactionId, key = gbaKey))
109 }
110 }
111
112 override fun onAuthenticationFailure(reason: Int) {
113 Log.status(TAG, "GBA authentication failure reason=$reason")
114 done(null)
115 }
116 }
117 // One reflective hop: the method is @SystemApi/hidden on the
118 // SDK-visible TelephonyManager (same precedent as RcsHiddenApi).
119 val method = tm.javaClass.getMethod(
120 "bootstrapAuthenticationRequest",
121 Int::class.javaPrimitiveType,
122 Uri::class.java,
123 UaSecurityProtocolIdentifier::class.java,
124 Boolean::class.javaPrimitiveType,
125 Executor::class.java,
126 `TelephonyManager$BootstrapAuthenticationCallback`::class.java,
127 )
128 try {
129 method.invoke(
130 tm,
131 TelephonyManager.APPTYPE_ISIM,
132 nafUrl.toUri(),
133 spId,
134 force,
135 executor,
136 callback,
137 )
138 } catch (e: java.lang.reflect.InvocationTargetException) {
139 // Framework-side refusal (no privilege, modem error): degrade.
140 Log.status(TAG, "GBA request refused", e.cause ?: e)
141 done(null)
142 }
143 }
144
145 /**
146 * Build the UA security protocol id from carrier config (TestRcsApp
147 * `GbaAuthenticationProvider` logic): org/protocol/cipher-suite ints,
148 * defaulting the NULL suite to AES_128_CBC_SHA. Null when the config is
149 * unreadable.
150 */
151 private fun buildSecurityProtocolId(context: Context, subId: Int): UaSecurityProtocolIdentifier? {
152 return runCatching {
153 val ccm = context.getSystemService(CarrierConfigManager::class.java)
154 ?: return null
155 // The keyed getter is API 34+; on 31-33 read the whole bundle.
156 val bundle = try {
157 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
158 ccm.getConfigForSubId(subId, KEY_ORG, KEY_PROTOCOL, KEY_CIPHER_SUITE)
159 } else {
160 @Suppress("DEPRECATION")
161 ccm.getConfigForSubId(subId)
162 }
163 } catch (_: SecurityException) {
164 return null
165 } catch (_: Exception) {
166 return null
167 } ?: return null
168 val org = bundle.getInt(KEY_ORG, UaSecurityProtocolIdentifier.ORG_NONE)
169 val protocol = bundle.getInt(
170 KEY_PROTOCOL,
171 UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_HTTP_DIGEST_AUTHENTICATION,
172 )
173 var suite = bundle.getInt(KEY_CIPHER_SUITE, TlsParams.TLS_NULL_WITH_NULL_NULL)
174 if (suite == TlsParams.TLS_NULL_WITH_NULL_NULL) {
175 suite = TlsParams.TLS_RSA_WITH_AES_128_CBC_SHA
176 }
177 UaSecurityProtocolIdentifier.Builder()
178 .setOrg(org)
179 .setProtocol(protocol)
180 .setTlsCipherSuite(suite)
181 .build()
182 }.getOrElse {
183 Log.status(TAG, "GBA security-protocol build failed", it)
184 null
185 }
186 }
187}