Modern Apps git

← Modern-Apps.git

euicc: fixes

Commit
65523888b8abc6823ad07602e53e8598b37ec325
Author
vayun-mathur <[email protected]>
When
2026-09-26 22:33 UTC (2 months ago)
Parents
e58ddbf

Diff

euicc/src/main/AndroidManifest.xml
diff --git a/euicc/src/main/AndroidManifest.xml b/euicc/src/main/AndroidManifest.xmlindex 639cd6e335..37f41115f7 100644--- a/euicc/src/main/AndroidManifest.xml+++ b/euicc/src/main/AndroidManifest.xml@@ -51,6 +51,35 @@             </intent-filter>         </activity> +        <!--+          Standard eSIM universal link handler:+          https://esimsetup.android.com/esim_qrcode_provisioning?carddata=<code>.+          Scanners fire ACTION_VIEW on this URL and the LPA declaring the host+path+          receives it instead of a browser. Deliberately NOT gated by+          BIND_EUICC_SERVICE: that permission constrains the caller, and a+          third-party app holds no signature permission, so gating this would make+          the handoff unopenable. It carries no eUICC capability itself — it only+          seeds the normal AddSim/Download flow, which needs no privilege to+          display and fails gracefully where there is no eUICC.+        -->+        <activity+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:name=".platform.AddEsimActivity"+            android:exported="true"+            android:excludeFromRecents="true"+            android:taskAffinity=""+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.VIEW" />+                <category android:name="android.intent.category.DEFAULT" />+                <category android:name="android.intent.category.BROWSABLE" />+                <data+                    android:scheme="https"+                    android:host="esimsetup.android.com"+                    android:path="/esim_qrcode_provisioning" />+            </intent-filter>+        </activity>+         <service             android:name=".service.EuiccManagerService"             android:exported="true"
euicc/src/main/java/com/vayunmathur/euicc/Navigation.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/Navigation.kt b/euicc/src/main/java/com/vayunmathur/euicc/Navigation.ktindex 2856be1be2..bd4f50133d 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/Navigation.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/Navigation.kt@@ -1,6 +1,7 @@ package com.vayunmathur.euicc  import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember import com.vayunmathur.euicc.platform.EuiccViewModel import com.vayunmathur.euicc.ui.ActivationCodeScreen import com.vayunmathur.euicc.ui.AddSimScreen@@ -16,8 +17,15 @@ import com.vayunmathur.library.util.MorphPage import com.vayunmathur.library.util.rememberNavBackStack  @Composable-fun Navigation(viewModel: EuiccViewModel) {-    val backStack = rememberNavBackStack<Route>(Route.Home)+fun Navigation(viewModel: EuiccViewModel, start: Route? = null) {+    // A cross-app handoff (e.g. camera's "Add eSIM") lands mid-flow: seed Home underneath+    // so back from the entry point reaches the profile list instead of an empty stack.+    // Null means a plain launch — start on Home exactly as before.+    val initial = remember(start) {+        if (start == null || start == Route.Home) arrayOf<Route>(Route.Home)+        else arrayOf(Route.Home, start)+    }+    val backStack = rememberNavBackStack(*initial)      /**      * Leaving the activation flow: drop every step of it at once rather than popping back
euicc/src/main/java/com/vayunmathur/euicc/platform/AddEsimActivity.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/platform/AddEsimActivity.kt b/euicc/src/main/java/com/vayunmathur/euicc/platform/AddEsimActivity.ktnew file mode 100644index 0000000000..141f34661d--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/platform/AddEsimActivity.kt@@ -0,0 +1,43 @@+package com.vayunmathur.euicc.platform++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import com.vayunmathur.euicc.Navigation+import com.vayunmathur.euicc.Route+import com.vayunmathur.euicc.ui.looksLikeActivationCode+import com.vayunmathur.library.intents.euicc.EsimLink+import com.vayunmathur.library.ui.DynamicTheme++/**+ * Permission-free handler for the standard eSIM universal link:+ * `https://esimsetup.android.com/esim_qrcode_provisioning?carddata=<activation-code>`.+ *+ * This is the platform-standard handoff (the same URL Google's own LPA flow uses):+ * a scanner builds the link from the QR payload and fires `ACTION_VIEW`, and the+ * LPA whose manifest declares the host+path receives it instead of a browser.+ *+ * This exists alongside [LuiActivity] because that entry point cannot serve here:+ * its `BIND_EUICC_SERVICE` gate constrains the *caller*, and a third-party app+ * holds no signature permission — the platform itself is the only caller that can+ * reach it. This activity carries no gate, so anyone holding the scanned code can+ * open it.+ *+ * A valid `carddata` lands straight on the download flow ([Route.Download]); a+ * missing or malformed one lands on [Route.AddSim] so the user can type the code+ * in by hand instead of staring at Home with no path forward.+ */+class AddEsimActivity : ComponentActivity() {+    private val viewModel: EuiccViewModel by viewModels()++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        val code = intent?.data?.getQueryParameter(EsimLink.CARDDATA_PARAM)?.trim().orEmpty()+        val start: Route =+            if (looksLikeActivationCode(code)) Route.Download(code) else Route.AddSim+        setContent { DynamicTheme { Navigation(viewModel, start) } }+    }+}
euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.kt b/euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.ktindex db76de7d42..186266e078 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.kt@@ -1,6 +1,7 @@ package com.vayunmathur.euicc.platform  import android.app.Application+import android.util.Log import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue@@ -11,6 +12,8 @@ import com.vayunmathur.euicc.data.EuiccInfo import com.vayunmathur.euicc.data.Notification import com.vayunmathur.euicc.data.Profile import com.vayunmathur.euicc.telephony.EuiccChannelManager+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext@@ -32,6 +35,8 @@ data class EuiccScreenState( @kotlinx.serialization.Serializable private data class DownloadResult(val success: Boolean = false, val message: String = "") +private const val TAG = "EuiccViewModel"+ class EuiccViewModel(app: Application) : AndroidViewModel(app) {     private val channelManager = EuiccChannelManager(app)     private val json = Json { ignoreUnknownKeys = true }@@ -48,6 +53,10 @@ class EuiccViewModel(app: Application) : AndroidViewModel(app) {         private set      init {+        // SM-DP+ servers authenticate TLS under the GSMA CI PKI as well as public+        // CAs, so downloads need the ESIM bundle (system roots + GSMA CI root).+        // Both entry activities create this ViewModel before any download runs.+        NetworkClient.init(app, TrustBundle.ESIM)         reload()     } @@ -73,12 +82,22 @@ class EuiccViewModel(app: Application) : AndroidViewModel(app) {                 onSuccess = { raw ->                     val result = runCatching { json.decodeFromString<DownloadResult>(raw) }.getOrNull()                     when {-                        result == null -> DownloadState.Failed(null)+                        result == null -> {+                            // Error strings only — no activation data or crypto material.+                            Log.e(TAG, "download failed: unreadable native result")+                            DownloadState.Failed(null)+                        }                         result.success -> DownloadState.Complete(null)-                        else -> DownloadState.Failed(result.message.ifBlank { null })+                        else -> {+                            Log.e(TAG, "download failed: ${result.message.ifBlank { "<empty>" }}")+                            DownloadState.Failed(result.message.ifBlank { null })+                        }                     }                 },-                onFailure = { DownloadState.Failed(it.message) },+                onFailure = {+                    Log.e(TAG, "download failed: ${it.message}", it)+                    DownloadState.Failed(it.message)+                },             )             // The eUICC changed either way: a success installed a profile, and a failure may             // still have left a notification behind.
euicc/src/main/rust/src/download.rs
diff --git a/euicc/src/main/rust/src/download.rs b/euicc/src/main/rust/src/download.rsindex 9dccae2a47..7dc3957dd7 100644--- a/euicc/src/main/rust/src/download.rs+++ b/euicc/src/main/rust/src/download.rs@@ -13,7 +13,7 @@ use jni::JNIEnv;  use crate::jni::store_data;-use crate::{es10, es9p};+use crate::{asn1, es10, es9p};  /// A parsed SGP.22 activation code. #[derive(Debug, Clone, PartialEq, Eq)]@@ -48,6 +48,24 @@ pub fn parse_activation_code(code: &str) -> Result<ActivationCode, String> {     }) } +/// The key bytes of a CI public-key identifier field, unwrapping one DER TLV+/// layer when the server sends the full TLV rather than the bare value.+fn pkid_value(field: &[u8]) -> &[u8] {+    asn1::parse(field)+        .map(|(tlv, _)| tlv.value)+        .unwrap_or(field)+}++/// Whether the server's chosen CI key appears in the eUICC's verification list+/// (hex of the raw field or of its unwrapped value).+fn ci_key_known(verification_list: &[String], field: &[u8]) -> bool {+    let raw_hex = es10::hex(field);+    let inner_hex = es10::hex(pkid_value(field));+    verification_list+        .iter()+        .any(|k| *k == raw_hex || *k == inner_hex)+}+ /// Runs the full download for an activation code, driving the eUICC over the /// already-open ISD-R channel (via [`store_data`]) and the SM-DP+ over HTTP. ///@@ -66,6 +84,24 @@ pub fn download_profile(     // 2. Server authentication material.     let r1 = es9p::initiate_authentication(&ac.smdp, &challenge, &euicc_info1)?; +    // The eUICC can only verify the server against a CI public key it holds;+    // otherwise AuthenticateServer fails with SW 6A88. Compare the server's+    // chosen key against the eUICC's own verification list first so the failure+    // names the key instead of surfacing as a bare status word. PKIds are+    // public key identifiers, safe to report. Skip the check when the eUICC+    // gave no list (never block a download on a parser gap).+    if let Ok(info) = es10::parse_euicc_info1(&euicc_info1) {+        if !info.ci_pkid_verification.is_empty()+            && !ci_key_known(&info.ci_pkid_verification, &r1.euicc_ci_pkid)+        {+            return Err(format!(+                "server uses CI key {} unknown to this eUICC (eUICC trusts: {})",+                es10::hex(&pkid_value(&r1.euicc_ci_pkid)),+                info.ci_pkid_verification.join(", "),+            ));+        }+    }+     // 3. eUICC authenticates the server and signs its own material.     let ctx = es10::build_ctx_params1(&ac.matching_id, &[0, 0, 0, 0]);     let auth_req = es10::build_authenticate_server(@@ -128,4 +164,15 @@ mod tests {         assert!(parse_activation_code("LPA:1$smdp.example.com").is_err());         assert!(parse_activation_code("garbage").is_err());     }++    #[test]+    fn ci_key_match_accepts_bare_and_wrapped_forms() {+        let list = vec!["aabbcc".to_string()];+        assert!(ci_key_known(&list, &[0xAA, 0xBB, 0xCC]));+        // Full DER TLV around the same value also matches.+        let wrapped = crate::asn1::tlv(0x04, &[0xAA, 0xBB, 0xCC]);+        assert!(ci_key_known(&list, &wrapped));+        assert!(!ci_key_known(&list, &[0xDD]));+        assert!(!ci_key_known(&[], &[0xAA, 0xBB, 0xCC]));+    } }
euicc/src/main/rust/src/es10.rs
diff --git a/euicc/src/main/rust/src/es10.rs b/euicc/src/main/rust/src/es10.rsindex 9ca6f55b3c..5eba0d8e3f 100644--- a/euicc/src/main/rust/src/es10.rs+++ b/euicc/src/main/rust/src/es10.rs@@ -64,7 +64,7 @@ const TAG_ERROR_RESULT: u32 = 0xA1; // [1] errorResult // ctxParams1 / DeviceInfo construction tags. const TAG_CTX_PARAMS_COMMON: u32 = 0xA0; // [0] ctxParamsForCommonAuthentication const TAG_MATCHING_ID: u32 = 0x80; // [0] matchingId UTF8String-const TAG_DEVICE_INFO: u32 = 0x30; // DeviceInfo SEQUENCE+const TAG_DEVICE_INFO: u32 = 0xA1; // [1] deviceInfo (IMPLICIT replaces SEQUENCE tag) const TAG_TAC: u32 = 0x80; // [0] tac Octet4 const TAG_DEVICE_CAPS: u32 = 0xA1; // [1] deviceCapabilities SEQUENCE 
euicc/src/main/rust/src/es10_part1.rs
diff --git a/euicc/src/main/rust/src/es10_part1.rs b/euicc/src/main/rust/src/es10_part1.rsindex a640edba08..e3ba636a2f 100644--- a/euicc/src/main/rust/src/es10_part1.rs+++ b/euicc/src/main/rust/src/es10_part1.rs@@ -100,6 +100,26 @@ mod tests {         assert_eq!(build_get_eid(), vec![0xBF, 0x3E, 0x03, 0x5C, 0x01, 0x5A]);     } +    #[test]+    fn ctx_params1_tags_match_sgp22() {+        // CtxParamsForCommonAuthentication: matchingId [0] IMPLICIT, deviceInfo+        // [1] IMPLICIT (constructed). A bare SEQUENCE tag (0x30) on deviceInfo is+        // malformed — the SM-DP+ cannot verify the AuthenticateServer response+        // built over it (seen as an empty authenticateClient reply).+        let ctx = build_ctx_params1("ABC", &[0x35, 0x29, 0x06, 0x11]);+        let body = asn1::find(&ctx, TAG_CTX_PARAMS_COMMON).expect("outer A0");+        let kids = asn1::children(body).expect("two children");+        assert_eq!(kids.len(), 2);+        assert_eq!(kids[0].tag, 0x80); // matchingId+        assert_eq!(kids[0].value, b"ABC");+        assert_eq!(kids[1].tag, 0xA1); // deviceInfo [1], NOT 0x30 SEQUENCE+        let dev = asn1::children(kids[1].value).expect("deviceInfo children");+        assert_eq!(dev.len(), 2);+        assert_eq!(dev[0].tag, 0x80); // tac+        assert_eq!(dev[0].value, &[0x35, 0x29, 0x06, 0x11]);+        assert_eq!(dev[1].tag, 0xA1); // deviceCapabilities+    }+     #[test]     fn parse_eid_from_response() {         let mut inner = vec![0x5A, 0x10];
euicc/src/main/rust/src/es9p.rs
diff --git a/euicc/src/main/rust/src/es9p.rs b/euicc/src/main/rust/src/es9p.rsindex 7c232e7207..b0bcd93246 100644--- a/euicc/src/main/rust/src/es9p.rs+++ b/euicc/src/main/rust/src/es9p.rs@@ -46,7 +46,7 @@ pub fn initiate_authentication(         "euiccChallenge": base64::encode(euicc_challenge),         "euiccInfo1": base64::encode(euicc_info1),     });-    let v = post(&endpoint(smdp, "initiateAuthentication"), &body)?;+    let v = post("initiateAuthentication", &endpoint(smdp, "initiateAuthentication"), &body, true)?;     Ok(InitiateAuthResult {         transaction_id: get_str(&v, "transactionId")?,         server_signed1: get_b64(&v, "serverSigned1")?,@@ -67,7 +67,7 @@ pub fn authenticate_client(         "transactionId": transaction_id,         "authenticateServerResponse": base64::encode(authenticate_server_response),     });-    let v = post(&endpoint(smdp, "authenticateClient"), &body)?;+    let v = post("authenticateClient", &endpoint(smdp, "authenticateClient"), &body, true)?;     Ok(AuthenticateClientResult {         smdp_signed2: get_b64(&v, "smdpSigned2")?,         smdp_signature2: get_b64(&v, "smdpSignature2")?,@@ -86,7 +86,12 @@ pub fn get_bound_profile_package(         "transactionId": transaction_id,         "prepareDownloadResponse": base64::encode(prepare_download_response),     });-    let v = post(&endpoint(smdp, "getBoundProfilePackage"), &body)?;+    let v = post(+        "getBoundProfilePackage",+        &endpoint(smdp, "getBoundProfilePackage"),+        &body,+        true,+    )?;     get_b64(&v, "boundProfilePackage") } @@ -95,7 +100,7 @@ pub fn get_bound_profile_package( pub fn handle_notification(smdp: &str, pending_notification: &[u8]) -> Result<(), String> {     let body = json!({ "pendingNotification": base64::encode(pending_notification) });     // A 204/empty body is normal here; ignore the parsed value.-    let _ = post(&endpoint(smdp, "handleNotification"), &body)?;+    let _ = post("handleNotification", &endpoint(smdp, "handleNotification"), &body, false)?;     Ok(()) } @@ -103,7 +108,7 @@ pub fn handle_notification(smdp: &str, pending_notification: &[u8]) -> Result<() // HTTP + helpers // --------------------------------------------------------------------------- -fn post(url: &str, body: &Value) -> Result<Value, String> {+fn post(function: &str, url: &str, body: &Value, expect_body: bool) -> Result<Value, String> {     let headers = [         ("Content-Type".to_string(), "application/json".to_string()),         ("X-Admin-Protocol".to_string(), "gsma/rsp/v2.2.0".to_string()),@@ -117,7 +122,16 @@ fn post(url: &str, body: &Value) -> Result<Value, String> {         return Err(format!("SM-DP+ HTTP {} at {url}", resp.status));     }     if resp.body.is_empty() {-        return Ok(Value::Null);+        // HandleNotification answers 204/empty normally; every other function+        // must return a JSON body, so an empty reply names the function and+        // status instead of failing later on a missing field.+        if !expect_body {+            return Ok(Value::Null);+        }+        return Err(format!(+            "SM-DP+ {function} returned HTTP {} with empty body",+            resp.status+        ));     }     let v: Value = serde_json::from_slice(&resp.body).map_err(|e| format!("parse response: {e}"))?;     check_function_execution_status(&v)?;@@ -125,20 +139,27 @@ fn post(url: &str, body: &Value) -> Result<Value, String> { }  /// Surfaces an SM-DP+ ES9+ functionExecutionStatus error, if present.+/// Like lpac, a missing `header`/`functionExecutionStatus` object is itself an+/// error: per SGP.22 every ES9+ reply carries one, so its absence means the+/// server did not answer the function at all (rather than a field-level gap). fn check_function_execution_status(v: &Value) -> Result<(), String> {     let status = v         .get("header")         .and_then(|h| h.get("functionExecutionStatus"));-    if let Some(status) = status {-        let state = status.get("status").and_then(Value::as_str).unwrap_or("");-        if !state.is_empty() && state != "Executed-Success" {-            let reason = status-                .get("statusCodeData")-                .and_then(|d| d.get("reasonCode"))-                .and_then(Value::as_str)-                .unwrap_or("unknown");-            return Err(format!("SM-DP+ {state} ({reason})"));-        }+    let Some(status) = status else {+        return Err(describe_missing(v, "header.functionExecutionStatus"));+    };+    let state = status.get("status").and_then(Value::as_str).unwrap_or("");+    if state.is_empty() {+        return Err("SM-DP+ reply has functionExecutionStatus without status".to_string());+    }+    if state != "Executed-Success" {+        let reason = status+            .get("statusCodeData")+            .and_then(|d| d.get("reasonCode"))+            .and_then(Value::as_str)+            .unwrap_or("unknown");+        return Err(format!("SM-DP+ {state} ({reason})"));     }     Ok(()) }@@ -171,7 +192,7 @@ fn get_str(v: &Value, key: &str) -> Result<String, String> {     v.get(key)         .and_then(Value::as_str)         .map(str::to_string)-        .ok_or_else(|| format!("SM-DP+ response missing '{key}'"))+        .ok_or_else(|| describe_missing(v, key)) }  fn get_b64(v: &Value, key: &str) -> Result<Vec<u8>, String> {@@ -179,6 +200,34 @@ fn get_b64(v: &Value, key: &str) -> Result<Vec<u8>, String> {     base64::decode(&s).ok_or_else(|| format!("SM-DP+ '{key}' is not valid base64")) } +/// Names what the SM-DP+ actually returned when an expected field is absent:+/// the top-level keys present (or the scalar it replied with), so the failure+/// screen shows the server's real answer instead of just the missing key.+fn describe_missing(v: &Value, key: &str) -> String {+    match v {+        Value::Object(map) => {+            let mut keys: Vec<&str> = map.keys().map(String::as_str).collect();+            keys.sort_unstable();+            format!("SM-DP+ response missing '{key}' (has: {})", keys.join(", "))+        }+        Value::Null => format!("SM-DP+ response missing '{key}' (empty reply)"),+        other => format!(+            "SM-DP+ response missing '{key}' (non-object reply: {})",+            summarize_scalar(other)+        ),+    }+}++fn summarize_scalar(v: &Value) -> String {+    match v {+        Value::String(s) => format!("string[{}]", s.len()),+        Value::Array(a) => format!("array[{}]", a.len()),+        Value::Bool(b) => format!("bool({b})"),+        Value::Number(n) => format!("number({n})"),+        _ => "null".to_string(),+    }+}+ #[cfg(test)] mod tests {     use super::*;@@ -208,6 +257,21 @@ mod tests {         assert!(get_b64(&v, "missing").is_err());     } +    #[test]+    fn missing_field_names_present_keys() {+        let v = json!({ "header": {}, "other": 1 });+        let err = get_str(&v, "smdpSigned2").expect_err("must be missing");+        assert!(err.contains("smdpSigned2"), "names the missing key: {err}");+        assert!(err.contains("header"), "lists present keys: {err}");+        assert!(err.contains("other"), "lists present keys: {err}");+    }++    #[test]+    fn missing_field_on_empty_reply() {+        let err = get_str(&Value::Null, "smdpSigned2").expect_err("must be missing");+        assert!(err.contains("empty reply"), "says the reply was empty: {err}");+    }+     #[test]     fn function_status_error_is_surfaced() {         let v = json!({@@ -218,4 +282,15 @@ mod tests {         });         assert!(check_function_execution_status(&v).is_err());     }++    #[test]+    fn missing_status_block_is_an_error() {+        // lpac parity: a reply without header.functionExecutionStatus is not a+        // function answer at all, even if data fields happen to be present.+        let v = json!({ "smdpSigned2": "aGVsbG8=" });+        let err = check_function_execution_status(&v).expect_err("must be missing");+        assert!(err.contains("functionExecutionStatus"), "names it: {err}");+        let empty = json!({});+        assert!(check_function_execution_status(&empty).is_err());+    } }