From 04ecb49a0c0a39dcec52ac768a9b333f6c9513be Mon Sep 17 00:00:00 2001 From: "Shane B." Date: Fri, 20 Nov 2026 17:35:50 +0100 Subject: [PATCH 1/2] Move the FindMy.py pin to the hsc 409 fix, for the exporter as well as the app parawanderer/FindMy.py#9 (merged as 37d5ca0b) reads Grand Slam's hsc 409 with no au as a second factor, so an account Apple wants a code for is asked for one instead of failing at the mobileme step (#248). The exporter runs the same library, so it gets the same fix. Moved in all four places (AGENTS.md rule 14); uv.lock by `uv lock`. Co-Authored-By: Rob Lazzurs Co-Authored-By: Claude Opus 5.5 --- app/build.gradle.kts | 2 +- app/src/test/python/requirements.txt | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 6 +++--- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 513ed154..59d200ac 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -447,7 +447,7 @@ chaquopy { // wheel for desktop platforms and a pure-Python `py3-none-any` one as well. // There is no Android wheel, so pip falls back to the pure-Python build - which // is correct but markedly slower. The messages here are small enough not to care. - install("git+https://github.com/parawanderer/FindMy.py@00fd962a0e8ec9f5601fe0b9db3f16ccea252a3c") + install("git+https://github.com/parawanderer/FindMy.py@37d5ca0b4ab0143e53ca158d61cf6d5e18bd6ba8") install("NSKeyedUnArchiver==1.5") diff --git a/app/src/test/python/requirements.txt b/app/src/test/python/requirements.txt index 2c54b08b..7f303b8e 100644 --- a/app/src/test/python/requirements.txt +++ b/app/src/test/python/requirements.txt @@ -9,7 +9,7 @@ # `FindMy==0.9.8` here for as long as the app built the fork, so every bridge test # ran against a library the app does not ship - which is not a small difference: # the fork's Anisette providers take `serial=` and PyPI's do not. -git+https://github.com/parawanderer/FindMy.py@00fd962a0e8ec9f5601fe0b9db3f16ccea252a3c +git+https://github.com/parawanderer/FindMy.py@37d5ca0b4ab0143e53ca158d61cf6d5e18bd6ba8 NSKeyedUnArchiver==1.5 PyYAML==6.0.2 diff --git a/python/pyproject.toml b/python/pyproject.toml index 2f0bc4a4..c6cf0dcf 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -69,7 +69,7 @@ constraint-dependencies = [ ] [tool.uv.sources] -FindMy = { git = "https://github.com/parawanderer/FindMy.py", rev = "00fd962a0e8ec9f5601fe0b9db3f16ccea252a3c" } +FindMy = { git = "https://github.com/parawanderer/FindMy.py", rev = "37d5ca0b4ab0143e53ca158d61cf6d5e18bd6ba8" } [dependency-groups] # Only the release build installs this, with `uv sync --no-default-groups --group build`. It is diff --git a/python/uv.lock b/python/uv.lock index b6194833..ef9e160c 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.10" resolution-markers = [ "platform_machine == 'x86_64' and sys_platform == 'darwin'", @@ -659,7 +659,7 @@ wheels = [ [[package]] name = "findmy" version = "0.10.1" -source = { git = "https://github.com/parawanderer/FindMy.py?rev=00fd962a0e8ec9f5601fe0b9db3f16ccea252a3c#00fd962a0e8ec9f5601fe0b9db3f16ccea252a3c" } +source = { git = "https://github.com/parawanderer/FindMy.py?rev=37d5ca0b4ab0143e53ca158d61cf6d5e18bd6ba8#37d5ca0b4ab0143e53ca158d61cf6d5e18bd6ba8" } dependencies = [ { name = "aiohttp" }, { name = "anisette" }, @@ -1032,7 +1032,7 @@ dev = [ [package.metadata] requires-dist = [ - { name = "findmy", git = "https://github.com/parawanderer/FindMy.py?rev=00fd962a0e8ec9f5601fe0b9db3f16ccea252a3c" }, + { name = "findmy", git = "https://github.com/parawanderer/FindMy.py?rev=37d5ca0b4ab0143e53ca158d61cf6d5e18bd6ba8" }, { name = "pycryptodome", specifier = "==3.22.0" }, { name = "pyyaml", specifier = "==6.0.2" }, { name = "pyzipper", specifier = "==0.4.0" }, From 05b5d7cb26c9a48925f5fa580f063da4c1bed3b0 Mon Sep 17 00:00:00 2001 From: "Shane B." Date: Fri, 20 Nov 2026 17:35:50 +0100 Subject: [PATCH 2/2] Sign the exporter in as an emulated Mac, running Apple's own macOS CoreADI Since 2026-10-12 Apple serves the Android ADI machine that `anisette` provisions differently from a Mac (#248), and the exporter's iCloud route signs in as exactly that machine (#288). This makes the default an emulated Mac instead: Apple's x86_64 CoreADI under Unicorn, through sacca97's machoadi engine from os-findmy-e. - The engine is GPL-2.0 and runs as `python -m machoadi.mac_anisette` in its own process, never imported. It comes from parawanderer/os-findmy-e, which spells the OS "Mac OS X" (#289), verifies TLS against FindMy.py's pinned Apple root rather than CERT_NONE, takes a serial, and installs with pip. - Apple's library is fetched from Apple: 3.5 MB of the iTunes 12.8.3 installer in one range request, checked against two pinned hashes. A port of the app's MacCoreAdiFetcher; nothing for the user to supply, on any OS. - The machine is provisioned once, under this install's 0PENTAGX serial, and kept beside device-identity.json. The account signs in with the ids it was provisioned with. An install that was the Android machine gains one device-list entry, once, and is told so. - CloudKit is given the machine's host UUID, since it parses the device id as a UUID and a Mac's is not one (as #274's _forCloudKit). - --anisette-url is unchanged; --anisette-libs now explicitly selects the Android ADI. A PyInstaller build refuses with a message for now: it has no interpreter to run the engine with. Not yet verified: a real sign-in through it. Co-Authored-By: sacca97 Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 12 ++ python/exporter/cli.py | 9 +- python/exporter/icloud.py | 93 +++++++++ python/exporter/macadi.py | 340 +++++++++++++++++++++++++++++++ python/pyproject.toml | 6 + python/test/test_emulated_mac.py | 259 +++++++++++++++++++++++ python/uv.lock | 11 + 7 files changed, 728 insertions(+), 2 deletions(-) create mode 100644 python/exporter/macadi.py create mode 100644 python/test/test_emulated_mac.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b4f7dcbf..f5203028 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -582,6 +582,18 @@ uv run pytest ./test -rs `361 passed, 4 skipped` means Tk was missing and neither file ran. `378 passed, 2 skipped` means they did, and the two remaining skips are the macOS-14-only decryptor tests. +#### The emulated Mac's engine, for real + +`test_emulated_mac.py` runs Apple's macOS CoreADI under Unicorn only when `OTV_COREADI` names a +copy of the library, and otherwise skips that one class. It sends Apple nothing: `info` is +`Initialize` and `IsMachineProvisioned`. Fetching the library is one 3.5 MB range request to +Apple, and is the only network use: + +```bash +uv run python -c "from pathlib import Path; from exporter import macadi; macadi.ensure_library(Path('/tmp/CoreADI.x86_64'))" +OTV_COREADI=/tmp/CoreADI.x86_64 uv run pytest test/test_emulated_mac.py -rs +``` + ### Tooling tests ```bash diff --git a/python/exporter/cli.py b/python/exporter/cli.py index 49ab15fb..5c9034c5 100644 --- a/python/exporter/cli.py +++ b/python/exporter/cli.py @@ -207,13 +207,18 @@ def build_parser() -> argparse.ArgumentParser: "--anisette-url", help=( "Use a remote Anisette server instead of running it locally. Local is the default and" - " keeps the sign-in between this machine and Apple." + " keeps the sign-in between this machine and Apple: an emulated Mac, running Apple's" + " own macOS CoreADI, which is fetched from Apple on first use." ), ) parser.add_argument( "--anisette-libs", type=Path, - help="Where to cache Apple's ADI libraries, so a later run does not download them again.", + help=( + "Sign in as the Android ADI machine instead of the emulated Mac, caching its libraries" + " here. Apple has served that machine differently since October 2026 (#248), so this" + " is for comparison, not for use." + ), ) parser.add_argument( "-v", diff --git a/python/exporter/icloud.py b/python/exporter/icloud.py index 949a7956..967dcffb 100644 --- a/python/exporter/icloud.py +++ b/python/exporter/icloud.py @@ -296,6 +296,12 @@ def make_account( identity = ClientIdentity( serial=serial_from(stored), device_name=identity.device_name) + # **The emulated Mac unless something else was asked for.** Apple stopped serving the Android + # ADI machine `anisette` provisions (#248), so it is reached only by naming its library cache. + # See `exporter.macadi`. + if provider is None and anisette_url is None and libs_path is None: + return _emulated_mac_account(stored, identity, identity_path) + # After the substitution above, never before: the provider is what actually sends # `X-Apple-I-SRL-NO`, so building it from the placeholder identity would present the constant # this change exists to stop presenting. @@ -327,6 +333,48 @@ def make_account( ) +def _emulated_mac_account( + stored: dict[str, Any] | None, + identity: ClientIdentity, + identity_path: Path | None, +) -> AsyncAppleAccount: + """ + An account on the emulated Mac kept beside the device identity, provisioning it if needed. + + **The ids are the machine's.** Provisioning registered one device id and one local user id + with Apple, and `X-Apple-I-MD-M` is derived from that registration; an account sending other + ids alongside it is a shape no real Mac produces. So they come from the machine, not from + `device-identity.json` - which only confirms the stored session is this machine's. + """ + from exporter import macadi # noqa: PLC0415 - the app imports this module and never needs it + + root = (identity_path or device.identity_path()).parent / macadi.DIRNAME + provider = macadi.EmulatedMacAnisetteProvider(macadi.EmulatedMac.open(root, identity.serial)) + + if stored is not None and (stored["uid"], stored["devid"]) == (provider.uid, provider.devid): + logger.info("Reusing the stored emulated Mac, so this is not a new device to Apple") + state: Any = { + "type": "account", + "ids": {"uid": stored["uid"], "devid": stored["devid"]}, + "account": {"username": None, "password": None, "info": None}, + "login": {"state": LoginState.LOGGED_OUT.value, "data": None}, + "anisette": provider.to_json(), + } + return AsyncAppleAccount( + provider, state_info=state, device_name=identity.device_name, + timeout=LOGIN_TIMEOUT_SECONDS) + + if stored is not None: + # Unavoidable once: the stored ids are the Android ADI machine Apple stopped serving. + logger.warning( + "This install signed in before as a different machine; signing in as the emulated Mac" + " adds one entry to the account's device list. The serial stays %s.", provider.serial) + + return AsyncAppleAccount( + provider, uid=provider.uid, devid=provider.devid, device_name=identity.device_name, + timeout=LOGIN_TIMEOUT_SECONDS) + + def _make_provider( anisette_url: str | None, libs_path: str | None, @@ -751,6 +799,50 @@ def _describe_factor(method: object) -> str: return type(method).__name__ +class _CloudKitDeviceView: + """ + The account, except that `device_uuid` is a UUID - for the keychain and CloudKit clients only. + + FindMy.py's CloudKit client sends `uuid.UUID(account.device_uuid)`, and a Mac's device id is a + provisioning UDID - `00006000-` and sixteen hex - so opening the client failed with "badly + formed hexadecimal UUID string" before anything was sent. CloudKit's identifier is a separate + field from `X-Mme-Device-Id`, so it is answered with another stable value, and everything else - + Grand Slam, tokens, PET renewal - reaches the real account. After #274's `_forCloudKit`, and + sacca97/os-findmy-e's `tag_keys.CloudKitIdentity` before it. + """ + + def __init__(self, account: AsyncAppleAccount, device_uuid: str) -> None: + self._account = account + self._device_uuid = device_uuid + + @property + def device_uuid(self) -> str: + return self._device_uuid + + def __getattr__(self, name: str) -> Any: + return getattr(self._account, name) + + +def _with_a_uuid_for_cloudkit(account: Any) -> Any: + """`account`, or a view of it whose device id CloudKit can parse.""" + device_id = getattr(account, "device_uuid", None) + if not isinstance(device_id, str): + return account + try: + uuid.UUID(device_id) + return account + except ValueError: + pass + + # The emulated Mac's host UUID when the provider can say; otherwise one derived from the + # device id, which is as stable as the device id is. + stable = getattr(getattr(account, "_anisette", None), "cloudkit_device_uuid", None) + if not isinstance(stable, str): + stable = str(uuid.uuid5(uuid.NAMESPACE_URL, f"opentagviewer:device:{device_id}")).upper() + logger.info("The device id is not a UUID; CloudKit is told %s instead", stable) + return _CloudKitDeviceView(account, stable) + + async def open_client( account: AsyncAppleAccount, identity: ClientIdentity = EXPORTER_IDENTITY, ) -> AsyncFindMyClient: @@ -761,6 +853,7 @@ async def open_client( client with the library's own device name. Rule 11: every path has to send the same identity, and a second name here would be a second device in the user's list. """ + account = _with_a_uuid_for_cloudkit(account) session = await AsyncKeychainSession.open(account) try: store = AsyncBeaconStore( diff --git a/python/exporter/macadi.py b/python/exporter/macadi.py new file mode 100644 index 00000000..bb48e3a5 --- /dev/null +++ b/python/exporter/macadi.py @@ -0,0 +1,340 @@ +""" +The machine this exporter signs in as: an emulated Mac, running Apple's own macOS CoreADI. + +**Why not the Android ADI that `anisette` runs.** Since 2026-10-12 Apple has treated a session +provisioned by its Android ADI libraries differently from a Mac's: the sign-in is asked for a +second factor in a new way (#248, handled in FindMy.py since parawanderer/FindMy.py#9) and the +tokens that follow it are not the ones a Mac gets (malmeloo/FindMy.py#278). A Mac-lineage machine +is what Apple still serves. The Android app reaches the same conclusion in #274. + +**What runs it.** `machoadi`, from sacca97/os-findmy-e by way of parawanderer/os-findmy-e: Apple's +x86_64 `CoreADI.framework` mapped and executed under Unicorn, with a synthetic macOS userland. It +is pure Python on the `unicorn` wheel, which the exporter already ships through `anisette`, so it +runs on Windows and Linux - where nearly everybody runs this - as well as on a Mac. + +**It runs in its own process, always.** `machoadi` is GPL-2.0 and this exporter is MIT, so it is +invoked as a program rather than imported - the arrangement `docs/emulated-mac-emulator-choice.md` +describes for the app. That also suits it technically: one Unicorn process faults after about +eight OTP requests, so `machoadi`'s own provider already asks a fresh process once per 30-second +OTP window and reuses the answer within it. + +**Apple's library is fetched from Apple, never shipped.** It sits inside the iTunes 12.8.3 for Mac +installer Apple still serves, at a fixed position; one range request of 3.5 MB gets it, and two +pinned hashes check it. This is `MacCoreAdiFetcher` in the app, ported. + +**The identity is the app's emulated Mac's**, `MacIdentity` in #274: a MacBookPro13,2 on macOS 13.1, +which is what os-findmy-e was observed to be issued tokens as. The OS is spelt `Mac OS X`, because +Apple's edge refuses `macOS` at sign-in since 2026-11-20 (#289). The serial is this install's own +`0PENTAGX` one (rule 11), handed to the engine when the machine is first provisioned. +""" + +from __future__ import annotations + +import gzip +import hashlib +import json +import logging +import os +import struct +import subprocess +import sys +import time +import urllib.request +import uuid +from pathlib import Path +from typing import Any + +from findmy.reports.anisette import BaseAnisetteProvider, DeviceIdentity +from findmy.util.tls import apple_trust_context +from typing_extensions import override + +logger = logging.getLogger(__name__) + +DIRNAME = "emulated-mac" +"""Beside `device-identity.json`: the CoreADI library, and the machine's state directory.""" + +IDENTITY = DeviceIdentity( + model="MacBookPro13,2", + os_name="Mac OS X", + os_version="13.1", + os_build="22C65", + cfnetwork="1404.0.5", + darwin="22.2.0", +) +""" +What this machine claims to be, field for field the app's `MacIdentity`. + +**The provisioning half is not composed here.** `machoadi` provisions under its own +`DEFAULT_CLIENT_INFO`, which the parawanderer fork spells identically; `test_macadi` pins that the +two agree, because a login describing a different platform than provisioning did is a second +machine (rule 11). +""" + +WINDOW_SECONDS = 30 +"""The OTP changes only at multiples of 30 seconds of Unix time, so one engine run serves a window.""" + +ENGINE_TIMEOUT_SECONDS = 180 +"""Provisioning is two round trips to Apple plus emulation; headers alone take a few seconds.""" + +DMG_URL = ( + "https://secure-appldnld.apple.com/itunes12/" + "041-56365-20210413-79A5AC6D-6B0A-46EC-B399-5A381183E3BE/iTunes12.8.3.dmg" +) +PAYLOAD_OFFSET = 184_678_769 +PAYLOAD_LENGTH = 3_471_595 +PAYLOAD_SHA256 = "8a6c068c95036326eb2d2885fa60912ed0f7229d0939ae92934a70a3bb6cf025" +LIBRARY_SHA256 = "2eafc3c79c7f41a8afbfbeaaf23ee5dab5ad5bda55ec8e54dbc0ddf1d20ce630" +"""The x86_64 slice of CoreADI 4.19 - the build `machoadi` knows the dispatcher offset of.""" + +FRAMEWORK_PATH = "System/Library/PrivateFrameworks/CoreADI.framework/Versions/A/CoreADI" +_CPU_TYPE_X86_64 = 0x01000007 + + +class EmulatedMacError(RuntimeError): + """The emulated Mac could not be fetched, provisioned or asked for headers.""" + + +# -- Apple's library --------------------------------------------------------------------------- + + +def ensure_library(target: Path, url: str = DMG_URL) -> Path: + """Make sure `target` holds Apple's x86_64 CoreADI, fetching it if not.""" + if target.is_file() and _sha256(target.read_bytes()) == LIBRARY_SHA256: + return target + + logger.info("Fetching Apple's macOS CoreADI from Apple (3.5 MB of the iTunes 12.8.3 installer)") + library = extract(_fetch_payload(url)) + + target.parent.mkdir(parents=True, exist_ok=True) + # Written beside and renamed over, so an interrupted write never leaves a truncated library. + partial = target.with_name(target.name + ".partial") + partial.write_bytes(library) + partial.replace(target) + return target + + +def _fetch_payload(url: str) -> bytes: + request = urllib.request.Request( + url, headers={"Range": f"bytes={PAYLOAD_OFFSET}-{PAYLOAD_OFFSET + PAYLOAD_LENGTH - 1}"}) + try: + with urllib.request.urlopen(request, timeout=60, context=apple_trust_context()) as response: + # Anything but a partial answer means the range was ignored, and reading on would + # download the whole 291 MB image to throw nearly all of it away. + if response.status != 206: + msg = f"Apple answered HTTP {response.status} to the range request; expected 206" + raise EmulatedMacError(msg) + payload = response.read(PAYLOAD_LENGTH + 1) + except OSError as e: + msg = f"Could not download Apple's CoreADI: {e}" + raise EmulatedMacError(msg) from e + + if len(payload) != PAYLOAD_LENGTH: + msg = f"Expected {PAYLOAD_LENGTH} bytes of the installer, got {len(payload)}" + raise EmulatedMacError(msg) + return payload + + +def extract(payload: bytes) -> bytes: + """The x86_64 library out of the installer's payload. Bytes in, bytes out, no network.""" + if _sha256(payload) != PAYLOAD_SHA256: + msg = f"The installer bytes are not the expected ones (sha256 {_sha256(payload)})" + raise EmulatedMacError(msg) + + library = _slice(_file_from_cpio(gzip.decompress(payload), FRAMEWORK_PATH), _CPU_TYPE_X86_64) + if _sha256(library) != LIBRARY_SHA256: + msg = f"The library is not the expected build (sha256 {_sha256(library)})" + raise EmulatedMacError(msg) + return library + + +def _file_from_cpio(cpio: bytes, wanted: str) -> bytes: + """ + One file from an "odc" cpio archive, which Apple's package payloads are. + + Each entry is the magic `070707`, six-digit octal fields up to the name size at offset 59 and + an eleven-digit file size at 65 - 76 bytes - then the name with its NUL, then the data. + """ + pos = 0 + while pos + 76 <= len(cpio): + if cpio[pos:pos + 6] != b"070707": + msg = f"Not an odc cpio archive at offset {pos}" + raise EmulatedMacError(msg) + name_size = int(cpio[pos + 59:pos + 65], 8) + file_size = int(cpio[pos + 65:pos + 76], 8) + data = pos + 76 + name_size + name = cpio[pos + 76:data - 1].decode("utf-8").removeprefix("./") + if name == "TRAILER!!!": + break + # A hard link's twins carry no data; the entry that matters is the one that does. + if name == wanted and file_size: + return cpio[data:data + file_size] + pos = data + file_size + msg = f"{wanted} is not in the installer payload" + raise EmulatedMacError(msg) + + +def _slice(fat: bytes, cpu_type: int) -> bytes: + """The slice for `cpu_type` out of a Mach-O universal binary.""" + if fat[:4] != b"\xca\xfe\xba\xbe": + msg = "The library is not a universal binary" + raise EmulatedMacError(msg) + (count,) = struct.unpack(">I", fat[4:8]) + for i in range(count): + cpu, _, offset, size, _ = struct.unpack(">5I", fat[8 + 20 * i:28 + 20 * i]) + if cpu == cpu_type: + return fat[offset:offset + size] + msg = "The library has no x86_64 slice" + raise EmulatedMacError(msg) + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +# -- the engine, in its own process ------------------------------------------------------------ + + +def _engine(command: str, state: Path, library: Path, *extra: str) -> str: + """Run one `machoadi` command and return what it printed.""" + if getattr(sys, "frozen", False): + # A PyInstaller build has no interpreter to hand `-m` to. Not silently degraded to the + # Android ADI: that is the machine Apple stopped serving, and it would fail later and + # less legibly. + msg = ( + "The emulated Mac is not available in the packaged build yet. Run the exporter from" + " source (`uv run python -m exporter.cli`), or pass --anisette-url." + ) + raise EmulatedMacError(msg) + + try: + done = subprocess.run( + [sys.executable, "-m", "machoadi.mac_anisette", command, "--state", str(state), *extra], + capture_output=True, + text=True, + timeout=ENGINE_TIMEOUT_SECONDS, + env={**os.environ, "COREADI_PATH": str(library)}, + check=False, + ) + except subprocess.TimeoutExpired as e: + msg = f"The emulated Mac did not answer `{command}` within {ENGINE_TIMEOUT_SECONDS}s" + raise EmulatedMacError(msg) from e + + if done.returncode != 0: + detail = (done.stderr or done.stdout).strip().splitlines() + msg = f"The emulated Mac failed `{command}`: {detail[-1] if detail else done.returncode}" + raise EmulatedMacError(msg) + return done.stdout + + +class EmulatedMac: + """One provisioned machine: its state directory, and Apple's library to run it with.""" + + def __init__(self, root: Path) -> None: + self.state = root / "machine" + self.library = root / "CoreADI.x86_64" + + @classmethod + def open(cls, root: Path, serial: str) -> EmulatedMac: + """ + The machine kept under `root`, provisioning one first if there is none. + + :param serial: What a machine provisioned now presents. A stored machine keeps its own: + changing it would be a second entry in the account's device list. + """ + mac = cls(root) + ensure_library(mac.library) + + if not mac.info()["provisioned"]: + logger.info("Provisioning the emulated Mac with Apple (no account is involved)") + _engine("provision", mac.state, mac.library, "--serial", serial) + return mac + + def info(self) -> dict[str, Any]: + return json.loads(_engine("info", self.state, self.library)) + + @property + def identity(self) -> dict[str, Any]: + """`machoadi`'s `identity.json`: device id, local user id, client info, host UUID, serial.""" + return json.loads((self.state / "identity.json").read_text(encoding="utf-8")) + + def headers(self) -> dict[str, str]: + return json.loads(_engine("headers", self.state, self.library)) + + +class EmulatedMacAnisetteProvider(BaseAnisetteProvider): + """Anisette from the emulated Mac, asked once per OTP window.""" + + def __init__(self, mac: EmulatedMac) -> None: + self._mac = mac + self._machine = mac.identity + super().__init__(serial=self._machine["serial"], identity=IDENTITY) + + self._window: int | None = None + self._headers: dict[str, str] | None = None + + @property + def uid(self) -> str: + """The local user id the machine was provisioned with. FindMy.py sends `base64(uid)`.""" + return self._machine["local_user_uuid"] + + @property + def devid(self) -> str: + """The machine's provisioning UDID, `00006000-` and sixteen hex. Not a UUID.""" + return self._machine["device_id"] + + @property + def cloudkit_device_uuid(self) -> str: + """ + A UUID for CloudKit, which parses the device id as one and cannot parse a Mac's. + + The host UUID, as os-findmy-e's `tag_keys.CloudKitIdentity` used: stable for exactly as + long as the machine is. CloudKit's identifier is a different field from `X-Mme-Device-Id`. + """ + return str(uuid.UUID(self._machine["host_uuid"])).upper() + + def _fetch(self) -> dict[str, str]: + window = int(time.time()) // WINDOW_SECONDS + if self._headers is None or window != self._window: + self._headers = self._mac.headers() + self._window = window + return self._headers + + @property + @override + def otp(self) -> str: + return self._fetch()["X-Apple-I-MD"] + + @property + @override + def machine(self) -> str: + return self._fetch()["X-Apple-I-MD-M"] + + @property + @override + def router(self) -> str: + # The routing Apple handed back at provisioning, which is what the machine is registered + # under - not one of the library's constants. + return str(self._fetch()["X-Apple-I-MD-RINFO"]) + + @property + @override + def timestamp(self) -> str: + # From the same run as the OTP, so it cannot describe a different window. + return self._fetch()["X-Apple-I-Client-Time"] + + @override + def to_json(self, dst: str | Path | None = None, /) -> Any: + # The state directory is the machine; a second copy of it here would drift. This only says + # which kind of machine the stored ids belong to. + return {"type": "aniEmulatedMac"} + + @classmethod + @override + def from_json(cls, val: Any) -> EmulatedMacAnisetteProvider: + msg = "An emulated Mac is restored from its state directory, not from JSON" + raise NotImplementedError(msg) + + @override + async def close(self) -> None: + self._headers = None + self._window = None diff --git a/python/pyproject.toml b/python/pyproject.toml index c6cf0dcf..2d694ea3 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -43,6 +43,11 @@ dependencies = [ # on Windows - which rules out curses. See main/prompts.py for what happens without a # terminal, which is not "it falls back": prompt_toolkit waits for keystrokes that never come. "questionary>=2.1.1", + # The machine the iCloud route signs in as: Apple's macOS CoreADI under Unicorn + # (exporter/macadi.py). sacca97/os-findmy-e's engine, from parawanderer's fork, which spells + # the OS "Mac OS X", verifies TLS and installs with pip. **GPL-2.0, and never imported**: the + # exporter runs it as `python -m machoadi.mac_anisette` in its own process. + "machoadi", ] [tool.uv] @@ -70,6 +75,7 @@ constraint-dependencies = [ [tool.uv.sources] FindMy = { git = "https://github.com/parawanderer/FindMy.py", rev = "37d5ca0b4ab0143e53ca158d61cf6d5e18bd6ba8" } +machoadi = { git = "https://github.com/parawanderer/os-findmy-e", rev = "595d39810639d750715babc30b063d4ac8f2c437", subdirectory = "tools/machoadi" } [dependency-groups] # Only the release build installs this, with `uv sync --no-default-groups --group build`. It is diff --git a/python/test/test_emulated_mac.py b/python/test/test_emulated_mac.py new file mode 100644 index 00000000..95ce2651 --- /dev/null +++ b/python/test/test_emulated_mac.py @@ -0,0 +1,259 @@ +""" +The exporter signing in as an emulated Mac (exporter/macadi.py). + +Offline throughout by default. The engine itself runs only with `OTV_COREADI` set to a fetched +library - `python -c "from exporter import macadi; macadi.ensure_library(Path('CoreADI.x86_64'))"` - +and even then sends Apple nothing: `info` is `Initialize` and `IsMachineProvisioned`. +""" + +from __future__ import annotations + +import gzip +import hashlib +import importlib.util +import json +import os +import re +import struct +import uuid +from pathlib import Path + +import pytest +from findmy.reports.anisette import _AKD_BUNDLE # noqa: PLC2701 - the bundle sign-in names + +from exporter import device, icloud, macadi + +MAC_DEVICE_ID = "00006000-0123456789ABCDEF" +HOST_UUID = "786d2185e483fde6eb73112524314456" + + +class FakeMac: + """An `EmulatedMac` that counts how often the engine would have been run.""" + + def __init__(self, serial: str = "0PENTAGXTEST") -> None: + self.identity = { + "device_id": MAC_DEVICE_ID, + "local_user_uuid": "12E2E61F124C792F2361EB2082DD4CB5", + "client_info": macadi.IDENTITY.client_info(_AKD_BUNDLE), + "host_uuid": HOST_UUID, + "routing": 17106176, + "serial": serial, + } + self.asked = 0 + + def headers(self) -> dict[str, str]: + self.asked += 1 + return { + "X-Apple-I-MD": f"otp-{self.asked}", + "X-Apple-I-MD-M": "mid", + "X-Apple-I-MD-RINFO": "17106176", + "X-Apple-I-Client-Time": "2026-11-20T12:00:00Z", + } + + +@pytest.fixture +def mac(monkeypatch: pytest.MonkeyPatch) -> FakeMac: + fake = FakeMac() + opened: list[tuple[Path, str]] = [] + + def open_(root: Path, serial: str) -> FakeMac: + opened.append((root, serial)) + return fake + + monkeypatch.setattr(macadi.EmulatedMac, "open", staticmethod(open_)) + fake.opened = opened # type: ignore[attr-defined] + return fake + + +class TestTheIdentityItPresents: + def test_the_os_is_spelt_the_way_apple_still_lets_through(self): + """#289: `` is refused at sign-in since 2026-11-20, `` is not.""" + assert macadi.IDENTITY.os_name == "Mac OS X" + assert " " + + +class TestTheProvider: + def test_one_engine_run_serves_a_whole_otp_window(self, mac: FakeMac): + provider = macadi.EmulatedMacAnisetteProvider(mac) # type: ignore[arg-type] + + assert (provider.otp, provider.machine, provider.router, provider.timestamp) == ( + "otp-1", "mid", "17106176", "2026-11-20T12:00:00Z") + assert mac.asked == 1 + + def test_the_next_window_asks_again(self, mac: FakeMac, monkeypatch: pytest.MonkeyPatch): + provider = macadi.EmulatedMacAnisetteProvider(mac) # type: ignore[arg-type] + now = [1_700_000_000.0] + monkeypatch.setattr(macadi.time, "time", lambda: now[0]) + + first = provider.otp + now[0] += macadi.WINDOW_SECONDS + + assert provider.otp != first + assert mac.asked == 2 + + def test_it_presents_the_machines_serial_and_ids(self, mac: FakeMac): + provider = macadi.EmulatedMacAnisetteProvider(mac) # type: ignore[arg-type] + + assert provider.serial == "0PENTAGXTEST" + assert provider.uid == mac.identity["local_user_uuid"] + assert provider.devid == MAC_DEVICE_ID + assert provider.identity == macadi.IDENTITY + + def test_what_it_stores_carries_nothing_device_json_would_refuse(self, mac: FakeMac): + provider = macadi.EmulatedMacAnisetteProvider(mac) # type: ignore[arg-type] + + device._only_identity({"uid": "u", "devid": "d", "anisette": provider.to_json()}) + + +class TestTheAccount: + def test_the_default_is_the_emulated_mac(self, mac: FakeMac, tmp_path: Path): + account = icloud.make_account(identity_path=tmp_path / "device-identity.json") + + assert isinstance(account._anisette, macadi.EmulatedMacAnisetteProvider) + assert mac.opened == [(tmp_path / macadi.DIRNAME, mac.opened[0][1])] # type: ignore[attr-defined] + + def test_it_signs_in_with_the_ids_the_machine_was_provisioned_with( + self, mac: FakeMac, tmp_path: Path): + """`X-Apple-I-MD-M` is derived from that registration; other ids beside it are no Mac.""" + account = icloud.make_account(identity_path=tmp_path / "device-identity.json") + + assert account._uid == mac.identity["local_user_uuid"] + assert account._devid == MAC_DEVICE_ID + + def test_a_machine_provisioned_now_presents_this_installs_serial( + self, mac: FakeMac, tmp_path: Path): + path = tmp_path / "device-identity.json" + device.save("old-uid", "old-devid", {"type": "aniLocal"}, path, serial="0PENTAGXK7QX") + + icloud.make_account(identity_path=path) + + assert mac.opened[0][1] == "0PENTAGXK7QX" # type: ignore[attr-defined] + + def test_the_second_run_is_the_same_device(self, mac: FakeMac, tmp_path: Path): + path = tmp_path / "device-identity.json" + first = icloud.make_account(identity_path=path) + icloud.remember(first, path) + + second = icloud.make_account(identity_path=path) + + assert (second._uid, second._devid) == (first._uid, first._devid) + assert device.load(path)["anisette"] == {"type": "aniEmulatedMac"} + + def test_an_install_that_was_the_android_machine_moves_and_says_so( + self, mac: FakeMac, tmp_path: Path, caplog: pytest.LogCaptureFixture): + path = tmp_path / "device-identity.json" + device.save("old-uid", "old-devid", {"type": "aniLocal"}, path, serial="0PENTAGXK7QX") + + account = icloud.make_account(identity_path=path) + + assert account._devid == MAC_DEVICE_ID + assert "adds one entry to the account's device list" in caplog.text + + def test_naming_an_anisette_server_still_uses_it(self, mac: FakeMac, tmp_path: Path): + icloud.make_account("https://example.invalid", identity_path=tmp_path / "identity.json") + + assert mac.opened == [] # type: ignore[attr-defined] + + def test_naming_the_android_libraries_still_uses_them(self, mac: FakeMac, tmp_path: Path): + account = icloud.make_account( + libs_path=str(tmp_path / "libs.bin"), identity_path=tmp_path / "identity.json") + + assert not isinstance(account._anisette, macadi.EmulatedMacAnisetteProvider) + assert mac.opened == [] # type: ignore[attr-defined] + + +class TestWhatCloudKitIsToldTheDeviceIs: + def test_a_uuid_is_passed_through_untouched(self): + class Account: + device_uuid = "9F1C2D3E-4B5A-4C6D-8E7F-001122334455" + + account = Account() + assert icloud._with_a_uuid_for_cloudkit(account) is account + + def test_a_mac_device_id_gets_the_machines_host_uuid(self, mac: FakeMac): + class Account: + device_uuid = MAC_DEVICE_ID + _anisette = macadi.EmulatedMacAnisetteProvider(mac) # type: ignore[arg-type] + serial = "0PENTAGXTEST" + + view = icloud._with_a_uuid_for_cloudkit(Account()) + + assert view.device_uuid == str(uuid.UUID(HOST_UUID)).upper() + assert view.serial == "0PENTAGXTEST" + + def test_without_a_provider_that_can_say_it_is_derived_and_stable(self): + class Account: + device_uuid = MAC_DEVICE_ID + + first = icloud._with_a_uuid_for_cloudkit(Account()).device_uuid + assert first == icloud._with_a_uuid_for_cloudkit(Account()).device_uuid + uuid.UUID(first) + + +def _odc_entry(name: str, data: bytes) -> bytes: + name_bytes = name.encode() + b"\0" + return (b"070707" + b"0" * 53 + f"{len(name_bytes):06o}".encode() + + f"{len(data):011o}".encode() + name_bytes + data) + + +class TestTakingTheLibraryOutOfTheInstaller: + def test_a_file_is_found_in_an_odc_archive(self): + cpio = (_odc_entry("./other", b"x") + _odc_entry("./" + macadi.FRAMEWORK_PATH, b"lib") + + _odc_entry("TRAILER!!!", b"")) + + assert macadi._file_from_cpio(cpio, macadi.FRAMEWORK_PATH) == b"lib" + + def test_the_x86_64_slice_is_taken_from_a_universal_binary(self): + arm, intel = b"ARM64", b"INTEL" + header = b"\xca\xfe\xba\xbe" + struct.pack(">I", 2) + first = 8 + 40 + fat = (header + + struct.pack(">5I", 0x0100000C, 0, first, len(arm), 0) + + struct.pack(">5I", 0x01000007, 0, first + len(arm), len(intel), 0) + + arm + intel) + + assert macadi._slice(fat, 0x01000007) == intel + + def test_bytes_that_are_not_apples_are_refused(self): + with pytest.raises(macadi.EmulatedMacError, match="not the expected ones"): + macadi.extract(gzip.compress(b"not the installer")) + + def test_a_stored_library_is_not_fetched_again(self, tmp_path: Path, monkeypatch): + """Only the hash decides; a library that matches is never downloaded twice.""" + target = tmp_path / "CoreADI.x86_64" + target.write_bytes(b"pretend") + monkeypatch.setattr(macadi, "LIBRARY_SHA256", hashlib.sha256(b"pretend").hexdigest()) + monkeypatch.setattr(macadi, "_fetch_payload", lambda url: pytest.fail("fetched again")) + + assert macadi.ensure_library(target) == target + + +@pytest.mark.skipif(not os.environ.get("OTV_COREADI"), reason="set OTV_COREADI to a fetched library") +class TestTheRealEngine: + """Apple's CoreADI under Unicorn, in its own process. Nothing is sent to Apple.""" + + def test_it_loads_and_reports_an_unprovisioned_machine(self, tmp_path: Path): + library = Path(os.environ["OTV_COREADI"]) + assert macadi.ensure_library(library) == library + + info = json.loads(macadi._engine("info", tmp_path / "machine", library)) + + assert info["provisioned"] is False + assert "