diff --git a/.github/workflows/app-ci.yml b/.github/workflows/app-ci.yml index 2235874..6219e68 100644 --- a/.github/workflows/app-ci.yml +++ b/.github/workflows/app-ci.yml @@ -35,6 +35,34 @@ jobs: working-directory: ./App run: ./gradlew testDebugUnitTest + # 缓存并准备CoreADI + - name: Cache CoreADI asset + id: cache-coreadi + uses: actions/cache@v4 + with: + path: App/app/src/main/assets/coreadi/CoreADI.x86_64 + key: coreadi-2eafc3c79c7f41a8afbfbeaaf23ee5dab5ad5bda55ec8e54dbc0ddf1d20ce630 + + - name: Install p7zip + if: steps.cache-coreadi.outputs.cache-hit != 'true' + run: | + sudo apt-get update + sudo apt-get install -y p7zip-full + + - name: Extract CoreADI + if: steps.cache-coreadi.outputs.cache-hit != 'true' + run: | + python3 tools/extract_coreadi.py --dest App/app/src/main/assets/coreadi + + - name: Verify CoreADI Asset + run: | + COREADI_FILE="App/app/src/main/assets/coreadi/CoreADI.x86_64" + if [ ! -f "$COREADI_FILE" ]; then + echo "Error: CoreADI asset not found at $COREADI_FILE" + exit 1 + fi + echo "CoreADI asset verified: $(sha256sum "$COREADI_FILE")" + - name: Build Debug APK working-directory: ./App run: ./gradlew assembleDebug diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b180b7a..3391b85 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,6 +5,12 @@ on: tags: - 'v*' workflow_dispatch: + inputs: + tag_name: + description: '发布版本号 / Release Tag (例如 v1.0.0-beta.1)' + required: false + default: '' + type: string jobs: build-and-release: @@ -17,6 +23,22 @@ jobs: - name: Checkout Code uses: actions/checkout@v4 + # 确定版本 Tag(支持通过 Git 推送 Tag,或在网页端 Run workflow 手动输入 Tag) + - name: Determine Release Tag + run: | + TAG="${{ inputs.tag_name }}" + if [ -z "$TAG" ]; then + if [ "${{ github.ref_type }}" = "tag" ]; then + TAG="${{ github.ref_name }}" + else + echo "Error: 当前是在分支上运行,且未在 Run workflow 中输入 tag_name!" + echo "GitHub Release 必须绑定一个版本 Tag(例如 v1.0.0-beta.1)。" + exit 1 + fi + fi + echo "TARGET_TAG=$TAG" >> $GITHUB_ENV + echo "Target Release Tag is: $TAG" + - name: Set up JDK 17 uses: actions/setup-java@v4 with: @@ -27,6 +49,34 @@ jobs: - name: Grant execute permission for gradlew run: chmod +x App/gradlew + # 缓存并准备CoreADI + - name: Cache CoreADI asset + id: cache-coreadi + uses: actions/cache@v4 + with: + path: App/app/src/main/assets/coreadi/CoreADI.x86_64 + key: coreadi-2eafc3c79c7f41a8afbfbeaaf23ee5dab5ad5bda55ec8e54dbc0ddf1d20ce630 + + - name: Install p7zip + if: steps.cache-coreadi.outputs.cache-hit != 'true' + run: | + sudo apt-get update + sudo apt-get install -y p7zip-full + + - name: Extract CoreADI + if: steps.cache-coreadi.outputs.cache-hit != 'true' + run: | + python3 tools/extract_coreadi.py --dest App/app/src/main/assets/coreadi + + - name: Verify CoreADI Asset + run: | + COREADI_FILE="App/app/src/main/assets/coreadi/CoreADI.x86_64" + if [ ! -f "$COREADI_FILE" ]; then + echo "Error: CoreADI asset not found at $COREADI_FILE" + exit 1 + fi + echo "CoreADI asset verified: $(sha256sum "$COREADI_FILE")" + # 正式 Release 编译 - name: Build Android Release APK working-directory: ./App @@ -83,7 +133,7 @@ jobs: fi # 5. 执行 apksigner 写入正式签名 - OUT_APK="release-assets/YuiTag-App-${{ github.ref_name }}.apk" + OUT_APK="release-assets/YuiTag-App-${TARGET_TAG}.apk" echo "Running apksigner..." "$APKSIGNER" sign \ --ks release.jks \ @@ -105,8 +155,10 @@ jobs: - name: Create GitHub Release (Draft) uses: softprops/action-gh-release@v2 with: + tag_name: ${{ env.TARGET_TAG }} + name: ${{ env.TARGET_TAG }} draft: true - prerelease: ${{ contains(github.ref_name, 'beta') || contains(github.ref_name, 'rc') || contains(github.ref_name, 'alpha') }} + prerelease: ${{ contains(env.TARGET_TAG, 'beta') || contains(env.TARGET_TAG, 'rc') || contains(env.TARGET_TAG, 'alpha') || contains(env.TARGET_TAG, 'dev') || contains(env.TARGET_TAG, 'preview') }} generate_release_notes: true files: | release-assets/*.apk diff --git a/App/.gitignore b/App/.gitignore index 3554ac0..0a25edd 100644 --- a/App/.gitignore +++ b/App/.gitignore @@ -13,8 +13,13 @@ Thumbs.db *.jks *.p12 *.pem +!app/src/main/res/raw/*.pem *.log # 本地私有脚本与说明 build.ps1 AGENTS.md + +# CoreADI +app/src/main/assets/coreadi/CoreADI.x86_64 + diff --git a/App/app/build.gradle.kts b/App/app/build.gradle.kts index 7a9fd69..d1ef212 100644 --- a/App/app/build.gradle.kts +++ b/App/app/build.gradle.kts @@ -14,8 +14,8 @@ android { applicationId = "com.reiyy.yuitag" minSdk = 31 targetSdk = 35 - versionCode = 2 - versionName = "1.0.0" + versionCode = 3 + versionName = "1.0.0-beta.2" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } @@ -82,6 +82,8 @@ dependencies { // Gson (theme config JSON serialization) implementation("com.google.code.gson:gson:2.11.0") + // OkHttp (Apple GrandSlam & FindMy direct API) + implementation("com.squareup.okhttp3:okhttp:4.12.0") // AboutLibraries (自动化开源许可) implementation(libs.aboutlibraries.compose.m3) @@ -91,5 +93,4 @@ dependencies { androidTestImplementation(libs.junit) androidTestImplementation(libs.androidx.test.ext.junit) androidTestImplementation(libs.androidx.test.runner) - androidTestImplementation(libs.androidx.room.testing) } diff --git a/App/app/src/main/AndroidManifest.xml b/App/app/src/main/AndroidManifest.xml index c18ada8..18b1993 100644 --- a/App/app/src/main/AndroidManifest.xml +++ b/App/app/src/main/AndroidManifest.xml @@ -34,6 +34,7 @@ android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher" android:supportsRtl="true" + android:networkSecurityConfig="@xml/network_security_config" android:theme="@style/Theme.YuiTagApp"> = mutableMapOf() + val loginStateData: Map get() = _loginStateData + + fun loginStateString(key: String): String? = _loginStateData[key] as? String + + fun getDsid(): String? = loginStateString("dsid")?.takeIf { it.isNotBlank() } + + @Suppress("UNCHECKED_CAST") + fun getSearchPartyToken(): String? { + val mobileme = _loginStateData["mobileme_data"] as? Map ?: return null + val tokens = mobileme["tokens"] as? Map ?: return null + return tokens["searchPartyToken"] as? String + } + + fun setLoginState(state: LoginState, data: Map?) { + if (state.value < loginState.value) { + accountInfo = null + } + loginState = state + _loginStateData = data?.toMutableMap() ?: mutableMapOf() + } + + fun exportToJson(): String { + val map = mapOf( + "ids" to mapOf("uid" to uid, "devid" to devid), + "account" to mapOf( + "username" to username, + "password" to password, + "info" to accountInfo + ), + "login_state" to mapOf( + "state" to loginState.value, + "data" to _loginStateData + ) + ) + return GSON.toJson(map) + } + + companion object { + private val GSON = Gson() + + @Suppress("UNCHECKED_CAST") + fun restoreFromJson(json: String): AppleAccount = try { + val type = object : TypeToken>() {}.type + val map: Map = GSON.fromJson(json, type) + val ids = map["ids"] as? Map ?: emptyMap() + val account = map["account"] as? Map ?: emptyMap() + val login = map["login_state"] as? Map ?: emptyMap() + + val acc = AppleAccount( + uid = ids["uid"] as? String, + devid = ids["devid"] as? String, + ) + acc.username = account["username"] as? String + acc.password = account["password"] as? String + + account["info"]?.let { infoMap -> + val infoJson = GSON.toJson(infoMap) + acc.accountInfo = GSON.fromJson(infoJson, AccountInfo::class.java) + } + + val stateNum = (login["state"] as? Number)?.toInt() ?: LoginState.LOGGED_OUT.value + acc.loginState = LoginState.fromValue(stateNum) + val d = login["data"] as? Map + acc._loginStateData = d?.toMutableMap() ?: mutableMapOf() + acc + } catch (e: Exception) { + throw IllegalArgumentException("Failed to restore AppleAccount from JSON: ${e.message}", e) + } + } +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/account/AppleAccountManager.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/account/AppleAccountManager.kt new file mode 100644 index 0000000..0358bca --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/account/AppleAccountManager.kt @@ -0,0 +1,104 @@ +package com.reiyy.yuitag.apple.account + +import android.content.Context +import android.content.SharedPreferences +import com.reiyy.yuitag.apple.anisette.AnisetteClient +import com.reiyy.yuitag.apple.anisette.AnisetteProvider +import com.reiyy.yuitag.apple.anisette.createAndroidAnisetteProvider +import com.reiyy.yuitag.apple.gsa.GsaClient +import com.reiyy.yuitag.apple.http.HttpTransport +import com.reiyy.yuitag.apple.http.OkHttpTransport +import com.reiyy.yuitag.apple.mobileme.MobileMeClient +import com.reiyy.yuitag.apple.reports.LocationReportsClient +import com.reiyy.yuitag.ble.FileLog + +/** + * Singleton managing Apple ID credentials, Anisette emulation, and network clients. + */ +class AppleAccountManager private constructor(private val appContext: Context) { + + private val prefs: SharedPreferences = + appContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) + + val http: HttpTransport = OkHttpTransport() + + val anisetteProvider: AnisetteProvider by lazy { + createAndroidAnisetteProvider(appContext, http) + } + + val anisetteClient: AnisetteClient by lazy { + AnisetteClient(anisetteProvider) + } + + val gsaClient: GsaClient by lazy { + GsaClient(http, anisetteClient) + } + + val mobileMeClient: MobileMeClient by lazy { + MobileMeClient(http, anisetteClient) + } + + val reportsClient: LocationReportsClient by lazy { + LocationReportsClient(http, anisetteClient) + } + + private var currentAccount: AppleAccount = loadAccount() + + fun getAccount(): AppleAccount = currentAccount + + @Synchronized + fun saveAccount(account: AppleAccount) { + currentAccount = account + prefs.edit().putString(KEY_ACCOUNT_JSON, account.exportToJson()).apply() + FileLog.i(TAG, "AppleAccount saved, state: ${account.loginState}") + } + + @Synchronized + fun clearAccount() { + currentAccount = AppleAccount() + prefs.edit().remove(KEY_ACCOUNT_JSON).apply() + FileLog.i(TAG, "AppleAccount cleared") + } + + fun isLoggedIn(): Boolean = + currentAccount.loginState == LoginState.LOGGED_IN && currentAccount.getSearchPartyToken() != null + + fun createLoginService(): AppleLoginService { + // 每次登录创建全新实例,避免旧会话残留或 2FA 死锁 + val freshAccount = AppleAccount() + return AppleLoginService( + account = freshAccount, + http = http, + anisette = anisetteClient, + gsa = gsaClient, + mobileMe = mobileMeClient, + ) + } + + private fun loadAccount(): AppleAccount { + val json = prefs.getString(KEY_ACCOUNT_JSON, null) + if (!json.isNullOrEmpty()) { + try { + return AppleAccount.restoreFromJson(json) + } catch (e: Exception) { + FileLog.w(TAG, "Failed to restore AppleAccount from prefs: ${e.message}") + } + } + return AppleAccount() + } + + companion object { + private const val TAG = "AppleAccountManager" + private const val PREF_NAME = "yuitag_apple_account" + private const val KEY_ACCOUNT_JSON = "apple_account_json" + + @Volatile + private var INSTANCE: AppleAccountManager? = null + + fun getInstance(context: Context): AppleAccountManager { + return INSTANCE ?: synchronized(this) { + INSTANCE ?: AppleAccountManager(context.applicationContext).also { INSTANCE = it } + } + } + } +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/account/AppleLoginException.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/account/AppleLoginException.kt new file mode 100644 index 0000000..16b6ad3 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/account/AppleLoginException.kt @@ -0,0 +1,18 @@ +package com.reiyy.yuitag.apple.account + +/** + * Failure modes produced during Apple login or 2FA orchestration. + */ +class AppleLoginException( + val kind: Kind, + message: String, + cause: Throwable? = null, +) : RuntimeException(message, cause) { + + enum class Kind { + INVALID_CREDENTIALS, + UNHANDLED_PROTOCOL, + INVALID_STATE, + UNAUTHORIZED, + } +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/account/AppleLoginService.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/account/AppleLoginService.kt new file mode 100644 index 0000000..d6dd86d --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/account/AppleLoginService.kt @@ -0,0 +1,390 @@ +package com.reiyy.yuitag.apple.account + +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import com.reiyy.yuitag.apple.anisette.AnisetteClient +import com.reiyy.yuitag.apple.crypto.GsaCrypto +import com.reiyy.yuitag.apple.crypto.Srp6aGsa +import com.reiyy.yuitag.apple.gsa.GSA_CONNECTION +import com.reiyy.yuitag.apple.gsa.GsaClient +import com.reiyy.yuitag.apple.http.HttpRequest +import com.reiyy.yuitag.apple.http.HttpTransport +import com.reiyy.yuitag.apple.mobileme.MobileMeClient +import com.reiyy.yuitag.apple.plist.PlistValue +import com.reiyy.yuitag.apple.plist.XmlPlist +import kotlin.io.encoding.Base64 +import kotlin.io.encoding.ExperimentalEncodingApi + +/** + * Orchestrates Apple authentication across GSA SRP-6a, 2FA challenge dispatch, + * and MobileMe delegate exchange to obtain [AppleAccount] credentials and `searchPartyToken`. + */ +@OptIn(ExperimentalEncodingApi::class) +class AppleLoginService( + val account: AppleAccount, + private val http: HttpTransport, + private val anisette: AnisetteClient, + private val gsa: GsaClient, + private val mobileMe: MobileMeClient, +) : TwoFactorCoordinator { + + suspend fun login(username: String, password: String): LoginResult { + if (account.loginState == LoginState.REQUIRE_2FA) { + account.setLoginState(LoginState.LOGGED_OUT, null) + } + requireState(LoginState.LOGGED_OUT) + val afterGsa = gsaAuthenticate(username, password) + return if (afterGsa == LoginState.REQUIRE_2FA) { + val methods = fetchTwoFactorMethods() + if (methods.isEmpty()) { + throw AppleLoginException( + AppleLoginException.Kind.UNHANDLED_PROTOCOL, + "Apple ID 要求双重认证,但未能获取到可用的验证设备或验证手机号,请检查网络或稍后重试", + ) + } + LoginResult.RequireTwoFactor(methods = methods) + } else { + loginMobileMe() + LoginResult.LoggedIn + } + } + + private suspend fun fetchTwoFactorMethods(): List { + requireState(LoginState.REQUIRE_2FA) + val out = mutableListOf() + + if (account.accountInfo?.trustedDevice2fa == true) { + out += TwoFactorChallenge.TrustedDevice(coordinator = this) + } + + val html = twoFactorRequest("GET", ENDPOINT_2FA_METHODS, data = null, extraHeaders = null) + for (number in extractPhoneNumbers(html)) { + val id = (number["id"] as? Number)?.toInt() ?: -1 + val label = number["numberWithDialCode"] as? String ?: "-" + out += TwoFactorChallenge.Sms(id, label, coordinator = this) + } + return out + } + + override suspend fun requestSms(phoneNumberId: Int) { + requireState(LoginState.REQUIRE_2FA) + val data = mutableMapOf( + "phoneNumber" to mapOf("id" to phoneNumberId), + "mode" to "sms", + ) + twoFactorRequest("PUT", ENDPOINT_2FA_SMS_REQUEST, data, null) + } + + override suspend fun submitSms(phoneNumberId: Int, code: String): LoginResult { + requireState(LoginState.REQUIRE_2FA) + val data = mutableMapOf( + "phoneNumber" to mapOf("id" to phoneNumberId), + "securityCode" to mapOf("code" to code), + "mode" to "sms", + ) + twoFactorRequest("POST", ENDPOINT_2FA_SMS_SUBMIT, data, null) + + completeTwoFactor() + return LoginResult.LoggedIn + } + + override suspend fun requestTrustedDevice() { + requireState(LoginState.REQUIRE_2FA) + val headers = linkedMapOf( + "Content-Type" to "text/x-xml-plist", + "Accept" to "text/x-xml-plist", + ) + twoFactorRequest("GET", ENDPOINT_2FA_TD_REQUEST, data = null, extraHeaders = headers) + } + + override suspend fun submitTrustedDevice(code: String): LoginResult { + requireState(LoginState.REQUIRE_2FA) + val headers = linkedMapOf( + "security-code" to code, + "Content-Type" to "text/x-xml-plist", + "Accept" to "text/x-xml-plist", + ) + twoFactorRequest("GET", ENDPOINT_2FA_TD_SUBMIT, data = null, extraHeaders = headers) + + completeTwoFactor() + return LoginResult.LoggedIn + } + + private suspend fun completeTwoFactor() { + val after = gsaAuthenticate(null, null) + if (after != LoginState.AUTHENTICATED) { + throw AppleLoginException( + AppleLoginException.Kind.UNHANDLED_PROTOCOL, + "Unexpected state after submitting 2FA: $after", + ) + } + loginMobileMe() + } + + private suspend fun gsaAuthenticate(username: String?, password: String?): LoginState { + username?.let { account.username = it } + password?.let { account.password = it } + val u = account.username ?: throw AppleLoginException( + AppleLoginException.Kind.INVALID_STATE, "No username or password specified" + ) + val p = account.password ?: throw AppleLoginException( + AppleLoginException.Kind.INVALID_STATE, "No username or password specified" + ) + + val srp = Srp6aGsa(u) + val a2k = srp.startAuthentication() + + val init = mutableMapOf( + "A2k" to a2k, + "u" to u, + "ps" to listOf("s2k", "s2k_fo"), + "o" to "init", + ) + val initResp = gsa.request(init) + + val initStatus = requireStatus(initResp) + if (initStatus.int64("ec") != 0L) { + throw AppleLoginException( + AppleLoginException.Kind.INVALID_CREDENTIALS, + "Email verification failed: ${initStatus.string("em")} (${initStatus.int64("ec")})", + ) + } + val sp = initResp.string("sp") + if (sp != GsaCrypto.PROTOCOL_S2K && sp != GsaCrypto.PROTOCOL_S2K_FO) { + throw AppleLoginException( + AppleLoginException.Kind.UNHANDLED_PROTOCOL, + "Unsupported SRP protocol: $sp", + ) + } + + val salt = initResp.data("s") + ?: throw protocolError("GSA init response missing 's' (salt)") + val serverB = initResp.data("B") + ?: throw protocolError("GSA init response missing 'B' (server ephemeral)") + val iterations = initResp.int64("i")?.toInt() + ?: throw protocolError("GSA init response missing 'i' (iterations)") + val cookie = initResp["c"] + ?: throw protocolError("GSA init response missing 'c' (cookie)") + + val pbkdfPw = GsaCrypto.encryptPassword(p, salt, iterations, sp) + val m1 = srp.processChallenge(salt, serverB, pbkdfPw) + + val complete = mutableMapOf( + "c" to cookie, + "M1" to m1, + "u" to u, + "o" to "complete", + ) + val completeResp = gsa.request(complete) + + val completeStatus = requireStatus(completeResp) + if (completeStatus.int64("ec") != 0L) { + throw AppleLoginException( + AppleLoginException.Kind.INVALID_CREDENTIALS, + "Password authentication failed: ${completeStatus.string("em")} (${completeStatus.int64("ec")})", + ) + } + + val m2 = completeResp.data("M2") + ?: throw protocolError("GSA complete response missing 'M2'") + if (!srp.verifySession(m2)) { + throw AppleLoginException( + AppleLoginException.Kind.UNHANDLED_PROTOCOL, + "Failed to verify SRP session (M2 mismatch)", + ) + } + + val spdCiphertext = completeResp.data("spd") + ?: throw protocolError("GSA complete response missing 'spd'") + val sessionKey = srp.getSessionKey() + ?: throw protocolError("SRP session key unavailable") + val spdPlain = GsaCrypto.decryptSpdAesCbc(sessionKey, spdCiphertext) + val spd = XmlPlist.parse(spdPlain) as? PlistValue.Dict + ?: throw protocolError("SPD payload is not a ") + + val info = AccountInfo( + accountName = spd.string("acname"), + firstName = spd.string("fn"), + lastName = spd.string("ln"), + trustedDevice2fa = false, + ) + account.accountInfo = info + + val au = completeStatus.string("au") + return when (au) { + "secondaryAuth", "trustedDeviceSecondaryAuth" -> { + info.trustedDevice2fa = au == "trustedDeviceSecondaryAuth" + account.setLoginState( + LoginState.REQUIRE_2FA, + mapOf( + "adsid" to spd.string("adsid").orEmpty(), + "idms_token" to spd.string("GsIdmsToken").orEmpty(), + ), + ) + LoginState.REQUIRE_2FA + } + null -> { + val idmsPet = spd.dict("t") + ?.dict("com.apple.gs.idms.pet") + ?.string("token") + .orEmpty() + account.setLoginState( + LoginState.AUTHENTICATED, + mapOf( + "idms_pet" to idmsPet, + "adsid" to spd.string("adsid").orEmpty(), + ), + ) + LoginState.AUTHENTICATED + } + else -> throw AppleLoginException( + AppleLoginException.Kind.UNHANDLED_PROTOCOL, + "Unknown auth value: $au", + ) + } + } + + private suspend fun loginMobileMe(): LoginState { + requireState(LoginState.AUTHENTICATED) + val idmsPet = account.loginStateString("idms_pet") ?: "" + val adsid = account.loginStateString("adsid") ?: "" + val uname = account.username + ?: throw AppleLoginException(AppleLoginException.Kind.INVALID_STATE, "No username") + + val response = mobileMe.login(uname, idmsPet, adsid) + + val delegates = response.dict("delegates") + val mobileMeData = delegates?.dict("com.apple.mobileme") + + val status = mobileMeData?.int64("status") ?: response.int64("status") + if (status == null || status != 0L) { + val msg = mobileMeData?.string("status-message") ?: response.string("status-message") + throw AppleLoginException( + AppleLoginException.Kind.UNHANDLED_PROTOCOL, + "com.apple.mobileme login failed: $status / $msg", + ) + } + + val dsidStr = when (val d = response["dsid"]) { + is PlistValue.Str -> d.value + is PlistValue.Int64 -> d.value.toString() + else -> "" + } + val serviceData = mobileMeData?.get("service-data")?.let(::plistToAny) ?: emptyMap() + + // 登录成功获取到授权令牌后,立即清空内存中的主密码,防止明文持久化到磁盘 + account.password = null + account.setLoginState( + LoginState.LOGGED_IN, + mapOf( + "dsid" to dsidStr, + "mobileme_data" to serviceData, + ), + ) + return LoginState.LOGGED_IN + } + + private suspend fun twoFactorRequest( + method: String, + url: String, + data: Map?, + extraHeaders: Map?, + ): String { + val adsid = account.loginStateString("adsid") ?: "" + val idmsToken = account.loginStateString("idms_token") ?: "" + val identityToken = Base64.encode("$adsid:$idmsToken".encodeToByteArray()) + + val headers = linkedMapOf( + "User-Agent" to "Xcode", + "Accept-Language" to "en-us", + "X-Apple-Identity-Token" to identityToken, + GSA_CONNECTION, + ) + extraHeaders?.let { headers.putAll(it) } + headers.putAll(anisette.getHeaders(withClientInfo = true)) + + val body = data?.let { + if ("Content-Type" !in headers) { + headers["Content-Type"] = "application/json" + } + GSON.toJson(it).encodeToByteArray() + } + + val resp = http.execute( + HttpRequest( + method = method, + url = url, + headers = headers, + body = body, + ) + ) + if (!resp.isOk()) { + throw AppleLoginException( + AppleLoginException.Kind.UNHANDLED_PROTOCOL, + "2FA request failed: HTTP ${resp.statusCode}", + ) + } + return resp.body.decodeToString() + } + + @Suppress("UNCHECKED_CAST") + private fun extractPhoneNumbers(html: String): List> { + val pattern = Regex( + """]*class="boot_args"[^>]*>([\s\S]*?)""", + RegexOption.IGNORE_CASE, + ) + val match = pattern.find(html) ?: return emptyList() + val json = match.groupValues[1].trim() + return try { + val type = object : TypeToken>() {}.type + val root: Map = GSON.fromJson(json, type) + val direct = root["direct"] as? Map ?: return emptyList() + val pnv = direct["phoneNumberVerification"] as? Map ?: return emptyList() + (pnv["trustedPhoneNumbers"] as? List>) ?: emptyList() + } catch (_: Exception) { + emptyList() + } + } + + private fun requireState(expected: LoginState) { + if (account.loginState != expected) { + throw AppleLoginException( + AppleLoginException.Kind.INVALID_STATE, + "Required state $expected but account is ${account.loginState}", + ) + } + } + + private fun requireStatus(resp: PlistValue.Dict): PlistValue.Dict = + resp.dict("Status") + ?: throw protocolError("GSA response missing 'Status' dictionary") + + private fun protocolError(message: String): AppleLoginException = + AppleLoginException(AppleLoginException.Kind.UNHANDLED_PROTOCOL, message) + + private fun plistToAny(value: PlistValue): Any? = when (value) { + PlistValue.Null -> null + is PlistValue.Bool -> value.value + is PlistValue.Int64 -> value.value + is PlistValue.Real -> value.value + is PlistValue.Str -> value.value + is PlistValue.Data -> Base64.encode(value.bytes) + is PlistValue.Date -> value.epochMillis + is PlistValue.Uid -> value.value + is PlistValue.Dict -> value.entries.mapValues { plistToAny(it.value) } + is PlistValue.Array -> value.items.map { plistToAny(it) } + } + + companion object { + private const val ENDPOINT_2FA_METHODS = "https://gsa.apple.com/auth" + private const val ENDPOINT_2FA_SMS_REQUEST = "https://gsa.apple.com/auth/verify/phone" + private const val ENDPOINT_2FA_SMS_SUBMIT = + "https://gsa.apple.com/auth/verify/phone/securitycode" + private const val ENDPOINT_2FA_TD_REQUEST = + "https://gsa.apple.com/auth/verify/trusteddevice" + private const val ENDPOINT_2FA_TD_SUBMIT = + "https://gsa.apple.com/grandslam/GsService2/validate" + + private val GSON = Gson() + } +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/account/LoginResult.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/account/LoginResult.kt new file mode 100644 index 0000000..e646d70 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/account/LoginResult.kt @@ -0,0 +1,9 @@ +package com.reiyy.yuitag.apple.account + +/** + * Outcome of an Apple login attempt or a 2FA challenge submission. + */ +sealed interface LoginResult { + data object LoggedIn : LoginResult + data class RequireTwoFactor(val methods: List) : LoginResult +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/account/LoginState.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/account/LoginState.kt new file mode 100644 index 0000000..710c802 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/account/LoginState.kt @@ -0,0 +1,16 @@ +package com.reiyy.yuitag.apple.account + +/** + * State machine position of an [AppleAccount]. + */ +enum class LoginState(val value: Int) { + LOGGED_OUT(0), + REQUIRE_2FA(1), + AUTHENTICATED(2), + LOGGED_IN(3); + + companion object { + fun fromValue(v: Int): LoginState = entries.firstOrNull { it.value == v } + ?: throw IllegalArgumentException("Unknown login state value: $v") + } +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/account/TwoFactorChallenge.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/account/TwoFactorChallenge.kt new file mode 100644 index 0000000..7da7021 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/account/TwoFactorChallenge.kt @@ -0,0 +1,39 @@ +package com.reiyy.yuitag.apple.account + +sealed class TwoFactorChallenge { + abstract val displayName: String + protected abstract val coordinator: TwoFactorCoordinator + + suspend fun request() = when (this) { + is Sms -> coordinator.requestSms(phoneNumberId) + is TrustedDevice -> coordinator.requestTrustedDevice() + } + + suspend fun submit(code: String): LoginResult = when (this) { + is Sms -> coordinator.submitSms(phoneNumberId, code) + is TrustedDevice -> coordinator.submitTrustedDevice(code) + } + + @ConsistentCopyVisibility + data class Sms internal constructor( + val phoneNumberId: Int, + val phoneNumber: String, + override val coordinator: TwoFactorCoordinator, + ) : TwoFactorChallenge() { + override val displayName: String get() = "短信验证码 ($phoneNumber)" + } + + @ConsistentCopyVisibility + data class TrustedDevice internal constructor( + override val coordinator: TwoFactorCoordinator, + ) : TwoFactorChallenge() { + override val displayName: String get() = "受信任 Apple 设备弹窗提示" + } +} + +interface TwoFactorCoordinator { + suspend fun requestSms(phoneNumberId: Int) + suspend fun submitSms(phoneNumberId: Int, code: String): LoginResult + suspend fun requestTrustedDevice() + suspend fun submitTrustedDevice(code: String): LoginResult +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/AndroidAnisetteProvider.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/AndroidAnisetteProvider.kt new file mode 100644 index 0000000..02077c3 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/AndroidAnisetteProvider.kt @@ -0,0 +1,35 @@ +package com.reiyy.yuitag.apple.anisette + +import android.content.Context +import com.reiyy.yuitag.apple.http.HttpTransport +import io.github.tieo.taghistory.anisette.AnisetteException +import io.github.tieo.taghistory.anisette.FileMachineStorage +import io.github.tieo.taghistory.anisette.JniCoreAdi +import kotlinx.coroutines.Dispatchers +import java.io.File + +/** + * Creates an [AnisetteProvider] configured for Android using the emulated macOS CoreADI binary. + */ +fun createAndroidAnisetteProvider(context: Context, http: HttpTransport): AnisetteProvider { + val app = context.applicationContext + return MacAnisetteProvider( + openAdi = { hostUuid, store -> + val local = CoreAdiDownloader.getLocalFile(app) + val bytes = if (local.exists() && local.length() > 0) { + local.readBytes() + } else { + try { + app.assets.open(CoreAdiDownloader.ASSET_PATH).use { it.readBytes() } + } catch (e: Exception) { + throw AnisetteException("macOS CoreADI binary not found in storage or assets: ${e.message}", e) + } + } + JniCoreAdi(bytes, hostUuid, store) + }, + storage = FileMachineStorage(File(app.filesDir, "anisette/machine.json")), + http = http, + nativeVersion = JniCoreAdi::version, + blockingContext = Dispatchers.IO, + ) +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/AnisetteClient.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/AnisetteClient.kt new file mode 100644 index 0000000..4821fd5 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/AnisetteClient.kt @@ -0,0 +1,77 @@ +package com.reiyy.yuitag.apple.anisette + +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * Builds the anisette part of Apple requests from [provider]. + * Provider values are cached for [CACHE_TTL_SECONDS] seconds. + */ +class AnisetteClient( + private val provider: AnisetteProvider, + private val clockMillis: () -> Long = { System.currentTimeMillis() }, +) { + private var cachedHeaders: Map? = null + private var cacheExpiresAtMs: Long = 0L + private val refreshLock = Mutex() + + /** The machine every request is sent as. */ + suspend fun machine(): MachineIdentity = provider.machine() + + /** + * Anisette headers for a request. [withClientInfo] adds the client info + * trio expected by the 2FA endpoints (Xcode identity). + */ + suspend fun getHeaders(withClientInfo: Boolean = false): Map { + val headers = LinkedHashMap(fetchAnisetteDict()) + if (withClientInfo) { + headers["X-Mme-Client-Info"] = machine().clientInfoFor(XCODE_BUNDLE) + headers["X-Apple-App-Info"] = "com.apple.gs.xcode.auth" + headers["X-Xcode-Version"] = "11.2 (11B41)" + } + return headers + } + + /** + * "Client provided data": embedded in GSA SRP request body. + */ + suspend fun getCpd(): Map { + val out = linkedMapOf() + out["bootstrap"] = true + out["icscrec"] = true + out["pbe"] = false + out["prkgen"] = true + out["svct"] = "iCloud" + out.putAll(fetchAnisetteDict()) + return out + } + + /** + * Answers Apple's resync request (`hsc 434`) and invalidates cached headers. + */ + suspend fun resync(sim: ByteArray) { + refreshLock.withLock { + provider.resync(sim) + cachedHeaders = null + cacheExpiresAtMs = 0L + } + } + + private suspend fun fetchAnisetteDict(): Map { + cachedHeaders?.let { if (clockMillis() < cacheExpiresAtMs) return it } + + return refreshLock.withLock { + cachedHeaders?.let { if (clockMillis() < cacheExpiresAtMs) return@withLock it } + + val fresh = provider.getHeaders() + cachedHeaders = fresh + cacheExpiresAtMs = clockMillis() + CACHE_TTL_SECONDS * 1000L + fresh + } + } + + companion object { + const val CACHE_TTL_SECONDS: Int = 30 + const val XCODE_BUNDLE = "com.apple.AOSKit/282 (com.apple.dt.Xcode/3594.4.19)" + } +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/AnisetteProvider.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/AnisetteProvider.kt new file mode 100644 index 0000000..edb6af9 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/AnisetteProvider.kt @@ -0,0 +1,40 @@ +package com.reiyy.yuitag.apple.anisette + +/** + * Produces anisette data for Apple GSA / iCloud requests. + */ +interface AnisetteProvider { + /** + * One-time password and machine id plus the machine's identity: + * `X-Apple-I-MD`, `X-Apple-I-MD-M`, `X-Apple-I-MD-RINFO`, + * `X-Apple-I-MD-LU`, `X-Mme-Device-Id`, `X-Apple-I-SRL-NO`, + * `X-Apple-I-Client-Time`, `X-Apple-I-TimeZone`, `X-Apple-Locale`, + * `loc`. Provisions the machine with Apple first if it never was. + */ + suspend fun getHeaders(): Map + + /** The machine the headers belong to. Provisions it first if it never was. */ + suspend fun machine(): MachineIdentity + + /** + * Answers Apple's resync request (`hsc 434`), whose `X-Apple-I-MD-DATA` is [sim]. + */ + suspend fun resync(sim: ByteArray) + + /** Underlying ottjni crate version. */ + suspend fun version(): String +} + +/** + * Machine identity claimed by the emulated Mac. + */ +data class MachineIdentity( + val deviceId: String, + val localUserUuid: String, + val serial: String, + val clientInfo: String, +) { + val platform: String get() = clientInfo.substringBeforeLast(" <") + + fun clientInfoFor(bundle: String): String = "$platform <$bundle>" +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/CoreAdiDownloader.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/CoreAdiDownloader.kt new file mode 100644 index 0000000..32f7c57 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/CoreAdiDownloader.kt @@ -0,0 +1,100 @@ +package com.reiyy.yuitag.apple.anisette + +import android.content.Context +import com.reiyy.yuitag.ble.FileLog +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.File +import java.io.InputStream +import java.security.MessageDigest + +/** + * Manages Apple's authentic macOS CoreADI x86_64 binary. + * + * Supports: + * 1. Bundled asset: `assets/coreadi/CoreADI.x86_64` + * 2. Cached file in app private files: `files/coreadi/CoreADI.x86_64` + * 3. User manual import from external file with SHA-256 verification + */ +object CoreAdiDownloader { + private const val TAG = "CoreAdiDownloader" + const val ASSET_PATH = "coreadi/CoreADI.x86_64" + const val LOCAL_FILENAME = "coreadi/CoreADI.x86_64" + + /** Expected SHA-256 hash of iTunes 12.8.3 macOS CoreADI.x86_64 */ + const val EXPECTED_SHA256 = "2eafc3c79c7f41a8afbfbeaaf23ee5dab5ad5bda55ec8e54dbc0ddf1d20ce630" + + fun getLocalFile(context: Context): File = + File(context.filesDir, LOCAL_FILENAME) + + fun isReady(context: Context): Boolean { + val file = getLocalFile(context) + if (file.exists() && file.length() > 0) return true + return try { + context.assets.open(ASSET_PATH).use { true } + } catch (_: Exception) { + false + } + } + + suspend fun getCoreAdiBytes(context: Context): ByteArray? = withContext(Dispatchers.IO) { + val local = getLocalFile(context) + if (local.exists() && local.length() > 0) { + try { + val bytes = local.readBytes() + if (verifyHash(bytes)) return@withContext bytes + FileLog.w(TAG, "Local CoreADI hash mismatch, deleting corrupted file") + local.delete() + } catch (e: Exception) { + FileLog.w(TAG, "Failed to read local CoreADI: ${e.message}") + } + } + + try { + val bytes = context.assets.open(ASSET_PATH).use { it.readBytes() } + if (verifyHash(bytes)) { + // Cache into local file for uniform access + try { + local.parentFile?.mkdirs() + local.writeBytes(bytes) + } catch (_: Exception) {} + return@withContext bytes + } else { + FileLog.w(TAG, "Asset CoreADI hash mismatch!") + } + } catch (_: Exception) { + // Asset not bundled in this build + } + + null + } + + suspend fun importFromStream(context: Context, inputStream: InputStream): Boolean = withContext(Dispatchers.IO) { + try { + val bytes = inputStream.use { it.readBytes() } + if (verifyHash(bytes)) { + val local = getLocalFile(context) + local.parentFile?.mkdirs() + local.writeBytes(bytes) + FileLog.i(TAG, "Successfully imported CoreADI.x86_64 (${bytes.size} bytes)") + true + } else { + val hash = sha256Hex(bytes) + FileLog.w(TAG, "Import rejected: hash mismatch. Got $hash, expected $EXPECTED_SHA256") + false + } + } catch (e: Exception) { + FileLog.w(TAG, "Import failed: ${e.message}") + false + } + } + + fun verifyHash(bytes: ByteArray): Boolean = + sha256Hex(bytes).equals(EXPECTED_SHA256, ignoreCase = true) + + private fun sha256Hex(bytes: ByteArray): String { + val md = MessageDigest.getInstance("SHA-256") + val digest = md.digest(bytes) + return digest.joinToString("") { "%02x".format(it) } + } +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/MacAnisetteProvider.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/MacAnisetteProvider.kt new file mode 100644 index 0000000..9918cd8 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/anisette/MacAnisetteProvider.kt @@ -0,0 +1,215 @@ +package com.reiyy.yuitag.apple.anisette + +import com.google.gson.Gson +import com.reiyy.yuitag.apple.gsa.GSA_CONNECTION +import com.reiyy.yuitag.apple.http.HttpRequest +import com.reiyy.yuitag.apple.http.HttpTransport +import com.reiyy.yuitag.apple.plist.PlistValue +import com.reiyy.yuitag.apple.plist.XmlPlist +import com.reiyy.yuitag.apple.plist.anyToPlist +import io.github.tieo.taghistory.anisette.AnisetteException +import io.github.tieo.taghistory.anisette.CoreAdi +import io.github.tieo.taghistory.anisette.MachineStorage +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import java.time.Instant +import kotlin.coroutines.CoroutineContext +import kotlin.io.encoding.Base64 +import kotlin.io.encoding.ExperimentalEncodingApi +import kotlin.random.Random + +/** + * Anisette provider using Apple's macOS CoreADI run under Unicorn x86_64 emulation. + * Registers a virtual Mac identity with Apple's MidService once, saving state to [storage]. + */ +@OptIn(ExperimentalEncodingApi::class) +class MacAnisetteProvider( + private val openAdi: (hostUuid: ByteArray, store: ByteArray) -> CoreAdi, + private val storage: MachineStorage, + private val http: HttpTransport, + private val nativeVersion: () -> String, + private val clockMillis: () -> Long = { System.currentTimeMillis() }, + private val random: Random = Random.Default, + private val blockingContext: CoroutineContext = Dispatchers.IO, +) : AnisetteProvider { + + private val lock = Mutex() + private var machine: MachineFile? = null + private var adi: CoreAdi? = null + private var provisionedChecked = false + + override suspend fun version(): String = nativeVersion() + + override suspend fun machine(): MachineIdentity = serialized { provisioned().first.identity() } + + override suspend fun getHeaders(): Map = serialized { + val (file, core) = provisioned() + val headers = core.headers() + save(file, core) + linkedMapOf( + "X-Apple-I-Client-Time" to isoTime(), + "X-Apple-I-TimeZone" to "UTC", + "loc" to LOCALE, + "X-Apple-Locale" to LOCALE, + "X-Apple-I-MD" to Base64.encode(headers.otp), + "X-Apple-I-MD-LU" to Base64.encode(file.localUserUuid.encodeToByteArray()), + "X-Apple-I-MD-M" to Base64.encode(headers.mid), + "X-Apple-I-MD-RINFO" to headers.routing.toString(), + "X-Mme-Device-Id" to file.deviceId.uppercase(), + "X-Apple-I-SRL-NO" to file.serial, + ) + } + + override suspend fun resync(sim: ByteArray) = serialized { + val (file, core) = provisioned() + val sync = core.sync(sim) + save(file, core) + val urls = urlBag(file) + val request = linkedMapOf( + "srm" to Base64.encode(sync.srm), + "X-Apple-I-MD-M" to Base64.encode(sync.mid), + ) + file.routing?.let { request["X-Apple-I-MD-RINFO"] = it } + val status = midService(file, urls.require("midSyncMachine"), request).dict("Status") + val ec = status?.int64("ec") + if (ec != 0L) { + throw AnisetteException("Apple refused the machine's resync: ec=$ec ${status?.string("em").orEmpty()}") + } + } + + private suspend fun serialized(block: suspend () -> T): T = + lock.withLock { withContext(blockingContext) { block() } } + + private suspend fun provisioned(): Pair { + val file = machine ?: load().also { machine = it } + val core = adi ?: openAdi(file.hostUuidBytes(), file.storeBytes()).also { adi = it } + if (!provisionedChecked) { + if (!core.isProvisioned()) provision(file, core) + provisionedChecked = true + } + return machine!! to core + } + + private suspend fun provision(file: MachineFile, core: CoreAdi) { + val urls = urlBag(file) + val spim = midService(file, urls.require("midStartProvisioning"), emptyMap()).string("spim") + ?: throw AnisetteException("midStartProvisioning gave no spim") + val begun = core.provisioningBegin(Base64.decode(spim)) + val finished = midService( + file, + urls.require("midFinishProvisioning"), + mapOf("cpim" to Base64.encode(begun.cpim)), + ) + val ptm = finished.string("ptm") ?: throw AnisetteException("midFinishProvisioning gave no ptm") + val tk = finished.string("tk") ?: throw AnisetteException("midFinishProvisioning gave no tk") + val routing = when (val r = finished["X-Apple-I-MD-RINFO"]) { + is PlistValue.Int64 -> r.value + is PlistValue.Str -> r.value.toLongOrNull() ?: 0L + else -> 0L + } + core.provisioningFinish(begun.session, Base64.decode(ptm), Base64.decode(tk), routing) + val updated = file.copy(routing = routing, provisionedAtMs = clockMillis()) + machine = updated + save(updated, core) + } + + private fun load(): MachineFile { + storage.read()?.let { bytes -> + runCatching { GSON.fromJson(bytes.decodeToString(), MachineFile::class.java) } + .getOrNull() + ?.takeIf { it.version == MachineFile.VERSION } + ?.let { return it } + } + return mint().also { storage.write(GSON.toJson(it).encodeToByteArray()) } + } + + private fun save(file: MachineFile, core: CoreAdi) { + val updated = file.copy(storeB64 = Base64.encode(core.store())) + machine = updated + storage.write(GSON.toJson(updated).encodeToByteArray()) + } + + private fun mint(): MachineFile = MachineFile( + version = MachineFile.VERSION, + hostUuid = random.nextBytes(16).toHex(), + deviceId = "00006000-" + random.nextBytes(8).toHex().uppercase(), + localUserUuid = random.nextBytes(16).toHex().uppercase(), + serial = "C02" + (1..9).map { SERIAL_ALPHABET[random.nextInt(SERIAL_ALPHABET.length)] }.joinToString(""), + clientInfo = CLIENT_INFO, + ) + + private suspend fun urlBag(file: MachineFile): Map { + val response = http.execute(HttpRequest("GET", LOOKUP_URL, midServiceHeaders(file, clientTime = false))) + if (!response.isOk()) throw AnisetteException("GSA lookup failed: HTTP ${response.statusCode}") + val urls = (XmlPlist.parse(response.body) as? PlistValue.Dict)?.dict("urls") + ?: throw AnisetteException("GSA lookup has no urls") + return urls.entries.mapNotNull { (k, v) -> (v as? PlistValue.Str)?.let { k to it.value } }.toMap() + } + + private suspend fun midService(file: MachineFile, url: String, request: Map): PlistValue.Dict { + val body = XmlPlist.encode( + anyToPlist(linkedMapOf("Header" to emptyMap(), "Request" to request)), + ) + val response = http.execute(HttpRequest("POST", url, midServiceHeaders(file, clientTime = true), body)) + if (!response.isOk()) throw AnisetteException("${url.substringAfterLast('/')} failed: HTTP ${response.statusCode}") + return (XmlPlist.parse(response.body) as? PlistValue.Dict)?.dict("Response") + ?: throw AnisetteException("${url.substringAfterLast('/')} gave no Response") + } + + private fun midServiceHeaders(file: MachineFile, clientTime: Boolean): Map = + linkedMapOf( + "User-Agent" to MID_SERVICE_USER_AGENT, + "Content-Type" to "application/x-www-form-urlencoded", + "Accept" to "*/*", + "X-Mme-Device-Id" to file.deviceId, + "X-MMe-Client-Info" to file.clientInfo, + "X-Apple-I-MD-LU" to file.localUserUuid, + "X-Apple-Client-App-Name" to "Setup", + "X-Apple-I-SRL-NO" to file.serial, + GSA_CONNECTION, + ).apply { if (clientTime) put("X-Apple-I-Client-Time", isoTime()) } + + private fun isoTime(): String { + val s = Instant.ofEpochMilli(clockMillis()).toString() + val dot = s.indexOf('.') + return if (dot >= 0) s.substring(0, dot) + "Z" else s + } + + private fun Map.require(name: String): String = + this[name] ?: throw AnisetteException("GSA lookup has no $name") + + companion object { + const val LOOKUP_URL = "https://gsa.apple.com/grandslam/GsService2/lookup" + const val CLIENT_INFO = " " + const val CFNETWORK_DARWIN = "CFNetwork/1404.0.5 Darwin/22.2.0" + private const val MID_SERVICE_USER_AGENT = "akd/1.0 CFNetwork/1404.0.5 Darwin/22.3.0" + private const val LOCALE = "en_US" + private const val SERIAL_ALPHABET = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ" + private val GSON = Gson() + } +} + +data class MachineFile( + val version: Int = VERSION, + val hostUuid: String = "", + val deviceId: String = "", + val localUserUuid: String = "", + val serial: String = "", + val clientInfo: String = "", + val routing: Long? = null, + val provisionedAtMs: Long? = null, + val storeB64: String = "", +) { + fun identity() = MachineIdentity(deviceId, localUserUuid, serial, clientInfo) + fun hostUuidBytes(): ByteArray = hostUuid.chunked(2).map { it.toInt(16).toByte() }.toByteArray() + @OptIn(ExperimentalEncodingApi::class) + fun storeBytes(): ByteArray = if (storeB64.isEmpty()) ByteArray(0) else Base64.decode(storeB64) + + companion object { + const val VERSION = 1 + } +} + +private fun ByteArray.toHex(): String = joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') } diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/BigInt.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/BigInt.kt new file mode 100644 index 0000000..f155382 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/BigInt.kt @@ -0,0 +1,35 @@ +package com.reiyy.yuitag.apple.crypto + +import java.math.BigInteger + +/** + * Arbitrary-precision unsigned integer abstraction for SRP-6a. + * Only the operations SRP-6a needs are exposed. + * Matches pysrp's `long_to_bytes` semantics (no leading zero padding). + */ +class BigInt internal constructor(internal val value: BigInteger) : Comparable { + operator fun plus(other: BigInt): BigInt = BigInt(value.add(other.value)) + operator fun minus(other: BigInt): BigInt = BigInt(value.subtract(other.value)) + operator fun times(other: BigInt): BigInt = BigInt(value.multiply(other.value)) + fun mod(m: BigInt): BigInt = BigInt(value.mod(m.value)) + fun modPow(exponent: BigInt, m: BigInt): BigInt = + BigInt(value.modPow(exponent.value, m.value)) + + fun signum(): Int = value.signum() + + /** Unpadded big-endian byte representation (no leading zero). */ + fun toMinimalBytes(): ByteArray { + require(value.signum() >= 0) { "Cannot encode negative BigInt" } + val raw = value.toByteArray() + return if (raw.size > 1 && raw[0] == 0.toByte()) raw.copyOfRange(1, raw.size) else raw + } + + override fun compareTo(other: BigInt): Int = value.compareTo(other.value) + override fun equals(other: Any?): Boolean = other is BigInt && value == other.value + override fun hashCode(): Int = value.hashCode() + override fun toString(): String = value.toString() +} + +fun bigIntFromBytes(bytes: ByteArray): BigInt = BigInt(BigInteger(1, bytes)) +fun bigIntFromString(value: String, radix: Int = 10): BigInt = BigInt(BigInteger(value, radix)) +fun bigIntOf(value: Long): BigInt = BigInt(BigInteger.valueOf(value)) diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/CryptoPrimitives.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/CryptoPrimitives.kt new file mode 100644 index 0000000..7ecc771 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/CryptoPrimitives.kt @@ -0,0 +1,84 @@ +package com.reiyy.yuitag.apple.crypto + +import java.security.MessageDigest +import javax.crypto.Cipher +import javax.crypto.Mac +import javax.crypto.spec.GCMParameterSpec +import javax.crypto.spec.IvParameterSpec +import javax.crypto.spec.SecretKeySpec + +/** + * Sync crypto primitives used by the GSA login and FindMy report decryptions. + */ +fun sha256(data: ByteArray): ByteArray = + MessageDigest.getInstance("SHA-256").digest(data) + +fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray { + val mac = Mac.getInstance("HmacSHA256") + mac.init(SecretKeySpec(key, "HmacSHA256")) + return mac.doFinal(data) +} + +/** + * PBKDF2-HMAC-SHA256 over an arbitrary-byte password. + */ +fun pbkdf2HmacSha256( + password: ByteArray, + salt: ByteArray, + iterations: Int, + dkLenBytes: Int, +): ByteArray { + val prf = Mac.getInstance("HmacSHA256") + prf.init(SecretKeySpec(password, "HmacSHA256")) + val hLen = prf.macLength + val blocks = (dkLenBytes + hLen - 1) / hLen + val out = ByteArray(blocks * hLen) + + for (i in 1..blocks) { + prf.reset() + prf.update(salt) + prf.update(intBigEndian(i)) + var u = prf.doFinal() + val t = u.copyOf() + for (j in 1 until iterations) { + prf.reset() + u = prf.doFinal(u) + for (k in 0 until hLen) t[k] = (t[k].toInt() xor u[k].toInt()).toByte() + } + t.copyInto(out, destinationOffset = (i - 1) * hLen) + } + return if (out.size == dkLenBytes) out else out.copyOf(dkLenBytes) +} + +/** AES-128-CBC decrypt with PKCS#7 padding. Throws on auth/pad failure. */ +fun aesCbcDecryptPkcs7(key: ByteArray, iv: ByteArray, ciphertext: ByteArray): ByteArray { + val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") + cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), IvParameterSpec(iv)) + return cipher.doFinal(ciphertext) +} + +/** + * AES-128-GCM decrypt used by the FindMy location-report payload. + * Concatenation of raw ciphertext bytes and 16-byte authentication tag. + */ +fun aesGcmDecrypt( + key: ByteArray, + iv: ByteArray, + ciphertextWithTag: ByteArray, + tagLenBits: Int = 128, +): ByteArray { + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init( + Cipher.DECRYPT_MODE, + SecretKeySpec(key, "AES"), + GCMParameterSpec(tagLenBits, iv), + ) + return cipher.doFinal(ciphertextWithTag) +} + +private fun intBigEndian(value: Int): ByteArray = byteArrayOf( + ((value ushr 24) and 0xFF).toByte(), + ((value ushr 16) and 0xFF).toByte(), + ((value ushr 8) and 0xFF).toByte(), + (value and 0xFF).toByte(), +) diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/GsaCrypto.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/GsaCrypto.kt new file mode 100644 index 0000000..73bdbd1 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/GsaCrypto.kt @@ -0,0 +1,73 @@ +package com.reiyy.yuitag.apple.crypto + +/** + * GSA login flow crypto helpers: password-to-PBKDF2, SPD AES-CBC decrypt, X9.63 KDF. + */ +object GsaCrypto { + + const val PROTOCOL_S2K = "s2k" + const val PROTOCOL_S2K_FO = "s2k_fo" + + /** + * Apple's GSA password pre-hash. + */ + fun encryptPassword( + password: String, + salt: ByteArray, + iterations: Int, + protocol: String, + ): ByteArray { + require(protocol == PROTOCOL_S2K || protocol == PROTOCOL_S2K_FO) { + "Unsupported SRP protocol: $protocol" + } + val preHash = sha256(password.encodeToByteArray()) + val pbkdfPassword = when (protocol) { + PROTOCOL_S2K -> preHash + else -> toLowerHex(preHash).encodeToByteArray() + } + return pbkdf2HmacSha256(pbkdfPassword, salt, iterations, 32) + } + + /** + * SPD = "Signed Plist Data" blob returned by the GSA server. + * AES-128-CBC with key and IV derived from the SRP session key via HMAC-SHA256. + */ + fun decryptSpdAesCbc(sessionKey: ByteArray, ciphertext: ByteArray): ByteArray { + val extraKey = hmacSha256(sessionKey, "extra data key:".encodeToByteArray()) + val extraIvFull = hmacSha256(sessionKey, "extra data iv:".encodeToByteArray()) + val iv = extraIvFull.copyOfRange(0, 16) + return aesCbcDecryptPkcs7(extraKey, iv, ciphertext) + } + + /** + * ANSI X9.63 KDF with SHA-256. + */ + fun x963Kdf(secret: ByteArray, sharedInfo: ByteArray, length: Int): ByteArray { + val hLen = 32 + val blocks = (length + hLen - 1) / hLen + val out = ByteArray(blocks * hLen) + for (i in 1..blocks) { + val block = sha256(secret + intBigEndian(i) + sharedInfo) + block.copyInto(out, destinationOffset = (i - 1) * hLen) + } + return if (out.size == length) out else out.copyOf(length) + } + + private fun toLowerHex(bytes: ByteArray): String { + val hexChars = "0123456789abcdef" + val out = CharArray(bytes.size * 2) + for (i in bytes.indices) { + val v = bytes[i].toInt() and 0xFF + out[i * 2] = hexChars[v ushr 4] + out[i * 2 + 1] = hexChars[v and 0xF] + } + return out.concatToString() + } + + private fun intBigEndian(value: Int): ByteArray = byteArrayOf( + ((value ushr 24) and 0xFF).toByte(), + ((value ushr 16) and 0xFF).toByte(), + ((value ushr 8) and 0xFF).toByte(), + (value and 0xFF).toByte(), + ) +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/Rng.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/Rng.kt new file mode 100644 index 0000000..f3db245 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/Rng.kt @@ -0,0 +1,15 @@ +package com.reiyy.yuitag.apple.crypto + +import java.security.SecureRandom + +/** + * Cryptographically secure random source. + */ +fun interface Rng { + fun nextBytes(out: ByteArray) +} + +fun secureRng(): Rng { + val sr = SecureRandom() + return Rng { out -> sr.nextBytes(out) } +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/Srp6aGsa.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/Srp6aGsa.kt new file mode 100644 index 0000000..0a0b219 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/crypto/Srp6aGsa.kt @@ -0,0 +1,148 @@ +package com.reiyy.yuitag.apple.crypto + +/** + * SRP-6a client configured to match pysrp's + * `rfc5054_enable() + no_username_in_x() + SHA-256 + NG_2048` — which + * is exactly what Apple's GSA expects. + * + * Quirks that MUST match pysrp byte-for-byte: + * - `long_to_bytes(n)` is the MINIMUM big-endian encoding (no leading zero). + * - `k = H(N || PAD(g, len(N)))` with PAD enabled (RFC 5054 mode). + * - `u = H(PAD(A, N_BYTES) || PAD(B, N_BYTES))`. + * - `HNxorg` pads g to len(N_bytes) before hashing. + * - `no_username_in_x=true` means `x = H(salt || H(":" || password))`. + */ +class Srp6aGsa( + private val username: String, + private val rng: Rng = secureRng(), +) { + private var a: BigInt? = null + private var capitalA: BigInt? = null + + private var _sessionKey: ByteArray? = null + private var _m1: ByteArray? = null + private var expectedM2: ByteArray? = null + + /** + * Generate `A = g^a mod N` and return its unpadded big-endian bytes. + */ + fun startAuthentication(): ByteArray { + if (a == null) { + val buf = ByteArray(N_BYTES) + rng.nextBytes(buf) + buf[0] = (buf[0].toInt() or 0x80).toByte() + a = bigIntFromBytes(buf) + capitalA = G_2048.modPow(a!!, N_2048) + } + return capitalA!!.toMinimalBytes() + } + + /** + * Given server salt, server ephemeral B, and PBKDF2-derived password bytes, compute M1. + */ + fun processChallenge( + salt: ByteArray, + serverB: ByteArray, + pbkdfPassword: ByteArray, + ): ByteArray { + val capitalA = this.capitalA + ?: throw IllegalStateException("startAuthentication() must be called first") + val a = this.a!! + + val B = bigIntFromBytes(serverB) + check(B.mod(N_2048).signum() != 0) { "SRP-6a safety check failed: B mod N == 0" } + + // k = H(N || PAD(g, len(N))) + val k = bigIntFromBytes( + sha256( + N_2048.toMinimalBytes() + + padToLength(G_2048.toMinimalBytes(), N_BYTES) + ) + ) + + // u = H(PAD(A, N_BYTES) || PAD(B, N_BYTES)) + val aPadded = padToLength(capitalA.toMinimalBytes(), N_BYTES) + val bPadded = padToLength(B.toMinimalBytes(), N_BYTES) + val u = bigIntFromBytes(sha256(aPadded + bPadded)) + check(u.signum() != 0) { "SRP-6a safety check failed: u == 0" } + + // x = H(salt || H(":" || pbkdfPassword)) (no_username_in_x=true) + val inner = sha256(byteArrayOf(':'.code.toByte()) + pbkdfPassword) + val xBytes = sha256(salt + inner) + val xInt = bigIntFromBytes(xBytes) + + // v = g^x mod N + val v = G_2048.modPow(xInt, N_2048) + + // S = (B - k*v)^(a + u*x) mod N + val base = (B - k * v).mod(N_2048) + val exp = a + u * xInt + val S = base.modPow(exp, N_2048) + + // K = SHA256(long_to_bytes(S)) + val sBytes = S.toMinimalBytes() + val sessionKey = sha256(sBytes) + _sessionKey = sessionKey + + // M1 = H(HNxorg || H(I) || s || long_to_bytes(A) || long_to_bytes(B) || K) + val hNxorg = hNxorG() + val iHash = sha256(username.encodeToByteArray()) + val aBytes = capitalA.toMinimalBytes() + val bBytes = B.toMinimalBytes() + + val m1 = sha256(hNxorg + iHash + salt + aBytes + bBytes + sessionKey) + _m1 = m1 + + // H_AMK = SHA256(long_to_bytes(A) || M1 || K) — server returns this as M2. + expectedM2 = sha256(aBytes + m1 + sessionKey) + return m1 + } + + /** Verify the server's M2 matches our expected `H(A || M1 || K)`. */ + fun verifySession(serverM2: ByteArray): Boolean { + val expected = expectedM2 + ?: throw IllegalStateException("processChallenge() must be called first") + return constantTimeEquals(expected, serverM2) + } + + fun getSessionKey(): ByteArray? = _sessionKey?.copyOf() + fun getM1(): ByteArray? = _m1?.copyOf() + + private fun hNxorG(): ByteArray { + val hN = sha256(N_2048.toMinimalBytes()) + val hG = sha256(padToLength(G_2048.toMinimalBytes(), N_BYTES)) + val out = ByteArray(hN.size) + for (i in hN.indices) out[i] = (hN[i].toInt() xor hG[i].toInt()).toByte() + return out + } + + companion object { + private val N_2048 = bigIntFromString( + "AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050" + + "A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50" + + "E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B8" + + "55F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773B" + + "CA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748" + + "544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6" + + "AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6" + + "94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73", + 16, + ) + private val G_2048 = bigIntOf(2) + private const val N_BYTES = 256 + + private fun padToLength(src: ByteArray, length: Int): ByteArray { + if (src.size >= length) return src + val out = ByteArray(length) + src.copyInto(out, destinationOffset = length - src.size) + return out + } + + private fun constantTimeEquals(a: ByteArray, b: ByteArray): Boolean { + if (a.size != b.size) return false + var diff = 0 + for (i in a.indices) diff = diff or (a[i].toInt() xor b[i].toInt()) + return diff == 0 + } + } +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/gsa/GsaClient.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/gsa/GsaClient.kt new file mode 100644 index 0000000..f9e4bd4 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/gsa/GsaClient.kt @@ -0,0 +1,94 @@ +package com.reiyy.yuitag.apple.gsa + +import com.reiyy.yuitag.apple.anisette.AnisetteClient +import com.reiyy.yuitag.apple.http.HttpRequest +import com.reiyy.yuitag.apple.http.HttpTransport +import com.reiyy.yuitag.apple.plist.PlistValue +import com.reiyy.yuitag.apple.plist.XmlPlist +import com.reiyy.yuitag.apple.plist.anyToPlist +import kotlin.io.encoding.Base64 +import kotlin.io.encoding.ExperimentalEncodingApi + +/** + * Low-level client for Apple's Grand Slam Authentication endpoint. + * + * Handles plist envelope wrapping (Header + Request.cpd + parameters) + * and unwraps `["Response"]`. Supports Apple's `hsc 434` Resync challenge. + */ +class GsaClient( + private val http: HttpTransport, + private val anisette: AnisetteClient, + private val endpoint: String = ENDPOINT_GSA, +) { + + suspend fun request(parameters: Map): PlistValue.Dict { + val first = send(parameters) + val sim = resyncSim(first) ?: return first + anisette.resync(sim) + return send(parameters) + } + + private suspend fun send(parameters: Map): PlistValue.Dict { + val bodyDict = linkedMapOf( + "Header" to linkedMapOf("Version" to "1.0.1"), + "Request" to linkedMapOf().apply { + put("cpd", anisette.getCpd()) + putAll(parameters) + }, + ) + val plistBody = XmlPlist.encode(anyToPlist(bodyDict)) + + val req = HttpRequest( + method = "POST", + url = endpoint, + headers = linkedMapOf( + "Content-Type" to "text/x-xml-plist", + "Accept" to "*/*", + "User-Agent" to "akd/1.0 CFNetwork/978.0.7 Darwin/18.7.0", + "X-MMe-Client-Info" to anisette.machine().clientInfo, + GSA_CONNECTION, + ), + body = plistBody, + ) + + val resp = http.execute(req) + if (!resp.isOk()) { + val body = resp.body.decodeToString() + val title = Regex("(.*?)", RegexOption.IGNORE_CASE).find(body)?.groupValues?.get(1)?.trim() + val detail = body.take(300).replace(Regex("\\s+"), " ").trim() + throw GsaRequestException( + "GSA request failed: HTTP " + when { + !title.isNullOrEmpty() -> title.removePrefix("${resp.statusCode}").trim().let { "${resp.statusCode} $it" } + detail.isEmpty() -> "${resp.statusCode}" + else -> "${resp.statusCode}: $detail" + }, + ) + } + + val parsed = XmlPlist.parse(resp.body) + require(parsed is PlistValue.Dict) { "GSA response is not a " } + val response = parsed["Response"] + require(response is PlistValue.Dict) { "GSA response missing 'Response' dictionary" } + return response + } + + @OptIn(ExperimentalEncodingApi::class) + private fun resyncSim(response: PlistValue.Dict): ByteArray? { + val status = response.dict("Status") ?: return null + if (status.int64("hsc") != HSC_RESYNC) return null + return when (val sim = status["X-Apple-I-MD-DATA"]) { + is PlistValue.Data -> sim.bytes + is PlistValue.Str -> Base64.decode(sim.value) + else -> null + } + } + + companion object { + const val ENDPOINT_GSA: String = "https://gsa.apple.com/grandslam/GsService2" + private const val HSC_RESYNC = 434L + } +} + +class GsaRequestException(message: String) : RuntimeException(message) + +val GSA_CONNECTION: Pair = "Connection" to "close" diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/http/AppleTlsConfig.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/http/AppleTlsConfig.kt new file mode 100644 index 0000000..1a9725e --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/http/AppleTlsConfig.kt @@ -0,0 +1,156 @@ +package com.reiyy.yuitag.apple.http + +import okhttp3.OkHttpClient +import java.io.ByteArrayInputStream +import java.security.KeyStore +import java.security.cert.CertificateException +import java.security.cert.CertificateFactory +import java.security.cert.X509Certificate +import javax.net.ssl.SSLContext +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.TrustManagerFactory +import javax.net.ssl.X509TrustManager + +/** + * Injects Apple Root CAs into OkHttp so that connections to Apple's private-PKI servers + * (such as gsa.apple.com, setup.icloud.com) validate properly on Android devices + * whose system trust store does not contain Apple's root certificates. + */ +object AppleTlsConfig { + + private val APPLE_CERTS_PEM = listOf( + // Apple Root CA (2006-2035) + """-----BEGIN CERTIFICATE----- +MIIEuzCCA6OgAwIBAgIBAjANBgkqhkiG9w0BAQUFADBiMQswCQYDVQQGEwJVUzET +MBEGA1UEChMKQXBwbGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlv +biBBdXRob3JpdHkxFjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0EwHhcNMDYwNDI1MjE0 +MDM2WhcNMzUwMjA5MjE0MDM2WjBiMQswCQYDVQQGEwJVUzETMBEGA1UEChMKQXBw +bGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkx +FjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQDkkakJH5HbHkdQ6wXtXnmELes2oldMVeyLGYne+Uts9QerIjAC6Bg+ ++FAJ039BqJj50cpmnCRrEdCju+QbKsMflZ56DKRHi1vUFjczy8QPTc4UadHJGXL1 +XQ7Vf1+b8iUDulWPTV0N8WQ1IxVLFVkds5T39pyez1C6wVhQZ48ItCD3y6wsIG9w +tj8BMIy3Q88PnT3zK0koGsj+zrW5DtleHNbLPbU6rfQPDgCSC7EhFi501TwN22IW +q6NxkkdTVcGvL0Gz+PvjcM3mo0xFfh9Ma1CWQYnEdGILEINBhzOKgbEwWOxaBDKM +aLOPHd5lc/9nXmW8Sdh2nzMUZaF3lMktAgMBAAGjggF6MIIBdjAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUK9BpR5R2Cf70a40uQKb3 +R01/CF4wHwYDVR0jBBgwFoAUK9BpR5R2Cf70a40uQKb3R01/CF4wggERBgNVHSAE +ggEIMIIBBDCCAQAGCSqGSIb3Y2QFATCB8jAqBggrBgEFBQcCARYeaHR0cHM6Ly93 +d3cuYXBwbGUuY29tL2FwcGxlY2EvMIHDBggrBgEFBQcCAjCBthqBs1JlbGlhbmNl +IG9uIHRoaXMgY2VydGlmaWNhdGUgYnkgYW55IHBhcnR5IGFzc3VtZXMgYWNjZXB0 +YW5jZSBvZiB0aGUgdGhlbiBhcHBsaWNhYmxlIHN0YW5kYXJkIHRlcm1zIGFuZCBj +b25kaXRpb25zIG9mIHVzZSwgY2VydGlmaWNhdGUgcG9saWN5IGFuZCBjZXJ0aWZp +Y2F0aW9uIHByYWN0aWNlIHN0YXRlbWVudHMuMA0GCSqGSIb3DQEBBQUAA4IBAQBc +NplMLXi37Yyb3PN3m/J20ncwT8EfhYOFG5k9RzfyqZtAjizUsZAS2L70c5vu0mQP +y3lPNNiiPvl4/2vIB+x9OYOLUyDTOMSxv5pPCmv/K/xZpwUJfBdAVhEedNO3iyM7 +R6PVbyTi69G3cN8PReEnyvFteO3ntRcXqNx+IjXKJdXZD9Zr1KIkIxH3oayPc4Fg +xhtbCS+SsvhESPBgOJ4V9T0mZyCKM2r3DYLP3uujL/lTaltkwGMzd/c6ByxW69oP +IQ7aunMZT7XZNn/Bh1XZp5m5MkL72NVxnn6hUrcbvZNCJBIqxw8dtk2cXmPIS4AX +UKqK1drk/NAJBzewdXUh +-----END CERTIFICATE-----""", + + // Apple Root CA - G2 (2014-2039) + """-----BEGIN CERTIFICATE----- +MIIFkjCCA3qgAwIBAgIIAeDltYNno+AwDQYJKoZIhvcNAQEMBQAwZzEbMBkGA1UE +AwwSQXBwbGUgUm9vdCBDQSAtIEcyMSYwJAYDVQQLDB1BcHBsZSBDZXJ0aWZpY2F0 +aW9uIEF1dGhvcml0eTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UEBhMCVVMw +HhcNMTQwNDMwMTgxMDA5WhcNMzkwNDMwMTgxMDA5WjBnMRswGQYDVQQDDBJBcHBs +ZSBSb290IENBIC0gRzIxJjAkBgNVBAsMHUFwcGxlIENlcnRpZmljYXRpb24gQXV0 +aG9yaXR5MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzCCAiIwDQYJ +KoZIhvcNAQEBBQADggIPADCCAgoCggIBANgREkhI2imKScUcx+xuM23+TfvgHN6s +XuI2pyT5f1BrTM65MFQn5bPW7SXmMLYFN14UIhHF6Kob0vuy0gmVOKTvKkmMXT5x +ZgM4+xb1hYjkWpIMBDLyyED7Ul+f9sDx47pFoFDVEovy3d6RhiPw9bZyLgHaC/Yu +OQhfGaFjQQscp5TBhsRTL3b2CtcM0YM/GlMZ81fVJ3/8E7j4ko380yhDPLVoACVd +J2LT3VXdRCCQgzWTxb+4Gftr49wIQuavbfqeQMpOhYV4SbHXw8EwOTKrfl+q04tv +ny0aIWhwZ7Oj8ZhBbZF8+NfbqOdfIRqMM78xdLe40fTgIvS/cjTf94FNcX1RoeKz +8NMoFnNvzcytN31O661A4T+B/fc9Cj6i8b0xlilZ3MIZgIxbdMYs0xBTJh0UT8TU +gWY8h2czJxQI6bR3hDRSj4n4aJgXv8O7qhOTH11UL6jHfPsNFL4VPSQ08prcdUFm +IrQB1guvkJ4M6mL4m1k8COKWNORj3rw31OsMiANDC1CvoDTdUE0V+1ok2Az6DGOe +HwOx4e7hqkP0ZmUoNwIx7wHHHtHMn23KVDpA287PT0aLSmWaasZobNfMmRtHsHLD +d4/E92GcdB/O/WuhwpyUgquUoue9G7q5cDmVF8Up8zlYNPXEpMZ7YLlmQ1A/bmH8 +DvmGqmAMQ0uVAgMBAAGjQjBAMB0GA1UdDgQWBBTEmRNsGAPCe8CjoA1/coB6HHcm +jTAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQwF +AAOCAgEAUabz4vS4PZO/Lc4Pu1vhVRROTtHlznldgX/+tvCHM/jvlOV+3Gp5pxy+ +8JS3ptEwnMgNCnWefZKVfhidfsJxaXwU6s+DDuQUQp50DhDNqxq6EWGBeNjxtUVA +eKuowM77fWM3aPbn+6/Gw0vsHzYmE1SGlHKy6gLti23kDKaQwFd1z4xCfVzmMX3z +ybKSaUYOiPjjLUKyOKimGY3xn83uamW8GrAlvacp/fQ+onVJv57byfenHmOZ4VxG +/5IFjPoeIPmGlFYl5bRXOJ3riGQUIUkhOb9iZqmxospvPyFgxYnURTbImHy99v6Z +SYA7LNKmp4gDBDEZt7Y6YUX6yfIjyGNzv1aJMbDZfGKnexWoiIqrOEDCzBL/FePw +N983csvMmOa/orz6JopxVtfnJBtIRD6e/J/JzBrsQzwBvDR4yGn1xuZW7AYJNpDr +FEobXsmII9oDMJELuDY++ee1KG++P+w8j2Ud5cAeh6Squpj9kuNsJnfdBrRkBof0 +Tta6SqoWqPQFZ2aWuuJVecMsXUmPgEkrihLHdoBR37q9ZV0+N0djMenl9MU/S60E +inpxLK8JQzcPqOMyT/RFtm2XNuyE9QoB6he7hY1Ck3DDUOUUi78/w0EP3SIEIwiK +um1xRKtzCTrJ+VKACd+66eYWyi4uTLLT3OUEVLLUNIAytbwPF+E= +-----END CERTIFICATE-----""", + + // Apple Root CA - G3 (2014-2039) + """-----BEGIN CERTIFICATE----- +MIICQzCCAcmgAwIBAgIILcX8iNLFS5UwCgYIKoZIzj0EAwMwZzEbMBkGA1UEAwwS +QXBwbGUgUm9vdCBDQSAtIEczMSYwJAYDVQQLDB1BcHBsZSBDZXJ0aWZpY2F0aW9u +IEF1dGhvcml0eTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UEBhMCVVMwHhcN +MTQwNDMwMTgxOTA2WhcNMzkwNDMwMTgxOTA2WjBnMRswGQYDVQQDDBJBcHBsZSBS +b290IENBIC0gRzMxJjAkBgNVBAsMHUFwcGxlIENlcnRpZmljYXRpb24gQXV0aG9y +aXR5MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzB2MBAGByqGSM49 +AgEGBSuBBAAiA2IABJjpLz1AcqTtkyJygRMc3RCV8cWjTnHcFBbZDuWmBSp3ZHtf +TjjTuxxEtX/1H7YyYl3J6YRbTzBPEVoA/VhYDKX1DyxNB0cTddqXl5dvMVztK517 +IDvYuVTZXpmkOlEKMaNCMEAwHQYDVR0OBBYEFLuw3qFYM4iapIqZ3r6966/ayySr +MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2gA +MGUCMQCD6cHEFl4aXTQY2e3v9GwOAEZLuN+yRhHFD/3meoyhpmvOwgPUnPWTxnS4 +at+qIxUCMG1mihDK1A3UT82NQz60imOlM27jbdoXt2QfyFMm+YhidDkLF1vLUagM +6BgD56KyKA== +-----END CERTIFICATE-----""" + ) + + fun applyTo(builder: OkHttpClient.Builder) { + val (sslSocketFactory, trustManager) = createSslSocketFactory() + builder.sslSocketFactory(sslSocketFactory, trustManager) + } + + private fun createSslSocketFactory(): Pair { + val cf = CertificateFactory.getInstance("X.509") + + val defaultTmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply { + init(null as KeyStore?) + } + val systemTrustManager = defaultTmf.trustManagers.filterIsInstance().first() + + val appleKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()).apply { + load(null, null) + APPLE_CERTS_PEM.forEachIndexed { index, pem -> + val cert = cf.generateCertificate(ByteArrayInputStream(pem.trim().toByteArray())) as X509Certificate + setCertificateEntry("apple_root_ca_$index", cert) + } + } + val appleTmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply { + init(appleKeyStore) + } + val appleTrustManager = appleTmf.trustManagers.filterIsInstance().first() + + val compositeTrustManager = object : X509TrustManager { + override fun checkClientTrusted(chain: Array?, authType: String?) { + systemTrustManager.checkClientTrusted(chain, authType) + } + + override fun checkServerTrusted(chain: Array?, authType: String?) { + try { + systemTrustManager.checkServerTrusted(chain, authType) + } catch (systemEx: CertificateException) { + try { + appleTrustManager.checkServerTrusted(chain, authType) + } catch (_: CertificateException) { + throw systemEx + } + } + } + + override fun getAcceptedIssuers(): Array { + return systemTrustManager.acceptedIssuers + appleTrustManager.acceptedIssuers + } + } + + val sslContext = SSLContext.getInstance("TLS").apply { + init(null, arrayOf(compositeTrustManager), null) + } + return sslContext.socketFactory to compositeTrustManager + } +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/http/HttpTransport.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/http/HttpTransport.kt new file mode 100644 index 0000000..a7f6cee --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/http/HttpTransport.kt @@ -0,0 +1,125 @@ +package com.reiyy.yuitag.apple.http + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import java.util.concurrent.TimeUnit + +/** + * Minimal suspend HTTP abstraction used by the GSA / MobileMe / anisette bridge clients. + */ +interface HttpTransport { + suspend fun execute(request: HttpRequest): HttpResponse +} + +/** + * Single HTTP request. [headers] preserves insertion order. + */ +data class HttpRequest( + val method: String, + val url: String, + val headers: Map = emptyMap(), + val body: ByteArray? = null, + val timeoutMs: Long? = null, +) { + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is HttpRequest) return false + if (method != other.method) return false + if (url != other.url) return false + if (headers != other.headers) return false + if (timeoutMs != other.timeoutMs) return false + val a = body + val b = other.body + if (a == null && b == null) return true + if (a == null || b == null) return false + return a.contentEquals(b) + } + + override fun hashCode(): Int { + var h = method.hashCode() + h = 31 * h + url.hashCode() + h = 31 * h + headers.hashCode() + h = 31 * h + (timeoutMs?.hashCode() ?: 0) + h = 31 * h + (body?.contentHashCode() ?: 0) + return h + } +} + +class HttpResponse( + val statusCode: Int, + headers: Map, + val body: ByteArray, +) { + private val headersCaseInsensitive: Map = + headers.mapKeys { it.key.lowercase() } + + val headers: Map = headers + + fun header(name: String): String? = headersCaseInsensitive[name.lowercase()] + + fun isOk(): Boolean = statusCode in 200..299 +} + +/** + * Production [HttpTransport] backed by OkHttp. + */ +class OkHttpTransport( + private val client: OkHttpClient = defaultClient, +) : HttpTransport { + + override suspend fun execute(request: HttpRequest): HttpResponse = withContext(Dispatchers.IO) { + val reqBuilder = Request.Builder().url(request.url) + + for ((k, v) in request.headers) { + reqBuilder.addHeader(k, v) + } + + val requestBody = request.body?.let { bytes -> + val contentType = request.headers.entries + .firstOrNull { it.key.equals("Content-Type", ignoreCase = true) } + ?.value + bytes.toRequestBody(contentType?.toMediaTypeOrNull()) + } + + reqBuilder.method(request.method, requestBody) + + val activeClient = if (request.timeoutMs != null && request.timeoutMs > 0) { + client.newBuilder() + .connectTimeout(request.timeoutMs, TimeUnit.MILLISECONDS) + .readTimeout(request.timeoutMs, TimeUnit.MILLISECONDS) + .writeTimeout(request.timeoutMs, TimeUnit.MILLISECONDS) + .build() + } else { + client + } + + activeClient.newCall(reqBuilder.build()).execute().use { resp -> + val respHeaders = mutableMapOf() + val headers = resp.headers + for (i in 0 until headers.size) { + respHeaders[headers.name(i)] = headers.value(i) + } + HttpResponse( + statusCode = resp.code, + headers = respHeaders, + body = resp.body?.bytes() ?: ByteArray(0), + ) + } + } + + companion object { + val defaultClient: OkHttpClient = OkHttpClient.Builder() + .connectTimeout(30, TimeUnit.SECONDS) + .readTimeout(30, TimeUnit.SECONDS) + .writeTimeout(30, TimeUnit.SECONDS) + .followRedirects(false) + .apply { + AppleTlsConfig.applyTo(this) + } + .build() + } +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/mobileme/MobileMeClient.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/mobileme/MobileMeClient.kt new file mode 100644 index 0000000..55f5a83 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/mobileme/MobileMeClient.kt @@ -0,0 +1,73 @@ +package com.reiyy.yuitag.apple.mobileme + +import com.reiyy.yuitag.apple.anisette.AnisetteClient +import com.reiyy.yuitag.apple.anisette.MacAnisetteProvider +import com.reiyy.yuitag.apple.http.HttpRequest +import com.reiyy.yuitag.apple.http.HttpTransport +import com.reiyy.yuitag.apple.plist.PlistValue +import com.reiyy.yuitag.apple.plist.XmlPlist +import com.reiyy.yuitag.apple.plist.anyToPlist +import kotlin.io.encoding.Base64 +import kotlin.io.encoding.ExperimentalEncodingApi + +/** + * Exchanges GSA `idms_pet` token for iCloud delegates including `searchPartyToken`. + */ +@OptIn(ExperimentalEncodingApi::class) +class MobileMeClient( + private val http: HttpTransport, + private val anisette: AnisetteClient, + private val endpoint: String = ENDPOINT, +) { + + suspend fun login( + username: String, + idmsPet: String, + adsid: String, + ): PlistValue.Dict { + val machine = anisette.machine() + val body = linkedMapOf( + "apple-id" to username, + "delegates" to linkedMapOf("com.apple.mobileme" to emptyMap()), + "password" to idmsPet, + "client-id" to machine.localUserUuid, + ) + val plistBody = XmlPlist.encode(anyToPlist(body)) + + val headers = linkedMapOf().apply { + put("X-Apple-ADSID", adsid) + put("User-Agent", "com.apple.iCloudHelper/282 ${MacAnisetteProvider.CFNETWORK_DARWIN}") + put("X-Mme-Client-Info", machine.clientInfoFor("com.apple.AOSKit/282 (com.apple.accountsd/113)")) + putAll(anisette.getHeaders()) + put("Authorization", basicAuth(username, idmsPet)) + put("Content-Type", "application/octet-stream") + put("Accept", "*/*") + } + + val resp = http.execute( + HttpRequest( + method = "POST", + url = endpoint, + headers = headers, + body = plistBody, + ) + ) + if (!resp.isOk()) { + throw MobileMeRequestException("MobileMe login failed: HTTP ${resp.statusCode}") + } + val parsed = XmlPlist.parse(resp.body) + require(parsed is PlistValue.Dict) { "MobileMe response is not a " } + return parsed + } + + private fun basicAuth(user: String, pass: String): String { + val token = "$user:$pass" + return "Basic " + Base64.encode(token.encodeToByteArray()) + } + + companion object { + const val ENDPOINT: String = "https://setup.icloud.com/setup/iosbuddy/loginDelegates" + } +} + +class MobileMeRequestException(message: String) : RuntimeException(message) diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/plist/PlistValue.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/plist/PlistValue.kt new file mode 100644 index 0000000..0178a37 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/plist/PlistValue.kt @@ -0,0 +1,88 @@ +package com.reiyy.yuitag.apple.plist + +/** + * Typed Apple property-list value tree. + */ +sealed interface PlistValue { + data object Null : PlistValue + + data class Bool(val value: Boolean) : PlistValue + + data class Int64(val value: Long) : PlistValue + + data class Real(val value: Double) : PlistValue + + data class Str(val value: String) : PlistValue + + class Data(val bytes: ByteArray) : PlistValue { + override fun equals(other: Any?): Boolean = + other is Data && bytes.contentEquals(other.bytes) + override fun hashCode(): Int = bytes.contentHashCode() + override fun toString(): String = "Data(${bytes.size} bytes)" + } + + data class Date(val epochMillis: Long) : PlistValue + + data class Uid(val value: Long) : PlistValue + + data class Dict(val entries: Map = emptyMap()) : PlistValue { + operator fun get(key: String): PlistValue? = entries[key] + + fun string(key: String): String? = (entries[key] as? Str)?.value + fun data(key: String): ByteArray? = (entries[key] as? Data)?.bytes + fun int64(key: String): Long? = (entries[key] as? Int64)?.value + fun bool(key: String): Boolean? = (entries[key] as? Bool)?.value + fun dict(key: String): Dict? = entries[key] as? Dict + fun array(key: String): Array? = entries[key] as? Array + + fun opaque(key: String): ByteArray? = when (val v = entries[key]) { + is Str -> v.value.encodeToByteArray() + is Data -> v.bytes + null -> null + else -> throw IllegalArgumentException("Expected bytes/string for \"$key\", got ${v::class.simpleName}") + } + } + + data class Array(val items: List = emptyList()) : PlistValue { + val size: Int get() = items.size + operator fun get(index: Int): PlistValue = items[index] + } +} + +fun plistDictOf(vararg pairs: Pair): PlistValue.Dict = + PlistValue.Dict(linkedMapOf(*pairs)) + +fun plistArrayOf(vararg items: PlistValue): PlistValue.Array = + PlistValue.Array(items.toList()) + +fun String.asPlist(): PlistValue = PlistValue.Str(this) +fun Long.asPlist(): PlistValue = PlistValue.Int64(this) +fun Int.asPlist(): PlistValue = PlistValue.Int64(toLong()) +fun Boolean.asPlist(): PlistValue = PlistValue.Bool(this) +fun ByteArray.asPlist(): PlistValue = PlistValue.Data(this) +fun Double.asPlist(): PlistValue = PlistValue.Real(this) + +fun anyToPlist(value: Any?): PlistValue = when (value) { + null -> PlistValue.Null + is PlistValue -> value + is String -> PlistValue.Str(value) + is Boolean -> PlistValue.Bool(value) + is Byte -> PlistValue.Int64(value.toLong()) + is Short -> PlistValue.Int64(value.toLong()) + is Int -> PlistValue.Int64(value.toLong()) + is Long -> PlistValue.Int64(value) + is Float -> PlistValue.Real(value.toDouble()) + is Double -> PlistValue.Real(value) + is ByteArray -> PlistValue.Data(value) + is Map<*, *> -> { + val out = linkedMapOf() + for ((k, v) in value) { + val key = k as? String + ?: throw IllegalArgumentException("Plist dict keys must be String, got ${k?.let { it::class.simpleName }}") + out[key] = anyToPlist(v) + } + PlistValue.Dict(out) + } + is List<*> -> PlistValue.Array(value.map { anyToPlist(it) }) + else -> throw IllegalArgumentException("Cannot encode ${value::class.simpleName} as a plist value") +} diff --git a/App/app/src/main/java/com/reiyy/yuitag/apple/plist/XmlPlist.kt b/App/app/src/main/java/com/reiyy/yuitag/apple/plist/XmlPlist.kt new file mode 100644 index 0000000..612b4e8 --- /dev/null +++ b/App/app/src/main/java/com/reiyy/yuitag/apple/plist/XmlPlist.kt @@ -0,0 +1,467 @@ +package com.reiyy.yuitag.apple.plist + +import kotlin.io.encoding.Base64 +import kotlin.io.encoding.ExperimentalEncodingApi + +/** + * Hand-rolled XML plist reader + writer. + * + * Not a general XML library — it understands just the plist grammar: accepts Apple's + * bare `` SPD fragments, preserves dictionary insertion order, and surfaces + * type mismatches at parse time. + */ +object XmlPlist { + + /** + * Parse a UTF-8 XML plist document or fragment. Accepts: + * - `` + `` + `...` + * - just `...` + * - a bare `...` or `...` (Apple SPD emits this). + */ + fun parse(xml: String): PlistValue { + val lexer = XmlLexer(xml) + skipPrologue(lexer) + // `` wrapper is optional — Apple SPD omits it. + if (lexer.peekElementName() == "plist") { + lexer.consumeStartTag("plist") + skipWhitespaceAndMisc(lexer) + val value = parseValue(lexer) + skipWhitespaceAndMisc(lexer) + lexer.consumeEndTag("plist") + return value + } + return parseValue(lexer) + } + + fun parse(bytes: ByteArray): PlistValue = parse(bytes.decodeToString()) + + /** + * Encode a [PlistValue] to a UTF-8 XML plist document. + */ + fun encode(value: PlistValue): ByteArray = buildString { + append("""""") + append("""""") + append("""""") + encodeValue(value, this) + append("") + }.encodeToByteArray() + + // ----------------------------------------------------------------- + // Parser + // ----------------------------------------------------------------- + + private fun parseValue(lexer: XmlLexer): PlistValue { + skipWhitespaceAndMisc(lexer) + val tag = lexer.peekElementName() + ?: throw PlistParseException("Expected a plist element, got EOF") + return when (tag) { + "dict" -> parseDict(lexer) + "array" -> parseArray(lexer) + "string" -> PlistValue.Str(parseTextElement(lexer, "string")) + "integer" -> PlistValue.Int64(parseTextElement(lexer, "integer").trim().toLong()) + "real" -> PlistValue.Real(parseTextElement(lexer, "real").trim().toDouble()) + "data" -> PlistValue.Data(decodeBase64(parseTextElement(lexer, "data"))) + "date" -> PlistValue.Date(parseIso8601(parseTextElement(lexer, "date").trim())) + "true" -> { lexer.consumeEmptyElement("true"); PlistValue.Bool(true) } + "false" -> { lexer.consumeEmptyElement("false"); PlistValue.Bool(false) } + "null" -> { lexer.consumeEmptyElement("null"); PlistValue.Null } + else -> throw PlistParseException("Unknown plist element <$tag>") + } + } + + private fun parseDict(lexer: XmlLexer): PlistValue.Dict { + lexer.consumeStartTag("dict") + val out = linkedMapOf() + while (true) { + skipWhitespaceAndMisc(lexer) + if (lexer.peekEndTag() == "dict") { + lexer.consumeEndTag("dict") + return PlistValue.Dict(out) + } + if (lexer.peekElementName() != "key") { + throw PlistParseException( + "Expected inside , got <${lexer.peekElementName()}>") + } + val key = parseTextElement(lexer, "key") + skipWhitespaceAndMisc(lexer) + out[key] = parseValue(lexer) + } + } + + private fun parseArray(lexer: XmlLexer): PlistValue.Array { + lexer.consumeStartTag("array") + val items = mutableListOf() + while (true) { + skipWhitespaceAndMisc(lexer) + if (lexer.peekEndTag() == "array") { + lexer.consumeEndTag("array") + return PlistValue.Array(items) + } + items.add(parseValue(lexer)) + } + } + + private fun parseTextElement(lexer: XmlLexer, tag: String): String { + val attrs = lexer.consumeStartTagFull(tag) + if (attrs.selfClosed) return "" + val text = lexer.readTextUntilEnd(tag) + return decodeXmlEntities(text) + } + + // ----------------------------------------------------------------- + // Writer + // ----------------------------------------------------------------- + + private fun encodeValue(value: PlistValue, out: StringBuilder) { + when (value) { + is PlistValue.Dict -> { + if (value.entries.isEmpty()) { out.append(""); return } + out.append("") + for ((k, v) in value.entries) { + out.append("").append(escapeXml(k)).append("") + encodeValue(v, out) + } + out.append("") + } + is PlistValue.Array -> { + if (value.items.isEmpty()) { out.append(""); return } + out.append("") + for (item in value.items) encodeValue(item, out) + out.append("") + } + is PlistValue.Str -> + out.append("").append(escapeXml(value.value)).append("") + is PlistValue.Int64 -> out.append("").append(value.value).append("") + is PlistValue.Real -> out.append("").append(value.value).append("") + is PlistValue.Bool -> out.append(if (value.value) "" else "") + is PlistValue.Data -> out.append("").append(encodeBase64(value.bytes)).append("") + is PlistValue.Date -> out.append("").append(formatIso8601(value.epochMillis)).append("") + is PlistValue.Uid -> { + out.append("CF\$UID") + .append(value.value) + .append("") + } + is PlistValue.Null -> out.append("") + } + } + + // ----------------------------------------------------------------- + // Prologue / misc-skipping + // ----------------------------------------------------------------- + + private fun skipPrologue(lexer: XmlLexer) { + while (true) { + skipWhitespaceAndMisc(lexer) + val peek = lexer.peekRaw(5) + when { + peek.startsWith(" lexer.skipProcessingInstruction() + peek.startsWith(" lexer.skipProcessingInstruction() + peek.startsWith(" lexer.skipDoctype() + peek.startsWith("", pos + 4) + if (end < 0) throw PlistParseException("Unterminated comment") + pos = end + 3 + } + + fun peekElementName(): String? { + skipWhitespace() + if (pos >= src.length || src[pos] != '<') return null + if (pos + 1 < src.length && src[pos + 1] == '/') return null + if (pos + 1 < src.length && (src[pos + 1] == '?' || src[pos + 1] == '!')) return null + var i = pos + 1 + val start = i + while (i < src.length) { + val c = src[i] + if (c.isWhitespace() || c == '>' || c == '/') break + i++ + } + return src.substring(start, i) + } + + fun peekEndTag(): String? { + skipWhitespace() + if (pos + 1 >= src.length || src[pos] != '<' || src[pos + 1] != '/') return null + var i = pos + 2 + val start = i + while (i < src.length) { + val c = src[i] + if (c.isWhitespace() || c == '>') break + i++ + } + return src.substring(start, i) + } + + fun consumeStartTag(expected: String) { + val attrs = consumeStartTagFull(expected) + if (attrs.selfClosed) { + throw PlistParseException("Expected open <$expected>, got self-closed") + } + } + + fun consumeEmptyElement(expected: String) { + val attrs = consumeStartTagFull(expected) + if (!attrs.selfClosed) consumeEndTag(expected) + } + + fun consumeEndTag(expected: String) { + skipWhitespace() + if (!src.startsWith(" at pos=$pos, got '${peekRaw(10)}'") + } + val end = src.indexOf('>', pos + 2) + if (end < 0) throw PlistParseException("Unterminated end tag") + val name = src.substring(pos + 2, end).trim() + if (name != expected) { + throw PlistParseException("Expected , got ") + } + pos = end + 1 + } + + data class StartTag(val name: String, val selfClosed: Boolean) + + fun consumeStartTagFull(expected: String): StartTag { + skipWhitespace() + if (pos >= src.length || src[pos] != '<') { + throw PlistParseException( + "Expected <$expected>, got '${peekRaw(10)}' at pos=$pos") + } + val end = src.indexOf('>', pos + 1) + if (end < 0) throw PlistParseException("Unterminated tag") + val body = src.substring(pos + 1, end).trim() + val selfClosed = body.endsWith("/") + val nameEnd = body.indexOfFirst { it.isWhitespace() || it == '/' } + val name = if (nameEnd < 0) body else body.substring(0, nameEnd) + if (name != expected) { + throw PlistParseException("Expected <$expected>, got <$name>") + } + pos = end + 1 + return StartTag(name, selfClosed) + } + + fun readTextUntilEnd(tag: String): String { + val buf = StringBuilder() + while (pos < src.length) { + if (src.startsWith("", pos + 9) + if (cdataEnd < 0) throw PlistParseException("Unterminated CDATA") + buf.append(src, pos + 9, cdataEnd) + pos = cdataEnd + 3 + continue + } + if (src.startsWith("