euicc: add ISD-R APDU transport and ES10 GetEID/GetEUICCInfo
- Commit
d55cf3c902e7732a55f84b7c7a8bfa26679ba02e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-12 16:17 UTC (3 months ago)
- Parents
d0caea7
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 73be15bf11..47f64ec765 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -592,6 +592,7 @@ version = "0.1.0" dependencies = [ "jni", "log",+ "serde_json", ] [[package]]
euicc/src/main/AndroidManifest.xml
diff --git a/euicc/src/main/AndroidManifest.xml b/euicc/src/main/AndroidManifest.xmlindex baf0cf9707..905806d231 100644--- a/euicc/src/main/AndroidManifest.xml+++ b/euicc/src/main/AndroidManifest.xml@@ -1,6 +1,11 @@ <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> + <!-- Driving the eUICC over a telephony logical channel requires either carrier+ privileges or a platform-signed system app holding these permissions. -->+ <uses-permission android:name="android.permission.READ_PHONE_STATE" />+ <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />+ <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules"
euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt b/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.ktindex 0c7977b194..bc9cee2b91 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt@@ -3,15 +3,42 @@ package com.vayunmathur.euicc /** * JNI entry points into the native SGP.22 core (libeuicc.so). *- * The Rust side owns the ASN.1 + ES9+/ES10 protocol logic and calls back into- * [transmitApdu] to drive the eUICC over the telephony logical channel. Only- * marshalling lives here; see euicc/src/main/rust/.+ * The Rust side owns the ASN.1 + ES10 protocol logic and drives the eUICC by+ * calling back into [transmitApdu], which forwards each command APDU over the+ * telephony logical channel currently opened by [com.vayunmathur.euicc.telephony.EuiccChannelManager].+ * Only marshalling lives here; see euicc/src/main/rust/.+ *+ * The native `nativeXxx` operations are only valid while a channel is open, i.e.+ * inside `EuiccChannelManager.withIsdrChannel { ... }`, which installs+ * [activeChannel] for the duration of the block. */ object EuiccNative { init { System.loadLibrary("euicc") } - /** Returns the native core's version string. Stub sanity check for Phase 1. */+ /**+ * The transmit function for the currently open ISD-R logical channel, or+ * null when no channel is open. Set by `EuiccChannelManager.withIsdrChannel`.+ */+ @Volatile+ @JvmStatic+ var activeChannel: ((ByteArray) -> ByteArray)? = null++ /**+ * Called by the native core to send one command APDU to the eUICC. Returns+ * the response bytes (response data followed by the two status bytes).+ */+ @JvmStatic+ fun transmitApdu(command: ByteArray): ByteArray =+ (activeChannel ?: error("no active eUICC channel")).invoke(command)++ /** Returns the native core's version string. */ external fun nativeVersion(): String++ /** Returns the 32-hex-digit EID, or null on error. */+ external fun nativeGetEid(): String?++ /** Returns the EUICCInfo1 subset as a JSON string, or null on error. */+ external fun nativeGetEuiccInfo(): String? }
euicc/src/main/java/com/vayunmathur/euicc/MainActivity.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/MainActivity.kt b/euicc/src/main/java/com/vayunmathur/euicc/MainActivity.ktindex 653a69bf72..dc6e86baac 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/MainActivity.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/MainActivity.kt@@ -4,16 +4,20 @@ 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.ui.EuiccApp+import com.vayunmathur.euicc.ui.EuiccViewModel import com.vayunmathur.library.ui.DynamicTheme class MainActivity : ComponentActivity() {+ private val viewModel: EuiccViewModel by viewModels()+ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { DynamicTheme {- EuiccApp()+ EuiccApp(viewModel) } } }
euicc/src/main/java/com/vayunmathur/euicc/data/EuiccInfo.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/data/EuiccInfo.kt b/euicc/src/main/java/com/vayunmathur/euicc/data/EuiccInfo.ktnew file mode 100644index 0000000000..aa980ff6ec--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/data/EuiccInfo.kt@@ -0,0 +1,17 @@+package com.vayunmathur.euicc.data++import kotlinx.serialization.Serializable++/**+ * Displayable subset of SGP.22 EUICCInfo1, deserialized from the JSON the native+ * core emits (see euicc/src/main/rust/src/es10.rs).+ */+@Serializable+data class EuiccInfo(+ /** SGP.22 spec version, e.g. "2.2.0". */+ val svn: String = "",+ /** GSMA CI public-key identifiers accepted for verification. */+ val ciPkIdListForVerification: List<String> = emptyList(),+ /** GSMA CI public-key identifiers the eUICC can sign under. */+ val ciPkIdListForSigning: List<String> = emptyList(),+)
euicc/src/main/java/com/vayunmathur/euicc/telephony/EuiccChannelManager.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/telephony/EuiccChannelManager.kt b/euicc/src/main/java/com/vayunmathur/euicc/telephony/EuiccChannelManager.ktnew file mode 100644index 0000000000..bb83481b2b--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/telephony/EuiccChannelManager.kt@@ -0,0 +1,131 @@+package com.vayunmathur.euicc.telephony++import android.content.Context+import android.telephony.IccOpenLogicalChannelResponse+import android.telephony.TelephonyManager+import com.vayunmathur.euicc.EuiccNative++/** Thrown when the eUICC cannot be reached (no eUICC, no privilege, or an APDU error). */+class EuiccException(message: String) : Exception(message)++/**+ * Opens and drives a logical channel to the eUICC's ISD-R applet.+ *+ * SGP.22 local (ES10) operations run over an ISO-7816 logical channel selected+ * onto the ISD-R AID. This wraps the telephony+ * `iccOpenLogicalChannel` / `iccTransmitApduLogicalChannel` /+ * `iccCloseLogicalChannel` APIs, which require the app to hold carrier+ * privileges or be a platform-signed system app (`MODIFY_PHONE_STATE`). The+ * native core builds the command APDUs and calls back into+ * [EuiccNative.transmitApdu]; [transmit] performs the field-based transmit and+ * handles `61xx` GET RESPONSE / `6Cxx` Le-correction chaining.+ */+class EuiccChannelManager(context: Context) {+ private val telephony: TelephonyManager =+ context.applicationContext.getSystemService(TelephonyManager::class.java)+ ?: throw EuiccException("TelephonyManager unavailable")++ /**+ * Opens the ISD-R channel, installs it as [EuiccNative.activeChannel] for the+ * duration of [block] (so native ops can transmit), and closes it afterward.+ */+ @Synchronized+ @Suppress("DEPRECATION")+ fun <T> withIsdrChannel(block: () -> T): T {+ val response: IccOpenLogicalChannelResponse =+ telephony.iccOpenLogicalChannel(ISDR_AID, /* p2 = */ 0)+ if (response.status != IccOpenLogicalChannelResponse.STATUS_NO_ERROR) {+ throw EuiccException("cannot open ISD-R channel (status=${response.status})")+ }+ val channel = response.channel+ if (channel <= 0) throw EuiccException("invalid ISD-R channel ($channel)")+ return try {+ EuiccNative.activeChannel = { apdu -> transmit(channel, apdu) }+ block()+ } finally {+ EuiccNative.activeChannel = null+ runCatching { telephony.iccCloseLogicalChannel(channel) }+ }+ }++ /**+ * Transmits one command APDU on [channel] using the field-based telephony+ * API, following `61xx`/`6Cxx` chaining, and returns the full response+ * (response data followed by the two status bytes).+ */+ @Suppress("DEPRECATION")+ private fun transmit(channel: Int, command: ByteArray): ByteArray {+ require(command.size >= 4) { "APDU too short (${command.size} bytes)" }+ val cla = command[0].toInt() and 0xFF+ val ins = command[1].toInt() and 0xFF+ val p1 = command[2].toInt() and 0xFF+ val p2 = command[3].toInt() and 0xFF+ val p3: Int+ val dataHex: String+ when {+ command.size == 4 -> {+ p3 = 0; dataHex = ""+ }+ command.size == 5 -> {+ // Case 2: the fifth byte is Le.+ p3 = command[4].toInt() and 0xFF; dataHex = ""+ }+ else -> {+ // Case 3/4: fifth byte is Lc; ignore any trailing Le.+ val lc = command[4].toInt() and 0xFF+ val end = (5 + lc).coerceAtMost(command.size)+ p3 = lc+ dataHex = command.copyOfRange(5, end).toHex()+ }+ }++ val out = StringBuilder()+ var response = telephony+ .iccTransmitApduLogicalChannel(channel, cla, ins, p1, p2, p3, dataHex).orEmpty()+ while (response.length >= 4) {+ val body = response.substring(0, response.length - 4)+ val sw1 = response.substring(response.length - 4, response.length - 2).toInt(16)+ val sw2 = response.substring(response.length - 2).toInt(16)+ when (sw1) {+ 0x61 -> {+ // More data available: GET RESPONSE for sw2 bytes.+ out.append(body)+ response = telephony+ .iccTransmitApduLogicalChannel(channel, 0x00, 0xC0, 0x00, 0x00, sw2, "")+ .orEmpty()+ }+ 0x6C -> {+ // Wrong Le: resend the original command with Le = sw2.+ out.setLength(0)+ response = telephony+ .iccTransmitApduLogicalChannel(channel, cla, ins, p1, p2, sw2, dataHex)+ .orEmpty()+ }+ else -> {+ out.append(body)+ out.append("%02X%02X".format(sw1, sw2))+ return out.toString().hexToBytes()+ }+ }+ }+ return out.toString().hexToBytes()+ }++ companion object {+ /** ISD-R application identifier (SGP.22). */+ const val ISDR_AID = "A0000005591010FFFFFFFF8900000100"+ }+}++private fun ByteArray.toHex(): String {+ val sb = StringBuilder(size * 2)+ for (b in this) sb.append("%02X".format(b.toInt() and 0xFF))+ return sb.toString()+}++private fun String.hexToBytes(): ByteArray {+ if (length % 2 != 0) return ByteArray(0)+ return ByteArray(length / 2) { i ->+ substring(i * 2, i * 2 + 2).toInt(16).toByte()+ }+}
euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.ktindex 16ad05626a..e6be3919a9 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt@@ -1,20 +1,82 @@ package com.vayunmathur.euicc.ui +import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier+import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp-import com.vayunmathur.euicc.EuiccNative+import com.vayunmathur.euicc.data.EuiccInfo import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconRefresh+import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text @Composable-fun EuiccApp() {- AppScaffold(title = "EUICC") { padding ->- Column(modifier = Modifier.padding(padding).padding(16.dp)) {- Text("eSIM Local Profile Assistant")- Text("Native core: ${runCatching { EuiccNative.nativeVersion() }.getOrElse { "unavailable" }}")+fun EuiccApp(viewModel: EuiccViewModel) {+ AppScaffold(+ title = "EUICC",+ actions = {+ IconButton(onClick = viewModel::refresh) { IconRefresh() }+ },+ ) { padding ->+ Column(+ modifier = Modifier+ .fillMaxSize()+ .padding(padding)+ .padding(16.dp)+ .verticalScroll(rememberScrollState()),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ when (val state = viewModel.state) {+ is EuiccUiState.Loading -> CircularProgressIndicator()+ is EuiccUiState.Error -> Text(state.message)+ is EuiccUiState.Ready -> ReadyContent(state)+ }+ }+ }+}++@Composable+private fun ReadyContent(state: EuiccUiState.Ready) {+ LabeledCard(label = "EID") {+ Text(state.eid ?: "unavailable")+ }+ val info = state.info+ if (info != null) {+ LabeledCard(label = "eUICC info") {+ Text("SGP.22 version: ${info.svn.ifEmpty { "unknown" }}")+ KeyIdList("CI keys (verification)", info.ciPkIdListForVerification)+ KeyIdList("CI keys (signing)", info.ciPkIdListForSigning)+ }+ }+}++@Composable+private fun KeyIdList(label: String, ids: List<String>) {+ if (ids.isEmpty()) return+ Text(label, style = MaterialTheme.typography.labelMedium)+ for (id in ids) {+ Text(id, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+}++@Composable+private fun LabeledCard(label: String, content: @Composable () -> Unit) {+ Card(modifier = Modifier.fillMaxSize()) {+ Column(+ modifier = Modifier.padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ Text(label, style = MaterialTheme.typography.titleMedium)+ content() } } }
euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccViewModel.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccViewModel.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccViewModel.ktnew file mode 100644index 0000000000..3bafeb5c6b--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccViewModel.kt@@ -0,0 +1,53 @@+package com.vayunmathur.euicc.ui++import android.app.Application+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.euicc.EuiccNative+import com.vayunmathur.euicc.data.EuiccInfo+import com.vayunmathur.euicc.telephony.EuiccChannelManager+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlinx.serialization.json.Json++/** UI state for the EID / eUICC-info screen. */+sealed interface EuiccUiState {+ data object Loading : EuiccUiState+ data class Ready(val eid: String?, val info: EuiccInfo?) : EuiccUiState+ data class Error(val message: String) : EuiccUiState+}++class EuiccViewModel(app: Application) : AndroidViewModel(app) {+ private val channelManager = EuiccChannelManager(app)+ private val json = Json { ignoreUnknownKeys = true }++ var state by mutableStateOf<EuiccUiState>(EuiccUiState.Loading)+ private set++ init {+ refresh()+ }++ /** Opens the ISD-R channel and reads the EID + EUICCInfo1 off the eUICC. */+ fun refresh() {+ state = EuiccUiState.Loading+ viewModelScope.launch {+ state = withContext(Dispatchers.IO) {+ try {+ channelManager.withIsdrChannel {+ val eid = EuiccNative.nativeGetEid()+ val info = EuiccNative.nativeGetEuiccInfo()+ ?.let { json.decodeFromString<EuiccInfo>(it) }+ EuiccUiState.Ready(eid, info)+ }+ } catch (e: Exception) {+ EuiccUiState.Error(e.message ?: "eUICC unavailable")+ }+ }+ }+ }+}
euicc/src/main/rust/Cargo.toml
diff --git a/euicc/src/main/rust/Cargo.toml b/euicc/src/main/rust/Cargo.tomlindex d389d8b362..30175654d1 100644--- a/euicc/src/main/rust/Cargo.toml+++ b/euicc/src/main/rust/Cargo.toml@@ -15,6 +15,7 @@ crate-type = ["cdylib", "rlib"] [dependencies] jni.workspace = true log.workspace = true+serde_json.workspace = true [profile.release] opt-level = 3
euicc/src/main/rust/src/asn1.rs
diff --git a/euicc/src/main/rust/src/asn1.rs b/euicc/src/main/rust/src/asn1.rsnew file mode 100644index 0000000000..c44e03c4e9--- /dev/null+++ b/euicc/src/main/rust/src/asn1.rs@@ -0,0 +1,181 @@+//! Minimal BER-TLV (SGP.22 uses DER) encode/decode.+//!+//! SGP.22 ASN.1 is small and regular: context/application tags of one or two+//! bytes, definite lengths (short and long form), constructed and primitive+//! values. This module implements just that surface — enough to build the ES10+//! request TLVs and walk the responses — without pulling a full ASN.1 stack.+//!+//! It is pure and host-testable; no JNI, no protocol logic.++/// A parsed TLV: its tag, the raw value bytes, and the number of header bytes+/// (tag + length octets) that preceded the value.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Tlv<'a> {+ pub tag: u32,+ pub value: &'a [u8],+}++/// Reads the tag at the start of `data`, returning `(tag, bytes_consumed)`.+///+/// Handles single-byte tags and the multi-byte form (low 5 bits of the first+/// byte all set), which SGP.22 uses for two-byte context tags such as `BF3E`.+fn read_tag(data: &[u8]) -> Option<(u32, usize)> {+ let first = *data.first()?;+ // Low 5 bits set => tag number continues in following bytes.+ if first & 0x1F != 0x1F {+ return Some((first as u32, 1));+ }+ let mut tag = first as u32;+ let mut i = 1;+ loop {+ let b = *data.get(i)?;+ tag = (tag << 8) | b as u32;+ i += 1;+ // High bit clear terminates the tag.+ if b & 0x80 == 0 {+ break;+ }+ // SGP.22 never exceeds two-byte tags; guard runaway input.+ if i > 4 {+ return None;+ }+ }+ Some((tag, i))+}++/// Reads a definite BER length at the start of `data`, returning+/// `(length, bytes_consumed)`.+fn read_len(data: &[u8]) -> Option<(usize, usize)> {+ let first = *data.first()?;+ if first & 0x80 == 0 {+ return Some((first as usize, 1));+ }+ let n = (first & 0x7F) as usize;+ // Indefinite (n == 0) is not valid DER; refuse it. Cap at 4 length octets.+ if n == 0 || n > 4 {+ return None;+ }+ let mut len = 0usize;+ for i in 0..n {+ len = (len << 8) | *data.get(1 + i)? as usize;+ }+ Some((len, 1 + n))+}++/// Parses the first TLV in `data`, returning it together with the remaining+/// bytes after its value.+pub fn parse(data: &[u8]) -> Option<(Tlv<'_>, &[u8])> {+ let (tag, tag_len) = read_tag(data)?;+ let (len, len_len) = read_len(&data[tag_len..])?;+ let header = tag_len + len_len;+ let end = header.checked_add(len)?;+ let value = data.get(header..end)?;+ Some((Tlv { tag, value }, &data[end..]))+}++/// Returns the value of the first child TLV with `tag`, searching only the top+/// level of `data`.+pub fn find(data: &[u8], tag: u32) -> Option<&[u8]> {+ let mut rest = data;+ while !rest.is_empty() {+ let (tlv, next) = parse(rest)?;+ if tlv.tag == tag {+ return Some(tlv.value);+ }+ rest = next;+ }+ None+}++/// Returns every top-level child TLV of `data`.+pub fn children(data: &[u8]) -> Option<Vec<Tlv<'_>>> {+ let mut out = Vec::new();+ let mut rest = data;+ while !rest.is_empty() {+ let (tlv, next) = parse(rest)?;+ out.push(tlv);+ rest = next;+ }+ Some(out)+}++/// Encodes a definite length in BER short/long form.+pub fn encode_len(len: usize) -> Vec<u8> {+ if len < 0x80 {+ return vec![len as u8];+ }+ let mut bytes = Vec::new();+ let mut v = len;+ while v > 0 {+ bytes.insert(0, (v & 0xFF) as u8);+ v >>= 8;+ }+ let mut out = vec![0x80 | bytes.len() as u8];+ out.extend_from_slice(&bytes);+ out+}++/// Encodes the big-endian bytes of `tag` (1 or 2 bytes) as a tag prefix.+fn encode_tag(tag: u32) -> Vec<u8> {+ if tag <= 0xFF {+ vec![tag as u8]+ } else {+ vec![(tag >> 8) as u8, (tag & 0xFF) as u8]+ }+}++/// Builds a TLV: `tag || len(value) || value`.+pub fn tlv(tag: u32, value: &[u8]) -> Vec<u8> {+ let mut out = encode_tag(tag);+ out.extend_from_slice(&encode_len(value.len()));+ out.extend_from_slice(value);+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn single_byte_tag_and_len() {+ let (tlv, rest) = parse(&[0x5A, 0x02, 0xAB, 0xCD]).unwrap();+ assert_eq!(tlv.tag, 0x5A);+ assert_eq!(tlv.value, &[0xAB, 0xCD]);+ assert!(rest.is_empty());+ }++ #[test]+ fn two_byte_tag() {+ let (tlv, _) = parse(&[0xBF, 0x3E, 0x01, 0x00]).unwrap();+ assert_eq!(tlv.tag, 0xBF3E);+ assert_eq!(tlv.value, &[0x00]);+ }++ #[test]+ fn long_form_length() {+ let mut data = vec![0x04, 0x81, 0x80];+ data.extend(std::iter::repeat(0x11).take(0x80));+ let (tlv, rest) = parse(&data).unwrap();+ assert_eq!(tlv.tag, 0x04);+ assert_eq!(tlv.value.len(), 0x80);+ assert!(rest.is_empty());+ }++ #[test]+ fn find_nested() {+ // BF3E 12 5A 10 <16 bytes>+ let mut inner = vec![0x5A, 0x10];+ inner.extend(0..16u8);+ let outer = tlv(0xBF3E, &inner);+ let body = find(&outer, 0xBF3E).unwrap();+ let eid = find(body, 0x5A).unwrap();+ assert_eq!(eid.len(), 16);+ }++ #[test]+ fn roundtrip_encode() {+ assert_eq!(tlv(0x5C, &[0x5A]), vec![0x5C, 0x01, 0x5A]);+ assert_eq!(encode_len(0x80), vec![0x81, 0x80]);+ assert_eq!(encode_len(0x7F), vec![0x7F]);+ }+}
euicc/src/main/rust/src/es10.rs
diff --git a/euicc/src/main/rust/src/es10.rs b/euicc/src/main/rust/src/es10.rsnew file mode 100644index 0000000000..17e0de47c5--- /dev/null+++ b/euicc/src/main/rust/src/es10.rs@@ -0,0 +1,141 @@+//! ES10 local ISD-R command builders and response parsers (SGP.22).+//!+//! Pure protocol logic: each function either builds a request TLV (to be wrapped+//! in STORE DATA APDUs and transmitted by the transport layer) or parses a+//! response TLV. No JNI or transport here, so it is fully host-testable.+//!+//! Reimplemented for this repo, following the open-source OpenEUICC / lpac+//! (GPL-3.0-only).++use crate::asn1;++// --- Tags (SGP.22) ---+const TAG_GET_EUICC_DATA: u32 = 0xBF3E; // ES10c GetEuiccData request/response+const TAG_TAG_LIST: u32 = 0x5C; // [APPLICATION 28] tag list+const TAG_EID: u32 = 0x5A; // [APPLICATION 26] EID value+const TAG_EUICC_INFO1: u32 = 0xBF20; // ES10c GetEUICCInfo1 request/response+const TAG_SVN: u32 = 0x82; // [2] version (3 octets: major.minor.rev)+const TAG_CI_PKID_VERIFICATION: u32 = 0xA9; // [9] SEQUENCE OF SubjectKeyIdentifier+const TAG_CI_PKID_SIGNING: u32 = 0xAA; // [10] SEQUENCE OF SubjectKeyIdentifier++/// Parsed subset of EUICCInfo1 useful for display.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct EuiccInfo1 {+ /// SGP.22 spec version, e.g. "2.2.0".+ pub svn: String,+ /// GSMA CI public-key identifiers the eUICC accepts for verification.+ pub ci_pkid_verification: Vec<String>,+ /// GSMA CI public-key identifiers the eUICC can sign under.+ pub ci_pkid_signing: Vec<String>,+}++/// Builds the ES10c GetEID request (GetEuiccData with a tag list of `{EID}`).+pub fn build_get_eid() -> Vec<u8> {+ // BF3E 03 5C 01 5A+ let tag_list = asn1::tlv(TAG_TAG_LIST, &[TAG_EID as u8]);+ asn1::tlv(TAG_GET_EUICC_DATA, &tag_list)+}++/// Parses a GetEuiccData response and returns the EID as 32 hex digits.+///+/// The 16 EID octets already encode the 32 decimal digits (one per nibble), so+/// a plain hex encoding of the octets is the canonical EID string.+pub fn parse_eid(response: &[u8]) -> Result<String, String> {+ let body = asn1::find(response, TAG_GET_EUICC_DATA)+ .ok_or("GetEuiccData: missing BF3E")?;+ let eid = asn1::find(body, TAG_EID).ok_or("GetEuiccData: missing EID (5A)")?;+ if eid.len() != 16 {+ return Err(format!("EID length {} != 16", eid.len()));+ }+ Ok(hex(eid))+}++/// Builds the ES10c GetEUICCInfo1 request (empty BF20).+pub fn build_get_euicc_info1() -> Vec<u8> {+ asn1::tlv(TAG_EUICC_INFO1, &[])+}++/// Parses a GetEUICCInfo1 response into the displayable [`EuiccInfo1`] subset.+pub fn parse_euicc_info1(response: &[u8]) -> Result<EuiccInfo1, String> {+ let body = asn1::find(response, TAG_EUICC_INFO1).ok_or("EUICCInfo1: missing BF20")?;++ let svn = match asn1::find(body, TAG_SVN) {+ Some(v) if v.len() == 3 => format!("{}.{}.{}", v[0], v[1], v[2]),+ _ => String::new(),+ };++ let list = |tag: u32| -> Vec<String> {+ asn1::find(body, tag)+ .and_then(asn1::children)+ .map(|kids| kids.iter().map(|k| hex(k.value)).collect())+ .unwrap_or_default()+ };++ Ok(EuiccInfo1 {+ svn,+ ci_pkid_verification: list(TAG_CI_PKID_VERIFICATION),+ ci_pkid_signing: list(TAG_CI_PKID_SIGNING),+ })+}++/// Lowercase hex encoding.+pub fn hex(bytes: &[u8]) -> String {+ let mut s = String::with_capacity(bytes.len() * 2);+ for b in bytes {+ s.push_str(&format!("{b:02x}"));+ }+ s+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn get_eid_request_bytes() {+ assert_eq!(build_get_eid(), vec![0xBF, 0x3E, 0x03, 0x5C, 0x01, 0x5A]);+ }++ #[test]+ fn parse_eid_from_response() {+ // BF3E 12 5A 10 <89 04 40 ... 16 octets>+ let mut inner = vec![0x5A, 0x10];+ let octets: [u8; 16] = [+ 0x89, 0x04, 0x40, 0x00, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,+ 0x00, 0x01,+ ];+ inner.extend_from_slice(&octets);+ let resp = asn1::tlv(TAG_GET_EUICC_DATA, &inner);+ assert_eq!(parse_eid(&resp).unwrap(), "89044000001122334455667788990001");+ }++ #[test]+ fn get_euicc_info1_request_bytes() {+ assert_eq!(build_get_euicc_info1(), vec![0xBF, 0x20, 0x00]);+ }++ #[test]+ fn parse_euicc_info1_svn_and_lists() {+ let svn = asn1::tlv(TAG_SVN, &[0x02, 0x02, 0x00]);+ let ver_list = {+ let mut kids = Vec::new();+ kids.extend(asn1::tlv(0x04, &[0xAA; 20]));+ asn1::tlv(TAG_CI_PKID_VERIFICATION, &kids)+ };+ let sign_list = {+ let mut kids = Vec::new();+ kids.extend(asn1::tlv(0x04, &[0xBB; 20]));+ asn1::tlv(TAG_CI_PKID_SIGNING, &kids)+ };+ let mut body = Vec::new();+ body.extend(svn);+ body.extend(ver_list);+ body.extend(sign_list);+ let resp = asn1::tlv(TAG_EUICC_INFO1, &body);++ let info = parse_euicc_info1(&resp).unwrap();+ assert_eq!(info.svn, "2.2.0");+ assert_eq!(info.ci_pkid_verification, vec!["aa".repeat(20)]);+ assert_eq!(info.ci_pkid_signing, vec!["bb".repeat(20)]);+ }+}
euicc/src/main/rust/src/jni.rs
diff --git a/euicc/src/main/rust/src/jni.rs b/euicc/src/main/rust/src/jni.rsindex d2e90631cd..a6bf8b8651 100644--- a/euicc/src/main/rust/src/jni.rs+++ b/euicc/src/main/rust/src/jni.rs@@ -1,21 +1,130 @@ //! Thin JNI marshalling layer bridging the Kotlin `EuiccNative` object to the-//! native SGP.22 core. This file contains no protocol logic; later phases add-//! the ES10/ES9+ entry points and the `transmitApdu` upcall here.+//! native SGP.22 core, plus the STORE DATA transport that carries ES10 command+//! TLVs to the ISD-R.+//!+//! The protocol/ASN.1 logic lives in [`crate::asn1`] and [`crate::es10`]; this+//! file only wraps requests in GlobalPlatform STORE DATA APDUs, drives them over+//! the `EuiccNative.transmitApdu` upcall (which owns the telephony logical+//! channel on the Kotlin side), and converts results to Kotlin types. -use jni::objects::JClass;+use jni::objects::{JByteArray, JClass, JValue}; use jni::sys::jstring; use jni::JNIEnv; -use crate::VERSION;+use crate::{es10, VERSION}; -/// `nativeVersion()` — returns the native core's version string, or null on error.+const EUICC_NATIVE_CLASS: &str = "com/vayunmathur/euicc/EuiccNative";+const TRANSMIT_METHOD: &str = "transmitApdu";+/// `([B)[B` — command APDU bytes → response APDU bytes (data followed by SW1 SW2).+const TRANSMIT_SIG: &str = "([B)[B";++/// Sends one command APDU to the eUICC by calling back into Kotlin+/// `EuiccNative.transmitApdu`, which transmits over the open logical channel and+/// returns the response bytes (response data followed by the two status bytes).+fn transmit_apdu(env: &mut JNIEnv, apdu: &[u8]) -> Result<Vec<u8>, String> {+ let arr: JByteArray = env+ .byte_array_from_slice(apdu)+ .map_err(|e| format!("apdu marshal: {e}"))?;+ let result = env+ .call_static_method(+ EUICC_NATIVE_CLASS,+ TRANSMIT_METHOD,+ TRANSMIT_SIG,+ &[JValue::Object(&arr)],+ )+ .map_err(|e| {+ // A pending exception poisons the next JNI call on this thread.+ let _ = env.exception_clear();+ format!("transmitApdu call failed: {e}")+ })?;+ let object = result.l().map_err(|e| format!("bad return: {e}"))?;+ if object.is_null() {+ return Err("transmitApdu returned null".into());+ }+ env.convert_byte_array(JByteArray::from(object))+ .map_err(|e| format!("reading response: {e}"))+}++/// Sends an ES10 command TLV to the ISD-R via GlobalPlatform STORE DATA,+/// splitting into ≤255-byte blocks, and returns the final response TLV with the+/// trailing `90 00` status stripped.+fn store_data(env: &mut JNIEnv, command: &[u8]) -> Result<Vec<u8>, String> {+ // A zero-length command still sends one (empty) block.+ let blocks: Vec<&[u8]> = if command.is_empty() {+ vec![&command[0..0]]+ } else {+ command.chunks(255).collect()+ };+ let last = blocks.len() - 1;++ let mut response = Vec::new();+ for (i, block) in blocks.iter().enumerate() {+ // P1: 0x11 for an intermediate block, 0x91 for the last (b8 = last block).+ let p1 = if i == last { 0x91 } else { 0x11 };+ let mut apdu = vec![0x80u8, 0xE2, p1, i as u8, block.len() as u8];+ apdu.extend_from_slice(block);+ response = transmit_apdu(env, &apdu)?;+ }++ if response.len() < 2 {+ return Err("APDU response too short".into());+ }+ let (data, sw) = response.split_at(response.len() - 2);+ if sw != [0x90, 0x00] {+ return Err(format!("eUICC returned SW={:02X}{:02X}", sw[0], sw[1]));+ }+ Ok(data.to_vec())+}++/// Returns `s` as a new Java string, or null (used on the error path).+fn new_jstring(env: &JNIEnv, s: &str) -> jstring {+ match env.new_string(s) {+ Ok(js) => js.into_raw(),+ Err(_) => std::ptr::null_mut(),+ }+}++/// `nativeVersion()` — native core version string. #[no_mangle] pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeVersion<'l>( env: JNIEnv<'l>, _class: JClass<'l>, ) -> jstring {- match env.new_string(VERSION) {- Ok(s) => s.into_raw(),+ new_jstring(&env, VERSION)+}++/// `nativeGetEid()` — 32-hex-digit EID, or null on error (with a Kotlin+/// exception left pending is avoided; null signals failure).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeGetEid<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+) -> jstring {+ let result = store_data(&mut env, &es10::build_get_eid())+ .and_then(|resp| es10::parse_eid(&resp));+ match result {+ Ok(eid) => new_jstring(&env, &eid),+ Err(_) => std::ptr::null_mut(),+ }+}++/// `nativeGetEuiccInfo()` — EUICCInfo1 subset as a JSON string, or null on error.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeGetEuiccInfo<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+) -> jstring {+ let result = store_data(&mut env, &es10::build_get_euicc_info1())+ .and_then(|resp| es10::parse_euicc_info1(&resp));+ match result {+ Ok(info) => {+ let json = serde_json::json!({+ "svn": info.svn,+ "ciPkIdListForVerification": info.ci_pkid_verification,+ "ciPkIdListForSigning": info.ci_pkid_signing,+ });+ new_jstring(&env, &json.to_string())+ } Err(_) => std::ptr::null_mut(), } }
euicc/src/main/rust/src/lib.rs
diff --git a/euicc/src/main/rust/src/lib.rs b/euicc/src/main/rust/src/lib.rsindex bb1a3bae37..232718173b 100644--- a/euicc/src/main/rust/src/lib.rs+++ b/euicc/src/main/rust/src/lib.rs@@ -12,9 +12,11 @@ //! Reimplemented for this repo, following the open-source OpenEUICC //! (GPL-3.0-only). Ported files carry attribution in their own headers. //!-//! Phase 1 ships only the JNI plumbing and a version stub; the protocol modules-//! land in later phases.+//! Phase 3 adds the ASN.1 + ES10 (local ISD-R) layers and the STORE DATA+//! transport; the ES9+/SM-DP+ and crypto modules land in later phases. +mod asn1;+mod es10; mod jni; /// Version string reported by the native core.