diff --git a/.github/workflows/exporter-build-check.yml b/.github/workflows/exporter-build-check.yml index dd633403..53ab5edc 100644 --- a/.github/workflows/exporter-build-check.yml +++ b/.github/workflows/exporter-build-check.yml @@ -92,6 +92,7 @@ jobs: --name "OpenTagViewer" ` --icon=OpenTagViewer.ico ` --collect-all unicorn ` + --collect-submodules machoadi ` --collect-data findmy ` --collect-data anisette ` --noconfirm ` @@ -143,3 +144,34 @@ jobs: Write-Host "killed it - a native fault raises nothing, so there is no traceback to find." exit 1 } + + # **The emulated Mac, run by the frozen binary the way a sign-in runs it.** The exporter has no + # interpreter once frozen, so it starts itself with --run-emulated-mac and the engine answers + # through two files (exporter/macadi.py). This is that, for real: Apple's CoreADI under Unicorn + # inside the PyInstaller bundle, with Control Flow Guard already cleared above. `info` is + # Initialize and IsMachineProvisioned - nothing is sent to Apple but the library download. + - name: Run the emulated Mac's engine from the binary + shell: pwsh + run: | + $lib = Join-Path $env:RUNNER_TEMP 'CoreADI.x86_64' + Push-Location python + uv run --frozen python -c "import sys; from pathlib import Path; from exporter import macadi; macadi.ensure_library(Path(sys.argv[1]))" $lib + Pop-Location + + $out = Join-Path $env:RUNNER_TEMP 'engine.out' + $err = Join-Path $env:RUNNER_TEMP 'engine.err' + $env:COREADI_PATH = $lib + & ./python/dist/OpenTagViewer/OpenTagViewer --run-emulated-mac $out $err info --state (Join-Path $env:RUNNER_TEMP 'mac') | Out-Null + $code = $LASTEXITCODE + + $answer = if (Test-Path $out) { Get-Content $out -Raw } else { '' } + $problem = if (Test-Path $err) { Get-Content $err -Raw } else { '' } + Write-Host $answer + Write-Host $problem + Write-Host ("engine exit code: '{0}'" -f $code) + + # On the answer, like the self-test above: an exit code from a killed process proves nothing. + if ($answer -notmatch '"provisioned": false') { + Write-Host "The frozen engine did not report an unprovisioned machine." + exit 1 + } diff --git a/.github/workflows/macos-exporter-python.yml b/.github/workflows/macos-exporter-python.yml index dc653240..b5795521 100644 --- a/.github/workflows/macos-exporter-python.yml +++ b/.github/workflows/macos-exporter-python.yml @@ -260,6 +260,7 @@ jobs: --osx-bundle-identifier "dev.wander.opentagviewer" \ --icon=OpenTagViewer.icns \ --collect-all unicorn \ + --collect-submodules machoadi \ --collect-data findmy \ --collect-data anisette \ --noconfirm \ @@ -279,6 +280,7 @@ jobs: --name "OpenTagViewer" ` --icon=OpenTagViewer.ico ` --collect-all unicorn ` + --collect-submodules machoadi ` --collect-data findmy ` --collect-data anisette ` --noconfirm ` @@ -315,6 +317,7 @@ jobs: uv run --frozen pyinstaller \ --name "OpenTagViewer" \ --collect-all unicorn \ + --collect-submodules machoadi \ --collect-data findmy \ --collect-data anisette \ --noconfirm \ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cab88960..c405377e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -585,6 +585,18 @@ version ≤ 14` is the two decryptor tests for the macOS-local route: **they ski since GitHub stopped offering macOS 14 runners in November 2026, and run only by hand on a Mac that old. A skip naming `_tkinter` means the window tests did not run. +#### 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 @@ -895,7 +907,7 @@ run regardless: each AES entry carries a fresh random salt. | `build-release.yml` | on release | Translation check, JVM tests, Chaquopy bridge tests, release APK | | `macos-scripts-python.yml` | `python/**` or its own changes, or by hand | Exporter and shared-package tests across Python 3.10–3.13 on macOS 15, and 3.13 on Ubuntu under Xvfb | | `macos-exporter-python.yml` | on release | Tag/version check, exporter tests, and the PyInstaller build for macOS (both architectures), Windows and Linux | -| `exporter-build-check.yml` | PR and push to `main`, `python/**` | Builds the Windows binary and starts it. The release workflow above only runs on `release: published`, so without this a broken bundle is first run by whoever downloads it | +| `exporter-build-check.yml` | PR and push to `main`, `python/**` | Builds the Windows binary, starts it, and runs the emulated Mac's engine from inside it (`--run-emulated-mac … info`, which sends Apple nothing but the library download). The release workflow above only runs on `release: published`, so without this a broken bundle is first run by whoever downloads it | | `update-contributors.yml` | weekly, **and on merging a PR by anyone but the owner** | Regenerates the contributor list on the Information page, opens a PR if it changed. The merge run names who it expected to find and fails if GitHub's cached stats did not have them yet — the weekly run is still the guarantee | | `check-adi-libraries.yml` | weekly | Checks Apple's ADI libraries still match what is checked in, opens an issue if they drifted | | `native-stubs.yml` | `app/src/main/cpp/**`, `app/src/test/cpp/**` changes | Builds the stand-ins for Apple's two stubbed libraries on x86_64 and arm64 Linux and checks what they export and return. Seconds, no Android | 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/OpenTagViewer.spec b/python/OpenTagViewer.spec index a14009cb..17fec6f1 100644 --- a/python/OpenTagViewer.spec +++ b/python/OpenTagViewer.spec @@ -11,7 +11,7 @@ # The release workflow passes flags rather than using this file, because it needs three different # invocations for three platforms. The two must agree, and the flags there carry the same comment. -from PyInstaller.utils.hooks import collect_all, collect_data_files +from PyInstaller.utils.hooks import collect_all, collect_data_files, collect_submodules # unicorn loads its native library through ctypes at runtime, so PyInstaller's analysis never sees # it. Without this the build succeeds and the binary dies at startup with "Failed to load the @@ -20,6 +20,11 @@ from PyInstaller.utils.hooks import collect_all, collect_data_files # lets signing in work without a third-party Anisette server. unicorn_datas, unicorn_binaries, unicorn_hiddenimports = collect_all('unicorn') +# The emulated Mac's engine (exporter/macadi.py). Nothing imports it at build time - the frozen +# exporter runs it as a child of itself with --run-emulated-mac - so analysis never finds it, and +# a build without this signs in as nothing. The release workflow passes --collect-submodules. +machoadi_hiddenimports = collect_submodules('machoadi') + # FindMy.py keeps Apple's pinned root certificates as `.crt` files beside its code, and anisette # keeps `apple-root.pem` beside its own. PyInstaller bundles code, not the files next to it - so # without these the binary starts, signs in, and dies opening the keychain session with @@ -35,7 +40,7 @@ a = Analysis( pathex=['.'], binaries=unicorn_binaries, datas=unicorn_datas + findmy_datas + anisette_datas, - hiddenimports=unicorn_hiddenimports, + hiddenimports=unicorn_hiddenimports + machoadi_hiddenimports, hookspath=[], hooksconfig={}, runtime_hooks=[], 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..940d303e --- /dev/null +++ b/python/exporter/macadi.py @@ -0,0 +1,404 @@ +""" +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 importlib +import json +import logging +import os +import struct +import subprocess +import sys +import tempfile +import time +import traceback +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 ------------------------------------------------------------ + + +ENGINE_FLAG = "--run-emulated-mac" +""" +The argument that makes a *frozen* exporter run the engine instead of the window. + +A PyInstaller build has no interpreter to hand `-m` to, so it runs itself: `exporter.wizard` checks +for this before it does anything else and calls :func:`run_engine_here`. It is still a separate +process - which the engine needs, and which keeps the GPL code at arm's length - and on Windows it +is the same executable, so it inherits the Control Flow Guard setting Unicorn needs. +""" + +_ENGINE_MODULES = ("macho", "harness", "stubs", "adi_run", "gsa", "mac_anisette") +"""`machoadi`'s modules, leaves first: each imports only names earlier in this list.""" + + +def load_engine() -> Any: + """ + Import the engine so that its modules find each other, and return `mac_anisette`. + + **They import one another by bare name** - `from harness import ...` - after putting their own + directory on `sys.path`. A frozen build keeps them in an archive rather than a directory, so + that resolves to nothing. Importing each as `machoadi.`, leaves first, and registering it + under its bare name as well makes every one of those imports find the module already loaded. + """ + for name in _ENGINE_MODULES: + if name not in sys.modules: + sys.modules[name] = importlib.import_module(f"machoadi.{name}") + return sys.modules["mac_anisette"] + + +def run_engine_here(argv: list[str]) -> int: + """ + Run one engine command in this process: `out err command [args...]`. + + **Its output goes to files the parent names, not to stdout.** A windowed Windows build may have + no standard streams at all, and the answer is JSON the parent has to parse. Both are opened + before the engine is imported, so even an import failure reaches the parent. + """ + out_path, err_path, *command = argv + with open(out_path, "w", encoding="utf-8") as out, open(err_path, "w", encoding="utf-8") as err: + sys.stdout, sys.stderr = out, err + try: + mac_anisette = load_engine() + sys.argv = ["mac_anisette", *command] + return int(mac_anisette.main() or 0) + except SystemExit as e: + # The engine reports failures as `raise SystemExit("message")`. + if isinstance(e.code, str): + print(e.code, file=err) + return 1 + return int(e.code or 0) + except Exception: # noqa: BLE001 - reported to the parent, which raises EmulatedMacError + traceback.print_exc(file=err) + return 1 + + +def _engine(command: str, state: Path, library: Path, *extra: str) -> str: + """Run one `machoadi` command in its own process and return what it printed.""" + args = [command, "--state", str(state), *extra] + env = {**os.environ, "COREADI_PATH": str(library)} + try: + if getattr(sys, "frozen", False): + code, stdout, stderr = _run_frozen(args, env) + else: + done = subprocess.run( + [sys.executable, "-m", "machoadi.mac_anisette", *args], + capture_output=True, text=True, timeout=ENGINE_TIMEOUT_SECONDS, env=env, + check=False) + code, stdout, stderr = done.returncode, done.stdout, done.stderr + 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 code != 0: + detail = (stderr or stdout).strip().splitlines() + msg = f"The emulated Mac failed `{command}`: {detail[-1] if detail else code}" + raise EmulatedMacError(msg) + return stdout + + +def _run_frozen(args: list[str], env: dict[str, str]) -> tuple[int, str, str]: + """This executable again, with :data:`ENGINE_FLAG`. See :func:`run_engine_here`.""" + with tempfile.TemporaryDirectory(prefix="otv-engine-") as scratch: + out, err = Path(scratch) / "out", Path(scratch) / "err" + done = subprocess.run( + [sys.executable, ENGINE_FLAG, str(out), str(err), *args], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + timeout=ENGINE_TIMEOUT_SECONDS, env=env, check=False, + # A windowed parent starting a child must not flash a console window on Windows. + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) + read = lambda path: path.read_text(encoding="utf-8") if path.is_file() else "" # noqa: E731 + return done.returncode, read(out), read(err) + + +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/exporter/wizard.py b/python/exporter/wizard.py index b7512f07..f15d8cce 100644 --- a/python/exporter/wizard.py +++ b/python/exporter/wizard.py @@ -32,7 +32,7 @@ from typing import Callable, Sequence from tkinter.filedialog import askopenfilenames, asksaveasfilename -from exporter import icloud, localsource, source, terms +from exporter import icloud, localsource, macadi, source, terms from exporter.asyncui import Asker, Cancelled, run_with_progress from exporter.certs import ensure_ca_bundle from exporter.codes import ( @@ -1531,6 +1531,16 @@ def self_test() -> int: if not _emulator_runs(): return 1 + # The emulated Mac's engine is imported by nothing at build time - the frozen exporter runs it + # as a child of itself - so PyInstaller bundles it only because it was told to. A build that + # dropped it would start, show the window, and fail at sign-in. + try: + macadi.load_engine() + except Exception as e: # noqa: BLE001 - reported, and fails the self-test + _say(f"emulated mac engine: MISSING ({type(e).__name__}: {e})") + return 1 + _say("emulated mac engine: bundled") + _say("self-test passed") return 0 @@ -1622,6 +1632,11 @@ def _emu_run(state: dict) -> None: if __name__ == "__main__": + # First, before anything that could open a window: the frozen exporter runs itself as the + # emulated Mac's engine, because it has no other interpreter to run it with. exporter.macadi. + if sys.argv[1:2] == [macadi.ENGINE_FLAG]: + sys.exit(macadi.run_engine_here(sys.argv[2:])) + if "--self-test" in sys.argv[1:]: import anisette # noqa: F401, PLC0415 - imported for its path, above diff --git a/python/pyproject.toml b/python/pyproject.toml index 2f0bc4a4..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] @@ -69,7 +74,8 @@ 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" } +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..5a1f3d31 --- /dev/null +++ b/python/test/test_emulated_mac.py @@ -0,0 +1,310 @@ +""" +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 subprocess +import sys +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 " int: + """`run_engine_here` in a fresh interpreter, as the frozen child would be.""" + script = "import sys; from exporter import macadi; sys.exit(macadi.run_engine_here(sys.argv[1:]))" + return subprocess.run([sys.executable, "-c", script, str(out), str(err), *command], + cwd=Path(__file__).resolve().parents[1], env=env, check=False).returncode diff --git a/python/uv.lock b/python/uv.lock index b6194833..c83f2023 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" }, @@ -839,6 +839,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] +[[package]] +name = "machoadi" +version = "0.1.0" +source = { git = "https://github.com/parawanderer/os-findmy-e?subdirectory=tools%2Fmachoadi&rev=595d39810639d750715babc30b063d4ac8f2c437#595d39810639d750715babc30b063d4ac8f2c437" } +dependencies = [ + { name = "findmy" }, + { name = "unicorn" }, +] + [[package]] name = "macholib" version = "1.16.4" @@ -1013,6 +1022,7 @@ version = "0" source = { virtual = "." } dependencies = [ { name = "findmy" }, + { name = "machoadi" }, { name = "pycryptodome" }, { name = "pyyaml" }, { name = "pyzipper" }, @@ -1032,7 +1042,8 @@ 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 = "machoadi", git = "https://github.com/parawanderer/os-findmy-e?subdirectory=tools%2Fmachoadi&rev=595d39810639d750715babc30b063d4ac8f2c437" }, { name = "pycryptodome", specifier = "==3.22.0" }, { name = "pyyaml", specifier = "==6.0.2" }, { name = "pyzipper", specifier = "==0.4.0" },