Compare commits

...
83 Commits
Author SHA1 Message Date
Majd Alfhaily 3b02b4c555 fix: resolve storefronts from scoped apple bags 2026-11-18 00:43:02 +01:00
Majd Alfhaily d69faf83c8 fix: accept updated app store terms during purchases 2026-11-17 19:58:26 +01:00
Majd Alfhaily 5a6dfe0582 fix: recover account storefront for purchases 2026-11-17 19:18:49 +01:00
Majd Alfhaily b352566155 fix: harden version metadata range reads 2026-11-13 00:07:55 +01:00
rxliuli 6194bf4ecd perf: read ahead when reading version metadata from the IPA
get-version-metadata reads Info.plist out of the remote IPA through
httpRangeReaderAt. archive/zip parses the central directory through a
4 KiB bufio.Reader, and each ReadAt was a separate range request. Those
requests go through the Store "transfer" client, which opens the emulator
for every request, so an IPA with many files cost hundreds of emulator
round trips: 298 requests and ~71s (55s CPU) for one Chrome version.

On a miss, httpRangeReaderAt now fetches at least 1 MiB starting at the
requested offset and serves later reads from that window. Reads that cross
EOF are still clamped, and only the end of the IPA is downloaded.
2026-11-13 00:07:55 +01:00
Majd Alfhaily 20290220cd fix: prevent premature unicorn timeouts during concurrent requests 2026-11-12 22:31:38 +01:00
Majd Alfhaily 3e84853e2e perf: streamline apple asset downloads and caching 2026-11-12 00:30:19 +01:00
Majd Alfhaily 2cfd33fa45 perf: reuse immutable emulator image preparation 2026-11-12 00:30:19 +01:00
Majd Alfhaily e4b0aaee61 fix: bound unicorn runtime memory on all platforms 2026-11-12 00:30:19 +01:00
Majd Alfhaily 9df35a6d84 fix: suggest logging in when store auth state is unprovisioned 2026-11-11 23:40:09 +01:00
Majd Alfhaily 8771e57445 fix: recover delisted apps with unpinned entitlement downloads 2026-11-10 17:52:25 +01:00
Majd Alfhaily e0e2908dc8 feat: parallelize large downloads 2026-11-09 18:07:27 +01:00
Majd Alfhaily f137223276 fix: use compatible user agent for restore image downloads 2026-11-09 18:00:39 +01:00
Majd Alfhaily 536d7bacc1 fix: support percent-encoded url component queries 2026-11-08 18:39:27 +01:00
Majd Alfhaily 856323251a fix: handle authentication server dialogs 2026-11-08 18:19:13 +01:00
Majd Alfhaily 0d99fc2d96 feat: discover storefronts dynamically 2026-11-08 17:50:14 +01:00
Majd Alfhaily 72c47d538b fix: use current store request user agents 2026-11-08 05:41:10 -08:00
Majd Alfhaily 001d889896 fix: restore app store authentication locally 2026-11-07 20:16:18 -08:00
dependabot[bot] d9c0247dae chore: bump github.com/klauspost/compress to 1.18.7 2026-10-25 02:20:01 +02:00
Majd Alfhaily 5dc4c8058d feat: use apple frameworks for store operations 2026-10-18 18:22:14 +02:00
Majd Alfhaily 1b9ff28eb4 fix: accept legacy ios packages without platform declarations 2026-10-15 20:59:41 +02:00
Majd Alfhaily 7578671482 fix: allow redownloads for delisted ios apps 2026-10-15 20:39:07 +02:00
Majd Alfhaily b0fe32d8a1 feat: migrate sap services to macos 27 2026-10-11 18:16:54 +02:00
Majd Alfhaily 0259df3c09 feat: add arm64 sap emulation 2026-10-11 18:16:54 +02:00
Majd Alfhaily 5b7a812a77 feat: resolve macos 27 assets natively 2026-10-11 18:16:54 +02:00
Majd Alfhaily 9d343753c4 chore: update go toolchain and dependencies 2026-10-11 18:16:54 +02:00
Majd Alfhaily 987900b417 docs: document mcp tool setup 2026-10-09 23:55:40 +02:00
Majd Alfhaily 4484b55d36 feat: add watchos platform support 2026-10-09 23:22:25 +02:00
Majd Alfhaily e3932cec31 fix: resolve apple arcade versions through the catalog api 2026-10-08 01:02:30 +02:00
Majd Alfhaily cde7d00355 feat: add version metadata mcp tool 2026-10-06 19:43:42 +02:00
Majd Alfhaily 93b527a839 fix: support phone-number apple account login 2026-10-06 19:24:05 +02:00
Majd Alfhaily ed45c02852 fix: read version metadata for legacy macos apps 2026-10-06 00:35:10 +02:00
Majd Alfhaily f11d9abafe feat: add mcp support 2026-10-05 23:47:57 +02:00
Majd Alfhaily f9aa6536cd fix: normalize the initial authentication url path 2026-10-05 23:39:41 +02:00
Majd Alfhaily 3411d57f45 fix: improve download reliability with kbsync 2026-10-01 21:57:13 +02:00
Majd Alfhaily 0cc226a3d7 fix: select a stable machine identity from network adapters 2026-10-01 20:32:44 +02:00
Majd Alfhaily e258fed14a fix: bound authentication requests and retry transport failures 2026-10-01 19:54:32 +02:00
Majd Alfhaily 1ec8b3e5dc fix: preserve signed authentication requests across redirects 2026-10-01 18:40:36 +02:00
Majd Alfhaily 387d1a4f47 fix: allow downloads of delisted tvos apps 2026-09-30 00:00:53 +02:00
Majd Alfhaily 294488012f fix: reuse credentials across download retries 2026-09-29 23:54:41 +02:00
Majd Alfhaily 5deb9b521b test: cover tvos update fallback safeguards 2026-09-29 23:47:03 +02:00
zebrapurring acd9e7a972 fix: enable update fallback for tvos downloads 2026-09-29 23:47:03 +02:00
Majd Alfhaily 50312a928b fix: recover redacted mac addresses on macos 27 2026-09-29 23:33:35 +02:00
Majd Alfhaily 735b689ac3 fix: normalize 2fa input and clarify verification errors 2026-09-19 19:13:27 +02:00
Majd Alfhaily e5211d6fd9 fix: fall back to consumer catalogs for ios version lookup 2026-09-18 23:13:53 +02:00
Majd Alfhaily 747d66fc0a fix: enable update fallback for macos downloads 2026-09-13 23:52:03 +02:00
Majd Alfhaily 1ed3bf94dd feat: prompt for email during interactive login 2026-09-13 23:32:26 +02:00
Majd Alfhaily fb1ca3521b fix: keep authentication input inline and mask passwords 2026-09-13 23:24:08 +02:00
Majd Alfhaily ad88910ad6 feat: add ios builds for jailbroken devices 2026-09-13 23:08:40 +02:00
Majd Alfhaily c66d6537f4 fix: select macos packages for universal apps 2026-09-13 22:31:06 +02:00
Majd Alfhaily 7b4913a71c feat: include platforms in search results 2026-09-13 22:16:35 +02:00
Majd Alfhaily c4323e4c55 docs: simplify readme layout and usage 2026-09-13 22:07:38 +02:00
Majd Alfhaily 2aaf18b832 test: strengthen patch finalization regression coverage 2026-09-13 21:56:37 +02:00
leoca e3dea14461 fix: report zip finalization errors when applying patches 2026-09-13 21:56:37 +02:00
Majd Alfhaily dd28a3a9d8 fix: handle downloads without sinf data 2026-09-13 21:48:48 +02:00
Majd Alfhaily 5a47056bc3 fix: validate libc interpreter reads and cover detection fallbacks 2026-09-13 21:14:01 +02:00
rjvkn ba85241c88 fix: select the Unicorn artifact from the process libc, not the host
linuxUsesMusl globs the filesystem for a musl loader, which reports whether
the machine has musl available rather than whether this process runs on it.
glibc distributions package musl for cross compilation, so on such a host
the musllinux libunicorn is selected and dlopened into a glibc process.

That load succeeds, because the musl libc really is installed, and symbol
resolution then splits across both libcs: glibc exports __sigsetjmp but not
sigsetjmp, so libunicorn's sigsetjmp binds to musl and stores the jump
buffer unmangled, while siglongjmp binds to glibc and applies PTR_DEMANGLE
to it. The restored stack pointer and program counter come out
non-canonical, so the process dies with SIGSEGV (si_code SI_KERNEL) inside
cgo as soon as the SAP machine initializes.

Read PT_INTERP of /proc/self/exe instead, which names the loader this
process was linked against. Statically linked builds have no PT_INTERP and
keep the existing host probe.
2026-09-13 21:14:01 +02:00
Majd Alfhaily 394cd643de feat: support macos version metadata 2026-09-13 17:04:05 +02:00
Majd Alfhaily 62f1c8b435 feat: support macos in list-versions 2026-09-13 17:04:05 +02:00
Majd Alfhaily 5c522b685d fix: resolve macos versions before retrying downloads 2026-09-13 16:48:10 +02:00
Majd Alfhaily ba180d741d fix: include mac purchases and add platform filtering 2026-09-13 16:35:16 +02:00
Majd Alfhaily d1845ba678 fix: improve recovery from unexpected apple authentication responses 2026-09-13 15:19:45 +02:00
Majd Alfhaily a814a71a9f fix: preserve local zip timestamp metadata 2026-09-13 14:19:57 +02:00
Majd Alfhaily 843f5c6c29 fix: frame zip entries for ota installation 2026-09-13 13:46:34 +02:00
Majd Alfhaily b8bac296b8 feat: support xdg session storage with migration 2026-09-13 13:05:56 +02:00
Majd Alfhaily 24f93d332f chore: add github sponsors funding option 2026-09-13 12:50:16 +02:00
Majd Alfhaily e6acb9c3c2 fix: validate http responses before resuming downloads 2026-09-13 12:44:03 +02:00
dajiaohuang abdb5902cb fix: append resumed downloads without progress 2026-09-13 12:44:03 +02:00
Majd Alfhaily 91d4294085 feat: support purchasing apps by app id 2026-09-13 12:31:06 +02:00
Majd Alfhaily 73fabcc283 feat: include itunes artwork in downloaded ipa packages 2026-09-13 12:14:22 +02:00
Majd Alfhaily 30b2909231 fix: recover app store downloads with endpoint fallbacks 2026-09-13 11:28:44 +02:00
Majd Alfhaily a9bd16c9a2 fix: satisfy download test lint 2026-09-04 00:34:11 +02:00
Majd Alfhaily cee3674258 fix: handle ios apps available on macos 2026-09-04 00:34:11 +02:00
Majd Alfhaily 8f9748fa51 feat: add macos search and download support 2026-09-02 21:29:51 +02:00
Majd Alfhaily d5d0b56faf feat: add visionOS search and download support 2026-08-30 11:11:19 +02:00
Majd Alfhaily 30d19a6859 fix: retry transient authentication responses 2026-08-29 21:12:58 +02:00
Majd Alfhaily 27e8902d7e feat: add list purchases command 2026-08-29 16:21:32 +02:00
Majd Alfhaily acaf6c566e fix(keychain): trust credential creator 2026-08-29 15:15:09 +02:00
Majd Alfhaily 652b9d0083 fix(keychain): label stored credentials 2026-08-29 15:15:09 +02:00
Majd Alfhaily a53550f9c4 fix: handle sap guest timeouts 2026-08-29 00:26:00 +02:00
Jan S. 161888d240 feat: copying raw compressed ZIP entries during sinf replication (#506) 2026-08-29 00:05:57 +02:00
Majd Alfhaily abd86cb01a feat(auth): replace App Store login with SAP signing 2026-08-28 23:22:55 +02:00
AhmedBafkir 5f776fe2f5 fix: "An unknown error has occurred" FailureType 5002 (#500) 2026-08-28 18:34:06 +02:00
312 changed files with 103558 additions and 1549 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
github: majd
+14 -3
View File
@@ -17,7 +17,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go build -o ipatool-$GOOS-$GOARCH.exe
env:
@@ -38,7 +38,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go build -o ipatool-linux-$GOARCH
env:
@@ -54,7 +54,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go build -o ipatool-$GOOS-$GOARCH
env:
@@ -63,3 +63,14 @@ jobs:
CGO_ENABLED: 1
CGO_CFLAGS: -mmacosx-version-min=10.15
CGO_LDFLAGS: -mmacosx-version-min=10.15
build_ios:
name: Build for iOS
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.26.5"
cache: true
- run: brew install ldid cmake
- run: ./tools/build-ios.sh
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go build -o ipatool
env:
+2 -2
View File
@@ -13,9 +13,9 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go generate github.com/majd/ipatool/...
- run: go generate ./...
- uses: golangci/golangci-lint-action@v8
with:
version: v2.9
+47 -5
View File
@@ -21,10 +21,10 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go generate github.com/majd/ipatool/...
- run: go test -v github.com/majd/ipatool/...
- run: go generate ./...
- run: go test -v -timeout 20m ./...
build:
name: Build
runs-on: macos-latest
@@ -33,7 +33,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-windows-arm64.exe
env:
@@ -97,7 +97,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-linux-$GOARCH
env:
@@ -108,6 +108,48 @@ jobs:
name: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
path: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
if-no-files-found: error
build_ios:
name: Build for iOS
runs-on: macos-latest
needs: [get_version, test]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.26.5"
cache: true
- run: brew install ldid cmake
- run: ./tools/build-ios.sh "ipatool-$VERSION-ios-arm64"
env:
VERSION: ${{ needs.get_version.outputs.version }}
- uses: actions/upload-artifact@v4
with:
name: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
path: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
if-no-files-found: error
release_ios:
name: Release for iOS
runs-on: ubuntu-latest
needs: [get_version, build_ios, release_windows]
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
path: bin
- run: chmod +x "bin/$FILE" && tar -czvf "$FILE.tar.gz" "bin/$FILE"
env:
FILE: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
- run: ./tools/sha256sum.sh "$TARBALL" > "$TARBALL.sha256sum"
env:
TARBALL: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64.tar.gz
- uses: svenstaro/upload-release-action@v2
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
file: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64.*
tag: ${{ github.ref }}
overwrite: false
file_glob: true
release_windows:
name: Release for Windows
runs-on: ubuntu-latest
+48 -5
View File
@@ -6,14 +6,57 @@ on:
- main
jobs:
run_tests:
name: Run tests
cross_build_library:
name: Cross-build Windows library consumer
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go generate github.com/majd/ipatool/...
- run: go test -v github.com/majd/ipatool/...
- name: Build from an independent module without dependency replacements
shell: bash
env:
GOWORK: "off"
CGO_ENABLED: "0"
run: |
consumer_dir=$(mktemp -d)
cd "$consumer_dir"
go mod init example.com/ipatool-consumer
go mod edit -require=github.com/majd/ipatool/v2@v2.0.0
go mod edit -replace="github.com/majd/ipatool/v2=$GITHUB_WORKSPACE"
cat > main.go <<'EOF'
package main
import (
"context"
"github.com/majd/ipatool/v2/pkg/appstore"
)
func main() {
_ = appstore.NewAppStore(appstore.Args{})
if err := appstore.Prepare(context.Background()); err != nil {
panic(err)
}
}
EOF
go mod tidy
GOOS=windows GOARCH=amd64 go build -o consumer-amd64.exe .
GOOS=windows GOARCH=arm64 go build -o consumer-arm64.exe .
run_tests:
name: Run tests
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
matrix:
runner: [ubuntu-latest, windows-latest, windows-11-arm]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.26.5"
cache: true
- run: go generate ./...
- run: go test -v -timeout 20m ./...
+1 -1
View File
@@ -4,4 +4,4 @@
.vscode/
.idea/
**/*_mock.go
exp/
exp/
-34
View File
@@ -1,34 +0,0 @@
# AGENTS.md
This file provides guidance for coding agents working in this repository.
## Repository overview
- Project: `ipatool`
- Language: Go
- Entry point: `main.go`
- CLI command implementations: `cmd/`
## Development workflow
1. Keep changes focused and minimal.
2. Prefer idiomatic Go and keep command behavior consistent with existing commands in `cmd/`.
3. Run formatting and tests before finalizing changes.
## Local checks
Use these commands from the repository root:
```bash
go generate ./...
go test ./...
go build ./...
```
## Coding conventions
- Follow standard Go formatting (`gofmt`).
- Avoid introducing new dependencies unless necessary.
- Keep user-facing text consistent with existing CLI help/output tone.
- Preserve backward compatibility for CLI flags and output formats unless explicitly asked to change them.
## Commit/PR guidance
- Write clear, scoped commit messages.
- Summarize what changed and why in PR descriptions.
- Include test/build results in your handoff.
+51 -135
View File
@@ -1,34 +1,29 @@
# IPATool
<p align="center">
<a href="https://GitHub.com/majd/ipatool/releases/"><img src="https://img.shields.io/github/release/majd/ipatool.svg?label=Release" alt="Release"></a>
<a href="https://github.com/majd/ipatool/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License"></a>
<a href="https://github.com/sponsors/majd"><img src="https://img.shields.io/badge/Sponsor-%E2%9D%A4-pink.svg" alt="Sponsor"></a>
</p>
[![Release](https://img.shields.io/github/release/majd/ipatool.svg?label=Release)](https://GitHub.com/majd/ipatool/releases/)
[![License](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/majd/ipatool/blob/main/LICENSE)
<p align="center">
<code>ipatool</code> is a command line tool that allows you to search for iOS, iPadOS, tvOS, watchOS, visionOS, and macOS apps on the <a href="https://apps.apple.com">App Store</a>, and download <code>.ipa</code> or macOS <code>.pkg</code> app packages.
</p>
`ipatool` is a command line tool that allows you to search for iOS apps on the [App Store](https://apps.apple.com) and download a copy of the app package, known as an _ipa_ file.
![Demo](./resources/demo.gif)
- [Requirements](#requirements)
- [Installation](#installation)
- [Manual](#manual)
- [Package Manager (macOS)](#package-manager-macos)
- [Usage](#usage)
- [Compiling](#compiling)
- [License](#license)
- [Releases](https://github.com/majd/ipatool/releases)
- [FAQ](https://github.com/majd/ipatool/wiki/FAQ)
<p align="center">
<img src="./resources/demo.gif" alt="Demo">
</p>
## Requirements
- Supported operating system (Windows, Linux or macOS).
- Apple ID set up to use the App Store.
- A supported operating system (macOS, Linux, Windows or iOS).
- An Apple Account already configured to use the App Store.
## Installation
### Manual
### Linux and Windows
You can grab the latest version of `ipatool` from [GitHub releases](https://github.com/majd/ipatool/releases).
### Package Manager (macOS)
### macOS
You can install `ipatool` using [Homebrew](https://brew.sh).
@@ -38,135 +33,56 @@ $ brew install ipatool
## Usage
To authenticate with the App Store, use the `auth` command.
To get started, run the following command.
```
Authenticate with the App Store
```text
$ ipatool --help
A cli tool for interacting with Apple's ipa files
Usage:
ipatool auth [command]
ipatool [command]
Available Commands:
info Show current account info
login Login to the App Store
revoke Revoke your App Store credentials
auth Authenticate with the App Store
completion Generate the autocompletion script for the specified shell
download Download iOS, iPadOS, tvOS, watchOS, visionOS, and macOS app packages from the App Store
get-version-metadata Retrieves the metadata for a specific version of an app
help Help about any command
list-purchases List apps owned by the authenticated App Store account
list-versions List the available versions of an App Store app
mcp Serve App Store tools over MCP using stdio
purchase Obtain a license for the app from the App Store
search Search for iOS, iPadOS, tvOS, watchOS, visionOS, and macOS apps available on the App Store
Flags:
-h, --help help for auth
Global Flags:
--format format sets output format for command; can be 'text', 'json' (default text)
--non-interactive run in non-interactive session
--verbose enables verbose logs
Use "ipatool auth [command] --help" for more information about a command.
```
To search for apps on the App Store, use the `search` command.
```
Search for iOS and tvOS apps available on the App Store
Usage:
ipatool search <term> [flags]
Flags:
-h, --help help for search
-l, --limit int maximum amount of search results to retrieve (default 5)
--platform string Platform to search: iphone, ipad, or appletv
Global Flags:
--format format sets output format for command; can be 'text', 'json' (default text)
--non-interactive run in non-interactive session
--verbose enables verbose logs
```
To obtain a license for an app, use the `purchase` command.
```
Obtain a license for the app from the App Store
Usage:
ipatool purchase [flags]
Flags:
-b, --bundle-identifier string Bundle identifier of the target iOS app (required)
-h, --help help for purchase
Global Flags:
--format format sets output format for command; can be 'text', 'json' (default text)
--non-interactive run in non-interactive session
--verbose enables verbose logs
```
To obtain a list of availble app versions to download, use the `list-versions` command.
```
List the available versions of an iOS app
Usage:
ipatool list-versions [flags]
Flags:
-i, --app-id int ID of the target iOS app (required)
-b, --bundle-identifier string The bundle identifier of the target iOS app (overrides the app ID)
-h, --help help for list-versions
Global Flags:
--format format sets output format for command; can be 'text', 'json' (default text)
-h, --help help for ipatool
--keychain-passphrase string passphrase for unlocking keychain
--non-interactive run in non-interactive session
--verbose enables verbose logs
```
-v, --version version for ipatool
To download a copy of the ipa file, use the `download` command.
```
Download (encrypted) iOS and tvOS app packages from the App Store
Usage:
ipatool download [flags]
Flags:
-i, --app-id int ID of the target iOS app (required)
-b, --bundle-identifier string The bundle identifier of the target iOS app (overrides the app ID)
--external-version-id string External version identifier of the target iOS app (defaults to latest version when not specified)
-h, --help help for download
-o, --output string The destination path of the downloaded app package
--platform string Platform to download for: iphone, ipad, or appletv
--purchase Obtain a license for the app if needed
Global Flags:
--format format sets output format for command; can be 'text', 'json' (default text)
--keychain-passphrase string passphrase for unlocking keychain
--non-interactive run in non-interactive session
--verbose enables verbose logs
```
To resolve an external version identifier, returned by the `list-versions` command, use the `get-version-metadata` command.
```
Retrieves the metadata for a specific version of an app
Usage:
ipatool get-version-metadata [flags]
Flags:
-i, --app-id int ID of the target iOS app (required)
-b, --bundle-identifier string The bundle identifier of the target iOS app (overrides the app ID)
--external-version-id string External version identifier of the target iOS app (required)
-h, --help help for get-version-metadata
Global Flags:
--format format sets output format for command; can be 'text', 'json' (default text)
--keychain-passphrase string passphrase for unlocking keychain
--non-interactive run in non-interactive session
--verbose enables verbose logs
Use "ipatool [command] --help" for more information about a command.
```
**Note:** the tool runs in interactive mode by default. Use the `--non-interactive` flag
if running in an automated environment.
### MCP tools
Run `ipatool auth login` in a terminal, then configure your MCP client to launch the stdio server:
```json
{
"mcpServers": {
"ipatool": {
"command": "ipatool",
"args": ["mcp"]
}
}
}
```
## Compiling
The tool can be compiled using the Go toolchain.
@@ -178,10 +94,10 @@ $ go build -o ipatool
Unit tests can be executed with the following commands.
```shell
$ go generate github.com/majd/ipatool/...
$ go test -v github.com/majd/ipatool/...
$ go generate ./...
$ go test -v ./...
```
## License
IPATool is released under the [MIT license](https://github.com/majd/ipatool/blob/main/LICENSE).
ipatool is released under the [MIT license](https://github.com/majd/ipatool/blob/main/LICENSE).
+19 -35
View File
@@ -1,18 +1,13 @@
package cmd
import (
"bufio"
"errors"
"fmt"
"os"
"strings"
"time"
"github.com/avast/retry-go"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/majd/ipatool/v2/pkg/util"
"github.com/spf13/cobra"
"golang.org/x/term"
)
func authCmd() *cobra.Command {
@@ -29,18 +24,6 @@ func authCmd() *cobra.Command {
}
func loginCmd() *cobra.Command {
promptForAuthCode := func() (string, error) {
authCode, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return "", fmt.Errorf("failed to read string: %w", err)
}
authCode = strings.Trim(authCode, "\n")
authCode = strings.Trim(authCode, "\r")
return authCode, nil
}
var email, password, authCode string
cmd := &cobra.Command{
@@ -49,50 +32,53 @@ func loginCmd() *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
interactive := cmd.Context().Value(interactiveKey).(bool)
if email == "" && !interactive {
return errors.New("an Apple ID is required when not running in interactive mode; use the \"--email\" flag")
}
if email == "" && interactive {
value, err := readPrompt("enter Apple ID (email address or phone number): ", false)
if err != nil {
return fmt.Errorf("failed to read Apple ID: %w", err)
}
email = value
}
if password == "" && !interactive {
return errors.New("password is required when not running in interactive mode; use the \"--password\" flag")
}
if password == "" && interactive {
dependencies.Logger.Log().Msg("enter password:")
bytes, err := term.ReadPassword(int(os.Stdin.Fd()))
value, err := readPrompt("enter password: ", true)
if err != nil {
return fmt.Errorf("failed to read password: %w", err)
}
password = string(bytes)
password = value
}
dependencies.Logger.Log().Msg("preparing authentication; the first login may take a few minutes")
var lastErr error
// nolint:wrapcheck
return retry.Do(func() error {
if errors.Is(lastErr, appstore.ErrAuthCodeRequired) && interactive {
dependencies.Logger.Log().Msg("enter 2FA code:")
var err error
authCode, err = promptForAuthCode()
authCode, err = readPrompt("enter 2FA code: ", false)
if err != nil {
return fmt.Errorf("failed to read auth code: %w", err)
}
}
dependencies.Logger.Verbose().
Str("password", password).
Str("email", email).
Str("authCode", util.IfEmpty(authCode, "<nil>")).
Bool("authCodeProvided", authCode != "").
Msg("logging in")
bag, err := dependencies.AppStore.Bag(appstore.BagInput{})
if err != nil {
return fmt.Errorf("failed to get bag: %w", err)
}
output, err := dependencies.AppStore.Login(appstore.LoginInput{
Email: email,
Password: password,
AuthCode: authCode,
Endpoint: bag.AuthEndpoint,
})
if err != nil {
if errors.Is(err, appstore.ErrAuthCodeRequired) && !interactive {
@@ -125,12 +111,10 @@ func loginCmd() *cobra.Command {
},
}
cmd.Flags().StringVarP(&email, "email", "e", "", "email address for the Apple ID (required)")
cmd.Flags().StringVarP(&email, "email", "e", "", "Apple ID email address or phone number (required)")
cmd.Flags().StringVarP(&password, "password", "p", "", "password for the Apple ID (required)")
cmd.Flags().StringVar(&authCode, "auth-code", "", "2FA code for the Apple ID")
_ = cmd.MarkFlagRequired("email")
return cmd
}
+106
View File
@@ -0,0 +1,106 @@
package cmd
import (
"context"
"os"
"path/filepath"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/majd/ipatool/v2/pkg/log"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Login command", func() {
var store *fakeLoginAppStore
BeforeEach(func() {
previousDependencies := dependencies
DeferCleanup(func() { dependencies = previousDependencies })
store = &fakeLoginAppStore{}
dependencies.AppStore = store
dependencies.Logger = log.NewLogger(log.Args{})
})
DescribeTable("requires credentials in non-interactive mode", func(args []string, message string) {
cmd := loginCmd()
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
cmd.SetArgs(args)
Expect(cmd.Execute()).To(MatchError(message))
Expect(store.loginCalls).To(BeZero())
},
Entry("missing Apple ID", []string{"--password", "secret"}, "an Apple ID is required when not running in interactive mode; use the \"--email\" flag"),
Entry("missing password", []string{"--email", "user@example.com"}, "password is required when not running in interactive mode; use the \"--password\" flag"),
)
DescribeTable("uses supplied credentials", func(interactive bool, appleID string) {
cmd := loginCmd()
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, interactive))
cmd.SetArgs([]string{"--email", appleID, "--password", "secret"})
Expect(cmd.Execute()).To(Succeed())
Expect(store.loginCalls).To(Equal(1))
Expect(store.input).To(Equal(appstore.LoginInput{Email: appleID, Password: "secret"}))
},
Entry("interactive email", true, "user@example.com"),
Entry("non-interactive email", false, "user@example.com"),
Entry("interactive Chinese phone number", true, "+8613912345678"),
Entry("non-interactive Chinese phone number", false, "+8613912345678"),
Entry("interactive Indian phone number", true, "9123456789"),
Entry("non-interactive Indian phone number", false, "9123456789"),
)
DescribeTable("prompts for an Apple ID", func(input, appleID, message string) {
dir := GinkgoT().TempDir()
inputPath := filepath.Join(dir, "stdin")
Expect(os.WriteFile(inputPath, []byte(input), 0o600)).To(Succeed())
stdin, err := os.Open(inputPath)
Expect(err).NotTo(HaveOccurred())
DeferCleanup(stdin.Close)
stderr, err := os.Create(filepath.Join(dir, "stderr"))
Expect(err).NotTo(HaveOccurred())
DeferCleanup(stderr.Close)
previousStdin, previousStderr := os.Stdin, os.Stderr
os.Stdin, os.Stderr = stdin, stderr
DeferCleanup(func() { os.Stdin, os.Stderr = previousStdin, previousStderr })
cmd := loginCmd()
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, true))
cmd.SetArgs([]string{"--password", "secret"})
cmd.SilenceErrors = true
cmd.SilenceUsage = true
err = cmd.Execute()
if message == "" {
Expect(err).NotTo(HaveOccurred())
Expect(store.loginCalls).To(Equal(1))
Expect(store.input).To(Equal(appstore.LoginInput{Email: appleID, Password: "secret"}))
} else {
Expect(err).To(MatchError(message))
Expect(store.loginCalls).To(BeZero())
}
prompt, err := os.ReadFile(stderr.Name())
Expect(err).NotTo(HaveOccurred())
Expect(string(prompt)).To(Equal("enter Apple ID (email address or phone number): "))
},
Entry("reads email without requiring a terminal", "user@example.com\n", "user@example.com", ""),
Entry("reads a phone number without requiring a terminal", "+91 91234-56789\n", "+91 91234-56789", ""),
Entry("reports input errors", "", "", "failed to read Apple ID: failed to read input: EOF"),
)
})
type fakeLoginAppStore struct {
appstore.AppStore
input appstore.LoginInput
loginCalls int
}
func (f *fakeLoginAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
f.input = input
f.loginCalls++
return appstore.LoginOutput{}, nil
}
+13
View File
@@ -0,0 +1,13 @@
package cmd
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestCmd(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Command Suite")
}
+19 -35
View File
@@ -19,7 +19,6 @@ import (
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
"github.com/rs/zerolog"
"github.com/spf13/cobra"
"golang.org/x/term"
)
var dependencies = Dependencies{}
@@ -53,22 +52,23 @@ func newLogger(format OutputFormat, verbose bool) log.Logger {
}
// newCookieJar returns a new cookie jar instance.
func newCookieJar(machine machine.Machine) http.CookieJar {
func newCookieJar(stateDirectory string) http.CookieJar {
return util.Must(cookiejar.New(&cookiejar.Options{
Filename: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName, CookieJarFileName),
Filename: filepath.Join(stateDirectory, CookieJarFileName),
}))
}
// newKeychain returns a new keychain instance.
func newKeychain(machine machine.Machine, logger log.Logger, interactive bool) keychain.Keychain {
ring := util.Must(keyring.Open(keyring.Config{
func newKeychain(stateDirectory string, interactive bool) keychain.Keychain {
ring := util.Must(openKeyring(keyring.Config{
AllowedBackends: []keyring.BackendType{
keyring.KeychainBackend,
keyring.SecretServiceBackend,
keyring.FileBackend,
},
ServiceName: KeychainServiceName,
FileDir: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName),
ServiceName: KeychainServiceName,
KeychainTrustApplication: true,
FileDir: stateDirectory,
FilePasswordFunc: func(s string) (string, error) {
if keychainPassphrase == "" && !interactive {
return "", errors.New("keychain passphrase is required when not running in interactive mode; use the \"--keychain-passphrase\" flag")
@@ -79,21 +79,19 @@ func newKeychain(machine machine.Machine, logger log.Logger, interactive bool) k
}
path := strings.Split(s, " unlock ")[1]
logger.Log().Msgf("enter passphrase to unlock %s (this is separate from your Apple ID password): ", path)
bytes, err := term.ReadPassword(int(os.Stdin.Fd()))
password, err := readPrompt(fmt.Sprintf("enter passphrase to unlock %s (this is separate from your Apple ID password): ", path), true)
if err != nil {
return "", fmt.Errorf("failed to read password: %w", err)
}
password := string(bytes)
password = strings.Trim(password, "\n")
password = strings.Trim(password, "\r")
return password, nil
},
}))
return keychain.New(keychain.Args{Keyring: ring})
return keychain.New(keychain.Args{
Keyring: ring,
Label: KeychainServiceName,
})
}
// initWithCommand initializes the dependencies of the command.
@@ -103,33 +101,19 @@ func initWithCommand(cmd *cobra.Command) {
format := util.Must(OutputFormatFromString(cmd.Flag("format").Value.String()))
dependencies.Logger = newLogger(format, verbose)
if cmd.Name() == "mcp" {
dependencies.Logger = log.NewLogger(log.Args{Verbose: verbose, Writer: zerolog.SyncWriter(os.Stderr)})
}
dependencies.OS = operatingsystem.New()
dependencies.Machine = machine.New(machine.Args{OS: dependencies.OS})
dependencies.CookieJar = newCookieJar(dependencies.Machine)
dependencies.Keychain = newKeychain(dependencies.Machine, dependencies.Logger, interactive)
stateDirectory := util.Must(prepareStateDirectory(dependencies.OS, dependencies.Machine.HomeDirectory()))
dependencies.CookieJar = newCookieJar(stateDirectory)
dependencies.Keychain = newKeychain(stateDirectory, interactive)
dependencies.AppStore = appstore.NewAppStore(appstore.Args{
CookieJar: dependencies.CookieJar,
OperatingSystem: dependencies.OS,
Keychain: dependencies.Keychain,
Machine: dependencies.Machine,
})
util.Must("", createConfigDirectory(dependencies.OS, dependencies.Machine))
}
// createConfigDirectory creates the configuration directory for the CLI tool, if needed.
func createConfigDirectory(os operatingsystem.OperatingSystem, machine machine.Machine) error {
configDirectoryPath := filepath.Join(machine.HomeDirectory(), ConfigDirectoryName)
_, err := os.Stat(configDirectoryPath)
if err != nil && os.IsNotExist(err) {
err = os.MkdirAll(configDirectoryPath, 0700)
if err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
} else if err != nil {
return fmt.Errorf("could not read metadata: %w", err)
}
return nil
}
+70 -38
View File
@@ -2,7 +2,6 @@ package cmd
import (
"errors"
"fmt"
"os"
"time"
@@ -14,6 +13,11 @@ import (
// nolint:wrapcheck
func downloadCmd() *cobra.Command {
return downloadCmdWithAppStore(func() appstore.AppStore { return dependencies.AppStore })
}
//nolint:wrapcheck
func downloadCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
var (
acquireLicense bool
outputPath string
@@ -25,34 +29,33 @@ func downloadCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "download",
Short: "Download (encrypted) iOS and tvOS app packages from the App Store",
Short: "Download iOS, iPadOS, tvOS, watchOS, visionOS, and macOS app packages from the App Store",
RunE: func(cmd *cobra.Command, args []string) error {
if appID == 0 && bundleID == "" {
return errors.New("either the app ID or the bundle identifier must be specified")
}
platform, err := appstore.ParsePlatform(platformValue)
if err != nil {
return err
}
store := appStore()
infoResult, err := store.AccountInfo()
if err != nil {
return err
}
acc := infoResult.Account
var lastErr error
var acc appstore.Account
purchaseRequired := false
purchased := false
return retry.Do(func() error {
infoResult, err := dependencies.AppStore.AccountInfo()
if err != nil {
return err
}
acc = infoResult.Account
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
bagOutput, err := dependencies.AppStore.Bag(appstore.BagInput{})
if err != nil {
return fmt.Errorf("failed to get bag: %w", err)
}
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
loginResult, err := store.Login(appstore.LoginInput{
Email: acc.Email,
Password: acc.Password,
Endpoint: bagOutput.AuthEndpoint,
})
if err != nil {
return err
@@ -61,30 +64,46 @@ func downloadCmd() *cobra.Command {
acc = loginResult.Account
}
app := appstore.App{ID: appID}
platform, err := appstore.ParsePlatform(platformValue)
if err != nil {
return err
}
app := appstore.App{ID: appID, BundleID: bundleID}
if bundleID != "" {
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{
lookupResult, err := store.Lookup(appstore.LookupInput{
Account: acc,
BundleID: bundleID,
Platform: platform,
})
if err != nil && (appID == 0 || !errors.Is(err, appstore.ErrAppNotFound)) {
return err
}
// Delisted apps may still be downloadable by their numeric ID.
if err == nil {
app = lookupResult.App
}
}
if errors.Is(lastErr, appstore.ErrLicenseRequired) {
purchaseRequired = true
}
if purchaseRequired {
err := store.Purchase(appstore.PurchaseInput{
Account: acc,
App: app,
Platform: platform,
})
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
return err
}
// Purchasing may persist a server-corrected storefront.
info, err := store.AccountInfo()
if err != nil {
return err
}
app = lookupResult.App
}
if errors.Is(lastErr, appstore.ErrLicenseRequired) {
err := dependencies.AppStore.Purchase(appstore.PurchaseInput{Account: acc, App: app})
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
return err
}
acc = info.Account
purchaseRequired = false
purchased = true
dependencies.Logger.Verbose().
Bool("success", true).
@@ -110,7 +129,8 @@ func downloadCmd() *cobra.Command {
)
}
out, err := dependencies.AppStore.Download(appstore.DownloadInput{
out, err := store.Download(appstore.DownloadInput{
Context: cmd.Context(),
Account: acc,
App: app,
OutputPath: outputPath,
@@ -122,8 +142,7 @@ func downloadCmd() *cobra.Command {
return err
}
err = dependencies.AppStore.ReplicateSinf(appstore.ReplicateSinfInput{Sinfs: out.Sinfs, PackagePath: out.DestinationPath})
if err != nil {
if err := replicateDownloadSinf(store, platform, out); err != nil {
return err
}
@@ -156,12 +175,25 @@ func downloadCmd() *cobra.Command {
},
}
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target iOS app (required)")
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (overrides the app ID)")
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app (required)")
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID when found)")
cmd.Flags().StringVarP(&outputPath, "output", "o", "", "The destination path of the downloaded app package")
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target iOS app (defaults to latest version when not specified)")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to download for: iphone, ipad, or appletv")
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target app (defaults to latest version when not specified)")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to download for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
cmd.Flags().BoolVar(&acquireLicense, "purchase", false, "Obtain a license for the app if needed")
return cmd
}
type sinfReplicator interface {
ReplicateSinf(input appstore.ReplicateSinfInput) error
}
//nolint:wrapcheck
func replicateDownloadSinf(store sinfReplicator, platform appstore.Platform, out appstore.DownloadOutput) error {
if platform == appstore.PlatformMacOS && len(out.Sinfs) == 0 {
return nil
}
return store.ReplicateSinf(appstore.ReplicateSinfInput{Sinfs: out.Sinfs, PackagePath: out.DestinationPath})
}
+368
View File
@@ -0,0 +1,368 @@
package cmd
import (
"context"
"errors"
"fmt"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/majd/ipatool/v2/pkg/log"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Download command", func() {
Describe("app resolution", func() {
var store *fakeDownloadAppStore
BeforeEach(func() {
store = &fakeDownloadAppStore{account: appstore.Account{StoreFront: "143441"}}
previousDependencies := dependencies
DeferCleanup(func() { dependencies = previousDependencies })
dependencies.Logger = log.NewLogger(log.Args{})
})
execute := func(args ...string) error {
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
cmd.SetArgs(args)
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
return cmd.Execute()
}
It("uses the app ID when the bundle is absent from the catalog", func() {
store.lookupError = fmt.Errorf("lookup: %w", appstore.ErrAppNotFound)
Expect(execute("-i", "42", "-b", "com.example.delisted", "--platform", "appletv")).To(Succeed())
Expect(store.lookupInputs).To(Equal([]appstore.LookupInput{{
Account: appstore.Account{StoreFront: "143441"},
BundleID: "com.example.delisted",
Platform: appstore.PlatformAppleTV,
}}))
Expect(store.downloadInputs).To(HaveLen(1))
Expect(store.downloadInputs[0].App).To(Equal(appstore.App{ID: 42, BundleID: "com.example.delisted"}))
Expect(store.downloadInputs[0].Platform).To(Equal(appstore.PlatformAppleTV))
})
It("preserves bundle identifier precedence when lookup succeeds", func() {
store.lookupOutput.App = appstore.App{ID: 43, BundleID: "com.example.listed"}
Expect(execute("-i", "42", "-b", "com.example.listed")).To(Succeed())
Expect(store.downloadInputs).To(HaveLen(1))
Expect(store.downloadInputs[0].App).To(Equal(store.lookupOutput.App))
})
It("resolves a bundle identifier without an app ID", func() {
store.lookupOutput.App = appstore.App{ID: 43, BundleID: "com.example.listed"}
Expect(execute("-b", "com.example.listed")).To(Succeed())
Expect(store.downloadInputs).To(HaveLen(1))
Expect(store.downloadInputs[0].App).To(Equal(store.lookupOutput.App))
})
It("does not look up the bundle for an explicit app ID and version", func() {
Expect(execute("-i", "42", "--platform", "appletv", "--external-version-id", "123456")).To(Succeed())
Expect(store.lookupInputs).To(BeEmpty())
Expect(store.downloadInputs).To(HaveLen(1))
Expect(store.downloadInputs[0].App).To(Equal(appstore.App{ID: 42}))
Expect(store.downloadInputs[0].ExternalVersionID).To(Equal("123456"))
})
DescribeTable("preserves lookup errors", func(args []string, lookupError error) {
store.lookupError = lookupError
Expect(execute(args...)).To(MatchError(lookupError))
Expect(store.downloadInputs).To(BeEmpty())
},
Entry("missing bundle without an app ID", []string{"-b", "com.example.delisted"}, appstore.ErrAppNotFound),
Entry("request failure with an app ID", []string{"-i", "42", "-b", "com.example.app"}, errors.New("request failed")),
)
})
It("exposes macOS in platform help", func() {
cmd := downloadCmd()
Expect(cmd.Flag("platform").Usage).To(ContainSubstring("macos"))
})
It("skips sinf replication for macOS packages", func() {
replicator := &fakeSinfReplicator{}
err := replicateDownloadSinf(replicator, appstore.PlatformMacOS, appstore.DownloadOutput{
DestinationPath: "app.pkg",
})
Expect(err).ToNot(HaveOccurred())
Expect(replicator.called).To(BeFalse())
})
It("replicates sinf for mobile packages downloaded for macOS", func() {
replicator := &fakeSinfReplicator{}
out := appstore.DownloadOutput{
DestinationPath: "app.ipa",
Sinfs: []appstore.Sinf{{Data: []byte("sinf")}},
}
err := replicateDownloadSinf(replicator, appstore.PlatformMacOS, out)
Expect(err).ToNot(HaveOccurred())
Expect(replicator.called).To(BeTrue())
Expect(replicator.input).To(Equal(appstore.ReplicateSinfInput{
PackagePath: out.DestinationPath,
Sinfs: out.Sinfs,
}))
})
It("replicates sinf for non-macOS packages", func() {
replicator := &fakeSinfReplicator{}
out := appstore.DownloadOutput{
DestinationPath: "app.ipa",
Sinfs: []appstore.Sinf{{Data: []byte("sinf")}},
}
err := replicateDownloadSinf(replicator, appstore.PlatformIPhone, out)
Expect(err).ToNot(HaveOccurred())
Expect(replicator.called).To(BeTrue())
Expect(replicator.input).To(Equal(appstore.ReplicateSinfInput{
PackagePath: out.DestinationPath,
Sinfs: out.Sinfs,
}))
})
It("returns sinf replication errors for non-macOS packages", func() {
replicator := &fakeSinfReplicator{err: errors.New("replication failed")}
err := replicateDownloadSinf(replicator, appstore.PlatformIPhone, appstore.DownloadOutput{})
Expect(err).To(MatchError("replication failed"))
})
DescribeTable("preserves the platform when automatic purchase retries the download", func(platform appstore.Platform) {
store := &fakeDownloadAppStore{downloadErrors: []error{appstore.ErrLicenseRequired, nil}}
previousDependencies := dependencies
DeferCleanup(func() { dependencies = previousDependencies })
dependencies.Logger = log.NewLogger(log.Args{})
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
cmd.SetArgs([]string{"--app-id", "42", "--platform", string(platform), "--purchase"})
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
Expect(cmd.Execute()).To(Succeed())
Expect(store.accountInfoCalls).To(Equal(2))
Expect(store.purchaseInputs).To(HaveLen(1))
Expect(store.purchaseInputs[0].Platform).To(Equal(platform))
Expect(store.purchaseInputs[0].App).To(Equal(appstore.App{ID: 42}))
Expect(store.downloadInputs).To(HaveLen(2))
Expect(store.downloadInputs[0].Platform).To(Equal(platform))
Expect(store.downloadInputs[1].Platform).To(Equal(platform))
},
Entry("macOS", appstore.PlatformMacOS),
Entry("watchOS", appstore.PlatformWatchOS),
)
It("retains the pending automatic purchase after refreshing authentication", func() {
store := &fakeDownloadAppStore{
downloadErrors: []error{appstore.ErrLicenseRequired, nil},
purchaseErrors: []error{appstore.ErrPasswordTokenExpired, nil},
}
previousDependencies := dependencies
DeferCleanup(func() { dependencies = previousDependencies })
dependencies.Logger = log.NewLogger(log.Args{})
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
cmd.SetArgs([]string{"--app-id", "42", "--platform", "macos", "--purchase"})
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
Expect(cmd.Execute()).To(Succeed())
Expect(store.accountInfoCalls).To(Equal(2))
Expect(store.loginInputs).To(HaveLen(1))
Expect(store.purchaseInputs).To(HaveLen(2))
Expect(store.purchaseInputs[0].Platform).To(Equal(appstore.PlatformMacOS))
Expect(store.purchaseInputs[1].Platform).To(Equal(appstore.PlatformMacOS))
Expect(store.downloadInputs).To(HaveLen(2))
})
DescribeTable("reuses the account throughout download retries", func(downloadErrors []error, purchaseCount int) {
account := appstore.Account{
Email: "user@example.com",
Password: "password",
PasswordToken: "expired-token",
StoreFront: "143441",
}
refreshedAccount := account
refreshedAccount.PasswordToken = "refreshed-token"
store := &fakeDownloadAppStore{
account: account,
loginAccount: refreshedAccount,
downloadErrors: downloadErrors,
}
previousDependencies := dependencies
DeferCleanup(func() { dependencies = previousDependencies })
dependencies.Logger = log.NewLogger(log.Args{})
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
cmd.SetArgs([]string{"--bundle-identifier", "com.example.app", "--purchase"})
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
Expect(cmd.Execute()).To(Succeed())
Expect(store.accountInfoCalls).To(Equal(1 + purchaseCount))
Expect(store.loginInputs).To(Equal([]appstore.LoginInput{{Email: account.Email, Password: account.Password}}))
Expect(store.lookupInputs).To(HaveLen(len(downloadErrors)))
Expect(store.lookupInputs[0].Account).To(Equal(account))
Expect(store.downloadInputs).To(HaveLen(len(downloadErrors)))
Expect(store.downloadInputs[0].Account).To(Equal(account))
for _, input := range store.lookupInputs[1:] {
Expect(input.Account).To(Equal(refreshedAccount))
}
for _, input := range store.downloadInputs[1:] {
Expect(input.Account).To(Equal(refreshedAccount))
}
Expect(store.purchaseInputs).To(HaveLen(purchaseCount))
for _, input := range store.purchaseInputs {
Expect(input.Account).To(Equal(refreshedAccount))
}
},
Entry("refreshes an expired token", []error{appstore.ErrPasswordTokenExpired, nil}, 0),
Entry("retains the refreshed token for a subsequent purchase", []error{appstore.ErrPasswordTokenExpired, appstore.ErrLicenseRequired, nil}, 1),
)
DescribeTable("downloads using the storefront persisted during purchase", func(refresh bool) {
original := appstore.Account{Email: "user@example.com", Password: "password", PasswordToken: "old-token", StoreFront: "143441-1,34"}
corrected := original
corrected.StoreFront = "143462-1,34"
store := &fakeDownloadAppStore{
account: original, downloadErrors: []error{appstore.ErrLicenseRequired, nil},
purchaseStorefront: corrected.StoreFront,
}
if refresh {
corrected.PasswordToken = "new-token"
store.loginAccount = corrected
store.purchaseErrors = []error{appstore.ErrPasswordTokenExpired, nil}
}
previousDependencies := dependencies
DeferCleanup(func() { dependencies = previousDependencies })
dependencies.Logger = log.NewLogger(log.Args{})
command := downloadCmdWithAppStore(func() appstore.AppStore { return store })
command.SetArgs([]string{"--app-id", "42", "--purchase"})
command.SetContext(context.WithValue(context.Background(), interactiveKey, false))
Expect(command.Execute()).To(Succeed())
Expect(store.downloadInputs).To(HaveLen(2))
Expect(store.downloadInputs[0].Account).To(Equal(original))
Expect(store.downloadInputs[1].Account).To(Equal(corrected))
if refresh {
Expect(store.loginInputs).To(HaveLen(1))
Expect(store.purchaseInputs).To(HaveLen(2))
Expect(store.purchaseInputs[1].Account).To(Equal(corrected))
} else {
Expect(store.loginInputs).To(BeEmpty())
}
}, Entry("immediate success", false), Entry("token refresh after correction", true))
It("returns an account read error before attempting a download", func() {
store := &fakeDownloadAppStore{accountInfoError: errors.New("account unavailable")}
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
cmd.SetArgs([]string{"--app-id", "42"})
Expect(cmd.Execute()).To(MatchError(store.accountInfoError))
Expect(store.accountInfoCalls).To(Equal(1))
Expect(store.loginInputs).To(BeEmpty())
Expect(store.lookupInputs).To(BeEmpty())
Expect(store.purchaseInputs).To(BeEmpty())
Expect(store.downloadInputs).To(BeEmpty())
})
})
type fakeSinfReplicator struct {
called bool
input appstore.ReplicateSinfInput
err error
}
func (f *fakeSinfReplicator) ReplicateSinf(input appstore.ReplicateSinfInput) error {
f.called = true
f.input = input
return f.err
}
type fakeDownloadAppStore struct {
account appstore.Account
accountInfoCalls int
accountInfoError error
downloadErrors []error
downloadInputs []appstore.DownloadInput
loginAccount appstore.Account
loginInputs []appstore.LoginInput
lookupInputs []appstore.LookupInput
lookupOutput appstore.LookupOutput
lookupError error
purchaseErrors []error
purchaseInputs []appstore.PurchaseInput
purchaseStorefront string
}
func (f *fakeDownloadAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
f.loginInputs = append(f.loginInputs, input)
f.account = f.loginAccount
return appstore.LoginOutput{Account: f.loginAccount}, nil
}
func (f *fakeDownloadAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
f.accountInfoCalls++
return appstore.AccountInfoOutput{Account: f.account}, f.accountInfoError
}
func (*fakeDownloadAppStore) Revoke() error { return nil }
func (f *fakeDownloadAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
f.lookupInputs = append(f.lookupInputs, input)
return f.lookupOutput, f.lookupError
}
func (*fakeDownloadAppStore) Search(input appstore.SearchInput) (appstore.SearchOutput, error) {
return appstore.SearchOutput{}, nil
}
func (*fakeDownloadAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
return appstore.OwnedAppsOutput{}, nil
}
func (f *fakeDownloadAppStore) Purchase(input appstore.PurchaseInput) error {
f.purchaseInputs = append(f.purchaseInputs, input)
if f.purchaseStorefront != "" {
f.account.StoreFront = f.purchaseStorefront
}
index := len(f.purchaseInputs) - 1
if index < len(f.purchaseErrors) && f.purchaseErrors[index] != nil {
return f.purchaseErrors[index]
}
return nil
}
func (f *fakeDownloadAppStore) Download(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
f.downloadInputs = append(f.downloadInputs, input)
index := len(f.downloadInputs) - 1
if index < len(f.downloadErrors) && f.downloadErrors[index] != nil {
return appstore.DownloadOutput{}, f.downloadErrors[index]
}
return appstore.DownloadOutput{DestinationPath: "app.pkg"}, nil
}
func (*fakeDownloadAppStore) ReplicateSinf(input appstore.ReplicateSinfInput) error { return nil }
func (*fakeDownloadAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
return appstore.ListVersionsOutput{}, nil
}
func (*fakeDownloadAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
return appstore.GetVersionMetadataOutput{}, nil
}
func (*fakeDownloadAppStore) Bag(input appstore.BagInput) (appstore.BagOutput, error) {
return appstore.BagOutput{}, nil
}
+14 -11
View File
@@ -2,7 +2,6 @@ package cmd
import (
"errors"
"fmt"
"time"
"github.com/avast/retry-go"
@@ -16,6 +15,7 @@ func getVersionMetadataCmd() *cobra.Command {
appID int64
bundleID string
externalVersionID string
platformValue string
)
cmd := &cobra.Command{
@@ -26,6 +26,11 @@ func getVersionMetadataCmd() *cobra.Command {
return errors.New("either the app ID or the bundle identifier must be specified")
}
platform, err := appstore.ParsePlatform(platformValue)
if err != nil {
return err
}
var lastErr error
var acc appstore.Account
@@ -38,15 +43,9 @@ func getVersionMetadataCmd() *cobra.Command {
acc = infoResult.Account
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
bagOutput, err := dependencies.AppStore.Bag(appstore.BagInput{})
if err != nil {
return fmt.Errorf("failed to get bag: %w", err)
}
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
Email: acc.Email,
Password: acc.Password,
Endpoint: bagOutput.AuthEndpoint,
})
if err != nil {
return err
@@ -57,7 +56,7 @@ func getVersionMetadataCmd() *cobra.Command {
app := appstore.App{ID: appID}
if bundleID != "" {
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID})
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID, Platform: platform})
if err != nil {
return err
}
@@ -66,9 +65,11 @@ func getVersionMetadataCmd() *cobra.Command {
}
out, err := dependencies.AppStore.GetVersionMetadata(appstore.GetVersionMetadataInput{
Context: cmd.Context(),
Account: acc,
App: app,
VersionID: externalVersionID,
Platform: platform,
})
if err != nil {
return err
@@ -96,9 +97,11 @@ func getVersionMetadataCmd() *cobra.Command {
},
}
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target iOS app (required)")
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (overrides the app ID)")
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target iOS app (required)")
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app (required)")
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target app (required)")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to retrieve metadata for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
_ = cmd.MarkFlagRequired("external-version-id")
+48
View File
@@ -0,0 +1,48 @@
package cmd
import (
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/majd/ipatool/v2/pkg/log"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Get Version Metadata command", func() {
DescribeTable("passes the platform and exact version to metadata lookup", func(args []string, platform appstore.Platform, lookup bool) {
store := &fakeVersionMetadataAppStore{}
previous := dependencies
DeferCleanup(func() { dependencies = previous })
dependencies.AppStore = store
dependencies.Logger = log.NewLogger(log.Args{})
cmd := getVersionMetadataCmd()
cmd.SetArgs(append(args, "--external-version-id", "876660716"))
Expect(cmd.Execute()).To(Succeed())
Expect(store.input.Platform).To(Equal(platform))
Expect(store.input.VersionID).To(Equal("876660716"))
Expect(store.input.App.ID).To(Equal(int64(42)))
Expect(store.lookupCalled).To(Equal(lookup))
if lookup {
Expect(store.lookupInput.Platform).To(Equal(platform))
}
},
Entry("Mac bundle", []string{"-b", "com.example.mac", "--platform", "macos"}, appstore.PlatformMacOS, true),
Entry("Mac ID alias", []string{"-i", "42", "--platform", "mac"}, appstore.PlatformMacOS, false),
Entry("default", []string{"-i", "42"}, appstore.Platform(""), false),
)
It("rejects unknown as a filter", func() {
cmd := getVersionMetadataCmd()
cmd.SetArgs([]string{"-i", "42", "--external-version-id", "123", "--platform", "unknown"})
Expect(cmd.Execute()).To(MatchError(`invalid platform "unknown"`))
})
})
type fakeVersionMetadataAppStore struct {
fakeListVersionsAppStore
input appstore.GetVersionMetadataInput
}
func (s *fakeVersionMetadataAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
s.input = input
return appstore.GetVersionMetadataOutput{}, nil
}
+12
View File
@@ -0,0 +1,12 @@
//go:build !ios
package cmd
import (
"github.com/byteness/keyring"
"github.com/majd/ipatool/v2/pkg/keychain"
)
func openKeyring(config keyring.Config) (keychain.Keyring, error) {
return keyring.Open(config) //nolint:wrapcheck
}
+48
View File
@@ -0,0 +1,48 @@
package cmd
import (
"fmt"
gokeychain "github.com/byteness/go-keychain"
"github.com/byteness/keyring"
"github.com/majd/ipatool/v2/pkg/keychain"
)
// iosKeyring fixes the update query in keyring v1.9.0, which includes attributes
// that SecItemUpdate rejects on iOS (kSecMatchLimit and kSecReturnAttributes).
type iosKeyring struct {
keyring.Keyring
service string
}
func openKeyring(config keyring.Config) (keychain.Keyring, error) {
ring, err := keyring.Open(config)
if err != nil {
return nil, fmt.Errorf("open iOS keyring: %w", err)
}
return &iosKeyring{Keyring: ring, service: config.ServiceName}, nil
}
func (k *iosKeyring) Set(item keyring.Item) error {
query := gokeychain.NewItem()
query.SetSecClass(gokeychain.SecClassGenericPassword)
query.SetService(k.service)
query.SetAccount(item.Key)
attributes := gokeychain.NewItem()
attributes.SetData(item.Data)
attributes.SetLabel(item.Label)
attributes.SetDescription(item.Description)
err := gokeychain.UpdateItem(query, attributes)
if err == gokeychain.ErrorItemNotFound {
return k.Keyring.Set(item) //nolint:wrapcheck
}
if err != nil {
return fmt.Errorf("update iOS keyring item: %w", err)
}
return nil
}
+27
View File
@@ -0,0 +1,27 @@
package cmd
import (
"fmt"
"time"
"github.com/byteness/keyring"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("iOS keyring", func() {
It("persists and updates credentials without invalid SecItemUpdate parameters", func() {
ring, err := openKeyring(keyring.Config{
AllowedBackends: []keyring.BackendType{keyring.KeychainBackend},
ServiceName: fmt.Sprintf("ipatool-test-%d", time.Now().UnixNano()),
})
Expect(err).NotTo(HaveOccurred())
DeferCleanup(func() { Expect(ring.Remove("account")).To(Succeed()) })
Expect(ring.Set(keyring.Item{Key: "account", Data: []byte("first"), Label: "ipatool"})).To(Succeed())
Expect(ring.Set(keyring.Item{Key: "account", Data: []byte("updated"), Label: "ipatool"})).To(Succeed())
item, err := ring.Get("account")
Expect(err).NotTo(HaveOccurred())
Expect(item.Data).To(Equal([]byte("updated")))
Expect(item.Label).To(Equal("ipatool"))
})
})
+15 -14
View File
@@ -2,7 +2,6 @@ package cmd
import (
"errors"
"fmt"
"time"
"github.com/avast/retry-go"
@@ -13,18 +12,24 @@ import (
// nolint:wrapcheck
func ListVersionsCmd() *cobra.Command {
var (
appID int64
bundleID string
appID int64
bundleID string
platformValue string
)
cmd := &cobra.Command{
Use: "list-versions",
Short: "List the available versions of an iOS app",
Short: "List the available versions of an App Store app",
RunE: func(cmd *cobra.Command, args []string) error {
if appID == 0 && bundleID == "" {
return errors.New("either the app ID or the bundle identifier must be specified")
}
platform, err := appstore.ParsePlatform(platformValue)
if err != nil {
return err
}
var lastErr error
var acc appstore.Account
@@ -37,15 +42,9 @@ func ListVersionsCmd() *cobra.Command {
acc = infoResult.Account
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
bagOutput, err := dependencies.AppStore.Bag(appstore.BagInput{})
if err != nil {
return fmt.Errorf("failed to get bag: %w", err)
}
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
Email: acc.Email,
Password: acc.Password,
Endpoint: bagOutput.AuthEndpoint,
})
if err != nil {
return err
@@ -56,7 +55,7 @@ func ListVersionsCmd() *cobra.Command {
app := appstore.App{ID: appID}
if bundleID != "" {
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID})
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID, Platform: platform})
if err != nil {
return err
}
@@ -64,7 +63,7 @@ func ListVersionsCmd() *cobra.Command {
app = lookupResult.App
}
out, err := dependencies.AppStore.ListVersions(appstore.ListVersionsInput{Account: acc, App: app})
out, err := dependencies.AppStore.ListVersions(appstore.ListVersionsInput{Context: cmd.Context(), Account: acc, App: app, Platform: platform})
if err != nil {
return err
}
@@ -90,8 +89,10 @@ func ListVersionsCmd() *cobra.Command {
},
}
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target iOS app (required)")
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (overrides the app ID)")
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app (required)")
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to list versions for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
return cmd
}
+60
View File
@@ -0,0 +1,60 @@
package cmd
import (
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/majd/ipatool/v2/pkg/log"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("List Versions command", func() {
DescribeTable("passes the selected platform to lookup and version listing", func(args []string, expected appstore.Platform, lookup bool) {
store := &fakeListVersionsAppStore{}
previous := dependencies
DeferCleanup(func() { dependencies = previous })
dependencies.AppStore = store
dependencies.Logger = log.NewLogger(log.Args{})
cmd := ListVersionsCmd()
cmd.SetArgs(args)
Expect(cmd.Execute()).To(Succeed())
Expect(store.input.Platform).To(Equal(expected))
Expect(store.input.App.ID).To(Equal(int64(42)))
Expect(store.lookupCalled).To(Equal(lookup))
if lookup {
Expect(store.lookupInput.Platform).To(Equal(expected))
}
},
Entry("Mac bundle ID", []string{"-b", "com.example.mac", "--platform", "macos"}, appstore.PlatformMacOS, true),
Entry("Mac app ID alias", []string{"-i", "42", "--platform", "mac"}, appstore.PlatformMacOS, false),
Entry("default platform", []string{"-i", "42"}, appstore.Platform(""), false),
Entry("iOS alias", []string{"-i", "42", "--platform", "ios"}, appstore.PlatformIPhone, false),
)
It("rejects unknown as a platform before accessing the account", func() {
cmd := ListVersionsCmd()
cmd.SetArgs([]string{"-i", "42", "--platform", "unknown"})
Expect(cmd.Execute()).To(MatchError(`invalid platform "unknown"`))
})
})
type fakeListVersionsAppStore struct {
appstore.AppStore
input appstore.ListVersionsInput
lookupInput appstore.LookupInput
lookupCalled bool
}
func (*fakeListVersionsAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
return appstore.AccountInfoOutput{}, nil
}
func (s *fakeListVersionsAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
s.lookupCalled = true
s.lookupInput = input
return appstore.LookupOutput{App: appstore.App{ID: 42, BundleID: input.BundleID}}, nil
}
func (s *fakeListVersionsAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
s.input = input
return appstore.ListVersionsOutput{ExternalVersionIdentifiers: []string{"123"}}, nil
}
+87
View File
@@ -0,0 +1,87 @@
package cmd
import (
"context"
"fmt"
"os"
"os/signal"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/spf13/cobra"
)
func mcpCmd() *cobra.Command {
return &cobra.Command{
Use: "mcp",
Short: "Serve App Store tools over MCP using stdio",
Long: "Serve App Store tools over the Model Context Protocol using stdio.\n" +
"Authenticate with 'ipatool auth login' before using the tools.\n" +
"Runs non-interactively; authentication tools are not exposed.",
Args: cobra.NoArgs,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cmd.SetContext(context.WithValue(cmd.Context(), interactiveKey, false))
initWithCommand(cmd)
},
RunE: func(cmd *cobra.Command, args []string) error {
ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt)
defer stop()
server := newMCPServer(dependencies.AppStore)
if err := server.Run(ctx, &mcp.StdioTransport{}); err != nil {
return fmt.Errorf("MCP server failed: %w", err)
}
return nil
},
}
}
type mcpTools struct {
store appstore.AppStore
gate chan struct{}
}
func newMCPServer(store appstore.AppStore) *mcp.Server {
server := mcp.NewServer(&mcp.Implementation{Name: "ipatool", Version: version}, &mcp.ServerOptions{
Instructions: "Use the existing ipatool account. If authentication is required, ask the user to run ipatool auth login outside MCP. Purchases support free apps only.",
})
tools := &mcpTools{store: store, gate: make(chan struct{}, 1)}
addMCPTool(server, tools, "search_apps", "Search for apps on the App Store.", true, tools.search)
addMCPTool(server, tools, "download_app", "Download an app package to the local filesystem. Optionally acquire a free license if purchase is true.", false, tools.download)
addMCPTool(server, tools, "list_app_versions", "List available external version identifiers for an app.", true, tools.listVersions)
addMCPTool(server, tools, "get_version_metadata", "Retrieve the display version and release date for a specific external version identifier of an app.", true, tools.getVersionMetadata)
addMCPTool(server, tools, "list_purchases", "List apps owned by the authenticated account, with pagination.", true, tools.listPurchases)
addMCPTool(server, tools, "purchase_app", "Obtain a license for a free app. Paid apps are not supported.", false, tools.purchase)
return server
}
func addMCPTool[In, Out any](server *mcp.Server, tools *mcpTools, name, description string, readOnly bool, handler func(context.Context, In) (Out, error)) {
mcp.AddTool(server, &mcp.Tool{
Name: name,
Description: description,
Annotations: &mcp.ToolAnnotations{ReadOnlyHint: readOnly},
}, func(ctx context.Context, _ *mcp.CallToolRequest, input In) (*mcp.CallToolResult, Out, error) {
var zero Out
// The App Store client shares account state and caches across calls.
select {
case tools.gate <- struct{}{}:
defer func() { <-tools.gate }()
case <-ctx.Done():
return nil, zero, fmt.Errorf("tool call canceled: %w", ctx.Err())
}
if err := ctx.Err(); err != nil {
return nil, zero, fmt.Errorf("tool call canceled: %w", err)
}
output, err := handler(ctx, input)
if err != nil {
return nil, zero, fmt.Errorf("%s failed: %w", name, err)
}
return nil, output, nil
})
}
+93
View File
@@ -0,0 +1,93 @@
package cmd
import (
"time"
"github.com/majd/ipatool/v2/pkg/appstore"
)
// mcpApp keeps every metadata field in the MCP response, including zero values.
// The App Store's JSON representation is also used by other callers, so its
// omission rules are left unchanged.
type mcpApp struct {
ID int64 `json:"trackId"`
BundleID string `json:"bundleId"`
Name string `json:"trackName"`
Version string `json:"version"`
Price float64 `json:"price"`
PurchaseDate *time.Time `json:"purchaseDate"`
Platforms []appstore.Platform `json:"platforms"`
}
func newMCPApp(app appstore.App) mcpApp {
output := mcpApp{
ID: app.ID, BundleID: app.BundleID, Name: app.Name, Version: app.Version, Price: app.Price,
Platforms: append([]appstore.Platform{}, app.Platforms...),
}
if !app.PurchaseDate.IsZero() {
output.PurchaseDate = &app.PurchaseDate
}
return output
}
// completeApp supplements sparse metadata without making catalog availability a
// prerequisite for operating on owned or delisted apps.
func (t *mcpTools) completeApp(acc appstore.Account, app appstore.App, platform appstore.Platform) appstore.App {
knownPlatforms := len(app.Platforms) > 0 && app.Platforms[0] != appstore.PlatformUnknown
if app.ID <= 0 || (app.BundleID != "" && app.Name != "" && app.Version != "" && knownPlatforms) {
return app
}
// Purchase history can contain several platforms when no filter was supplied.
// Use an app's known platform for its catalog lookup in that case.
if platform == "" && len(app.Platforms) > 0 && app.Platforms[0] != appstore.PlatformUnknown {
platform = app.Platforms[0]
}
out, err := t.store.Lookup(appstore.LookupInput{Account: acc, AppID: app.ID, Platform: platform})
if err != nil || out.App.ID != app.ID {
return app
}
if app.BundleID == "" {
app.BundleID = out.App.BundleID
}
if app.Name == "" {
app.Name = out.App.Name
}
if app.Version == "" {
app.Version = out.App.Version
}
if len(out.App.Platforms) > 0 && (len(app.Platforms) == 0 || (len(app.Platforms) == 1 && app.Platforms[0] == appstore.PlatformUnknown)) {
app.Platforms = out.App.Platforms
}
if app.Price == 0 {
app.Price = out.App.Price
}
return app
}
func (t *mcpTools) appResults(acc appstore.Account, apps []appstore.App, platform appstore.Platform) []mcpApp {
results := make([]mcpApp, 0, len(apps))
for _, app := range apps {
results = append(results, newMCPApp(t.completeApp(acc, app, platform)))
}
return results
}
type mcpAppParameters struct {
AppID int64 `json:"app_id"`
BundleIdentifier string `json:"bundle_identifier"`
Platform appstore.Platform `json:"platform"`
}
func appParameters(app appstore.App, platform appstore.Platform) mcpAppParameters {
return mcpAppParameters{AppID: app.ID, BundleIdentifier: app.BundleID, Platform: platform}
}
+32
View File
@@ -0,0 +1,32 @@
package cmd
import (
"errors"
"github.com/majd/ipatool/v2/pkg/appstore"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("MCP app metadata", func() {
DescribeTable("preserves source data when catalog metadata cannot be used", func(catalog appstore.App, lookupErr error) {
original := appstore.App{ID: 123, Name: "Original name", Price: 2.99, Platforms: []appstore.Platform{appstore.PlatformUnknown}}
store := &fakeMCPAppStore{lookup: func(appstore.LookupInput) (appstore.LookupOutput, error) {
return appstore.LookupOutput{App: catalog}, lookupErr
}}
tools := &mcpTools{store: store}
Expect(tools.completeApp(appstore.Account{}, original, "")).To(Equal(original))
},
Entry("delisted app", appstore.App{}, appstore.ErrAppNotFound),
Entry("network failure", appstore.App{}, errors.New("network failure")),
Entry("wrong app ID", appstore.App{ID: 999, BundleID: "wrong.bundle"}, nil),
Entry("missing catalog values", appstore.App{ID: 123}, nil),
)
It("avoids catalog lookups when app metadata is already complete", func() {
tools := &mcpTools{store: &fakeMCPAppStore{}}
app := appstore.App{ID: 123, BundleID: "com.example.app", Name: "Example", Version: "1.0", Platforms: []appstore.Platform{appstore.PlatformIPhone}}
Expect(tools.completeApp(appstore.Account{}, app, "")).To(Equal(app))
})
})
+670
View File
@@ -0,0 +1,670 @@
package cmd
import (
"context"
"encoding/json"
"errors"
"time"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/modelcontextprotocol/go-sdk/mcp"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("MCP server", func() {
var (
ctx context.Context
store *fakeMCPAppStore
session *mcp.ClientSession
account appstore.Account
app appstore.App
)
BeforeEach(func() {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
DeferCleanup(cancel)
account = appstore.Account{Email: "private-email", Password: "private-password", PasswordToken: "private-token"}
app = appstore.App{ID: 123, BundleID: "com.example.app", Name: "Example"}
store = &fakeMCPAppStore{}
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
return appstore.AccountInfoOutput{Account: account}, nil
}
store.lookup = func(appstore.LookupInput) (appstore.LookupOutput, error) {
return appstore.LookupOutput{}, appstore.ErrAppNotFound
}
clientTransport, serverTransport := mcp.NewInMemoryTransports()
serverSession, err := newMCPServer(store).Connect(ctx, serverTransport, nil)
Expect(err).NotTo(HaveOccurred())
DeferCleanup(func() { Expect(serverSession.Close()).To(Succeed()) })
session, err = mcp.NewClient(&mcp.Implementation{Name: "test", Version: "1"}, nil).Connect(ctx, clientTransport, nil)
Expect(err).NotTo(HaveOccurred())
DeferCleanup(func() { Expect(session.Close()).To(Succeed()) })
})
call := func(name string, args map[string]any) *mcp.CallToolResult {
result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: name, Arguments: args})
Expect(err).NotTo(HaveOccurred())
return result
}
It("registers the mcp subcommand", func() {
command, _, err := rootCmd().Find([]string{"mcp"})
Expect(err).NotTo(HaveOccurred())
Expect(command.Name()).To(Equal("mcp"))
Expect(command.Args(command, []string{"unexpected"})).NotTo(Succeed())
})
It("advertises exactly six tools and their schemas without auth functions", func() {
result, err := session.ListTools(ctx, nil)
Expect(err).NotTo(HaveOccurred())
names := make([]string, 0, len(result.Tools))
for _, tool := range result.Tools {
names = append(names, tool.Name)
Expect(tool.InputSchema).NotTo(BeNil())
Expect(tool.OutputSchema).NotTo(BeNil())
Expect(tool.Annotations.ReadOnlyHint).To(Equal(tool.Name != "download_app" && tool.Name != "purchase_app"))
}
Expect(names).To(ConsistOf("search_apps", "download_app", "list_app_versions", "get_version_metadata", "list_purchases", "purchase_app"))
})
It("searches with CLI defaults and returns structured app data without credentials", func() {
var input appstore.SearchInput
store.search = func(in appstore.SearchInput) (appstore.SearchOutput, error) {
input = in
return appstore.SearchOutput{Count: 1, Results: []appstore.App{app}}, nil
}
result := call("search_apps", map[string]any{"term": "example"})
Expect(result.IsError).To(BeFalse())
Expect(input).To(Equal(appstore.SearchInput{Account: account, Term: "example", Limit: 5}))
data, err := json.Marshal(result.StructuredContent)
Expect(err).NotTo(HaveOccurred())
Expect(string(data)).To(ContainSubstring("com.example.app"))
Expect(string(data)).NotTo(ContainSubstring("private-"))
Expect(result.Content).To(HaveLen(1))
Expect(result.StructuredContent).To(HaveKeyWithValue("term", "example"))
Expect(result.StructuredContent).To(HaveKeyWithValue("limit", float64(5)))
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", ""))
})
DescribeTable("passes search platform aliases and limits to the App Store", func(value string, platform appstore.Platform) {
var input appstore.SearchInput
store.search = func(in appstore.SearchInput) (appstore.SearchOutput, error) {
input = in
return appstore.SearchOutput{}, nil
}
Expect(call("search_apps", map[string]any{"term": "example", "platform": value, "limit": 7}).IsError).To(BeFalse())
Expect(input.Platform).To(Equal(platform))
Expect(input.Limit).To(Equal(int64(7)))
},
Entry("tvOS", "tvos", appstore.PlatformAppleTV),
Entry("watchOS", "watch", appstore.PlatformWatchOS),
)
DescribeTable("rejects invalid inputs before accessing the account", func(name string, args map[string]any) {
accountCalls := 0
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
accountCalls++
return appstore.AccountInfoOutput{}, errors.New("unexpected account access")
}
result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: name, Arguments: args})
Expect(err != nil || (result != nil && result.IsError)).To(BeTrue())
Expect(accountCalls).To(BeZero())
},
Entry("missing search term", "search_apps", map[string]any{}),
Entry("blank search term", "search_apps", map[string]any{"term": " "}),
Entry("invalid search limit", "search_apps", map[string]any{"term": "app", "limit": 0}),
Entry("wrong argument type", "search_apps", map[string]any{"term": 123}),
Entry("credentials are not arguments", "search_apps", map[string]any{"term": "app", "password": "secret"}),
Entry("invalid platform", "search_apps", map[string]any{"term": "app", "platform": "unknown"}),
Entry("missing download app", "download_app", map[string]any{}),
Entry("negative app ID", "purchase_app", map[string]any{"app_id": -1}),
Entry("missing versions app", "list_app_versions", map[string]any{}),
Entry("missing metadata app", "get_version_metadata", map[string]any{"external_version_id": "200"}),
Entry("missing metadata version", "get_version_metadata", map[string]any{"app_id": 123}),
Entry("empty metadata version", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": ""}),
Entry("blank metadata version", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": " "}),
Entry("invalid metadata version type", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": 200}),
Entry("invalid metadata platform", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200", "platform": "unknown"}),
Entry("invalid page", "list_purchases", map[string]any{"page": 0}),
Entry("invalid page size", "list_purchases", map[string]any{"max_results": 101}),
)
It("returns actionable account errors and keeps serving requests", func() {
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
return appstore.AccountInfoOutput{}, errors.New("account not found")
}
result := call("list_purchases", map[string]any{})
Expect(result.IsError).To(BeTrue())
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring("ipatool auth login"))
_, err := session.ListTools(ctx, nil)
Expect(err).NotTo(HaveOccurred())
})
DescribeTable("lists purchases with pagination", func(args map[string]any, page, limit int, platform appstore.Platform) {
var input appstore.OwnedAppsInput
store.ownedApps = func(in appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
input = in
return appstore.OwnedAppsOutput{Count: 1, TotalCount: 11, Page: in.Page, Results: []appstore.App{app}}, nil
}
result := call("list_purchases", args)
Expect(result.IsError).To(BeFalse())
Expect(input).To(Equal(appstore.OwnedAppsInput{Account: account, Page: page, Limit: limit, Platform: platform}))
Expect(result.StructuredContent).To(HaveKeyWithValue("totalCount", float64(11)))
Expect(result.StructuredContent).To(HaveKeyWithValue("page", float64(page)))
Expect(result.StructuredContent).To(HaveKeyWithValue("max_results", float64(limit)))
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", string(platform)))
},
Entry("defaults", map[string]any{}, 1, 10, appstore.Platform("")),
Entry("explicit values", map[string]any{"page": 2, "max_results": 5, "platform": "macos"}, 2, 5, appstore.PlatformMacOS),
)
It("resolves bundle identifiers and lists versions", func() {
var lookup appstore.LookupInput
var input appstore.ListVersionsInput
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
lookup = in
return appstore.LookupOutput{App: app}, nil
}
store.listVersions = func(in appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
input = in
return appstore.ListVersionsOutput{ExternalVersionIdentifiers: []string{"100", "200"}, LatestExternalVersionID: "200"}, nil
}
result := call("list_app_versions", map[string]any{"app_id": 999, "bundle_identifier": app.BundleID, "platform": "ipados"})
Expect(result.IsError).To(BeFalse())
Expect(lookup).To(Equal(appstore.LookupInput{Account: account, BundleID: app.BundleID, Platform: appstore.PlatformIPad}))
Expect(input.App).To(Equal(app))
Expect(input.Context).NotTo(BeNil())
Expect(result.StructuredContent).To(HaveKeyWithValue("externalVersionIdentifiers", []any{"100", "200"}))
Expect(result.StructuredContent).To(HaveKeyWithValue("app_id", float64(app.ID)))
Expect(result.StructuredContent).To(HaveKeyWithValue("bundle_identifier", app.BundleID))
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", "ipad"))
})
It("resolves a bundle identifier and returns metadata for the requested version", func() {
var lookup appstore.LookupInput
var input appstore.GetVersionMetadataInput
app.Version = "2.0"
releasedAt := time.Date(2025, time.January, 2, 3, 4, 5, 0, time.UTC)
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
lookup = in
return appstore.LookupOutput{App: app}, nil
}
store.getVersionMetadata = func(in appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
input = in
return appstore.GetVersionMetadataOutput{DisplayVersion: "1.2.3", ReleaseDate: releasedAt}, nil
}
result := call("get_version_metadata", map[string]any{"app_id": 999, "bundle_identifier": app.BundleID, "external_version_id": "200", "platform": "ipados"})
Expect(result.IsError).To(BeFalse())
Expect(lookup).To(Equal(appstore.LookupInput{Account: account, BundleID: app.BundleID, Platform: appstore.PlatformIPad}))
Expect(input.Context).NotTo(BeNil())
Expect(input.Account).To(Equal(account))
Expect(input.App).To(Equal(app))
Expect(input.VersionID).To(Equal("200"))
Expect(input.Platform).To(Equal(appstore.PlatformIPad))
Expect(result.StructuredContent).To(HaveKeyWithValue("app_id", float64(app.ID)))
Expect(result.StructuredContent).To(HaveKeyWithValue("bundle_identifier", app.BundleID))
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", "ipad"))
Expect(result.StructuredContent).To(HaveKeyWithValue("external_version_id", "200"))
Expect(result.StructuredContent).To(HaveKeyWithValue("displayVersion", "1.2.3"))
Expect(result.StructuredContent).To(HaveKeyWithValue("releaseDate", releasedAt.Format(time.RFC3339)))
Expect(result.StructuredContent).To(HaveKeyWithValue("success", true))
Expect(result.StructuredContent.(map[string]any)["app"]).To(HaveKeyWithValue("version", "2.0"))
data, err := json.Marshal(result.StructuredContent)
Expect(err).NotTo(HaveOccurred())
Expect(string(data)).NotTo(ContainSubstring("private-"))
Expect(result.Content[0].(*mcp.TextContent).Text).To(MatchJSON(string(data)))
})
DescribeTable("retrieves version metadata by app ID when catalog metadata is unavailable", func(platform string, expected appstore.Platform) {
var input appstore.GetVersionMetadataInput
store.getVersionMetadata = func(in appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
input = in
return appstore.GetVersionMetadataOutput{DisplayVersion: "1.2.3"}, nil
}
result := call("get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200", "platform": platform})
Expect(result.IsError).To(BeFalse())
Expect(input.App).To(Equal(appstore.App{ID: 123}))
Expect(input.VersionID).To(Equal("200"))
Expect(input.Platform).To(Equal(expected))
},
Entry("CLI default", "", appstore.Platform("")),
Entry("iOS alias", "ios", appstore.PlatformIPhone),
Entry("macOS", "macos", appstore.PlatformMacOS),
)
It("returns bundle lookup failures as metadata tool errors", func() {
result := call("get_version_metadata", map[string]any{"bundle_identifier": app.BundleID, "external_version_id": "200"})
Expect(result.IsError).To(BeTrue())
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring(appstore.ErrAppNotFound.Error()))
})
DescribeTable("returns metadata failures as tool errors without acquiring a license", func(metadataErr error) {
store.getVersionMetadata = func(appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
return appstore.GetVersionMetadataOutput{}, appstore.NewErrorWithMetadata(metadataErr, account)
}
result := call("get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200"})
Expect(result.IsError).To(BeTrue())
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring(metadataErr.Error()))
data, err := json.Marshal(result)
Expect(err).NotTo(HaveOccurred())
Expect(string(data)).NotTo(ContainSubstring("private-"))
},
Entry("missing license", appstore.ErrLicenseRequired),
Entry("metadata unavailable", errors.New("metadata unavailable")),
)
It("refreshes an expired session when retrieving version metadata", func() {
var login appstore.LoginInput
var accounts []appstore.Account
refreshed := appstore.Account{PasswordToken: "refreshed-private-token"}
store.getVersionMetadata = func(in appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
accounts = append(accounts, in.Account)
if len(accounts) == 1 {
return appstore.GetVersionMetadataOutput{}, appstore.ErrPasswordTokenExpired
}
return appstore.GetVersionMetadataOutput{DisplayVersion: "1.2.3"}, nil
}
store.login = func(in appstore.LoginInput) (appstore.LoginOutput, error) {
login = in
return appstore.LoginOutput{Account: refreshed}, nil
}
result := call("get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200"})
Expect(result.IsError).To(BeFalse())
Expect(login).To(Equal(appstore.LoginInput{Email: account.Email, Password: account.Password}))
Expect(accounts).To(Equal([]appstore.Account{account, refreshed}))
Expect(result.StructuredContent).To(HaveKeyWithValue("displayVersion", "1.2.3"))
})
DescribeTable("purchases a free license", func(purchaseErr error, alreadyOwned bool) {
var input appstore.PurchaseInput
store.purchase = func(in appstore.PurchaseInput) error {
input = in
return purchaseErr
}
result := call("purchase_app", map[string]any{"app_id": 123, "platform": "visionos"})
Expect(result.IsError).To(BeFalse())
Expect(input).To(Equal(appstore.PurchaseInput{Account: account, App: appstore.App{ID: 123}, Platform: appstore.PlatformVisionOS}))
Expect(result.StructuredContent).To(HaveKeyWithValue("alreadyOwned", alreadyOwned))
},
Entry("new license", nil, false),
Entry("existing license", appstore.ErrLicenseAlreadyExists, true),
)
It("downloads a selected version and finalizes the package without a progress bar", func() {
var input appstore.DownloadInput
var sinfInput appstore.ReplicateSinfInput
store.download = func(in appstore.DownloadInput) (appstore.DownloadOutput, error) {
input = in
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
}
store.replicateSinf = func(in appstore.ReplicateSinfInput) error {
sinfInput = in
return nil
}
result := call("download_app", map[string]any{"app_id": 123, "output": "/tmp/example.ipa", "external_version_id": "200", "platform": "ios"})
Expect(result.IsError).To(BeFalse())
Expect(input.App.ID).To(Equal(int64(123)))
Expect(input.OutputPath).To(Equal("/tmp/example.ipa"))
Expect(input.ExternalVersionID).To(Equal("200"))
Expect(input.Platform).To(Equal(appstore.PlatformIPhone))
Expect(input.Context).NotTo(BeNil())
Expect(input.Progress).To(BeNil())
Expect(sinfInput.PackagePath).To(Equal(input.OutputPath))
Expect(result.StructuredContent).To(HaveKeyWithValue("output", input.OutputPath))
Expect(result.StructuredContent).To(HaveKeyWithValue("external_version_id", "200"))
Expect(result.StructuredContent).To(HaveKeyWithValue("purchase", false))
})
It("downloads delisted macOS apps by ID without attempting IPA finalization", func() {
var input appstore.DownloadInput
store.lookup = func(appstore.LookupInput) (appstore.LookupOutput, error) {
return appstore.LookupOutput{}, appstore.ErrAppNotFound
}
store.download = func(in appstore.DownloadInput) (appstore.DownloadOutput, error) {
input = in
return appstore.DownloadOutput{DestinationPath: "/tmp/example.pkg"}, nil
}
result := call("download_app", map[string]any{"app_id": 123, "bundle_identifier": app.BundleID, "platform": "macos"})
Expect(result.IsError).To(BeFalse())
Expect(input.App.ID).To(Equal(int64(123)))
})
DescribeTable("only acquires a license during download when requested", func(purchase bool) {
downloads, purchases := 0, 0
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
downloads++
if downloads == 1 {
return appstore.DownloadOutput{}, appstore.ErrLicenseRequired
}
return appstore.DownloadOutput{DestinationPath: "/tmp/example.pkg"}, nil
}
store.purchase = func(appstore.PurchaseInput) error {
purchases++
return nil
}
result := call("download_app", map[string]any{"app_id": 123, "platform": "macos", "purchase": purchase})
Expect(result.IsError).To(Equal(!purchase))
if purchase {
Expect(purchases).To(Equal(1))
Expect(downloads).To(Equal(2))
Expect(result.StructuredContent).To(HaveKeyWithValue("purchased", true))
} else {
Expect(purchases).To(BeZero())
Expect(downloads).To(Equal(1))
}
}, Entry("explicit opt in", true), Entry("no opt in", false))
DescribeTable("uses a purchase-corrected storefront for MCP downloads", func(refresh bool) {
account.DirectoryServicesID = "123456"
account.StoreFront = "143441-1,34"
var downloads []appstore.Account
purchases := 0
expectedPurchases := 1
if refresh {
expectedPurchases = 2
}
store.download = func(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
downloads = append(downloads, input.Account)
if purchases < expectedPurchases {
return appstore.DownloadOutput{}, appstore.ErrLicenseRequired
}
return appstore.DownloadOutput{DestinationPath: "/tmp/example.pkg"}, nil
}
store.purchase = func(input appstore.PurchaseInput) error {
purchases++
account.StoreFront = "143462-1,34"
if refresh && purchases == 1 {
return appstore.ErrPasswordTokenExpired
}
return nil
}
store.login = func(appstore.LoginInput) (appstore.LoginOutput, error) {
account.PasswordToken = "new-token"
return appstore.LoginOutput{Account: account}, nil
}
result := call("download_app", map[string]any{"app_id": 123, "platform": "macos", "purchase": true})
Expect(result.IsError).To(BeFalse())
Expect(purchases).To(Equal(expectedPurchases))
Expect(result.StructuredContent).To(HaveKeyWithValue("purchased", true))
Expect(downloads[0].StoreFront).To(Equal("143441-1,34"))
Expect(downloads[len(downloads)-1].StoreFront).To(Equal("143462-1,34"))
if refresh {
Expect(downloads[len(downloads)-1].PasswordToken).To(Equal("new-token"))
}
}, Entry("immediate success", false), Entry("after token refresh", true))
DescribeTable("propagates errors after purchasing during an MCP download", func(accountReadFails bool) {
failure := errors.New("fixture post-purchase failure")
downloads := 0
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
downloads++
if downloads == 1 {
return appstore.DownloadOutput{}, appstore.ErrLicenseRequired
}
return appstore.DownloadOutput{}, failure
}
store.purchase = func(appstore.PurchaseInput) error {
if accountReadFails {
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
return appstore.AccountInfoOutput{}, failure
}
}
return nil
}
result := call("download_app", map[string]any{"app_id": 123, "platform": "macos", "purchase": true})
Expect(result.IsError).To(BeTrue())
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring(failure.Error()))
}, Entry("reloading the saved account", true), Entry("retrying the download", false))
It("refreshes an expired session using saved credentials", func() {
var login appstore.LoginInput
var accounts []appstore.Account
refreshed := appstore.Account{PasswordToken: "refreshed-private-token"}
store.purchase = func(in appstore.PurchaseInput) error {
accounts = append(accounts, in.Account)
if len(accounts) == 1 {
return appstore.ErrPasswordTokenExpired
}
return nil
}
store.login = func(in appstore.LoginInput) (appstore.LoginOutput, error) {
login = in
return appstore.LoginOutput{Account: refreshed}, nil
}
Expect(call("purchase_app", map[string]any{"app_id": 123}).IsError).To(BeFalse())
Expect(login).To(Equal(appstore.LoginInput{Email: account.Email, Password: account.Password}))
Expect(accounts).To(Equal([]appstore.Account{account, refreshed}))
})
It("reports two-factor requirements as tool errors without requesting credentials", func() {
store.purchase = func(appstore.PurchaseInput) error {
return appstore.ErrPasswordTokenExpired
}
store.login = func(appstore.LoginInput) (appstore.LoginOutput, error) {
return appstore.LoginOutput{}, appstore.ErrAuthCodeRequired
}
result := call("purchase_app", map[string]any{"app_id": 123})
Expect(result.IsError).To(BeTrue())
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring("ipatool auth login"))
})
It("does not expose App Store error metadata", func() {
store.search = func(appstore.SearchInput) (appstore.SearchOutput, error) {
return appstore.SearchOutput{}, appstore.NewErrorWithMetadata(errors.New("request failed"), account)
}
result := call("search_apps", map[string]any{"term": "example"})
Expect(result.IsError).To(BeTrue())
data, err := json.Marshal(result)
Expect(err).NotTo(HaveOccurred())
Expect(string(data)).To(ContainSubstring("request failed"))
Expect(string(data)).NotTo(ContainSubstring("private-"))
})
It("reports package finalization failures as tool errors", func() {
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
}
store.replicateSinf = func(appstore.ReplicateSinfInput) error {
return errors.New("finalization failed")
}
result := call("download_app", map[string]any{"app_id": 123})
Expect(result.IsError).To(BeTrue())
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring("finalization failed"))
})
DescribeTable("returns every parameter and app field even when metadata is unavailable", func(name string, args map[string]any, expectedKeys []string) {
partial := appstore.App{ID: 123}
store.search = func(appstore.SearchInput) (appstore.SearchOutput, error) {
return appstore.SearchOutput{Count: 1, Results: []appstore.App{partial}}, nil
}
store.ownedApps = func(appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
return appstore.OwnedAppsOutput{Count: 1, TotalCount: 1, Page: 1, Results: []appstore.App{partial}}, nil
}
store.listVersions = func(appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
return appstore.ListVersionsOutput{ExternalVersionIdentifiers: []string{"200"}}, nil
}
store.getVersionMetadata = func(appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
return appstore.GetVersionMetadataOutput{}, nil
}
store.purchase = func(appstore.PurchaseInput) error { return nil }
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
}
store.replicateSinf = func(appstore.ReplicateSinfInput) error { return nil }
result := call(name, args)
Expect(result.IsError).To(BeFalse())
output := result.StructuredContent.(map[string]any)
for _, key := range expectedKeys {
Expect(output).To(HaveKey(key))
}
metadata := output["app"]
if metadata == nil {
metadata = output["apps"].([]any)[0]
}
Expect(metadata).To(Equal(map[string]any{
"trackId": float64(123), "bundleId": "", "trackName": "", "version": "",
"price": float64(0), "purchaseDate": nil, "platforms": []any{},
}))
textJSON, err := json.Marshal(result.StructuredContent)
Expect(err).NotTo(HaveOccurred())
Expect(result.Content[0].(*mcp.TextContent).Text).To(MatchJSON(string(textJSON)))
},
Entry("search", "search_apps", map[string]any{"term": "example"}, []string{"term", "limit", "platform", "count", "apps"}),
Entry("purchases", "list_purchases", map[string]any{}, []string{"page", "max_results", "platform", "count", "totalCount", "apps"}),
Entry("versions", "list_app_versions", map[string]any{"app_id": 123}, []string{"app_id", "bundle_identifier", "platform", "bundleID", "app", "externalVersionIdentifiers", "latestExternalVersionID", "success"}),
Entry("version metadata", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200"}, []string{"app_id", "bundle_identifier", "platform", "app", "external_version_id", "displayVersion", "releaseDate", "success"}),
Entry("purchase", "purchase_app", map[string]any{"app_id": 123}, []string{"app_id", "bundle_identifier", "platform", "app", "alreadyOwned", "success"}),
Entry("download", "download_app", map[string]any{"app_id": 123}, []string{"app_id", "bundle_identifier", "platform", "app", "output", "external_version_id", "purchase", "purchased", "success"}),
)
DescribeTable("fills missing bundle identifiers in app lists without losing purchase metadata", func(name string, args map[string]any) {
purchasedAt := time.Date(2025, time.January, 2, 3, 4, 5, 0, time.UTC)
partial := appstore.App{ID: 123, Name: "Original name", PurchaseDate: purchasedAt, Platforms: []appstore.Platform{appstore.PlatformMacOS}}
var lookup appstore.LookupInput
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
lookup = in
return appstore.LookupOutput{App: appstore.App{ID: 123, BundleID: app.BundleID, Name: "Catalog name", Version: "2.0", Price: 4.99}}, nil
}
store.search = func(appstore.SearchInput) (appstore.SearchOutput, error) {
return appstore.SearchOutput{Count: 1, Results: []appstore.App{partial}}, nil
}
store.ownedApps = func(appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
return appstore.OwnedAppsOutput{Count: 1, TotalCount: 1, Page: 1, Results: []appstore.App{partial}}, nil
}
result := call(name, args)
Expect(result.IsError).To(BeFalse())
Expect(lookup).To(Equal(appstore.LookupInput{Account: account, AppID: 123, Platform: appstore.PlatformMacOS}))
metadata := result.StructuredContent.(map[string]any)["apps"].([]any)[0]
Expect(metadata).To(Equal(map[string]any{
"trackId": float64(123), "bundleId": app.BundleID, "trackName": "Original name", "version": "2.0",
"price": 4.99, "purchaseDate": purchasedAt.Format(time.RFC3339), "platforms": []any{"macos"},
}))
},
Entry("search", "search_apps", map[string]any{"term": "example"}),
Entry("purchases", "list_purchases", map[string]any{}),
)
DescribeTable("resolves bundle identifiers for numeric app IDs", func(name string) {
var lookup appstore.LookupInput
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
lookup = in
return appstore.LookupOutput{App: app}, nil
}
store.purchase = func(appstore.PurchaseInput) error { return nil }
store.listVersions = func(appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
return appstore.ListVersionsOutput{}, nil
}
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
}
store.replicateSinf = func(appstore.ReplicateSinfInput) error { return nil }
result := call(name, map[string]any{"app_id": 123})
Expect(result.IsError).To(BeFalse())
Expect(lookup.AppID).To(Equal(int64(123)))
Expect(result.StructuredContent).To(HaveKeyWithValue("app_id", float64(123)))
Expect(result.StructuredContent).To(HaveKeyWithValue("bundle_identifier", app.BundleID))
Expect(result.StructuredContent.(map[string]any)["app"]).To(HaveKeyWithValue("bundleId", app.BundleID))
if name == "list_app_versions" {
Expect(result.StructuredContent).To(HaveKeyWithValue("bundleID", app.BundleID))
Expect(result.StructuredContent).To(HaveKeyWithValue("externalVersionIdentifiers", []any{}))
}
}, Entry("purchase", "purchase_app"), Entry("download", "download_app"), Entry("versions", "list_app_versions"))
})
type fakeMCPAppStore struct {
appstore.AppStore
accountInfo func() (appstore.AccountInfoOutput, error)
search func(appstore.SearchInput) (appstore.SearchOutput, error)
lookup func(appstore.LookupInput) (appstore.LookupOutput, error)
ownedApps func(appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error)
listVersions func(appstore.ListVersionsInput) (appstore.ListVersionsOutput, error)
getVersionMetadata func(appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error)
purchase func(appstore.PurchaseInput) error
download func(appstore.DownloadInput) (appstore.DownloadOutput, error)
replicateSinf func(appstore.ReplicateSinfInput) error
login func(appstore.LoginInput) (appstore.LoginOutput, error)
}
func (s *fakeMCPAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
return s.accountInfo()
}
func (s *fakeMCPAppStore) Search(input appstore.SearchInput) (appstore.SearchOutput, error) {
return s.search(input)
}
func (s *fakeMCPAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
return s.lookup(input)
}
func (s *fakeMCPAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
return s.ownedApps(input)
}
func (s *fakeMCPAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
return s.listVersions(input)
}
func (s *fakeMCPAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
return s.getVersionMetadata(input)
}
func (s *fakeMCPAppStore) Purchase(input appstore.PurchaseInput) error {
return s.purchase(input)
}
func (s *fakeMCPAppStore) Download(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
return s.download(input)
}
func (s *fakeMCPAppStore) ReplicateSinf(input appstore.ReplicateSinfInput) error {
return s.replicateSinf(input)
}
func (s *fakeMCPAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
return s.login(input)
}
+364
View File
@@ -0,0 +1,364 @@
package cmd
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/majd/ipatool/v2/pkg/appstore"
)
type mcpSearchInput struct {
Term string `json:"term" jsonschema:"Search term"`
Limit *int64 `json:"limit,omitempty" jsonschema:"Maximum results; defaults to 5. visionOS supports up to 12."`
Platform string `json:"platform,omitempty" jsonschema:"iphone (ios), ipad (ipados), appletv (tvos), watchos, visionos, or macos; defaults to iOS and iPadOS"`
}
type mcpSearchOutput struct {
Term string `json:"term"`
Limit int64 `json:"limit"`
Platform appstore.Platform `json:"platform"`
Count int `json:"count"`
Apps []mcpApp `json:"apps"`
}
type mcpAppInput struct {
AppID int64 `json:"app_id,omitempty" jsonschema:"Numeric app ID; required unless bundle_identifier is provided"`
BundleID string `json:"bundle_identifier,omitempty" jsonschema:"Bundle identifier; overrides app_id when found"`
Platform string `json:"platform,omitempty" jsonschema:"iphone (ios), ipad (ipados), appletv (tvos), watchos, visionos, or macos; uses the CLI default when omitted"`
}
type mcpDownloadInput struct {
mcpAppInput
Output string `json:"output,omitempty" jsonschema:"Destination file or directory; defaults to the server's working directory"`
ExternalVersionID string `json:"external_version_id,omitempty" jsonschema:"External version identifier; defaults to the latest version"`
Purchase bool `json:"purchase,omitempty" jsonschema:"Acquire a free license if needed; defaults to false"`
}
type mcpDownloadOutput struct {
mcpAppParameters
App mcpApp `json:"app"`
Output string `json:"output"`
ExternalVersionID string `json:"external_version_id"`
Purchase bool `json:"purchase"`
Purchased bool `json:"purchased"`
Success bool `json:"success"`
}
type mcpVersionsOutput struct {
mcpAppParameters
App mcpApp `json:"app"`
ExternalVersionIdentifiers []string `json:"externalVersionIdentifiers"`
LatestExternalVersionID string `json:"latestExternalVersionID"`
BundleID string `json:"bundleID"`
Success bool `json:"success"`
}
type mcpVersionMetadataInput struct {
mcpAppInput
ExternalVersionID string `json:"external_version_id" jsonschema:"External version identifier of the target app (required)"`
}
type mcpVersionMetadataOutput struct {
mcpAppParameters
App mcpApp `json:"app"`
ExternalVersionID string `json:"external_version_id"`
DisplayVersion string `json:"displayVersion" jsonschema:"Display version of the requested external version identifier"`
ReleaseDate time.Time `json:"releaseDate"`
Success bool `json:"success"`
}
type mcpPurchasesInput struct {
Page *int `json:"page,omitempty" jsonschema:"Page number starting at 1; defaults to 1"`
MaxResults *int `json:"max_results,omitempty" jsonschema:"Apps per page from 1 to 100; defaults to 10"`
Platform string `json:"platform,omitempty" jsonschema:"iphone (ios), ipad (ipados), appletv (tvos), visionos, or macos; defaults to all platforms"`
}
type mcpPurchasesOutput struct {
Count int `json:"count"`
TotalCount int `json:"totalCount"`
Page int `json:"page"`
MaxResults int `json:"max_results"`
Platform appstore.Platform `json:"platform"`
Apps []mcpApp `json:"apps"`
}
type mcpPurchaseOutput struct {
mcpAppParameters
App mcpApp `json:"app"`
AlreadyOwned bool `json:"alreadyOwned"`
Success bool `json:"success"`
}
// withMCPAccount refreshes expired tokens using the saved credentials, as the CLI does.
// Authentication and account details are never included in tool results.
func withMCPAccount[Out any](ctx context.Context, store appstore.AppStore, operation func(appstore.Account) (Out, error)) (Out, error) {
var zero Out
info, err := store.AccountInfo()
if err != nil {
return zero, fmt.Errorf("account unavailable; run 'ipatool auth login' before using MCP: %w", err)
}
output, err := operation(info.Account)
if !errors.Is(err, appstore.ErrPasswordTokenExpired) {
return output, err
}
if err := ctx.Err(); err != nil {
return zero, fmt.Errorf("tool call canceled: %w", err)
}
login, err := store.Login(appstore.LoginInput{Email: info.Account.Email, Password: info.Account.Password})
if err != nil {
return zero, fmt.Errorf("session refresh failed; run 'ipatool auth login' outside MCP: %w", err)
}
output, err = operation(login.Account)
if err != nil {
return zero, fmt.Errorf("operation failed after session refresh: %w", err)
}
return output, nil
}
//nolint:wrapcheck
func (t *mcpTools) search(ctx context.Context, input mcpSearchInput) (mcpSearchOutput, error) {
if strings.TrimSpace(input.Term) == "" {
return mcpSearchOutput{}, errors.New("search term must not be empty")
}
limit := int64(5)
if input.Limit != nil {
limit = *input.Limit
}
if limit < 1 {
return mcpSearchOutput{}, errors.New("limit must be greater than 0")
}
platform, err := appstore.ParsePlatform(input.Platform)
if err != nil {
return mcpSearchOutput{}, err
}
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpSearchOutput, error) {
out, err := t.store.Search(appstore.SearchInput{Account: acc, Term: input.Term, Limit: limit, Platform: platform})
if err != nil {
return mcpSearchOutput{}, err
}
return mcpSearchOutput{
Term: input.Term, Limit: limit, Platform: platform,
Count: out.Count, Apps: t.appResults(acc, out.Results, platform),
}, nil
})
}
//nolint:wrapcheck
func (input mcpAppInput) validate() (appstore.Platform, error) {
if input.AppID < 0 || (input.AppID == 0 && strings.TrimSpace(input.BundleID) == "") {
return "", errors.New("a positive app ID or a bundle identifier must be specified")
}
return appstore.ParsePlatform(input.Platform)
}
//nolint:wrapcheck
func (t *mcpTools) resolveApp(acc appstore.Account, input mcpAppInput, platform appstore.Platform, allowDelisted bool) (appstore.App, error) {
app := appstore.App{ID: input.AppID, BundleID: input.BundleID}
if input.BundleID == "" {
return t.completeApp(acc, app, platform), nil
}
out, err := t.store.Lookup(appstore.LookupInput{Account: acc, BundleID: input.BundleID, Platform: platform})
if allowDelisted && input.AppID > 0 && errors.Is(err, appstore.ErrAppNotFound) {
return app, nil
}
if err != nil {
return appstore.App{}, err
}
// Preserve a known bundle identifier even if the catalog omits it.
if out.App.BundleID == "" {
out.App.BundleID = input.BundleID
}
return out.App, nil
}
//nolint:wrapcheck
func (t *mcpTools) download(ctx context.Context, input mcpDownloadInput) (mcpDownloadOutput, error) {
platform, err := input.validate()
if err != nil {
return mcpDownloadOutput{}, err
}
purchased := false
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpDownloadOutput, error) {
app, err := t.resolveApp(acc, input.mcpAppInput, platform, true)
if err != nil {
return mcpDownloadOutput{}, err
}
downloadInput := appstore.DownloadInput{
Context: ctx, Account: acc, App: app, OutputPath: input.Output,
ExternalVersionID: input.ExternalVersionID, Platform: platform,
}
out, err := t.store.Download(downloadInput)
if errors.Is(err, appstore.ErrLicenseRequired) && input.Purchase && !purchased {
err = t.store.Purchase(appstore.PurchaseInput{Account: acc, App: app, Platform: platform})
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
return mcpDownloadOutput{}, err
}
info, accountErr := t.store.AccountInfo()
if accountErr != nil {
return mcpDownloadOutput{}, accountErr
}
downloadInput.Account = info.Account
purchased = true
out, err = t.store.Download(downloadInput)
}
if err != nil {
return mcpDownloadOutput{}, err
}
if err := replicateDownloadSinf(t.store, platform, out); err != nil {
return mcpDownloadOutput{}, err
}
return mcpDownloadOutput{
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
Output: out.DestinationPath, ExternalVersionID: input.ExternalVersionID,
Purchase: input.Purchase, Purchased: purchased, Success: true,
}, nil
})
}
//nolint:wrapcheck
func (t *mcpTools) listVersions(ctx context.Context, input mcpAppInput) (mcpVersionsOutput, error) {
platform, err := input.validate()
if err != nil {
return mcpVersionsOutput{}, err
}
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpVersionsOutput, error) {
app, err := t.resolveApp(acc, input, platform, false)
if err != nil {
return mcpVersionsOutput{}, err
}
out, err := t.store.ListVersions(appstore.ListVersionsInput{Context: ctx, Account: acc, App: app, Platform: platform})
if err != nil {
return mcpVersionsOutput{}, err
}
return mcpVersionsOutput{
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
ExternalVersionIdentifiers: append([]string{}, out.ExternalVersionIdentifiers...),
LatestExternalVersionID: out.LatestExternalVersionID, BundleID: app.BundleID, Success: true,
}, nil
})
}
//nolint:wrapcheck
func (t *mcpTools) getVersionMetadata(ctx context.Context, input mcpVersionMetadataInput) (mcpVersionMetadataOutput, error) {
platform, err := input.validate()
if err != nil {
return mcpVersionMetadataOutput{}, err
}
if strings.TrimSpace(input.ExternalVersionID) == "" {
return mcpVersionMetadataOutput{}, errors.New("external version identifier must not be empty")
}
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpVersionMetadataOutput, error) {
app, err := t.resolveApp(acc, input.mcpAppInput, platform, false)
if err != nil {
return mcpVersionMetadataOutput{}, err
}
out, err := t.store.GetVersionMetadata(appstore.GetVersionMetadataInput{
Context: ctx, Account: acc, App: app, VersionID: input.ExternalVersionID, Platform: platform,
})
if err != nil {
return mcpVersionMetadataOutput{}, err
}
return mcpVersionMetadataOutput{
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
ExternalVersionID: input.ExternalVersionID, DisplayVersion: out.DisplayVersion,
ReleaseDate: out.ReleaseDate, Success: true,
}, nil
})
}
//nolint:wrapcheck
func (t *mcpTools) listPurchases(ctx context.Context, input mcpPurchasesInput) (mcpPurchasesOutput, error) {
page, limit := 1, appstore.DefaultOwnedAppsLimit
if input.Page != nil {
page = *input.Page
}
if input.MaxResults != nil {
limit = *input.MaxResults
}
if page < 1 {
return mcpPurchasesOutput{}, errors.New("page must be greater than 0")
}
if limit < 1 || limit > appstore.MaxOwnedAppsLimit {
return mcpPurchasesOutput{}, fmt.Errorf("max results must be between 1 and %d", appstore.MaxOwnedAppsLimit)
}
platform, err := appstore.ParsePlatform(input.Platform)
if err != nil {
return mcpPurchasesOutput{}, err
}
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpPurchasesOutput, error) {
out, err := t.store.OwnedApps(appstore.OwnedAppsInput{Account: acc, Page: page, Limit: limit, Platform: platform})
if err != nil {
return mcpPurchasesOutput{}, err
}
return mcpPurchasesOutput{
Count: out.Count, TotalCount: out.TotalCount, Page: out.Page, MaxResults: limit, Platform: platform,
Apps: t.appResults(acc, out.Results, platform),
}, nil
})
}
//nolint:wrapcheck
func (t *mcpTools) purchase(ctx context.Context, input mcpAppInput) (mcpPurchaseOutput, error) {
platform, err := input.validate()
if err != nil {
return mcpPurchaseOutput{}, err
}
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpPurchaseOutput, error) {
app, err := t.resolveApp(acc, input, platform, false)
if err != nil {
return mcpPurchaseOutput{}, err
}
err = t.store.Purchase(appstore.PurchaseInput{Account: acc, App: app, Platform: platform})
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
return mcpPurchaseOutput{}, err
}
return mcpPurchaseOutput{
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
AlreadyOwned: errors.Is(err, appstore.ErrLicenseAlreadyExists), Success: true,
}, nil
})
}
+98
View File
@@ -0,0 +1,98 @@
package cmd
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"strings"
"unicode"
"golang.org/x/term"
)
func readPrompt(prompt string, masked bool) (string, error) {
if masked {
state, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil {
return "", fmt.Errorf("failed to configure terminal: %w", err)
}
defer term.Restore(int(os.Stdin.Fd()), state) //nolint:errcheck
}
// Prompts belong on stderr so structured output on stdout stays valid.
if _, err := io.WriteString(os.Stderr, prompt); err != nil {
return "", fmt.Errorf("failed to write prompt: %w", err)
}
if masked {
defer fmt.Fprint(os.Stderr, "\r\n")
return readMaskedInput(os.Stdin, os.Stderr)
}
line, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return "", fmt.Errorf("failed to read input: %w", err)
}
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
}
func readMaskedInput(input io.Reader, output io.Writer) (string, error) {
reader := bufio.NewReader(input)
var (
password []rune
escape int
)
for {
key, _, err := reader.ReadRune()
if err != nil {
return "", fmt.Errorf("failed to read input: %w", err)
}
// Ignore terminal escape sequences (for example, arrow keys).
if escape != 0 {
if escape == 1 && (key == '[' || key == 'O') {
escape = 2
} else if escape == 1 || (key >= 0x40 && key <= 0x7e) {
escape = 0
}
continue
}
var echo string
switch key {
case '\r', '\n':
return string(password), nil
case 3:
return "", errors.New("input interrupted")
case 4:
return "", io.EOF
case 27:
escape = 1
case '\b', 127:
if len(password) > 0 {
password = password[:len(password)-1]
echo = "\b \b"
}
case 21:
echo = strings.Repeat("\b \b", len(password))
password = password[:0]
default:
if unicode.IsPrint(key) {
password = append(password, key)
echo = "*"
}
}
if _, err := io.WriteString(output, echo); err != nil {
return "", fmt.Errorf("failed to echo input: %w", err)
}
}
}
+48
View File
@@ -0,0 +1,48 @@
package cmd
import (
"bytes"
"io"
"strings"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Masked input", func() {
DescribeTable("echoes masks while preserving the entered password", func(input, password, echo string) {
var output bytes.Buffer
value, err := readMaskedInput(strings.NewReader(input), &output)
Expect(err).NotTo(HaveOccurred())
Expect(value).To(Equal(password))
Expect(output.String()).To(Equal(echo))
},
Entry("enter", "secret\r", "secret", "******"),
Entry("newline", "secret\n", "secret", "******"),
Entry("unicode", "pä密🔑\r", "pä密🔑", "****"),
Entry("delete", "ab\x7fc\r", "ac", "**\b \b*"),
Entry("unicode backspace", "a密\bc\r", "ac", "**\b \b*"),
Entry("backspace on empty input", "\b\x7fa\r", "a", "*"),
Entry("clear line", "ab\x15c\r", "c", "**\b \b\b \b*"),
Entry("arrow keys", "ab\x1b[D\x1bOCc\r", "abc", "***"),
Entry("empty input", "\r", "", ""),
)
It("cancels without returning the password on Ctrl-C", func() {
value, err := readMaskedInput(strings.NewReader("secret\x03"), io.Discard)
Expect(err).To(MatchError("input interrupted"))
Expect(value).To(BeEmpty())
})
DescribeTable("discards incomplete input", func(input string) {
value, err := readMaskedInput(strings.NewReader(input), io.Discard)
Expect(err).To(MatchError(ContainSubstring("EOF")))
Expect(value).To(BeEmpty())
},
Entry("end of stream", "secret"),
Entry("Ctrl-D", "secret\x04"),
)
})
+42 -16
View File
@@ -2,7 +2,6 @@ package cmd
import (
"errors"
"fmt"
"time"
"github.com/avast/retry-go"
@@ -12,17 +11,36 @@ import (
// nolint:wrapcheck
func purchaseCmd() *cobra.Command {
var bundleID string
return purchaseCmdWithAppStore(func() appstore.AppStore { return dependencies.AppStore })
}
//nolint:wrapcheck
func purchaseCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
var (
appID int64
bundleID string
platformValue string
)
cmd := &cobra.Command{
Use: "purchase",
Short: "Obtain a license for the app from the App Store",
RunE: func(cmd *cobra.Command, args []string) error {
if appID == 0 && bundleID == "" {
return errors.New("either the app ID or the bundle identifier must be specified")
}
platform, err := appstore.ParsePlatform(platformValue)
if err != nil {
return err
}
var lastErr error
var acc appstore.Account
return retry.Do(func() error {
infoResult, err := dependencies.AppStore.AccountInfo()
store := appStore()
infoResult, err := store.AccountInfo()
if err != nil {
return err
}
@@ -30,15 +48,9 @@ func purchaseCmd() *cobra.Command {
acc = infoResult.Account
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
bagOutput, err := dependencies.AppStore.Bag(appstore.BagInput{})
if err != nil {
return fmt.Errorf("failed to get bag: %w", err)
}
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
loginResult, err := store.Login(appstore.LoginInput{
Email: acc.Email,
Password: acc.Password,
Endpoint: bagOutput.AuthEndpoint,
})
if err != nil {
return err
@@ -47,12 +59,25 @@ func purchaseCmd() *cobra.Command {
acc = loginResult.Account
}
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID})
if err != nil {
return err
app := appstore.App{ID: appID}
if bundleID != "" {
lookupResult, err := store.Lookup(appstore.LookupInput{
Account: acc,
BundleID: bundleID,
Platform: platform,
})
if err != nil {
return err
}
app = lookupResult.App
}
err = dependencies.AppStore.Purchase(appstore.PurchaseInput{Account: acc, App: lookupResult.App})
err = store.Purchase(appstore.PurchaseInput{
Account: acc,
App: app,
Platform: platform,
})
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
return err
}
@@ -77,8 +102,9 @@ func purchaseCmd() *cobra.Command {
},
}
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "Bundle identifier of the target iOS app (required)")
_ = cmd.MarkFlagRequired("bundle-identifier")
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app")
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to purchase for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
return cmd
}
+133
View File
@@ -0,0 +1,133 @@
package cmd
import (
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/majd/ipatool/v2/pkg/log"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Purchase command", func() {
It("accepts a platform flag with macOS help", func() {
cmd := purchaseCmd()
platform, err := cmd.Flags().GetString("platform")
Expect(err).ToNot(HaveOccurred())
Expect(platform).To(BeEmpty())
Expect(cmd.Flag("platform").Usage).To(ContainSubstring("macos"))
})
DescribeTable("purchasing by app ID", func(flag string) {
store := &fakePurchaseAppStore{}
previousDependencies := dependencies
DeferCleanup(func() { dependencies = previousDependencies })
dependencies.Logger = log.NewLogger(log.Args{})
cmd := purchaseCmdWithAppStore(func() appstore.AppStore { return store })
cmd.SetArgs([]string{flag, "123456789", "--platform", "macos"})
Expect(cmd.Execute()).To(Succeed())
Expect(store.lookupCalls).To(BeZero())
Expect(store.purchaseInput.App).To(Equal(appstore.App{ID: 123456789}))
Expect(store.purchaseInput.Platform).To(Equal(appstore.PlatformMacOS))
},
Entry("accepts the long flag", "--app-id"),
Entry("accepts the short flag", "-i"),
)
It("requires an app ID or bundle identifier before accessing the account", func() {
cmd := purchaseCmdWithAppStore(func() appstore.AppStore {
Fail("must not access the app store without a target")
return nil
})
cmd.SetArgs([]string{})
Expect(cmd.Execute()).To(MatchError("either the app ID or the bundle identifier must be specified"))
})
It("lets the bundle identifier override the app ID", func() {
store := &fakePurchaseAppStore{}
previousDependencies := dependencies
DeferCleanup(func() { dependencies = previousDependencies })
dependencies.Logger = log.NewLogger(log.Args{})
cmd := purchaseCmdWithAppStore(func() appstore.AppStore { return store })
cmd.SetArgs([]string{"-i", "123456789", "-b", "com.example.app"})
Expect(cmd.Execute()).To(Succeed())
Expect(store.lookupCalls).To(Equal(1))
Expect(store.purchaseInput.App).To(Equal(appstore.App{ID: 42, BundleID: "com.example.app"}))
})
It("propagates macOS to lookup and purchase", func() {
store := &fakePurchaseAppStore{}
previousDependencies := dependencies
DeferCleanup(func() { dependencies = previousDependencies })
dependencies.Logger = log.NewLogger(log.Args{})
cmd := purchaseCmdWithAppStore(func() appstore.AppStore { return store })
cmd.SetArgs([]string{"--bundle-identifier", "com.example.mac", "--platform", "macos"})
Expect(cmd.Execute()).To(Succeed())
Expect(store.lookupInput.BundleID).To(Equal("com.example.mac"))
Expect(store.lookupInput.Platform).To(Equal(appstore.PlatformMacOS))
Expect(store.purchaseInput.Platform).To(Equal(appstore.PlatformMacOS))
Expect(store.purchaseInput.App).To(Equal(appstore.App{ID: 42, BundleID: "com.example.mac"}))
})
})
type fakePurchaseAppStore struct {
lookupCalls int
lookupInput appstore.LookupInput
purchaseInput appstore.PurchaseInput
}
func (*fakePurchaseAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
return appstore.LoginOutput{}, nil
}
func (*fakePurchaseAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
return appstore.AccountInfoOutput{Account: appstore.Account{StoreFront: "143441"}}, nil
}
func (*fakePurchaseAppStore) Revoke() error { return nil }
func (f *fakePurchaseAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
f.lookupCalls++
f.lookupInput = input
return appstore.LookupOutput{App: appstore.App{ID: 42, BundleID: input.BundleID}}, nil
}
func (*fakePurchaseAppStore) Search(input appstore.SearchInput) (appstore.SearchOutput, error) {
return appstore.SearchOutput{}, nil
}
func (*fakePurchaseAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
return appstore.OwnedAppsOutput{}, nil
}
func (f *fakePurchaseAppStore) Purchase(input appstore.PurchaseInput) error {
f.purchaseInput = input
return nil
}
func (*fakePurchaseAppStore) Download(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
return appstore.DownloadOutput{}, nil
}
func (*fakePurchaseAppStore) ReplicateSinf(input appstore.ReplicateSinfInput) error { return nil }
func (*fakePurchaseAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
return appstore.ListVersionsOutput{}, nil
}
func (*fakePurchaseAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
return appstore.GetVersionMetadataOutput{}, nil
}
func (*fakePurchaseAppStore) Bag(input appstore.BagInput) (appstore.BagOutput, error) {
return appstore.BagOutput{}, nil
}
+100
View File
@@ -0,0 +1,100 @@
package cmd
import (
"errors"
"fmt"
"time"
"github.com/avast/retry-go"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/spf13/cobra"
)
// nolint:wrapcheck
func listPurchasesCmd() *cobra.Command {
var page, maxResults int
var platformValue string
var platform appstore.Platform
cmd := &cobra.Command{
Use: "list-purchases",
Short: "List apps owned by the authenticated App Store account",
Args: cobra.NoArgs,
PreRunE: func(cmd *cobra.Command, args []string) error {
if page < 1 {
return errors.New("page must be greater than 0")
}
if maxResults < 1 {
return errors.New("max results must be greater than 0")
}
if maxResults > appstore.MaxOwnedAppsLimit {
return fmt.Errorf("max results must not exceed %d", appstore.MaxOwnedAppsLimit)
}
var err error
platform, err = appstore.ParsePlatform(platformValue)
return err
},
RunE: func(cmd *cobra.Command, args []string) error {
var lastErr error
return retry.Do(func() error {
infoResult, err := dependencies.AppStore.AccountInfo()
if err != nil {
return err
}
acc := infoResult.Account
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
Email: acc.Email,
Password: acc.Password,
})
if err != nil {
return err
}
acc = loginResult.Account
}
output, err := dependencies.AppStore.OwnedApps(appstore.OwnedAppsInput{
Account: acc,
Page: page,
Limit: maxResults,
Platform: platform,
})
if err != nil {
return err
}
dependencies.Logger.Log().
Int("count", output.Count).
Int("totalCount", output.TotalCount).
Int("page", output.Page).
Array("apps", appstore.Apps(output.Results)).
Send()
return nil
},
retry.LastErrorOnly(true),
retry.DelayType(retry.FixedDelay),
retry.Delay(time.Millisecond),
retry.Attempts(2),
retry.RetryIf(func(err error) bool {
lastErr = err
return errors.Is(err, appstore.ErrPasswordTokenExpired)
}),
)
},
}
cmd.Flags().IntVarP(&maxResults, "max-results", "l", appstore.DefaultOwnedAppsLimit, "maximum number of apps to return per page")
cmd.Flags().IntVarP(&page, "page", "p", 1, "page of owned apps to return")
cmd.Flags().StringVar(&platformValue, "platform", "", "Filter by platform: iphone (iOS), ipad (iPadOS), appletv (tvOS), visionos, or macos")
return cmd
}
+88
View File
@@ -0,0 +1,88 @@
package cmd
import (
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/majd/ipatool/v2/pkg/log"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("List Purchases command", func() {
DescribeTable("passes the platform filter to owned apps",
func(value string, expected appstore.Platform) {
store := &fakePurchasesAppStore{}
previousDependencies := dependencies
DeferCleanup(func() { dependencies = previousDependencies })
dependencies.AppStore = store
dependencies.Logger = log.NewLogger(log.Args{})
cmd := listPurchasesCmd()
cmd.SetArgs([]string{"--platform", value})
Expect(cmd.Execute()).To(Succeed())
Expect(store.input.Platform).To(Equal(expected))
},
Entry("all platforms by default", "", appstore.Platform("")),
Entry("iOS alias", "ios", appstore.PlatformIPhone),
Entry("iPadOS alias", "ipados", appstore.PlatformIPad),
Entry("tvOS alias", "tvos", appstore.PlatformAppleTV),
Entry("visionOS", "visionos", appstore.PlatformVisionOS),
Entry("macOS", "macos", appstore.PlatformMacOS),
)
DescribeTable("rejects an invalid platform before accessing the account", func(value string) {
cmd := listPurchasesCmd()
Expect(cmd.Flags().Set("platform", value)).To(Succeed())
Expect(cmd.PreRunE(cmd, nil)).To(MatchError(ContainSubstring("invalid platform")))
},
Entry("invalid value", "invalid"),
Entry("unknown is output only", "unknown"),
Entry("uppercase unknown", "UNKNOWN"),
)
It("uses the pagination defaults", func() {
cmd := listPurchasesCmd()
page, err := cmd.Flags().GetInt("page")
Expect(err).ToNot(HaveOccurred())
Expect(page).To(Equal(1))
maxResults, err := cmd.Flags().GetInt("max-results")
Expect(err).ToNot(HaveOccurred())
Expect(maxResults).To(Equal(appstore.DefaultOwnedAppsLimit))
})
DescribeTable("rejects invalid pagination",
func(flag, value, errorText string) {
cmd := listPurchasesCmd()
Expect(cmd.Flags().Set(flag, value)).To(Succeed())
err := cmd.PreRunE(cmd, nil)
Expect(err).To(MatchError(ContainSubstring(errorText)))
},
Entry("page below one", "page", "0", "page"),
Entry("max results below one", "max-results", "0", "max results"),
Entry("max results over limit", "max-results", "101", "100"),
)
It("is registered on the root command", func() {
cmd, _, err := rootCmd().Find([]string{"list-purchases"})
Expect(err).ToNot(HaveOccurred())
Expect(cmd.Name()).To(Equal("list-purchases"))
})
})
type fakePurchasesAppStore struct {
appstore.AppStore
input appstore.OwnedAppsInput
}
func (*fakePurchasesAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
return appstore.AccountInfoOutput{}, nil
}
func (s *fakePurchasesAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
s.input = input
return appstore.OwnedAppsOutput{}, nil
}
+2
View File
@@ -47,10 +47,12 @@ func rootCmd() *cobra.Command {
cmd.AddCommand(authCmd())
cmd.AddCommand(downloadCmd())
cmd.AddCommand(listPurchasesCmd())
cmd.AddCommand(purchaseCmd())
cmd.AddCommand(searchCmd())
cmd.AddCommand(ListVersionsCmd())
cmd.AddCommand(getVersionMetadataCmd())
cmd.AddCommand(mcpCmd())
return cmd
}
+3 -3
View File
@@ -14,7 +14,7 @@ func searchCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "search <term>",
Short: "Search for iOS and tvOS apps available on the App Store",
Short: "Search for iOS, iPadOS, tvOS, watchOS, visionOS, and macOS apps available on the App Store",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
infoResult, err := dependencies.AppStore.AccountInfo()
@@ -46,8 +46,8 @@ func searchCmd() *cobra.Command {
},
}
cmd.Flags().Int64VarP(&limit, "limit", "l", 5, "maximum amount of search results to retrieve")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to search: iphone, ipad, or appletv")
cmd.Flags().Int64VarP(&limit, "limit", "l", 5, "maximum amount of search results to retrieve; visionOS supports up to 12")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to search: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
return cmd
}
+61
View File
@@ -0,0 +1,61 @@
package cmd
import (
"fmt"
"path/filepath"
"strings"
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
)
// prepareStateDirectory resolves and migrates session storage before it is opened.
func prepareStateDirectory(os operatingsystem.OperatingSystem, homeDirectory string) (string, error) {
legacyDirectory := filepath.Join(homeDirectory, ConfigDirectoryName)
stateDirectory := legacyDirectory
for _, variable := range []string{"XDG_STATE_HOME", "XDG_DATA_HOME"} {
if base := os.Getenv(variable); filepath.IsAbs(base) {
stateDirectory = filepath.Join(base, "ipatool")
break
}
}
info, err := os.Stat(legacyDirectory)
if err != nil && !os.IsNotExist(err) {
return "", fmt.Errorf("could not read legacy state directory metadata: %w", err)
}
if err == nil {
if !info.IsDir() {
return "", fmt.Errorf("legacy state path is not a directory: %s", legacyDirectory)
}
// Never merge sessions or move a directory into itself. Keeping the legacy
// directory also preserves authentication when migration is unavailable.
relative, err := filepath.Rel(legacyDirectory, stateDirectory)
if err == nil && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
return legacyDirectory, nil
}
if _, err := os.Stat(stateDirectory); err == nil || !os.IsNotExist(err) {
return legacyDirectory, nil
}
if err := os.MkdirAll(filepath.Dir(stateDirectory), 0700); err != nil {
return legacyDirectory, nil
}
// Rename keeps cookies and encrypted credentials together, with their
// existing permissions. Cross-filesystem moves fall back to legacy storage.
if err := os.Rename(legacyDirectory, stateDirectory); err != nil {
return legacyDirectory, nil
}
return stateDirectory, nil
}
if err := os.MkdirAll(stateDirectory, 0700); err != nil {
return "", fmt.Errorf("failed to create state directory: %w", err)
}
return stateDirectory, nil
}
+182
View File
@@ -0,0 +1,182 @@
package cmd
import (
"errors"
"net/http"
"net/url"
"os"
"path/filepath"
"time"
"github.com/byteness/keyring"
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("State directory", func() {
var home, legacy, target string
BeforeEach(func() {
home = GinkgoT().TempDir()
legacy = filepath.Join(home, ConfigDirectoryName)
target = filepath.Join(home, "state", "ipatool")
GinkgoT().Setenv("XDG_STATE_HOME", filepath.Dir(target))
GinkgoT().Setenv("XDG_DATA_HOME", "")
})
DescribeTable("selects the session directory", func(state, data, want string) {
for variable, value := range map[string]string{"XDG_STATE_HOME": state, "XDG_DATA_HOME": data} {
if value != "" && value != "relative" {
value = filepath.Join(home, value)
}
GinkgoT().Setenv(variable, value)
}
got, err := prepareStateDirectory(operatingsystem.New(), home)
Expect(err).ToNot(HaveOccurred())
Expect(got).To(Equal(filepath.Join(home, want)))
Expect(got).To(BeADirectory())
if got != legacy {
Expect(legacy).ToNot(BeAnExistingFile())
}
},
Entry("defaults to legacy storage", "", "", ConfigDirectoryName),
Entry("prefers state storage", "state", "data", "state/ipatool"),
Entry("falls back to data storage", "", "data", "data/ipatool"),
Entry("ignores a relative state path", "relative", "data", "data/ipatool"),
Entry("ignores relative paths", "relative", "relative", ConfigDirectoryName),
)
It("preserves authentication after migration and subsequent startup", func() {
Expect(os.MkdirAll(legacy, 0700)).To(Succeed())
openKeyring := func(directory string) keyring.Keyring {
ring, err := keyring.Open(keyring.Config{
AllowedBackends: []keyring.BackendType{keyring.FileBackend},
ServiceName: KeychainServiceName,
FileDir: directory,
FilePasswordFunc: keyring.FixedStringPrompt("test-passphrase"),
})
ExpectWithOffset(1, err).ToNot(HaveOccurred())
return ring
}
item := keyring.Item{Key: "account", Data: []byte("existing-session"), Label: KeychainServiceName}
Expect(openKeyring(legacy).Set(item)).To(Succeed())
cookieURL, err := url.Parse("https://apps.apple.com/")
Expect(err).ToNot(HaveOccurred())
jar := newCookieJar(legacy)
jar.SetCookies(cookieURL, []*http.Cookie{{Name: "session", Value: "existing-cookie", Path: "/", Expires: time.Now().Add(time.Hour)}})
Expect(jar.Save()).To(Succeed())
before, err := os.ReadFile(filepath.Join(legacy, item.Key))
Expect(err).ToNot(HaveOccurred())
for i := 0; i < 2; i++ {
directory, err := prepareStateDirectory(operatingsystem.New(), home)
Expect(err).ToNot(HaveOccurred())
Expect(directory).To(Equal(target))
got, err := openKeyring(directory).Get(item.Key)
Expect(err).ToNot(HaveOccurred())
Expect(got.Data).To(Equal(item.Data))
after, err := os.ReadFile(filepath.Join(directory, item.Key))
Expect(err).ToNot(HaveOccurred())
Expect(after).To(Equal(before), "encrypted credentials must remain unchanged")
cookies := newCookieJar(directory).Cookies(cookieURL)
Expect(cookies).To(HaveLen(1))
Expect(cookies[0].Name).To(Equal("session"))
Expect(cookies[0].Value).To(Equal("existing-cookie"))
}
Expect(legacy).ToNot(BeAnExistingFile())
})
DescribeTable("preserves legacy storage when migration fails", func(mkdirErr, renameErr error) {
Expect(os.MkdirAll(legacy, 0700)).To(Succeed())
Expect(os.WriteFile(filepath.Join(legacy, CookieJarFileName), []byte("session"), 0600)).To(Succeed())
got, err := prepareStateDirectory(migrationFailureOS{operatingsystem.New(), mkdirErr, renameErr}, home)
Expect(err).ToNot(HaveOccurred())
Expect(got).To(Equal(legacy))
data, err := os.ReadFile(filepath.Join(got, CookieJarFileName))
Expect(err).ToNot(HaveOccurred())
Expect(string(data)).To(Equal("session"))
},
Entry("parent creation denied", os.ErrPermission, nil),
Entry("rename denied", nil, os.ErrPermission),
Entry("cross filesystem", nil, errors.New("cross-device link")),
)
It("preserves conflicting sessions and uses legacy storage", func() {
for _, directory := range []string{legacy, target} {
Expect(os.MkdirAll(directory, 0700)).To(Succeed())
Expect(os.WriteFile(filepath.Join(directory, "account"), []byte(directory), 0600)).To(Succeed())
}
got, err := prepareStateDirectory(operatingsystem.New(), home)
Expect(err).ToNot(HaveOccurred())
Expect(got).To(Equal(legacy))
for _, directory := range []string{legacy, target} {
data, err := os.ReadFile(filepath.Join(directory, "account"))
Expect(err).ToNot(HaveOccurred())
Expect(string(data)).To(Equal(directory))
}
})
DescribeTable("rejects files at directory paths", func(useLegacy bool) {
path := target
if useLegacy {
path = legacy
}
Expect(os.MkdirAll(filepath.Dir(path), 0700)).To(Succeed())
Expect(os.WriteFile(path, []byte("existing file"), 0600)).To(Succeed())
_, err := prepareStateDirectory(operatingsystem.New(), home)
Expect(err).To(HaveOccurred())
},
Entry("legacy", true),
Entry("destination", false),
)
It("preserves legacy storage for a nested destination", func() {
GinkgoT().Setenv("XDG_STATE_HOME", filepath.Join(legacy, "state"))
Expect(os.MkdirAll(legacy, 0700)).To(Succeed())
got, err := prepareStateDirectory(operatingsystem.New(), home)
Expect(err).ToNot(HaveOccurred())
Expect(got).To(Equal(legacy))
entries, err := os.ReadDir(legacy)
Expect(err).ToNot(HaveOccurred())
Expect(entries).To(BeEmpty(), "migration must not create directories inside legacy storage")
})
})
type migrationFailureOS struct {
operatingsystem.OperatingSystem
mkdirErr, renameErr error
}
// nolint:wrapcheck
func (o migrationFailureOS) MkdirAll(path string, mode os.FileMode) error {
if o.mkdirErr != nil {
return o.mkdirErr
}
return o.OperatingSystem.MkdirAll(path, mode)
}
func (o migrationFailureOS) Rename(from, to string) error {
return o.renameErr
}
+56 -20
View File
@@ -1,63 +1,99 @@
module github.com/majd/ipatool/v2
go 1.25.0
go 1.26.5
require (
github.com/avast/retry-go v3.0.0+incompatible
github.com/blacktop/go-macho v1.1.282
github.com/bodgit/sevenzip v1.6.3
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4
github.com/byteness/keyring v1.9.0
github.com/deploymenttheory/go-macos-pkg v0.3.0
github.com/ebitengine/purego v0.10.2
github.com/go-compressions/lzfse v0.3.0
github.com/juju/persistent-cookiejar v1.0.0
github.com/klauspost/compress v1.18.7
github.com/majd/go-apfs v1.0.29
github.com/modelcontextprotocol/go-sdk v1.8.0
github.com/onsi/ginkgo/v2 v2.5.0
github.com/onsi/gomega v1.24.0
github.com/rs/zerolog v1.28.0
github.com/schollz/progressbar/v3 v3.13.1
github.com/spf13/cobra v1.6.1
github.com/schollz/progressbar/v3 v3.19.1
github.com/spf13/cobra v1.10.2
github.com/thediveo/enumflag/v2 v2.0.1
go.uber.org/mock v0.4.0
golang.org/x/term v0.43.0
howett.net/plist v1.0.0
golang.org/x/sys v0.48.0
golang.org/x/term v0.46.0
golang.org/x/text v0.42.0
howett.net/plist v1.0.1
)
require (
github.com/1Password/connect-sdk-go v1.5.4-0.20250417152128-c154b387248b // indirect
github.com/1password/onepassword-sdk-go v0.4.1-beta.1 // indirect
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
github.com/VividCortex/ewma v1.2.0 // indirect
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d // indirect
github.com/andybalholm/brotli v1.2.1 // indirect
github.com/apex/log v1.9.0 // indirect
github.com/blacktop/go-dwarf v1.0.14 // indirect
github.com/blacktop/go-plist v1.0.2 // indirect
github.com/bodgit/plumbing v1.3.0 // indirect
github.com/bodgit/windows v1.0.1 // indirect
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0 // indirect
github.com/byteness/percent v0.2.2 // indirect
github.com/danieljoos/wincred v1.2.3 // indirect
github.com/dustin/go-humanize v1.1.0 // indirect
github.com/dvsekhvalnov/jose2go v1.8.0 // indirect
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 // indirect
github.com/extism/go-sdk v1.7.1 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/fatih/color v1.19.0 // indirect
github.com/frankban/quicktest v1.14.6 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/gobwas/glob v0.2.3 // indirect
github.com/godbus/dbus/v5 v5.2.2 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/jsonschema-go v0.4.3 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f // indirect
github.com/inconshreveable/mousetrap v1.0.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mattn/go-runewidth v0.0.14 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.22 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
github.com/noamcohen97/touchid-go v0.3.0 // indirect
github.com/opentracing/opentracing-go v1.2.0 // indirect
github.com/pierrec/lz4/v4 v4.1.29 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/rogpeppe/go-internal v1.14.1 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/stangelandcl/ppmd v0.1.0 // indirect
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 // indirect
github.com/tetratelabs/wazero v1.11.0 // indirect
github.com/uber/jaeger-client-go v2.30.0+incompatible // indirect
github.com/uber/jaeger-lib v2.4.1+incompatible // indirect
github.com/ulikunitz/xz v0.5.17 // indirect
github.com/vbauerster/mpb/v7 v7.5.3 // indirect
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
golang.org/x/crypto v0.52.0 // indirect
go4.org v0.0.0-20260112195520-a5071408f32f // indirect
golang.org/x/crypto v0.57.0 // indirect
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect
golang.org/x/mod v0.35.0 // indirect
golang.org/x/net v0.55.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/text v0.37.0 // indirect
golang.org/x/tools v0.44.0 // indirect
golang.org/x/mod v0.41.0 // indirect
golang.org/x/net v0.58.0 // indirect
golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/sync v0.23.0 // indirect
golang.org/x/time v0.15.0 // indirect
golang.org/x/tools v0.49.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/errgo.v1 v1.0.1 // indirect
gopkg.in/retry.v1 v1.0.3 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
+196 -50
View File
@@ -4,8 +4,33 @@ github.com/1password/onepassword-sdk-go v0.4.1-beta.1 h1:b/tt+bAXFXR5f3/irmPAayt
github.com/1password/onepassword-sdk-go v0.4.1-beta.1/go.mod h1:j/CbzhucTywjlYrd6SE6k0LcQaFZ2l8OLBsAsOYtvD0=
github.com/HdrHistogram/hdrhistogram-go v1.1.2 h1:5IcZpTvzydCQeHzK4Ef/D5rrSqwxob0t8PQPMybUNFM=
github.com/HdrHistogram/hdrhistogram-go v1.1.2/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo=
github.com/VividCortex/ewma v1.2.0 h1:f58SaIzcDXrSy3kWaHNvuJgJ3Nmz59Zji6XoJR/q1ow=
github.com/VividCortex/ewma v1.2.0/go.mod h1:nz4BbCtbLyFDeC9SUHbtcT5644juEuWfUAUnGx7j5l4=
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d h1:licZJFw2RwpHMqeKTCYkitsPqHNxTmd4SNR5r94FGM8=
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d/go.mod h1:asat636LX7Bqt5lYEZ27JNDcqxfjdBQuJ/MM4CN/Lzo=
github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eTWro=
github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/apex/log v1.9.0 h1:FHtw/xuaM8AgmvDDTI9fiwoAL25Sq2cxojnZICUU8l0=
github.com/apex/log v1.9.0/go.mod h1:m82fZlWIuiWzWP04XCTXmnX0xRkYYbCdYn8jbJeLBEA=
github.com/apex/logs v1.0.0/go.mod h1:XzxuLZ5myVHDy9SAmYpamKKRNApGj54PfYLcFrXqDwo=
github.com/aphistic/golf v0.0.0-20180712155816-02c07f170c5a/go.mod h1:3NqKYiepwy8kCu4PNA+aP7WUV72eXWJeP9/r3/K9aLE=
github.com/aphistic/sweet v0.2.0/go.mod h1:fWDlIh/isSE9n6EPsRmC0det+whmX6dJid3stzu0Xys=
github.com/avast/retry-go v3.0.0+incompatible h1:4SOWQ7Qs+oroOTQOYnAHqelpCO0biHSxpiH9JdtuBj0=
github.com/avast/retry-go v3.0.0+incompatible/go.mod h1:XtSnn+n/sHqQIpZ10K1qAevBhOOCWBLXXy3hyiqqBrY=
github.com/aws/aws-sdk-go v1.20.6/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
github.com/aybabtme/rgbterm v0.0.0-20170906152045-cc83f3b3ce59/go.mod h1:q/89r3U2H7sSsE2t6Kca0lfwTK8JdoNGS/yzM/4iH5I=
github.com/blacktop/go-dwarf v1.0.14 h1:OjmzfSgg/qAKckn2tWFebcgKgJ7HOqCj7bS+CiE1lrY=
github.com/blacktop/go-dwarf v1.0.14/go.mod h1:4W2FKgSFYcZLDwnR7k+apv5i3nrau4NGl9N6VQ9DSTo=
github.com/blacktop/go-macho v1.1.282 h1:DW3HYz5zVCT6+Jlp1+hxauYvEgxqZsGMvu8/1j4+Ibg=
github.com/blacktop/go-macho v1.1.282/go.mod h1:Hc5E2Lvt/U1VT+jOxr1O5l/LNFJeMYK4eAmDfazTiGc=
github.com/blacktop/go-plist v1.0.2 h1:DMX8uBiE308HWZkO9o37j7Z2b0neI3GSzN2caNa2zXk=
github.com/blacktop/go-plist v1.0.2/go.mod h1:fqVhCVVXVJWsIGY9QPgdK0mDWZD82HrRMfU5PanvdTA=
github.com/bodgit/plumbing v1.3.0 h1:pf9Itz1JOQgn7vEOE7v7nlEfBykYqvUYioC61TwWCFU=
github.com/bodgit/plumbing v1.3.0/go.mod h1:JOTb4XiRu5xfnmdnDJo6GmSbSbtSyufrsyZFByMtKEs=
github.com/bodgit/sevenzip v1.6.3 h1:t7K1jcgPnXdZyRHr68vq5L9vO/WmjDJEiGUwTR6i6gk=
github.com/bodgit/sevenzip v1.6.3/go.mod h1:a29jn+ZL8UfQr/L+8jJT1wmhCMulGOfaT5d1HWxwD5g=
github.com/bodgit/windows v1.0.1 h1:tF7K6KOluPYygXa3Z2594zxlkbKPAOvqr97etrGNIz4=
github.com/bodgit/windows v1.0.1/go.mod h1:a6JLwrB4KrTR5hBpp8FI9/9W9jJfeQ2h4XDXU74ZCdM=
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:HFl8GFmwK19hYuXB8OQ0rTO9WOCgZY9JUy964zaYawY=
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:9HlL8SWBRtCZE7sCNq+c3//H/oHywgSwtocmPTdOij8=
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0 h1:j59wGsxaBk6aFBuuYofk2oznMGZYyzFovjDqavlJHM8=
@@ -14,95 +39,172 @@ github.com/byteness/keyring v1.9.0 h1:9m+7pru+JkMJ8wxma5id5m6pSt2Zx/xPj77kyM+yAV
github.com/byteness/keyring v1.9.0/go.mod h1:a6CV8t/qfEUERPTP+dqeVfKgib2wz3PIYbMWRfmvmes=
github.com/byteness/percent v0.2.2 h1:vnIFh8WBR1xoC+U2etz0EMB1cgp+vsK6vynqTCeDziU=
github.com/byteness/percent v0.2.2/go.mod h1:nwavge92FhIyfnldz4YWZD8uxPVvdh8NlzLRd1VYRDs=
github.com/chengxilo/virtualterm v1.0.4 h1:Z6IpERbRVlfB8WkOmtbHiDbBANU7cimRIof7mk9/PwM=
github.com/chengxilo/virtualterm v1.0.4/go.mod h1:DyxxBZz/x1iqJjFxTFcr6/x+jSpqN0iwWCOK1q10rlY=
github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/deploymenttheory/go-macos-pkg v0.3.0 h1:1pbCbFpib7lzAdu0FUnCW5frhYtjEmqO1iNg0kIKthI=
github.com/deploymenttheory/go-macos-pkg v0.3.0/go.mod h1:aSMBLo4teBpMNx6bioyGfF22Kkdu1dodyWiyn0PLFjg=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/dvsekhvalnov/jose2go v1.8.0 h1:LqkkVKAlHFfH9LOEl5fe4p/zL02OhWE7pCufMBG2jLA=
github.com/dvsekhvalnov/jose2go v1.8.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU=
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 h1:idfl8M8rPW93NehFw5H1qqH8yG158t5POr+LX9avbJY=
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1/go.mod h1:C8DzXehI4zAbrdlbtOByKX6pfivJTBiV9Jjqv56Yd9Q=
github.com/ebitengine/purego v0.10.2 h1:W809HbnvzAxgdm+aOvlSekrM16wGCdT/e76+9tS7gzE=
github.com/ebitengine/purego v0.10.2/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/extism/go-sdk v1.7.1 h1:lWJos6uY+tRFdlIHR+SJjwFDApY7OypS/2nMhiVQ9Sw=
github.com/extism/go-sdk v1.7.1/go.mod h1:IT+Xdg5AZM9hVtpFUA+uZCJMge/hbvshl8bwzLtFyKA=
github.com/frankban/quicktest v1.2.2 h1:xfmOhhoH5fGPgbEAlhLpJH9p0z/0Qizio9osmvn9IUY=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/go-compressions/lzfse v0.3.0 h1:slxIjY9HeG2llJSoXTwTnQ+u/iKMbr2WHUwaNAl/2yI=
github.com/go-compressions/lzfse v0.3.0/go.mod h1:geg9IRFbMNHPgbm8xNwF3AnYTsldTX9YptJ0DOWzYv8=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.2.1-0.20190312032427-6f77996f0c42/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f h1:Fnl4pzx8SR7k7JuzyW8lEtSFH6EQ8xgcypgIn8pcGIE=
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=
github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
github.com/jpillora/backoff v0.0.0-20180909062703-3050d21c67d7/go.mod h1:2iMrUgbbvHEiQClaW2NsSzMyGHqN+rDFqY705q49KG0=
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a h1:45JtCyuNYE+QN9aPuR1ID9++BQU+NMTMudHSuaK0Las=
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a/go.mod h1:RVHtZuvrpETIepiNUrNlih2OynoFf1eM6DGC6dloXzk=
github.com/juju/persistent-cookiejar v1.0.0 h1:Ag7+QLzqC2m+OYXy2QQnRjb3gTkEBSZagZ6QozwT3EQ=
github.com/juju/persistent-cookiejar v1.0.0/go.mod h1:zrbmo4nBKaiP/Ez3F67ewkMbzGYfXyMvRtbOfuAwG0w=
github.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213/go.mod h1:vNUNkEQ1e29fT/6vq2aBdFsgNPmy8qMdSay1npru+Sw=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw=
github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/majd/go-apfs v1.0.29 h1:UogjWvwkvNIcDRjiEQvIpOxrK5PgFo48yRern2mnrVM=
github.com/majd/go-apfs v1.0.29/go.mod h1:gA+fjwBmzHsm5ubsWtRJJUdRcu/8qhyuAJ4jFGGNYdk=
github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/noamcohen97/touchid-go v0.3.0 h1:fcXxVCizysD7KHRR6hrURt3nyNIs5JBGSbOIidD/3wo=
github.com/noamcohen97/touchid-go v0.3.0/go.mod h1:X9MRNIBGEmPqwpDm1G3fQOAQX7fwBlhzUbnkDTxuta0=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo/v2 v2.5.0 h1:TRtrvv2vdQqzkwrQ1ke6vtXf7IK34RBUJafIy1wMwls=
github.com/onsi/ginkgo/v2 v2.5.0/go.mod h1:Luc4sArBICYCS8THh8v3i3i5CuSZO+RaQRaJoeNwomw=
github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/onsi/gomega v1.24.0 h1:+0glovB9Jd6z3VR+ScSwQqXVTIfJcGA9UBM8yzQxhqg=
github.com/onsi/gomega v1.24.0/go.mod h1:Z/NWtiqwBrwUt4/2loMmHL63EDLnYHmVbuBpDr2vQAg=
github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
github.com/pierrec/lz4/v4 v4.1.29 h1:CDQY6qZOLI4DW0Nx6R1vRrifrCeQHnNXkMb0hZWXFjg=
github.com/pierrec/lz4/v4 v4.1.29/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/clock v0.0.0-20190514195947-2896927a307a h1:3QH7VyOaaiUHNrA9Se4YQIRkDTCw1EJls9xTUCaCeRM=
github.com/rogpeppe/clock v0.0.0-20190514195947-2896927a307a/go.mod h1:4r5QyqhjIWCcK8DO4KMclc5Iknq5qVBAlbYYzAbUScQ=
github.com/rogpeppe/fastuuid v1.1.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.28.0 h1:MirSo27VyNi7RJYP3078AA1+Cyzd2GB66qy3aUHvsWY=
github.com/rs/zerolog v1.28.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/schollz/progressbar/v3 v3.13.1 h1:o8rySDYiQ59Mwzy2FELeHY5ZARXZTVJC7iHD6PEFUiE=
github.com/schollz/progressbar/v3 v3.13.1/go.mod h1:xvrbki8kfT1fzWzBT/UZd9L6GA+jdL7HAgq2RFnO6fQ=
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA=
github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/schollz/progressbar/v3 v3.19.1 h1:iv8BgwOvdML/S3p84uBpy/IMigv4U9594vPZYa2EdrU=
github.com/schollz/progressbar/v3 v3.19.1/go.mod h1:LFL7jqimKxfhero4K1eCkUr/6R39AgQeiPCJtlTWIW8=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/smartystreets/assertions v1.0.0/go.mod h1:kHHU4qYBaI3q23Pp3VPrmWhuIUrLW/7eUrw0BU5VaoM=
github.com/smartystreets/go-aws-auth v0.0.0-20180515143844-0c1422d1fdb9/go.mod h1:SnhjPscd9TpLiy1LpzGSKh3bXCfxxXuqd9xmQJy3slM=
github.com/smartystreets/gunit v1.0.0/go.mod h1:qwPWnhz6pn0NnRBP++URONOVyNkPyr4SauJk4cUOwJs=
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stangelandcl/ppmd v0.1.0 h1:0gOKtSdWyXxpRW55H/dZ3AgaJqjrtlIrAvsokFwp7ug=
github.com/stangelandcl/ppmd v0.1.0/go.mod h1:Rrv7M+/2P5jYr/GMLhBl7Ug3uJ1bUiVzr5LbbaV6xgY=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 h1:ZF+QBjOI+tILZjBaFj3HgFonKXUcwgJ4djLb6i42S3Q=
@@ -111,50 +213,94 @@ github.com/tetratelabs/wazero v1.11.0 h1:+gKemEuKCTevU4d7ZTzlsvgd1uaToIDtlQlmNbw
github.com/tetratelabs/wazero v1.11.0/go.mod h1:eV28rsN8Q+xwjogd7f4/Pp4xFxO7uOGbLcD/LzB1wiU=
github.com/thediveo/enumflag/v2 v2.0.1 h1:2bmWZPD2uSARDsOjXIdLRlNcYBFNF9xX0RNUNF2vKic=
github.com/thediveo/enumflag/v2 v2.0.1/go.mod h1:SyxyCNvv0QeRtZ7fjuaUz4FRLC3cWuDiD7QdORU0MGg=
github.com/tj/assert v0.0.0-20171129193455-018094318fb0/go.mod h1:mZ9/Rh9oLWpLLDRpvE+3b7gP/C2YyLFYxNmcLnPTMe0=
github.com/tj/assert v0.0.3 h1:Df/BlaZ20mq6kuai7f5z2TvPFiwC3xaWJSDQNiIS3Rk=
github.com/tj/assert v0.0.3/go.mod h1:Ne6X72Q+TB1AteidzQncjw9PabbMp4PBMZ1k+vd1Pvk=
github.com/tj/go-buffer v1.1.0/go.mod h1:iyiJpfFcR2B9sXu7KvjbT9fpM4mOelRSDTbntVj52Uc=
github.com/tj/go-elastic v0.0.0-20171221160941-36157cbbebc2/go.mod h1:WjeM0Oo1eNAjXGDx2yma7uG2XoyRZTq1uv3M/o7imD0=
github.com/tj/go-kinesis v0.0.0-20171128231115-08b17f58cb1b/go.mod h1:/yhzCV0xPfx6jb1bBgRFjl5lytqVqZXEaeqWP8lTEao=
github.com/tj/go-spin v1.1.0/go.mod h1:Mg1mzmePZm4dva8Qz60H2lHwmJ2loum4VIrLgVnKwh4=
github.com/uber/jaeger-client-go v2.30.0+incompatible h1:D6wyKGCecFaSRUpo8lCVbaOOb6ThwMmTEbhRwtKR97o=
github.com/uber/jaeger-client-go v2.30.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk=
github.com/uber/jaeger-lib v2.4.1+incompatible h1:td4jdvLcExb4cBISKIpHuGoVXh+dVKhn2Um6rjCsSsg=
github.com/uber/jaeger-lib v2.4.1+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U=
github.com/ulikunitz/xz v0.5.17 h1:flR0y/x1hgM8EGV1AW3Xll6T413G0glV8UfBwR617V4=
github.com/ulikunitz/xz v0.5.17/go.mod h1:H9Rt/W6/Qj27PGauhQc6nfCDy7vHpzsOThBSaYDoEhw=
github.com/vbauerster/mpb/v7 v7.5.3 h1:BkGfmb6nMrrBQDFECR/Q7RkKCw7ylMetCb4079CGs4w=
github.com/vbauerster/mpb/v7 v7.5.3/go.mod h1:i+h4QY6lmLvBNK2ah1fSreiw3ajskRlBp9AhY/PnuOE=
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo=
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU=
go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
go4.org v0.0.0-20260112195520-a5071408f32f h1:ziUVAjmTPwQMBmYR1tbdRFJPtTcQUI12fH9QQjfb0Sw=
go4.org v0.0.0-20260112195520-a5071408f32f/go.mod h1:ZRJnO5ZI4zAwMFp+dS1+V6J6MSyAowhRqAE+DPa1Xp0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfUMj69yZXw17EnHg/otA=
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA=
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220909162455-aba9fc2a8ff2/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/errgo.v1 v1.0.1 h1:oQFRXzZ7CkBGdm1XZm/EbQYaYNNEElNBOd09M6cqNso=
gopkg.in/errgo.v1 v1.0.1/go.mod h1:3NjfXwocQRYAPTq4/fzX+CwUhPRcR/azYRhj8G+LqMo=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/retry.v1 v1.0.3 h1:a9CArYczAVv6Qs6VGoLMio99GEs7kY9UzSF9+LD+iGs=
gopkg.in/retry.v1 v1.0.3/go.mod h1:FJkXmWiMaAo7xB+xhvDF59zhfjDWyzmyAxiT4dB688g=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20200605160147-a5ece683394c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
howett.net/plist v1.0.0 h1:7CrbWYbPPO/PyNy38b2EB/+gYbjCe2DXBxgtOOZbSQM=
howett.net/plist v1.0.0/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g=
howett.net/plist v1.0.1 h1:37GdZ8tP09Q35o9ych3ehygcsL+HqKSwzctveSlarvM=
howett.net/plist v1.0.1/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g=
+641
View File
@@ -0,0 +1,641 @@
//nolint:wsl // Binary format parsing is clearer when related bounds checks remain adjacent.
package assets
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/ecdh"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/hkdf"
"crypto/hmac"
"crypto/hpke"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/binary"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"github.com/go-compressions/lzfse"
)
const (
aeaMagic = "AEA1"
aeaSymmetricProfile = 1
aeaMainKeyInfo = "AEA_AMK"
aeaRootKeyInfo = "AEA_RHEK"
aeaClusterKeyInfo = "AEA_CK"
aeaClusterHeaderKeyInfo = "AEA_CHEK"
aeaSegmentKeyInfo = "AEA_SK"
aeaLZFSECompression = 'e'
aeaSHA256Checksum = 2
aeaDecodedSegmentCacheCount = 64
maxAEAAuthDataSize = 1 << 20
maxFCSKeySize = 64 << 10
)
type aeaHeader struct {
Magic [4]byte
ProfileAndScryptStrength uint32
AuthDataLength uint32
}
type aeaMAC [sha256.Size]byte
type encryptedAEARootHeader struct {
MAC aeaMAC
Data [48]byte
ClusterMAC aeaMAC
}
type aeaRootHeader struct {
FileSize uint64
EncryptedSize uint64
SegmentSize uint32
SegmentsPerCluster uint32
Compression uint8
Checksum uint8
_ [22]byte
}
type aeaHeaderKey struct {
MAC aeaMAC
Key [32]byte
IV [aes.BlockSize]byte
}
type aeaSegmentHeader struct {
DecompressedSize uint32
CompressedSize uint32
Checksum [sha256.Size]byte
}
type aeaSegment struct {
inputOffset int64
outputOffset int64
compressedSize uint32
decompressedSize uint32
checksum [sha256.Size]byte
mac aeaMAC
cluster uint32
index uint32
}
type aeaReader struct {
source io.ReaderAt
size int64
segmentSize uint32
mainKey []byte
segments []aeaSegment
cache map[int][]byte
cacheOrder []int
cacheMu sync.Mutex
}
type fcsResponse struct {
EncRequest string `json:"enc-request"`
WrappedKey string `json:"wrapped-key"`
}
func newAEAReader(ctx context.Context, client *http.Client, source io.ReaderAt, sourceSize int64) (*aeaReader, error) {
var header aeaHeader
if err := readBinaryAt(source, 0, &header); err != nil {
return nil, fmt.Errorf("read AEA header: %w", err)
}
if string(header.Magic[:]) != aeaMagic {
return nil, fmt.Errorf("invalid AEA magic %q", header.Magic)
}
if header.ProfileAndScryptStrength&0xffffff != aeaSymmetricProfile {
return nil, fmt.Errorf("unsupported AEA profile %d", header.ProfileAndScryptStrength&0xffffff)
}
if header.AuthDataLength > maxAEAAuthDataSize {
return nil, fmt.Errorf("AEA authentication data is too large: %d", header.AuthDataLength)
}
headerSize := int64(binary.Size(header))
authData := make([]byte, header.AuthDataLength)
if _, err := source.ReadAt(authData, headerSize); err != nil {
return nil, fmt.Errorf("read AEA authentication data: %w", err)
}
metadata, err := parseAEAMetadata(authData)
if err != nil {
return nil, err
}
symmetricKey, err := resolveAEASymmetricKey(ctx, client, metadata)
if err != nil {
return nil, err
}
mainSaltOffset := headerSize + int64(len(authData))
mainSalt := make([]byte, sha256.Size)
if _, err := source.ReadAt(mainSalt, mainSaltOffset); err != nil {
return nil, fmt.Errorf("read AEA main salt: %w", err)
}
mainKey, err := deriveAEAKey(symmetricKey, mainSalt, binary.LittleEndian.AppendUint32([]byte(aeaMainKeyInfo), header.ProfileAndScryptStrength), len(symmetricKey))
if err != nil {
return nil, fmt.Errorf("derive AEA main key: %w", err)
}
rootOffset := mainSaltOffset + int64(len(mainSalt))
var encryptedRoot encryptedAEARootHeader
if err := readBinaryAt(source, rootOffset, &encryptedRoot); err != nil {
return nil, fmt.Errorf("read encrypted AEA root header: %w", err)
}
rootKey, err := deriveAEAHeaderKey(mainKey, []byte(aeaRootKeyInfo))
if err != nil {
return nil, fmt.Errorf("derive AEA root key: %w", err)
}
rootSalt := make([]byte, 0, len(encryptedRoot.ClusterMAC)+len(authData))
rootSalt = append(rootSalt, encryptedRoot.ClusterMAC[:]...)
rootSalt = append(rootSalt, authData...)
computedRootMAC := calculateAEAMAC(rootKey.MAC[:], encryptedRoot.Data[:], rootSalt)
if !hmac.Equal(encryptedRoot.MAC[:], computedRootMAC[:]) {
return nil, errors.New("AEA root header failed authentication")
}
rootData, err := decryptAEACTR(encryptedRoot.Data[:], rootKey.Key[:], rootKey.IV[:])
if err != nil {
return nil, fmt.Errorf("decrypt AEA root header: %w", err)
}
var root aeaRootHeader
if err := binary.Read(bytes.NewReader(rootData), binary.LittleEndian, &root); err != nil {
return nil, fmt.Errorf("decode AEA root header: %w", err)
}
if root.FileSize == 0 || root.FileSize > ^uint64(0)>>1 {
return nil, fmt.Errorf("invalid AEA output size %d", root.FileSize)
}
if root.EncryptedSize != uint64(sourceSize) {
return nil, fmt.Errorf("AEA encrypted size is %d, expected %d", root.EncryptedSize, sourceSize)
}
if root.SegmentSize == 0 || root.SegmentsPerCluster == 0 {
return nil, errors.New("AEA has an invalid segment layout")
}
if root.Compression != aeaLZFSECompression || root.Checksum != aeaSHA256Checksum {
return nil, fmt.Errorf("unsupported AEA encoding: compression %q, checksum %d", root.Compression, root.Checksum)
}
reader := &aeaReader{
source: source,
size: int64(root.FileSize),
segmentSize: root.SegmentSize,
mainKey: mainKey,
segments: make([]aeaSegment, (root.FileSize+uint64(root.SegmentSize)-1)/uint64(root.SegmentSize)),
cache: make(map[int][]byte, aeaDecodedSegmentCacheCount),
}
clusterOffset := rootOffset + int64(binary.Size(encryptedRoot))
if err := reader.indexClusters(clusterOffset, encryptedRoot.ClusterMAC, root, sourceSize); err != nil {
return nil, err
}
return reader, nil
}
func parseAEAMetadata(data []byte) (map[string][]byte, error) {
metadata := make(map[string][]byte)
reader := bytes.NewReader(data)
for reader.Len() != 0 {
var length uint32
if err := binary.Read(reader, binary.LittleEndian, &length); err != nil {
return nil, fmt.Errorf("read AEA metadata length: %w", err)
}
if length < 5 || uint64(length-4) > uint64(reader.Len()) {
return nil, fmt.Errorf("invalid AEA metadata record length %d", length)
}
record := make([]byte, length-4)
if _, err := io.ReadFull(reader, record); err != nil {
return nil, fmt.Errorf("read AEA metadata record: %w", err)
}
key, value, ok := bytes.Cut(record, []byte{0})
if !ok || len(key) == 0 {
return nil, errors.New("invalid AEA metadata record")
}
metadata[string(key)] = value
}
return metadata, nil
}
// resolveAEASymmetricKey downloads the Apple-published FCS P-256 private key
// identified by the AEA metadata. That key is the HPKE recipient key for this
// image's wrapped symmetric key; the unwrapped key is then used to derive the
// AES and HMAC keys that decrypt and authenticate the AEA headers and segments.
// It is restore-image key material, not a user credential.
func resolveAEASymmetricKey(ctx context.Context, client *http.Client, metadata map[string][]byte) ([]byte, error) {
keyURLData, ok := metadata["com.apple.wkms.fcs-key-url"]
if !ok {
return nil, errors.New("AEA metadata does not contain an FCS key URL")
}
keyURL, err := url.Parse(string(keyURLData))
if err != nil || keyURL.Scheme != "https" || keyURL.Hostname() != "wkms-public.apple.com" {
return nil, fmt.Errorf("invalid Apple FCS key URL %q", keyURLData)
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, keyURL.String(), nil)
if err != nil {
return nil, fmt.Errorf("create Apple FCS key request: %w", err)
}
response, err := client.Do(request)
if err != nil {
return nil, fmt.Errorf("download Apple FCS key: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("download Apple FCS key: server returned %s", response.Status)
}
pemData, err := io.ReadAll(io.LimitReader(response.Body, maxFCSKeySize+1))
if err != nil {
return nil, fmt.Errorf("read Apple FCS key: %w", err)
}
if len(pemData) > maxFCSKeySize {
return nil, errors.New("apple FCS key response is too large")
}
block, _ := pem.Decode(pemData)
if block == nil {
return nil, errors.New("apple FCS key response is not PEM encoded")
}
privateKeyValue, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("parse Apple FCS private key: %w", err)
}
privateKey, ok := privateKeyValue.(*ecdsa.PrivateKey)
if !ok || privateKey.Curve != elliptic.P256() {
return nil, errors.New("apple FCS key is not a P-256 private key")
}
responseData, ok := metadata["com.apple.wkms.fcs-response"]
if !ok {
return nil, errors.New("AEA metadata does not contain an FCS response")
}
var wrapped fcsResponse
if err := json.Unmarshal(responseData, &wrapped); err != nil {
return nil, fmt.Errorf("parse AEA FCS response: %w", err)
}
encapsulation, err := base64.StdEncoding.DecodeString(wrapped.EncRequest)
if err != nil {
return nil, fmt.Errorf("decode AEA FCS encapsulation: %w", err)
}
wrappedKey, err := base64.StdEncoding.DecodeString(wrapped.WrappedKey)
if err != nil {
return nil, fmt.Errorf("decode AEA wrapped key: %w", err)
}
kem := hpke.DHKEM(ecdh.P256())
ecdhPrivateKey, err := privateKey.ECDH()
if err != nil {
return nil, fmt.Errorf("convert AEA FCS private key: %w", err)
}
hpkePrivateKey, err := kem.NewPrivateKey(ecdhPrivateKey.Bytes())
if err != nil {
return nil, fmt.Errorf("load AEA FCS private key: %w", err)
}
recipient, err := hpke.NewRecipient(encapsulation, hpkePrivateKey, hpke.HKDFSHA256(), hpke.AES256GCM(), nil)
if err != nil {
return nil, fmt.Errorf("initialize AEA FCS recipient: %w", err)
}
symmetricKey, err := recipient.Open(nil, wrappedKey)
if err != nil {
return nil, fmt.Errorf("unwrap AEA symmetric key: %w", err)
}
return symmetricKey, nil
}
func (r *aeaReader) indexClusters(offset int64, clusterMAC aeaMAC, root aeaRootHeader, sourceSize int64) error {
const segmentHeaderSize = 8 + sha256.Size
headerSize := int64(segmentHeaderSize*root.SegmentsPerCluster + sha256.Size + sha256.Size*root.SegmentsPerCluster)
outputSize := uint64(0)
clusterIndex := uint32(0)
for outputSize < root.FileSize {
if offset < 0 || headerSize > sourceSize-offset {
return errors.New("AEA cluster header extends beyond the encrypted image")
}
headerData := make([]byte, headerSize)
if _, err := r.source.ReadAt(headerData, offset); err != nil {
return fmt.Errorf("read AEA cluster %d header: %w", clusterIndex, err)
}
clusterKey, err := deriveAEAKey(r.mainKey, nil, binary.LittleEndian.AppendUint32([]byte(aeaClusterKeyInfo), clusterIndex), len(r.mainKey))
if err != nil {
return fmt.Errorf("derive AEA cluster %d key: %w", clusterIndex, err)
}
clusterHeaderKey, err := deriveAEAHeaderKey(clusterKey, []byte(aeaClusterHeaderKeyInfo))
if err != nil {
return fmt.Errorf("derive AEA cluster %d header key: %w", clusterIndex, err)
}
encryptedHeadersSize := int(segmentHeaderSize * root.SegmentsPerCluster)
encryptedHeaders := headerData[:encryptedHeadersSize]
var nextClusterMAC aeaMAC
copy(nextClusterMAC[:], headerData[encryptedHeadersSize:encryptedHeadersSize+sha256.Size])
segmentMACData := headerData[encryptedHeadersSize+sha256.Size:]
hmacSalt := make([]byte, 0, len(nextClusterMAC)+len(segmentMACData))
hmacSalt = append(hmacSalt, nextClusterMAC[:]...)
hmacSalt = append(hmacSalt, segmentMACData...)
computedMAC := calculateAEAMAC(clusterHeaderKey.MAC[:], encryptedHeaders, hmacSalt)
if !hmac.Equal(clusterMAC[:], computedMAC[:]) {
return fmt.Errorf("AEA cluster %d failed authentication", clusterIndex)
}
decryptedHeaders, err := decryptAEACTR(encryptedHeaders, clusterHeaderKey.Key[:], clusterHeaderKey.IV[:])
if err != nil {
return fmt.Errorf("decrypt AEA cluster %d headers: %w", clusterIndex, err)
}
dataOffset := offset + headerSize
for segmentIndex := range root.SegmentsPerCluster {
start := int(segmentIndex) * segmentHeaderSize
var segmentHeader aeaSegmentHeader
if err := binary.Read(bytes.NewReader(decryptedHeaders[start:start+segmentHeaderSize]), binary.LittleEndian, &segmentHeader); err != nil {
return fmt.Errorf("decode AEA cluster %d segment %d header: %w", clusterIndex, segmentIndex, err)
}
if segmentHeader.DecompressedSize == 0 {
if segmentHeader.CompressedSize != 0 {
return fmt.Errorf("AEA cluster %d segment %d has compressed data without output", clusterIndex, segmentIndex)
}
continue
}
if segmentHeader.DecompressedSize > root.SegmentSize || segmentHeader.CompressedSize == 0 {
return fmt.Errorf("AEA cluster %d segment %d has invalid sizes", clusterIndex, segmentIndex)
}
if int64(segmentHeader.CompressedSize) > sourceSize-dataOffset {
return fmt.Errorf("AEA cluster %d segment %d extends beyond the encrypted image", clusterIndex, segmentIndex)
}
var segmentMAC aeaMAC
copy(segmentMAC[:], segmentMACData[int(segmentIndex)*sha256.Size:(int(segmentIndex)+1)*sha256.Size])
globalIndex := uint64(clusterIndex)*uint64(root.SegmentsPerCluster) + uint64(segmentIndex)
if globalIndex >= uint64(len(r.segments)) {
return fmt.Errorf("AEA cluster %d segment %d is outside the declared output", clusterIndex, segmentIndex)
}
outputOffset := int64(globalIndex * uint64(root.SegmentSize))
if uint64(outputOffset)+uint64(segmentHeader.DecompressedSize) > root.FileSize {
return fmt.Errorf("AEA cluster %d segment %d extends beyond the declared output", clusterIndex, segmentIndex)
}
r.segments[globalIndex] = aeaSegment{
inputOffset: dataOffset,
outputOffset: outputOffset,
compressedSize: segmentHeader.CompressedSize,
decompressedSize: segmentHeader.DecompressedSize,
checksum: segmentHeader.Checksum,
mac: segmentMAC,
cluster: clusterIndex,
index: segmentIndex,
}
dataOffset += int64(segmentHeader.CompressedSize)
outputSize += uint64(segmentHeader.DecompressedSize)
if outputSize > root.FileSize {
return errors.New("AEA segment data exceeds the declared output size")
}
}
offset = dataOffset
clusterMAC = nextClusterMAC
clusterIndex++
}
if outputSize != root.FileSize {
return fmt.Errorf("AEA segment data has size %d, expected %d", outputSize, root.FileSize)
}
return nil
}
func (r *aeaReader) ReadAt(data []byte, offset int64) (int, error) {
if len(data) == 0 {
return 0, nil
}
if offset < 0 {
return 0, errors.New("negative AEA output offset")
}
if offset >= r.size {
return 0, io.EOF
}
wanted := len(data)
if remaining := r.size - offset; int64(wanted) > remaining {
wanted = int(remaining)
}
written := 0
for written < wanted {
segmentIndex := int((offset + int64(written)) / int64(r.segmentSize))
if segmentIndex >= len(r.segments) {
return written, errors.New("AEA segment index is incomplete")
}
segment := r.segments[segmentIndex]
if segment.decompressedSize == 0 {
return written, fmt.Errorf("AEA segment %d is missing", segmentIndex)
}
decoded, err := r.decodeSegment(segmentIndex, segment)
if err != nil {
return written, err
}
inside := int(offset + int64(written) - segment.outputOffset)
if inside < 0 || inside >= len(decoded) {
return written, errors.New("AEA segment has an invalid output offset")
}
count := min(wanted-written, len(decoded)-inside)
copy(data[written:written+count], decoded[inside:inside+count])
written += count
}
if wanted != len(data) {
return written, io.EOF
}
return written, nil
}
func (r *aeaReader) decodeSegment(cacheIndex int, segment aeaSegment) ([]byte, error) {
r.cacheMu.Lock()
defer r.cacheMu.Unlock()
if data, ok := r.cache[cacheIndex]; ok {
return data, nil
}
encrypted := make([]byte, segment.compressedSize)
if _, err := r.source.ReadAt(encrypted, segment.inputOffset); err != nil {
return nil, fmt.Errorf("read AEA cluster %d segment %d: %w", segment.cluster, segment.index, err)
}
clusterKey, err := deriveAEAKey(r.mainKey, nil, binary.LittleEndian.AppendUint32([]byte(aeaClusterKeyInfo), segment.cluster), len(r.mainKey))
if err != nil {
return nil, fmt.Errorf("derive AEA cluster %d key: %w", segment.cluster, err)
}
segmentKey, err := deriveAEAHeaderKey(clusterKey, binary.LittleEndian.AppendUint32([]byte(aeaSegmentKeyInfo), segment.index))
if err != nil {
return nil, fmt.Errorf("derive AEA cluster %d segment %d key: %w", segment.cluster, segment.index, err)
}
computedMAC := calculateAEAMAC(segmentKey.MAC[:], encrypted, nil)
if !hmac.Equal(segment.mac[:], computedMAC[:]) {
return nil, fmt.Errorf("AEA cluster %d segment %d failed authentication", segment.cluster, segment.index)
}
compressed, err := decryptAEACTR(encrypted, segmentKey.Key[:], segmentKey.IV[:])
if err != nil {
return nil, fmt.Errorf("decrypt AEA cluster %d segment %d: %w", segment.cluster, segment.index, err)
}
var decoded []byte
if segment.compressedSize == segment.decompressedSize {
decoded = compressed
} else {
decoded, err = lzfse.Decompress(compressed)
if err != nil && strings.Contains(err.Error(), "fse: stream too short") {
padded, e := padLZFSEStreams(compressed)
if e == nil {
decoded, err = lzfse.Decompress(padded)
}
}
if err != nil {
return nil, fmt.Errorf("decompress AEA cluster %d segment %d: %w", segment.cluster, segment.index, err)
}
if len(decoded) != int(segment.decompressedSize) {
return nil, fmt.Errorf("decompress AEA cluster %d segment %d: produced %d bytes, expected %d", segment.cluster, segment.index, len(decoded), segment.decompressedSize)
}
}
if sha256.Sum256(decoded) != segment.checksum {
return nil, fmt.Errorf("AEA cluster %d segment %d failed checksum verification", segment.cluster, segment.index)
}
if len(r.cacheOrder) == aeaDecodedSegmentCacheCount {
delete(r.cache, r.cacheOrder[0])
copy(r.cacheOrder, r.cacheOrder[1:])
r.cacheOrder = r.cacheOrder[:len(r.cacheOrder)-1]
}
r.cache[cacheIndex] = decoded
r.cacheOrder = append(r.cacheOrder, cacheIndex)
return decoded, nil
}
func deriveAEAKey(key, salt, info []byte, size int) ([]byte, error) {
derived, err := hkdf.Key(sha256.New, key, salt, string(info), size)
if err != nil {
return nil, fmt.Errorf("expand AEA key: %w", err)
}
return derived, nil
}
func deriveAEAHeaderKey(key, info []byte) (aeaHeaderKey, error) {
var headerKey aeaHeaderKey
derived, err := deriveAEAKey(key, nil, info, binary.Size(headerKey))
if err != nil {
return aeaHeaderKey{}, fmt.Errorf("derive AEA header key: %w", err)
}
if err := binary.Read(bytes.NewReader(derived), binary.LittleEndian, &headerKey); err != nil {
return aeaHeaderKey{}, fmt.Errorf("decode AEA header key: %w", err)
}
return headerKey, nil
}
func calculateAEAMAC(key, data, salt []byte) aeaMAC {
mac := hmac.New(sha256.New, key)
_, _ = mac.Write(salt)
_, _ = mac.Write(data)
var length [8]byte
binary.LittleEndian.PutUint64(length[:], uint64(len(salt)))
_, _ = mac.Write(length[:])
return aeaMAC(mac.Sum(nil))
}
func decryptAEACTR(data, key, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("initialize AEA cipher: %w", err)
}
decrypted := make([]byte, len(data))
cipher.NewCTR(block, iv).XORKeyStream(decrypted, data)
return decrypted, nil
}
func readBinaryAt(source io.ReaderAt, offset int64, value any) error {
size := binary.Size(value)
if size < 0 {
return errors.New("invalid binary value")
}
data := make([]byte, size)
if _, err := source.ReadAt(data, offset); err != nil {
return fmt.Errorf("read binary value: %w", err)
}
if err := binary.Read(bytes.NewReader(data), binary.LittleEndian, value); err != nil {
return fmt.Errorf("decode binary value: %w", err)
}
return nil
}
+872
View File
@@ -0,0 +1,872 @@
//nolint:wsl // Binary tree traversal is clearer when related bounds checks remain adjacent.
package assets
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"fmt"
"io"
"math"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"github.com/deploymenttheory/go-macos-pkg/pkg/lzbitmap"
"github.com/go-compressions/lzfse"
"github.com/majd/go-apfs"
"github.com/majd/go-apfs/pkg/disk"
"github.com/majd/go-apfs/pkg/disk/dmg"
"github.com/majd/go-apfs/types"
"github.com/majd/ipatool/v2/internal/sap/machimage"
)
const (
apfsObjectHeaderSize = 32
apfsObjectTypeBTree = 2
apfsObjectTypeNode = 3
apfsObjectTypeFSTree = 14
apfsObjectNoHeader = 0x20000000
apfsNodeRoot = 0x0001
apfsNodeNoHeader = 0x0010
apfsBlockSize = 4096
apfsMaximumTreeDepth = 32
decmpfsLZVN = 8
decmpfsLZFSE = 12
decmpfsLZBitmap = 14
decmpfsBlockSize = 64 << 10
)
type apfsExtractor struct {
device disk.Device
filesystem *apfs.APFS
volumeOMap types.BTreeNodePhys
rootTreeBase uint64
transactionID types.XidT
}
type apfsExtent struct {
logical uint64
physical uint64
length uint64
}
type apfsFile struct {
io.ReaderAt
size int64
}
func extractAPFSFiles(ctx context.Context, source io.ReaderAt, size int64, paths []string, destination string) error {
extractor, closeExtractor, err := newAPFSExtractor(source, size)
if err != nil {
return err
}
defer func() { _ = closeExtractor() }()
if err := os.MkdirAll(destination, 0o700); err != nil {
return fmt.Errorf("create Apple filesystem extraction directory: %w", err)
}
for _, path := range paths {
if err := ctx.Err(); err != nil {
return fmt.Errorf("extract Apple filesystem files: %w", err)
}
if err := extractor.extractImageFile(ctx, path, destination, filepath.Ext(path) != ".icxs"); err != nil {
return fmt.Errorf("extract %s from Apple filesystem: %w", path, err)
}
}
return nil
}
func newAPFSExtractor(source io.ReaderAt, size int64) (*apfsExtractor, func() error, error) {
device, closeDevice, err := openAPFSDevice(source, size)
if err != nil {
return nil, nil, err
}
filesystem, err := apfs.NewAPFS(device)
if err != nil {
_ = closeDevice()
return nil, nil, fmt.Errorf("open Apple filesystem: %w", err)
}
fail := func(err error) (*apfsExtractor, func() error, error) {
filesystem.Close()
_ = closeDevice()
return nil, nil, err
}
volumeOMap, ok := filesystem.Volume.OMap.Body.(types.OMap)
if !ok {
return fail(fmt.Errorf("apple filesystem volume has an invalid object map"))
}
if volumeOMap.Tree == nil {
return fail(fmt.Errorf("apple filesystem volume has no object-map tree"))
}
volumeOMapRoot, ok := volumeOMap.Tree.Body.(types.BTreeNodePhys)
if !ok {
return fail(fmt.Errorf("apple filesystem volume has an invalid object-map tree"))
}
extractor := &apfsExtractor{
device: device,
filesystem: filesystem,
volumeOMap: volumeOMapRoot,
rootTreeBase: uint64(filesystem.Volume.RootTreeOid),
transactionID: filesystem.Volume.OMap.Hdr.Xid,
}
closeExtractor := func() error {
filesystem.Close()
return closeDevice()
}
return extractor, closeExtractor, nil
}
func (e *apfsExtractor) extractImageFile(ctx context.Context, path, destination string, thin bool) (err error) {
file, err := e.openFile(ctx, path)
if err != nil {
return err
}
outputPath := filepath.Join(destination, filepath.Base(path))
output, err := os.OpenFile(outputPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
if err != nil {
return fmt.Errorf("create output: %w", err)
}
defer func() {
if closeErr := output.Close(); err == nil && closeErr != nil {
err = fmt.Errorf("close output: %w", closeErr)
}
if err != nil {
_ = os.Remove(outputPath)
}
}()
offset, size := int64(0), file.size
if thin {
offset, size, err = machimage.ARM64Range(file, file.size)
if err != nil {
return fmt.Errorf("select runtime image architecture: %w", err)
}
}
reader := &contextReader{ctx: ctx, reader: io.NewSectionReader(file, offset, size)}
if _, err := io.CopyN(output, reader, size); err != nil {
return fmt.Errorf("copy file data: %w", err)
}
if err := output.Sync(); err != nil {
return fmt.Errorf("sync output: %w", err)
}
return nil
}
func (e *apfsExtractor) openFile(ctx context.Context, path string) (*apfsFile, error) {
records, err := e.resolvePath(path)
if err != nil {
return nil, err
}
var inode *types.JInodeVal
var compression *types.DecmpfsDiskHeader
var resource *types.JXattrDstreamT
var extents []apfsExtent
for _, record := range records {
switch record.Hdr.GetType() {
case types.APFS_TYPE_INODE:
value, ok := record.Val.(types.JInodeVal)
if ok {
inode = &value
}
case types.APFS_TYPE_FILE_EXTENT:
key, keyOK := record.Key.(types.JFileExtentKeyT)
value, valueOK := record.Val.(types.JFileExtentValT)
if keyOK && valueOK {
extents = append(extents, apfsExtent{
logical: key.LogicalAddr,
physical: value.PhysBlockNum,
length: value.Length(),
})
}
case types.APFS_TYPE_XATTR:
key, keyOK := record.Key.(types.JXattrKeyT)
value, valueOK := record.Val.(types.JXattrValT)
if !keyOK || !valueOK {
continue
}
switch key.Name {
case types.DECMPFS_XATTR_NAME:
compression, err = types.GetDecmpfsHeader(record)
if err != nil {
return nil, fmt.Errorf("read compression metadata: %w", err)
}
case "com.apple.ResourceFork":
stream, ok := value.Data.(types.JXattrDstreamT)
if ok {
resource = &stream
}
}
}
}
if inode == nil {
return nil, fmt.Errorf("file has no inode record")
}
if compression != nil {
method := uint32(compression.CompressionType)
if method != decmpfsLZVN && method != decmpfsLZFSE && method != decmpfsLZBitmap {
return nil, fmt.Errorf("unsupported compression type %d", compression.CompressionType)
}
if resource == nil {
return nil, fmt.Errorf("compressed file has no resource fork")
}
extents, err = e.dataExtents(resource.XattrObjID)
if err != nil {
return nil, fmt.Errorf("read resource-fork extents: %w", err)
}
resourceReader, err := newAPFSExtentReader(e.device, extents, resource.DStream.Size)
if err != nil {
return nil, err
}
reader, err := newDecmpfsReader(ctx, resourceReader, resource.DStream.Size, compression.UncompressedSize, method)
if err != nil {
return nil, err
}
return &apfsFile{ReaderAt: reader, size: int64(compression.UncompressedSize)}, nil
}
size := inode.UncompressedSize
for _, field := range inode.Xfields {
if stream, ok := field.Field.(types.JDstreamT); ok {
size = stream.Size
break
}
}
if len(extents) == 0 && size != 0 {
extents, err = e.dataExtents(inode.PrivateID)
if err != nil {
return nil, fmt.Errorf("read file extents: %w", err)
}
}
reader, err := newAPFSExtentReader(e.device, extents, size)
if err != nil {
return nil, err
}
return &apfsFile{ReaderAt: reader, size: int64(size)}, nil
}
func (e *apfsExtractor) resolvePath(path string) ([]types.NodeEntry, error) {
objectID := uint64(types.FSROOT_OID)
for _, name := range strings.Split(strings.Trim(path, "/"), "/") {
records, err := e.recordsForObject(objectID)
if err != nil {
return nil, err
}
found := false
for _, record := range records {
if record.Hdr.GetType() != types.APFS_TYPE_DIR_REC {
continue
}
key, keyOK := record.Key.(types.JDrecHashedKeyT)
value, valueOK := record.Val.(types.JDrecVal)
if keyOK && valueOK && key.Name == name {
objectID = value.FileID
found = true
break
}
}
if !found {
return nil, fmt.Errorf("path component %q was not found", name)
}
}
return e.recordsForObject(objectID)
}
func (e *apfsExtractor) recordsForObject(objectID uint64) ([]types.NodeEntry, error) {
visited := make(map[uint64]struct{})
return e.collectRecords(e.filesystem.FSRootBtree, objectID, visited, 0)
}
func (e *apfsExtractor) collectRecords(node types.BTreeNodePhys, objectID uint64, visited map[uint64]struct{}, depth int) ([]types.NodeEntry, error) {
if depth > apfsMaximumTreeDepth {
return nil, fmt.Errorf("filesystem tree exceeds maximum depth")
}
if node.IsLeaf() {
var records []types.NodeEntry
for _, raw := range node.Entries {
record, ok := raw.(types.NodeEntry)
if ok && record.Hdr.GetID() == objectID {
records = append(records, record)
}
}
return records, nil
}
var records []types.NodeEntry
for index, raw := range node.Entries {
entry, ok := raw.(types.NodeEntry)
if !ok {
return nil, fmt.Errorf("filesystem tree contains an invalid index entry")
}
lower := entry.Hdr.GetID()
upper := ^uint64(0)
if index+1 < len(node.Entries) {
next, ok := node.Entries[index+1].(types.NodeEntry)
if !ok {
return nil, fmt.Errorf("filesystem tree contains an invalid index entry")
}
upper = next.Hdr.GetID()
}
if objectID < lower || objectID > upper {
continue
}
child, address, err := e.filesystemChild(entry)
if err != nil {
return nil, err
}
if _, seen := visited[address]; seen {
continue
}
visited[address] = struct{}{}
childRecords, err := e.collectRecords(child, objectID, visited, depth+1)
if err != nil {
return nil, err
}
records = append(records, childRecords...)
}
return records, nil
}
func (e *apfsExtractor) filesystemChild(entry types.NodeEntry) (types.BTreeNodePhys, uint64, error) {
var objectID types.OidT
var expectedHash *[sha256.Size]byte
switch value := entry.Val.(type) {
case types.BTreeNodeIndexNodeValT:
objectID = types.OidT(e.rootTreeBase + uint64(value.ChildOid))
expectedHash = &value.ChildHash
case uint64:
objectID = types.OidT(value)
default:
return types.BTreeNodePhys{}, 0, fmt.Errorf("sealed filesystem tree contains an invalid child reference")
}
mapping, err := e.volumeOMap.GetOMapEntry(e.device, objectID, e.transactionID)
if err != nil {
return types.BTreeNodePhys{}, 0, fmt.Errorf("resolve filesystem child %#x: %w", objectID, err)
}
if expectedHash != nil {
raw := make([]byte, apfsBlockSize)
if _, err := readAPFSBlock(e.device, raw, mapping.Val.Paddr); err != nil {
return types.BTreeNodePhys{}, 0, fmt.Errorf("read filesystem child %#x: %w", objectID, err)
}
if digest := sha256.Sum256(raw); digest != *expectedHash {
return types.BTreeNodePhys{}, 0, fmt.Errorf("filesystem child %#x failed SHA-256 verification", objectID)
}
}
object, err := types.ReadObj(e.device, mapping.Val.Paddr)
if err != nil {
return types.BTreeNodePhys{}, 0, fmt.Errorf("decode filesystem child %#x: %w", objectID, err)
}
child, ok := object.Body.(types.BTreeNodePhys)
if !ok {
return types.BTreeNodePhys{}, 0, fmt.Errorf("filesystem child %#x is not a tree node", objectID)
}
return child, mapping.Val.Paddr, nil
}
func (e *apfsExtractor) physicalExtents(objectID uint64) ([]apfsExtent, error) {
object, err := types.ReadObj(e.device, uint64(e.filesystem.Volume.FextTreeOid))
if err != nil {
return nil, fmt.Errorf("read physical extent tree: %w", err)
}
root, ok := object.Body.(types.BTreeNodePhys)
if !ok {
return nil, fmt.Errorf("physical extent tree root is not a tree node")
}
extents, err := e.collectPhysicalExtents(root, objectID, make(map[uint64]struct{}), 0)
if err != nil {
return nil, err
}
sort.Slice(extents, func(i, j int) bool { return extents[i].logical < extents[j].logical })
return extents, nil
}
func (e *apfsExtractor) dataExtents(objectID uint64) ([]apfsExtent, error) {
if e.filesystem.Volume.FextTreeOid != 0 {
return e.physicalExtents(objectID)
}
records, err := e.recordsForObject(objectID)
if err != nil {
return nil, err
}
var extents []apfsExtent
for _, record := range records {
if record.Hdr.GetType() != types.APFS_TYPE_FILE_EXTENT {
continue
}
key, keyOK := record.Key.(types.JFileExtentKeyT)
value, valueOK := record.Val.(types.JFileExtentValT)
if keyOK && valueOK {
extents = append(extents, apfsExtent{
logical: key.LogicalAddr,
physical: value.PhysBlockNum,
length: value.Length(),
})
}
}
sort.Slice(extents, func(i, j int) bool { return extents[i].logical < extents[j].logical })
return extents, nil
}
func (e *apfsExtractor) collectPhysicalExtents(node types.BTreeNodePhys, objectID uint64, visited map[uint64]struct{}, depth int) ([]apfsExtent, error) {
if depth > apfsMaximumTreeDepth {
return nil, fmt.Errorf("physical extent tree exceeds maximum depth")
}
if node.IsLeaf() {
var extents []apfsExtent
for _, raw := range node.Entries {
entry, ok := raw.(types.FextNodeEntry)
if ok && entry.Key.PrivateID == objectID {
extents = append(extents, apfsExtent{
logical: entry.Key.LogicalAddr,
physical: entry.Val.PhysBlockNum,
length: entry.Val.Length(),
})
}
}
return extents, nil
}
var extents []apfsExtent
for index, raw := range node.Entries {
entry, ok := raw.(types.OMapNodeEntry)
if !ok {
return nil, fmt.Errorf("physical extent tree contains an invalid index entry")
}
lower := uint64(entry.Key.Oid)
upper := ^uint64(0)
if index+1 < len(node.Entries) {
next, ok := node.Entries[index+1].(types.OMapNodeEntry)
if !ok {
return nil, fmt.Errorf("physical extent tree contains an invalid index entry")
}
upper = uint64(next.Key.Oid)
}
if objectID < lower || objectID > upper {
continue
}
if _, seen := visited[entry.PAddr]; seen {
continue
}
visited[entry.PAddr] = struct{}{}
object, err := types.ReadObj(e.device, entry.PAddr)
if err != nil {
return nil, fmt.Errorf("read physical extent child %#x: %w", entry.PAddr, err)
}
child, ok := object.Body.(types.BTreeNodePhys)
if !ok {
return nil, fmt.Errorf("physical extent child %#x is not a tree node", entry.PAddr)
}
childExtents, err := e.collectPhysicalExtents(child, objectID, visited, depth+1)
if err != nil {
return nil, err
}
extents = append(extents, childExtents...)
}
return extents, nil
}
func readAPFSBlock(device disk.Device, data []byte, physicalAddress uint64) (int, error) {
var count int
var err error
if raw, ok := device.(*readerDevice); ok {
count, err = raw.source.ReadAt(data, int64(physicalAddress*apfsBlockSize))
} else {
count, err = device.ReadAt(data, int64(physicalAddress*apfsBlockSize))
}
if err != nil {
return count, fmt.Errorf("read Apple filesystem block: %w", err)
}
return count, nil
}
type apfsExtentReader struct {
device disk.Device
extents []apfsExtent
size uint64
}
func newAPFSExtentReader(device disk.Device, extents []apfsExtent, size uint64) (*apfsExtentReader, error) {
if size > math.MaxInt64 {
return nil, fmt.Errorf("file size %d exceeds the supported maximum", size)
}
sort.Slice(extents, func(i, j int) bool { return extents[i].logical < extents[j].logical })
position := uint64(0)
for _, extent := range extents {
if extent.length == 0 || extent.logical != position || extent.physical > ^uint64(0)/apfsBlockSize {
return nil, fmt.Errorf("file has invalid or sparse physical extents")
}
physicalOffset := extent.physical * apfsBlockSize
if physicalOffset > device.GetSize() || extent.length > device.GetSize()-physicalOffset {
return nil, fmt.Errorf("file extent exceeds the Apple filesystem image")
}
position += extent.length
if position < extent.logical {
return nil, fmt.Errorf("file extent length overflows")
}
}
if position < size {
return nil, fmt.Errorf("file extents cover %d bytes, expected %d", position, size)
}
return &apfsExtentReader{device: device, extents: extents, size: size}, nil
}
func (r *apfsExtentReader) ReadAt(data []byte, offset int64) (int, error) {
if offset < 0 {
return 0, fmt.Errorf("negative file offset")
}
if len(data) == 0 {
return 0, nil
}
position := uint64(offset)
if position >= r.size {
return 0, io.EOF
}
written := 0
for written < len(data) && position < r.size {
index := sort.Search(len(r.extents), func(index int) bool {
extent := r.extents[index]
return extent.logical+extent.length > position
})
if index == len(r.extents) || position < r.extents[index].logical {
return written, io.ErrUnexpectedEOF
}
extent := r.extents[index]
available := min(extent.logical+extent.length-position, r.size-position)
count := min(uint64(len(data)-written), available)
physicalOffset := extent.physical*apfsBlockSize + position - extent.logical
n, err := r.device.ReadAt(data[written:written+int(count)], int64(physicalOffset))
written += n
position += uint64(n)
if err != nil {
return written, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
}
if n != int(count) {
return written, io.ErrUnexpectedEOF
}
}
if written != len(data) {
return written, io.EOF
}
return written, nil
}
type decmpfsReader struct {
ctx context.Context
source io.ReaderAt
outputSize uint64
method uint32
offsets []uint32
mu sync.Mutex
cache map[uint64][]byte
cacheOrder []uint64
}
func newDecmpfsReader(ctx context.Context, source io.ReaderAt, sourceSize, outputSize uint64, method uint32) (*decmpfsReader, error) {
if outputSize > math.MaxInt64 {
return nil, fmt.Errorf("compressed file size %d exceeds the supported maximum", outputSize)
}
if sourceSize < 8 {
return nil, fmt.Errorf("compressed resource fork is too small")
}
var first [4]byte
if _, err := source.ReadAt(first[:], 0); err != nil {
return nil, fmt.Errorf("read compression index: %w", err)
}
tableSize := uint64(binary.LittleEndian.Uint32(first[:]))
blockCount := (outputSize + decmpfsBlockSize - 1) / decmpfsBlockSize
expectedTableSize := (blockCount + 1) * 4
if tableSize != expectedTableSize || tableSize > sourceSize {
return nil, fmt.Errorf("compression index has size %d, expected %d", tableSize, expectedTableSize)
}
table := make([]byte, tableSize)
if _, err := source.ReadAt(table, 0); err != nil {
return nil, fmt.Errorf("read compression index: %w", err)
}
offsets := make([]uint32, blockCount+1)
for index := range offsets {
offsets[index] = binary.LittleEndian.Uint32(table[index*4:])
}
for index := uint64(0); index < blockCount; index++ {
start, end := uint64(offsets[index]), uint64(offsets[index+1])
if start < tableSize || end <= start || end > sourceSize || end-start > decmpfsBlockSize+1 {
return nil, fmt.Errorf("compressed block %d has invalid range %d..%d", index, start, end)
}
}
if uint64(offsets[len(offsets)-1]) != sourceSize {
return nil, fmt.Errorf("compressed blocks end at %d, expected %d", offsets[len(offsets)-1], sourceSize)
}
return &decmpfsReader{
ctx: ctx,
source: source,
outputSize: outputSize,
method: method,
offsets: offsets,
cache: make(map[uint64][]byte),
}, nil
}
func (r *decmpfsReader) ReadAt(data []byte, offset int64) (int, error) {
if offset < 0 {
return 0, fmt.Errorf("negative compressed file offset")
}
if len(data) == 0 {
return 0, nil
}
if err := r.ctx.Err(); err != nil {
return 0, err //nolint:wrapcheck // ReaderAt must preserve context cancellation.
}
position := uint64(offset)
if position >= r.outputSize {
return 0, io.EOF
}
wanted := len(data)
if remaining := r.outputSize - position; uint64(wanted) > remaining {
wanted = int(remaining)
}
written := 0
for written < wanted {
blockIndex := position / decmpfsBlockSize
block, err := r.block(blockIndex)
if err != nil {
return written, err
}
blockOffset := position % decmpfsBlockSize
count := min(wanted-written, len(block)-int(blockOffset))
copy(data[written:written+count], block[blockOffset:uint64(count)+blockOffset])
written += count
position += uint64(count)
}
if written != len(data) {
return written, io.EOF
}
return written, nil
}
func (r *decmpfsReader) block(index uint64) ([]byte, error) {
r.mu.Lock()
defer r.mu.Unlock()
if block, ok := r.cache[index]; ok {
return block, nil
}
if index+1 >= uint64(len(r.offsets)) {
return nil, io.EOF
}
if err := r.ctx.Err(); err != nil {
return nil, fmt.Errorf("read compressed file: %w", err)
}
start, end := uint64(r.offsets[index]), uint64(r.offsets[index+1])
compressed := make([]byte, end-start)
if _, err := r.source.ReadAt(compressed, int64(start)); err != nil {
return nil, fmt.Errorf("read compressed block %d: %w", index, err)
}
expected := min(uint64(decmpfsBlockSize), r.outputSize-index*decmpfsBlockSize)
plain, err := decompressBlock(compressed, r.method, int(expected))
if err != nil {
return nil, fmt.Errorf("decode compressed block %d: %w", index, err)
}
if uint64(len(plain)) != expected {
return nil, fmt.Errorf("decompressed block %d has size %d, expected %d", index, len(plain), expected)
}
const maximumCachedBlocks = 128
if len(r.cacheOrder) == maximumCachedBlocks {
delete(r.cache, r.cacheOrder[0])
r.cacheOrder = r.cacheOrder[1:]
}
r.cache[index] = plain
r.cacheOrder = append(r.cacheOrder, index)
return plain, nil
}
func decompressBlock(compressed []byte, method uint32, maximumSize int) ([]byte, error) {
switch method {
case decmpfsLZVN:
if compressed[0] == 0x06 {
return compressed[1:], nil
}
decoded, err := lzfse.DecompressLZVN(compressed, maximumSize)
if err != nil {
return nil, fmt.Errorf("decompress LZVN block: %w", err)
}
return decoded, nil
case decmpfsLZFSE:
if compressed[0] != 'b' {
return compressed[1:], nil
}
decoded, err := lzfse.Decompress(compressed)
if err != nil {
return nil, fmt.Errorf("decompress LZFSE block: %w", err)
}
return decoded, nil
case decmpfsLZBitmap:
if compressed[0] == 0xff {
return compressed[1:], nil
}
decoded, err := lzbitmap.Decompress(compressed)
if err != nil {
return nil, fmt.Errorf("decompress LZBITMAP block: %w", err)
}
return decoded, nil
default:
return nil, fmt.Errorf("unsupported compression type %d", method)
}
}
type contextReader struct {
ctx context.Context
reader io.Reader
}
func (r *contextReader) Read(data []byte) (int, error) {
if err := r.ctx.Err(); err != nil {
return 0, err //nolint:wrapcheck // Preserve context cancellation for io.CopyN.
}
return r.reader.Read(data) //nolint:wrapcheck // Reader adapters must preserve io.EOF.
}
func openAPFSDevice(source io.ReaderAt, size int64) (disk.Device, func() error, error) {
if size < 36 {
return nil, nil, fmt.Errorf("apple filesystem image is too small: %d", size)
}
header := make([]byte, 36)
if _, err := source.ReadAt(header, 0); err != nil {
return nil, nil, fmt.Errorf("read Apple filesystem header: %w", err)
}
if bytes.Equal(header[32:36], []byte("NXSB")) {
device := &readerDevice{source: source, size: uint64(size)}
return device, device.Close, nil
}
image, err := dmg.NewDMG(io.NewSectionReader(source, 0, size))
if err != nil {
return nil, nil, fmt.Errorf("open Apple disk image: %w", err)
}
return image, image.Close, nil
}
type readerDevice struct {
source io.ReaderAt
size uint64
}
func (d *readerDevice) Close() error {
return nil
}
func (d *readerDevice) ReadFile(writer *bufio.Writer, offset, length int64) error {
if offset < 0 || length < 0 || uint64(offset) > d.size || uint64(length) > d.size-uint64(offset) {
return fmt.Errorf("invalid Apple filesystem range %d+%d", offset, length)
}
if _, err := io.CopyN(writer, io.NewSectionReader(d.source, offset, length), length); err != nil {
return fmt.Errorf("copy Apple filesystem range: %w", err)
}
if err := writer.Flush(); err != nil {
return fmt.Errorf("flush Apple filesystem range: %w", err)
}
return nil
}
func (d *readerDevice) GetSize() uint64 {
return d.size
}
func (d *readerDevice) ReadAt(data []byte, offset int64) (int, error) {
count, err := d.source.ReadAt(data, offset)
if count != len(data) || len(data) != int(types.BLOCK_SIZE) || offset%int64(types.BLOCK_SIZE) != 0 {
return count, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
}
if !bytes.Equal(data[:apfsObjectHeaderSize], make([]byte, apfsObjectHeaderSize)) {
return count, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
}
flags := binary.LittleEndian.Uint16(data[apfsObjectHeaderSize:])
if flags&apfsNodeNoHeader == 0 {
return count, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
}
objectType := uint32(apfsObjectTypeNode)
if flags&apfsNodeRoot != 0 {
objectType = apfsObjectTypeBTree
}
// Sealed APFS tree nodes omit the normal object header. Add a synthetic
// header after their hash has been verified so go-apfs can decode them.
binary.LittleEndian.PutUint64(data[8:16], uint64(offset/int64(types.BLOCK_SIZE)))
binary.LittleEndian.PutUint32(data[24:28], apfsObjectNoHeader|objectType)
binary.LittleEndian.PutUint32(data[28:32], apfsObjectTypeFSTree)
binary.LittleEndian.PutUint64(data[:8], types.CreateChecksum(data))
return count, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
}
+435
View File
@@ -0,0 +1,435 @@
package assets
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"hash"
"io"
"io/fs"
"os"
"path/filepath"
"github.com/majd/ipatool/v2/internal/sap/machimage"
)
const (
macOSVersion = "27.0.1"
macOSBuild = "26A434"
macOSRestoreURL = "https://updates.cdn-apple.com/2026FallFCS/59241290-5d51-4ca8-9df4-31624b9a4eac/UniversalMac_27.0.1_26A434_Restore.ipsw"
assetCacheDirectory = "apple-assets-macos-27-26A434-arm64-v5"
legacyAssetCacheDirectory = "apple-assets-macos-27-26A434-arm64-v4"
)
type Bundle struct {
AppleMediaServices []byte
Commerce []byte
ADID []byte
CoreFP []byte
CoreFPICXS []byte
FairPlayD []byte
FairPlayKext []byte
}
type fileSpec struct {
name string
size int
digest [32]byte
}
var requiredFiles = []fileSpec{
{name: "AppleMediaServices", size: 14813888, digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4")},
{name: "commerce", size: 2735088, digest: mustDigest("c4b2088dd39aeb353f59cb57597902e8317aec66ae7da0414b03c5f932771343")},
{name: "adid", size: 3047808, digest: mustDigest("43419a206c28bc93ecb8884256088d18306a0a462350f83adbced8e60a94e390")},
{name: "CoreFP", size: 30764976, digest: mustDigest("afbc123e688a822d980d5816cc2b52f69fde669d1dca92cf85627e1cbee587f6")},
{name: "CoreFP.icxs", size: 7365344, digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b")},
{name: "fairplayd", size: 17389744, digest: mustDigest("1e58d37e9602dd0ca5e24b14762063b6c310248b4d3a94272771d815e4ea1784")},
{name: "FairPlayIOKit", size: 2132320, digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025")},
}
var legacyFiles = []fileSpec{
{
name: "AppleMediaServices",
size: 14813888,
digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4"),
},
{
name: "commerce",
size: 8092640,
digest: mustDigest("76de40a4a32f691947cb926ce3b128d2fc446f7cac9755f831c406cf5a316ac9"),
},
{
name: "adid",
size: 9797952,
digest: mustDigest("1fec225b6917206e3d9b00fe636c04878f82bfd06a87a4b6941711de60efab5b"),
},
{
name: "CoreFP",
size: 94842464,
digest: mustDigest("2c30fa2b5f695fd66c0360dce72f54757d03ddb7107549715c12cb359a003b46"),
},
{
name: "CoreFP.icxs",
size: 7365344,
digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b"),
},
{
name: "fairplayd",
size: 37689264,
digest: mustDigest("28b4c7b2a5a0409c5020da55fc3984713a8e2b0eec8557076c8717f7166d003e"),
},
{
name: "FairPlayIOKit",
size: 2132320,
digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025"),
},
}
type bundleLoader struct {
gate chan struct{}
installed *Bundle
resolve func(context.Context) (Bundle, error)
}
var defaultLoader = bundleLoader{gate: make(chan struct{}, 1), resolve: loadBundle}
// Load resolves and verifies the pinned macOS framework profile once per process.
// The returned slices are shared and must not be modified by callers.
func Load(ctx context.Context) (Bundle, error) {
return defaultLoader.load(ctx)
}
func (l *bundleLoader) load(ctx context.Context) (Bundle, error) {
if ctx == nil {
return Bundle{}, errors.New("apple asset context is nil")
}
if err := ctx.Err(); err != nil {
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
}
select {
case l.gate <- struct{}{}:
case <-ctx.Done():
return Bundle{}, fmt.Errorf("load Apple assets: %w", ctx.Err())
}
defer func() { <-l.gate }()
if err := ctx.Err(); err != nil {
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
}
if l.installed != nil {
return *l.installed, nil
}
bundle, err := l.resolve(ctx)
if err != nil {
return Bundle{}, err
}
if err := ctx.Err(); err != nil {
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
}
l.installed = &bundle
return bundle, nil
}
func loadBundle(ctx context.Context) (Bundle, error) {
directory, err := cacheDirectory()
if err != nil {
return Bundle{}, err
}
if bundle, found := loadCachedBundle(directory); found {
return bundle, nil
}
bundle, err := resolveRemoteImage(ctx)
if err != nil {
return Bundle{}, err
}
if err := writeCache(directory, bundle); err != nil {
return Bundle{}, fmt.Errorf("cache Apple SAP assets: %w", err)
}
return bundle, nil
}
// Keep only the architecture used by the emulator after verifying and caching
// the original files. Cloning releases the unused slices of universal binaries.
func compactBundle(bundle Bundle) (Bundle, error) {
for _, image := range []struct {
name string
data *[]byte
}{
{"AppleMediaServices", &bundle.AppleMediaServices},
{"commerce", &bundle.Commerce},
{"adid", &bundle.ADID},
{"CoreFP", &bundle.CoreFP},
{"fairplayd", &bundle.FairPlayD},
{"FairPlayIOKit", &bundle.FairPlayKext},
} {
data, err := compactImage(image.name, *image.data)
if err != nil {
return Bundle{}, err
}
*image.data = data
}
return bundle, nil
}
func compactImage(name string, input []byte) ([]byte, error) {
data, err := machimage.ARM64Slice(input)
if err != nil {
return nil, fmt.Errorf("select %s architecture: %w", name, err)
}
if len(data) != len(input) {
return bytes.Clone(data), nil
}
return data, nil
}
func cacheDirectory() (string, error) {
root, err := os.UserCacheDir()
if err != nil {
return "", fmt.Errorf("find user cache directory: %w", err)
}
return filepath.Join(root, "ipatool", "sap", assetCacheDirectory), nil
}
func loadCachedBundle(directory string) (Bundle, bool) {
if bundle, err := readCache(directory); err == nil {
return bundle, true
}
legacyDirectory := filepath.Join(filepath.Dir(directory), legacyAssetCacheDirectory)
bundle, err := readCacheSpecs(legacyDirectory, legacyFiles)
if err != nil {
return Bundle{}, false
}
if err := validate(bundle); err != nil {
return Bundle{}, false
}
// A verified legacy cache remains usable on read-only mounts. Persist the
// smaller representation when possible without requiring a new download.
_ = writeCache(directory, bundle)
return bundle, true
}
func readCache(directory string) (Bundle, error) {
return readCacheSpecs(directory, requiredFiles)
}
func readCacheSpecs(directory string, specs []fileSpec) (Bundle, error) {
files := make(map[string][]byte, len(specs))
for _, spec := range specs {
data, err := readCacheData(filepath.Join(directory, spec.name), spec.size, &spec)
if err != nil {
return Bundle{}, fmt.Errorf("read cached Apple SAP asset %s: %w", spec.name, err)
}
files[spec.name] = data
}
return bundleFrom(files), nil
}
func readCacheFile(path string, expectedSize int) ([]byte, error) {
return readCacheData(path, expectedSize, nil)
}
func readCacheData(path string, expectedSize int, spec *fileSpec) ([]byte, error) {
if expectedSize < 0 {
return nil, errors.New("invalid expected size")
}
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("open cached asset: %w", err)
}
defer file.Close()
info, err := file.Stat()
if err != nil {
return nil, fmt.Errorf("inspect cached asset: %w", err)
}
if info.Size() != int64(expectedSize) {
return nil, fmt.Errorf("has size %d, expected %d", info.Size(), expectedSize)
}
var reader io.Reader = file
var digest hash.Hash
if spec != nil {
digest = sha256.New()
reader = io.TeeReader(file, digest)
}
var data []byte
if spec != nil && spec.name != "CoreFP.icxs" {
data, err = machimage.ReadARM64(reader, expectedSize)
} else {
data = make([]byte, expectedSize)
_, err = io.ReadFull(reader, data)
}
if err != nil {
return nil, fmt.Errorf("read cached asset: %w", err)
}
var extra [1]byte
if count, err := io.ReadFull(file, extra[:]); err == nil || count != 0 {
return nil, fmt.Errorf("grew beyond expected size %d while being read", expectedSize)
} else if !errors.Is(err, io.EOF) {
return nil, fmt.Errorf("verify cached asset length: %w", err)
}
if spec != nil && !bytes.Equal(digest.Sum(nil), spec.digest[:]) {
return nil, fmt.Errorf("apple SAP asset %s failed integrity verification", spec.name)
}
return data, nil
}
func writeCache(directory string, bundle Bundle) error {
if err := validate(bundle); err != nil {
return err
}
if err := os.MkdirAll(directory, 0o700); err != nil {
return fmt.Errorf("create SAP asset cache: %w", err)
}
files := bundleFiles(bundle)
for _, spec := range requiredFiles {
if err := replaceFile(filepath.Join(directory, spec.name), files[spec.name]); err != nil {
return fmt.Errorf("write cached SAP asset %s: %w", spec.name, err)
}
}
return nil
}
func replaceFile(path string, data []byte) error {
temporary, err := os.CreateTemp(filepath.Dir(path), ".download-*")
if err != nil {
return fmt.Errorf("create temporary cache file: %w", err)
}
temporaryPath := temporary.Name()
defer os.Remove(temporaryPath)
if err := temporary.Chmod(0o600); err != nil {
_ = temporary.Close()
return fmt.Errorf("set cache file permissions: %w", err)
}
if _, err := temporary.Write(data); err != nil {
_ = temporary.Close()
return fmt.Errorf("write temporary cache file: %w", err)
}
if err := temporary.Close(); err != nil {
return fmt.Errorf("close temporary cache file: %w", err)
}
if err := os.Rename(temporaryPath, path); err == nil {
return nil
}
if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("remove existing cache file: %w", err)
}
if err := os.Rename(temporaryPath, path); err != nil {
return fmt.Errorf("install cache file: %w", err)
}
return nil
}
func validate(bundle Bundle) error {
files := bundleFiles(bundle)
for _, spec := range requiredFiles {
if err := validateFile(spec, files[spec.name]); err != nil {
return err
}
}
return nil
}
func validateFile(spec fileSpec, data []byte) error {
if len(data) != spec.size {
return fmt.Errorf("apple SAP asset %s has size %d, expected %d", spec.name, len(data), spec.size)
}
if sha256.Sum256(data) != spec.digest {
return fmt.Errorf("apple SAP asset %s failed integrity verification", spec.name)
}
return nil
}
func bundleFrom(files map[string][]byte) Bundle {
return Bundle{
AppleMediaServices: files["AppleMediaServices"],
Commerce: files["commerce"],
ADID: files["adid"],
CoreFP: files["CoreFP"],
CoreFPICXS: files["CoreFP.icxs"],
FairPlayD: files["fairplayd"],
FairPlayKext: files["FairPlayIOKit"],
}
}
func bundleFiles(bundle Bundle) map[string][]byte {
return map[string][]byte{
"AppleMediaServices": bundle.AppleMediaServices,
"commerce": bundle.Commerce,
"adid": bundle.ADID,
"CoreFP": bundle.CoreFP,
"CoreFP.icxs": bundle.CoreFPICXS,
"fairplayd": bundle.FairPlayD,
"FairPlayIOKit": bundle.FairPlayKext,
}
}
func mustDigest(value string) [32]byte {
var digest [32]byte
decoded, err := hex.DecodeString(value)
if err != nil {
panic(err)
}
if len(decoded) != len(digest) {
panic("invalid SHA-256 length")
}
copy(digest[:], decoded)
return digest
}
+13
View File
@@ -0,0 +1,13 @@
package assets
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestAssetsGinkgo(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "SAP Assets Suite")
}
+49
View File
@@ -0,0 +1,49 @@
package assets
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
)
func TestReadCacheFile(t *testing.T) {
tests := []struct {
name string
data []byte
expectedSize int
wantErr string
}{
{name: "exact size", data: []byte("12345678"), expectedSize: 8},
{name: "too short", data: []byte("1234"), expectedSize: 8, wantErr: "has size 4, expected 8"},
{name: "too large", data: bytes.Repeat([]byte{1}, 64), expectedSize: 8, wantErr: "has size 64, expected 8"},
{name: "invalid expected size", expectedSize: -1, wantErr: "invalid expected size"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "asset")
if err := os.WriteFile(path, test.data, 0o600); err != nil {
t.Fatal(err)
}
got, err := readCacheFile(path, test.expectedSize)
if test.wantErr == "" {
if err != nil {
t.Fatalf("readCacheFile() error = %v", err)
}
if !bytes.Equal(got, test.data) {
t.Fatalf("readCacheFile() = %q, want %q", got, test.data)
}
return
}
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
t.Fatalf("readCacheFile() error = %v, want error containing %q", err, test.wantErr)
}
})
}
}
+122
View File
@@ -0,0 +1,122 @@
package assets
import (
"context"
"errors"
"sync"
"sync/atomic"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Verified bundle cache", func() {
It("shares one successful load across concurrent callers", func() {
var calls atomic.Int32
entered, release := make(chan struct{}), make(chan struct{})
data := []byte("verified bundle")
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
calls.Add(1)
close(entered)
<-release
return Bundle{CoreFP: data}, nil
}}
var workers sync.WaitGroup
results := make(chan Bundle, 8)
failures := make(chan error, 8)
for range 8 {
workers.Go(func() {
bundle, err := loader.load(context.Background())
results <- bundle
failures <- err
})
}
Eventually(entered).Should(BeClosed())
close(release)
workers.Wait()
Expect(calls.Load()).To(Equal(int32(1)))
for range 8 {
Expect(<-failures).NotTo(HaveOccurred())
Expect(&(<-results).CoreFP[0]).To(BeIdenticalTo(&data[0]))
}
})
It("lets a waiting caller cancel without interrupting the load", func() {
entered, release := make(chan struct{}), make(chan struct{})
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
close(entered)
<-release
return Bundle{CoreFP: []byte("ready")}, nil
}}
done := make(chan error, 1)
go func() { _, err := loader.load(context.Background()); done <- err }()
Eventually(entered).Should(BeClosed())
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
_, err := loader.load(ctx)
Expect(errors.Is(err, context.DeadlineExceeded)).To(BeTrue())
close(release)
Eventually(done).Should(Receive(BeNil()))
bundle, err := loader.load(context.Background())
Expect(err).NotTo(HaveOccurred())
Expect(string(bundle.CoreFP)).To(Equal("ready"))
})
It("retries failed loads", func() {
calls := 0
failed := errors.New("temporary failure")
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
calls++
if calls == 1 {
return Bundle{}, failed
}
return Bundle{CoreFP: []byte("ready")}, nil
}}
_, err := loader.load(context.Background())
Expect(err).To(MatchError(failed))
bundle, err := loader.load(context.Background())
Expect(err).NotTo(HaveOccurred())
Expect(string(bundle.CoreFP)).To(Equal("ready"))
Expect(calls).To(Equal(2))
})
It("does not publish a load canceled before completion", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
calls := 0
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
calls++
cancel()
return Bundle{CoreFP: []byte("ready")}, nil
}}
_, err := loader.load(ctx)
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
Expect(loader.installed).To(BeNil())
_, err = loader.load(context.Background())
Expect(err).NotTo(HaveOccurred())
Expect(calls).To(Equal(2))
})
It("rejects nil and canceled contexts even after a successful load", func() {
calls := 0
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
calls++
return Bundle{}, nil
}}
_, err := loader.load(nil) //nolint:staticcheck // Verify invalid caller input.
Expect(err).To(MatchError(ContainSubstring("context is nil")))
_, err = loader.load(context.Background())
Expect(err).NotTo(HaveOccurred())
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err = loader.load(ctx)
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
Expect(calls).To(Equal(1))
})
})
+68
View File
@@ -0,0 +1,68 @@
package assets
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"os"
"path/filepath"
"github.com/blacktop/go-macho/types"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Runtime bundle compaction", func() {
It("retains independent arm64e images and preserves thin images and ICXS", func() {
fat := make([]byte, 32)
for i, value := range []uint32{types.MagicFat.Int(), 1, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 28, 4, 0} {
binary.BigEndian.PutUint32(fat[i*4:], value)
}
copy(fat[28:], "arm!")
thin, icxs := []byte("thin"), []byte("ICXS")
bundle := Bundle{CoreFP: fat, Commerce: fat, ADID: fat, FairPlayD: fat, AppleMediaServices: thin, FairPlayKext: thin, CoreFPICXS: icxs}
original := bytes.Clone(fat)
compact, err := compactBundle(bundle)
Expect(err).NotTo(HaveOccurred())
for _, data := range [][]byte{compact.CoreFP, compact.Commerce, compact.ADID, compact.FairPlayD} {
Expect(string(data)).To(Equal("arm!"))
Expect(&data[0]).NotTo(BeIdenticalTo(&fat[28]))
Expect(cap(data)).To(BeNumerically("<", len(fat)))
}
Expect(&compact.AppleMediaServices[0]).To(BeIdenticalTo(&thin[0]))
Expect(&compact.FairPlayKext[0]).To(BeIdenticalTo(&thin[0]))
Expect(&compact.CoreFPICXS[0]).To(BeIdenticalTo(&icxs[0]))
Expect(fat).To(Equal(original))
Expect(bundle.CoreFP).To(HaveLen(32))
})
It("verifies the entire cached file before discarding unused architectures", func() {
fat := make([]byte, 40)
for i, value := range []uint32{types.MagicFat.Int(), 1, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 28, 4, 0} {
binary.BigEndian.PutUint32(fat[i*4:], value)
}
copy(fat[28:], "arm!unused!!")
originalSpecs := requiredFiles
DeferCleanup(func() { requiredFiles = originalSpecs })
requiredFiles = []fileSpec{{name: "CoreFP", size: len(fat), digest: sha256.Sum256(fat)}}
directory := GinkgoT().TempDir()
path := filepath.Join(directory, "CoreFP")
Expect(os.WriteFile(path, fat, 0o600)).To(Succeed())
bundle, err := readCache(directory)
Expect(err).NotTo(HaveOccurred())
Expect(string(bundle.CoreFP)).To(Equal("arm!"))
cached, err := os.ReadFile(path)
Expect(err).NotTo(HaveOccurred())
Expect(cached).To(Equal(fat))
fat[len(fat)-1] ^= 0xff
Expect(os.WriteFile(path, fat, 0o600)).To(Succeed())
_, err = readCache(directory)
Expect(err).To(MatchError(ContainSubstring("failed integrity verification")))
})
It("rejects invalid universal images", func() {
fat := make([]byte, 4)
binary.BigEndian.PutUint32(fat, types.MagicFat.Int())
_, err := compactBundle(Bundle{CoreFP: fat})
Expect(err).To(MatchError(ContainSubstring("select CoreFP architecture")))
})
})
+691
View File
@@ -0,0 +1,691 @@
//nolint:wsl // Binary format parsing is clearer when related bounds checks remain adjacent.
package assets
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"os"
"strings"
"github.com/blacktop/go-macho"
"github.com/blacktop/go-macho/pkg/fixupchains"
machotypes "github.com/blacktop/go-macho/types"
)
const (
dyldHeaderSize = 568
dyldMappingSize = 56
dyldImageInfoSize = 32
dyldSubcacheEntrySize = 56
dyldMaximumMappings = 64
dyldMaximumImages = 100_000
dyldMaximumSubcaches = 128
dyldMaximumPathLength = 4096
dyldSlideInfo5Size = 24
dyldMachHeader64Size = 32
dyldMachSegment64Command = 0x19
dyldMaximumLoadCommandsSize = 16 << 20
dyldMaximumSlideChainPointers = 1 << 16
)
type dyldCache struct {
members []*dyldCacheMember
primary *dyldCacheMember
slide5 *dyldSlideInfo5
relativeSelectorBase uint64
}
type dyldCacheMember struct {
file io.ReaderAt
close func() error
size int64
uuid [16]byte
mappings []dyldCacheMapping
}
type dyldCacheMapping struct {
member *dyldCacheMember
address uint64
size uint64
fileOffset uint64
slideInfoOffset uint64
slideInfoSize uint64
}
type dyldSlideInfo5 struct {
pageSize uint32
pageStartsCount uint32
valueAdd uint64
}
type dyldCacheFile struct {
reader io.ReaderAt
size int64
close func() error
}
type dyldCacheOpener func(suffix string) (*dyldCacheFile, error)
type dyldImage struct {
member *dyldCacheMember
address uint64
offset uint64
}
type dyldRebase struct {
address uint64
target uint64
}
func extractDyldImageFromFiles(opener dyldCacheOpener, imagePath, outputPath string) error {
cache, err := openDyldCache(opener)
if err != nil {
return fmt.Errorf("open shared cache: %w", err)
}
defer cache.Close()
image, err := cache.image(imagePath)
if err != nil {
return fmt.Errorf("find %s in shared cache: %w", imagePath, err)
}
imageMachO, err := cache.openImage(image, machotypes.LC_SYMTAB, machotypes.LC_DYSYMTAB)
if err != nil {
return fmt.Errorf("read %s from shared cache: %w", imagePath, err)
}
defer imageMachO.Close()
if err = cache.imageSymbols(image, imageMachO); err != nil {
return fmt.Errorf("read %s symbols: %w", imagePath, err)
}
var chainedFixups *fixupchains.DyldChainedFixups
if imageMachO.HasFixups() {
chainedFixups, err = imageMachO.DyldChainedFixups()
if err != nil {
return fmt.Errorf("read %s chained fixups: %w", imagePath, err)
}
}
if err := imageMachO.Export(outputPath, chainedFixups, imageMachO.GetBaseAddress(), nil); err != nil {
return fmt.Errorf("export %s from shared cache: %w", imagePath, err)
}
if err := cache.applySlide(outputPath); err != nil {
return fmt.Errorf("apply %s shared-cache pointers: %w", imagePath, err)
}
return nil
}
func (c *dyldCache) openImage(image *dyldImage, excluding ...machotypes.LoadCmd) (*macho.File, error) {
linkeditAddress, err := image.linkeditAddress()
if err != nil {
return nil, err
}
linkedit, err := c.mappingForAddress(linkeditAddress)
if err != nil {
return nil, err
}
reader := &dyldCacheReader{cache: c, member: linkedit.member, offset: 0}
converter := machotypes.VMAddrConverter{
Converter: c.slidePointer,
VMAddr2Offet: func(address uint64) (uint64, error) {
mapping, err := c.mappingForAddress(address)
if err != nil {
return 0, err
}
return mapping.fileOffset + address - mapping.address, nil
},
Offet2VMAddr: func(offset uint64) (uint64, error) {
return c.addressForOffset(image.member, offset)
},
}
sectionReader := machotypes.NewCustomSectionReader(image.member.file, &converter, 0, image.member.size)
file, err := macho.NewFile(
io.NewSectionReader(image.member.file, int64(image.offset), image.member.size-int64(image.offset)),
macho.FileConfig{
Offset: int64(image.offset),
SectionReader: sectionReader,
CacheReader: reader,
VMAddrConverter: converter,
RelativeSelectorBase: c.relativeSelectorBase,
LoadExcluding: excluding,
},
)
if err != nil {
return nil, fmt.Errorf("parse shared-cache image: %w", err)
}
return file, nil
}
func openDyldCache(opener dyldCacheOpener) (*dyldCache, error) {
primary, header, err := openDyldCacheMember(opener, "")
if err != nil {
return nil, err
}
cache := &dyldCache{members: []*dyldCacheMember{primary}, primary: primary}
complete := false
defer func() {
if !complete {
_ = cache.Close()
}
}()
subcacheOffset := uint64(binary.LittleEndian.Uint32(header[392:]))
subcacheCount := uint64(binary.LittleEndian.Uint32(header[396:]))
if subcacheCount > dyldMaximumSubcaches || subcacheCount > 0 && !validDyldRange(primary.size, subcacheOffset, subcacheCount*dyldSubcacheEntrySize) {
return nil, fmt.Errorf("shared cache has an invalid subcache table")
}
entries := make([]byte, subcacheCount*dyldSubcacheEntrySize)
if len(entries) > 0 {
if _, err := primary.file.ReadAt(entries, int64(subcacheOffset)); err != nil {
return nil, fmt.Errorf("read shared-cache subcache table: %w", err)
}
}
for index := uint64(0); index < subcacheCount; index++ {
entry := entries[index*dyldSubcacheEntrySize : (index+1)*dyldSubcacheEntrySize]
suffix := strings.TrimRight(string(entry[24:56]), "\x00")
if suffix == "" || strings.ContainsAny(suffix, `/\\`) {
return nil, fmt.Errorf("shared cache has an invalid subcache suffix")
}
member, _, err := openDyldCacheMember(opener, suffix)
if err != nil {
return nil, fmt.Errorf("open shared-cache member %s: %w", suffix, err)
}
if !bytes.Equal(member.uuid[:], entry[:16]) {
_ = member.close()
return nil, fmt.Errorf("shared-cache member %s has an unexpected UUID", suffix)
}
cache.members = append(cache.members, member)
}
for _, member := range cache.members {
for _, mapping := range member.mappings {
if mapping.slideInfoSize == 0 {
continue
}
version, err := readDyldSlideVersion(mapping)
if err != nil {
return nil, err
}
if version != 5 {
return nil, fmt.Errorf("unsupported shared-cache slide version %d", version)
}
slide, err := readDyldSlideInfo5(mapping)
if err != nil {
return nil, err
}
if cache.slide5 == nil {
cache.slide5 = slide
} else if cache.slide5.pageSize != slide.pageSize || cache.slide5.valueAdd != slide.valueAdd {
return nil, fmt.Errorf("shared-cache members use incompatible slide information")
}
}
}
if cache.slide5 == nil {
return nil, fmt.Errorf("shared cache has no slide information")
}
complete = true
return cache, nil
}
func openDyldCacheMember(opener dyldCacheOpener, suffix string) (*dyldCacheMember, []byte, error) {
opened, err := opener(suffix)
if err != nil {
return nil, nil, err
}
fail := func(err error) (*dyldCacheMember, []byte, error) {
_ = opened.close()
return nil, nil, err
}
if opened.size < dyldHeaderSize {
return fail(fmt.Errorf("shared-cache member is too small"))
}
header := make([]byte, dyldHeaderSize)
if _, err := opened.reader.ReadAt(header, 0); err != nil {
return fail(err)
}
magic := strings.TrimRight(string(header[:16]), "\x00")
if magic != "dyld_v1 arm64e" {
return fail(fmt.Errorf("unsupported shared-cache format %q", magic))
}
mappingOffset := uint64(binary.LittleEndian.Uint32(header[312:]))
mappingCount := uint64(binary.LittleEndian.Uint32(header[316:]))
if mappingCount == 0 || mappingCount > dyldMaximumMappings || !validDyldRange(opened.size, mappingOffset, mappingCount*dyldMappingSize) {
return fail(fmt.Errorf("shared-cache member has an invalid mapping table"))
}
mappingData := make([]byte, mappingCount*dyldMappingSize)
if _, err := opened.reader.ReadAt(mappingData, int64(mappingOffset)); err != nil {
return fail(err)
}
member := &dyldCacheMember{file: opened.reader, close: opened.close, size: opened.size}
copy(member.uuid[:], header[88:104])
for index := uint64(0); index < mappingCount; index++ {
data := mappingData[index*dyldMappingSize : (index+1)*dyldMappingSize]
mapping := dyldCacheMapping{
member: member,
address: binary.LittleEndian.Uint64(data[0:]),
size: binary.LittleEndian.Uint64(data[8:]),
fileOffset: binary.LittleEndian.Uint64(data[16:]),
slideInfoOffset: binary.LittleEndian.Uint64(data[24:]),
slideInfoSize: binary.LittleEndian.Uint64(data[32:]),
}
if mapping.size == 0 || mapping.address+mapping.size < mapping.address || !validDyldRange(opened.size, mapping.fileOffset, mapping.size) || mapping.slideInfoSize != 0 && !validDyldRange(opened.size, mapping.slideInfoOffset, mapping.slideInfoSize) {
return fail(fmt.Errorf("shared-cache member has an invalid mapping"))
}
member.mappings = append(member.mappings, mapping)
}
return member, header, nil
}
func validDyldRange(size int64, offset, length uint64) bool {
return size >= 0 && offset <= uint64(size) && length <= uint64(size)-offset
}
func (c *dyldCache) Close() error {
var first error
for _, member := range c.members {
if err := member.close(); err != nil && first == nil {
first = err
}
}
return first
}
func (c *dyldCache) image(path string) (*dyldImage, error) {
header := make([]byte, dyldHeaderSize)
if _, err := c.primary.file.ReadAt(header, 0); err != nil {
return nil, fmt.Errorf("read shared-cache header: %w", err)
}
imagesOffset := uint64(binary.LittleEndian.Uint32(header[448:]))
imagesCount := uint64(binary.LittleEndian.Uint32(header[452:]))
if imagesCount == 0 || imagesCount > dyldMaximumImages || !validDyldRange(c.primary.size, imagesOffset, imagesCount*dyldImageInfoSize) {
return nil, fmt.Errorf("shared cache has an invalid image table")
}
images := make([]byte, imagesCount*dyldImageInfoSize)
if _, err := c.primary.file.ReadAt(images, int64(imagesOffset)); err != nil {
return nil, fmt.Errorf("read shared-cache image table: %w", err)
}
for index := uint64(0); index < imagesCount; index++ {
data := images[index*dyldImageInfoSize : (index+1)*dyldImageInfoSize]
address := binary.LittleEndian.Uint64(data)
pathOffset := uint64(binary.LittleEndian.Uint32(data[24:]))
name, err := readDyldCString(c.primary.file, c.primary.size, pathOffset)
if err != nil {
return nil, err
}
if name != path {
continue
}
mapping, err := c.mappingForAddress(address)
if err != nil {
return nil, err
}
return &dyldImage{
member: mapping.member,
address: address,
offset: mapping.fileOffset + address - mapping.address,
}, nil
}
return nil, fmt.Errorf("image was not found")
}
func readDyldCString(file io.ReaderAt, size int64, offset uint64) (string, error) {
if !validDyldRange(size, offset, 1) {
return "", fmt.Errorf("shared cache contains an invalid string offset")
}
limit := min(uint64(dyldMaximumPathLength), uint64(size)-offset)
data := make([]byte, limit)
n, err := file.ReadAt(data, int64(offset))
if err != nil && err != io.EOF {
return "", fmt.Errorf("read shared-cache string: %w", err)
}
data = data[:n]
if end := bytes.IndexByte(data, 0); end >= 0 {
return string(data[:end]), nil
}
return "", fmt.Errorf("shared-cache string is not terminated")
}
func (c *dyldCache) mappingForAddress(address uint64) (*dyldCacheMapping, error) {
for _, member := range c.members {
for index := range member.mappings {
mapping := &member.mappings[index]
if mapping.address <= address && address < mapping.address+mapping.size {
return mapping, nil
}
}
}
return nil, fmt.Errorf("address %#x is outside the shared cache", address)
}
func (c *dyldCache) addressForOffset(member *dyldCacheMember, offset uint64) (uint64, error) {
for _, mapping := range member.mappings {
if mapping.fileOffset <= offset && offset < mapping.fileOffset+mapping.size {
return mapping.address + offset - mapping.fileOffset, nil
}
}
return 0, fmt.Errorf("offset %#x is outside the shared-cache member", offset)
}
func (c *dyldCache) slidePointer(pointer uint64) uint64 {
if pointer == 0 {
return 0
}
if _, err := c.mappingForAddress(pointer); err == nil {
return pointer
}
return c.slide5.decode(pointer)
}
func (i *dyldImage) linkeditAddress() (uint64, error) {
header := make([]byte, dyldMachHeader64Size)
if _, err := i.member.file.ReadAt(header, int64(i.offset)); err != nil {
return 0, fmt.Errorf("read Mach-O header: %w", err)
}
if binary.LittleEndian.Uint32(header) != uint32(machotypes.Magic64) {
return 0, fmt.Errorf("image has an invalid Mach-O magic")
}
commandCount := binary.LittleEndian.Uint32(header[16:])
commandsSize := uint64(binary.LittleEndian.Uint32(header[20:]))
if commandsSize > dyldMaximumLoadCommandsSize || !validDyldRange(i.member.size, i.offset+dyldMachHeader64Size, commandsSize) {
return 0, fmt.Errorf("image has invalid load commands")
}
commands := make([]byte, commandsSize)
if _, err := i.member.file.ReadAt(commands, int64(i.offset+dyldMachHeader64Size)); err != nil {
return 0, fmt.Errorf("read Mach-O load commands: %w", err)
}
for index, offset := uint32(0), uint64(0); index < commandCount; index++ {
if offset+8 > uint64(len(commands)) {
return 0, fmt.Errorf("image load commands are truncated")
}
commandSize := uint64(binary.LittleEndian.Uint32(commands[offset+4:]))
if commandSize < 8 || offset+commandSize > uint64(len(commands)) {
return 0, fmt.Errorf("image has an invalid load command")
}
if binary.LittleEndian.Uint32(commands[offset:]) == dyldMachSegment64Command && commandSize >= 72 {
name := strings.TrimRight(string(commands[offset+8:offset+24]), "\x00")
if name == "__LINKEDIT" {
return binary.LittleEndian.Uint64(commands[offset+24:]), nil
}
}
offset += commandSize
}
return 0, fmt.Errorf("image has no __LINKEDIT segment")
}
type dyldCacheReader struct {
cache *dyldCache
member *dyldCacheMember
offset int64
}
func (r *dyldCacheReader) Read(data []byte) (int, error) {
n, err := r.member.file.ReadAt(data, r.offset)
r.offset += int64(n)
return n, err //nolint:wrapcheck // Reader adapters must preserve io.EOF.
}
func (r *dyldCacheReader) Seek(offset int64, whence int) (int64, error) {
switch whence {
case io.SeekStart:
case io.SeekCurrent:
offset += r.offset
case io.SeekEnd:
offset += r.member.size
default:
return 0, fmt.Errorf("invalid seek mode")
}
if offset < 0 {
return 0, fmt.Errorf("negative shared-cache offset")
}
r.offset = offset
return offset, nil
}
func (r *dyldCacheReader) ReadAt(data []byte, offset int64) (int, error) {
return r.member.file.ReadAt(data, offset) //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
}
func (r *dyldCacheReader) SeekToAddr(address uint64) error {
mapping, err := r.cache.mappingForAddress(address)
if err != nil {
return err
}
r.member = mapping.member
r.offset = int64(mapping.fileOffset + address - mapping.address)
return nil
}
func (r *dyldCacheReader) ReadAtAddr(data []byte, address uint64) (int, error) {
written := 0
for written < len(data) {
mapping, err := r.cache.mappingForAddress(address)
if err != nil {
return written, err
}
available := mapping.address + mapping.size - address
count := min(uint64(len(data)-written), available)
offset := mapping.fileOffset + address - mapping.address
n, err := mapping.member.file.ReadAt(data[written:written+int(count)], int64(offset))
written += n
address += uint64(n)
if err != nil {
return written, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
}
if n != int(count) {
return written, io.ErrUnexpectedEOF
}
}
return written, nil
}
func readDyldSlideVersion(mapping dyldCacheMapping) (uint32, error) {
if mapping.slideInfoSize < 4 {
return 0, fmt.Errorf("shared cache has truncated slide information")
}
var data [4]byte
if _, err := mapping.member.file.ReadAt(data[:], int64(mapping.slideInfoOffset)); err != nil {
return 0, fmt.Errorf("read shared-cache slide version: %w", err)
}
return binary.LittleEndian.Uint32(data[:]), nil
}
func readDyldSlideInfo5(mapping dyldCacheMapping) (*dyldSlideInfo5, error) {
if mapping.slideInfoSize < dyldSlideInfo5Size {
return nil, fmt.Errorf("shared cache has truncated slide information")
}
data := make([]byte, dyldSlideInfo5Size)
if _, err := mapping.member.file.ReadAt(data, int64(mapping.slideInfoOffset)); err != nil {
return nil, fmt.Errorf("read shared-cache slide information: %w", err)
}
if binary.LittleEndian.Uint32(data) != 5 {
return nil, fmt.Errorf("unsupported shared-cache slide version %d", binary.LittleEndian.Uint32(data))
}
slide := &dyldSlideInfo5{
pageSize: binary.LittleEndian.Uint32(data[4:]),
pageStartsCount: binary.LittleEndian.Uint32(data[8:]),
valueAdd: binary.LittleEndian.Uint64(data[16:]),
}
if slide.pageSize == 0 || uint64(dyldSlideInfo5Size)+uint64(slide.pageStartsCount)*2 > mapping.slideInfoSize {
return nil, fmt.Errorf("shared cache has invalid slide information")
}
return slide, nil
}
func (s *dyldSlideInfo5) decode(pointer uint64) uint64 {
if pointer == 0 {
return 0
}
target := pointer & ((uint64(1) << 34) - 1)
if pointer>>63 == 0 {
target |= (pointer >> 34 & 0xff) << 56
}
return s.valueAdd + target
}
func (c *dyldCache) applySlide(path string) error {
file, err := os.OpenFile(path, os.O_RDWR, 0o600)
if err != nil {
return fmt.Errorf("open exported image: %w", err)
}
defer file.Close()
exported, err := macho.NewFile(file)
if err != nil {
return fmt.Errorf("parse exported image: %w", err)
}
defer exported.Close()
for _, segment := range exported.Segments() {
mapping, err := c.mappingForAddress(segment.Addr)
if err != nil {
return err
}
if mapping.slideInfoOffset == 0 {
continue
}
pageSize, err := c.slidePageSize(*mapping)
if err != nil {
return err
}
start := (segment.Addr - mapping.address) / pageSize
end := (segment.Addr + segment.Memsz - mapping.address + pageSize) / pageSize
rebases, err := c.rebases(*mapping, start, end)
if err != nil {
return err
}
for _, rebase := range rebases {
offset, err := exported.GetOffset(rebase.address)
if err != nil {
continue
}
if _, err := file.Seek(int64(offset), io.SeekStart); err != nil {
return fmt.Errorf("seek to exported pointer %#x: %w", offset, err)
}
if err := binary.Write(file, binary.LittleEndian, rebase.target); err != nil {
return fmt.Errorf("write exported pointer %#x: %w", rebase.target, err)
}
}
}
if err := file.Sync(); err != nil {
return fmt.Errorf("sync exported image: %w", err)
}
return nil
}
func (c *dyldCache) rebases(mapping dyldCacheMapping, startPage, endPage uint64) ([]dyldRebase, error) {
version, err := readDyldSlideVersion(mapping)
if err != nil {
return nil, err
}
if version != 5 {
return nil, fmt.Errorf("unsupported shared-cache slide version %d", version)
}
slide, err := readDyldSlideInfo5(mapping)
if err != nil {
return nil, err
}
starts, err := readDyldSlideArray(mapping, dyldSlideInfo5Size, slide.pageStartsCount)
if err != nil {
return nil, err
}
if endPage == 0 || endPage > uint64(len(starts)) {
endPage = uint64(len(starts))
}
if startPage > endPage {
return nil, fmt.Errorf("invalid shared-cache slide page range")
}
var rebases []dyldRebase
for page := startPage; page < endPage; page++ {
start := starts[page]
if start == 0xffff {
continue
}
pageFileOffset := mapping.fileOffset + page*uint64(slide.pageSize)
pageAddress := mapping.address + page*uint64(slide.pageSize)
offset := uint64(start)
for count := 0; count < dyldMaximumSlideChainPointers; count++ {
if offset+8 > uint64(slide.pageSize) {
return nil, fmt.Errorf("shared-cache slide chain leaves its page")
}
var data [8]byte
if _, err := mapping.member.file.ReadAt(data[:], int64(pageFileOffset+offset)); err != nil {
return nil, fmt.Errorf("read shared-cache slide pointer: %w", err)
}
pointer := binary.LittleEndian.Uint64(data[:])
rebases = append(rebases, dyldRebase{
address: pageAddress + offset,
target: slide.decode(pointer),
})
next := pointer >> 52 & 0x7ff
if next == 0 {
break
}
offset += next * 8
if count == dyldMaximumSlideChainPointers-1 {
return nil, fmt.Errorf("shared-cache slide chain is too long")
}
}
}
return rebases, nil
}
func (c *dyldCache) slidePageSize(mapping dyldCacheMapping) (uint64, error) {
slide, err := readDyldSlideInfo5(mapping)
if err != nil {
return 0, err
}
return uint64(slide.pageSize), nil
}
func readDyldSlideArray(mapping dyldCacheMapping, offset, count uint32) ([]uint16, error) {
if count == 0 {
return nil, nil
}
data := make([]byte, uint64(count)*2)
if _, err := mapping.member.file.ReadAt(data, int64(mapping.slideInfoOffset+uint64(offset))); err != nil {
return nil, fmt.Errorf("read shared-cache slide table: %w", err)
}
values := make([]uint16, count)
for index := range values {
values[index] = binary.LittleEndian.Uint16(data[index*2:])
}
return values, nil
}
+166
View File
@@ -0,0 +1,166 @@
package assets
import (
"bytes"
"encoding/binary"
"fmt"
"strings"
"github.com/blacktop/go-macho"
machotypes "github.com/blacktop/go-macho/types"
)
// imageSymbols restores symbol load commands without allocating the cache-wide string table.
// Export needs only this image's nlists and the strings they actually reference.
func (c *dyldCache) imageSymbols(image *dyldImage, f *macho.File) error {
header := make([]byte, dyldMachHeader64Size)
if _, err := image.member.file.ReadAt(header, int64(image.offset)); err != nil {
return fmt.Errorf("read image header: %w", err)
}
size := uint64(binary.LittleEndian.Uint32(header[20:]))
if size > dyldMaximumLoadCommandsSize {
return fmt.Errorf("invalid image load command size")
}
commands := make([]byte, size)
if _, err := image.member.file.ReadAt(commands, int64(image.offset)+dyldMachHeader64Size); err != nil {
return fmt.Errorf("read image commands: %w", err)
}
address, err := image.linkeditAddress()
if err != nil {
return err
}
mapping, err := c.mappingForAddress(address)
if err != nil {
return err
}
loads := make([]macho.Load, 0, len(f.Loads)+2)
index := 0
for offset := 0; offset < len(commands); {
if len(commands)-offset < 8 {
return fmt.Errorf("truncated image command")
}
length := int(binary.LittleEndian.Uint32(commands[offset+4:]))
if length < 8 || length > len(commands)-offset {
return fmt.Errorf("invalid image command size")
}
raw := commands[offset : offset+length]
offset += length
command := machotypes.LoadCmd(binary.LittleEndian.Uint32(raw))
switch command {
case machotypes.LC_SYMTAB:
table, err := readImageSymbols(mapping.member, raw)
if err != nil {
return err
}
f.Symtab = table
loads = append(loads, table)
case machotypes.LC_DYSYMTAB:
table := &macho.Dysymtab{LoadBytes: raw}
if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &table.DysymtabCmd); err != nil {
return fmt.Errorf("decode dynamic symbols: %w", err)
}
if f.Symtab == nil || uint64(table.Iundefsym)+uint64(table.Nundefsym) > uint64(len(f.Symtab.Syms)) || table.Nindirectsyms > 4<<20 {
return fmt.Errorf("invalid dynamic symbol table")
}
if !validDyldRange(mapping.member.size, uint64(table.Indirectsymoff), uint64(table.Nindirectsyms)*4) {
return fmt.Errorf("indirect symbols exceed cache member")
}
encoded := make([]byte, int(table.Nindirectsyms)*4)
if _, err := mapping.member.file.ReadAt(encoded, int64(table.Indirectsymoff)); err != nil {
return fmt.Errorf("read indirect symbols: %w", err)
}
table.IndirectSyms = make([]uint32, table.Nindirectsyms)
if err := binary.Read(bytes.NewReader(encoded), binary.LittleEndian, table.IndirectSyms); err != nil {
return fmt.Errorf("decode indirect symbols: %w", err)
}
f.Dysymtab = table
loads = append(loads, table)
default:
if index >= len(f.Loads) || f.Loads[index].Command() != command {
return fmt.Errorf("image load command order changed")
}
loads = append(loads, f.Loads[index])
index++
}
}
f.Loads = loads
return nil
}
// readImageSymbols decodes just the referenced names, preserving go-macho's symbol normalization.
func readImageSymbols(member *dyldCacheMember, raw []byte) (*macho.Symtab, error) {
table := &macho.Symtab{LoadBytes: raw}
if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &table.SymtabCmd); err != nil {
return nil, fmt.Errorf("decode symbols: %w", err)
}
if table.Nsyms > 4<<20 || !validDyldRange(member.size, uint64(table.Symoff), uint64(table.Nsyms)*16) || !validDyldRange(member.size, uint64(table.Stroff), uint64(table.Strsize)) {
return nil, fmt.Errorf("invalid image symbol table")
}
encoded := make([]byte, int(table.Nsyms)*16)
if _, err := member.file.ReadAt(encoded, int64(table.Symoff)); err != nil {
return nil, fmt.Errorf("read image symbols: %w", err)
}
readName := func(offset uint64) (string, error) {
if offset >= uint64(table.Strsize) {
return "", nil
}
name, err := readDyldCString(member.file, int64(uint64(table.Stroff)+uint64(table.Strsize)), uint64(table.Stroff)+offset)
if err != nil {
return "", err
}
if strings.HasPrefix(name, "_") && strings.Contains(name, ".") {
name = name[1:]
}
return name, nil
}
reader := bytes.NewReader(encoded)
table.Syms = make([]macho.Symbol, 0, table.Nsyms)
for i := uint32(0); i < table.Nsyms; i++ {
var n machotypes.Nlist64
if err := binary.Read(reader, binary.LittleEndian, &n); err != nil {
return nil, fmt.Errorf("decode image symbol: %w", err)
}
name, err := readName(uint64(n.Name))
if err != nil {
return nil, err
}
indirect := ""
if n.Type.IsIndirectSym() {
indirect, err = readName(n.Value)
if err != nil {
return nil, err
}
}
table.Syms = append(table.Syms, macho.Symbol{Name: name, IndirectName: indirect, Type: n.Type, Sect: n.Sect, Desc: n.Desc, Value: n.Value})
}
return table, nil
}
+63
View File
@@ -0,0 +1,63 @@
package assets
import (
"bytes"
"encoding/binary"
"io"
machotypes "github.com/blacktop/go-macho/types"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
type sparseSymbols struct {
data []byte
largest int
}
// ReadAt simulates a large sparse cache and records the largest requested allocation.
func (s *sparseSymbols) ReadAt(output []byte, offset int64) (int, error) {
s.largest = max(s.largest, len(output))
if offset < 0 {
return 0, io.EOF
}
clear(output)
if offset < int64(len(s.data)) {
copy(output, s.data[offset:])
}
return len(output), nil
}
var _ = Describe("Shared-cache symbol loading", func() {
It("reads only referenced strings from a gigabyte-sized string table", func() {
raw := &sparseSymbols{data: make([]byte, 2048)}
names := []byte("\x00_regular\x00_Go.symbol\x00_target.symbol\x00")
copy(raw.data[1024:], names)
entries := []machotypes.Nlist64{{Nlist: machotypes.Nlist{Name: 1, Type: 0x0f}, Value: 0x180001000}, {Nlist: machotypes.Nlist{Name: 10, Type: 0x0b}, Value: 21}}
var table bytes.Buffer
for _, entry := range entries {
Expect(binary.Write(&table, binary.LittleEndian, entry)).To(Succeed())
}
copy(raw.data[128:], table.Bytes())
var command bytes.Buffer
header := machotypes.SymtabCmd{LoadCmd: machotypes.LC_SYMTAB, Len: 24, Symoff: 128, Nsyms: 2, Stroff: 1024, Strsize: 1 << 30}
Expect(binary.Write(&command, binary.LittleEndian, header)).To(Succeed())
result, err := readImageSymbols(&dyldCacheMember{file: raw, size: 2 << 30}, command.Bytes())
Expect(err).NotTo(HaveOccurred())
Expect(result.Syms).To(HaveLen(2))
Expect(result.Syms[0].Name).To(Equal("_regular"))
Expect(result.Syms[1].Name).To(Equal("Go.symbol"))
Expect(result.Syms[1].IndirectName).To(Equal("target.symbol"))
Expect(raw.largest).To(BeNumerically("<=", 4096))
})
It("rejects symbol data extending beyond the cache member", func() {
var command bytes.Buffer
Expect(binary.Write(&command, binary.LittleEndian, machotypes.SymtabCmd{LoadCmd: machotypes.LC_SYMTAB, Len: 24, Symoff: 128, Nsyms: 10, Stroff: 256, Strsize: 128})).To(Succeed())
_, err := readImageSymbols(&dyldCacheMember{file: bytes.NewReader(make([]byte, 256)), size: 256}, command.Bytes())
Expect(err).To(MatchError(ContainSubstring("invalid image symbol table")))
})
})
+172
View File
@@ -0,0 +1,172 @@
package assets
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Buffered remote ranges", func() {
var source []byte
var remote *remoteFile
var requests []string
var mu sync.Mutex
BeforeEach(func() {
source = make([]byte, 1<<20)
for n := range source {
source[n] = byte(n % 251)
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
requests = append(requests, r.Header.Get("Range"))
mu.Unlock()
http.ServeContent(w, r, "image", time.Time{}, bytes.NewReader(source))
}))
DeferCleanup(server.Close)
requests = nil
remote = &remoteFile{ctx: context.Background(), client: server.Client(), url: server.URL, size: int64(len(source))}
})
It("serves a small sequential stream in bounded larger transfers", func() {
output := make([]byte, len(source))
for offset := 0; offset < len(output); offset += 4096 {
count, err := remote.ReadAt(output[offset:offset+4096], int64(offset))
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(4096))
}
Expect(output).To(Equal(source))
mu.Lock()
count := len(requests)
mu.Unlock()
Expect(count).To(Equal(5))
Expect(len(remote.cache)).To(BeNumerically("<=", remoteReadAheadSize))
})
It("keeps sparse metadata requests exact", func() {
for _, offset := range []int64{0, 500000, 900000} {
output := make([]byte, 8)
_, err := remote.ReadAt(output, offset)
Expect(err).NotTo(HaveOccurred())
Expect(output).To(Equal(source[offset : offset+8]))
}
mu.Lock()
defer mu.Unlock()
Expect(requests).To(Equal([]string{"bytes=0-7", "bytes=500000-500007", "bytes=900000-900007"}))
})
It("isolates cached bytes from caller mutation and reports EOF correctly", func() {
data := make([]byte, 4096)
_, err := remote.ReadAt(data, 0)
Expect(err).NotTo(HaveOccurred())
clear(data)
_, err = remote.ReadAt(data, 0)
Expect(err).NotTo(HaveOccurred())
Expect(data).To(Equal(source[:4096]))
tail := make([]byte, 32)
count, err := remote.ReadAt(tail, int64(len(source)-16))
Expect(err).To(MatchError(io.EOF))
Expect(count).To(Equal(16))
Expect(tail[:count]).To(Equal(source[len(source)-16:]))
})
It("honors cancellation even when data is buffered", func() {
ctx, cancel := context.WithCancel(context.Background())
remote.ctx = ctx
data := make([]byte, 32)
_, err := remote.ReadAt(data, 0)
Expect(err).NotTo(HaveOccurred())
cancel()
_, err = remote.ReadAt(data, 0)
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
})
It("supports concurrent independent reads", func() {
finished := make(chan error, 8)
for n := range 8 {
go func() {
offset := int64(n * 40000)
output := make([]byte, 4096)
_, err := remote.ReadAt(output, offset)
if err == nil && !bytes.Equal(output, source[offset:offset+4096]) {
err = errors.New("incorrect concurrent range")
}
finished <- err
}()
}
for range 8 {
Eventually(finished).Should(Receive(BeNil()))
}
})
})
var _ = Describe("Interrupted remote responses", func() {
It("resumes a short response at the first unread byte", func() {
var ranges []string
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 8, client: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
ranges = append(ranges, r.Header.Get("Range"))
if len(ranges) == 1 {
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-7/8"}}, Body: io.NopCloser(strings.NewReader("abcd"))}, nil
}
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 4-7/8"}}, Body: io.NopCloser(strings.NewReader("efgh"))}, nil
})}}
data := make([]byte, 8)
count, err := remote.ReadAt(data, 0)
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(8))
Expect(string(data)).To(Equal("abcdefgh"))
Expect(ranges).To(Equal([]string{"bytes=0-7", "bytes=4-7"}))
})
It("rejects incorrect response ranges without caching them", func() {
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 8, client: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 1-7/8"}}, Body: io.NopCloser(strings.NewReader("1234567"))}, nil
})}}
_, err := remote.ReadAt(make([]byte, 8), 0)
Expect(err).To(MatchError(ContainSubstring("server returned bytes")))
Expect(remote.cache).To(BeEmpty())
})
It("does not fail a completed requested prefix when speculative tail reads fail", func() {
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 1 << 20}
calls := 0
remote.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
calls++
switch calls {
case 1:
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-3/1048576"}}, Body: io.NopCloser(strings.NewReader("abcd"))}, nil
case 2:
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{fmt.Sprintf("bytes 4-%d/1048576", 4+remoteReadAheadSize-1)}}, Body: io.NopCloser(strings.NewReader("efgh"))}, nil
default:
return nil, errors.New("connection interrupted")
}
})}
data := make([]byte, 4)
_, err := remote.ReadAt(data, 0)
Expect(err).NotTo(HaveOccurred())
count, err := remote.ReadAt(data, 4)
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(4))
Expect(string(data)).To(Equal("efgh"))
Expect(remote.cacheOffset).To(BeZero())
Expect(remote.cache).To(HaveLen(4))
})
})
var _ = Describe("Remote image size probes", func() {
DescribeTable("requires exactly the requested byte", func(body string, valid bool) {
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-0/123"}}, Body: io.NopCloser(strings.NewReader(body))}, nil
})}
remote, err := openRemoteFile(context.Background(), client)
if valid {
Expect(err).NotTo(HaveOccurred())
Expect(remote.size).To(Equal(int64(123)))
} else {
Expect(err).To(MatchError(ContainSubstring("probe has an invalid length")))
}
}, Entry("one byte", "x", true), Entry("empty body", "", false), Entry("too much data", "xx", false))
})
+238
View File
@@ -0,0 +1,238 @@
package assets
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"sync"
)
const (
remoteReadAttempts = 3
restoreImageUserAgent = "Mozilla/5.0"
remoteSmallReadSize = 32 << 10
remoteReadAheadSize = 256 << 10
)
type remoteFile struct {
ctx context.Context
client *http.Client
url string
size int64
mu sync.Mutex
cache []byte
cacheOffset int64
previous bool
lastEnd int64
}
//nolint:wsl // Request construction and validation are clearer in protocol order.
func openRemoteFile(ctx context.Context, client *http.Client) (*remoteFile, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, macOSRestoreURL, nil)
if err != nil {
return nil, fmt.Errorf("create remote image request: %w", err)
}
request.Header.Set("User-Agent", restoreImageUserAgent)
request.Header.Set("Range", "bytes=0-0")
response, err := client.Do(request)
if err != nil {
return nil, fmt.Errorf("open remote image: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusPartialContent {
return nil, fmt.Errorf("open remote image: server returned %s without byte-range support", response.Status)
}
start, end, size, err := parseContentRange(response.Header.Get("Content-Range"))
if err != nil {
return nil, fmt.Errorf("open remote image: %w", err)
}
if start != 0 || end != 0 {
return nil, fmt.Errorf("open remote image: server returned unexpected byte range %d-%d", start, end)
}
probe, err := io.ReadAll(io.LimitReader(response.Body, 2))
if err != nil {
return nil, fmt.Errorf("read remote image probe: %w", err)
}
if len(probe) != 1 {
return nil, errors.New("remote image probe has an invalid length")
}
return &remoteFile{ctx: ctx, client: client, url: macOSRestoreURL, size: size}, nil
}
//nolint:wsl // Parsing checks are clearer in wire-format order.
func parseContentRange(value string) (int64, int64, int64, error) {
unitAndRange, total, ok := strings.Cut(value, "/")
if !ok || total == "" || total == "*" {
return 0, 0, 0, fmt.Errorf("invalid Content-Range %q", value)
}
size, err := strconv.ParseInt(total, 10, 64)
if err != nil || size <= 0 {
return 0, 0, 0, fmt.Errorf("invalid Content-Range %q", value)
}
rangeValue, ok := strings.CutPrefix(unitAndRange, "bytes ")
if !ok {
return 0, 0, 0, fmt.Errorf("invalid Content-Range %q", value)
}
startValue, endValue, ok := strings.Cut(rangeValue, "-")
if !ok {
return 0, 0, 0, fmt.Errorf("invalid Content-Range %q", value)
}
start, startErr := strconv.ParseInt(startValue, 10, 64)
end, endErr := strconv.ParseInt(endValue, 10, 64)
if startErr != nil || endErr != nil || start < 0 || end < start || end >= size {
return 0, 0, 0, fmt.Errorf("invalid Content-Range %q", value)
}
return start, end, size, nil
}
//nolint:wsl // Range request validation is clearer in protocol order.
func (r *remoteFile) ReadAt(data []byte, offset int64) (int, error) {
if len(data) == 0 {
return 0, nil
}
if offset < 0 {
return 0, errors.New("negative remote image offset")
}
if offset >= r.size {
return 0, io.EOF
}
wanted := len(data)
if remaining := r.size - offset; int64(wanted) > remaining {
wanted = int(remaining)
}
if err := r.ctx.Err(); err != nil {
return 0, fmt.Errorf("read remote image: %w", err)
}
r.mu.Lock()
if offset >= r.cacheOffset && offset+int64(wanted) <= r.cacheOffset+int64(len(r.cache)) {
copy(data[:wanted], r.cache[offset-r.cacheOffset:offset-r.cacheOffset+int64(wanted)])
r.previous, r.lastEnd = true, offset+int64(wanted)
r.mu.Unlock()
if wanted != len(data) {
return wanted, io.EOF
}
return wanted, nil
}
// Sparse metadata reads stay exact; only a sequential small-read stream
// earns read-ahead. This avoids fetching large unused image regions.
ahead := r.previous && offset == r.lastEnd && wanted <= remoteSmallReadSize
r.previous, r.lastEnd = true, offset+int64(wanted)
r.mu.Unlock()
fetchSize := wanted
if ahead {
fetchSize = int(min(int64(remoteReadAheadSize), r.size-offset))
}
buffer := data[:wanted]
if fetchSize > wanted {
buffer = make([]byte, fetchSize)
}
count, err := r.readRange(buffer, offset)
if count == fetchSize && err == nil && fetchSize <= remoteReadAheadSize {
cached := buffer
if fetchSize == wanted {
cached = bytes.Clone(buffer)
}
r.mu.Lock()
r.cacheOffset, r.cache = offset, cached
r.mu.Unlock()
}
if fetchSize > wanted {
copy(data[:wanted], buffer[:min(count, wanted)])
}
if count < wanted {
return count, err
}
if wanted != len(data) {
return wanted, io.EOF
}
return wanted, nil
}
// Read and validate one wire range, resuming interrupted bodies as needed.
func (r *remoteFile) readRange(data []byte, offset int64) (int, error) {
wanted := len(data)
total := 0
var lastErr error
for attempt := 0; attempt < remoteReadAttempts && total < wanted; attempt++ {
start := offset + int64(total)
end := offset + int64(wanted) - 1
request, err := http.NewRequestWithContext(r.ctx, http.MethodGet, r.url, nil)
if err != nil {
return total, fmt.Errorf("create remote range request: %w", err)
}
request.Header.Set("User-Agent", restoreImageUserAgent)
request.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", start, end))
response, err := r.client.Do(request)
if err != nil {
lastErr = err
continue
}
if response.StatusCode != http.StatusPartialContent {
response.Body.Close()
return total, fmt.Errorf("read remote image range: server returned %s", response.Status)
}
actualStart, actualEnd, actualSize, err := parseContentRange(response.Header.Get("Content-Range"))
if err != nil || actualStart != start || actualEnd != end || actualSize != r.size {
response.Body.Close()
if err != nil {
return total, fmt.Errorf("read remote image range: %w", err)
}
return total, fmt.Errorf("read remote image range: server returned bytes %d-%d/%d, expected %d-%d/%d", actualStart, actualEnd, actualSize, start, end, r.size)
}
count, readErr := io.ReadFull(response.Body, data[total:wanted])
closeErr := response.Body.Close()
total += count
if readErr == nil {
lastErr = closeErr
break
}
lastErr = readErr
}
if total != wanted {
if lastErr == nil {
lastErr = io.ErrUnexpectedEOF
}
return total, fmt.Errorf("read remote image at offset %d: %w", offset+int64(total), lastErr)
}
return total, nil
}
+56
View File
@@ -0,0 +1,56 @@
package assets
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (function roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
return function(request)
}
var _ = Describe("remote image HTTP requests", func() {
It("reads image ranges from a server requiring a browser-compatible user agent", func() {
const content = "restore image"
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
if request.UserAgent() != "Mozilla/5.0" {
http.Error(response, "unsupported user agent", http.StatusForbidden)
return
}
http.ServeContent(response, request, "restore.ipsw", time.Time{}, strings.NewReader(content))
}))
DeferCleanup(server.Close)
transport := &http.Transport{}
DeferCleanup(transport.CloseIdleConnections)
client := &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
request = request.Clone(request.Context())
request.URL.Scheme = "http"
request.URL.Host = server.Listener.Addr().String()
return transport.RoundTrip(request)
})}
remote, err := openRemoteFile(context.Background(), client)
Expect(err).NotTo(HaveOccurred())
Expect(remote.size).To(Equal(int64(len(content))))
data := make([]byte, len(content)-1)
count, err := remote.ReadAt(data, 1)
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(len(data)))
Expect(string(data)).To(Equal(content[1:]))
})
})
+172
View File
@@ -0,0 +1,172 @@
package assets
import (
"archive/zip"
"bytes"
"encoding/asn1"
"errors"
"fmt"
"io"
"os"
"github.com/blacktop/go-macho"
"github.com/blacktop/go-macho/pkg/fixupchains"
"github.com/blacktop/go-macho/types"
"github.com/go-compressions/lzfse"
)
const (
kernelCacheName = "kernelcache.release.mac13j"
kernelCacheCompressedSize = 33043908
kernelCacheArchiveSize = 33096787
kernelCachePayloadSize = 33096384
kernelCacheImageSize = 124354560
fairPlayKextIdentifier = "com.apple.driver.FairPlayIOKit"
maximumKernelCacheSymbols = 1 << 20
)
func extractFairPlayKext(archive *zip.Reader, destination string) error {
entry, err := pinnedZipEntry(archive, kernelCacheName, kernelCacheCompressedSize, kernelCacheArchiveSize)
if err != nil {
return err
}
reader, err := entry.Open()
if err != nil {
return fmt.Errorf("open pinned kernel collection: %w", err)
}
data, readErr := io.ReadAll(io.LimitReader(reader, kernelCacheArchiveSize+1))
closeErr := reader.Close()
if readErr != nil || closeErr != nil {
return fmt.Errorf("read pinned kernel collection: %w", errors.Join(readErr, closeErr))
}
if len(data) != kernelCacheArchiveSize {
return fmt.Errorf("pinned kernel collection has size %d, expected %d", len(data), kernelCacheArchiveSize)
}
payload, err := im4pPayload(data)
if err != nil {
return fmt.Errorf("decode pinned kernel collection: %w", err)
}
if len(payload) != kernelCachePayloadSize {
return fmt.Errorf("pinned kernel payload has size %d, expected %d", len(payload), kernelCachePayloadSize)
}
image, err := lzfse.Decompress(payload)
if err != nil {
return fmt.Errorf("decompress pinned kernel collection: %w", err)
}
if len(image) != kernelCacheImageSize {
return fmt.Errorf("pinned kernel image has size %d, expected %d", len(image), kernelCacheImageSize)
}
collection, err := macho.NewFile(bytes.NewReader(image))
if err != nil {
return fmt.Errorf("open pinned kernel collection Mach-O: %w", err)
}
defer collection.Close()
if collection.Type != types.MH_FILESET {
return errors.New("pinned kernel collection is not a fileset")
}
var fixups *fixupchains.DyldChainedFixups
if collection.HasFixups() {
fixups, err = collection.DyldChainedFixups()
if err != nil {
return fmt.Errorf("read pinned kernel fixups: %w", err)
}
}
symbols := make(map[string]macho.Symbol)
for _, entry := range collection.FileSets() {
member, openErr := collection.GetFileSetFileByName(entry.EntryID)
if openErr != nil || member.Symtab == nil {
continue
}
for _, symbol := range member.Symtab.Syms {
if symbol.Type.IsExternalSym() && !symbol.Type.IsUndefinedSym() && symbol.Value != 0 {
symbols[symbol.Name] = symbol
if len(symbols) > maximumKernelCacheSymbols {
return errors.New("pinned kernel symbol table exceeds the limit")
}
}
}
}
member, err := collection.GetFileSetFileByName(fairPlayKextIdentifier)
if err != nil {
return fmt.Errorf("find FairPlayIOKit in pinned kernel collection: %w", err)
}
var resolved []macho.Symbol
if member.Symtab != nil {
for _, symbol := range member.Symtab.Syms {
if !symbol.Type.IsUndefinedSym() || symbol.Name == "" {
continue
}
if target, ok := symbols[symbol.Name]; ok {
resolved = append(resolved, macho.Symbol{
Name: symbol.Name,
Type: types.N_ABS | types.N_EXT,
Desc: symbol.Desc,
Value: target.Value,
})
}
}
}
if err := member.Export(destination, fixups, collection.GetBaseAddress(), resolved); err != nil {
return fmt.Errorf("export FairPlayIOKit from pinned kernel collection: %w", err)
}
info, err := os.Stat(destination)
if err != nil {
return fmt.Errorf("inspect exported FairPlayIOKit: %w", err)
}
if !info.Mode().IsRegular() {
return errors.New("exported FairPlayIOKit is not a regular file")
}
return nil
}
func im4pPayload(data []byte) ([]byte, error) {
var container asn1.RawValue
rest, err := asn1.Unmarshal(data, &container)
if err != nil || len(rest) != 0 || container.Tag != asn1.TagSequence || !container.IsCompound {
return nil, errors.New("invalid IM4P container")
}
contents := container.Bytes
fields := make([]asn1.RawValue, 0, 4)
for len(contents) != 0 && len(fields) < 4 {
var field asn1.RawValue
contents, err = asn1.Unmarshal(contents, &field)
if err != nil {
return nil, fmt.Errorf("decode IM4P field: %w", err)
}
fields = append(fields, field)
}
if len(fields) != 4 || fields[0].Tag != asn1.TagIA5String || string(fields[0].Bytes) != "IM4P" || fields[1].Tag != asn1.TagIA5String || string(fields[1].Bytes) != "krnl" || fields[3].Tag != asn1.TagOctetString {
return nil, errors.New("invalid IM4P kernel payload")
}
return append([]byte(nil), fields[3].Bytes...), nil
}
+98
View File
@@ -0,0 +1,98 @@
package assets
import (
"encoding/binary"
"errors"
)
// padLZFSEStreams supplies unused low accumulator bytes for short FSE streams.
// Apple's decoder can read those bytes before the payload; the pure Go decoder
// bounds each stream separately and otherwise rejects valid short payloads.
// This is only used on authenticated AEA data, whose decoded SHA-256 is checked.
func padLZFSEStreams(src []byte) ([]byte, error) {
var out []byte
for len(src) >= 4 {
magic := binary.LittleEndian.Uint32(src)
if magic == 0x24787662 {
return append(out, src...), nil
}
if len(src) < 12 {
return nil, errors.New("short LZFSE block")
}
if magic == 0x2d787662 || magic == 0x6e787662 {
size := 8 + int(binary.LittleEndian.Uint32(src[4:]))
if magic == 0x6e787662 {
size = 12 + int(binary.LittleEndian.Uint32(src[8:]))
}
if size > len(src) {
return nil, errors.New("truncated LZFSE block")
}
out = append(out, src[:size]...)
src = src[size:]
continue
}
var header, literals, matches int
var v0, v1 uint64
switch magic {
case 0x32787662:
if len(src) < 32 {
return nil, errors.New("short LZFSE V2 header")
}
v0 = binary.LittleEndian.Uint64(src[8:])
v1 = binary.LittleEndian.Uint64(src[16:])
header = int(binary.LittleEndian.Uint32(src[24:]))
literals = int(v0 >> 20 & 0xfffff)
matches = int(v1 >> 40 & 0xfffff)
if header < 32 {
return nil, errors.New("invalid LZFSE V2 header")
}
case 0x31787662:
header = 772
if len(src) < header {
return nil, errors.New("short LZFSE V1 header")
}
literals = int(binary.LittleEndian.Uint32(src[20:]))
matches = int(binary.LittleEndian.Uint32(src[24:]))
default:
return nil, errors.New("unknown LZFSE block")
}
if header > len(src) || literals > len(src)-header || matches > len(src)-header-literals {
return nil, errors.New("truncated LZFSE payload")
}
lp, mp := max(0, 8-literals), max(0, 8-matches)
h := append([]byte(nil), src[:header]...)
if magic == 0x32787662 {
binary.LittleEndian.PutUint64(h[8:], v0&^(uint64(0xfffff)<<20)|uint64(literals+lp)<<20)
binary.LittleEndian.PutUint64(h[16:], v1&^(uint64(0xfffff)<<40)|uint64(matches+mp)<<40)
} else {
binary.LittleEndian.PutUint32(h[8:], uint32(literals+lp+matches+mp))
binary.LittleEndian.PutUint32(h[20:], uint32(literals+lp))
binary.LittleEndian.PutUint32(h[24:], uint32(matches+mp))
}
out = append(out, h...)
out = append(out, make([]byte, lp)...)
out = append(out, src[header:header+literals]...)
out = append(out, make([]byte, mp)...)
out = append(out, src[header+literals:header+literals+matches]...)
src = src[header+literals+matches:]
}
return nil, errors.New("missing LZFSE end marker")
}
+33
View File
@@ -0,0 +1,33 @@
package assets
import (
"encoding/binary"
"github.com/go-compressions/lzfse"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Short LZFSE entropy streams", func() {
It("decodes a valid short literal payload without changing its output", func() {
original := make([]byte, 65536)
encoded, err := lzfse.Compress(original)
Expect(err).NotTo(HaveOccurred())
Expect(binary.LittleEndian.Uint32(encoded)).To(Equal(uint32(0x32787662)))
word := binary.LittleEndian.Uint64(encoded[8:])
Expect(word >> 20 & 0xfffff).To(BeZero())
header := int(binary.LittleEndian.Uint32(encoded[24:]))
short := append([]byte(nil), encoded[:header]...)
short = append(short, make([]byte, 4)...)
short = append(short, encoded[header:]...)
binary.LittleEndian.PutUint64(short[8:], word|4<<20)
_, err = lzfse.Decompress(short)
Expect(err).To(MatchError(ContainSubstring("stream too short")))
padded, err := padLZFSEStreams(short)
Expect(err).NotTo(HaveOccurred())
decoded, err := lzfse.Decompress(padded)
Expect(err).NotTo(HaveOccurred())
Expect(decoded).To(Equal(original))
})
It("rejects truncated block payloads", func() { _, err := padLZFSEStreams([]byte{'b', 'v', 'x', '2'}); Expect(err).To(HaveOccurred()) })
})
+79
View File
@@ -0,0 +1,79 @@
package assets
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"os"
"path/filepath"
"github.com/blacktop/go-macho/types"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Compact asset cache migration", func() {
var directory, legacyDirectory string
var source, selected []byte
BeforeEach(func() {
root := GinkgoT().TempDir()
directory = filepath.Join(root, assetCacheDirectory)
legacyDirectory = filepath.Join(root, legacyAssetCacheDirectory)
source = make([]byte, 40)
for n, v := range []uint32{types.MagicFat.Int(), 1, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 28, 4, 0} {
binary.BigEndian.PutUint32(source[n*4:], v)
}
copy(source[28:], "arm!unused!")
selected = []byte("arm!")
originalRequired, originalLegacy := requiredFiles, legacyFiles
DeferCleanup(func() { requiredFiles, legacyFiles = originalRequired, originalLegacy })
requiredFiles = []fileSpec{{name: "CoreFP", size: len(selected), digest: sha256.Sum256(selected)}}
legacyFiles = []fileSpec{{name: "CoreFP", size: len(source), digest: sha256.Sum256(source)}}
Expect(os.MkdirAll(legacyDirectory, 0o700)).To(Succeed())
Expect(os.WriteFile(filepath.Join(legacyDirectory, "CoreFP"), source, 0o600)).To(Succeed())
})
It("verifies legacy files and writes only the selected architecture", func() {
bundle, found := loadCachedBundle(directory)
Expect(found).To(BeTrue())
Expect(bundle.CoreFP).To(Equal(selected))
migrated, err := os.ReadFile(filepath.Join(directory, "CoreFP"))
Expect(err).NotTo(HaveOccurred())
Expect(migrated).To(Equal(selected))
old, err := os.ReadFile(filepath.Join(legacyDirectory, "CoreFP"))
Expect(err).NotTo(HaveOccurred())
Expect(old).To(Equal(source))
})
It("uses a compact cache without requiring the old files", func() {
Expect(writeCache(directory, Bundle{CoreFP: selected})).To(Succeed())
Expect(os.RemoveAll(legacyDirectory)).To(Succeed())
bundle, found := loadCachedBundle(directory)
Expect(found).To(BeTrue())
Expect(bundle.CoreFP).To(Equal(selected))
})
It("rejects corrupt discarded legacy bytes", func() {
corrupt := bytes.Clone(source)
corrupt[len(corrupt)-1] ^= 0xff
Expect(os.WriteFile(filepath.Join(legacyDirectory, "CoreFP"), corrupt, 0o600)).To(Succeed())
_, found := loadCachedBundle(directory)
Expect(found).To(BeFalse())
})
It("repairs corrupt compact data from a valid old cache", func() {
Expect(os.MkdirAll(directory, 0o700)).To(Succeed())
Expect(os.WriteFile(filepath.Join(directory, "CoreFP"), []byte("bad!"), 0o600)).To(Succeed())
bundle, found := loadCachedBundle(directory)
Expect(found).To(BeTrue())
Expect(bundle.CoreFP).To(Equal(selected))
})
It("keeps valid legacy data usable when the compact cache cannot be written", func() {
Expect(os.WriteFile(directory, []byte("not a directory"), 0o600)).To(Succeed())
bundle, found := loadCachedBundle(directory)
Expect(found).To(BeTrue())
Expect(bundle.CoreFP).To(Equal(selected))
})
It("rejects a legacy slice that does not match the new pin", func() {
requiredFiles[0].digest = sha256.Sum256([]byte("bad!"))
_, found := loadCachedBundle(directory)
Expect(found).To(BeFalse())
})
})
+183
View File
@@ -0,0 +1,183 @@
//nolint:wsl // Archive extraction is clearer when resource setup remains adjacent.
package assets
import (
"archive/zip"
"context"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
)
const (
appleMediaServicesImage = "/System/Library/PrivateFrameworks/AppleMediaServices.framework/Versions/A/AppleMediaServices"
fileSystemImageName = "043-70867-640.dmg.aea"
systemOSImageName = "043-70701-651.dmg.aea"
fileSystemArchiveSize = 11274289152
fileSystemImageSize = 14189330432
systemOSArchiveSize = 2415919104
systemOSImageSize = 2879389696
arm64CachePath = "/System/Library/dyld/dyld_shared_cache_arm64e"
)
var frameworkImagePaths = []string{
"/System/Library/PrivateFrameworks/CoreADI.framework/Versions/A/adid",
"/System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/Resources/commerce",
"/System/Library/PrivateFrameworks/CoreFP.framework/Versions/A/CoreFP",
"/System/Library/PrivateFrameworks/CoreFP.framework/Versions/A/Resources/CoreFP.icxs",
"/System/Library/PrivateFrameworks/CoreFP.framework/Versions/A/fairplayd",
}
func resolveRemoteImage(ctx context.Context) (Bundle, error) {
client := &http.Client{}
remote, err := openRemoteFile(ctx, client)
if err != nil {
return Bundle{}, fmt.Errorf("resolve macOS %s (%s) frameworks: %w", macOSVersion, macOSBuild, err)
}
archive, err := zip.NewReader(remote, remote.size)
if err != nil {
return Bundle{}, fmt.Errorf("read macOS %s (%s) restore image: %w", macOSVersion, macOSBuild, err)
}
fileSystemEntry, err := pinnedZipEntry(archive, fileSystemImageName, fileSystemArchiveSize, fileSystemArchiveSize)
if err != nil {
return Bundle{}, err
}
systemOSEntry, err := pinnedZipEntry(archive, systemOSImageName, systemOSArchiveSize, systemOSArchiveSize)
if err != nil {
return Bundle{}, err
}
workspace, err := os.MkdirTemp("", "ipatool-macos-27-*")
if err != nil {
return Bundle{}, fmt.Errorf("create macOS image workspace: %w", err)
}
defer os.RemoveAll(workspace)
frameworkDirectory := filepath.Join(workspace, "frameworks")
if err := extractFrameworkFiles(ctx, client, remote, fileSystemEntry, frameworkDirectory); err != nil {
return Bundle{}, err
}
appleMediaServicesPath := filepath.Join(frameworkDirectory, "AppleMediaServices")
if err := extractAppleMediaServices(ctx, client, remote, systemOSEntry, appleMediaServicesPath); err != nil {
return Bundle{}, fmt.Errorf("extract AppleMediaServices from macOS %s (%s): %w", macOSVersion, macOSBuild, err)
}
if err := extractFairPlayKext(archive, filepath.Join(frameworkDirectory, "FairPlayIOKit")); err != nil {
return Bundle{}, err
}
files := make(map[string][]byte, len(requiredFiles))
for _, spec := range requiredFiles {
data, err := os.ReadFile(filepath.Join(frameworkDirectory, spec.name))
if err != nil {
return Bundle{}, fmt.Errorf("read extracted %s: %w", spec.name, err)
}
files[spec.name] = data
}
bundle, err := compactBundle(bundleFrom(files))
if err != nil {
return Bundle{}, err
}
if err := validate(bundle); err != nil {
return Bundle{}, err
}
return bundle, nil
}
func extractAppleMediaServices(ctx context.Context, client *http.Client, remote *remoteFile, entry *zip.File, destination string) error {
if err := ctx.Err(); err != nil {
return fmt.Errorf("extract AppleMediaServices: %w", err)
}
offset, err := entry.DataOffset()
if err != nil {
return fmt.Errorf("locate encrypted SystemOS cryptex: %w", err)
}
encryptedImage := io.NewSectionReader(remote, offset, int64(entry.CompressedSize64))
image, err := newAEAReader(ctx, client, encryptedImage, int64(entry.CompressedSize64))
if err != nil {
return fmt.Errorf("open encrypted SystemOS cryptex: %w", err)
}
if image.size != systemOSImageSize {
return fmt.Errorf("SystemOS cryptex has size %d, expected %d", image.size, systemOSImageSize)
}
extractor, closeExtractor, err := newAPFSExtractor(image, image.size)
if err != nil {
return err
}
defer func() { _ = closeExtractor() }()
opener := func(suffix string) (*dyldCacheFile, error) {
file, err := extractor.openFile(ctx, arm64CachePath+suffix)
if err != nil {
return nil, fmt.Errorf("open arm64e shared-cache member %q: %w", suffix, err)
}
return &dyldCacheFile{reader: file, size: file.size, close: func() error { return nil }}, nil
}
if err := extractDyldImageFromFiles(opener, appleMediaServicesImage, destination); err != nil {
return fmt.Errorf("export AppleMediaServices from arm64e shared cache: %w", err)
}
return nil
}
func pinnedZipEntry(archive *zip.Reader, name string, compressedSize, uncompressedSize uint64) (*zip.File, error) {
expectedMethod := zip.Store
if compressedSize != uncompressedSize {
expectedMethod = zip.Deflate
}
for _, entry := range archive.File {
if entry.Name != name {
continue
}
if entry.Method != expectedMethod || entry.CompressedSize64 != compressedSize || entry.UncompressedSize64 != uncompressedSize {
return nil, fmt.Errorf("macOS %s (%s) restore member %s does not match the pinned image", macOSVersion, macOSBuild, name)
}
return entry, nil
}
return nil, fmt.Errorf("macOS %s (%s) restore image does not contain %s", macOSVersion, macOSBuild, name)
}
func extractFrameworkFiles(ctx context.Context, client *http.Client, remote *remoteFile, entry *zip.File, destination string) error {
if err := ctx.Err(); err != nil {
return fmt.Errorf("extract framework files: %w", err)
}
offset, err := entry.DataOffset()
if err != nil {
return fmt.Errorf("locate encrypted macOS filesystem: %w", err)
}
encryptedImage := io.NewSectionReader(remote, offset, int64(entry.CompressedSize64))
image, err := newAEAReader(ctx, client, encryptedImage, int64(entry.CompressedSize64))
if err != nil {
return fmt.Errorf("open encrypted macOS filesystem: %w", err)
}
if image.size != fileSystemImageSize {
return fmt.Errorf("macOS filesystem has size %d, expected %d", image.size, fileSystemImageSize)
}
if err := extractAPFSFiles(ctx, image, image.size, frameworkImagePaths, destination); err != nil {
return fmt.Errorf("extract frameworks from macOS %s (%s): %w", macOSVersion, macOSBuild, err)
}
return nil
}
+58
View File
@@ -0,0 +1,58 @@
package assets
import (
"bytes"
"encoding/binary"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("native remote image reader", func() {
DescribeTable("parses complete Content-Range values",
func(value string, expectedStart, expectedEnd, expectedSize int64) {
start, end, size, err := parseContentRange(value)
Expect(err).NotTo(HaveOccurred())
Expect(start).To(Equal(expectedStart))
Expect(end).To(Equal(expectedEnd))
Expect(size).To(Equal(expectedSize))
},
Entry("single byte", "bytes 0-0/26637307067", int64(0), int64(0), int64(26637307067)),
Entry("middle range", "bytes 100-199/1000", int64(100), int64(199), int64(1000)),
)
DescribeTable("rejects incomplete Content-Range values",
func(value string) {
_, _, _, err := parseContentRange(value)
Expect(err).To(HaveOccurred())
},
Entry("missing total", "bytes 0-0/*"),
Entry("missing separator", "bytes 0-0"),
Entry("zero length", "bytes 0-0/0"),
Entry("wrong unit", "items 0-0/1"),
Entry("range beyond total", "bytes 0-1/1"),
Entry("backwards range", "bytes 2-1/3"),
)
It("parses bounded AEA metadata records", func() {
var data bytes.Buffer
for key, value := range map[string]string{"first": "value", "second": "another"} {
record := append(append([]byte(key), 0), value...)
Expect(binary.Write(&data, binary.LittleEndian, uint32(len(record)+4))).To(Succeed())
_, err := data.Write(record)
Expect(err).NotTo(HaveOccurred())
}
metadata, err := parseAEAMetadata(data.Bytes())
Expect(err).NotTo(HaveOccurred())
Expect(metadata).To(HaveKeyWithValue("first", []byte("value")))
Expect(metadata).To(HaveKeyWithValue("second", []byte("another")))
})
It("rejects an AEA metadata record outside the authentication block", func() {
data := make([]byte, 8)
binary.LittleEndian.PutUint32(data, 32)
_, err := parseAEAMetadata(data)
Expect(err).To(MatchError(ContainSubstring("invalid AEA metadata record length")))
})
})
+267
View File
@@ -0,0 +1,267 @@
package assets
import (
"archive/zip"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"net/http"
"os"
)
const authenticationPluginImage = "/System/Library/Accounts/Authentication/AMSAccountAuthenticationPlugin.bundle/Contents/MacOS/AMSAccountAuthenticationPlugin"
// StoreCache reads the pinned shared-cache data without loading host frameworks.
// It is used both by the profile generator and the portable asset installer.
type StoreCache struct {
cache *dyldCache
ctx context.Context
opener dyldCacheOpener
cleanup func() error
slides map[uint64]map[uint64]uint64
images map[string]uint64
readSystemFile func(string) ([]byte, error)
}
// OpenLocalStoreCache opens shared-cache files for offline profile generation.
func OpenLocalStoreCache(ctx context.Context, path string) (*StoreCache, error) {
opener := func(suffix string) (*dyldCacheFile, error) {
file, err := os.Open(path + suffix)
if err != nil {
return nil, fmt.Errorf("open Store cache member: %w", err)
}
info, err := file.Stat()
if err != nil {
_ = file.Close()
return nil, fmt.Errorf("inspect Store cache member: %w", err)
}
return &dyldCacheFile{reader: file, size: info.Size(), close: file.Close}, nil
}
s, err := newStoreCache(ctx, opener, func() error { return nil })
if err == nil {
s.readSystemFile = os.ReadFile
}
return s, err
}
// OpenRemoteStoreCache obtains data directly from Apple's pinned restore image.
func OpenRemoteStoreCache(ctx context.Context) (*StoreCache, error) {
if ctx == nil {
return nil, errors.New("store asset context is nil")
}
client := &http.Client{}
remote, err := openRemoteFile(ctx, client)
if err != nil {
return nil, fmt.Errorf("open Store restore image: %w", err)
}
archive, err := zip.NewReader(remote, remote.size)
if err != nil {
return nil, fmt.Errorf("read Store restore archive: %w", err)
}
entry, err := pinnedZipEntry(archive, systemOSImageName, systemOSArchiveSize, systemOSArchiveSize)
if err != nil {
return nil, err
}
offset, err := entry.DataOffset()
if err != nil {
return nil, fmt.Errorf("locate Store cryptex: %w", err)
}
image, err := newAEAReader(ctx, client, io.NewSectionReader(remote, offset, int64(entry.CompressedSize64)), int64(entry.CompressedSize64))
if err != nil {
return nil, fmt.Errorf("open Store cryptex: %w", err)
}
if image.size != systemOSImageSize {
return nil, errors.New("store cryptex does not match the pinned image")
}
extractor, closeExtractor, err := newAPFSExtractor(image, image.size)
if err != nil {
return nil, err
}
opener := func(suffix string) (*dyldCacheFile, error) {
file, err := extractor.openFile(ctx, arm64CachePath+suffix)
if err != nil {
return nil, fmt.Errorf("open Store cache member: %w", err)
}
return &dyldCacheFile{reader: file, size: file.size, close: func() error { return nil }}, nil
}
var systemExtractor *apfsExtractor
var closeSystem func() error
cleanup := func() error {
err := closeExtractor()
if closeSystem != nil {
err = errors.Join(err, closeSystem())
}
return err
}
s, err := newStoreCache(ctx, opener, cleanup)
if err == nil {
s.readSystemFile = func(path string) ([]byte, error) {
if systemExtractor == nil {
entry, e := pinnedZipEntry(archive, fileSystemImageName, fileSystemArchiveSize, fileSystemArchiveSize)
if e != nil {
return nil, e
}
offset, e := entry.DataOffset()
if e != nil {
return nil, fmt.Errorf("locate Store filesystem: %w", e)
}
image, e := newAEAReader(ctx, client, io.NewSectionReader(remote, offset, int64(entry.CompressedSize64)), int64(entry.CompressedSize64))
if e != nil {
return nil, e
}
if image.size != fileSystemImageSize {
return nil, errors.New("store filesystem does not match pinned image")
}
systemExtractor, closeSystem, e = newAPFSExtractor(image, image.size)
if e != nil {
return nil, e
}
}
f, e := systemExtractor.openFile(ctx, path)
if e != nil {
return nil, e
}
if f.size > 4<<20 {
return nil, errors.New("store system file exceeds size limit")
}
return io.ReadAll(io.NewSectionReader(f, 0, f.size))
}
}
return s, err
}
func newStoreCache(ctx context.Context, opener dyldCacheOpener, cleanup func() error) (*StoreCache, error) {
if ctx == nil {
_ = cleanup()
return nil, errors.New("store asset context is nil")
}
if err := ctx.Err(); err != nil {
_ = cleanup()
return nil, fmt.Errorf("open Store cache: %w", err)
}
cache, err := openDyldCache(opener)
if err != nil {
_ = cleanup()
return nil, fmt.Errorf("open Store shared cache: %w", err)
}
return &StoreCache{cache: cache, ctx: ctx, opener: opener, cleanup: cleanup, slides: make(map[uint64]map[uint64]uint64)}, nil
}
func (s *StoreCache) Close() error {
return errors.Join(s.cache.Close(), s.cleanup())
}
// Page returns one unslid 4 KiB data page. Runtime-initialized metadata is applied
// separately by the versioned Store profile; these bytes always come from Apple.
func (s *StoreCache) Page(address uint64) ([]byte, error) {
if err := s.ctx.Err(); err != nil {
return nil, fmt.Errorf("read Store page: %w", err)
}
if address&4095 != 0 {
return nil, errors.New("unaligned Store page")
}
mapping, err := s.cache.mappingForAddress(address)
if err != nil {
return nil, err
}
data := make([]byte, 4096)
reader := &dyldCacheReader{cache: s.cache}
if _, err = reader.ReadAtAddr(data, address); err != nil {
return nil, fmt.Errorf("read Store page: %w", err)
}
if mapping.slideInfoSize == 0 {
return data, nil
}
pageSize, err := s.cache.slidePageSize(*mapping)
if err != nil {
return nil, err
}
index := (address - mapping.address) / pageSize
base := mapping.address + index*pageSize
rebases, ok := s.slides[base]
if !ok {
values, err := s.cache.rebases(*mapping, index, index+1)
if err != nil {
return nil, err
}
rebases = make(map[uint64]uint64, len(values))
for _, value := range values {
rebases[value.address] = value.target
}
s.slides[base] = rebases
}
for location, target := range rebases {
if location >= address && location+8 <= address+4096 {
binary.LittleEndian.PutUint64(data[location-address:], target)
}
}
return data, nil
}
// ExtractAuthenticationPlugin exports the same image on every host platform.
func (s *StoreCache) ExtractAuthenticationPlugin(destination string) error {
if err := s.ctx.Err(); err != nil {
return fmt.Errorf("extract authentication plugin: %w", err)
}
return extractDyldImageFromFiles(s.opener, authenticationPluginImage, destination)
}
// FeatureFlags reads the pinned operating system defaults used by Store metadata.
func (s *StoreCache) FeatureFlags(domain string) ([]byte, error) {
switch domain {
case "AppleMediaServices", "Foundation", "CFNetwork":
default:
return nil, errors.New("unsupported Store feature domain")
}
return s.readSystemFile("/System/Library/FeatureFlags/Domain/" + domain + ".plist")
}
+131
View File
@@ -0,0 +1,131 @@
package assets
import (
"encoding/binary"
"fmt"
"github.com/blacktop/go-macho"
machotypes "github.com/blacktop/go-macho/types"
)
// AddressRange reports the unslid virtual range occupied by cache mappings.
func (s *StoreCache) AddressRange() (uint64, uint64) {
start, end := ^uint64(0), uint64(0)
for _, member := range s.cache.members {
for _, mapping := range member.mappings {
start = min(start, mapping.address)
end = max(end, mapping.address+mapping.size)
}
}
return start, end - start
}
// Images lists the image install names recorded in the downloaded shared cache.
func (s *StoreCache) Images() (map[string]uint64, error) {
if s.images != nil {
return s.images, nil
}
header := make([]byte, dyldHeaderSize)
if _, err := s.cache.primary.file.ReadAt(header, 0); err != nil {
return nil, fmt.Errorf("read Store cache header: %w", err)
}
offset := uint64(binary.LittleEndian.Uint32(header[448:]))
count := uint64(binary.LittleEndian.Uint32(header[452:]))
if count == 0 || count > dyldMaximumImages || !validDyldRange(s.cache.primary.size, offset, count*dyldImageInfoSize) {
return nil, fmt.Errorf("invalid Store image table")
}
data := make([]byte, count*dyldImageInfoSize)
if _, err := s.cache.primary.file.ReadAt(data, int64(offset)); err != nil {
return nil, fmt.Errorf("read Store image table: %w", err)
}
images := make(map[string]uint64, count)
for index := uint64(0); index < count; index++ {
entry := data[index*dyldImageInfoSize:]
name, err := readDyldCString(s.cache.primary.file, s.cache.primary.size, uint64(binary.LittleEndian.Uint32(entry[24:])))
if err != nil {
return nil, err
}
images[name] = binary.LittleEndian.Uint64(entry)
}
s.images = images
return images, nil
}
// OpenImage exposes Mach-O metadata directly from the cache; no host image is loaded.
func (s *StoreCache) OpenImage(name string) (*macho.File, error) {
if s.cache.relativeSelectorBase == 0 {
objc, err := s.cache.image("/usr/lib/libobjc.A.dylib")
if err != nil {
return nil, err
}
f, err := s.cache.openImage(objc, machotypes.LC_SYMTAB, machotypes.LC_DYSYMTAB)
if err != nil {
return nil, err
}
defer f.Close()
for _, section := range f.Sections {
if section.Name == "__objc_opt_ro" {
page, err := s.Page(section.Addr &^ 4095)
if err != nil {
return nil, err
}
off := section.Addr & 4095
if off+48 > uint64(len(page)) || section.Size < 48 {
return nil, fmt.Errorf("invalid ObjC optimization header")
}
if binary.LittleEndian.Uint32(page[off:]) != 16 {
return nil, fmt.Errorf("unsupported ObjC optimization version")
}
s.cache.relativeSelectorBase = section.Addr + binary.LittleEndian.Uint64(page[off+40:])
}
}
}
images, err := s.Images()
if err != nil {
return nil, err
}
address, ok := images[name]
if !ok {
return nil, fmt.Errorf("image %s was not found", name)
}
mapping, err := s.cache.mappingForAddress(address)
if err != nil {
return nil, err
}
return s.cache.openImage(&dyldImage{member: mapping.member, address: address, offset: mapping.fileOffset + address - mapping.address}, machotypes.LC_SYMTAB, machotypes.LC_DYSYMTAB)
}
// Contains reports whether a range is backed by one shared-cache mapping.
func (s *StoreCache) Contains(address, size uint64) bool {
for _, member := range s.cache.members {
for _, m := range member.mappings {
if address >= m.address && address-m.address <= m.size && size <= m.size-(address-m.address) {
return true
}
}
}
return false
}
+55
View File
@@ -0,0 +1,55 @@
package assets
import (
"archive/zip"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("macOS 27 asset profile", func() {
It("pins the Apple restore image and cache namespace", func() {
Expect(macOSVersion).To(Equal("27.0.1"))
Expect(macOSBuild).To(Equal("26A434"))
Expect(macOSRestoreURL).To(Equal("https://updates.cdn-apple.com/2026FallFCS/59241290-5d51-4ca8-9df4-31624b9a4eac/UniversalMac_27.0.1_26A434_Restore.ipsw"))
Expect(assetCacheDirectory).To(ContainSubstring("macos-27-26A434"))
})
It("preserves the pinned legacy artifacts for migration", func() {
Expect(legacyFiles).To(ConsistOf(
fileSpec{name: "AppleMediaServices", size: 14813888, digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4")},
fileSpec{name: "commerce", size: 8092640, digest: mustDigest("76de40a4a32f691947cb926ce3b128d2fc446f7cac9755f831c406cf5a316ac9")},
fileSpec{name: "adid", size: 9797952, digest: mustDigest("1fec225b6917206e3d9b00fe636c04878f82bfd06a87a4b6941711de60efab5b")},
fileSpec{name: "CoreFP", size: 94842464, digest: mustDigest("2c30fa2b5f695fd66c0360dce72f54757d03ddb7107549715c12cb359a003b46")},
fileSpec{name: "CoreFP.icxs", size: 7365344, digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b")},
fileSpec{name: "fairplayd", size: 37689264, digest: mustDigest("28b4c7b2a5a0409c5020da55fc3984713a8e2b0eec8557076c8717f7166d003e")},
fileSpec{name: "FairPlayIOKit", size: 2132320, digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025")},
))
})
It("pins compact runtime artifacts by size and digest", func() {
Expect(requiredFiles).To(ConsistOf(
fileSpec{name: "AppleMediaServices", size: 14813888, digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4")},
fileSpec{name: "commerce", size: 2735088, digest: mustDigest("c4b2088dd39aeb353f59cb57597902e8317aec66ae7da0414b03c5f932771343")},
fileSpec{name: "adid", size: 3047808, digest: mustDigest("43419a206c28bc93ecb8884256088d18306a0a462350f83adbced8e60a94e390")},
fileSpec{name: "CoreFP", size: 30764976, digest: mustDigest("afbc123e688a822d980d5816cc2b52f69fde669d1dca92cf85627e1cbee587f6")},
fileSpec{name: "CoreFP.icxs", size: 7365344, digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b")},
fileSpec{name: "fairplayd", size: 17389744, digest: mustDigest("1e58d37e9602dd0ca5e24b14762063b6c310248b4d3a94272771d815e4ea1784")},
fileSpec{name: "FairPlayIOKit", size: 2132320, digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025")},
))
})
It("pins the CoreADI path and deflated kernel entry", func() {
Expect(frameworkImagePaths).To(ContainElement("/System/Library/PrivateFrameworks/CoreADI.framework/Versions/A/adid"))
archive := &zip.Reader{File: []*zip.File{{FileHeader: zip.FileHeader{
Name: kernelCacheName, Method: zip.Deflate,
CompressedSize64: kernelCacheCompressedSize, UncompressedSize64: kernelCacheArchiveSize,
}}}}
_, err := pinnedZipEntry(archive, kernelCacheName, kernelCacheCompressedSize, kernelCacheArchiveSize)
Expect(err).NotTo(HaveOccurred())
})
It("rejects an incomplete bundle", func() {
Expect(validate(Bundle{})).To(MatchError(ContainSubstring("AppleMediaServices has size 0")))
})
})
+821
View File
@@ -0,0 +1,821 @@
package machimage
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"sort"
"github.com/blacktop/go-macho"
"github.com/blacktop/go-macho/pkg/fixupchains"
"github.com/blacktop/go-macho/types"
)
const (
pageSize = uint64(0x1000)
maxImageSpan = uint64(1 << 30)
pointerSize = uint64(8)
)
type Memory interface {
MemMap(address, size uint64) error
MemWrite(address uint64, data []byte) error
}
type segment struct {
name string
address uint64
size uint64
fileOff uint64
fileSize uint64
}
type Image struct {
name string
data []byte
modified map[uint64][]byte
instructions map[uint64][]instructionPatch
file *macho.File
base uint64
segments []segment
binds []types.Bind
rebases []types.Rebase
chained *fixupchains.DyldChainedFixups
fixups []chainedRelocation
relocated bool
loadedBase uint64
}
func (i *Image) Base() uint64 {
return i.base
}
//nolint:wsl // Image validation and fixup discovery are clearer in execution order.
func Open(name string, input []byte) (*Image, error) {
data, err := arm64Slice(input)
if err != nil {
return nil, fmt.Errorf("open %s: %w", name, err)
}
return openImage(name, data, nil)
}
func openImage(name string, data []byte, modified map[uint64][]byte) (*Image, error) {
image := &Image{name: name, data: data, modified: modified}
var reader io.ReaderAt = bytes.NewReader(data)
if modified != nil {
reader = imageInput{image}
}
var key [sha256.Size]byte
var preparation imagePreparation
var cached bool
if modified != nil {
key = sha256.Sum256(data)
preparation, cached = imagePreparations.get(key)
}
var file *macho.File
var err error
if cached {
file, err = macho.NewFile(reader, macho.FileConfig{LoadExcluding: []types.LoadCmd{types.LC_SYMTAB, types.LC_DYSYMTAB, types.LC_CODE_SIGNATURE}})
if err == nil {
file.Symtab, file.Dysymtab = preparation.symtab, preparation.dysymtab
}
} else {
file, err = macho.NewFile(reader)
}
if err != nil {
return nil, fmt.Errorf("open %s Mach-O: %w", name, err)
}
if file.CPU != types.CPUArm64 {
return nil, fmt.Errorf("open %s: expected arm64 Mach-O, found %s", name, file.CPU)
}
image.file = file
image.base = file.GetBaseAddress()
for _, item := range file.Segments() {
image.segments = append(image.segments, segment{
name: item.Name,
address: item.Addr,
size: item.Memsz,
fileOff: item.Offset,
fileSize: item.Filesz,
})
}
if err := image.validateSegments(); err != nil {
return nil, err
}
if cached {
image.instructions, image.fixups = preparation.instructions, preparation.fixups
image.binds, image.rebases = preparation.binds, preparation.rebases
return image, nil
}
if err := image.removePointerAuthentication(); err != nil {
return nil, err
}
if file.HasDyldChainedFixups() {
image.chained, err = file.DyldChainedFixups()
if err != nil {
return nil, fmt.Errorf("read %s chained fixups: %w", name, err)
}
if _, err := image.chained.Parse(); err != nil {
return nil, fmt.Errorf("parse %s chained fixups: %w", name, err)
}
} else {
image.binds, err = file.GetBindInfo()
if err != nil && !errors.Is(err, macho.ErrMachODyldInfoNotFound) {
return nil, fmt.Errorf("read %s bindings: %w", name, err)
}
image.rebases, err = file.GetRebaseInfo()
if err != nil && !errors.Is(err, macho.ErrMachODyldInfoNotFound) {
return nil, fmt.Errorf("read %s rebases: %w", name, err)
}
}
if modified != nil {
if image.chained != nil {
image.fixups, err = image.decodeChainedRelocations()
if err != nil {
return nil, err
}
image.chained = nil
}
imagePreparations.put(key, imagePreparation{instructions: image.instructions, fixups: image.fixups, binds: image.binds, rebases: image.rebases, symtab: file.Symtab, dysymtab: file.Dysymtab})
}
return image, nil
}
func (i *Image) removePointerAuthentication() error {
var ranges [][2]uint64
for _, section := range i.file.Sections {
if !section.Flags.IsPureInstructions() && !section.Flags.IsSomeInstructions() {
continue
}
start := uint64(section.Offset)
end, overflow := add(start, section.Size)
if overflow || end > uint64(len(i.data)) {
return fmt.Errorf("instruction section %s exceeds %s", section.Name, i.name)
}
ranges = append(ranges, [2]uint64{start, end})
}
for _, region := range ranges {
for offset := region[0]; offset+4 <= region[1]; offset += 4 {
instruction := binary.LittleEndian.Uint32(i.data[offset:])
replacement := WithoutPointerAuthentication(instruction)
if replacement == instruction {
continue
}
i.writeInstruction(offset, replacement)
}
}
return nil
}
// WithoutPointerAuthentication rewrites ARM64e authentication operations for a
// VM with canonical, unsigned pointers. Other instructions are unchanged.
func WithoutPointerAuthentication(instruction uint32) uint32 {
const nop = uint32(0xd503201f)
var replacement uint32
switch instruction & 0xfffffc00 {
case 0xd71f0800, 0xd71f0c00, 0xd61f0800, 0xd61f0c00:
replacement = 0xd61f0000 | (instruction & 0x3e0) // br xN
case 0xd73f0800, 0xd73f0c00, 0xd63f0800, 0xd63f0c00:
replacement = 0xd63f0000 | (instruction & 0x3e0) // blr xN
case 0xdac10000, 0xdac10400, 0xdac10800, 0xdac10c00,
0xdac11000, 0xdac11400, 0xdac11800, 0xdac11c00:
replacement = nop
default:
switch instruction {
case 0xd65f0bff, 0xd65f0fff:
replacement = 0xd65f03c0 // ret
case 0xd503211f, 0xd503215f, 0xd503219f, 0xd50321df,
0xd503233f, 0xd503237f, 0xd50323bf, 0xd50323ff,
0xd50320ff:
replacement = nop
default:
opcode := instruction & 0xffffffe0
if opcode == 0xdac123e0 || opcode == 0xdac127e0 ||
opcode == 0xdac12be0 || opcode == 0xdac12fe0 ||
opcode == 0xdac133e0 || opcode == 0xdac137e0 ||
opcode == 0xdac13be0 || opcode == 0xdac13fe0 ||
opcode == 0xdac143e0 || opcode == 0xdac147e0 {
replacement = nop
}
}
}
if replacement == 0 {
return instruction
}
return replacement
}
// ARM64Slice selects the arm64e image without parsing the other architectures.
// The returned view aliases input and must not be modified by the caller.
func ARM64Slice(input []byte) ([]byte, error) {
if len(input) < 4 || binary.BigEndian.Uint32(input) != types.MagicFat.Int() {
return input, nil
}
const headerSize, architectureSize = 8, 20
if len(input) < headerSize {
return nil, errors.New("truncated universal binary header")
}
count := uint64(binary.BigEndian.Uint32(input[4:]))
if count == 0 || count > uint64(len(input)-headerSize)/architectureSize {
return nil, errors.New("invalid universal binary architecture count")
}
for index := uint64(0); index < count; index++ {
header := input[headerSize+index*architectureSize:]
cpu := types.CPU(binary.BigEndian.Uint32(header))
subtype := types.CPUSubtype(binary.BigEndian.Uint32(header[4:]))
if cpu != types.CPUArm64 || subtype&types.CpuSubtypeMask != types.CPUSubtypeArm64E {
continue
}
offset := uint64(binary.BigEndian.Uint32(header[8:]))
size := uint64(binary.BigEndian.Uint32(header[12:]))
end, overflow := add(offset, size)
if size == 0 || offset < headerSize+count*architectureSize || overflow || end > uint64(len(input)) {
return nil, errors.New("arm64e slice exceeds input size or overlaps universal binary header")
}
return input[offset:end], nil
}
return nil, errors.New("universal binary has no arm64e slice")
}
func arm64Slice(input []byte) ([]byte, error) {
data, err := ARM64Slice(input)
if err != nil {
return nil, err
}
return bytes.Clone(data), nil
}
func (i *Image) Export(name string, loadBase uint64) (uint64, error) {
address, err := i.file.FindSymbolAddress(name)
if err != nil {
return 0, fmt.Errorf("find %s in %s: %w", name, i.name, err)
}
if address < i.base {
return 0, fmt.Errorf("symbol %s in %s precedes image base", name, i.name)
}
result, overflow := add(loadBase, address-i.base)
if overflow {
return 0, fmt.Errorf("symbol %s address overflows in %s", name, i.name)
}
return result, nil
}
func (i *Image) Relocate(loadBase uint64, resolve func(string) (uint64, error)) error {
if i.relocated {
return fmt.Errorf("%s is already relocated", i.name)
}
for _, relocation := range i.rebases {
if relocation.Type != types.REBASE_TYPE_POINTER {
return fmt.Errorf("%s uses unsupported rebase type %d", i.name, relocation.Type)
}
if relocation.Value < i.base {
return fmt.Errorf("%s contains a rebase below its image base", i.name)
}
offset, err := i.segmentFileOffset(relocation.Segment, relocation.Offset, pointerSize)
if err != nil {
return err
}
address, overflow := add(loadBase, relocation.Value-i.base)
if overflow {
return fmt.Errorf("rebase address overflows in %s", i.name)
}
if err := i.putPointer(offset, address); err != nil {
return err
}
}
for _, binding := range i.binds {
// Lazy bind streams may omit SET_TYPE; dyld's default is a pointer bind.
if binding.Type != 0 && binding.Type != types.BIND_TYPE_POINTER {
return fmt.Errorf("%s uses unsupported bind type %d for %s", i.name, binding.Type, binding.Name)
}
offset, err := i.segmentFileOffset(binding.Segment, binding.SegOffset, pointerSize)
if err != nil {
return err
}
address, err := resolve(binding.Name)
if err != nil {
return fmt.Errorf("resolve %s for %s: %w", binding.Name, i.name, err)
}
address, err = addSigned(address, binding.Addend)
if err != nil {
return fmt.Errorf("apply addend for %s in %s: %w", binding.Name, i.name, err)
}
if err := i.putPointer(offset, address); err != nil {
return err
}
}
if err := i.relocateChained(loadBase, resolve); err != nil {
return err
}
i.relocated = true
i.loadedBase = loadBase
return nil
}
// RelocateKernelCachePointers decodes authenticated pointers embedded in an
// executable extracted from a kernel collection. These are already fixed up
// for the collection and are not described by the image's standalone Mach-O
// bind/rebase streams.
func (i *Image) RelocateKernelCachePointers(loadBase, kernelBase uint64, resolve func(string) (uint64, error)) error {
externalSymbols := make(map[uint64]string)
if i.file.Symtab != nil {
for _, symbol := range i.file.Symtab.Syms {
if symbol.Value == 0 || i.containsAddress(symbol.Value) {
continue
}
externalSymbols[symbol.Value] = symbol.Name
}
}
for _, item := range i.segments {
if item.name == "__TEXT" || item.name == "__TEXT_EXEC" || item.name == "__LINKEDIT" || item.fileSize < pointerSize {
continue
}
const kernelFixupStride = uint64(4)
start := item.fileOff
if remainder := item.address % kernelFixupStride; remainder != 0 {
start += kernelFixupStride - remainder
}
end := item.fileOff + item.fileSize
for offset := start; offset <= end-pointerSize; offset += kernelFixupStride {
raw := i.pointerAt(offset)
pointer := fixupchains.DyldChainedPtr64KernelCacheRebase{Pointer: raw}
if pointer.CacheLevel() != 0 || pointer.Target() == 0 {
continue
}
original, overflow := add(kernelBase, pointer.Target())
if overflow {
continue
}
var relocated uint64
if i.containsAddress(original) {
relocated, overflow = add(loadBase, original-i.base)
if overflow {
return fmt.Errorf("kernel-cache pointer at %#x overflows in %s", offset, i.name)
}
} else if name, ok := externalSymbols[original]; ok {
var err error
relocated, err = resolve(name)
if err != nil {
return fmt.Errorf("resolve kernel-cache pointer %s at %#x in %s: %w", name, offset, i.name, err)
}
} else {
continue
}
if err := i.putPointer(offset, relocated); err != nil {
return err
}
}
}
return nil
}
func (i *Image) containsAddress(address uint64) bool {
for _, item := range i.segments {
if address >= item.address && address-item.address < item.size {
return true
}
}
return false
}
//nolint:wsl // Chained-fixup decoding is clearer when related operations stay together.
func (i *Image) decodeChainedRelocations() ([]chainedRelocation, error) {
if i.chained == nil {
return nil, nil
}
var relocations []chainedRelocation
for _, start := range i.chained.Starts {
for _, fixup := range start.Fixups {
offset := fixup.Offset()
if offset > uint64(len(i.data)) || pointerSize > uint64(len(i.data))-offset {
return nil, fmt.Errorf("chained fixup at %#x exceeds %s", offset, i.name)
}
relocation := chainedRelocation{offset: offset}
switch {
case fixup.IsRebase():
var target uint64
switch rebase := fixup.(type) {
case fixupchains.DyldChainedPtr64RebaseOffset:
// DYLD_CHAINED_PTR_64_OFFSET encodes an image-relative
// target. go-macho's Rebase currently subtracts the
// preferred address from that offset a second time.
target = rebase.UnpackedTarget()
case fixupchains.DyldChainedPtrArm64eRebase:
target = rebase.Target()
if i.chained.PointerFormat == fixupchains.DYLD_CHAINED_PTR_ARM64E {
absolute := rebase.UnpackTarget() & 0x00ffffffffffffff
if absolute < i.base {
return nil, fmt.Errorf("chained rebase at %#x precedes the base of %s", offset, i.name)
}
target = absolute - i.base
}
case fixupchains.DyldChainedPtrArm64eAuthRebase:
target = rebase.Target()
default:
var err error
target, err = i.chained.Rebase(offset, i.base)
if err != nil {
return nil, fmt.Errorf("decode chained rebase at %#x in %s: %w", offset, i.name, err)
}
}
relocation.target = target
case fixup.IsBind():
binding, ok := fixup.(fixupchains.Bind)
if !ok {
return nil, fmt.Errorf("invalid chained bind at %#x in %s", offset, i.name)
}
relocation.isBind = true
relocation.symbol = binding.Name()
addend := int64(binding.Addend())
switch arm64e := fixup.(type) {
case fixupchains.DyldChainedPtrArm64eBind:
addend = arm64e.SignExtendedAddend()
case fixupchains.DyldChainedPtrArm64eBind24:
addend = arm64e.SignExtendedAddend()
}
if ordinal := binding.Ordinal(); ordinal < uint64(len(i.chained.Imports)) {
addend += int64(i.chained.Imports[ordinal].Addend())
}
relocation.addend = addend
default:
return nil, fmt.Errorf("unknown chained fixup at %#x in %s", offset, i.name)
}
relocations = append(relocations, relocation)
}
}
return relocations, nil
}
func (i *Image) relocateChained(loadBase uint64, resolve func(string) (uint64, error)) error {
relocations := i.fixups
if i.chained != nil {
var err error
relocations, err = i.decodeChainedRelocations()
if err != nil {
return err
}
}
for _, relocation := range relocations {
var address uint64
if relocation.isBind {
value, err := resolve(relocation.symbol)
if err != nil {
return fmt.Errorf("resolve %s for %s: %w", relocation.symbol, i.name, err)
}
address, err = addSigned(value, relocation.addend)
if err != nil {
return fmt.Errorf("apply chained addend for %s in %s: %w", relocation.symbol, i.name, err)
}
} else {
var overflow bool
address, overflow = add(loadBase, relocation.target)
if overflow {
return fmt.Errorf("chained rebase at %#x with target %#x overflows in %s", relocation.offset, relocation.target, i.name)
}
}
if err := i.putPointer(relocation.offset, address); err != nil {
return err
}
}
return nil
}
// PreparePrelinked prepares an image extracted from a dyld shared cache. Such
// images have already had their cache slide information applied, so they must
// remain at their preferred addresses. external maps cache symbol addresses to
// the import names implemented by the emulator.
func (i *Image) PreparePrelinked(external map[uint64]string, resolve func(string) (uint64, error)) error {
if i.relocated {
return fmt.Errorf("%s is already relocated", i.name)
}
patched := make(map[uint64]uint64, len(external))
for address, name := range external {
value, err := resolve(name)
if err != nil {
return fmt.Errorf("resolve %s for %s: %w", name, i.name, err)
}
patched[address] = value
}
if len(patched) == 0 {
i.relocated = true
i.loadedBase = i.base
return nil
}
for _, item := range i.segments {
if item.name == "__TEXT" || item.name == "__LINKEDIT" || item.fileSize < pointerSize {
continue
}
start := item.fileOff
if remainder := item.address % pointerSize; remainder != 0 {
start += pointerSize - remainder
}
end := item.fileOff + item.fileSize
for offset := start; offset <= end-pointerSize; offset += pointerSize {
current := i.pointerAt(offset)
value, ok := patched[current]
if !ok {
continue
}
if err := i.putPointer(offset, value); err != nil {
return err
}
}
}
i.relocated = true
i.loadedBase = i.base
return nil
}
func (i *Image) Load(memory Memory) error {
if !i.relocated {
return fmt.Errorf("%s must be relocated before loading", i.name)
}
type memoryRange struct {
start uint64
end uint64
}
ranges := make([]memoryRange, 0, len(i.segments))
for _, item := range i.segments {
if item.name == "__PAGEZERO" || item.size == 0 {
continue
}
if item.address < i.base {
return fmt.Errorf("segment %s in %s precedes image base", item.name, i.name)
}
address, overflow := add(i.loadedBase, item.address-i.base)
if overflow {
return fmt.Errorf("segment %s address overflows in %s", item.name, i.name)
}
end, overflow := add(address, item.size)
if overflow {
return fmt.Errorf("segment %s range overflows in %s", item.name, i.name)
}
ranges = append(ranges, memoryRange{start: address - address%pageSize, end: align(end, pageSize)})
}
if len(ranges) == 0 {
return fmt.Errorf("%s has no loadable segments", i.name)
}
sort.Slice(ranges, func(left, right int) bool { return ranges[left].start < ranges[right].start })
merged := ranges[:0]
for _, current := range ranges {
last := len(merged) - 1
if last >= 0 && current.start <= merged[last].end {
merged[last].end = max(merged[last].end, current.end)
continue
}
merged = append(merged, current)
}
var mapped uint64
for _, item := range merged {
size := item.end - item.start
mapped, _ = add(mapped, size)
if mapped > maxImageSpan {
return fmt.Errorf("mapped segments make %s too large", i.name)
}
if err := memory.MemMap(item.start, size); err != nil {
return fmt.Errorf("map %s: %w", i.name, err)
}
}
var buffer []byte
if len(i.modified) > 0 || len(i.instructions) > 0 {
buffer = make([]byte, min(128<<10, len(i.data)))
}
for _, item := range i.segments {
if item.name == "__PAGEZERO" || item.fileSize == 0 {
continue
}
end, overflow := add(item.fileOff, item.fileSize)
if overflow || end > uint64(len(i.data)) {
return fmt.Errorf("segment %s data exceeds %s", item.name, i.name)
}
address, overflow := add(i.loadedBase, item.address-i.base)
if overflow {
return fmt.Errorf("segment %s address overflows in %s", item.name, i.name)
}
if err := i.writeSegment(memory, address, item.fileOff, end, buffer); err != nil {
return fmt.Errorf("write segment %s from %s: %w", item.name, i.name, err)
}
}
return nil
}
func (i *Image) validateSegments() error {
for _, item := range i.segments {
if item.fileSize > item.size {
return fmt.Errorf("segment %s file data exceeds its memory size in %s", item.name, i.name)
}
if _, overflow := add(item.address, item.size); overflow {
return fmt.Errorf("segment %s address range overflows in %s", item.name, i.name)
}
end, overflow := add(item.fileOff, item.fileSize)
if overflow || end > uint64(len(i.data)) {
return fmt.Errorf("segment %s data exceeds %s", item.name, i.name)
}
}
return nil
}
func (i *Image) segmentFileOffset(name string, offset, size uint64) (uint64, error) {
for _, item := range i.segments {
if item.name != name {
continue
}
segmentEnd, overflow := add(offset, size)
if overflow || segmentEnd > item.size {
return 0, fmt.Errorf("fixup at %#x exceeds segment %s in %s", offset, name, i.name)
}
if segmentEnd > item.fileSize {
return 0, fmt.Errorf("fixup at %#x exceeds file data for segment %s in %s", offset, name, i.name)
}
result, overflow := add(item.fileOff, offset)
if overflow {
return 0, fmt.Errorf("fixup offset overflows in %s", i.name)
}
end, overflow := add(result, size)
if overflow || end > uint64(len(i.data)) {
return 0, fmt.Errorf("fixup at %#x exceeds %s", result, i.name)
}
return result, nil
}
return 0, fmt.Errorf("fixup references unknown segment %s in %s", name, i.name)
}
func (i *Image) putPointer(offset, value uint64) error {
end, overflow := add(offset, 8)
if overflow || end > uint64(len(i.data)) {
return fmt.Errorf("fixup at %#x exceeds %s", offset, i.name)
}
var data [8]byte
binary.LittleEndian.PutUint64(data[:], value)
i.writeAt(offset, data[:])
return nil
}
func addSigned(value uint64, delta int64) (uint64, error) {
if delta >= 0 {
result, overflow := add(value, uint64(delta))
if overflow {
return 0, errors.New("address overflow")
}
return result, nil
}
magnitude := uint64(-(delta + 1)) + 1
if magnitude > value {
return 0, errors.New("address underflow")
}
return value - magnitude, nil
}
func add(left, right uint64) (uint64, bool) {
return left + right, right > math.MaxUint64-left
}
func align(value, alignment uint64) uint64 {
return (value + alignment - 1) &^ (alignment - 1)
}
+149
View File
@@ -0,0 +1,149 @@
package machimage
import (
"math"
"strings"
"testing"
"github.com/blacktop/go-macho/types"
)
func TestValidateSegments(t *testing.T) {
tests := []struct {
name string
dataLen int
segment segment
wantErr string
}{
{
name: "valid",
dataLen: 32,
segment: segment{name: "__DATA", address: 0x1000, size: 16, fileOff: 8, fileSize: 16},
},
{
name: "file data exceeds memory",
dataLen: 32,
segment: segment{name: "__DATA", address: 0x1000, size: 8, fileOff: 8, fileSize: 16},
wantErr: "file data exceeds its memory size",
},
{
name: "file data exceeds image",
dataLen: 16,
segment: segment{name: "__DATA", address: 0x1000, size: 16, fileOff: 8, fileSize: 16},
wantErr: "data exceeds",
},
{
name: "file range overflows",
dataLen: 32,
segment: segment{name: "__DATA", address: 0x1000, size: 16, fileOff: math.MaxUint64 - 7, fileSize: 16},
wantErr: "data exceeds",
},
{
name: "address range overflows",
dataLen: 32,
segment: segment{name: "__DATA", address: math.MaxUint64 - 7, size: 16},
wantErr: "address range overflows",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
image := Image{name: "test", data: make([]byte, test.dataLen), segments: []segment{test.segment}}
err := image.validateSegments()
if test.wantErr == "" {
if err != nil {
t.Fatalf("validateSegments() error = %v", err)
}
return
}
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
t.Fatalf("validateSegments() error = %v, want error containing %q", err, test.wantErr)
}
})
}
}
func TestSegmentFileOffsetBounds(t *testing.T) {
image := Image{
name: "test",
data: make([]byte, 64),
segments: []segment{
{name: "__DATA", address: 0x1000, size: 24, fileOff: 16, fileSize: 16},
{name: "__SHORT", address: 0x2000, size: 16, fileOff: 56, fileSize: 16},
},
}
tests := []struct {
name string
segment string
offset uint64
want uint64
wantErr string
}{
{name: "valid at end", segment: "__DATA", offset: 8, want: 24},
{name: "past file data", segment: "__DATA", offset: 9, wantErr: "exceeds file data"},
{name: "past memory", segment: "__DATA", offset: 17, wantErr: "exceeds segment"},
{name: "past image", segment: "__SHORT", offset: 8, wantErr: "exceeds test"},
{name: "offset overflow", segment: "__DATA", offset: math.MaxUint64 - 3, wantErr: "exceeds segment"},
{name: "unknown segment", segment: "__MISSING", wantErr: "unknown segment"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got, err := image.segmentFileOffset(test.segment, test.offset, pointerSize)
if test.wantErr == "" {
if err != nil {
t.Fatalf("segmentFileOffset() error = %v", err)
}
if got != test.want {
t.Fatalf("segmentFileOffset() = %#x, want %#x", got, test.want)
}
return
}
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
t.Fatalf("segmentFileOffset() error = %v, want error containing %q", err, test.wantErr)
}
})
}
}
func TestRelocateRejectsFixupsOutsideTheirSegments(t *testing.T) {
tests := []struct {
name string
binds []types.Bind
rebases []types.Rebase
}{
{
name: "bind",
binds: []types.Bind{{Name: "symbol", Segment: "__DATA", SegOffset: 9}},
},
{
name: "rebase",
rebases: []types.Rebase{{Type: types.REBASE_TYPE_POINTER, Segment: "__DATA", Offset: 9, Value: 0x1000}},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
image := Image{
name: "test",
data: make([]byte, 64),
base: 0x1000,
segments: []segment{{name: "__DATA", address: 0x1000, size: 32, fileOff: 16, fileSize: 16}},
binds: test.binds,
rebases: test.rebases,
}
err := image.Relocate(0x2000, func(string) (uint64, error) { return 0x3000, nil })
if err == nil || !strings.Contains(err.Error(), "exceeds file data") {
t.Fatalf("Relocate() error = %v, want file-data bounds error", err)
}
})
}
}
+26
View File
@@ -0,0 +1,26 @@
package machimage
import "github.com/blacktop/go-macho"
// Symbols returns the immutable symbol table used for guest exports and ivars.
// Callers must not modify the returned slice.
func (i *Image) Symbols() []macho.Symbol {
if i.file.Symtab == nil {
return nil
}
return i.file.Symtab.Syms
}
// InstructionRanges returns the guest's executable section address ranges.
func (i *Image) InstructionRanges() [][2]uint64 {
var ranges [][2]uint64
for _, section := range i.file.Sections {
if section.Flags.IsPureInstructions() || section.Flags.IsSomeInstructions() {
ranges = append(ranges, [2]uint64{section.Addr, section.Addr + section.Size})
}
}
return ranges
}
+112
View File
@@ -0,0 +1,112 @@
package machimage
import (
"crypto/sha256"
"sync"
"unsafe"
"github.com/blacktop/go-macho"
"github.com/blacktop/go-macho/types"
)
const (
maxImagePreparations = 8
maxPreparationBytes = 64 << 20
)
type chainedRelocation struct {
offset, target uint64
addend int64
symbol string
isBind bool
}
type instructionPatch struct {
offset uint64
value uint32
}
type imagePreparation struct {
instructions map[uint64][]instructionPatch
fixups []chainedRelocation
binds []types.Bind
rebases []types.Rebase
symtab *macho.Symtab
dysymtab *macho.Dysymtab
}
func (p imagePreparation) size() int {
size := cap(p.fixups)*int(unsafe.Sizeof(chainedRelocation{})) + cap(p.binds)*int(unsafe.Sizeof(types.Bind{})) + cap(p.rebases)*int(unsafe.Sizeof(types.Rebase{}))
for _, patches := range p.instructions {
size += cap(patches) * int(unsafe.Sizeof(instructionPatch{}))
}
for _, fixup := range p.fixups {
size += len(fixup.symbol)
}
for _, bind := range p.binds {
size += len(bind.Name)
}
if p.symtab != nil {
size += cap(p.symtab.Syms)*int(unsafe.Sizeof(macho.Symbol{})) + cap(p.symtab.LoadBytes)
for _, symbol := range p.symtab.Syms {
size += len(symbol.Name) + len(symbol.IndirectName)
}
}
if p.dysymtab != nil {
size += cap(p.dysymtab.IndirectSyms)*4 + cap(p.dysymtab.LoadBytes)
}
return size
}
type imagePreparationCache struct {
mu sync.Mutex
entries map[[sha256.Size]byte]imagePreparation
order [][sha256.Size]byte
bytes int
}
// Cache only immutable instruction patches, symbol tables and decoded relocations. Every guest
// supplies its own load bases, import addresses and mutable memory.
var imagePreparations imagePreparationCache
func (c *imagePreparationCache) get(key [sha256.Size]byte) (imagePreparation, bool) {
c.mu.Lock()
defer c.mu.Unlock()
prepared, ok := c.entries[key]
return prepared, ok
}
func (c *imagePreparationCache) put(key [sha256.Size]byte, prepared imagePreparation) {
size := prepared.size()
if size > maxPreparationBytes {
return
}
c.mu.Lock()
defer c.mu.Unlock()
if _, exists := c.entries[key]; exists {
return
}
if c.entries == nil {
c.entries = make(map[[sha256.Size]byte]imagePreparation)
}
for len(c.order) >= maxImagePreparations || c.bytes+size > maxPreparationBytes {
oldest := c.order[0]
c.bytes -= c.entries[oldest].size()
delete(c.entries, oldest)
c.order = c.order[1:]
}
c.order = append(c.order, key)
c.entries[key] = prepared
c.bytes += size
}
+68
View File
@@ -0,0 +1,68 @@
package machimage
import (
"encoding/binary"
"errors"
"fmt"
"io"
"github.com/blacktop/go-macho/types"
)
// ARM64Range locates a thin image or the arm64e slice using only its headers.
// It leaves unselected architectures unread for range-backed remote sources.
func ARM64Range(source io.ReaderAt, size int64) (int64, int64, error) {
if size < 0 {
return 0, 0, errors.New("invalid image size")
}
var header [8]byte
if size < 4 {
return 0, size, nil
}
if _, err := source.ReadAt(header[:4], 0); err != nil {
return 0, 0, fmt.Errorf("read image magic: %w", err)
}
if binary.BigEndian.Uint32(header[:]) != types.MagicFat.Int() {
return 0, size, nil
}
if size < 8 {
return 0, 0, errors.New("truncated universal binary header")
}
if _, err := source.ReadAt(header[4:], 4); err != nil {
return 0, 0, fmt.Errorf("read universal binary header: %w", err)
}
count := int64(binary.BigEndian.Uint32(header[4:]))
if count == 0 || count > (size-8)/20 {
return 0, 0, errors.New("invalid universal binary architecture count")
}
var architecture [20]byte
for index := int64(0); index < count; index++ {
if _, err := source.ReadAt(architecture[:], 8+index*20); err != nil {
return 0, 0, fmt.Errorf("read universal binary architecture: %w", err)
}
cpu := types.CPU(binary.BigEndian.Uint32(architecture[:]))
subtype := types.CPUSubtype(binary.BigEndian.Uint32(architecture[4:]))
if cpu != types.CPUArm64 || subtype&types.CpuSubtypeMask != types.CPUSubtypeArm64E {
continue
}
offset, length := int64(binary.BigEndian.Uint32(architecture[8:])), int64(binary.BigEndian.Uint32(architecture[12:]))
if length == 0 || offset < 8+count*20 || offset > size || length > size-offset {
return 0, 0, errors.New("arm64e slice exceeds input size or overlaps universal binary header")
}
return offset, length, nil
}
return 0, 0, errors.New("universal binary has no arm64e slice")
}
+70
View File
@@ -0,0 +1,70 @@
package machimage
import (
"bytes"
"encoding/binary"
"io"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
type headerReader struct {
input []byte
read int
end int64
}
func (r *headerReader) ReadAt(data []byte, offset int64) (int, error) {
r.read += len(data)
r.end = max(r.end, offset+int64(len(data)))
return bytes.NewReader(r.input).ReadAt(data, offset) //nolint:wrapcheck // ReaderAt adapters preserve io.EOF.
}
var _ = Describe("Remote architecture selection", func() {
It("reads only the architecture headers", func() {
input := universalImage()
reader := &headerReader{input: input}
offset, size, err := ARM64Range(reader, int64(len(input)))
Expect(err).NotTo(HaveOccurred())
Expect(offset).To(Equal(int64(52)))
Expect(size).To(Equal(int64(4)))
Expect(reader.end).To(BeNumerically("<=", 48))
Expect(reader.read).To(BeNumerically("<=", 48))
})
It("keeps thin images whole", func() {
data := []byte("thin image")
reader := &headerReader{input: data}
offset, size, err := ARM64Range(reader, int64(len(data)))
Expect(err).NotTo(HaveOccurred())
Expect(offset).To(BeZero())
Expect(size).To(Equal(int64(len(data))))
Expect(reader.read).To(Equal(4))
})
It("rejects invalid counts and out-of-bounds slices", func() {
for _, index := range []int{4, 36, 40} {
data := universalImage()
binary.BigEndian.PutUint32(data[index:], ^uint32(0))
_, _, err := ARM64Range(bytes.NewReader(data), int64(len(data)))
Expect(err).To(HaveOccurred())
}
})
It("reports truncated headers and missing arm64e slices", func() {
data := universalImage()
_, _, err := ARM64Range(bytes.NewReader(data[:10]), int64(len(data)))
Expect(err).To(HaveOccurred())
binary.BigEndian.PutUint32(data[32:], 0)
_, _, err = ARM64Range(bytes.NewReader(data), int64(len(data)))
Expect(err).To(MatchError(ContainSubstring("no arm64e slice")))
})
It("handles tiny files and rejects a negative declared size", func() {
_, size, err := ARM64Range(bytes.NewReader([]byte{1}), 1)
Expect(err).NotTo(HaveOccurred())
Expect(size).To(Equal(int64(1)))
_, _, err = ARM64Range(bytes.NewReader(nil), -1)
Expect(err).To(HaveOccurred())
_, _, err = ARM64Range(io.NewSectionReader(bytes.NewReader(nil), 0, 4), 4)
Expect(err).To(HaveOccurred())
})
})
+103
View File
@@ -0,0 +1,103 @@
package machimage
import (
"encoding/binary"
"errors"
"fmt"
"io"
"github.com/blacktop/go-macho/types"
)
// ReadARM64 consumes exactly size bytes, retaining only the arm64e image of a
// universal binary. A caller can hash the entire input with an io.TeeReader.
func ReadARM64(input io.Reader, size int) ([]byte, error) {
if size < 0 {
return nil, errors.New("invalid image size")
}
var header [8]byte
prefix := min(size, 4)
if _, err := io.ReadFull(input, header[:prefix]); err != nil {
return nil, fmt.Errorf("read image magic: %w", err)
}
if prefix < 4 || binary.BigEndian.Uint32(header[:]) != types.MagicFat.Int() {
data := make([]byte, size)
copy(data, header[:prefix])
if _, err := io.ReadFull(input, data[prefix:]); err != nil {
return nil, fmt.Errorf("read thin image: %w", err)
}
return data, nil
}
if size < 8 {
return nil, errors.New("truncated universal binary header")
}
if _, err := io.ReadFull(input, header[4:]); err != nil {
return nil, fmt.Errorf("read universal binary header: %w", err)
}
count := uint64(binary.BigEndian.Uint32(header[4:]))
if count == 0 || count > uint64(size-8)/20 {
return nil, errors.New("invalid universal binary architecture count")
}
var offset, length uint64
var arch [20]byte
for range count {
if _, err := io.ReadFull(input, arch[:]); err != nil {
return nil, fmt.Errorf("read universal binary architecture: %w", err)
}
cpu := types.CPU(binary.BigEndian.Uint32(arch[:]))
subtype := types.CPUSubtype(binary.BigEndian.Uint32(arch[4:]))
if length == 0 && cpu == types.CPUArm64 && subtype&types.CpuSubtypeMask == types.CPUSubtypeArm64E {
offset = uint64(binary.BigEndian.Uint32(arch[8:]))
length = uint64(binary.BigEndian.Uint32(arch[12:]))
if length == 0 || offset < 8+count*20 || offset+length > uint64(size) {
return nil, errors.New("arm64e slice exceeds input size or overlaps universal binary header")
}
}
}
if length == 0 {
return nil, errors.New("universal binary has no arm64e slice")
}
buffer := make([]byte, 256<<10)
if err := discardImageBytes(input, offset-(8+count*20), buffer); err != nil {
return nil, fmt.Errorf("read universal binary prefix: %w", err)
}
data := make([]byte, int(length))
if _, err := io.ReadFull(input, data); err != nil {
return nil, fmt.Errorf("read arm64e image: %w", err)
}
if err := discardImageBytes(input, uint64(size)-offset-length, buffer); err != nil {
return nil, fmt.Errorf("read universal binary suffix: %w", err)
}
return data, nil
}
func discardImageBytes(input io.Reader, count uint64, buffer []byte) error {
for count > 0 {
size := min(count, uint64(len(buffer)))
if _, err := io.ReadFull(input, buffer[:size]); err != nil {
return fmt.Errorf("consume image bytes: %w", err)
}
count -= size
}
return nil
}
+52
View File
@@ -0,0 +1,52 @@
package machimage
import (
"bytes"
"crypto/sha256"
"errors"
"io"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Streaming ARM64 extraction", func() {
It("hashes discarded bytes and stops at the declared size", func() {
fat := append(universalImage(), []byte("unused suffix")...)
reader := bytes.NewReader(append(bytes.Clone(fat), []byte("trailer")...))
digest := sha256.New()
data, err := ReadARM64(io.TeeReader(reader, digest), len(fat))
Expect(err).NotTo(HaveOccurred())
Expect(string(data)).To(Equal("arm!"))
expected := sha256.Sum256(fat)
Expect(digest.Sum(nil)).To(Equal(expected[:]))
trailing, err := io.ReadAll(reader)
Expect(err).NotTo(HaveOccurred())
Expect(string(trailing)).To(Equal("trailer"))
})
It("preserves thin and short input", func() {
for _, input := range [][]byte{nil, {1}, {1, 2, 3}, []byte("thin image")} {
data, err := ReadARM64(bytes.NewReader(input), len(input))
Expect(err).NotTo(HaveOccurred())
Expect(bytes.Equal(data, input)).To(BeTrue())
}
})
It("rejects a negative size", func() {
_, err := ReadARM64(bytes.NewReader(nil), -1)
Expect(err).To(MatchError(ContainSubstring("invalid image size")))
})
It("rejects truncation before, inside, and after the selected slice", func() {
input := append(universalImage(), []byte("suffix")...)
for _, length := range []int{0, 4, 7, 20, 48, 53, 55, 59} {
_, err := ReadARM64(bytes.NewReader(input[:length]), len(input))
Expect(err).To(HaveOccurred())
Expect(errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF)).To(BeTrue())
}
})
It("rejects invalid architecture ranges before allocating their data", func() {
input := universalImage()
input[40] = 0xff
_, err := ReadARM64(bytes.NewReader(input), len(input))
Expect(err).To(MatchError(ContainSubstring("exceeds input size")))
})
})
+159
View File
@@ -0,0 +1,159 @@
package machimage
import (
"bytes"
"encoding/binary"
"fmt"
"io"
)
// OpenShared borrows immutable image bytes and copies only pages changed by
// relocation. Instruction patches are applied while loading into guest memory.
// Input must remain unchanged while the Image is used.
func OpenShared(name string, input []byte) (*Image, error) {
data, err := ARM64Slice(input)
if err != nil {
return nil, fmt.Errorf("open %s: %w", name, err)
}
return openImage(name, data, make(map[uint64][]byte))
}
func (i *Image) writeAt(offset uint64, data []byte) {
if i.modified == nil {
copy(i.data[offset:], data)
return
}
for len(data) > 0 {
page := offset &^ (pageSize - 1)
buffer := i.modified[page]
if buffer == nil {
buffer = bytes.Clone(i.data[page:min(page+pageSize, uint64(len(i.data)))])
i.overlay(buffer, page)
i.modified[page] = buffer
}
count := copy(buffer[offset-page:], data)
offset += uint64(count)
data = data[count:]
}
}
func (i *Image) pointerAt(offset uint64) uint64 {
pageStart := offset &^ (pageSize - 1)
if offset+pointerSize <= pageStart+pageSize {
if page := i.modified[pageStart]; page != nil {
return binary.LittleEndian.Uint64(page[offset-pageStart:])
}
if len(i.instructions[pageStart]) == 0 {
return binary.LittleEndian.Uint64(i.data[offset:])
}
}
var value [8]byte
copy(value[:], i.data[offset:offset+8])
i.overlay(value[:], offset)
return binary.LittleEndian.Uint64(value[:])
}
func (i *Image) writeInstruction(offset uint64, value uint32) {
if i.modified != nil {
if i.instructions == nil {
i.instructions = make(map[uint64][]instructionPatch)
}
for page := offset &^ (pageSize - 1); page < offset+4; page += pageSize {
i.instructions[page] = append(i.instructions[page], instructionPatch{offset, value})
}
return
}
var data [4]byte
binary.LittleEndian.PutUint32(data[:], value)
i.writeAt(offset, data[:])
}
// Overlay private relocations and immutable instruction patches. Clip each page
// and patch to the destination, including unaligned segment and chunk boundaries.
func (i *Image) overlay(data []byte, offset uint64) {
end := offset + uint64(len(data))
for page := offset &^ (pageSize - 1); page < end; page += pageSize {
first, last := max(page, offset), min(page+pageSize, end)
if modified := i.modified[page]; modified != nil {
copy(data[first-offset:last-offset], modified[first-page:last-page])
continue
}
for _, patch := range i.instructions[page] {
start, stop := max(first, patch.offset), min(last, patch.offset+4)
if start >= stop {
continue
}
var encoded [4]byte
binary.LittleEndian.PutUint32(encoded[:], patch.value)
copy(data[start-offset:stop-offset], encoded[start-patch.offset:stop-patch.offset])
}
}
}
// Keep staging memory bounded regardless of image size and guest count.
func (i *Image) writeSegment(memory Memory, address, start, end uint64, buffer []byte) error {
if len(i.modified) == 0 && len(i.instructions) == 0 {
if err := memory.MemWrite(address, i.data[start:end]); err != nil {
return fmt.Errorf("write image data: %w", err)
}
return nil
}
for position := start; position < end; {
stop := min(position+uint64(len(buffer)), end)
data := buffer[:stop-position]
copy(data, i.data[position:stop])
i.overlay(data, position)
if err := memory.MemWrite(address+position-start, data); err != nil {
return fmt.Errorf("write image chunk: %w", err)
}
position = stop
}
return nil
}
// Mach-O fixup parsing must observe the same rewritten bytes that will be loaded
// into the guest, including instruction patches in mixed code/data sections.
type imageInput struct{ image *Image }
func (r imageInput) ReadAt(data []byte, offset int64) (int, error) {
if offset < 0 {
return 0, fmt.Errorf("invalid image offset %d", offset)
}
if offset >= int64(len(r.image.data)) {
return 0, io.EOF
}
count := copy(data, r.image.data[offset:])
if len(r.image.instructions) > 0 || len(r.image.modified) > 0 {
r.image.overlay(data[:count], uint64(offset))
}
if count < len(data) {
return count, io.EOF
}
return count, nil
}
+207
View File
@@ -0,0 +1,207 @@
package machimage
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"github.com/blacktop/go-macho/types"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
// One instruction page and one data page following the Mach-O headers.
func sharedFixture() []byte {
data := make([]byte, 3*pageSize)
for n, v := range []uint32{0xfeedfacf, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 6, 2, 176, 0, 0} {
binary.LittleEndian.PutUint32(data[n*4:], v)
}
binary.LittleEndian.PutUint32(data[32:], 25)
binary.LittleEndian.PutUint32(data[36:], 152)
copy(data[40:], "__TEXT")
for n, v := range []uint64{0x100000000, uint64(len(data)), 0, uint64(len(data))} {
binary.LittleEndian.PutUint64(data[56+n*8:], v)
}
for n, v := range []uint32{7, 7, 1, 0} {
binary.LittleEndian.PutUint32(data[88+n*4:], v)
}
copy(data[104:], "__text")
copy(data[120:], "__TEXT")
binary.LittleEndian.PutUint64(data[136:], 0x100001000)
binary.LittleEndian.PutUint64(data[144:], pageSize)
binary.LittleEndian.PutUint32(data[152:], uint32(pageSize))
binary.LittleEndian.PutUint32(data[156:], 2)
binary.LittleEndian.PutUint32(data[168:], 0x80000400)
for n, v := range []uint32{2, 24, 512, 1, 528, 8} {
binary.LittleEndian.PutUint32(data[184+n*4:], v)
}
binary.LittleEndian.PutUint32(data[512:], 1)
data[516], data[517] = 0x0f, 1
binary.LittleEndian.PutUint64(data[520:], 0x100001000)
copy(data[528:], []byte{0, 't', 'a', 'r', 'g', 'e', 't', 0})
binary.LittleEndian.PutUint32(data[4096:], 0xd503233f)
return data
}
type imageMemory struct {
data []byte
base uint64
fail error
}
func (m *imageMemory) MemMap(uint64, uint64) error { return nil }
func (m *imageMemory) MemWrite(address uint64, data []byte) error {
if m.fail != nil {
return m.fail
}
copy(m.data[address-m.base:], data)
return nil
}
var _ = Describe("Shared image preparation", func() {
It("shares instruction patches and isolates relocation and source bytes", func() {
source := sharedFixture()
original := bytes.Clone(source)
first, err := OpenShared("first", source)
Expect(err).NotTo(HaveOccurred())
second, err := OpenShared("second", source)
Expect(err).NotTo(HaveOccurred())
Expect(&first.data[0]).To(BeIdenticalTo(&source[0]))
Expect(&first.instructions[4096][0]).To(BeIdenticalTo(&second.instructions[4096][0]))
Expect(first.modified).To(BeEmpty())
Expect(first.file.Symtab).To(BeIdenticalTo(second.file.Symtab))
exported, err := second.Export("target", 0x300000000)
Expect(err).NotTo(HaveOccurred())
Expect(exported).To(Equal(uint64(0x300001000)))
Expect(second.InstructionRanges()).To(Equal([][2]uint64{{0x100001000, 0x100002000}}))
Expect(second.Symbols()).To(HaveLen(1))
first.binds = []types.Bind{{Name: "target", Segment: "__TEXT", SegOffset: 8192, Type: types.BIND_TYPE_POINTER}}
second.binds = first.binds
Expect(first.Relocate(0x200000000, func(string) (uint64, error) { return 0x1111, nil })).To(Succeed())
Expect(second.Relocate(0x300000000, func(string) (uint64, error) { return 0x2222, nil })).To(Succeed())
Expect(second.putPointer(4092, 0x8877665544332211)).To(Succeed())
Expect(second.pointerAt(4092)).To(Equal(uint64(0x8877665544332211)))
Expect(first.pointerAt(4092)).To(Equal(uint64(0xd503201f00000000)))
for _, test := range []struct {
image *Image
base, value uint64
}{{first, 0x200000000, 0x1111}, {second, 0x300000000, 0x2222}} {
memory := &imageMemory{base: test.base, data: make([]byte, len(source))}
Expect(test.image.Load(memory)).To(Succeed())
Expect(binary.LittleEndian.Uint64(memory.data[8192:])).To(Equal(test.value))
if test.image == first {
Expect(binary.LittleEndian.Uint32(memory.data[4096:])).To(Equal(uint32(0xd503201f)))
}
}
Expect(source).To(Equal(original))
})
It("keeps concurrent guests independent while sharing preparation", func() {
source := sharedFixture()
source[len(source)-2] = 77
finished := make(chan error, 8)
for n := range 8 {
go func() {
image, err := OpenShared("concurrent", source)
if err == nil {
image.binds = []types.Bind{{Name: "target", Segment: "__TEXT", SegOffset: 8192, Type: types.BIND_TYPE_POINTER}}
expected := uint64(n+1) * 4096
err = image.Relocate(uint64(n+1)<<32, func(string) (uint64, error) { return expected, nil })
if err == nil && image.pointerAt(8192) != expected {
err = fmt.Errorf("guest %d has another guest's binding", n)
}
}
finished <- err
}()
}
for range 8 {
Eventually(finished).Should(Receive(BeNil()))
}
})
It("applies cached chained relocations with each guest's own addresses", func() {
source := make([]byte, 4096)
plan := []chainedRelocation{{offset: 0, target: 0x80}, {offset: 8, isBind: true, symbol: "target", addend: -4}}
for _, base := range []uint64{0x1000, 0x2000} {
image := &Image{data: source, modified: map[uint64][]byte{}, fixups: plan}
Expect(image.relocateChained(base, func(string) (uint64, error) { return base + 0x404, nil })).To(Succeed())
Expect(image.pointerAt(0)).To(Equal(base + 0x80))
Expect(image.pointerAt(8)).To(Equal(base + 0x400))
}
Expect(source).To(Equal(make([]byte, 4096)))
})
It("overlays patches across unaligned page, segment, and chunk boundaries", func() {
source := make([]byte, 3*pageSize+13)
image := &Image{data: source, modified: map[uint64][]byte{}}
image.writeInstruction(4094, 0x11223344)
Expect(image.pointerAt(4092)).To(Equal(uint64(0x112233440000)))
var decoded [8]byte
count, err := (imageInput{image}).ReadAt(decoded[:], 4092)
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(8))
Expect(binary.LittleEndian.Uint64(decoded[:])).To(Equal(uint64(0x112233440000)))
Expect(image.putPointer(4095, 0xaabbccddeeff0011)).To(Succeed())
expected := bytes.Clone(source)
binary.LittleEndian.PutUint32(expected[4094:], 0x11223344)
binary.LittleEndian.PutUint64(expected[4095:], 0xaabbccddeeff0011)
memory := &imageMemory{data: make([]byte, len(source))}
Expect(image.writeSegment(memory, 0, 3, uint64(len(source)), make([]byte, 4093))).To(Succeed())
Expect(memory.data[:len(source)-3]).To(Equal(expected[3:]))
})
It("invalidates preparation when any source byte changes", func() {
source := sharedFixture()
first, err := OpenShared("first", source)
Expect(err).NotTo(HaveOccurred())
changed := bytes.Clone(source)
changed[len(changed)-1] = 1
second, err := OpenShared("second", changed)
Expect(err).NotTo(HaveOccurred())
Expect(&first.instructions[4096][0]).NotTo(BeIdenticalTo(&second.instructions[4096][0]))
})
It("preserves write errors and rejects fixups outside the image", func() {
image, err := OpenShared("image", sharedFixture())
Expect(err).NotTo(HaveOccurred())
Expect(image.Relocate(image.Base(), nil)).To(Succeed())
failed := errors.New("write failure")
Expect(errors.Is(image.Load(&imageMemory{fail: failed}), failed)).To(BeTrue())
Expect(image.putPointer(uint64(len(image.data)-7), 1)).NotTo(Succeed())
})
})
var _ = Describe("Image preparation cache bounds", func() {
It("evicts old preparations when the image count is exceeded", func() {
var cache imagePreparationCache
first := sha256.Sum256([]byte{0})
for n := 0; n <= maxImagePreparations; n++ {
cache.put(sha256.Sum256([]byte{byte(n)}), imagePreparation{})
}
_, ok := cache.get(first)
Expect(ok).To(BeFalse())
Expect(cache.entries).To(HaveLen(maxImagePreparations))
})
It("bounds retained patch and fixup storage", func() {
var cache imagePreparationCache
key := sha256.Sum256([]byte("first"))
large := imagePreparation{instructions: map[uint64][]instructionPatch{0: make([]instructionPatch, 0, maxPreparationBytes/16+1)}}
cache.put(key, large)
_, ok := cache.get(key)
Expect(ok).To(BeFalse())
half := imagePreparation{instructions: map[uint64][]instructionPatch{0: large.instructions[0][: 0 : maxPreparationBytes/32+1]}}
cache.put(key, half)
second := sha256.Sum256([]byte("second"))
cache.put(second, half)
_, ok = cache.get(key)
Expect(ok).To(BeFalse())
Expect(cache.bytes).To(BeNumerically("<=", maxPreparationBytes))
})
})
+98
View File
@@ -0,0 +1,98 @@
package machimage
import (
"bytes"
"encoding/binary"
"testing"
"github.com/blacktop/go-macho/types"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestImageGinkgo(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Mach-O Image Suite")
}
func universalImage() []byte {
data := make([]byte, 56)
for index, value := range []uint32{
types.MagicFat.Int(), 2,
uint32(types.CPUAmd64), 3, 48, 4, 0,
uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 52, 4, 0,
} {
binary.BigEndian.PutUint32(data[index*4:], value)
}
copy(data[48:], []byte("x86!arm!"))
return data
}
var _ = Describe("ARM64 image selection", func() {
It("selects arm64e without parsing unused architectures", func() {
input := universalImage()
data, err := ARM64Slice(input)
Expect(err).NotTo(HaveOccurred())
Expect(string(data)).To(Equal("arm!"))
Expect(&data[0]).To(BeIdenticalTo(&input[52]))
})
It("preserves thin image data", func() {
input := []byte("thin image")
data, err := ARM64Slice(input)
Expect(err).NotTo(HaveOccurred())
Expect(&data[0]).To(BeIdenticalTo(&input[0]))
})
It("isolates mutable relocation data from the source bundle", func() {
for _, input := range [][]byte{universalImage(), []byte("thin image")} {
original := bytes.Clone(input)
data, err := arm64Slice(input)
Expect(err).NotTo(HaveOccurred())
data[0] ^= 0xff
Expect(input).To(Equal(original))
}
})
DescribeTable("rejects malformed universal images", func(mutate func([]byte) []byte, message string) {
_, err := ARM64Slice(mutate(universalImage()))
Expect(err).To(MatchError(ContainSubstring(message)))
},
Entry("truncated header", func(b []byte) []byte { return b[:4] }, "header"),
Entry("truncated architecture table", func(b []byte) []byte { return b[:47] }, "architecture count"),
Entry("no architectures", func(b []byte) []byte {
binary.BigEndian.PutUint32(b[4:], 0)
return b
}, "architecture count"),
Entry("excessive count", func(b []byte) []byte {
binary.BigEndian.PutUint32(b[4:], ^uint32(0))
return b
}, "architecture count"),
Entry("no arm64e image", func(b []byte) []byte {
binary.BigEndian.PutUint32(b[32:], 0)
return b
}, "no arm64e slice"),
Entry("slice past the end", func(b []byte) []byte {
binary.BigEndian.PutUint32(b[40:], 5)
return b
}, "exceeds input size"),
Entry("empty slice", func(b []byte) []byte {
binary.BigEndian.PutUint32(b[40:], 0)
return b
}, "exceeds input size"),
Entry("overlapping header", func(b []byte) []byte {
binary.BigEndian.PutUint32(b[36:], 8)
return b
}, "overlaps"),
Entry("large offset", func(b []byte) []byte {
binary.BigEndian.PutUint32(b[36:], ^uint32(0))
return b
}, "exceeds input size"),
)
})
+40
View File
@@ -0,0 +1,40 @@
package machine
import (
"encoding/binary"
"encoding/hex"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("portable IOAES", func() {
DescribeTable("evaluates FairPlay hardware handles with the emulated key",
func(handle uint32) {
keyData := make([]byte, 40)
binary.LittleEndian.PutUint32(keyData[36:40], handle)
plaintext := make([]byte, 16)
iv := make([]byte, 16)
expected, err := hex.DecodeString("66e94bd4ef8a2c3b884cfa59ca342b2e")
Expect(err).NotTo(HaveOccurred())
ciphertext, outputIV, err := emulateIOAES(plaintext, iv, 0, keyData)
Expect(err).NotTo(HaveOccurred())
Expect(ciphertext).To(Equal(expected))
Expect(outputIV).To(Equal(expected))
decrypted, outputIV, err := emulateIOAES(ciphertext, iv, 1, keyData)
Expect(err).NotTo(HaveOccurred())
Expect(decrypted).To(Equal(plaintext))
Expect(outputIV).To(Equal(ciphertext))
},
Entry("commerce", commerceAESHandle),
)
It("rejects unrelated key handles", func() {
keyData := make([]byte, 40)
binary.LittleEndian.PutUint32(keyData[36:40], 1)
_, _, err := emulateIOAES(make([]byte, 16), make([]byte, 16), 0, keyData)
Expect(err).To(MatchError("unsupported IOAES key handle 0x1"))
})
})
+227
View File
@@ -0,0 +1,227 @@
//nolint:wsl // Instruction decoding is clearer when related operations stay together.
package machine
import (
"encoding/binary"
"fmt"
"github.com/majd/ipatool/v2/internal/sap/unicorn"
)
const (
arm64AtomicMask = uint32(0xffe0fc00)
arm64CASAL32 = uint32(0x88e0fc00)
arm64CASAL64 = uint32(0xc8e0fc00)
arm64SWPAL32 = uint32(0xb8e08000)
arm64SWPAL64 = uint32(0xf8e08000)
arm64EOR3Mask = uint32(0xffe08000)
arm64EOR3 = uint32(0xce000000)
)
type arm64Compatibility struct {
engine *unicorn.Engine
}
func newARM64Compatibility(engine *unicorn.Engine) *arm64Compatibility {
return &arm64Compatibility{engine: engine}
}
func (c *arm64Compatibility) emulateInvalidInstruction() (bool, error) {
pc, err := c.engine.RegRead(unicorn.RegPC)
if err != nil {
return false, fmt.Errorf("read arm64 instruction address: %w", err)
}
data, err := c.engine.MemRead(pc, 4)
if err != nil {
return false, nil
}
instruction := binary.LittleEndian.Uint32(data)
if instruction&arm64EOR3Mask == arm64EOR3 {
if err := c.emulateEOR3(instruction); err != nil {
return false, err
}
if err := c.engine.RegWrite(unicorn.RegPC, pc+4); err != nil {
return false, fmt.Errorf("advance arm64 instruction address: %w", err)
}
return true, nil
}
opcode := instruction & arm64AtomicMask
var width uint64
switch opcode {
case arm64CASAL32, arm64SWPAL32:
width = 4
case arm64CASAL64, arm64SWPAL64:
width = 8
default:
return false, nil
}
source := (instruction >> 16) & 31
base := (instruction >> 5) & 31
destination := instruction & 31
address, err := c.readBaseRegister(base)
if err != nil {
return false, err
}
memory, err := c.engine.MemRead(address, width)
if err != nil {
return false, fmt.Errorf("read arm64 atomic operand at %#x: %w", address, err)
}
oldValue := binary.LittleEndian.Uint64(append(memory, make([]byte, 8-width)...))
sourceValue, err := c.readValueRegister(source)
if err != nil {
return false, err
}
if width == 4 {
sourceValue = uint64(uint32(sourceValue))
}
switch opcode {
case arm64CASAL32, arm64CASAL64:
newValue, readErr := c.readValueRegister(destination)
if readErr != nil {
return false, readErr
}
if width == 4 {
newValue = uint64(uint32(newValue))
}
if oldValue == sourceValue {
if err := c.writeMemoryValue(address, newValue, width); err != nil {
return false, err
}
}
if err := c.writeValueRegister(source, oldValue); err != nil {
return false, err
}
case arm64SWPAL32, arm64SWPAL64:
if err := c.writeMemoryValue(address, sourceValue, width); err != nil {
return false, err
}
if err := c.writeValueRegister(destination, oldValue); err != nil {
return false, err
}
}
if err := c.engine.RegWrite(unicorn.RegPC, pc+4); err != nil {
return false, fmt.Errorf("advance arm64 instruction address: %w", err)
}
return true, nil
}
func (c *arm64Compatibility) emulateEOR3(instruction uint32) error {
destination := instruction & 31
first := (instruction >> 5) & 31
third := (instruction >> 10) & 31
second := (instruction >> 16) & 31
firstValue, err := c.engine.RegRead128(unicorn.RegV0 + int(first))
if err != nil {
return fmt.Errorf("read arm64 vector register %d: %w", first, err)
}
secondValue, err := c.engine.RegRead128(unicorn.RegV0 + int(second))
if err != nil {
return fmt.Errorf("read arm64 vector register %d: %w", second, err)
}
thirdValue, err := c.engine.RegRead128(unicorn.RegV0 + int(third))
if err != nil {
return fmt.Errorf("read arm64 vector register %d: %w", third, err)
}
var result [16]byte
for index := range result {
result[index] = firstValue[index] ^ secondValue[index] ^ thirdValue[index]
}
if err := c.engine.RegWrite128(unicorn.RegV0+int(destination), result); err != nil {
return fmt.Errorf("write arm64 vector register %d: %w", destination, err)
}
return nil
}
func (c *arm64Compatibility) readBaseRegister(index uint32) (uint64, error) {
register := unicorn.RegSP
if index != 31 {
var ok bool
register, ok = arm64GeneralRegister(index)
if !ok {
return 0, fmt.Errorf("invalid arm64 base register %d", index)
}
}
value, err := c.engine.RegRead(register)
if err != nil {
return 0, fmt.Errorf("read arm64 base register %d: %w", index, err)
}
return value, nil
}
func (c *arm64Compatibility) readValueRegister(index uint32) (uint64, error) {
if index == 31 {
return 0, nil
}
register, ok := arm64GeneralRegister(index)
if !ok {
return 0, fmt.Errorf("invalid arm64 value register %d", index)
}
value, err := c.engine.RegRead(register)
if err != nil {
return 0, fmt.Errorf("read arm64 value register %d: %w", index, err)
}
return value, nil
}
func (c *arm64Compatibility) writeValueRegister(index uint32, value uint64) error {
if index == 31 {
return nil
}
register, ok := arm64GeneralRegister(index)
if !ok {
return fmt.Errorf("invalid arm64 value register %d", index)
}
if err := c.engine.RegWrite(register, value); err != nil {
return fmt.Errorf("write arm64 value register %d: %w", index, err)
}
return nil
}
func (c *arm64Compatibility) writeMemoryValue(address, value, width uint64) error {
var data [8]byte
binary.LittleEndian.PutUint64(data[:], value)
if err := c.engine.MemWrite(address, data[:width]); err != nil {
return fmt.Errorf("write arm64 atomic operand at %#x: %w", address, err)
}
return nil
}
func arm64GeneralRegister(index uint32) (int, bool) {
switch {
case index <= 28:
return unicorn.RegX0 + int(index), true
case index == 29:
return unicorn.RegX29, true
case index == 30:
return unicorn.RegLR, true
default:
return 0, false
}
}
+45
View File
@@ -0,0 +1,45 @@
package machine
import (
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"errors"
"fmt"
)
const commerceAESHandle = uint32(0x89c)
// emulateIOAES evaluates the device-key handle used by the pinned FairPlay
// runtime without delegating to the host operating system.
func emulateIOAES(source, iv []byte, operation uint32, keyData []byte) ([]byte, []byte, error) {
if len(source) == 0 || len(source)%aes.BlockSize != 0 || len(iv) != aes.BlockSize || len(keyData) != 40 {
return nil, nil, errors.New("invalid IOAES parameters")
}
handle := binary.LittleEndian.Uint32(keyData[36:40])
if handle != commerceAESHandle {
return nil, nil, fmt.Errorf("unsupported IOAES key handle %#x", handle)
}
block, err := aes.NewCipher(make([]byte, aes.BlockSize))
if err != nil {
return nil, nil, fmt.Errorf("initialize IOAES cipher: %w", err)
}
destination := make([]byte, len(source))
outputIV := make([]byte, aes.BlockSize)
switch operation {
case 0:
cipher.NewCBCEncrypter(block, iv).CryptBlocks(destination, source)
copy(outputIV, destination[len(destination)-aes.BlockSize:])
case 1:
copy(outputIV, source[len(source)-aes.BlockSize:])
cipher.NewCBCDecrypter(block, iv).CryptBlocks(destination, source)
default:
return nil, nil, fmt.Errorf("unsupported IOAES operation %#x", operation)
}
return destination, outputIV, nil
}
+70
View File
@@ -0,0 +1,70 @@
package machine
import (
"context"
"errors"
"fmt"
"github.com/majd/ipatool/v2/internal/sap/assets"
)
// GenerateKBSync creates the account and hardware bound FairPlay data required
// by the bag's ent/download endpoint, without opening a decryption session.
func GenerateKBSync(ctx context.Context, bundle assets.Bundle, hardwareID []byte, dsid uint64) ([]byte, error) {
if ctx == nil {
return nil, errors.New("StoreAgent context is nil")
}
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("generate kbsync: %w", err)
}
if dsid == 0 {
return nil, errors.New("kbsync requires a nonzero account DSID")
}
agent, globalContext, err := openStoreAgentGlobal(ctx, bundle, hardwareID)
if err != nil {
return nil, err
}
defer agent.Close()
return agent.guest.generateKBSync(storeAgentKBSyncEntry, globalContext, dsid)
}
func (m *Machine) generateKBSync(entry uint64, globalContext uint32, dsid uint64) ([]byte, error) {
m.beginCall()
defer m.clearScratch()
pointerField, err := m.scratch(nil, 8)
if err != nil {
return nil, err
}
// StoreAgent writes a uint32 length. Zero the upper half so consumeOutput
// can share the SAP buffer bounds checking and storage disposal.
lengthField, err := m.scratch(nil, 8)
if err != nil {
return nil, err
}
status, err := m.invoke(entry, uint64(globalContext), dsid, 0, 1, pointerField, lengthField)
if err != nil {
return nil, fmt.Errorf("generate StoreAgent kbsync: %w", err)
}
output, outputErr := m.consumeOutput(pointerField, lengthField)
if int32(status) != 0 {
return nil, errors.Join(fmt.Errorf("StoreAgent kbsync returned %d", int32(status)), outputErr)
}
if outputErr != nil {
return nil, outputErr
}
if len(output) == 0 {
return nil, errors.New("StoreAgent kbsync returned an empty buffer")
}
return output, nil
}
+91
View File
@@ -0,0 +1,91 @@
package machine
import (
"context"
"encoding/binary"
"github.com/majd/ipatool/v2/internal/sap/assets"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("StoreAgent kbsync", func() {
It("pins the kbsync entry in the verified StoreAgent image", func() {
Expect(storeAgentKBSyncEntry).To(Equal(storeAgentBase + 0x19ae34))
})
It("rejects a canceled context before loading assets", func() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := GenerateKBSync(ctx, assets.Bundle{}, []byte{1}, 123)
Expect(err).To(MatchError(ContainSubstring(context.Canceled.Error())))
})
It("rejects missing context or account identity before loading assets", func() {
var missingContext context.Context
_, err := GenerateKBSync(missingContext, assets.Bundle{}, nil, 123)
Expect(err).To(MatchError("StoreAgent context is nil"))
_, err = GenerateKBSync(context.Background(), assets.Bundle{}, nil, 0)
Expect(err).To(MatchError("kbsync requires a nonzero account DSID"))
})
DescribeTable("copies and disposes guest output with the StoreAgent ABI",
func(pointer, length uint64, status uint32, wantError string) {
guest := newGinkgoServiceMachine(shimOptions{})
data := []byte{0, 4, 0, 1, 42}
Expect(guest.engine.MemWrite(heapBase, data)).To(Succeed())
var disposed []uint64
dispose, err := guest.services.addFunction("test.kbsync.dispose", func() error {
address, err := guest.services.argument(0)
Expect(err).NotTo(HaveOccurred())
disposed = append(disposed, address)
return guest.services.setResult(0)
})
Expect(err).NotTo(HaveOccurred())
guest.entry.dispose = dispose
entry, err := guest.services.addFunction("test.kbsync.generate", func() error {
for index, expected := range []uint64{0x1234, 0x123456789abcdef0, 0, 1} {
argument, err := guest.services.argument(index)
Expect(err).NotTo(HaveOccurred())
Expect(argument).To(Equal(expected))
}
pointerField, err := guest.services.argument(4)
Expect(err).NotTo(HaveOccurred())
Expect(guest.writeUint64(pointerField, pointer)).To(Succeed())
lengthField, err := guest.services.argument(5)
Expect(err).NotTo(HaveOccurred())
// Only the low 32 bits are written by the real entry point.
Expect(guest.engine.MemWrite(lengthField, binary.LittleEndian.AppendUint32(nil, uint32(length)))).To(Succeed())
return guest.services.setResult(uint64(status))
})
Expect(err).NotTo(HaveOccurred())
output, err := guest.generateKBSync(entry, 0x1234, 0x123456789abcdef0)
if wantError == "" {
Expect(err).NotTo(HaveOccurred())
Expect(output).To(Equal(data))
} else {
Expect(err).To(MatchError(ContainSubstring(wantError)))
Expect(output).To(BeNil())
}
if pointer != 0 {
Expect(disposed).To(Equal([]uint64{pointer}))
} else {
Expect(disposed).To(BeEmpty())
}
Expect(guest.scratchCursor).To(BeZero())
Expect(guest.engine.MemRead(scratchBase, 32)).To(Equal(make([]byte, 32)))
},
Entry("valid blob", heapBase, uint64(5), uint32(0), ""),
Entry("guest error still releases storage", heapBase, uint64(5), ^uint32(41), "kbsync returned -42"),
Entry("oversized blob", heapBase, maxOutputSize+1, uint32(0), "maximum is"),
Entry("null pointer", uint64(0), uint64(5), uint32(0), "null output pointer"),
Entry("empty blob", heapBase, uint64(0), uint32(0), "empty buffer"),
)
})
+740
View File
@@ -0,0 +1,740 @@
package machine
import (
"context"
"encoding/binary"
"errors"
"fmt"
"math"
"time"
"github.com/majd/ipatool/v2/internal/sap/assets"
"github.com/majd/ipatool/v2/internal/sap/machimage"
"github.com/majd/ipatool/v2/internal/sap/unicorn"
)
const sapGuestTimeout = time.Minute
const (
returnAddress = uint64(0x0000000100000000)
coreFPBase = uint64(0x0000100000000000)
scratchBase = uint64(0x0000300000000000)
scratchSize = uint64(32 << 20)
heapBase = uint64(0x0000400000000000)
heapSize = uint64(64 << 20)
stackBase = uint64(0x0000500000000000)
stackSize = uint64(8 << 20)
stackEnd = stackBase + stackSize
pageSize = uint64(0x1000)
maxOutputSize = uint64(16 << 20)
)
var coreExportNames = []string{
"_WIn9UJ86JKdV4dM",
"_X46O5IeS",
"_YlCJ3lg",
"_dku592fbFAj",
"_fdjkDSAFjklaf2s",
"_lxpgvVMLd0S7uRl",
}
type entryPoints struct {
initialize uint64
exchange uint64
sign uint64
teardown uint64
dispose uint64
}
type Machine struct {
engine *unicorn.Engine
arm64 *arm64Compatibility
services *shims
entry entryPoints
scratchCursor uint64
closed bool
}
type imageSpec struct {
name string
data []byte
base uint64
prelinked map[uint64]string
slots map[uint64]string
functions map[uint64]string
kernelBase uint64
}
type runtimeOptions struct {
extraImages []imageSpec
shims shimOptions
}
func Open(ctx context.Context, bundle assets.Bundle) (*Machine, error) {
machine, exports, err := openRuntime(ctx, bundle, runtimeOptions{})
if err != nil {
return nil, err
}
machine.entry = entryPoints{
initialize: exports["_cp2g1b9ro"],
exchange: exports["_Mib5yocT"],
sign: exports["_Fc3vhtJDvr"],
teardown: exports["_IPaI1oem5iL"],
dispose: exports["_jEHf8Xzsv8K"],
}
return machine, nil
}
func openRuntime(ctx context.Context, bundle assets.Bundle, options runtimeOptions) (*Machine, map[string]uint64, error) {
if ctx == nil {
return nil, nil, errors.New("SAP runtime context is nil")
}
if err := ctx.Err(); err != nil {
return nil, nil, fmt.Errorf("open SAP runtime: %w", err)
}
imageSpecs := make([]imageSpec, 0, 2+len(options.extraImages))
imageSpecs = append(imageSpecs,
imageSpec{name: "CoreFP", data: bundle.CoreFP, base: coreFPBase},
imageSpec{
name: "AppleMediaServices",
data: bundle.AppleMediaServices,
prelinked: macOS27SharedCacheFunctions,
slots: macOS27SharedCacheSlots,
functions: macOS27SharedCacheFunctions,
},
)
imageSpecs = append(imageSpecs, options.extraImages...)
images := make(map[string]*machimage.Image, len(imageSpecs))
for _, spec := range imageSpecs {
image, err := machimage.OpenShared(spec.name, spec.data)
if err != nil {
return nil, nil, fmt.Errorf("open %s image: %w", spec.name, err)
}
images[spec.name] = image
}
exports := make(map[string]uint64)
coreExports := make(map[string]uint64, len(coreExportNames))
coreFP := images["CoreFP"]
for _, name := range coreExportNames {
address, err := coreFP.Export(name, coreFPBase)
if err != nil {
return nil, nil, fmt.Errorf("resolve CoreFP export %s: %w", name, err)
}
exports[name] = address
coreExports[name] = address
}
appleMediaServices := images["AppleMediaServices"]
for _, name := range []string{
"_cp2g1b9ro",
"_Mib5yocT",
"_Fc3vhtJDvr",
"_IPaI1oem5iL",
"_jEHf8Xzsv8K",
} {
address, err := appleMediaServices.Export(name, appleMediaServices.Base())
if err != nil {
return nil, nil, fmt.Errorf("resolve AppleMediaServices export %s: %w", name, err)
}
exports[name] = address
}
if err := ctx.Err(); err != nil {
return nil, nil, fmt.Errorf("open SAP runtime: %w", err)
}
engine, err := unicorn.New(ctx)
if err != nil {
return nil, nil, fmt.Errorf("create Unicorn engine: %w", err)
}
machine := &Machine{engine: engine, arm64: newARM64Compatibility(engine)}
ready := false
defer func() {
if !ready {
_ = machine.Close()
}
}()
for _, region := range []struct {
address uint64
size uint64
}{
{returnAddress, pageSize},
{scratchBase, scratchSize},
{heapBase, heapSize},
{stackBase, stackSize},
} {
if err := engine.MemMap(region.address, region.size); err != nil {
return nil, nil, fmt.Errorf("map SAP guest memory at %#x: %w", region.address, err)
}
}
if err := engine.MemWrite(returnAddress, []byte{0x00, 0x00, 0x20, 0xd4}); err != nil {
return nil, nil, fmt.Errorf("write SAP guest return instruction: %w", err)
}
machine.services, err = newShimsWithOptions(engine, coreExports, bundle.CoreFPICXS, options.shims)
if err != nil {
return nil, nil, err
}
resolver := func(name string) (uint64, error) {
if address, ok := exports[name]; ok {
return address, nil
}
return machine.services.resolve(name)
}
for _, spec := range imageSpecs {
if err := loadPrelinkedSlots(engine, spec.slots, resolver); err != nil {
return nil, nil, fmt.Errorf("load %s shared-cache slots: %w", spec.name, err)
}
if err := loadPrelinkedFunctions(engine, spec.functions, resolver); err != nil {
return nil, nil, fmt.Errorf("load %s shared-cache functions: %w", spec.name, err)
}
}
for _, spec := range imageSpecs {
image := images[spec.name]
var err error
if spec.prelinked != nil {
err = image.PreparePrelinked(spec.prelinked, resolver)
} else {
err = image.Relocate(spec.base, resolver)
}
if err != nil {
return nil, nil, fmt.Errorf("relocate SAP guest image: %w", err)
}
if spec.kernelBase != 0 {
if err := image.RelocateKernelCachePointers(spec.base, spec.kernelBase, resolver); err != nil {
return nil, nil, fmt.Errorf("relocate %s kernel-cache pointers: %w", spec.name, err)
}
}
if err := image.Load(engine); err != nil {
return nil, nil, fmt.Errorf("load SAP guest image: %w", err)
}
}
ready = true
return machine, exports, nil
}
func loadPrelinkedFunctions(engine *unicorn.Engine, functions map[uint64]string, resolve func(string) (uint64, error)) error {
pages := make(map[uint64]struct{})
for address := range functions {
pages[address-address%pageSize] = struct{}{}
end := address + 15
pages[end-end%pageSize] = struct{}{}
}
for address := range pages {
if err := engine.MemMap(address, pageSize); err != nil {
return fmt.Errorf("map function page at %#x: %w", address, err)
}
}
for address, name := range functions {
target, err := resolve(name)
if err != nil {
return fmt.Errorf("resolve %s: %w", name, err)
}
trampoline := make([]byte, 16)
binary.LittleEndian.PutUint32(trampoline[0:4], 0x58000050) // ldr x16, #8
binary.LittleEndian.PutUint32(trampoline[4:8], 0xd61f0200) // br x16
binary.LittleEndian.PutUint64(trampoline[8:16], target)
if err := engine.MemWrite(address, trampoline); err != nil {
return fmt.Errorf("write %s trampoline at %#x: %w", name, address, err)
}
}
return nil
}
func loadPrelinkedSlots(engine *unicorn.Engine, slots map[uint64]string, resolve func(string) (uint64, error)) error {
pages := make(map[uint64]struct{})
for address := range slots {
pages[address-address%pageSize] = struct{}{}
}
for address := range pages {
if err := engine.MemMap(address, pageSize); err != nil {
return fmt.Errorf("map slot page at %#x: %w", address, err)
}
}
for address, name := range slots {
value, err := resolve(name)
if err != nil {
return fmt.Errorf("resolve %s: %w", name, err)
}
var data [8]byte
binary.LittleEndian.PutUint64(data[:], value)
if err := engine.MemWrite(address, data[:]); err != nil {
return fmt.Errorf("write %s slot at %#x: %w", name, address, err)
}
}
return nil
}
func (m *Machine) Initialize(hardwareID []byte) (uint64, error) {
hardware, err := hardwareBlock(hardwareID)
if err != nil {
return 0, err
}
m.beginCall()
defer m.clearScratch()
contextField, err := m.scratch(nil, 8)
if err != nil {
return 0, err
}
hardwareAddress, err := m.scratch(hardware, uint64(len(hardware)))
if err != nil {
return 0, err
}
status, err := m.invoke(m.entry.initialize, contextField, hardwareAddress)
if err != nil {
return 0, err
}
if int32(status) != 0 {
return 0, fmt.Errorf("SAP initialization returned %d", int32(status))
}
contextValue, err := m.readUint64(contextField)
if err != nil {
return 0, err
}
if contextValue == 0 {
return 0, errors.New("SAP initialization returned a null context")
}
return contextValue, nil
}
func (m *Machine) Exchange(version uint32, hardwareID []byte, contextValue uint64, input []byte) ([]byte, int32, error) {
if uint64(len(input)) > math.MaxUint32 {
return nil, 0, errors.New("SAP exchange input is too large")
}
hardware, err := hardwareBlock(hardwareID)
if err != nil {
return nil, 0, err
}
m.beginCall()
defer m.clearScratch()
hardwareAddress, err := m.scratch(hardware, uint64(len(hardware)))
if err != nil {
return nil, 0, err
}
inputAddress, err := m.scratch(input, uint64(len(input)))
if err != nil {
return nil, 0, err
}
outputField, err := m.scratch(nil, 8)
if err != nil {
return nil, 0, err
}
lengthField, err := m.scratch(nil, 8)
if err != nil {
return nil, 0, err
}
resultField, err := m.scratch(nil, 4)
if err != nil {
return nil, 0, err
}
status, err := m.invoke(
m.entry.exchange,
uint64(version),
hardwareAddress,
contextValue,
inputAddress,
uint64(len(input)),
outputField,
lengthField,
resultField,
)
if err != nil {
return nil, 0, err
}
if int32(status) != 0 {
return nil, 0, fmt.Errorf("SAP exchange returned %d", int32(status))
}
output, err := m.consumeOutput(outputField, lengthField)
if err != nil {
return nil, 0, err
}
result, err := m.readUint32(resultField)
if err != nil {
return nil, 0, err
}
return output, int32(result), nil
}
func (m *Machine) Sign(contextValue uint64, input []byte) ([]byte, error) {
if uint64(len(input)) > math.MaxUint32 {
return nil, errors.New("SAP signing input is too large")
}
m.beginCall()
defer m.clearScratch()
inputAddress, err := m.scratch(input, uint64(len(input)))
if err != nil {
return nil, err
}
outputField, err := m.scratch(nil, 8)
if err != nil {
return nil, err
}
lengthField, err := m.scratch(nil, 8)
if err != nil {
return nil, err
}
status, err := m.invoke(
m.entry.sign,
contextValue,
inputAddress,
uint64(len(input)),
outputField,
lengthField,
)
if err != nil {
return nil, err
}
if int32(status) != 0 {
return nil, fmt.Errorf("SAP signing returned %d", int32(status))
}
output, err := m.consumeOutput(outputField, lengthField)
if err != nil {
return nil, err
}
return output, nil
}
func (m *Machine) Teardown(contextValue uint64) error {
status, err := m.invoke(m.entry.teardown, contextValue)
if err != nil {
return err
}
if int32(status) != 0 {
return fmt.Errorf("SAP teardown returned %d", int32(status))
}
return nil
}
func (m *Machine) dispose(output uint64) error {
status, err := m.invoke(m.entry.dispose, output)
if err != nil {
return err
}
if int32(status) != 0 {
return fmt.Errorf("SAP storage disposal returned %d", int32(status))
}
return nil
}
//nolint:wsl // Register setup and compatibility retries are clearer in execution order.
func (m *Machine) invoke(function uint64, arguments ...uint64) (uint64, error) {
if m.closed {
return 0, errors.New("SAP guest machine is closed")
}
if function == 0 {
return 0, errors.New("SAP guest entry point is unavailable")
}
registers := [...]int{
unicorn.RegX0,
unicorn.RegX1,
unicorn.RegX2,
unicorn.RegX3,
unicorn.RegX4,
unicorn.RegX5,
unicorn.RegX6,
unicorn.RegX7,
}
for index, register := range registers {
var value uint64
if index < len(arguments) {
value = arguments[index]
}
if err := m.engine.RegWrite(register, value); err != nil {
return 0, fmt.Errorf("write SAP guest argument register: %w", err)
}
}
extra := max(len(arguments)-len(registers), 0)
stackPointer := stackEnd - uint64(extra)*8
stackPointer -= stackPointer % 16
for index := range extra {
if err := m.writeUint64(stackPointer+uint64(index)*8, arguments[len(registers)+index]); err != nil {
return 0, err
}
}
if err := m.engine.RegWrite(unicorn.RegSP, stackPointer); err != nil {
return 0, fmt.Errorf("write SAP guest stack register: %w", err)
}
if err := m.engine.RegWrite(unicorn.RegLR, returnAddress); err != nil {
return 0, fmt.Errorf("write SAP guest return register: %w", err)
}
m.services.resetFault()
// SAP's cryptographic routines have input- and host-dependent instruction
// counts. Bound execution by wall time without rejecting legitimate work on
// slower machines for crossing a fixed instruction limit.
next := function
for {
executionErr := m.engine.StartBounded(next, returnAddress, sapGuestTimeout, 0)
if executionErr == nil {
break
}
if m.services.fault != nil {
return 0, m.services.fault
}
if m.arm64 != nil {
handled, compatibilityErr := m.arm64.emulateInvalidInstruction()
if compatibilityErr != nil {
return 0, compatibilityErr
}
if handled {
next, compatibilityErr = m.engine.RegRead(unicorn.RegPC)
if compatibilityErr != nil {
return 0, fmt.Errorf("resume SAP guest function: %w", compatibilityErr)
}
continue
}
}
instruction, readErr := m.engine.RegRead(unicorn.RegPC)
if readErr != nil {
return 0, fmt.Errorf("execute SAP guest function: %w", executionErr)
}
link, linkErr := m.engine.RegRead(unicorn.RegLR)
if linkErr != nil {
return 0, fmt.Errorf("execute SAP guest function at %#x: %w", instruction, executionErr)
}
return 0, fmt.Errorf("execute SAP guest function at %#x from %#x: %w", instruction, link, executionErr)
}
if m.services.fault != nil {
return 0, m.services.fault
}
instruction, err := m.engine.RegRead(unicorn.RegPC)
if err != nil {
return 0, fmt.Errorf("read SAP guest instruction register: %w", err)
}
if instruction != returnAddress {
return 0, fmt.Errorf("SAP guest stopped unexpectedly at %#x", instruction)
}
result, err := m.engine.RegRead(unicorn.RegX0)
if err != nil {
return 0, fmt.Errorf("read SAP guest result register: %w", err)
}
return result, nil
}
func (m *Machine) beginCall() {
m.scratchCursor = 0
}
func (m *Machine) scratch(data []byte, size uint64) (uint64, error) {
reserved := align(max(size, 1), 16)
if m.scratchCursor > scratchSize || reserved > scratchSize-m.scratchCursor {
return 0, errors.New("SAP guest scratch space exhausted")
}
address := scratchBase + m.scratchCursor
m.scratchCursor += reserved
if len(data) != 0 {
if uint64(len(data)) > size {
return 0, errors.New("scratch data exceeds reservation")
}
if err := m.engine.MemWrite(address, data); err != nil {
return 0, fmt.Errorf("write SAP guest scratch data: %w", err)
}
} else if size != 0 {
if err := m.engine.MemWrite(address, make([]byte, size)); err != nil {
return 0, fmt.Errorf("clear SAP guest scratch data: %w", err)
}
}
return address, nil
}
func (m *Machine) clearScratch() {
if m.scratchCursor != 0 && m.engine != nil && !m.closed {
_ = m.engine.MemWrite(scratchBase, make([]byte, m.scratchCursor))
}
m.scratchCursor = 0
}
func (m *Machine) consumeOutput(pointerField, lengthField uint64) ([]byte, error) {
pointer, err := m.readUint64(pointerField)
if err != nil {
return nil, err
}
length, err := m.readUint64(lengthField)
if err != nil {
return nil, err
}
var output []byte
var outputErr error
switch {
case length > maxOutputSize:
outputErr = fmt.Errorf("SAP output is %d bytes, maximum is %d", length, maxOutputSize)
case length == 0:
case pointer == 0:
outputErr = errors.New("SAP returned a null output pointer")
default:
output, outputErr = m.engine.MemRead(pointer, length)
}
var disposeErr error
if pointer != 0 {
disposeErr = m.dispose(pointer)
}
return output, errors.Join(outputErr, disposeErr)
}
func (m *Machine) readUint32(address uint64) (uint32, error) {
data, err := m.engine.MemRead(address, 4)
if err != nil {
return 0, fmt.Errorf("read SAP guest uint32: %w", err)
}
return binary.LittleEndian.Uint32(data), nil
}
func (m *Machine) readUint64(address uint64) (uint64, error) {
data, err := m.engine.MemRead(address, 8)
if err != nil {
return 0, fmt.Errorf("read SAP guest uint64: %w", err)
}
return binary.LittleEndian.Uint64(data), nil
}
func (m *Machine) writeUint64(address, value uint64) error {
var data [8]byte
binary.LittleEndian.PutUint64(data[:], value)
if err := m.engine.MemWrite(address, data[:]); err != nil {
return fmt.Errorf("write SAP guest uint64: %w", err)
}
return nil
}
func (m *Machine) Close() error {
if m == nil || m.closed {
return nil
}
m.closed = true
var errs []error
if m.services != nil {
errs = append(errs, m.services.close())
}
if m.engine != nil {
errs = append(errs, m.engine.Close())
}
return errors.Join(errs...)
}
func hardwareBlock(hardwareID []byte) ([]byte, error) {
if len(hardwareID) == 0 || len(hardwareID) > 20 {
return nil, errors.New("hardware ID must contain between 1 and 20 bytes")
}
result := make([]byte, 24)
binary.LittleEndian.PutUint32(result[0:4], uint32(len(hardwareID)))
copy(result[4:], hardwareID)
return result, nil
}
func align(value, alignment uint64) uint64 {
return (value + alignment - 1) &^ (alignment - 1)
}
@@ -0,0 +1,13 @@
package machine
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestMachineGinkgo(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "SAP Machine Suite")
}
+319
View File
@@ -0,0 +1,319 @@
package machine
import (
"bytes"
"context"
"encoding/binary"
"errors"
"math"
"strings"
"testing"
"github.com/majd/ipatool/v2/internal/sap/assets"
"github.com/majd/ipatool/v2/internal/sap/unicorn"
)
func TestOpenHonorsCanceledContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err := Open(ctx, assets.Bundle{}); !errors.Is(err, context.Canceled) {
t.Fatalf("Open error = %v, want %v", err, context.Canceled)
}
}
func TestHardwareBlock(t *testing.T) {
identifier := []byte{1, 2, 3, 4, 5, 6}
block, err := hardwareBlock(identifier)
if err != nil {
t.Fatal(err)
}
if len(block) != 24 || binary.LittleEndian.Uint32(block[:4]) != uint32(len(identifier)) {
t.Fatalf("unexpected hardware block header: %x", block)
}
if string(block[4:10]) != string(identifier) {
t.Fatalf("hardware ID = %x", block[4:10])
}
if _, err := hardwareBlock(make([]byte, 21)); err == nil {
t.Fatal("oversized hardware ID was accepted")
}
}
func TestGuestServiceDispatchAndStackArguments(t *testing.T) {
machine := newServiceTestMachine(t)
address, err := machine.services.addFunction("test.stackArguments", func() error {
seventh, err := machine.services.argument(6)
if err != nil {
return err
}
eighth, err := machine.services.argument(7)
if err != nil {
return err
}
return machine.services.setResult(seventh + eighth)
})
if err != nil {
t.Fatal(err)
}
result, err := machine.invoke(address, 1, 2, 3, 4, 5, 6, 7, 8)
if err != nil {
t.Fatal(err)
}
if result != 15 {
t.Fatalf("result = %d, want 15", result)
}
}
func TestUnknownGuestServiceFailsClosed(t *testing.T) {
machine := newServiceTestMachine(t)
address, err := machine.services.resolve("test.unsupported")
if err != nil {
t.Fatal(err)
}
if _, err := machine.invoke(address); err == nil || !strings.Contains(err.Error(), "unsupported import") {
t.Fatalf("invoke error = %v", err)
}
}
func TestGuestAllocatorReusesAndClearsFreedMemory(t *testing.T) {
machine := newServiceTestMachine(t)
address, err := machine.services.allocate(64)
if err != nil {
t.Fatal(err)
}
if err := machine.engine.MemWrite(address, bytes.Repeat([]byte{0xa5}, 64)); err != nil {
t.Fatal(err)
}
if err := machine.services.release(address); err != nil {
t.Fatal(err)
}
reused, err := machine.services.allocate(32)
if err != nil {
t.Fatal(err)
}
if reused != address {
t.Fatalf("reused address = %#x, want %#x", reused, address)
}
data, err := machine.engine.MemRead(reused, 32)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(data, make([]byte, 32)) {
t.Fatalf("reused allocation was not cleared: %x", data)
}
if err := machine.services.release(reused); err != nil {
t.Fatal(err)
}
if machine.services.heapCursor != 0 || len(machine.services.freeBlocks) != 0 {
t.Fatalf("released heap was not reclaimed: cursor=%d free=%v", machine.services.heapCursor, machine.services.freeBlocks)
}
}
func TestMallocSizeReturnsUsableSize(t *testing.T) {
machine := newServiceTestMachine(t)
address, err := machine.services.allocate(1)
if err != nil {
t.Fatal(err)
}
result, err := machine.invoke(machine.services.symbols["_malloc_size"], address)
if err != nil {
t.Fatal(err)
}
if result != 16 {
t.Fatalf("malloc_size = %d, want 16", result)
}
}
func TestStrncmpStopsAtMappedPageBoundary(t *testing.T) {
machine := newServiceTestMachine(t)
left := returnAddress + pageSize - 2
right := stackBase + pageSize - 2
for _, address := range []uint64{left, right} {
if err := machine.engine.MemWrite(address, []byte{'a', 0}); err != nil {
t.Fatal(err)
}
}
result, err := machine.invoke(machine.services.symbols["_strncmp"], left, right, 64)
if err != nil {
t.Fatal(err)
}
if result != 0 {
t.Fatalf("strncmp = %d, want 0", result)
}
}
func TestPlatformServicesInitializeOutputs(t *testing.T) {
machine := newServiceTestMachine(t)
buffer := stackBase + pageSize
if err := machine.engine.MemWrite(buffer, bytes.Repeat([]byte{0xa5}, 16)); err != nil {
t.Fatal(err)
}
result, err := machine.invoke(machine.services.symbols["_CFStringGetCString"], fakeHandle, buffer, 16, 0)
if err != nil {
t.Fatal(err)
}
if result != 1 {
t.Fatalf("CFStringGetCString = %d, want 1", result)
}
data, err := machine.engine.MemRead(buffer, 1)
if err != nil {
t.Fatal(err)
}
if data[0] != 0 {
t.Fatalf("CFStringGetCString output = %#x, want NUL", data[0])
}
for _, name := range []string{"_IORegistryEntryGetParentEntry", "_IOServiceGetMatchingServices"} {
if err := machine.engine.MemWrite(buffer, bytes.Repeat([]byte{0xa5}, 4)); err != nil {
t.Fatal(err)
}
result, err := machine.invoke(machine.services.symbols[name], 0, 0, buffer)
if err != nil {
t.Fatal(err)
}
if result != 0 {
t.Fatalf("%s = %d, want 0", name, result)
}
data, err := machine.engine.MemRead(buffer, 4)
if err != nil {
t.Fatal(err)
}
if binary.LittleEndian.Uint32(data) != math.MaxUint32 {
t.Fatalf("%s output = %x, want uint32 max", name, data)
}
}
result, err = machine.invoke(machine.services.symbols["_statfs"], 0, buffer)
if err != nil {
t.Fatal(err)
}
if result != math.MaxUint64 {
t.Fatalf("statfs = %#x, want -1", result)
}
}
func TestConsumeOutputDisposesAllocation(t *testing.T) {
machine := newServiceTestMachine(t)
output, err := machine.services.allocate(4)
if err != nil {
t.Fatal(err)
}
if err := machine.engine.MemWrite(output, []byte("test")); err != nil {
t.Fatal(err)
}
pointerField := scratchBase
lengthField := scratchBase + 8
if err := machine.writeUint64(pointerField, output); err != nil {
t.Fatal(err)
}
if err := machine.writeUint64(lengthField, 4); err != nil {
t.Fatal(err)
}
machine.entry.dispose, err = machine.services.addFunction("test.dispose", machine.services.free)
if err != nil {
t.Fatal(err)
}
data, err := machine.consumeOutput(pointerField, lengthField)
if err != nil {
t.Fatal(err)
}
if string(data) != "test" {
t.Fatalf("output = %q, want test", data)
}
if _, ok := machine.services.allocations[output]; ok {
t.Fatal("output allocation was not released")
}
}
func newServiceTestMachine(t *testing.T) *Machine {
t.Helper()
engine, err := unicorn.New(context.Background())
if err != nil {
t.Fatalf("create Unicorn engine: %v", err)
}
for _, region := range []struct {
address uint64
size uint64
}{
{returnAddress, pageSize},
{scratchBase, scratchSize},
{heapBase, heapSize},
{stackBase, stackSize},
} {
if err := engine.MemMap(region.address, region.size); err != nil {
_ = engine.Close()
t.Fatal(err)
}
}
if err := engine.MemWrite(returnAddress, []byte{0x00, 0x00, 0x20, 0xd4}); err != nil {
_ = engine.Close()
t.Fatal(err)
}
services, err := newShims(engine, map[string]uint64{}, nil)
if err != nil {
_ = engine.Close()
t.Fatal(err)
}
machine := &Machine{engine: engine, services: services}
t.Cleanup(func() {
if err := machine.Close(); err != nil {
t.Errorf("close machine: %v", err)
}
})
return machine
}
+37
View File
@@ -0,0 +1,37 @@
package machine
// macOS27SharedCacheFunctions maps the external function pointers used by the
// AppleMediaServices image extracted from the macOS 27.0.1 (26A434) arm64e
// shared cache. The extraction has its cache slide applied, so these values are
// stable for this exact build and are replaced with emulator services at load
// time.
var macOS27SharedCacheFunctions = map[uint64]string{
0x0000000180675ce8: "_malloc",
0x00000001806766f0: "_free",
0x00000001806cf570: "_dispatch_once",
0x000000018071acc8: "_sysctlbyname",
0x000000018071bec4: "_gettimeofday",
0x0000000180721fb8: "_arc4random",
0x00000001807238a4: "___memset_chk",
0x00000001807903c4: "_abort",
0x0000000180849604: "___error",
0x0000000180889bc4: "_pthread_once",
0x000000018088a6f8: "_pthread_rwlock_unlock",
0x000000018088a7c0: "_pthread_rwlock_wrlock",
0x000000018088b2d8: "_pthread_rwlock_init",
0x0000000180894b40: "_strlen",
0x00000001808cf540: "_CFStringCreateWithCString",
0x00000001808d4200: "_CFStringGetLength",
0x00000001808d44dc: "_CFStringGetCString",
0x00000001808d7278: "_CFRelease",
0x00000001808e89e8: "_CFDataGetLength",
0x0000000184d6b4cc: "_IOServiceMatching",
0x0000000184d6c168: "_IOServiceGetMatchingServices",
0x0000000184d6c4fc: "_IOIteratorNext",
0x0000000184d6cb50: "_IOObjectRelease",
}
var macOS27SharedCacheSlots = map[uint64]string{
0x00000001e02205c0: "___stack_chk_guard",
0x00000001e800c958: "___chkstk_darwin",
}
+662
View File
@@ -0,0 +1,662 @@
package machine
import (
"context"
"encoding/binary"
"errors"
"fmt"
"path/filepath"
"github.com/majd/ipatool/v2/internal/sap/assets"
)
const (
modernADIStartEntry = storeAgentBase + 0x1b4400
modernADIEndEntry = storeAgentBase + 0x1d5124
modernADIOTPEntry = storeAgentBase + 0x1dab04
modernKeyBagEntry = storeAgentBase + 0x16e0f8
modernADIStatePath = "/var/db/fpsd/adi/adi.pb"
modernADIDBase = uint64(0x0000200000000000)
modernADIDEntry = modernADIDBase + 0x11180
modernFairPlayDBase = uint64(0x0000600000000000)
modernFairPlayDEntry = modernFairPlayDBase + 0x332040
// Preserve the prelinked image's original 0x510 page offset so its ADRP
// references retain the same slide as its data segments.
modernFairPlayKextBase = uint64(0x0000700000000510)
modernFairPlayKextStart = modernFairPlayKextBase + 0x2bca984
modernFairPlayKextSetup = modernFairPlayKextBase + 0x2c67e50
modernFairPlayKextInit = modernFairPlayKextBase + 0x2bca714
modernFairPlayKextEntry = modernFairPlayKextBase + 0x2cf978c
)
// ModernADI runs the ADI implementation embedded in the pinned macOS 27
// commerce image. Apple Store otp/1.5 provisioning requires this generation;
// the Sierra implementation cannot consume its settingInfo payload.
type ModernADI struct {
runtime *Machine
daemon *Machine
fairplay *Machine
kernel *Machine
kernelContext uint64
storeGlobal uint32
daemonHandler uint64
}
func OpenModernADI(ctx context.Context, bundle assets.Bundle, identifier, state []byte) (*ModernADI, error) {
if len(identifier) != 16 {
return nil, errors.New("modern ADI host UUID must be 16 bytes")
}
runtime, _, err := openRuntime(ctx, bundle, runtimeOptions{
extraImages: []imageSpec{{name: "commerce", data: bundle.Commerce, base: storeAgentBase}},
shims: shimOptions{zeroReturnAliases: storeAgentZeroReturnAliases},
})
if err != nil {
return nil, err
}
ready := false
defer func() {
if !ready {
_ = runtime.Close()
}
}()
daemon, _, err := openRuntime(ctx, bundle, runtimeOptions{
extraImages: []imageSpec{{name: "adid", data: bundle.ADID, base: modernADIDBase}},
shims: shimOptions{pauseRunLoop: true},
})
if err != nil {
return nil, fmt.Errorf("open modern ADI daemon: %w", err)
}
defer func() {
if !ready {
_ = daemon.Close()
}
}()
fairplay, _, err := openRuntime(ctx, bundle, runtimeOptions{
extraImages: []imageSpec{{name: "fairplayd", data: bundle.FairPlayD, base: modernFairPlayDBase}},
shims: shimOptions{pauseRunLoop: true},
})
if err != nil {
return nil, fmt.Errorf("open modern FairPlay daemon: %w", err)
}
defer func() {
if !ready {
_ = fairplay.Close()
}
}()
copy(runtime.services.hostUUID[:], identifier)
copy(daemon.services.hostUUID[:], identifier)
copy(fairplay.services.hostUUID[:], identifier)
if len(state) != 0 {
daemon.services.adiFiles[modernADIStatePath] = append([]byte(nil), state...)
}
var kernel *Machine
if len(bundle.FairPlayKext) != 0 {
kernel, _, err = openRuntime(ctx, bundle, runtimeOptions{
extraImages: []imageSpec{{name: "FairPlayIOKit", data: bundle.FairPlayKext, base: modernFairPlayKextBase, kernelBase: 0xfffffe0007004000}},
})
if err != nil {
return nil, fmt.Errorf("open modern FairPlay kernel client: %w", err)
}
defer func() {
if !ready {
_ = kernel.Close()
}
}()
copy(kernel.services.hostUUID[:], identifier)
}
adi := &ModernADI{runtime: runtime, daemon: daemon, fairplay: fairplay, kernel: kernel}
if kernel != nil {
kernel.services.machRPCHandler = adi.handleFairPlayMachRPC
if err := adi.initializeFairPlayKernel(); err != nil {
return nil, err
}
}
fairplay.services.fairPlayHandler = adi.handleFairPlayMessage
if _, err = fairplay.invoke(modernFairPlayDEntry, 0, 0, 0); err != nil {
return nil, fmt.Errorf("initialize modern FairPlay daemon: %w", err)
}
daemon.services.fairPlayHandler = adi.handleFairPlayMessage
runtime.services.fairPlayHandler = adi.handleFairPlayMessage
if err := adi.initializeDaemon(); err != nil {
return nil, err
}
ready = true
return adi, nil
}
func (a *ModernADI) initializeFairPlayKernel() error {
a.kernel.beginCall()
defer a.kernel.clearScratch()
if _, err := a.kernel.invoke(modernFairPlayKextStart); err != nil {
return fmt.Errorf("start modern FairPlay kernel: %w", err)
}
status, err := a.kernel.invoke(modernFairPlayKextSetup)
if err != nil {
return fmt.Errorf("set up modern FairPlay kernel: %w", err)
}
if int32(status) != 0 {
return fmt.Errorf("set up modern FairPlay kernel: status %d", int32(status))
}
output, err := a.kernel.scratch(nil, 8)
if err != nil {
return err
}
task, err := a.kernel.services.allocate(0x1000)
if err != nil {
return fmt.Errorf("allocate modern FairPlay kernel task: %w", err)
}
if err := a.kernel.engine.MemWrite(task, make([]byte, 0x1000)); err != nil {
return fmt.Errorf("initialize modern FairPlay kernel task: %w", err)
}
status, err = a.kernel.invoke(modernFairPlayKextInit, 0, output, 0, task)
if err != nil {
return fmt.Errorf("initialize modern FairPlay kernel session: %w", err)
}
if int32(status) != 0 {
return fmt.Errorf("initialize modern FairPlay kernel session: status %d", int32(status))
}
context, err := a.kernel.readUint64(output)
if err != nil {
return err
}
if context == 0 {
return errors.New("modern FairPlay kernel returned no session context")
}
a.kernelContext = context
return nil
}
func (a *ModernADI) ImportKeyBag(hardwareID, keyBag []byte) error {
if a == nil || a.runtime == nil {
return errors.New("modern ADI runtime is unavailable")
}
hardware, err := hardwareBlock(hardwareID)
if err != nil {
return err
}
a.runtime.beginCall()
defer a.runtime.clearScratch()
hardwareAddress, err := a.runtime.scratch(hardware, uint64(len(hardware)))
if err != nil {
return err
}
path := append([]byte(storeAgentSCInfoPath), 0)
pathAddress, err := a.runtime.scratch(path, uint64(len(path)))
if err != nil {
return err
}
contextField, err := a.runtime.scratch(nil, 4)
if err != nil {
return err
}
status, err := a.runtime.invoke(storeAgentGlobalInit, 0, hardwareAddress, pathAddress, contextField)
if err != nil {
return fmt.Errorf("initialize FairPlay keybag context: %w", err)
}
if int32(status) != 0 {
return fmt.Errorf("initialize FairPlay keybag context: status %d", int32(status))
}
global, err := a.runtime.readUint32(contextField)
if err != nil {
return err
}
if global == 0 {
return errors.New("initialize FairPlay keybag context: null context")
}
keyBagAddress, err := a.runtime.scratch(keyBag, uint64(len(keyBag)))
if err != nil {
return err
}
status, err = a.runtime.invoke(modernKeyBagEntry, uint64(global), keyBagAddress, uint64(len(keyBag)))
if err != nil {
return fmt.Errorf("import FairPlay keybag: %w", err)
}
if int32(status) != 0 {
return fmt.Errorf("import FairPlay keybag: status %d", int32(status))
}
a.storeGlobal = global
return nil
}
func (a *ModernADI) handleFairPlayMessage(input, indirect []byte, outputSize int) ([]byte, []byte, int32, error) {
if a.kernel != nil {
stackProbe, _ := a.kernel.readUint64(modernFairPlayKextBase + 0xb8c028)
if stackProbe != modernFairPlayKextBase+0x2c66248 {
return nil, nil, 0, fmt.Errorf("modern FairPlay kernel stack probe is %#x", stackProbe)
}
a.kernel.beginCall()
defer a.kernel.clearScratch()
message, err := a.kernel.scratch(indirect, uint64(len(indirect)))
if err != nil {
return nil, nil, 0, err
}
status, err := a.kernel.invoke(modernFairPlayKextEntry, message, uint64(len(indirect)), a.kernelContext)
if err != nil {
return nil, nil, 0, fmt.Errorf("run modern FairPlay kernel message: %w", err)
}
updated, err := a.kernel.engine.MemRead(message, uint64(len(indirect)))
if err != nil {
return nil, nil, 0, fmt.Errorf("read modern FairPlay kernel message: %w", err)
}
output := append([]byte(nil), input...)
if len(output) > outputSize {
output = output[:outputSize]
}
return output, updated, int32(status), nil
}
if a.fairplay.services.machPortCallback == 0 {
return nil, nil, 0, errors.New("modern FairPlay daemon installed no message callback")
}
a.fairplay.beginCall()
defer a.fairplay.clearScratch()
message, err := a.fairplay.scratch(indirect, uint64(len(indirect)))
if err != nil {
return nil, nil, 0, err
}
_, err = a.fairplay.invoke(
a.fairplay.services.machPortCallback,
fakeHandle,
message,
uint64(len(indirect)),
a.fairplay.services.machPortInfo,
)
if err != nil {
return nil, nil, 0, fmt.Errorf("run modern FairPlay message callback: %w", err)
}
updated, err := a.fairplay.engine.MemRead(message, uint64(len(indirect)))
if err != nil {
return nil, nil, 0, fmt.Errorf("read modern FairPlay daemon message: %w", err)
}
output := append([]byte(nil), input...)
if len(output) > outputSize {
output = output[:outputSize]
}
return output, updated, 0, nil
}
func (a *ModernADI) handleFairPlayMachRPC(request []byte, receiveSize int) ([]byte, error) {
if a.fairplay.services.machPortCallback == 0 {
return nil, errors.New("modern FairPlay daemon installed no message callback")
}
a.fairplay.beginCall()
defer a.fairplay.clearScratch()
message, err := a.fairplay.scratch(request, uint64(max(len(request), receiveSize)))
if err != nil {
return nil, err
}
a.fairplay.services.machMessageReply = nil
_, err = a.fairplay.invoke(
a.fairplay.services.machPortCallback,
fakeHandle,
message,
uint64(len(request)),
a.fairplay.services.machPortInfo,
)
if err != nil {
return nil, fmt.Errorf("run modern FairPlay Mach callback: %w", err)
}
if len(a.fairplay.services.machMessageReply) == 0 {
return nil, errors.New("modern FairPlay daemon returned no Mach reply")
}
return append([]byte(nil), a.fairplay.services.machMessageReply...), nil
}
func (a *ModernADI) initializeDaemon() error {
_, entryErr := a.daemon.invoke(modernADIDEntry, 0, 0, 0, 0)
if a.daemon.services.xpcEventHandler == 0 {
return fmt.Errorf("initialize modern ADI daemon: %w", entryErr)
}
listener := a.daemon.services.xpcEventHandler
connection := a.daemon.services.newXPCObject(nil)
if err := a.invokeDaemonBlock(listener, connection); err != nil {
return fmt.Errorf("accept modern ADI daemon connection: %w", err)
}
if a.daemon.services.xpcEventHandler == listener {
return errors.New("modern ADI daemon did not install a request handler")
}
a.daemonHandler = a.daemon.services.xpcEventHandler
return nil
}
func (a *ModernADI) invokeDaemonBlock(block, argument uint64) error {
handler, err := a.daemon.readUint64(block + 16)
if err != nil {
return err
}
_, err = a.daemon.invoke(handler, block, argument)
return err
}
func (a *ModernADI) invoke(function uint64, arguments ...uint64) (uint64, error) {
a.runtime.services.xpcData = nil
a.runtime.services.xpcSyncReply = nil
_, firstErr := a.runtime.invoke(function, arguments...)
request := append([]byte(nil), a.runtime.services.xpcData...)
if len(request) == 0 {
return 0, fmt.Errorf("modern ADI client created no daemon request: %w", firstErr)
}
a.daemon.services.xpcReply = nil
a.daemon.services.xpcReplied = false
requestObject := a.daemon.services.newXPCObject(request)
if err := a.invokeDaemonBlock(a.daemonHandler, requestObject); err != nil {
return 0, fmt.Errorf("run modern ADI daemon request: %w", err)
}
if !a.daemon.services.xpcReplied || len(a.daemon.services.xpcReply) == 0 {
return 0, errors.New("modern ADI daemon returned no reply")
}
a.runtime.services.xpcSyncReply = append([]byte(nil), a.daemon.services.xpcReply...)
return a.runtime.invoke(function, arguments...)
}
// ExchangeXPC sends the opaque data payload used by AppleMediaServices to the
// emulated com.apple.adid service and returns its opaque reply payload.
func (a *ModernADI) ExchangeXPC(request []byte) ([]byte, error) {
if a == nil || a.daemon == nil || a.daemonHandler == 0 {
return nil, errors.New("modern ADI daemon is unavailable")
}
if len(request) == 0 || len(request) > 1<<20 {
return nil, errors.New("modern ADI XPC request is invalid")
}
a.daemon.services.xpcReply = nil
a.daemon.services.xpcReplied = false
requestObject := a.daemon.services.newXPCObject(request)
if err := a.invokeDaemonBlock(a.daemonHandler, requestObject); err != nil {
return nil, fmt.Errorf("run modern ADI XPC request: %w", err)
}
if !a.daemon.services.xpcReplied || len(a.daemon.services.xpcReply) == 0 {
return nil, errors.New("modern ADI XPC service returned no reply")
}
return append([]byte(nil), a.daemon.services.xpcReply...), nil
}
func (a *ModernADI) StartProvisioning(dsid uint64, spim []byte) ([]byte, uint32, error) {
if a == nil || a.runtime == nil {
return nil, 0, errors.New("modern ADI runtime is unavailable")
}
a.runtime.beginCall()
defer a.runtime.clearScratch()
input, err := a.runtime.scratch(spim, uint64(len(spim)))
if err != nil {
return nil, 0, err
}
pointerField, err := a.runtime.scratch(nil, 8)
if err != nil {
return nil, 0, err
}
lengthField, err := a.runtime.scratch(nil, 4)
if err != nil {
return nil, 0, err
}
sessionField, err := a.runtime.scratch(nil, 4)
if err != nil {
return nil, 0, err
}
status, err := a.invoke(modernADIStartEntry, dsid, input, uint64(len(spim)), pointerField, lengthField, sessionField)
if err != nil {
return nil, 0, err
}
if int32(status) != 0 {
return nil, 0, fmt.Errorf("start modern ADI provisioning: status %d", int32(status))
}
output, err := a.readOutput(pointerField, lengthField)
if err != nil {
return nil, 0, err
}
session, err := a.runtime.engine.MemRead(sessionField, 4)
if err != nil {
return nil, 0, fmt.Errorf("read modern ADI provisioning session: %w", err)
}
return output, binary.LittleEndian.Uint32(session), nil
}
func (a *ModernADI) EndProvisioning(session uint32, settingInfo, transportKey []byte) error {
if a == nil || a.runtime == nil {
return errors.New("modern ADI runtime is unavailable")
}
a.runtime.beginCall()
defer a.runtime.clearScratch()
settingAddress, err := a.runtime.scratch(settingInfo, uint64(len(settingInfo)))
if err != nil {
return err
}
keyAddress, err := a.runtime.scratch(transportKey, uint64(len(transportKey)))
if err != nil {
return err
}
status, err := a.invoke(modernADIEndEntry, uint64(session), settingAddress, uint64(len(settingInfo)), keyAddress, uint64(len(transportKey)))
if err != nil {
return err
}
if int32(status) != 0 {
return fmt.Errorf("finish modern ADI provisioning: status %d", int32(status))
}
return nil
}
func (a *ModernADI) RequestOTP(dsid uint64) ([]byte, []byte, error) {
if a == nil || a.runtime == nil {
return nil, nil, errors.New("modern ADI runtime is unavailable")
}
a.runtime.beginCall()
defer a.runtime.clearScratch()
midPointer, err := a.runtime.scratch(nil, 8)
if err != nil {
return nil, nil, err
}
midLength, err := a.runtime.scratch(nil, 4)
if err != nil {
return nil, nil, err
}
otpPointer, err := a.runtime.scratch(nil, 8)
if err != nil {
return nil, nil, err
}
otpLength, err := a.runtime.scratch(nil, 4)
if err != nil {
return nil, nil, err
}
status, err := a.invoke(modernADIOTPEntry, dsid, midPointer, midLength, otpPointer, otpLength)
if err != nil {
return nil, nil, err
}
if int32(status) != 0 {
return nil, nil, fmt.Errorf("request modern ADI OTP: status %d", int32(status))
}
mid, err := a.readOutput(midPointer, midLength)
if err != nil {
return nil, nil, err
}
otp, err := a.readOutput(otpPointer, otpLength)
if err != nil {
return nil, nil, err
}
return mid, otp, nil
}
func (a *ModernADI) readOutput(pointerField, lengthField uint64) ([]byte, error) {
pointer, err := a.runtime.readUint64(pointerField)
if err != nil {
return nil, err
}
length, err := a.runtime.readUint32(lengthField)
if err != nil {
return nil, err
}
if pointer == 0 || length == 0 || length > 1<<20 {
return nil, errors.New("modern ADI returned invalid output")
}
output, err := a.runtime.engine.MemRead(pointer, uint64(length))
if err != nil {
return nil, fmt.Errorf("read modern ADI output: %w", err)
}
return output, nil
}
func (a *ModernADI) State() ([]byte, error) {
if a == nil || a.runtime == nil {
return nil, errors.New("modern ADI runtime is unavailable")
}
if state := a.daemon.services.adiFiles[modernADIStatePath]; len(state) != 0 {
return append([]byte(nil), state...), nil
}
for path, state := range a.daemon.services.adiFiles {
if filepath.Base(path) == "adi.pb" && len(state) != 0 {
return append([]byte(nil), state...), nil
}
}
return nil, errors.New("modern ADI state was not created")
}
func (a *ModernADI) Close() error {
if a == nil || a.runtime == nil {
return nil
}
var err error
if a.storeGlobal != 0 {
if status, closeErr := a.runtime.invoke(storeAgentGlobalClose, uint64(a.storeGlobal)); closeErr != nil {
err = errors.Join(err, fmt.Errorf("close FairPlay keybag context: %w", closeErr))
} else if int32(status) != 0 {
err = errors.Join(err, fmt.Errorf("close FairPlay keybag context: status %d", int32(status)))
}
}
err = errors.Join(err, a.runtime.Close())
err = errors.Join(err, a.daemon.Close())
err = errors.Join(err, a.fairplay.Close())
if a.kernel != nil {
err = errors.Join(err, a.kernel.Close())
}
a.runtime = nil
a.daemon = nil
a.fairplay = nil
a.kernel = nil
return err
}
+739
View File
@@ -0,0 +1,739 @@
package machine
import (
"bytes"
"errors"
"fmt"
"math"
"sort"
)
const maxGuestTransfer = uint64(64 << 20)
func (s *shims) registerMemoryServices() error {
services := []struct {
names []string
handler shimHandler
}{
{[]string{"_malloc", "_IOMalloc", "_IOMallocData"}, s.malloc},
{[]string{"_IOMallocAligned"}, s.mallocAligned},
{[]string{"_IOMallocTypeImpl"}, s.mallocTyped},
{[]string{"_IOMallocTypeVarImpl", "_OSObject_typed_operator_new"}, s.mallocTypedVariable},
{[]string{"_IOLockAlloc", "_IORWLockAlloc"}, s.mallocLock},
{[]string{"_malloc_good_size"}, s.mallocGoodSize},
{[]string{"_malloc_size"}, s.mallocSize},
{[]string{"_calloc"}, s.calloc},
{[]string{"_realloc", "_reallocf"}, s.realloc},
{[]string{"_free", "_IOFree", "_IOFreeAligned", "_IOFreeData", "_IOLockFree", "_IORWLockFree", "_OSObject_typed_operator_delete"}, s.free},
{[]string{"_IOFreeTypeImpl", "_IOFreeTypeVarImpl"}, s.freeTyped},
{[]string{"_mmap"}, s.mmap},
{[]string{"_munmap"}, s.munmap},
{[]string{"_vm_allocate"}, s.vmAllocate},
{[]string{"_vm_deallocate"}, s.vmDeallocate},
{[]string{"_memcpy", "_memmove"}, s.memmove},
{[]string{"_memset"}, s.memset},
{[]string{"___bzero"}, s.bzero},
{[]string{"___memcpy_chk"}, s.checkedMemcpy},
{[]string{"___memset_chk"}, s.checkedMemset},
{[]string{"_memcmp"}, s.memcmp},
{[]string{"_strcmp"}, s.strcmp},
{[]string{"_strncmp"}, s.strncmp},
{[]string{"_strlen"}, s.strlen},
{[]string{"_strnlen"}, s.strnlen},
}
for _, service := range services {
if err := s.addAliases(service.names, service.handler); err != nil {
return fmt.Errorf("clear allocated guest memory: %w", err)
}
}
return nil
}
func (s *shims) malloc() error {
size, err := s.argument(0)
if err != nil {
return fmt.Errorf("write reallocated guest memory: %w", err)
}
address, err := s.allocate(size)
if err != nil {
return err
}
return s.setResult(address)
}
func (s *shims) mallocAligned() error {
size, err := s.argument(0)
if err != nil {
return err
}
alignment, err := s.argument(1)
if err != nil {
return err
}
if alignment == 0 || alignment&(alignment-1) != 0 {
return fmt.Errorf("invalid allocation alignment %#x", alignment)
}
address, err := s.allocateAligned(size, alignment)
if err != nil {
return err
}
return s.setResult(address)
}
func (s *shims) mallocTyped() error {
view, err := s.argument(0)
if err != nil {
return err
}
size, err := s.readUint32(view + 44)
if err != nil {
return fmt.Errorf("read typed allocation size: %w", err)
}
address, err := s.allocate(uint64(size & 0x00ff_ffff))
if err != nil {
return err
}
return s.setResult(address)
}
func (s *shims) mallocTypedVariable() error {
size, err := s.argument(1)
if err != nil {
return err
}
address, err := s.allocate(size)
if err != nil {
return err
}
return s.setResult(address)
}
func (s *shims) mallocLock() error {
address, err := s.allocate(8)
if err != nil {
return err
}
if err := s.engine.MemWrite(address, make([]byte, 8)); err != nil {
return fmt.Errorf("initialize malloc lock: %w", err)
}
return s.setResult(address)
}
func (s *shims) freeTyped() error {
address, err := s.argument(1)
if err != nil {
return err
}
if address != 0 {
if err := s.release(address); err != nil {
return err
}
}
return s.setResult(0)
}
func (s *shims) mallocGoodSize() error {
size, err := s.argument(0)
if err != nil {
return err
}
return s.setResult(align(max(size, 1), 16))
}
func (s *shims) mallocSize() error {
address, err := s.argument(0)
if err != nil {
return err
}
allocation, ok := s.allocations[address]
if !ok {
return s.setResult(0)
}
return s.setResult(allocation.reserved)
}
func (s *shims) calloc() error {
count, err := s.argument(0)
if err != nil {
return err
}
size, err := s.argument(1)
if err != nil {
return err
}
if count != 0 && size > math.MaxUint64/count {
return errors.New("allocation size overflows")
}
total := count * size
address, err := s.allocate(total)
if err != nil {
return err
}
if total != 0 {
if err := s.engine.MemWrite(address, make([]byte, total)); err != nil {
_ = s.release(address)
return fmt.Errorf("clear allocated guest memory: %w", err)
}
}
return s.setResult(address)
}
func (s *shims) realloc() error {
oldAddress, err := s.argument(0)
if err != nil {
return fmt.Errorf("write reallocated guest memory: %w", err)
}
newSize, err := s.argument(1)
if err != nil {
return err
}
if oldAddress == 0 {
address, err := s.allocate(newSize)
if err != nil {
return err
}
return s.setResult(address)
}
oldAllocation, ok := s.allocations[oldAddress]
if !ok {
return fmt.Errorf("reallocate unknown pointer %#x", oldAddress)
}
if newSize <= oldAllocation.reserved {
oldAllocation.size = newSize
s.allocations[oldAddress] = oldAllocation
return s.setResult(oldAddress)
}
newAddress, err := s.allocate(newSize)
if err != nil {
return err
}
data, err := s.engine.MemRead(oldAddress, oldAllocation.size)
if err != nil {
_ = s.release(newAddress)
return fmt.Errorf("read reallocated guest memory: %w", err)
}
if err := s.engine.MemWrite(newAddress, data); err != nil {
_ = s.release(newAddress)
return fmt.Errorf("write reallocated guest memory: %w", err)
}
if err := s.release(oldAddress); err != nil {
return err
}
return s.setResult(newAddress)
}
func (s *shims) free() error {
address, err := s.argument(0)
if err != nil {
return err
}
if address != 0 {
if err := s.release(address); err != nil {
return err
}
}
return s.setResult(0)
}
func (s *shims) allocate(size uint64) (uint64, error) {
if size > maxGuestTransfer {
return 0, fmt.Errorf("allocation size %d exceeds limit", size)
}
reserved := align(max(size, 1), 16)
for index, block := range s.freeBlocks {
if block.size < reserved {
continue
}
address := block.address
if block.size == reserved {
s.freeBlocks = append(s.freeBlocks[:index], s.freeBlocks[index+1:]...)
} else {
s.freeBlocks[index].address += reserved
s.freeBlocks[index].size -= reserved
}
s.allocations[address] = guestAllocation{size: size, reserved: reserved}
return address, nil
}
if s.heapCursor > heapSize || reserved > heapSize-s.heapCursor {
return 0, errors.New("guest heap exhausted")
}
address := heapBase + s.heapCursor
s.heapCursor += reserved
s.allocations[address] = guestAllocation{size: size, reserved: reserved}
return address, nil
}
func (s *shims) allocateAligned(size, alignment uint64) (uint64, error) {
if size > maxGuestTransfer {
return 0, fmt.Errorf("allocation size %d exceeds limit", size)
}
reserved := align(max(size, 1), alignment)
cursor := align(s.heapCursor, alignment)
if cursor > heapSize || reserved > heapSize-cursor {
return 0, errors.New("guest heap exhausted")
}
address := heapBase + cursor
s.heapCursor = cursor + reserved
s.allocations[address] = guestAllocation{size: size, reserved: reserved}
return address, nil
}
func (s *shims) mmap() error {
length, err := s.argument(1)
if err != nil {
return err
}
address, err := s.allocateAligned(length, pageSize)
if err != nil {
return s.returnMinusOne()
}
if err := s.engine.MemWrite(address, make([]byte, length)); err != nil {
_ = s.release(address)
return fmt.Errorf("clear mapped guest memory: %w", err)
}
return s.setResult(address)
}
func (s *shims) munmap() error {
address, err := s.argument(0)
if err != nil {
return err
}
if err := s.release(address); err != nil {
return s.setResult(math.MaxUint64)
}
return s.setResult(0)
}
func (s *shims) vmAllocate() error {
field, err := s.argument(1)
if err != nil {
return err
}
size, err := s.argument(2)
if err != nil {
return err
}
address, err := s.allocateAligned(size, pageSize)
if err != nil {
return s.setResult(3) // KERN_NO_SPACE
}
if err := s.engine.MemWrite(address, make([]byte, size)); err != nil {
_ = s.release(address)
return fmt.Errorf("clear allocated VM memory: %w", err)
}
if err := s.writeUint64(field, address); err != nil {
_ = s.release(address)
return err
}
return s.setResult(0)
}
func (s *shims) vmDeallocate() error {
address, err := s.argument(1)
if err != nil {
return err
}
if err := s.release(address); err != nil {
return s.setResult(1) // KERN_INVALID_ADDRESS
}
return s.setResult(0)
}
func (s *shims) release(address uint64) error {
allocation, ok := s.allocations[address]
if !ok {
return fmt.Errorf("free unknown pointer %#x", address)
}
if err := s.engine.MemWrite(address, make([]byte, allocation.reserved)); err != nil {
return fmt.Errorf("clear released guest memory: %w", err)
}
delete(s.allocations, address)
s.freeBlocks = append(s.freeBlocks, freeBlock{address: address, size: allocation.reserved})
s.coalesceFreeBlocks()
return nil
}
func (s *shims) coalesceFreeBlocks() {
sort.Slice(s.freeBlocks, func(left, right int) bool {
return s.freeBlocks[left].address < s.freeBlocks[right].address
})
merged := s.freeBlocks[:0]
for _, block := range s.freeBlocks {
last := len(merged) - 1
if last >= 0 && merged[last].address+merged[last].size == block.address {
merged[last].size += block.size
continue
}
merged = append(merged, block)
}
s.freeBlocks = merged
for len(s.freeBlocks) != 0 {
last := len(s.freeBlocks) - 1
block := s.freeBlocks[last]
if block.address+block.size != heapBase+s.heapCursor {
break
}
s.heapCursor -= block.size
s.freeBlocks = s.freeBlocks[:last]
}
}
func (s *shims) memmove() error {
destination, err := s.argument(0)
if err != nil {
return err
}
source, err := s.argument(1)
if err != nil {
return err
}
length, err := s.argument(2)
if err != nil {
return err
}
if _, err := checkedSize(length); err != nil {
return err
}
data, err := s.engine.MemRead(source, length)
if err != nil {
return fmt.Errorf("read memmove source: %w", err)
}
if err := s.engine.MemWrite(destination, data); err != nil {
return fmt.Errorf("write memmove destination: %w", err)
}
return s.setResult(destination)
}
func (s *shims) memset() error {
destination, err := s.argument(0)
if err != nil {
return err
}
value, err := s.argument(1)
if err != nil {
return err
}
length, err := s.argument(2)
if err != nil {
return err
}
size, err := checkedSize(length)
if err != nil {
return err
}
if err := s.engine.MemWrite(destination, bytes.Repeat([]byte{byte(value)}, size)); err != nil {
return fmt.Errorf("write guest memory fill: %w", err)
}
return s.setResult(destination)
}
func (s *shims) bzero() error {
destination, err := s.argument(0)
if err != nil {
return err
}
length, err := s.argument(1)
if err != nil {
return err
}
size, err := checkedSize(length)
if err != nil {
return err
}
if err := s.engine.MemWrite(destination, make([]byte, size)); err != nil {
return fmt.Errorf("clear guest memory: %w", err)
}
return s.setResult(destination)
}
func (s *shims) checkedMemcpy() error {
length, err := s.argument(2)
if err != nil {
return err
}
capacity, err := s.argument(3)
if err != nil {
return err
}
if length > capacity {
return errors.New("checked copy exceeds destination")
}
return s.memmove()
}
func (s *shims) checkedMemset() error {
length, err := s.argument(2)
if err != nil {
return err
}
capacity, err := s.argument(3)
if err != nil {
return err
}
if length > capacity {
return errors.New("checked fill exceeds destination")
}
return s.memset()
}
func (s *shims) memcmp() error {
left, err := s.argument(0)
if err != nil {
return err
}
right, err := s.argument(1)
if err != nil {
return err
}
length, err := s.argument(2)
if err != nil {
return err
}
if _, err := checkedSize(length); err != nil {
return err
}
a, err := s.engine.MemRead(left, length)
if err != nil {
return fmt.Errorf("read left memory operand: %w", err)
}
b, err := s.engine.MemRead(right, length)
if err != nil {
return fmt.Errorf("read right memory operand: %w", err)
}
return s.setResult(uint64(int64(bytes.Compare(a, b))))
}
func (s *shims) strcmp() error {
left, err := s.argument(0)
if err != nil {
return err
}
right, err := s.argument(1)
if err != nil {
return err
}
a, err := s.readCString(left)
if err != nil {
return err
}
b, err := s.readCString(right)
if err != nil {
return err
}
return s.setResult(uint64(int64(bytes.Compare([]byte(a), []byte(b)))))
}
func (s *shims) strncmp() error {
left, err := s.argument(0)
if err != nil {
return err
}
right, err := s.argument(1)
if err != nil {
return err
}
length, err := s.argument(2)
if err != nil {
return err
}
if _, err := checkedSize(length); err != nil {
return err
}
for offset := uint64(0); offset < length; {
if left > math.MaxUint64-offset || right > math.MaxUint64-offset {
return errors.New("string comparison address overflows")
}
leftAddress := left + offset
rightAddress := right + offset
chunk := min(
length-offset,
pageSize-leftAddress%pageSize,
pageSize-rightAddress%pageSize,
)
a, err := s.engine.MemRead(leftAddress, chunk)
if err != nil {
return fmt.Errorf("read left memory page: %w", err)
}
b, err := s.engine.MemRead(rightAddress, chunk)
if err != nil {
return fmt.Errorf("read right memory page: %w", err)
}
for index := range a {
if a[index] != b[index] {
return s.setResult(uint64(int64(int(a[index]) - int(b[index]))))
}
if a[index] == 0 {
return s.setResult(0)
}
}
offset += chunk
}
return s.setResult(0)
}
func (s *shims) strlen() error {
address, err := s.argument(0)
if err != nil {
return err
}
value, err := s.readCString(address)
if err != nil {
return err
}
return s.setResult(uint64(len(value)))
}
func (s *shims) strnlen() error {
address, err := s.argument(0)
if err != nil {
return err
}
limit, err := s.argument(1)
if err != nil {
return err
}
if limit > maxGuestTransfer {
return fmt.Errorf("string length limit %d exceeds maximum", limit)
}
for offset := uint64(0); offset < limit; {
chunk := min(limit-offset, pageSize-(address+offset)%pageSize)
data, err := s.engine.MemRead(address+offset, chunk)
if err != nil {
return fmt.Errorf("read bounded guest string: %w", err)
}
if index := bytes.IndexByte(data, 0); index >= 0 {
return s.setResult(offset + uint64(index))
}
offset += chunk
}
return s.setResult(limit)
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,64 @@
package machine
import (
"math"
"github.com/majd/ipatool/v2/internal/sap/unicorn"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("guest once services", func() {
It("runs a pthread initializer once with a valid call frame", func() {
machine := newGinkgoServiceMachine(shimOptions{})
control := scratchBase
Expect(machine.services.writeUint64(control, 0x30b1bcba)).To(Succeed())
calls := 0
initializer, err := machine.services.addFunction("test.pthread.initializer", func() error {
stack, readErr := machine.engine.RegRead(unicorn.RegSP)
Expect(readErr).NotTo(HaveOccurred())
Expect(stack % 16).To(BeZero())
calls++
return machine.services.setResult(0xdeadbeef)
})
Expect(err).NotTo(HaveOccurred())
for range 2 {
result, invokeErr := machine.invoke(machine.services.symbols["_pthread_once"], control, initializer)
Expect(invokeErr).NotTo(HaveOccurred())
Expect(result).To(BeZero())
}
Expect(calls).To(Equal(1))
Expect(machine.services.readUint64(control)).To(Equal(uint64(0x4f4e4345)))
})
It("runs a dispatch block once", func() {
machine := newGinkgoServiceMachine(shimOptions{})
predicate := scratchBase
block := scratchBase + 0x100
calls := 0
initializer, err := machine.services.addFunction("test.dispatch.initializer", func() error {
argument, argumentErr := machine.services.argument(0)
Expect(argumentErr).NotTo(HaveOccurred())
Expect(argument).To(Equal(block))
calls++
return machine.services.setResult(0xdeadbeef)
})
Expect(err).NotTo(HaveOccurred())
Expect(machine.services.writeUint64(block+16, initializer)).To(Succeed())
for range 2 {
result, invokeErr := machine.invoke(machine.services.symbols["_dispatch_once"], predicate, block)
Expect(invokeErr).NotTo(HaveOccurred())
Expect(result).To(BeZero())
}
Expect(calls).To(Equal(1))
Expect(machine.services.readUint64(predicate)).To(Equal(uint64(math.MaxUint64)))
})
})
+352
View File
@@ -0,0 +1,352 @@
package machine
import (
"encoding/binary"
"errors"
"fmt"
"math"
"github.com/majd/ipatool/v2/internal/sap/unicorn"
)
const (
shimBase = uint64(0x00007ff880000000)
shimCodeSize = uint64(0x0000000000080000)
shimSize = uint64(0x0000000000100000)
shimSlotSize = uint64(16)
)
type shimHandler func() error
type shimEntry struct {
name string
handler shimHandler
}
type guestAllocation struct {
size uint64
reserved uint64
}
type freeBlock struct {
address uint64
size uint64
}
type xpcObject struct {
data []byte
dataAddress uint64
hasData bool
}
type shimOptions struct {
zeroReturnAliases []string
pauseRunLoop bool
}
type shims struct {
engine *unicorn.Engine
hook *unicorn.Hook
entries map[uint64]shimEntry
symbols map[string]uint64
codeCursor uint64
dataCursor uint64
fault error
coreExports map[string]uint64
icxs []byte
icxsOffset int
errno uint64
heapCursor uint64
allocations map[uint64]guestAllocation
freeBlocks []freeBlock
iterator uint32
callbackReturns []uint64
xpcData []byte
xpcObjects map[uint64]*xpcObject
xpcNextObject uint64
xpcEventHandler uint64
xpcReply []byte
xpcReplied bool
xpcSyncReply []byte
machPortCallback uint64
machPortContext uint64
machPortInfo uint64
fairPlayHandler func([]byte, []byte, int) ([]byte, []byte, int32, error)
machRPCHandler func([]byte, int) ([]byte, error)
machMessageReply []byte
adiFiles map[string][]byte
adiPath string
adiOffset int
hostUUID [16]byte
pauseRunLoop bool
aesVtable uint64
aesService uint64
bufferVtable uint64
}
func newShims(engine *unicorn.Engine, coreExports map[string]uint64, icxs []byte) (*shims, error) {
return newShimsWithOptions(engine, coreExports, icxs, shimOptions{})
}
func newShimsWithOptions(engine *unicorn.Engine, coreExports map[string]uint64, icxs []byte, options shimOptions) (*shims, error) {
if err := engine.MemMap(shimBase, shimSize); err != nil {
return nil, fmt.Errorf("map guest service area: %w", err)
}
s := &shims{
engine: engine,
entries: make(map[uint64]shimEntry),
symbols: make(map[string]uint64),
codeCursor: shimBase,
dataCursor: shimBase + shimCodeSize,
coreExports: coreExports,
icxs: icxs,
allocations: make(map[uint64]guestAllocation),
xpcObjects: make(map[uint64]*xpcObject),
xpcNextObject: 0xffff000000000000,
adiFiles: make(map[string][]byte),
pauseRunLoop: options.pauseRunLoop,
}
if err := s.registerMemoryServices(); err != nil {
return nil, err
}
if err := s.registerPlatformServices(); err != nil {
return nil, err
}
if err := s.addAliases(options.zeroReturnAliases, s.returnZero); err != nil {
return nil, fmt.Errorf("register profile guest services: %w", err)
}
var err error
s.hook, err = engine.AddCodeHook(shimBase, shimBase+shimCodeSize-1, s.dispatch)
if err != nil {
return nil, fmt.Errorf("register guest service dispatcher: %w", err)
}
return s, nil
}
func (s *shims) close() error {
if s.hook == nil {
return nil
}
err := s.hook.Close()
s.hook = nil
if err != nil {
return fmt.Errorf("close guest service hook: %w", err)
}
return nil
}
func (s *shims) resolve(name string) (uint64, error) {
if address, ok := s.symbols[name]; ok {
return address, nil
}
return s.addFunction(name, func() error {
return fmt.Errorf("guest called unsupported import %s", name)
})
}
func (s *shims) addAliases(names []string, handler shimHandler) error {
for _, name := range names {
if _, err := s.addFunction(name, handler); err != nil {
return err
}
}
return nil
}
func (s *shims) addFunction(name string, handler shimHandler) (uint64, error) {
if address, exists := s.symbols[name]; exists {
return address, nil
}
if s.codeCursor+shimSlotSize > shimBase+shimCodeSize {
return 0, errors.New("guest service code area is full")
}
address := s.codeCursor
s.codeCursor += shimSlotSize
if err := s.engine.MemWrite(address, []byte{0xc0, 0x03, 0x5f, 0xd6}); err != nil {
return 0, fmt.Errorf("write guest service stub: %w", err)
}
s.entries[address] = shimEntry{name: name, handler: handler}
s.symbols[name] = address
return address, nil
}
func (s *shims) addData(name string, data []byte) (uint64, error) {
if address, exists := s.symbols[name]; exists {
return address, nil
}
s.dataCursor = align(s.dataCursor, 8)
if s.dataCursor+uint64(len(data)) > shimBase+shimSize {
return 0, errors.New("guest service data area is full")
}
address := s.dataCursor
s.dataCursor += uint64(max(len(data), 8))
if err := s.engine.MemWrite(address, data); err != nil {
return 0, fmt.Errorf("write guest service data: %w", err)
}
s.symbols[name] = address
return address, nil
}
func (s *shims) dispatch(address uint64, _ uint32) {
entry, ok := s.entries[address]
if !ok {
s.fail(fmt.Errorf("guest entered unknown service address %#x", address))
return
}
if err := entry.handler(); err != nil {
s.fail(fmt.Errorf("%s: %w", entry.name, err))
}
}
func (s *shims) fail(err error) {
if s.fault == nil {
s.fault = err
}
if stopErr := s.engine.Stop(); stopErr != nil && s.fault == nil {
s.fault = stopErr
}
}
func (s *shims) resetFault() {
s.fault = nil
}
func (s *shims) argument(index int) (uint64, error) {
registers := [...]int{
unicorn.RegX0,
unicorn.RegX1,
unicorn.RegX2,
unicorn.RegX3,
unicorn.RegX4,
unicorn.RegX5,
unicorn.RegX6,
unicorn.RegX7,
}
if index >= 0 && index < len(registers) {
value, err := s.engine.RegRead(registers[index])
if err != nil {
return 0, fmt.Errorf("read guest argument register: %w", err)
}
return value, nil
}
if index < 0 {
return 0, errors.New("negative guest argument index")
}
stack, err := s.engine.RegRead(unicorn.RegSP)
if err != nil {
return 0, fmt.Errorf("read guest stack register: %w", err)
}
data, err := s.engine.MemRead(stack+uint64(index-len(registers))*8, 8)
if err != nil {
return 0, fmt.Errorf("read guest stack argument: %w", err)
}
return binary.LittleEndian.Uint64(data), nil
}
func (s *shims) setResult(value uint64) error {
if err := s.engine.RegWrite(unicorn.RegX0, value); err != nil {
return fmt.Errorf("write guest result register: %w", err)
}
return nil
}
func (s *shims) readUint32(address uint64) (uint32, error) {
data, err := s.engine.MemRead(address, 4)
if err != nil {
return 0, fmt.Errorf("read guest uint32: %w", err)
}
return binary.LittleEndian.Uint32(data), nil
}
func (s *shims) writeUint32(address uint64, value uint32) error {
var data [4]byte
binary.LittleEndian.PutUint32(data[:], value)
if err := s.engine.MemWrite(address, data[:]); err != nil {
return fmt.Errorf("write guest uint32: %w", err)
}
return nil
}
func (s *shims) readUint64(address uint64) (uint64, error) {
data, err := s.engine.MemRead(address, 8)
if err != nil {
return 0, fmt.Errorf("read guest uint64: %w", err)
}
return binary.LittleEndian.Uint64(data), nil
}
func (s *shims) writeUint64(address, value uint64) error {
var data [8]byte
binary.LittleEndian.PutUint64(data[:], value)
if err := s.engine.MemWrite(address, data[:]); err != nil {
return fmt.Errorf("write guest uint64: %w", err)
}
return nil
}
func (s *shims) readCString(address uint64) (string, error) {
const maximum = 4096
value := make([]byte, 0, 64)
for len(value) < maximum {
item, err := s.engine.MemRead(address+uint64(len(value)), 1)
if err != nil {
return "", fmt.Errorf("read guest string: %w", err)
}
if item[0] == 0 {
return string(value), nil
}
value = append(value, item[0])
}
return "", fmt.Errorf("guest string exceeds %d bytes", maximum)
}
func checkedSize(value uint64) (int, error) {
if value > uint64(math.MaxInt) || value > maxGuestTransfer {
return 0, fmt.Errorf("guest transfer size %d exceeds limit", value)
}
return int(value), nil
}
+335
View File
@@ -0,0 +1,335 @@
package machine
import (
"context"
"errors"
"fmt"
"io"
"sync"
"github.com/majd/ipatool/v2/internal/sap/assets"
)
const (
storeAgentBase = uint64(0x00001000c0000000)
storeAgentGlobalInit = storeAgentBase + 0x1312fc
storeAgentKBSyncEntry = storeAgentBase + 0x19ae34
storeAgentSessionInit = storeAgentBase + 0x13ac60
storeAgentDecryptEntry = storeAgentBase + 0x175390
storeAgentGlobalClose = storeAgentBase + 0x130eb4
storeAgentChunkSize = 0x8000
storeAgentSCInfoPath = "/Users/Shared/SC Info"
)
var storeAgentZeroReturnAliases = []string{
"_pthread_rwlock_rdlock",
"_pthread_rwlock_rdlock$UNIX2003",
"_pthread_mutex_init",
"_pthread_mutex_destroy",
"_pthread_rwlock_destroy",
}
type StoreAgent struct {
mu sync.Mutex
guest *Machine
global uint32
session uint64
decryptEntry uint64
closeEntry uint64
closed bool
}
func OpenStoreAgent(ctx context.Context, bundle assets.Bundle, hardwareID, dpInfo []byte) (*StoreAgent, error) {
if ctx == nil {
return nil, errors.New("StoreAgent context is nil")
}
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("open StoreAgent runtime: %w", err)
}
return openStoreAgent(ctx, bundle, hardwareID, dpInfo)
}
func openStoreAgent(ctx context.Context, bundle assets.Bundle, hardwareID, dpInfo []byte) (*StoreAgent, error) {
if len(dpInfo) == 0 {
return nil, errors.New("StoreAgent dpInfo is empty")
}
agent, globalContext, err := openStoreAgentGlobal(ctx, bundle, hardwareID)
if err != nil {
return nil, err
}
agent.session, err = agent.initializeSession(globalContext, dpInfo)
if err != nil {
_ = agent.Close()
return nil, err
}
return agent, nil
}
func openStoreAgentGlobal(ctx context.Context, bundle assets.Bundle, hardwareID []byte) (*StoreAgent, uint32, error) {
if ctx == nil {
return nil, 0, errors.New("StoreAgent context is nil")
}
if err := ctx.Err(); err != nil {
return nil, 0, fmt.Errorf("open StoreAgent runtime: %w", err)
}
hardware, err := hardwareBlock(hardwareID)
if err != nil {
return nil, 0, err
}
guest, exports, err := openRuntime(ctx, bundle, runtimeOptions{
extraImages: []imageSpec{{name: "commerce", data: bundle.Commerce, base: storeAgentBase}},
shims: shimOptions{
zeroReturnAliases: storeAgentZeroReturnAliases,
},
})
if err != nil {
return nil, 0, fmt.Errorf("start StoreAgent runtime: %w", err)
}
guest.entry.dispose = exports["_jEHf8Xzsv8K"]
agent := &StoreAgent{
guest: guest,
decryptEntry: storeAgentDecryptEntry,
closeEntry: storeAgentGlobalClose,
}
globalContext, err := agent.initializeGlobal(hardware)
if err != nil {
_ = agent.Close()
return nil, 0, err
}
agent.global = globalContext
return agent, globalContext, nil
}
func (s *StoreAgent) initializeGlobal(hardware []byte) (uint32, error) {
s.guest.beginCall()
defer s.guest.clearScratch()
hardwareAddress, err := s.guest.scratch(hardware, uint64(len(hardware)))
if err != nil {
return 0, err
}
path := append([]byte(storeAgentSCInfoPath), 0)
pathAddress, err := s.guest.scratch(path, uint64(len(path)))
if err != nil {
return 0, err
}
contextField, err := s.guest.scratch(nil, 4)
if err != nil {
return 0, err
}
status, err := s.guest.invoke(storeAgentGlobalInit, 0, hardwareAddress, pathAddress, contextField)
if err != nil {
return 0, fmt.Errorf("initialize StoreAgent global context: %w", err)
}
if int32(status) != 0 {
return 0, fmt.Errorf("StoreAgent global initialization returned %d", int32(status))
}
value, err := s.guest.readUint32(contextField)
if err != nil {
return 0, err
}
if value == 0 {
return 0, errors.New("StoreAgent global initialization returned a null context")
}
return value, nil
}
func (s *StoreAgent) initializeSession(globalContext uint32, dpInfo []byte) (uint64, error) {
s.guest.beginCall()
defer s.guest.clearScratch()
dpInfoAddress, err := s.guest.scratch(dpInfo, uint64(len(dpInfo)))
if err != nil {
return 0, err
}
sessionField, err := s.guest.scratch(nil, 8)
if err != nil {
return 0, err
}
status, err := s.guest.invoke(
storeAgentSessionInit,
uint64(globalContext),
dpInfoAddress,
uint64(len(dpInfo)),
sessionField,
)
if err != nil {
return 0, fmt.Errorf("initialize StoreAgent session: %w", err)
}
if int32(status) != 0 {
return 0, fmt.Errorf("StoreAgent session initialization returned %d", int32(status))
}
session, err := s.guest.readUint64(sessionField)
if err != nil {
return 0, err
}
if session == 0 {
return 0, errors.New("StoreAgent session initialization returned a null session")
}
return session, nil
}
func (s *StoreAgent) Decrypt(ctx context.Context, dst io.Writer, src io.Reader) (int64, error) {
if s == nil {
return 0, errors.New("StoreAgent is nil")
}
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return 0, errors.New("StoreAgent is closed")
}
if ctx == nil {
return 0, errors.New("StoreAgent decryption context is nil")
}
if dst == nil {
return 0, errors.New("StoreAgent decryption destination is nil")
}
if src == nil {
return 0, errors.New("StoreAgent decryption source is nil")
}
return decryptStream(ctx, dst, src, s.decryptChunk)
}
func (s *StoreAgent) decryptChunk(data []byte) error {
s.guest.beginCall()
defer s.guest.clearScratch()
address, err := s.guest.scratch(data, uint64(len(data)))
if err != nil {
return err
}
status, err := s.guest.invoke(
s.decryptEntry,
s.session,
address,
uint64(len(data)),
address,
0,
)
if err != nil {
return fmt.Errorf("decrypt StoreAgent chunk: %w", err)
}
if int32(status) != 0 {
return fmt.Errorf("StoreAgent decryption returned %d", int32(status))
}
if err := s.guest.engine.MemReadInto(data, address); err != nil {
return fmt.Errorf("read decrypted StoreAgent chunk: %w", err)
}
return nil
}
func decryptStream(ctx context.Context, dst io.Writer, src io.Reader, decrypt func([]byte) error) (int64, error) {
buffer := make([]byte, storeAgentChunkSize)
var written int64
for {
if err := ctx.Err(); err != nil {
return written, fmt.Errorf("decrypt StoreAgent stream: %w", err)
}
count, readErr := io.ReadFull(src, buffer)
if count != 0 {
chunk := buffer[:count]
if err := decrypt(chunk); err != nil {
return written, err
}
n, err := dst.Write(chunk)
written += int64(n)
if err != nil {
return written, fmt.Errorf("write decrypted StoreAgent stream: %w", err)
}
if n != len(chunk) {
return written, fmt.Errorf("write decrypted StoreAgent stream: %w", io.ErrShortWrite)
}
}
switch {
case readErr == nil:
continue
case errors.Is(readErr, io.EOF), errors.Is(readErr, io.ErrUnexpectedEOF):
return written, nil
default:
return written, fmt.Errorf("read encrypted StoreAgent stream: %w", readErr)
}
}
}
func (s *StoreAgent) Close() error {
if s == nil {
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil
}
s.closed = true
var errs []error
if s.guest != nil && s.global != 0 {
global := s.global
s.global = 0
s.session = 0
status, err := s.guest.invoke(s.closeEntry, uint64(global))
if err != nil {
errs = append(errs, fmt.Errorf("close StoreAgent global context: %w", err))
} else if int32(status) != 0 {
errs = append(errs, fmt.Errorf("StoreAgent global context close returned %d", int32(status)))
}
}
if s.guest != nil {
errs = append(errs, s.guest.Close())
s.guest = nil
}
return errors.Join(errs...)
}
+198
View File
@@ -0,0 +1,198 @@
package machine
import (
"bytes"
"context"
"errors"
"io"
"github.com/majd/ipatool/v2/internal/sap/unicorn"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("StoreAgent", func() {
Describe("profile", func() {
It("pins the verified image base and entry offsets", func() {
Expect(storeAgentBase).To(Equal(uint64(0x00001000c0000000)))
Expect(storeAgentGlobalInit).To(Equal(storeAgentBase + 0x1312fc))
Expect(storeAgentSessionInit).To(Equal(storeAgentBase + 0x13ac60))
Expect(storeAgentDecryptEntry).To(Equal(storeAgentBase + 0x175390))
Expect(storeAgentGlobalClose).To(Equal(storeAgentBase + 0x130eb4))
})
It("adds only the StoreAgent synchronization aliases", func() {
machine := newGinkgoServiceMachine(shimOptions{zeroReturnAliases: storeAgentZeroReturnAliases})
for _, name := range storeAgentZeroReturnAliases {
address, ok := machine.services.symbols[name]
Expect(ok).To(BeTrue(), name)
Expect(machine.invoke(address)).To(Equal(uint64(0)))
}
})
It("does not add StoreAgent aliases to the default SAP profile", func() {
machine := newGinkgoServiceMachine(shimOptions{})
address, err := machine.services.resolve("_pthread_mutex_init")
Expect(err).NotTo(HaveOccurred())
_, err = machine.invoke(address)
Expect(err).To(MatchError(ContainSubstring("unsupported import _pthread_mutex_init")))
})
})
Describe("streaming decryption", func() {
It("uses full 0x8000 chunks and a final partial chunk", func() {
input := bytes.Repeat([]byte{0x3c}, 2*storeAgentChunkSize+17)
var output bytes.Buffer
var sizes []int
written, err := decryptStream(context.Background(), &output, bytes.NewReader(input), func(chunk []byte) error {
sizes = append(sizes, len(chunk))
for index := range chunk {
chunk[index] ^= 0xff
}
return nil
})
Expect(err).NotTo(HaveOccurred())
Expect(written).To(Equal(int64(len(input))))
Expect(sizes).To(Equal([]int{storeAgentChunkSize, storeAgentChunkSize, 17}))
Expect(output.Bytes()).To(Equal(bytes.Repeat([]byte{0xc3}, len(input))))
})
It("does not invoke the decryptor for an empty stream", func() {
called := false
written, err := decryptStream(context.Background(), io.Discard, bytes.NewReader(nil), func([]byte) error {
called = true
return nil
})
Expect(err).NotTo(HaveOccurred())
Expect(written).To(BeZero())
Expect(called).To(BeFalse())
})
It("writes a partial read before returning its source error", func() {
sourceErr := errors.New("source failed")
source := io.MultiReader(bytes.NewReader([]byte("partial")), errorReader{err: sourceErr})
var output bytes.Buffer
written, err := decryptStream(context.Background(), &output, source, func(chunk []byte) error {
return nil
})
Expect(written).To(Equal(int64(len("partial"))))
Expect(output.String()).To(Equal("partial"))
Expect(err).To(MatchError(ContainSubstring(sourceErr.Error())))
})
It("stops before the next chunk when the context is canceled", func() {
ctx, cancel := context.WithCancel(context.Background())
input := bytes.Repeat([]byte{1}, 2*storeAgentChunkSize)
calls := 0
written, err := decryptStream(ctx, io.Discard, bytes.NewReader(input), func([]byte) error {
calls++
cancel()
return nil
})
Expect(calls).To(Equal(1))
Expect(written).To(Equal(int64(storeAgentChunkSize)))
Expect(err).To(MatchError(ContainSubstring(context.Canceled.Error())))
})
It("returns decryptor errors without writing the failed chunk", func() {
decryptErr := errors.New("decrypt failed")
var output bytes.Buffer
written, err := decryptStream(context.Background(), &output, bytes.NewReader([]byte("encrypted")), func([]byte) error {
return decryptErr
})
Expect(written).To(BeZero())
Expect(output.Len()).To(BeZero())
Expect(err).To(MatchError(decryptErr))
})
It("reports short writes", func() {
written, err := decryptStream(context.Background(), shortWriter{}, bytes.NewReader([]byte("encrypted")), func([]byte) error {
return nil
})
Expect(written).To(Equal(int64(1)))
Expect(err).To(MatchError(ContainSubstring(io.ErrShortWrite.Error())))
})
})
It("closes the global context and machine idempotently", func() {
machine := newGinkgoServiceMachine(shimOptions{})
var closedContext uint64
closeEntry, err := machine.services.addFunction("test.storeagent.close", func() error {
value, argumentErr := machine.services.argument(0)
if argumentErr != nil {
return argumentErr
}
closedContext = value
return machine.services.setResult(0)
})
Expect(err).NotTo(HaveOccurred())
agent := &StoreAgent{guest: machine, global: 0x1234, session: 0x5678, closeEntry: closeEntry}
Expect(agent.Close()).To(Succeed())
Expect(closedContext).To(Equal(uint64(0x1234)))
Expect(agent.global).To(BeZero())
Expect(agent.session).To(BeZero())
Expect(agent.guest).To(BeNil())
Expect(agent.Close()).To(Succeed())
})
})
type errorReader struct {
err error
}
func (r errorReader) Read([]byte) (int, error) {
return 0, r.err
}
type shortWriter struct{}
func (shortWriter) Write([]byte) (int, error) {
return 1, nil
}
func newGinkgoServiceMachine(options shimOptions) *Machine {
engine, err := unicorn.New(context.Background())
Expect(err).NotTo(HaveOccurred())
for _, region := range []struct {
address uint64
size uint64
}{
{returnAddress, pageSize},
{scratchBase, scratchSize},
{heapBase, heapSize},
{stackBase, stackSize},
} {
Expect(engine.MemMap(region.address, region.size)).To(Succeed())
}
Expect(engine.MemWrite(returnAddress, []byte{0x00, 0x00, 0x20, 0xd4})).To(Succeed())
services, err := newShimsWithOptions(engine, map[string]uint64{}, nil, options)
Expect(err).NotTo(HaveOccurred())
machine := &Machine{engine: engine, services: services}
DeferCleanup(func() {
Expect(machine.Close()).To(Succeed())
})
return machine
}
+104
View File
@@ -0,0 +1,104 @@
package sap
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"howett.net/plist"
apphttp "github.com/majd/ipatool/v2/pkg/http"
)
const (
setupCertificateKey = "sign-sap-setup-cert"
setupBufferKey = "sign-sap-setup-buffer"
maxSetupBody = int64(1 << 20)
)
type setupProtocol struct {
client interface {
Do(*http.Request) (*http.Response, error)
}
}
func (p setupProtocol) certificate(ctx context.Context, endpoint string) ([]byte, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, fmt.Errorf("create SAP certificate request: %w", err)
}
request.Header.Set("User-Agent", apphttp.DefaultUserAgent)
body, err := p.send(request)
if err != nil {
return nil, fmt.Errorf("fetch SAP certificate: %w", err)
}
return plistBytes(body, setupCertificateKey)
}
func (p setupProtocol) exchange(ctx context.Context, endpoint string, input []byte) ([]byte, error) {
envelope, err := plist.Marshal(map[string]any{setupBufferKey: input}, plist.XMLFormat)
if err != nil {
return nil, fmt.Errorf("encode SAP setup message: %w", err)
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(envelope))
if err != nil {
return nil, fmt.Errorf("create SAP setup request: %w", err)
}
request.Header.Set("Content-Type", "application/x-plist")
request.Header.Set("User-Agent", apphttp.DefaultUserAgent)
body, err := p.send(request)
if err != nil {
return nil, fmt.Errorf("exchange SAP setup message: %w", err)
}
return plistBytes(body, setupBufferKey)
}
func (p setupProtocol) send(request *http.Request) ([]byte, error) {
response, err := p.client.Do(request)
if err != nil {
return nil, fmt.Errorf("send SAP request: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, maxSetupBody))
return nil, fmt.Errorf("apple returned %s", response.Status)
}
body, err := io.ReadAll(io.LimitReader(response.Body, maxSetupBody+1))
if err != nil {
return nil, fmt.Errorf("read SAP response: %w", err)
}
if int64(len(body)) > maxSetupBody {
return nil, fmt.Errorf("apple response exceeds %d bytes", maxSetupBody)
}
return body, nil
}
func plistBytes(document []byte, key string) ([]byte, error) {
var values map[string]any
if _, err := plist.Unmarshal(document, &values); err != nil {
return nil, fmt.Errorf("decode Apple plist: %w", err)
}
value, ok := values[key].([]byte)
if !ok || len(value) == 0 {
return nil, errors.New("Apple plist is missing " + key)
}
return value, nil
}
+89
View File
@@ -0,0 +1,89 @@
package sap
import (
"bytes"
"context"
"io"
"net/http"
"strings"
"testing"
"howett.net/plist"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (function roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
return function(request)
}
func TestSetupProtocol(t *testing.T) {
protocol := setupProtocol{client: &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
if request.Header.Get("User-Agent") == "" {
t.Error("User-Agent is empty")
}
key := setupCertificateKey
value := []byte("certificate")
if request.Method == http.MethodPost {
if request.Header.Get("Content-Type") != "application/x-plist" {
t.Errorf("Content-Type = %q", request.Header.Get("Content-Type"))
}
requestBody, err := io.ReadAll(request.Body)
if err != nil {
t.Fatal(err)
}
decoded, err := plistBytes(requestBody, setupBufferKey)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(decoded, []byte("request")) {
t.Errorf("request data = %q", decoded)
}
key = setupBufferKey
value = []byte("reply")
}
body, err := plist.Marshal(map[string]any{key: value}, plist.XMLFormat)
if err != nil {
t.Fatal(err)
}
return &http.Response{
StatusCode: http.StatusOK,
Status: "200 OK",
Body: io.NopCloser(bytes.NewReader(body)),
Header: make(http.Header),
}, nil
})}}
certificate, err := protocol.certificate(context.Background(), "https://example.com/certificate")
if err != nil {
t.Fatal(err)
}
if string(certificate) != "certificate" {
t.Fatalf("certificate = %q", certificate)
}
reply, err := protocol.exchange(context.Background(), "https://example.com/setup", []byte("request"))
if err != nil {
t.Fatal(err)
}
if string(reply) != "reply" {
t.Fatalf("reply = %q", reply)
}
}
func TestSetupProtocolRejectsOversizedResponse(t *testing.T) {
protocol := setupProtocol{client: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Status: "200 OK",
Body: io.NopCloser(strings.NewReader(strings.Repeat("x", int(maxSetupBody)+1))),
Header: make(http.Header),
}, nil
})}}
if _, err := protocol.certificate(context.Background(), "https://example.com/certificate"); err == nil {
t.Fatal("oversized response was accepted")
}
}
+56
View File
@@ -0,0 +1,56 @@
package sap
import (
"errors"
"fmt"
"net/http"
"net/url"
)
const supportedVersion = uint32(200)
var errSignerClosed = errors.New("SAP signer is closed")
type Config struct {
HTTPClient interface {
Do(*http.Request) (*http.Response, error)
}
SetupURL string
CertificateURL string
Version uint32
HardwareID []byte
}
type ActionSigner interface {
Sign(input []byte) ([]byte, error)
Close() error
}
func validateConfig(config Config) error {
if config.Version != supportedVersion {
return fmt.Errorf("unsupported SAP version %d", config.Version)
}
if len(config.HardwareID) == 0 || len(config.HardwareID) > 20 {
return errors.New("SAP hardware ID must contain between 1 and 20 bytes")
}
if err := validateEndpoint("setup", config.SetupURL); err != nil {
return err
}
if err := validateEndpoint("certificate", config.CertificateURL); err != nil {
return err
}
return nil
}
func validateEndpoint(label, value string) error {
endpoint, err := url.Parse(value)
if err != nil || endpoint.Scheme != "https" || endpoint.Host == "" || endpoint.User != nil {
return fmt.Errorf("SAP %s URL must be an absolute HTTPS URL", label)
}
return nil
}
+55
View File
@@ -0,0 +1,55 @@
package sap
import (
"context"
"errors"
"net"
"testing"
"time"
"github.com/avast/retry-go"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestSignerIntegration(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "SAP Signer Integration Suite")
}
var _ = Describe("SAP signer integration", func() {
It("signs distinct payloads with distinct signatures", func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
var signer ActionSigner
// Retry live endpoint timeouts with a fresh session, within the overall deadline.
err := retry.Do(func() error {
var err error
signer, err = NewSigner(ctx, Config{
SetupURL: "https://fpinit.itunes.apple.com/v1/signSapSetup/legacy",
CertificateURL: "https://s.mzstatic.com/sap/setupCert.plist",
Version: 200,
HardwareID: []byte{0x02, 0, 0, 0, 0, 1},
})
return err
}, retry.Context(ctx), retry.Attempts(3), retry.RetryIf(func(err error) bool {
var networkError net.Error
return errors.As(err, &networkError) && networkError.Timeout()
}))
Expect(err).NotTo(HaveOccurred())
DeferCleanup(signer.Close)
signature, err := signer.Sign([]byte("ipatool SAP smoke test"))
Expect(err).NotTo(HaveOccurred())
Expect(signature).NotTo(BeEmpty())
second, err := signer.Sign([]byte("ipatool second SAP smoke test"))
Expect(err).NotTo(HaveOccurred())
Expect(second).NotTo(BeEmpty())
Expect(second).NotTo(Equal(signature))
})
})
+155
View File
@@ -0,0 +1,155 @@
package sap
import (
"context"
"errors"
"fmt"
"net/http"
"sync"
"time"
"github.com/majd/ipatool/v2/internal/sap/assets"
"github.com/majd/ipatool/v2/internal/sap/machine"
)
type Signer struct {
mu sync.Mutex
machine *machine.Machine
context uint64
hardware []byte
closed bool
}
func NewSigner(ctx context.Context, config Config) (ActionSigner, error) {
if ctx == nil {
return nil, errors.New("SAP signer context is nil")
}
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("create SAP signer: %w", err)
}
if err := validateConfig(config); err != nil {
return nil, err
}
bundle, err := assets.Load(ctx)
if err != nil {
return nil, fmt.Errorf("load Apple SAP assets: %w", err)
}
guest, err := machine.Open(ctx, bundle)
if err != nil {
return nil, fmt.Errorf("start Apple SAP runtime: %w", err)
}
signer := &Signer{
machine: guest,
hardware: append([]byte(nil), config.HardwareID...),
}
complete := false
defer func() {
if !complete {
_ = signer.Close()
}
}()
signer.context, err = guest.Initialize(signer.hardware)
if err != nil {
return nil, fmt.Errorf("initialize Apple SAP session: %w", err)
}
protocol := setupProtocol{client: &http.Client{Timeout: 30 * time.Second}}
if config.HTTPClient != nil {
protocol.client = config.HTTPClient
}
certificate, err := protocol.certificate(ctx, config.CertificateURL)
if err != nil {
return nil, err
}
request, state, err := guest.Exchange(config.Version, signer.hardware, signer.context, certificate)
if err != nil {
return nil, fmt.Errorf("create SAP setup message: %w", err)
}
if state != 1 {
return nil, fmt.Errorf("SAP setup entered unexpected state %d", state)
}
if len(request) == 0 {
return nil, errors.New("SAP setup message is empty")
}
reply, err := protocol.exchange(ctx, config.SetupURL, request)
if err != nil {
return nil, err
}
_, state, err = guest.Exchange(config.Version, signer.hardware, signer.context, reply)
if err != nil {
return nil, fmt.Errorf("complete SAP setup: %w", err)
}
if state != 0 {
return nil, fmt.Errorf("SAP setup completed in unexpected state %d", state)
}
complete = true
return signer, nil
}
func (s *Signer) Sign(input []byte) ([]byte, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil, errSignerClosed
}
signature, err := s.machine.Sign(s.context, input)
if err != nil {
return nil, fmt.Errorf("sign Apple request: %w", err)
}
if len(signature) == 0 {
return nil, errors.New("sign Apple request: signature is empty")
}
return signature, nil
}
func (s *Signer) Close() error {
if s == nil {
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil
}
s.closed = true
var closeErrors []error
if s.machine != nil && s.context != 0 {
closeErrors = append(closeErrors, s.machine.Teardown(s.context))
s.context = 0
}
if s.machine != nil {
closeErrors = append(closeErrors, s.machine.Close())
s.machine = nil
}
for index := range s.hardware {
s.hardware[index] = 0
}
return errors.Join(closeErrors...)
}
+17
View File
@@ -0,0 +1,17 @@
package sap
import (
"errors"
"testing"
)
func TestClosedSigner(t *testing.T) {
signer := &Signer{closed: true}
if _, err := signer.Sign([]byte("message")); !errors.Is(err, errSignerClosed) {
t.Fatalf("Sign error = %v, want %v", err, errSignerClosed)
}
if err := signer.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
}
+62
View File
@@ -0,0 +1,62 @@
package sap
import (
"context"
"errors"
"testing"
)
func TestNewSignerRejectsInvalidContext(t *testing.T) {
config := Config{
SetupURL: "https://example.apple.com/setup",
CertificateURL: "https://example.apple.com/certificate",
Version: 200,
HardwareID: []byte{1, 2, 3, 4, 5, 6},
}
//nolint:staticcheck // This test verifies that a nil context is rejected.
if _, err := NewSigner(nil, config); err == nil {
t.Fatal("NewSigner accepted a nil context")
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err := NewSigner(ctx, config); !errors.Is(err, context.Canceled) {
t.Fatalf("NewSigner error = %v, want %v", err, context.Canceled)
}
}
func TestValidateConfig(t *testing.T) {
valid := Config{
SetupURL: "https://example.apple.com/setup",
CertificateURL: "https://example.apple.com/certificate",
Version: 200,
HardwareID: []byte{1, 2, 3, 4, 5, 6},
}
tests := []struct {
name string
mutate func(*Config)
}{
{"version", func(config *Config) { config.Version = 210 }},
{"empty hardware ID", func(config *Config) { config.HardwareID = nil }},
{"long hardware ID", func(config *Config) { config.HardwareID = make([]byte, 21) }},
{"relative setup URL", func(config *Config) { config.SetupURL = "/setup" }},
{"HTTP certificate URL", func(config *Config) { config.CertificateURL = "http://example.apple.com/cert" }},
{"credentialed URL", func(config *Config) { config.SetupURL = "https://user@example.apple.com/setup" }},
}
if err := validateConfig(valid); err != nil {
t.Fatalf("valid config: %v", err)
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
config := valid
test.mutate(&config)
if err := validateConfig(config); err == nil {
t.Fatal("validateConfig accepted invalid config")
}
})
}
}
+17
View File
@@ -0,0 +1,17 @@
package unicorn
import "io"
type archiveFormat uint8
const (
archiveZIP archiveFormat = iota
archiveSevenZip
archiveTarZstd
)
type archiveEntry struct {
reader io.Reader
size uint64
close func() error
}
@@ -0,0 +1,56 @@
//go:build windows
package unicorn
import (
"errors"
"fmt"
"github.com/bodgit/sevenzip"
)
func openArchiveEntry(path, name string, format archiveFormat) (archiveEntry, error) {
switch format {
case archiveZIP:
return openZIPEntry(path, name)
case archiveSevenZip:
return openSevenZipEntry(path, name)
case archiveTarZstd:
return openTarZstdEntry(path, name)
default:
return archiveEntry{}, fmt.Errorf("unsupported Unicorn archive format %d", format)
}
}
func openSevenZipEntry(path, name string) (archiveEntry, error) {
archive, err := sevenzip.OpenReader(path)
if err != nil {
return archiveEntry{}, fmt.Errorf("open Unicorn archive: %w", err)
}
for _, candidate := range archive.File {
if candidate.Name != name {
continue
}
if candidate.FileInfo().IsDir() {
_ = archive.Close()
return archiveEntry{}, fmt.Errorf("invalid Unicorn library entry %q", name)
}
reader, err := candidate.Open()
if err != nil {
_ = archive.Close()
return archiveEntry{}, fmt.Errorf("open Unicorn library entry: %w", err)
}
return archiveEntry{
reader: reader,
size: candidate.UncompressedSize,
close: func() error {
return errors.Join(reader.Close(), archive.Close())
},
}, nil
}
_ = archive.Close()
return archiveEntry{}, fmt.Errorf("Unicorn archive does not contain %q", name)
}
+64
View File
@@ -0,0 +1,64 @@
package unicorn
import (
"archive/tar"
"errors"
"fmt"
"io"
"os"
"github.com/klauspost/compress/zstd"
)
func openTarZstdEntry(path, name string) (archiveEntry, error) {
file, err := os.Open(path)
if err != nil {
return archiveEntry{}, fmt.Errorf("open Unicorn archive: %w", err)
}
decoder, err := zstd.NewReader(file)
if err != nil {
_ = file.Close()
return archiveEntry{}, fmt.Errorf("open Unicorn archive: %w", err)
}
closeArchive := func() error {
decoder.Close()
return file.Close()
}
reader := tar.NewReader(decoder)
for {
header, err := reader.Next()
if errors.Is(err, io.EOF) {
_ = closeArchive()
return archiveEntry{}, fmt.Errorf("unicorn archive does not contain %q", name)
}
if err != nil {
_ = closeArchive()
return archiveEntry{}, fmt.Errorf("read Unicorn archive: %w", err)
}
if header.Name != name {
continue
}
if header.Typeflag != tar.TypeReg || header.Size < 0 {
_ = closeArchive()
return archiveEntry{}, fmt.Errorf("invalid Unicorn library entry %q", name)
}
return archiveEntry{
reader: io.LimitReader(reader, header.Size),
size: uint64(header.Size),
close: closeArchive,
}, nil
}
}
@@ -0,0 +1,71 @@
package unicorn
import (
"archive/tar"
"bytes"
"io"
"os"
"path/filepath"
"testing"
"github.com/klauspost/compress/zstd"
)
func TestOpenTarZstdEntry(t *testing.T) {
const name = "clangarm64/bin/libunicorn.dll"
payload := []byte("test Unicorn library")
var compressed bytes.Buffer
encoder, err := zstd.NewWriter(&compressed)
if err != nil {
t.Fatal(err)
}
archive := tar.NewWriter(encoder)
if err := archive.WriteHeader(&tar.Header{Name: name, Mode: 0o600, Size: int64(len(payload))}); err != nil {
t.Fatal(err)
}
if _, err := archive.Write(payload); err != nil {
t.Fatal(err)
}
if err := archive.Close(); err != nil {
t.Fatal(err)
}
if err := encoder.Close(); err != nil {
t.Fatal(err)
}
path := filepath.Join(t.TempDir(), "runtime.pkg.tar.zst")
if err := os.WriteFile(path, compressed.Bytes(), 0o600); err != nil {
t.Fatal(err)
}
entry, err := openTarZstdEntry(path, name)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := entry.close(); err != nil {
t.Errorf("close archive entry: %v", err)
}
})
actual, err := io.ReadAll(entry.reader)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(actual, payload) {
t.Fatalf("contents = %q, want %q", actual, payload)
}
if entry.size != uint64(len(payload)) {
t.Fatalf("size = %d, want %d", entry.size, len(payload))
}
}
+13
View File
@@ -0,0 +1,13 @@
//go:build darwin || linux
package unicorn
import "fmt"
func openArchiveEntry(path, name string, format archiveFormat) (archiveEntry, error) {
if format != archiveZIP {
return archiveEntry{}, fmt.Errorf("unsupported Unicorn archive format %d", format)
}
return openZIPEntry(path, name)
}
Loaded 100 of 312 files, more files were not shown because too many files have changed in this diff. Show more