mirror of
https://github.com/majd/ipatool
synced 2026-11-28 18:27:52 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72c47d538b | ||
|
|
001d889896 | ||
|
|
d9c0247dae | ||
|
|
5dc4c8058d | ||
|
|
1b9ff28eb4 | ||
|
|
7578671482 | ||
|
|
b0fe32d8a1 | ||
|
|
0259df3c09 | ||
|
|
5b7a812a77 | ||
|
|
9d343753c4 | ||
|
|
987900b417 | ||
|
|
4484b55d36 | ||
|
|
e3932cec31 | ||
|
|
cde7d00355 | ||
|
|
93b527a839 | ||
|
|
ed45c02852 | ||
|
|
f11d9abafe | ||
|
|
f9aa6536cd | ||
|
|
3411d57f45 | ||
|
|
0cc226a3d7 | ||
|
|
e258fed14a | ||
|
|
1ec8b3e5dc | ||
|
|
387d1a4f47 | ||
|
|
294488012f | ||
|
|
5deb9b521b | ||
|
|
acd9e7a972 | ||
|
|
50312a928b | ||
|
|
735b689ac3 | ||
|
|
e5211d6fd9 | ||
|
|
747d66fc0a | ||
|
|
1ed3bf94dd | ||
|
|
fb1ca3521b | ||
|
|
ad88910ad6 | ||
|
|
c66d6537f4 | ||
|
|
7b4913a71c | ||
|
|
c4323e4c55 | ||
|
|
2aaf18b832 | ||
|
|
e3dea14461 | ||
|
|
dd28a3a9d8 | ||
|
|
5a47056bc3 | ||
|
|
ba85241c88 | ||
|
|
394cd643de | ||
|
|
62f1c8b435 | ||
|
|
5c522b685d | ||
|
|
ba180d741d | ||
|
|
d1845ba678 | ||
|
|
a814a71a9f | ||
|
|
843f5c6c29 | ||
|
|
b8bac296b8 | ||
|
|
24f93d332f | ||
|
|
e6acb9c3c2 | ||
|
|
abdb5902cb | ||
|
|
91d4294085 | ||
|
|
73fabcc283 | ||
|
|
30b2909231 | ||
|
|
a9bd16c9a2 | ||
|
|
cee3674258 | ||
|
|
8f9748fa51 |
No files matched your search
@@ -0,0 +1 @@
|
||||
github: majd
|
||||
@@ -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
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -6,6 +6,45 @@ on:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
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.26.5"
|
||||
cache: true
|
||||
- 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 }}
|
||||
@@ -17,7 +56,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 generate github.com/majd/ipatool/...
|
||||
- run: go test -v github.com/majd/ipatool/...
|
||||
- run: go generate ./...
|
||||
- run: go test -v -timeout 20m ./...
|
||||
+1
-1
@@ -4,4 +4,4 @@
|
||||
.vscode/
|
||||
.idea/
|
||||
**/*_mock.go
|
||||
exp/
|
||||
exp/
|
||||
@@ -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>
|
||||
|
||||
[](https://GitHub.com/majd/ipatool/releases/)
|
||||
[](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, iPadOS, tvOS, and visionOS apps on the [App Store](https://apps.apple.com) and download a copy of the app package, known as an _ipa_ file.
|
||||
|
||||

|
||||
|
||||
- [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,155 +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, iPadOS, tvOS, and visionOS 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; visionOS supports up to 12 (default 5)
|
||||
--platform string Platform to search: iphone (iOS), ipad (iPadOS), appletv (tvOS), or visionos
|
||||
|
||||
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 list apps owned by the authenticated account, use the `list-purchases` command. Results are ordered by purchase date, newest first.
|
||||
|
||||
```
|
||||
List apps owned by the authenticated App Store account
|
||||
|
||||
Usage:
|
||||
ipatool list-purchases [flags]
|
||||
|
||||
Flags:
|
||||
-h, --help help for list-purchases
|
||||
-l, --max-results int maximum number of apps to return per page (default 10)
|
||||
-p, --page int page of owned apps to return (default 1)
|
||||
|
||||
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 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)
|
||||
--keychain-passphrase string passphrase for unlocking keychain
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
To download a copy of the ipa file, use the `download` command.
|
||||
|
||||
```
|
||||
Download (encrypted) iOS, iPadOS, tvOS, and visionOS app packages from the App Store
|
||||
|
||||
Usage:
|
||||
ipatool download [flags]
|
||||
|
||||
Flags:
|
||||
-i, --app-id int ID of the target app (required)
|
||||
-b, --bundle-identifier string The bundle identifier of the target app (overrides the app ID)
|
||||
--external-version-id string External version identifier of the target 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 (iOS), ipad (iPadOS), appletv (tvOS), or visionos
|
||||
--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.
|
||||
@@ -204,4 +100,4 @@ $ 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).
|
||||
+16
-26
@@ -1,17 +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/spf13/cobra"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
func authCmd() *cobra.Command {
|
||||
@@ -28,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{
|
||||
@@ -48,18 +32,28 @@ 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")
|
||||
@@ -69,10 +63,8 @@ func loginCmd() *cobra.Command {
|
||||
// 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)
|
||||
}
|
||||
@@ -119,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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
-33
@@ -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,15 +52,15 @@ 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,
|
||||
@@ -69,7 +68,7 @@ func newKeychain(machine machine.Machine, logger log.Logger, interactive bool) k
|
||||
},
|
||||
ServiceName: KeychainServiceName,
|
||||
KeychainTrustApplication: true,
|
||||
FileDir: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName),
|
||||
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")
|
||||
@@ -80,16 +79,11 @@ 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
|
||||
},
|
||||
}))
|
||||
@@ -107,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
|
||||
}
|
||||
+55
-24
@@ -13,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
|
||||
@@ -24,26 +29,31 @@ func downloadCmd() *cobra.Command {
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "download",
|
||||
Short: "Download (encrypted) iOS, iPadOS, tvOS, and visionOS 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) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
loginResult, err := store.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
@@ -54,30 +64,38 @@ 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 {
|
||||
if err != nil && (appID == 0 || !errors.Is(err, appstore.ErrAppNotFound)) {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
// Delisted apps may still be downloadable by their numeric ID.
|
||||
if err == nil {
|
||||
app = lookupResult.App
|
||||
}
|
||||
}
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrLicenseRequired) {
|
||||
err := dependencies.AppStore.Purchase(appstore.PurchaseInput{Account: acc, App: app})
|
||||
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
|
||||
}
|
||||
purchaseRequired = false
|
||||
purchased = true
|
||||
dependencies.Logger.Verbose().
|
||||
Bool("success", true).
|
||||
@@ -103,7 +121,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,
|
||||
@@ -115,8 +134,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
|
||||
}
|
||||
|
||||
@@ -150,11 +168,24 @@ func downloadCmd() *cobra.Command {
|
||||
}
|
||||
|
||||
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().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 app (defaults to latest version when not specified)")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to download for: iphone (iOS), ipad (iPadOS), appletv (tvOS), or visionos")
|
||||
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})
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
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(1))
|
||||
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(1))
|
||||
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))
|
||||
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),
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
f.loginInputs = append(f.loginInputs, input)
|
||||
|
||||
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)
|
||||
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
|
||||
}
|
||||
@@ -15,6 +15,7 @@ func getVersionMetadataCmd() *cobra.Command {
|
||||
appID int64
|
||||
bundleID string
|
||||
externalVersionID string
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
@@ -25,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
|
||||
|
||||
@@ -50,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
|
||||
}
|
||||
@@ -59,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
|
||||
@@ -89,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")
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
-7
@@ -12,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
|
||||
|
||||
@@ -49,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
|
||||
}
|
||||
@@ -57,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
|
||||
}
|
||||
@@ -83,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
|
||||
}
|
||||
@@ -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
@@ -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
|
||||
})
|
||||
}
|
||||
@@ -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}
|
||||
}
|
||||
@@ -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))
|
||||
})
|
||||
})
|
||||
+603
@@ -0,0 +1,603 @@
|
||||
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))
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
-9
@@ -11,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
|
||||
}
|
||||
@@ -29,7 +48,7 @@ func purchaseCmd() *cobra.Command {
|
||||
acc = infoResult.Account
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
loginResult, err := store.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
@@ -40,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
|
||||
}
|
||||
@@ -70,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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
+13
-4
@@ -14,6 +14,10 @@ import (
|
||||
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",
|
||||
@@ -29,7 +33,10 @@ func listPurchasesCmd() *cobra.Command {
|
||||
return fmt.Errorf("max results must not exceed %d", appstore.MaxOwnedAppsLimit)
|
||||
}
|
||||
|
||||
return nil
|
||||
var err error
|
||||
platform, err = appstore.ParsePlatform(platformValue)
|
||||
|
||||
return err
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
var lastErr error
|
||||
@@ -54,9 +61,10 @@ func listPurchasesCmd() *cobra.Command {
|
||||
}
|
||||
|
||||
output, err := dependencies.AppStore.OwnedApps(appstore.OwnedAppsInput{
|
||||
Account: acc,
|
||||
Page: page,
|
||||
Limit: maxResults,
|
||||
Account: acc,
|
||||
Page: page,
|
||||
Limit: maxResults,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -86,6 +94,7 @@ func listPurchasesCmd() *cobra.Command {
|
||||
|
||||
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
|
||||
}
|
||||
@@ -2,11 +2,43 @@ 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()
|
||||
|
||||
@@ -39,3 +71,18 @@ var _ = Describe("List Purchases command", func() {
|
||||
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
|
||||
}
|
||||
@@ -52,6 +52,7 @@ func rootCmd() *cobra.Command {
|
||||
cmd.AddCommand(searchCmd())
|
||||
cmd.AddCommand(ListVersionsCmd())
|
||||
cmd.AddCommand(getVersionMetadataCmd())
|
||||
cmd.AddCommand(mcpCmd())
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
+2
-2
@@ -14,7 +14,7 @@ func searchCmd() *cobra.Command {
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "search <term>",
|
||||
Short: "Search for iOS, iPadOS, tvOS, and visionOS 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()
|
||||
@@ -47,7 +47,7 @@ func searchCmd() *cobra.Command {
|
||||
}
|
||||
|
||||
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), or visionos")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to search: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,78 +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.6
|
||||
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
|
||||
howett.net/ranger v0.0.0-20171016084633-e2e137620847
|
||||
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/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-keychain v0.0.0-20191008050251-8e49817e8af4 // 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/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.26 // 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/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.5 // 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.15 // 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
|
||||
go4.org v0.0.0-20260112195520-a5071408f32f // indirect
|
||||
golang.org/x/crypto v0.52.0 // 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
|
||||
|
||||
@@ -4,14 +4,27 @@ 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=
|
||||
@@ -26,13 +39,21 @@ 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=
|
||||
@@ -41,8 +62,16 @@ github.com/ebitengine/purego v0.10.2 h1:W809HbnvzAxgdm+aOvlSekrM16wGCdT/e76+9tS7
|
||||
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/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=
|
||||
@@ -50,77 +79,119 @@ github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJA
|
||||
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/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
|
||||
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
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.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=
|
||||
github.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||
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/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.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/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=
|
||||
@@ -129,6 +200,8 @@ github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpE
|
||||
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=
|
||||
@@ -140,59 +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.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
|
||||
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
|
||||
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=
|
||||
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.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
|
||||
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
|
||||
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/ranger v0.0.0-20171016084633-e2e137620847 h1:jHX+2Sv8rQNb1nG2G9pcQLdVoWXBLW5fcd2gnfHluCU=
|
||||
howett.net/ranger v0.0.0-20171016084633-e2e137620847/go.mod h1:ZWGIG4mR6Ck+CdmFqK2/jox5vO2OAS8Qpb33HB8z0og=
|
||||
howett.net/plist v1.0.1 h1:37GdZ8tP09Q35o9ych3ehygcsL+HqKSwzctveSlarvM=
|
||||
howett.net/plist v1.0.1/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g=
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,864 @@
|
||||
//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"
|
||||
)
|
||||
|
||||
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.extractFile(ctx, path, destination); 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) extractFile(ctx context.Context, path, destination string) (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)
|
||||
}
|
||||
}()
|
||||
|
||||
reader := &contextReader{ctx: ctx, reader: io.NewSectionReader(file, 0, file.size)}
|
||||
if _, err := io.CopyN(output, reader, file.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.
|
||||
}
|
||||
+62
-152
@@ -1,8 +1,6 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/bzip2"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
@@ -10,67 +8,82 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/blacktop/go-macho/pkg/xar"
|
||||
"howett.net/ranger"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/cpio"
|
||||
)
|
||||
|
||||
const (
|
||||
updateURL = "https://swcdn.apple.com/content/downloads/27/34/041-98128-A_SYPWICN3KH/5dqkl4rqgbsr18yzy61yeie9g3cmjc5hiv/OSXUpd10.9.pkg"
|
||||
payloadName = "Payload"
|
||||
payloadBZOffset = int64(0x352F40D5)
|
||||
payloadCPIO = int64(0x3A4)
|
||||
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-v4"
|
||||
)
|
||||
|
||||
type Bundle struct {
|
||||
CommerceKit []byte
|
||||
CommerceCore []byte
|
||||
CoreFP []byte
|
||||
CoreFPICXS []byte
|
||||
AppleMediaServices []byte
|
||||
Commerce []byte
|
||||
ADID []byte
|
||||
CoreFP []byte
|
||||
CoreFPICXS []byte
|
||||
FairPlayD []byte
|
||||
FairPlayKext []byte
|
||||
}
|
||||
|
||||
type fileSpec struct {
|
||||
name string
|
||||
path string
|
||||
size int
|
||||
digest [32]byte
|
||||
}
|
||||
|
||||
var requiredFiles = []fileSpec{
|
||||
{
|
||||
name: "CommerceKit",
|
||||
path: "./System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/CommerceKit",
|
||||
size: 3271840,
|
||||
digest: mustDigest("b84ff12c21987856c0a17b78f1ad82b73195a6dec5f3b208a17d245555a2c8a2"),
|
||||
name: "AppleMediaServices",
|
||||
size: 14813888,
|
||||
digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4"),
|
||||
},
|
||||
{
|
||||
name: "CommerceCore",
|
||||
path: "./System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/Frameworks/CommerceCore.framework/Versions/A/CommerceCore",
|
||||
size: 207744,
|
||||
digest: mustDigest("c5401e57402230f3c876409d295319ddf1e61287bc882683c5d61277be7bc1f2"),
|
||||
name: "commerce",
|
||||
size: 8092640,
|
||||
digest: mustDigest("76de40a4a32f691947cb926ce3b128d2fc446f7cac9755f831c406cf5a316ac9"),
|
||||
},
|
||||
{
|
||||
name: "adid",
|
||||
size: 9797952,
|
||||
digest: mustDigest("1fec225b6917206e3d9b00fe636c04878f82bfd06a87a4b6941711de60efab5b"),
|
||||
},
|
||||
{
|
||||
name: "CoreFP",
|
||||
path: "./System/Library/PrivateFrameworks/CoreFP.framework/Versions/A/CoreFP",
|
||||
size: 29014912,
|
||||
digest: mustDigest("f19141336be4198d0f8991bb00017c915efc7aeaece36c345f7faa1237ea6074"),
|
||||
size: 94842464,
|
||||
digest: mustDigest("2c30fa2b5f695fd66c0360dce72f54757d03ddb7107549715c12cb359a003b46"),
|
||||
},
|
||||
{
|
||||
name: "CoreFP.icxs",
|
||||
path: "./System/Library/PrivateFrameworks/CoreFP.framework/Versions/A/CoreFP.icxs",
|
||||
size: 5288352,
|
||||
digest: mustDigest("473e78af86979f5bd4f6269561caf770b3d16c098d918846eeac8cdd2fe6566a"),
|
||||
size: 7365344,
|
||||
digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b"),
|
||||
},
|
||||
{
|
||||
name: "fairplayd",
|
||||
size: 37689264,
|
||||
digest: mustDigest("28b4c7b2a5a0409c5020da55fc3984713a8e2b0eec8557076c8717f7166d003e"),
|
||||
},
|
||||
{
|
||||
name: "FairPlayIOKit",
|
||||
size: 2132320,
|
||||
digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025"),
|
||||
},
|
||||
}
|
||||
|
||||
// Load resolves and caches the pinned macOS framework profile used by SAP,
|
||||
// kbsync generation, and package decryption.
|
||||
func 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)
|
||||
}
|
||||
|
||||
directory, err := cacheDirectory()
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
@@ -80,7 +93,7 @@ func Load(ctx context.Context) (Bundle, error) {
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
bundle, err := download(ctx)
|
||||
bundle, err := resolveRemoteImage(ctx)
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
@@ -92,108 +105,13 @@ func Load(ctx context.Context) (Bundle, error) {
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func download(ctx context.Context) (Bundle, error) {
|
||||
parsed, err := url.Parse(updateURL)
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("parse Apple software update URL: %w", err)
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: 2 * time.Minute,
|
||||
Transport: contextTransport{ctx: ctx, next: http.DefaultTransport},
|
||||
}
|
||||
|
||||
remote, err := ranger.NewReader(&ranger.HTTPRanger{Client: client, URL: parsed})
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("open Apple software update: %w", err)
|
||||
}
|
||||
|
||||
length, err := remote.Length()
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("measure Apple software update: %w", err)
|
||||
}
|
||||
|
||||
container, err := xar.NewReader(remote, length)
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read Apple software update: %w", err)
|
||||
}
|
||||
|
||||
var payload *xar.File
|
||||
|
||||
for _, candidate := range container.Files {
|
||||
if candidate.Name == payloadName {
|
||||
payload = candidate
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if payload == nil {
|
||||
return Bundle{}, &fs.PathError{Op: "open", Path: payloadName, Err: fs.ErrNotExist}
|
||||
}
|
||||
|
||||
raw := payload.OpenRaw()
|
||||
if _, err := raw.Seek(payloadBZOffset, io.SeekStart); err != nil {
|
||||
return Bundle{}, fmt.Errorf("seek Apple update payload: %w", err)
|
||||
}
|
||||
|
||||
compressed := io.MultiReader(bytes.NewReader([]byte{'B', 'Z', 'h', '9'}), raw)
|
||||
|
||||
archive := bzip2.NewReader(compressed)
|
||||
if _, err := io.CopyN(io.Discard, archive, payloadCPIO); err != nil {
|
||||
return Bundle{}, fmt.Errorf("seek Apple payload archive: %w", err)
|
||||
}
|
||||
|
||||
wanted := make(map[string]fileSpec, len(requiredFiles))
|
||||
for _, spec := range requiredFiles {
|
||||
wanted[spec.path] = spec
|
||||
}
|
||||
|
||||
found := make(map[string][]byte, len(requiredFiles))
|
||||
reader := cpio.NewReader(archive)
|
||||
|
||||
for len(found) != len(wanted) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Bundle{}, fmt.Errorf("download Apple SAP assets: %w", err)
|
||||
}
|
||||
|
||||
path, body, err := reader.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read Apple payload archive: %w", err)
|
||||
}
|
||||
|
||||
spec, ok := wanted[path]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(io.LimitReader(body, int64(spec.size)+1))
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read %s: %w", spec.name, err)
|
||||
}
|
||||
|
||||
found[spec.name] = data
|
||||
}
|
||||
|
||||
bundle := bundleFrom(found)
|
||||
if err := validate(bundle); err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
return bundle, 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", "apple-assets-v2"), nil
|
||||
return filepath.Join(root, "ipatool", "sap", assetCacheDirectory), nil
|
||||
}
|
||||
|
||||
func readCache(directory string) (Bundle, error) {
|
||||
@@ -329,19 +247,25 @@ func validate(bundle Bundle) error {
|
||||
|
||||
func bundleFrom(files map[string][]byte) Bundle {
|
||||
return Bundle{
|
||||
CommerceKit: files["CommerceKit"],
|
||||
CommerceCore: files["CommerceCore"],
|
||||
CoreFP: files["CoreFP"],
|
||||
CoreFPICXS: files["CoreFP.icxs"],
|
||||
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{
|
||||
"CommerceKit": bundle.CommerceKit,
|
||||
"CommerceCore": bundle.CommerceCore,
|
||||
"CoreFP": bundle.CoreFP,
|
||||
"CoreFP.icxs": bundle.CoreFPICXS,
|
||||
"AppleMediaServices": bundle.AppleMediaServices,
|
||||
"commerce": bundle.Commerce,
|
||||
"adid": bundle.ADID,
|
||||
"CoreFP": bundle.CoreFP,
|
||||
"CoreFP.icxs": bundle.CoreFPICXS,
|
||||
"fairplayd": bundle.FairPlayD,
|
||||
"FairPlayIOKit": bundle.FairPlayKext,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,17 +285,3 @@ func mustDigest(value string) [32]byte {
|
||||
|
||||
return digest
|
||||
}
|
||||
|
||||
type contextTransport struct {
|
||||
ctx context.Context
|
||||
next http.RoundTripper
|
||||
}
|
||||
|
||||
func (t contextTransport) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
response, err := t.next.RoundTrip(request.Clone(t.ctx))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetch Apple software update: %w", err)
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,163 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const remoteReadAttempts = 3
|
||||
|
||||
type remoteFile struct {
|
||||
ctx context.Context
|
||||
client *http.Client
|
||||
url string
|
||||
size 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("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)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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("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)
|
||||
}
|
||||
|
||||
if wanted != len(data) {
|
||||
return total, io.EOF
|
||||
}
|
||||
|
||||
return total, nil
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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()) })
|
||||
})
|
||||
@@ -0,0 +1,180 @@
|
||||
//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 := bundleFrom(files)
|
||||
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
|
||||
}
|
||||
@@ -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")))
|
||||
})
|
||||
})
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
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("pins every runtime artifact by size and digest", func() {
|
||||
Expect(requiredFiles).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 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")))
|
||||
})
|
||||
})
|
||||
@@ -1,86 +0,0 @@
|
||||
// Package cpio reads the old portable ASCII CPIO format used by Apple's
|
||||
// software-update payload. It streams entry bodies so unrelated files are not
|
||||
// retained while locating the small set needed by the SAP emulator.
|
||||
package cpio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
const (
|
||||
headerSize = 76
|
||||
nameSizeOffset = 59
|
||||
fileSizeOffset = 65
|
||||
)
|
||||
|
||||
var (
|
||||
headerMagic = []byte("070707")
|
||||
trailerName = []byte("TRAILER!!!")
|
||||
)
|
||||
|
||||
type Reader struct {
|
||||
source io.Reader
|
||||
current *io.LimitedReader
|
||||
}
|
||||
|
||||
func NewReader(source io.Reader) *Reader {
|
||||
return &Reader{source: source}
|
||||
}
|
||||
|
||||
func (r *Reader) Next() (string, io.Reader, error) {
|
||||
if r.current != nil {
|
||||
if _, err := io.Copy(io.Discard, r.current); err != nil {
|
||||
return "", nil, fmt.Errorf("skip CPIO entry: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
header := make([]byte, headerSize)
|
||||
if _, err := io.ReadFull(r.source, header); err != nil {
|
||||
return "", nil, fmt.Errorf("read CPIO header: %w", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(header[:len(headerMagic)], headerMagic) {
|
||||
return "", nil, fmt.Errorf("invalid CPIO magic %q", header[:len(headerMagic)])
|
||||
}
|
||||
|
||||
nameSize, err := parseOctal(header[nameSizeOffset:fileSizeOffset])
|
||||
if err != nil || nameSize < 1 {
|
||||
return "", nil, fmt.Errorf("invalid CPIO name size %q", header[nameSizeOffset:fileSizeOffset])
|
||||
}
|
||||
|
||||
fileSize, err := parseOctal(header[fileSizeOffset:headerSize])
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("invalid CPIO file size %q", header[fileSizeOffset:headerSize])
|
||||
}
|
||||
|
||||
name := make([]byte, nameSize)
|
||||
if _, err := io.ReadFull(r.source, name); err != nil {
|
||||
return "", nil, fmt.Errorf("read CPIO name: %w", err)
|
||||
}
|
||||
|
||||
if name[len(name)-1] != 0 {
|
||||
return "", nil, errors.New("CPIO name is not NUL-terminated")
|
||||
}
|
||||
|
||||
name = name[:len(name)-1]
|
||||
if bytes.Equal(name, trailerName) {
|
||||
return "", nil, io.EOF
|
||||
}
|
||||
|
||||
r.current = &io.LimitedReader{R: r.source, N: int64(fileSize)}
|
||||
|
||||
return string(name), r.current, nil
|
||||
}
|
||||
|
||||
func parseOctal(value []byte) (uint64, error) {
|
||||
parsed, err := strconv.ParseUint(string(value), 8, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("parse CPIO octal value: %w", err)
|
||||
}
|
||||
|
||||
return parsed, nil
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package cpio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReaderStreamsEntries(t *testing.T) {
|
||||
archive := append(cpioEntry("first", []byte("ignored")), cpioEntry("second", []byte("wanted"))...)
|
||||
archive = append(archive, cpioEntry("TRAILER!!!", nil)...)
|
||||
reader := NewReader(bytes.NewReader(archive))
|
||||
|
||||
name, _, err := reader.Next()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if name != "first" {
|
||||
t.Fatalf("name = %q, want first", name)
|
||||
}
|
||||
|
||||
name, body, err := reader.Next()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if name != "second" || string(data) != "wanted" {
|
||||
t.Fatalf("entry = %q %q, want second wanted", name, data)
|
||||
}
|
||||
|
||||
if _, _, err := reader.Next(); err != io.EOF {
|
||||
t.Fatalf("trailer error = %v, want EOF", err)
|
||||
}
|
||||
}
|
||||
|
||||
func cpioEntry(name string, body []byte) []byte {
|
||||
nameBytes := append([]byte(name), 0)
|
||||
header := fmt.Sprintf(
|
||||
"070707%06o%06o%06o%06o%06o%06o%06o%011o%06o%011o",
|
||||
0, 0, 0, 0, 0, 1, 0, 0, len(nameBytes), len(body),
|
||||
)
|
||||
entry := append([]byte(header), nameBytes...)
|
||||
|
||||
return append(entry, body...)
|
||||
}
|
||||
+368
-25
@@ -6,8 +6,10 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
|
||||
"github.com/blacktop/go-macho"
|
||||
"github.com/blacktop/go-macho/pkg/fixupchains"
|
||||
"github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
@@ -38,12 +40,18 @@ type Image struct {
|
||||
segments []segment
|
||||
binds []types.Bind
|
||||
rebases []types.Rebase
|
||||
chained *fixupchains.DyldChainedFixups
|
||||
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 := amd64Slice(input)
|
||||
data, err := arm64Slice(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %s: %w", name, err)
|
||||
}
|
||||
@@ -53,8 +61,8 @@ func Open(name string, input []byte) (*Image, error) {
|
||||
return nil, fmt.Errorf("open %s Mach-O: %w", name, err)
|
||||
}
|
||||
|
||||
if file.CPU != types.CPUAmd64 {
|
||||
return nil, fmt.Errorf("open %s: expected x86-64 Mach-O, found %s", name, file.CPU)
|
||||
if file.CPU != types.CPUArm64 {
|
||||
return nil, fmt.Errorf("open %s: expected arm64 Mach-O, found %s", name, file.CPU)
|
||||
}
|
||||
|
||||
image := &Image{
|
||||
@@ -76,40 +84,119 @@ func Open(name string, input []byte) (*Image, error) {
|
||||
if err := image.validateSegments(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
image.binds, err = file.GetBindInfo()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s bindings: %w", name, err)
|
||||
if err := image.removePointerAuthentication(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
image.rebases, err = file.GetRebaseInfo()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s rebases: %w", name, 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)
|
||||
}
|
||||
}
|
||||
|
||||
return image, nil
|
||||
}
|
||||
|
||||
func amd64Slice(input []byte) ([]byte, error) {
|
||||
//nolint:wsl // Instruction decoding is clearer when related operations stay together.
|
||||
func (i *Image) removePointerAuthentication() error {
|
||||
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)
|
||||
}
|
||||
for offset := start; offset+4 <= end; offset += 4 {
|
||||
instruction := binary.LittleEndian.Uint32(i.data[offset:])
|
||||
replacement := WithoutPointerAuthentication(instruction)
|
||||
if replacement != instruction {
|
||||
binary.LittleEndian.PutUint32(i.data[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
|
||||
}
|
||||
|
||||
func arm64Slice(input []byte) ([]byte, error) {
|
||||
fat, err := macho.NewFatFile(bytes.NewReader(input))
|
||||
if err != nil {
|
||||
return bytes.Clone(input), nil
|
||||
}
|
||||
|
||||
for _, architecture := range fat.Arches {
|
||||
if architecture.CPU != types.CPUAmd64 {
|
||||
if architecture.CPU != types.CPUArm64 || architecture.SubCPU&types.CpuSubtypeMask != types.CPUSubtypeArm64E {
|
||||
continue
|
||||
}
|
||||
|
||||
end, overflow := add(uint64(architecture.Offset), uint64(architecture.Size))
|
||||
if overflow || end > uint64(len(input)) {
|
||||
return nil, errors.New("x86-64 slice exceeds input size")
|
||||
return nil, errors.New("arm64e slice exceeds input size")
|
||||
}
|
||||
|
||||
return bytes.Clone(input[architecture.Offset:end]), nil
|
||||
}
|
||||
|
||||
return nil, errors.New("universal binary has no x86-64 slice")
|
||||
return nil, errors.New("universal binary has no arm64e slice")
|
||||
}
|
||||
|
||||
func (i *Image) Export(name string, loadBase uint64) (uint64, error) {
|
||||
@@ -185,18 +272,249 @@ func (i *Image) Relocate(loadBase uint64, resolve func(string) (uint64, error))
|
||||
}
|
||||
}
|
||||
|
||||
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 := binary.LittleEndian.Uint64(i.data[offset : offset+pointerSize])
|
||||
|
||||
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) relocateChained(loadBase uint64, resolve func(string) (uint64, error)) error {
|
||||
if i.chained == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
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 fmt.Errorf("chained fixup at %#x exceeds %s", offset, i.name)
|
||||
}
|
||||
|
||||
var address uint64
|
||||
|
||||
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 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 fmt.Errorf("decode chained rebase at %#x in %s: %w", offset, i.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
var overflow bool
|
||||
|
||||
address, overflow = add(loadBase, target)
|
||||
if overflow {
|
||||
return fmt.Errorf("chained rebase at %#x with target %#x, image base %#x, load base %#x, format %s, and type %T overflows in %s", offset, target, i.base, loadBase, i.chained.PointerFormat, fixup, i.name)
|
||||
}
|
||||
case fixup.IsBind():
|
||||
binding, ok := fixup.(fixupchains.Bind)
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid chained bind at %#x in %s", offset, i.name)
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
address, err = resolve(binding.Name())
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve %s for %s: %w", binding.Name(), i.name, err)
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
address, err = addSigned(address, addend)
|
||||
if err != nil {
|
||||
return fmt.Errorf("apply chained addend for %s in %s: %w", binding.Name(), i.name, err)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unknown chained fixup at %#x in %s", offset, i.name)
|
||||
}
|
||||
|
||||
if err := i.putPointer(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
|
||||
}
|
||||
|
||||
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 := binary.LittleEndian.Uint64(i.data[offset : offset+pointerSize])
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
var span uint64
|
||||
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 {
|
||||
@@ -207,25 +525,50 @@ func (i *Image) Load(memory Memory) error {
|
||||
return fmt.Errorf("segment %s in %s precedes image base", item.name, i.name)
|
||||
}
|
||||
|
||||
end, overflow := add(item.address-i.base, item.size)
|
||||
if overflow || end > maxImageSpan {
|
||||
return fmt.Errorf("segment %s makes %s too large", 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)
|
||||
}
|
||||
|
||||
span = max(span, end)
|
||||
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)})
|
||||
}
|
||||
|
||||
span = align(span, pageSize)
|
||||
if span == 0 {
|
||||
if len(ranges) == 0 {
|
||||
return fmt.Errorf("%s has no loadable segments", i.name)
|
||||
}
|
||||
|
||||
if _, overflow := add(i.loadedBase, span); overflow {
|
||||
return fmt.Errorf("load range for %s overflows", 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)
|
||||
}
|
||||
|
||||
if err := memory.MemMap(i.loadedBase, span); err != nil {
|
||||
return fmt.Errorf("map %s: %w", i.name, err)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
for _, item := range i.segments {
|
||||
|
||||
@@ -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"))
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"),
|
||||
)
|
||||
})
|
||||
+215
-78
@@ -18,8 +18,6 @@ const sapGuestTimeout = time.Minute
|
||||
const (
|
||||
returnAddress = uint64(0x0000000100000000)
|
||||
coreFPBase = uint64(0x0000100000000000)
|
||||
commerceBase = uint64(0x0000100040000000)
|
||||
kitBase = uint64(0x0000100080000000)
|
||||
scratchBase = uint64(0x0000300000000000)
|
||||
scratchSize = uint64(32 << 20)
|
||||
heapBase = uint64(0x0000400000000000)
|
||||
@@ -50,85 +48,118 @@ type entryPoints struct {
|
||||
|
||||
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, errors.New("SAP runtime context is nil")
|
||||
return nil, nil, errors.New("SAP runtime context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("open SAP runtime: %w", err)
|
||||
return nil, nil, fmt.Errorf("open SAP runtime: %w", err)
|
||||
}
|
||||
|
||||
coreFP, err := machimage.Open("CoreFP", bundle.CoreFP)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open CoreFP image: %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...)
|
||||
|
||||
commerceCore, err := machimage.Open("CommerceCore", bundle.CommerceCore)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open CommerceCore image: %w", err)
|
||||
}
|
||||
images := make(map[string]*machimage.Image, len(imageSpecs))
|
||||
|
||||
commerceKit, err := machimage.Open("CommerceKit", bundle.CommerceKit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open CommerceKit image: %w", err)
|
||||
for _, spec := range imageSpecs {
|
||||
image, err := machimage.Open(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, fmt.Errorf("resolve CoreFP export %s: %w", name, err)
|
||||
return nil, nil, fmt.Errorf("resolve CoreFP export %s: %w", name, err)
|
||||
}
|
||||
|
||||
exports[name] = address
|
||||
coreExports[name] = address
|
||||
}
|
||||
|
||||
macAddress, err := commerceCore.Export("_get_mac_address", commerceBase)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve CommerceCore MAC address export: %w", err)
|
||||
}
|
||||
|
||||
exports["_get_mac_address"] = macAddress
|
||||
|
||||
entryNames := []string{
|
||||
appleMediaServices := images["AppleMediaServices"]
|
||||
for _, name := range []string{
|
||||
"_cp2g1b9ro",
|
||||
"_Mib5yocT",
|
||||
"_Fc3vhtJDvr",
|
||||
"_IPaI1oem5iL",
|
||||
"_jEHf8Xzsv8K",
|
||||
}
|
||||
resolvedEntries := make(map[string]uint64, len(entryNames))
|
||||
|
||||
for _, name := range entryNames {
|
||||
address, err := commerceKit.Export(name, kitBase)
|
||||
} {
|
||||
address, err := appleMediaServices.Export(name, appleMediaServices.Base())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve CommerceKit export %s: %w", name, err)
|
||||
return nil, nil, fmt.Errorf("resolve AppleMediaServices export %s: %w", name, err)
|
||||
}
|
||||
|
||||
exports[name] = address
|
||||
resolvedEntries[name] = address
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("open SAP runtime: %w", err)
|
||||
return nil, nil, fmt.Errorf("open SAP runtime: %w", err)
|
||||
}
|
||||
|
||||
engine, err := unicorn.New(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create Unicorn engine: %w", err)
|
||||
return nil, nil, fmt.Errorf("create Unicorn engine: %w", err)
|
||||
}
|
||||
|
||||
machine := &Machine{engine: engine}
|
||||
machine := &Machine{engine: engine, arm64: newARM64Compatibility(engine)}
|
||||
ready := false
|
||||
|
||||
defer func() {
|
||||
@@ -147,17 +178,17 @@ func Open(ctx context.Context, bundle assets.Bundle) (*Machine, error) {
|
||||
{stackBase, stackSize},
|
||||
} {
|
||||
if err := engine.MemMap(region.address, region.size); err != nil {
|
||||
return nil, fmt.Errorf("map SAP guest memory at %#x: %w", region.address, err)
|
||||
return nil, nil, fmt.Errorf("map SAP guest memory at %#x: %w", region.address, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := engine.MemWrite(returnAddress, []byte{0xF4}); err != nil {
|
||||
return nil, fmt.Errorf("write SAP guest return instruction: %w", 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 = newShims(engine, coreExports, bundle.CoreFPICXS)
|
||||
machine.services, err = newShimsWithOptions(engine, coreExports, bundle.CoreFPICXS, options.shims)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
resolver := func(name string) (uint64, error) {
|
||||
@@ -167,33 +198,109 @@ func Open(ctx context.Context, bundle assets.Bundle) (*Machine, error) {
|
||||
|
||||
return machine.services.resolve(name)
|
||||
}
|
||||
for _, item := range []struct {
|
||||
image *machimage.Image
|
||||
base uint64
|
||||
}{
|
||||
{coreFP, coreFPBase},
|
||||
{commerceCore, commerceBase},
|
||||
{commerceKit, kitBase},
|
||||
} {
|
||||
if err := item.image.Relocate(item.base, resolver); err != nil {
|
||||
return nil, fmt.Errorf("relocate SAP guest image: %w", err)
|
||||
|
||||
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 := item.image.Load(engine); err != nil {
|
||||
return nil, fmt.Errorf("load SAP guest image: %w", err)
|
||||
if err := loadPrelinkedFunctions(engine, spec.functions, resolver); err != nil {
|
||||
return nil, nil, fmt.Errorf("load %s shared-cache functions: %w", spec.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
machine.entry = entryPoints{
|
||||
initialize: resolvedEntries["_cp2g1b9ro"],
|
||||
exchange: resolvedEntries["_Mib5yocT"],
|
||||
sign: resolvedEntries["_Fc3vhtJDvr"],
|
||||
teardown: resolvedEntries["_IPaI1oem5iL"],
|
||||
dispose: resolvedEntries["_jEHf8Xzsv8K"],
|
||||
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, nil
|
||||
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) {
|
||||
@@ -382,6 +489,7 @@ func (m *Machine) dispose(output uint64) error {
|
||||
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")
|
||||
@@ -392,12 +500,14 @@ func (m *Machine) invoke(function uint64, arguments ...uint64) (uint64, error) {
|
||||
}
|
||||
|
||||
registers := [...]int{
|
||||
unicorn.RegRDI,
|
||||
unicorn.RegRSI,
|
||||
unicorn.RegRDX,
|
||||
unicorn.RegRCX,
|
||||
unicorn.RegR8,
|
||||
unicorn.RegR9,
|
||||
unicorn.RegX0,
|
||||
unicorn.RegX1,
|
||||
unicorn.RegX2,
|
||||
unicorn.RegX3,
|
||||
unicorn.RegX4,
|
||||
unicorn.RegX5,
|
||||
unicorn.RegX6,
|
||||
unicorn.RegX7,
|
||||
}
|
||||
for index, register := range registers {
|
||||
var value uint64
|
||||
@@ -412,43 +522,70 @@ func (m *Machine) invoke(function uint64, arguments ...uint64) (uint64, error) {
|
||||
|
||||
extra := max(len(arguments)-len(registers), 0)
|
||||
|
||||
stackPointer := stackEnd - uint64(extra+1)*8
|
||||
if stackPointer%16 != 8 {
|
||||
stackPointer -= 8
|
||||
}
|
||||
|
||||
if err := m.writeUint64(stackPointer, returnAddress); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
stackPointer := stackEnd - uint64(extra)*8
|
||||
stackPointer -= stackPointer % 16
|
||||
|
||||
for index := range extra {
|
||||
if err := m.writeUint64(stackPointer+8+uint64(index)*8, arguments[len(registers)+index]); err != nil {
|
||||
if err := m.writeUint64(stackPointer+uint64(index)*8, arguments[len(registers)+index]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := m.engine.RegWrite(unicorn.RegRSP, stackPointer); err != nil {
|
||||
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.
|
||||
if err := m.engine.StartBounded(function, returnAddress, sapGuestTimeout, 0); err != nil {
|
||||
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
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("execute SAP guest function: %w", err)
|
||||
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.RegRIP)
|
||||
instruction, err := m.engine.RegRead(unicorn.RegPC)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read SAP guest instruction register: %w", err)
|
||||
}
|
||||
@@ -457,7 +594,7 @@ func (m *Machine) invoke(function uint64, arguments ...uint64) (uint64, error) {
|
||||
return 0, fmt.Errorf("SAP guest stopped unexpectedly at %#x", instruction)
|
||||
}
|
||||
|
||||
result, err := m.engine.RegRead(unicorn.RegRAX)
|
||||
result, err := m.engine.RegRead(unicorn.RegX0)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read SAP guest result register: %w", err)
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
@@ -294,7 +294,7 @@ func newServiceTestMachine(t *testing.T) *Machine {
|
||||
}
|
||||
}
|
||||
|
||||
if err := engine.MemWrite(returnAddress, []byte{0xF4}); err != nil {
|
||||
if err := engine.MemWrite(returnAddress, []byte{0x00, 0x00, 0x20, 0xd4}); err != nil {
|
||||
_ = engine.Close()
|
||||
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -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",
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -15,12 +15,21 @@ func (s *shims) registerMemoryServices() error {
|
||||
names []string
|
||||
handler shimHandler
|
||||
}{
|
||||
{[]string{"_malloc"}, s.malloc},
|
||||
{[]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"}, s.free},
|
||||
{[]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},
|
||||
@@ -30,6 +39,7 @@ func (s *shims) registerMemoryServices() error {
|
||||
{[]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 {
|
||||
@@ -54,6 +64,90 @@ func (s *shims) malloc() error {
|
||||
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 {
|
||||
@@ -218,6 +312,102 @@ func (s *shims) allocate(size uint64) (uint64, error) {
|
||||
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 {
|
||||
@@ -514,3 +704,36 @@ func (s *shims) strlen() error {
|
||||
|
||||
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)))
|
||||
})
|
||||
})
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
shimBase = uint64(0x0000200000000000)
|
||||
shimBase = uint64(0x00007ff880000000)
|
||||
shimCodeSize = uint64(0x0000000000080000)
|
||||
shimSize = uint64(0x0000000000100000)
|
||||
shimSlotSize = uint64(16)
|
||||
@@ -33,39 +33,81 @@ type freeBlock struct {
|
||||
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
|
||||
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),
|
||||
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
|
||||
}
|
||||
@@ -74,6 +116,10 @@ func newShims(engine *unicorn.Engine, coreExports map[string]uint64, icxs []byte
|
||||
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)
|
||||
@@ -131,7 +177,7 @@ func (s *shims) addFunction(name string, handler shimHandler) (uint64, error) {
|
||||
address := s.codeCursor
|
||||
s.codeCursor += shimSlotSize
|
||||
|
||||
if err := s.engine.MemWrite(address, []byte{0xC3}); err != nil {
|
||||
if err := s.engine.MemWrite(address, []byte{0xc0, 0x03, 0x5f, 0xd6}); err != nil {
|
||||
return 0, fmt.Errorf("write guest service stub: %w", err)
|
||||
}
|
||||
|
||||
@@ -192,12 +238,14 @@ func (s *shims) resetFault() {
|
||||
|
||||
func (s *shims) argument(index int) (uint64, error) {
|
||||
registers := [...]int{
|
||||
unicorn.RegRDI,
|
||||
unicorn.RegRSI,
|
||||
unicorn.RegRDX,
|
||||
unicorn.RegRCX,
|
||||
unicorn.RegR8,
|
||||
unicorn.RegR9,
|
||||
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])
|
||||
@@ -212,12 +260,12 @@ func (s *shims) argument(index int) (uint64, error) {
|
||||
return 0, errors.New("negative guest argument index")
|
||||
}
|
||||
|
||||
stack, err := s.engine.RegRead(unicorn.RegRSP)
|
||||
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+8+uint64(index-len(registers))*8, 8)
|
||||
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)
|
||||
}
|
||||
@@ -226,7 +274,7 @@ func (s *shims) argument(index int) (uint64, error) {
|
||||
}
|
||||
|
||||
func (s *shims) setResult(value uint64) error {
|
||||
if err := s.engine.RegWrite(unicorn.RegRAX, value); err != nil {
|
||||
if err := s.engine.RegWrite(unicorn.RegX0, value); err != nil {
|
||||
return fmt.Errorf("write guest result register: %w", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -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...)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -20,7 +20,9 @@ const (
|
||||
)
|
||||
|
||||
type setupProtocol struct {
|
||||
client *http.Client
|
||||
client interface {
|
||||
Do(*http.Request) (*http.Response, error)
|
||||
}
|
||||
}
|
||||
|
||||
func (p setupProtocol) certificate(ctx context.Context, endpoint string) ([]byte, error) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package sap
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
@@ -11,6 +12,9 @@ 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
|
||||
|
||||
@@ -1,47 +1,55 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestSignerIntegration(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
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},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Cleanup(func() {
|
||||
if err := signer.Close(); err != nil {
|
||||
t.Errorf("close signer: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
signature, err := signer.Sign([]byte("ipatool SAP smoke test"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(signature) == 0 {
|
||||
t.Fatal("signature is empty")
|
||||
}
|
||||
|
||||
second, err := signer.Sign([]byte("ipatool second SAP smoke test"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(second) == 0 || bytes.Equal(signature, second) {
|
||||
t.Fatal("second signature is empty or unexpectedly reused")
|
||||
}
|
||||
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))
|
||||
})
|
||||
})
|
||||
@@ -61,6 +61,9 @@ func NewSigner(ctx context.Context, config Config) (ActionSigner, error) {
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"debug/elf"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -10,61 +12,57 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"time"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const maxArtifactSize = 64 << 20
|
||||
|
||||
var artifactHTTPClient = &http.Client{Timeout: 2 * time.Minute}
|
||||
|
||||
type runtimePaths struct {
|
||||
library string
|
||||
dependencies []string
|
||||
func linuxUsesMusl() bool {
|
||||
return linuxUsesMuslFor("/proc/self/exe", muslLoaderInstalled)
|
||||
}
|
||||
|
||||
func cachedRuntimePaths(ctx context.Context) (runtimePaths, error) {
|
||||
goos := runtime.GOOS
|
||||
if goos == "linux" && linuxUsesMusl() {
|
||||
goos = "linux-musl"
|
||||
func linuxUsesMuslFor(executable string, loaderInstalled func() bool) bool {
|
||||
if interpreter, ok := executableInterpreter(executable); ok {
|
||||
return interpreterUsesMusl(interpreter)
|
||||
}
|
||||
|
||||
selected, err := artifactFor(goos, runtime.GOARCH)
|
||||
return loaderInstalled()
|
||||
}
|
||||
|
||||
// executableInterpreter reads the loader recorded in the executable. Missing PT_INTERP or
|
||||
// an unreadable executable leaves the caller to fall back to the host filesystem heuristic.
|
||||
func executableInterpreter(path string) (string, bool) {
|
||||
file, err := elf.Open(path)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
return "", false
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
cache, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return runtimePaths{}, fmt.Errorf("locate user cache: %w", err)
|
||||
}
|
||||
|
||||
root := filepath.Join(cache, "ipatool", "unicorn", unicornVersion)
|
||||
paths := runtimePaths{dependencies: make([]string, 0, len(selected.dependencies))}
|
||||
|
||||
for _, dependency := range selected.dependencies {
|
||||
path, err := ensureLibrary(ctx, root, dependency, artifactHTTPClient)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
for _, program := range file.Progs {
|
||||
if program.Type != elf.PT_INTERP {
|
||||
continue
|
||||
}
|
||||
|
||||
paths.dependencies = append(paths.dependencies, path)
|
||||
interpreter, err := io.ReadAll(program.Open())
|
||||
if err != nil || uint64(len(interpreter)) != program.Filesz {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return string(bytes.TrimRight(interpreter, "\x00")), true
|
||||
}
|
||||
|
||||
paths.library, err = ensureLibrary(ctx, root, selected, artifactHTTPClient)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
paths.library, err = prepareRuntimeLibrary(paths.library)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
return paths, nil
|
||||
return "", false
|
||||
}
|
||||
|
||||
func linuxUsesMusl() bool {
|
||||
func interpreterUsesMusl(interpreter string) bool {
|
||||
return strings.HasPrefix(filepath.Base(interpreter), "ld-musl-")
|
||||
}
|
||||
|
||||
// muslLoaderInstalled reports whether a musl loader exists on the host. That only says musl is
|
||||
// available, not that this process uses it, so it is a last resort when the interpreter is
|
||||
// unavailable. glibc distributions package musl for cross compilation, and selecting the
|
||||
// musllinux artifact there loads a second libc into the process.
|
||||
func muslLoaderInstalled() bool {
|
||||
loaders, _ := filepath.Glob("/lib/ld-musl-*.so.1")
|
||||
if len(loaders) != 0 {
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"debug/elf"
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestLibcDetection(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Unicorn Libc Detection Suite")
|
||||
}
|
||||
|
||||
var _ = Describe("Linux libc detection", func() {
|
||||
DescribeTable("classifies interpreter names", func(interpreter string, expected bool) {
|
||||
Expect(interpreterUsesMusl(interpreter)).To(Equal(expected))
|
||||
},
|
||||
Entry("musl amd64", "/lib/ld-musl-x86_64.so.1", true),
|
||||
Entry("musl arm64", "/lib/ld-musl-aarch64.so.1", true),
|
||||
Entry("glibc amd64", "/lib64/ld-linux-x86-64.so.2", false),
|
||||
Entry("glibc arm64", "/lib/ld-linux-aarch64.so.1", false),
|
||||
Entry("glibc under usr", "/usr/lib/ld-linux-x86-64.so.2", false),
|
||||
Entry("empty", "", false),
|
||||
)
|
||||
|
||||
DescribeTable("prefers the executable over installed loaders", func(interpreter string, installed, expected bool) {
|
||||
path := filepath.Join(GinkgoT().TempDir(), "exe")
|
||||
Expect(os.WriteFile(path, libcTestELF(interpreter), 0o600)).To(Succeed())
|
||||
|
||||
actual, ok := executableInterpreter(path)
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(actual).To(Equal(interpreter))
|
||||
|
||||
fallbackCalled := false
|
||||
Expect(linuxUsesMuslFor(path, func() bool {
|
||||
fallbackCalled = true
|
||||
|
||||
return installed
|
||||
})).To(Equal(expected))
|
||||
Expect(fallbackCalled).To(BeFalse())
|
||||
},
|
||||
Entry("glibc with musl installed", "/lib64/ld-linux-x86-64.so.2", true, false),
|
||||
Entry("glibc arm64 with musl installed", "/lib/ld-linux-aarch64.so.1", true, false),
|
||||
Entry("musl without a standard loader path", "/custom/ld-musl-x86_64.so.1", false, true),
|
||||
Entry("musl arm64", "/lib/ld-musl-aarch64.so.1", true, true),
|
||||
)
|
||||
|
||||
DescribeTable("falls back when the interpreter is unavailable", func(kind string) {
|
||||
path := filepath.Join(GinkgoT().TempDir(), "exe")
|
||||
switch kind {
|
||||
case "static":
|
||||
Expect(os.WriteFile(path, libcTestELF(""), 0o600)).To(Succeed())
|
||||
case "invalid":
|
||||
Expect(os.WriteFile(path, []byte("not an ELF executable"), 0o600)).To(Succeed())
|
||||
case "truncated":
|
||||
data := libcTestELF("/lib/ld-musl-x86_64.so.1")
|
||||
Expect(os.WriteFile(path, data[:len(data)-4], 0o600)).To(Succeed())
|
||||
}
|
||||
|
||||
interpreter, ok := executableInterpreter(path)
|
||||
Expect(ok).To(BeFalse())
|
||||
Expect(interpreter).To(BeEmpty())
|
||||
for _, installed := range []bool{false, true} {
|
||||
fallbackCalled := false
|
||||
Expect(linuxUsesMuslFor(path, func() bool {
|
||||
fallbackCalled = true
|
||||
|
||||
return installed
|
||||
})).To(Equal(installed))
|
||||
Expect(fallbackCalled).To(BeTrue())
|
||||
}
|
||||
},
|
||||
Entry("no PT_INTERP", "static"),
|
||||
Entry("executable cannot be opened", "missing"),
|
||||
Entry("invalid ELF", "invalid"),
|
||||
Entry("interpreter cannot be read", "truncated"),
|
||||
)
|
||||
|
||||
It("reads the running Linux executable", func() {
|
||||
if runtime.GOOS != "linux" {
|
||||
Skip("/proc/self/exe is Linux-specific")
|
||||
}
|
||||
interpreter, ok := executableInterpreter("/proc/self/exe")
|
||||
if !ok {
|
||||
Skip("running executable has no readable PT_INTERP")
|
||||
}
|
||||
Expect(filepath.IsAbs(interpreter)).To(BeTrue())
|
||||
Expect(linuxUsesMusl()).To(Equal(interpreterUsesMusl(interpreter)))
|
||||
})
|
||||
})
|
||||
|
||||
// libcTestELF builds an ELF64 executable with one program header. An empty
|
||||
// interpreter uses PT_NULL to model a static executable without PT_INTERP.
|
||||
func libcTestELF(interpreter string) []byte {
|
||||
const headerSize, programSize = 64, 56
|
||||
data := make([]byte, headerSize+programSize)
|
||||
copy(data, "\x7fELF")
|
||||
data[elf.EI_CLASS] = byte(elf.ELFCLASS64)
|
||||
data[elf.EI_DATA] = byte(elf.ELFDATA2LSB)
|
||||
data[elf.EI_VERSION] = byte(elf.EV_CURRENT)
|
||||
binary.LittleEndian.PutUint16(data[16:], uint16(elf.ET_EXEC))
|
||||
binary.LittleEndian.PutUint16(data[18:], uint16(elf.EM_X86_64))
|
||||
binary.LittleEndian.PutUint32(data[20:], uint32(elf.EV_CURRENT))
|
||||
binary.LittleEndian.PutUint64(data[32:], headerSize) // e_phoff
|
||||
binary.LittleEndian.PutUint16(data[52:], headerSize) // e_ehsize
|
||||
binary.LittleEndian.PutUint16(data[54:], programSize) // e_phentsize
|
||||
binary.LittleEndian.PutUint16(data[56:], 1) // e_phnum
|
||||
|
||||
if interpreter != "" {
|
||||
binary.LittleEndian.PutUint32(data[headerSize:], uint32(elf.PT_INTERP))
|
||||
binary.LittleEndian.PutUint64(data[headerSize+8:], headerSize+programSize) // p_offset
|
||||
binary.LittleEndian.PutUint64(data[headerSize+32:], uint64(len(interpreter)+1)) // p_filesz
|
||||
data = append(data, interpreter...)
|
||||
data = append(data, 0)
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//go:build !ios
|
||||
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
var artifactHTTPClient = &http.Client{Timeout: 2 * time.Minute}
|
||||
|
||||
type runtimePaths struct {
|
||||
library string
|
||||
dependencies []string
|
||||
}
|
||||
|
||||
func cachedRuntimePaths(ctx context.Context) (runtimePaths, error) {
|
||||
goos := runtime.GOOS
|
||||
if goos == "linux" && linuxUsesMusl() {
|
||||
goos = "linux-musl"
|
||||
}
|
||||
|
||||
selected, err := artifactFor(goos, runtime.GOARCH)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
cache, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return runtimePaths{}, fmt.Errorf("locate user cache: %w", err)
|
||||
}
|
||||
|
||||
root := filepath.Join(cache, "ipatool", "unicorn", unicornVersion)
|
||||
paths := runtimePaths{dependencies: make([]string, 0, len(selected.dependencies))}
|
||||
|
||||
for _, dependency := range selected.dependencies {
|
||||
path, err := ensureLibrary(ctx, root, dependency, artifactHTTPClient)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
paths.dependencies = append(paths.dependencies, path)
|
||||
}
|
||||
|
||||
paths.library, err = ensureLibrary(ctx, root, selected, artifactHTTPClient)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
paths.library, err = prepareRuntimeLibrary(paths.library)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
return paths, nil
|
||||
}
|
||||
@@ -12,22 +12,33 @@ import (
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
const queryTimeout = 4
|
||||
const (
|
||||
queryTimeout = 4
|
||||
controlCPUModel = uint32(7 | 1<<26 | 1<<30)
|
||||
arm64CPUModelMax = uint32(3)
|
||||
)
|
||||
|
||||
const (
|
||||
archX86 = 4
|
||||
mode64 = 8
|
||||
protAll = 7
|
||||
archARM64 = 2
|
||||
modeARM = 0
|
||||
protAll = 7
|
||||
|
||||
RegRAX = 35
|
||||
RegRCX = 38
|
||||
RegRDI = 39
|
||||
RegRDX = 40
|
||||
RegRIP = 41
|
||||
RegRSI = 43
|
||||
RegRSP = 44
|
||||
RegR8 = 106
|
||||
RegR9 = 107
|
||||
RegX29 = 1
|
||||
RegLR = 2
|
||||
RegSP = 4
|
||||
RegX0 = 199
|
||||
RegX1 = 200
|
||||
RegX2 = 201
|
||||
RegX3 = 202
|
||||
RegX4 = 203
|
||||
RegX5 = 204
|
||||
RegX6 = 205
|
||||
RegX7 = 206
|
||||
RegX14 = 213
|
||||
RegX15 = 214
|
||||
RegX16 = 215
|
||||
RegV0 = 228
|
||||
RegPC = 260
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -55,15 +66,16 @@ type api struct {
|
||||
}
|
||||
|
||||
type Engine struct {
|
||||
api api
|
||||
handle uintptr
|
||||
library library
|
||||
hooks hookState
|
||||
stateMu sync.Mutex
|
||||
active sync.WaitGroup
|
||||
closing bool
|
||||
closeDone chan struct{}
|
||||
closeErr error
|
||||
memoryGuard *memoryGuard
|
||||
api api
|
||||
handle uintptr
|
||||
library library
|
||||
hooks hookState
|
||||
stateMu sync.Mutex
|
||||
active sync.WaitGroup
|
||||
closing bool
|
||||
closeDone chan struct{}
|
||||
closeErr error
|
||||
}
|
||||
|
||||
func New(ctx context.Context) (*Engine, error) {
|
||||
@@ -108,10 +120,19 @@ func newEngine(ctx context.Context, loadLibrary func(context.Context) (library,
|
||||
return nil, fmt.Errorf("unsupported Unicorn API version %d.%d", major, minor)
|
||||
}
|
||||
|
||||
if err := engine.err(engine.api.open(archX86, mode64, &engine.handle)); err != nil {
|
||||
if err := engine.err(engine.api.open(archARM64, modeARM, &engine.handle)); err != nil {
|
||||
_ = library.close()
|
||||
|
||||
return nil, fmt.Errorf("create x86-64 emulator: %w", err)
|
||||
return nil, fmt.Errorf("create arm64 emulator: %w", err)
|
||||
}
|
||||
|
||||
// Select Unicorn's most capable ARM64 model. The compatibility layer handles
|
||||
// modern instructions that this Unicorn build does not implement.
|
||||
if err := engine.err(engine.api.ctl(engine.handle, controlCPUModel, arm64CPUModelMax)); err != nil {
|
||||
_ = engine.api.close(engine.handle)
|
||||
_ = library.close()
|
||||
|
||||
return nil, fmt.Errorf("configure arm64 CPU model: %w", err)
|
||||
}
|
||||
|
||||
if err := configureEngine(engine); err != nil {
|
||||
@@ -176,6 +197,10 @@ func (e *Engine) MemRead(address, size uint64) ([]byte, error) {
|
||||
}
|
||||
defer done()
|
||||
|
||||
if err := e.checkMemory(address, size); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
data := make([]byte, size)
|
||||
if len(data) == 0 {
|
||||
return data, nil
|
||||
@@ -197,6 +222,10 @@ func (e *Engine) MemReadInto(data []byte, address uint64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := e.checkMemory(address, uint64(len(data))); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return e.err(e.api.memRead(handle, address, unsafe.Pointer(&data[0]), uint64(len(data))))
|
||||
}
|
||||
|
||||
@@ -211,6 +240,10 @@ func (e *Engine) MemWrite(address uint64, data []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := e.checkMemory(address, uint64(len(data))); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return e.err(e.api.memWrite(handle, address, unsafe.Pointer(&data[0]), uint64(len(data))))
|
||||
}
|
||||
|
||||
@@ -238,6 +271,29 @@ func (e *Engine) RegWrite(register int, value uint64) error {
|
||||
return e.err(e.api.regWrite(handle, int32(register), unsafe.Pointer(&value)))
|
||||
}
|
||||
|
||||
func (e *Engine) RegRead128(register int) ([16]byte, error) {
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
return [16]byte{}, err
|
||||
}
|
||||
defer done()
|
||||
|
||||
var value [16]byte
|
||||
err = e.err(e.api.regRead(handle, int32(register), unsafe.Pointer(&value[0])))
|
||||
|
||||
return value, err
|
||||
}
|
||||
|
||||
func (e *Engine) RegWrite128(register int, value [16]byte) error {
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer done()
|
||||
|
||||
return e.err(e.api.regWrite(handle, int32(register), unsafe.Pointer(&value[0])))
|
||||
}
|
||||
|
||||
func (e *Engine) Start(begin, end uint64) error {
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
@@ -246,7 +302,11 @@ func (e *Engine) Start(begin, end uint64) error {
|
||||
|
||||
defer done()
|
||||
|
||||
return e.err(e.api.emuStart(handle, begin, end, 0, 0))
|
||||
if err := e.executionError(nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return e.executionError(e.err(e.api.emuStart(handle, begin, end, 0, 0)))
|
||||
}
|
||||
|
||||
func (e *Engine) StartBounded(begin, end uint64, timeout time.Duration, instructionLimit uint64) error {
|
||||
@@ -266,7 +326,11 @@ func (e *Engine) StartBounded(begin, end uint64, timeout time.Duration, instruct
|
||||
|
||||
defer done()
|
||||
|
||||
if err := e.err(e.api.emuStart(handle, begin, end, microseconds, instructionLimit)); err != nil {
|
||||
if err := e.executionError(nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := e.executionError(e.err(e.api.emuStart(handle, begin, end, microseconds, instructionLimit))); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -105,11 +105,11 @@ func TestEngineOperationsFailAfterClose(t *testing.T) {
|
||||
{"MemReadInto", func() error { return engine.MemReadInto(nil, 0) }},
|
||||
{"MemWrite", func() error { return engine.MemWrite(0, nil) }},
|
||||
{"RegRead", func() error {
|
||||
_, err := engine.RegRead(RegRAX)
|
||||
_, err := engine.RegRead(RegX0)
|
||||
|
||||
return err
|
||||
}},
|
||||
{"RegWrite", func() error { return engine.RegWrite(RegRAX, 0) }},
|
||||
{"RegWrite", func() error { return engine.RegWrite(RegX0, 0) }},
|
||||
{"Start", func() error { return engine.Start(0, 1) }},
|
||||
{"StartBounded", func() error { return engine.StartBounded(0, 1, time.Second, 1) }},
|
||||
{"Stop", engine.Stop},
|
||||
@@ -214,7 +214,7 @@ func waitForResult(t *testing.T, result <-chan error) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineExecutesX8664(t *testing.T) {
|
||||
func TestEngineExecutesARM64(t *testing.T) {
|
||||
engine := newTestEngine(t)
|
||||
defer engine.Close()
|
||||
|
||||
@@ -223,8 +223,8 @@ func TestEngineExecutesX8664(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// mov rax, 0x1234; hlt
|
||||
code := []byte{0x48, 0xc7, 0xc0, 0x34, 0x12, 0x00, 0x00, 0xf4}
|
||||
// mov x0, #0x1234
|
||||
code := []byte{0x80, 0x46, 0x82, 0xd2}
|
||||
if err := engine.MemWrite(address, code); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -233,13 +233,13 @@ func TestEngineExecutesX8664(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
value, err := engine.RegRead(RegRAX)
|
||||
value, err := engine.RegRead(RegX0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if value != 0x1234 {
|
||||
t.Fatalf("RAX = %#x, want %#x", value, uint64(0x1234))
|
||||
t.Fatalf("X0 = %#x, want %#x", value, uint64(0x1234))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,22 +252,22 @@ func TestStartBoundedReportsTimeout(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// jmp $-2
|
||||
if err := engine.MemWrite(address, []byte{0xeb, 0xfe}); err != nil {
|
||||
// b .
|
||||
if err := engine.MemWrite(address, []byte{0x00, 0x00, 0x00, 0x14}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := engine.StartBounded(address, address+2, 10*time.Millisecond, 0)
|
||||
err := engine.StartBounded(address, address+4, 10*time.Millisecond, 0)
|
||||
if !errors.Is(err, errTimeout) {
|
||||
t.Fatalf("StartBounded error = %v, want %v", err, errTimeout)
|
||||
}
|
||||
|
||||
const completionAddress = address + 0x10
|
||||
if err := engine.MemWrite(completionAddress, []byte{0xf4}); err != nil {
|
||||
if err := engine.MemWrite(completionAddress, []byte{0x1f, 0x20, 0x03, 0xd5}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := engine.StartBounded(completionAddress, completionAddress+1, time.Second, 0); err != nil {
|
||||
if err := engine.StartBounded(completionAddress, completionAddress+4, time.Second, 0); err != nil {
|
||||
t.Fatalf("StartBounded after timeout: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,11 @@ import (
|
||||
|
||||
const hookCode = 1 << 2
|
||||
|
||||
const hookUnmappedMemory = 1<<4 | 1<<5 | 1<<6
|
||||
|
||||
// MemoryFaultHook may map missing guest memory and return true to retry access.
|
||||
type MemoryFaultHook func(address uint64, size uint32) bool
|
||||
|
||||
type CodeHook func(address uint64, size uint32)
|
||||
|
||||
type hookState struct {
|
||||
@@ -39,6 +44,16 @@ var (
|
||||
callback.(CodeHook)(address, size)
|
||||
}
|
||||
|
||||
return 0
|
||||
})
|
||||
memoryFaultTrampoline = purego.NewCallback(func(
|
||||
_ purego.CDecl, _ uintptr, _ int32, address uint64, size int32, _ int64, userData uintptr,
|
||||
) uintptr {
|
||||
callback, ok := codeHookCallbacks.Load(userData)
|
||||
if ok && callback.(MemoryFaultHook)(address, uint32(size)) {
|
||||
return 1
|
||||
}
|
||||
|
||||
return 0
|
||||
})
|
||||
)
|
||||
@@ -47,6 +62,23 @@ var (
|
||||
// the inclusive range [begin, end]. The callback is retained until the Hook or
|
||||
// Engine is closed; it runs through a C ABI trampoline and must not panic.
|
||||
func (e *Engine) AddCodeHook(begin, end uint64, callback CodeHook) (*Hook, error) {
|
||||
if callback == nil {
|
||||
return nil, errors.New("unicorn code hook callback is nil")
|
||||
}
|
||||
|
||||
return e.addHook(hookCode, codeHookTrampoline, begin, end, callback)
|
||||
}
|
||||
|
||||
// AddMemoryFaultHook supports demand loading verified cache pages during bootstrap.
|
||||
func (e *Engine) AddMemoryFaultHook(callback MemoryFaultHook) (*Hook, error) {
|
||||
if callback == nil {
|
||||
return nil, errors.New("unicorn memory hook callback is nil")
|
||||
}
|
||||
|
||||
return e.addHook(hookUnmappedMemory, memoryFaultTrampoline, 1, 0, callback)
|
||||
}
|
||||
|
||||
func (e *Engine) addHook(kind int32, trampoline uintptr, begin, end uint64, callback any) (*Hook, error) {
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -54,10 +86,6 @@ func (e *Engine) AddCodeHook(begin, end uint64, callback CodeHook) (*Hook, error
|
||||
|
||||
defer done()
|
||||
|
||||
if callback == nil {
|
||||
return nil, errors.New("unicorn code hook callback is nil")
|
||||
}
|
||||
|
||||
id := uintptr(codeHookID.Add(1))
|
||||
if id == 0 {
|
||||
id = uintptr(codeHookID.Add(1))
|
||||
@@ -66,7 +94,7 @@ func (e *Engine) AddCodeHook(begin, end uint64, callback CodeHook) (*Hook, error
|
||||
codeHookCallbacks.Store(id, callback)
|
||||
|
||||
var hookHandle uintptr
|
||||
if err := e.err(e.api.hookAdd(handle, &hookHandle, hookCode, codeHookTrampoline, id, begin, end)); err != nil {
|
||||
if err := e.err(e.api.hookAdd(handle, &hookHandle, kind, trampoline, id, begin, end)); err != nil {
|
||||
codeHookCallbacks.Delete(id)
|
||||
|
||||
return nil, err
|
||||
|
||||
@@ -11,8 +11,8 @@ func TestCodeHookStopsEmulation(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// mov rax, 1; inc rax; ud2
|
||||
code := []byte{0x48, 0xc7, 0xc0, 0x01, 0x00, 0x00, 0x00, 0x48, 0xff, 0xc0, 0x0f, 0x0b}
|
||||
// mov x0, #1; add x0, x0, #1; brk #0
|
||||
code := []byte{0x20, 0x00, 0x80, 0xd2, 0x00, 0x04, 0x00, 0x91, 0x00, 0x00, 0x20, 0xd4}
|
||||
if err := engine.MemWrite(address, code); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -24,7 +24,7 @@ func TestCodeHookStopsEmulation(t *testing.T) {
|
||||
stopErr error
|
||||
)
|
||||
|
||||
hook, err := engine.AddCodeHook(address+7, address+7, func(current uint64, size uint32) {
|
||||
hook, err := engine.AddCodeHook(address+4, address+4, func(current uint64, size uint32) {
|
||||
calls++
|
||||
hookAddress = current
|
||||
hookSize = size
|
||||
@@ -48,8 +48,8 @@ func TestCodeHookStopsEmulation(t *testing.T) {
|
||||
t.Fatalf("callback calls = %d, want 1", calls)
|
||||
}
|
||||
|
||||
if hookAddress != address+7 || hookSize != 3 {
|
||||
t.Fatalf("callback instruction = (%#x, %d), want (%#x, 3)", hookAddress, hookSize, address+7)
|
||||
if hookAddress != address+4 || hookSize != 4 {
|
||||
t.Fatalf("callback instruction = (%#x, %d), want (%#x, 4)", hookAddress, hookSize, address+4)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ func TestClosedCodeHookDoesNotRun(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := engine.MemWrite(address, []byte{0x90, 0xf4}); err != nil {
|
||||
if err := engine.MemWrite(address, []byte{0x1f, 0x20, 0x03, 0xd5}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ func TestClosedCodeHookDoesNotRun(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := engine.Start(address, address+2); err != nil {
|
||||
if err := engine.Start(address, address+4); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// iOS builds statically link Unicorn because the desktop runtime artifacts
|
||||
// cannot be loaded on iOS. tools/build-ios.sh exports its symbols for purego.
|
||||
func openLibrary(ctx context.Context) (library, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return library{}, fmt.Errorf("load Unicorn library: %w", err)
|
||||
}
|
||||
|
||||
if _, err := purego.Dlsym(purego.RTLD_DEFAULT, "uc_version"); err != nil {
|
||||
return library{}, fmt.Errorf("unicorn is not linked; build with tools/build-ios.sh: %w", err)
|
||||
}
|
||||
|
||||
return library{handle: purego.RTLD_DEFAULT, close: func() error { return nil }}, nil
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build darwin || linux
|
||||
//go:build (darwin && !ios) || linux
|
||||
|
||||
package unicorn
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
const hookMemoryAccess = 1<<10 | 1<<11
|
||||
|
||||
// memoryGuard records the first guest violation even when uc_emu_stop returns a
|
||||
// successful status. Host accesses return their validation errors directly.
|
||||
type memoryGuard struct {
|
||||
check func(address, size uint64) error
|
||||
mu sync.Mutex
|
||||
err error
|
||||
}
|
||||
|
||||
var memoryAccessTrampoline = purego.NewCallback(func(
|
||||
_ purego.CDecl, _ uintptr, _ int32, address uint64, size int32, _ int64, userData uintptr,
|
||||
) uintptr {
|
||||
if callback, ok := codeHookCallbacks.Load(userData); ok {
|
||||
callback.(CodeHook)(address, uint32(size))
|
||||
}
|
||||
|
||||
return 0
|
||||
})
|
||||
|
||||
// GuardMemory validates guest reads, writes and instructions as well as host
|
||||
// MemRead, MemReadInto and MemWrite calls. Install it once, before executing any
|
||||
// guest code, without concurrent engine operations. The check must not panic.
|
||||
// Hooks live until Close; a rejected guest access permanently fails execution.
|
||||
func (e *Engine) GuardMemory(check func(address, size uint64) error) error {
|
||||
if check == nil {
|
||||
return errors.New("unicorn memory validator is nil")
|
||||
}
|
||||
|
||||
if e.memoryGuard != nil {
|
||||
return errors.New("unicorn memory validator is already installed")
|
||||
}
|
||||
|
||||
guard := &memoryGuard{check: check}
|
||||
callback := CodeHook(func(address uint64, size uint32) {
|
||||
if err := check(address, uint64(size)); err != nil {
|
||||
guard.mu.Lock()
|
||||
if guard.err == nil {
|
||||
guard.err = err
|
||||
}
|
||||
guard.mu.Unlock()
|
||||
|
||||
_ = e.Stop()
|
||||
}
|
||||
})
|
||||
|
||||
dataHook, err := e.addHook(hookMemoryAccess, memoryAccessTrampoline, 1, 0, callback)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Instruction hooks also cover fetches served from Unicorn's translation
|
||||
// cache, which need not trigger a memory-fetch hook on subsequent execution.
|
||||
if _, err = e.AddCodeHook(1, 0, callback); err != nil {
|
||||
_ = dataHook.Close()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
e.memoryGuard = guard
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkMemory applies the same policy to accesses made by the host bridge.
|
||||
func (e *Engine) checkMemory(address, size uint64) error {
|
||||
if e.memoryGuard != nil && size != 0 {
|
||||
return e.memoryGuard.check(address, size)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// executionError preserves guard failures even when Unicorn stops successfully.
|
||||
func (e *Engine) executionError(native error) error {
|
||||
if e.memoryGuard != nil {
|
||||
e.memoryGuard.mu.Lock()
|
||||
defer e.memoryGuard.mu.Unlock()
|
||||
|
||||
if e.memoryGuard.err != nil {
|
||||
return errors.Join(e.memoryGuard.err, native)
|
||||
}
|
||||
}
|
||||
|
||||
return native
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Guarded grouped memory", func() {
|
||||
const base = uint64(0x6000000)
|
||||
var engine *Engine
|
||||
var missing error
|
||||
BeforeEach(func() {
|
||||
var err error
|
||||
engine, err = New(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(engine.Close)
|
||||
Expect(engine.MemMap(base, 3*4096)).To(Succeed())
|
||||
missing = errors.New("missing dependency")
|
||||
})
|
||||
install := func() {
|
||||
Expect(engine.GuardMemory(func(address, size uint64) error {
|
||||
if size > 0 && address < base+8192 && address+size > base+4096 {
|
||||
return missing
|
||||
}
|
||||
|
||||
return nil
|
||||
})).To(Succeed())
|
||||
}
|
||||
instruction := func(address uint64, word uint32) {
|
||||
var data [4]byte
|
||||
binary.LittleEndian.PutUint32(data[:], word)
|
||||
Expect(engine.MemWrite(address, data[:])).To(Succeed())
|
||||
}
|
||||
|
||||
It("checks host reads, buffered reads and writes across a missing page", func() {
|
||||
install()
|
||||
_, err := engine.MemRead(base+4092, 8)
|
||||
Expect(errors.Is(err, missing)).To(BeTrue())
|
||||
Expect(errors.Is(engine.MemReadInto(make([]byte, 8), base+4092), missing)).To(BeTrue())
|
||||
Expect(errors.Is(engine.MemWrite(base+4092, make([]byte, 8)), missing)).To(BeTrue())
|
||||
Expect(engine.MemWrite(base, []byte{1})).To(Succeed())
|
||||
data, err := engine.MemRead(base, 1)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(data).To(Equal([]byte{1}))
|
||||
})
|
||||
DescribeTable("reports guest data violations for both execution APIs", func(word uint32, bounded bool) {
|
||||
instruction(base, word)
|
||||
Expect(engine.RegWrite(RegX1, base+4096)).To(Succeed())
|
||||
install()
|
||||
var err error
|
||||
if bounded {
|
||||
err = engine.StartBounded(base, base+4, time.Second, 10)
|
||||
} else {
|
||||
err = engine.Start(base, base+4)
|
||||
}
|
||||
|
||||
Expect(errors.Is(err, missing)).To(BeTrue())
|
||||
// A caller cannot accidentally continue after an ignored guard failure.
|
||||
Expect(errors.Is(engine.Start(base, base+4), missing)).To(BeTrue())
|
||||
}, Entry("read", uint32(0xf9400020), false), Entry("write", uint32(0xf9000020), false), Entry("bounded read", uint32(0xf9400020), true), Entry("bounded write", uint32(0xf9000020), true))
|
||||
It("rejects instruction execution in mapped padding", func() {
|
||||
instruction(base+4096, 0xd28000e0) // mov x0, #7
|
||||
install()
|
||||
Expect(errors.Is(engine.Start(base+4096, base+4100), missing)).To(BeTrue())
|
||||
value, err := engine.RegRead(RegX0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(value).To(BeZero())
|
||||
})
|
||||
DescribeTable("rejects guest accesses crossing from captured data into padding", func(word uint32) {
|
||||
instruction(base, word)
|
||||
Expect(engine.RegWrite(RegX1, base+4092)).To(Succeed())
|
||||
install()
|
||||
Expect(errors.Is(engine.Start(base, base+4), missing)).To(BeTrue())
|
||||
}, Entry("read", uint32(0xf9400020)), Entry("write", uint32(0xf9000020)))
|
||||
It("checks instruction fetches even when the translation was cached", func() {
|
||||
instruction(base, 0xd28000e0)
|
||||
allowed := true
|
||||
Expect(engine.GuardMemory(func(uint64, uint64) error {
|
||||
if !allowed {
|
||||
return missing
|
||||
}
|
||||
|
||||
return nil
|
||||
})).To(Succeed())
|
||||
Expect(engine.Start(base, base+4)).To(Succeed())
|
||||
allowed = false
|
||||
Expect(engine.RegWrite(RegX0, 0)).To(Succeed())
|
||||
Expect(errors.Is(engine.Start(base, base+4), missing)).To(BeTrue())
|
||||
value, err := engine.RegRead(RegX0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(value).To(BeZero())
|
||||
})
|
||||
It("allows guest reads and writes on captured pages", func() {
|
||||
instruction(base, 0xf9000020) // str x0, [x1]
|
||||
instruction(base+4, 0xf9400022) // ldr x2, [x1]
|
||||
Expect(engine.RegWrite(RegX0, 42)).To(Succeed())
|
||||
Expect(engine.RegWrite(RegX1, base+8192)).To(Succeed())
|
||||
install()
|
||||
Expect(engine.Start(base, base+8)).To(Succeed())
|
||||
value, err := engine.RegRead(RegX0 + 2)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(value).To(Equal(uint64(42)))
|
||||
})
|
||||
It("rejects invalid installation and releases both callbacks on close", func() {
|
||||
Expect(engine.GuardMemory(nil)).To(MatchError(ContainSubstring("validator is nil")))
|
||||
install()
|
||||
Expect(engine.GuardMemory(func(uint64, uint64) error { return nil })).To(MatchError(ContainSubstring("already installed")))
|
||||
ids := make([]uintptr, 0, len(engine.hooks.ids))
|
||||
for id := range engine.hooks.ids {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
|
||||
Expect(ids).To(HaveLen(2))
|
||||
Expect(engine.Close()).To(Succeed())
|
||||
for _, id := range ids {
|
||||
_, present := codeHookCallbacks.Load(id)
|
||||
Expect(present).To(BeFalse())
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,51 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Demand-loaded guest memory", func() {
|
||||
It("retries an unmapped instruction fetch and releases its callback", func() {
|
||||
engine, err := New(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(engine.Close)
|
||||
const address = uint64(0x6000000)
|
||||
count := 0
|
||||
var callbackErr error
|
||||
hook, err := engine.AddMemoryFaultHook(func(a uint64, _ uint32) bool {
|
||||
count++
|
||||
if a != address {
|
||||
return false
|
||||
}
|
||||
callbackErr = engine.MemMap(address, 4096)
|
||||
if callbackErr != nil {
|
||||
return false
|
||||
}
|
||||
callbackErr = engine.MemWrite(address, []byte{0xe0, 0, 0x80, 0xd2})
|
||||
|
||||
return callbackErr == nil
|
||||
})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(engine.Start(address, address+4)).To(Succeed())
|
||||
Expect(callbackErr).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(1))
|
||||
value, err := engine.RegRead(RegX0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(value).To(Equal(uint64(7)))
|
||||
id := hook.id
|
||||
Expect(hook.Close()).To(Succeed())
|
||||
_, present := codeHookCallbacks.Load(id)
|
||||
Expect(present).To(BeFalse())
|
||||
})
|
||||
It("propagates an unresolved memory fault", func() {
|
||||
engine, err := New(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(engine.Close)
|
||||
_, err = engine.AddMemoryFaultHook(func(uint64, uint32) bool { return false })
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(engine.Start(0x6000000, 0x6000004)).NotTo(Succeed())
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build !windows || !arm64
|
||||
//go:build !ios && (!windows || !arm64)
|
||||
|
||||
package unicorn
|
||||
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
// Package store provides the portable, framework-backed App Store request engine.
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
"github.com/majd/ipatool/v2/internal/store/emulator"
|
||||
"github.com/majd/ipatool/v2/internal/store/profile"
|
||||
apphttp "github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type Backend struct {
|
||||
jar http.CookieJar
|
||||
macAddress func() (string, error)
|
||||
mu sync.Mutex
|
||||
image []byte
|
||||
bag map[string]any
|
||||
transport *http.Transport
|
||||
authTransport *http.Transport
|
||||
}
|
||||
|
||||
type executor struct {
|
||||
backend *Backend
|
||||
operation string
|
||||
}
|
||||
|
||||
func New(jar http.CookieJar, macAddress func() (string, error)) *Backend {
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
transport.ResponseHeaderTimeout = 30 * time.Second
|
||||
transport.IdleConnTimeout = 90 * time.Second
|
||||
authTransport := transport.Clone()
|
||||
authTransport.DisableKeepAlives = true
|
||||
|
||||
return &Backend{jar: jar, macAddress: macAddress, transport: transport, authTransport: authTransport}
|
||||
}
|
||||
|
||||
// Client shares session cookies and bag data while isolating each guest VM.
|
||||
func (b *Backend) Client(operation string) apphttp.Executor {
|
||||
return &executor{backend: b, operation: operation}
|
||||
}
|
||||
|
||||
func (e *executor) Send(request apphttp.Request, body []byte) (*http.Response, error) {
|
||||
ctx := request.Context
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
if e.operation == "bag-direct" {
|
||||
direct, err := http.NewRequestWithContext(ctx, request.Method, request.URL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create Store request: %w", err)
|
||||
}
|
||||
|
||||
for key, value := range request.Headers {
|
||||
direct.Header.Set(key, value)
|
||||
}
|
||||
|
||||
if direct.Header.Get("User-Agent") == "" {
|
||||
direct.Header.Set("User-Agent", apphttp.DefaultUserAgent)
|
||||
}
|
||||
|
||||
return e.backend.requestTransport(emulator.Request{Operation: "authenticate"})(direct)
|
||||
}
|
||||
|
||||
input := emulator.Request{URL: request.URL, Method: request.Method, Operation: e.operation, Format: string(request.ResponseFormat), Timeout: request.Timeout, Body: body, Headers: make(http.Header), NoRedirects: request.NoRedirects, Raw: request.ResponseFormat == apphttp.ResponseFormatRaw}
|
||||
for key, value := range request.Headers {
|
||||
input.Headers.Set(key, value)
|
||||
}
|
||||
|
||||
if payload, ok := request.Payload.(*apphttp.XMLPayload); ok {
|
||||
input.Parameters = payload.Content
|
||||
if input.Parameters == nil {
|
||||
input.Parameters = map[string]any{}
|
||||
}
|
||||
}
|
||||
|
||||
if request.ActionSigner != nil {
|
||||
input.Sign = request.ActionSigner.Sign
|
||||
}
|
||||
|
||||
return e.backend.execute(ctx, input)
|
||||
}
|
||||
|
||||
func (e *executor) Do(request *http.Request) (*http.Response, error) {
|
||||
if request == nil {
|
||||
return nil, errors.New("store request is nil")
|
||||
}
|
||||
|
||||
if e.operation == "sap" {
|
||||
return e.backend.requestTransport(emulator.Request{Operation: "authenticate"})(request)
|
||||
}
|
||||
|
||||
var body []byte
|
||||
|
||||
var err error
|
||||
if request.Body != nil {
|
||||
body, err = io.ReadAll(io.LimitReader(request.Body, (1<<20)+1))
|
||||
_ = request.Body.Close()
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read Store request: %w", err)
|
||||
}
|
||||
|
||||
if len(body) > 1<<20 {
|
||||
return nil, errors.New("store request body exceeds limit")
|
||||
}
|
||||
}
|
||||
|
||||
return e.backend.execute(request.Context(), emulator.Request{URL: request.URL.String(), Method: request.Method, Headers: request.Header.Clone(), Body: body, Operation: e.operation, Stream: e.operation == "transfer"})
|
||||
}
|
||||
|
||||
func (b *Backend) hardware(parameters map[string]any) ([]byte, error) {
|
||||
if value, ok := parameters["guid"].(string); ok {
|
||||
data, err := hex.DecodeString(value)
|
||||
if err != nil || len(data) != 6 {
|
||||
return nil, errors.New("invalid Store hardware identity")
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
if b.macAddress == nil {
|
||||
return nil, errors.New("store machine identity is not configured")
|
||||
}
|
||||
|
||||
value, err := b.macAddress()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get Store machine identity: %w", err)
|
||||
}
|
||||
|
||||
data, err := net.ParseMAC(value)
|
||||
if err != nil || len(data) != 6 {
|
||||
return nil, errors.New("invalid Store machine address")
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (b *Backend) prepare(ctx context.Context) ([]byte, profile.Data, error) {
|
||||
prepared, err := profile.Load(ctx)
|
||||
if err != nil {
|
||||
return nil, profile.Data{}, fmt.Errorf("load Store runtime: %w", err)
|
||||
}
|
||||
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
if b.image == nil {
|
||||
bundle, err := assets.Load(ctx)
|
||||
if err != nil {
|
||||
return nil, profile.Data{}, fmt.Errorf("load Store runtime: %w", err)
|
||||
}
|
||||
|
||||
b.image = bundle.AppleMediaServices
|
||||
}
|
||||
|
||||
return b.image, prepared, nil
|
||||
}
|
||||
|
||||
func (b *Backend) execute(ctx context.Context, input emulator.Request) (*http.Response, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("store request: %w", err)
|
||||
}
|
||||
|
||||
hardware, err := b.hardware(input.Parameters)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store request: %w", err)
|
||||
}
|
||||
|
||||
input.HardwareID = hardware
|
||||
if input.Headers == nil {
|
||||
input.Headers = make(http.Header)
|
||||
}
|
||||
|
||||
if input.Headers.Get("User-Agent") == "" {
|
||||
input.Headers.Set("User-Agent", apphttp.DefaultUserAgent)
|
||||
|
||||
if input.Operation == "purchase" {
|
||||
input.Headers.Set("User-Agent", "Configurator/2.18 (Macintosh; OS X 15.3.2; 24D81) AppleWebKit/0620.2.4.11.6")
|
||||
}
|
||||
}
|
||||
|
||||
b.mu.Lock()
|
||||
bag := b.bag
|
||||
b.mu.Unlock()
|
||||
|
||||
if input.Operation == "purchase" && bag == nil {
|
||||
response, err := b.execute(ctx, emulator.Request{URL: "https://init.itunes.apple.com/bag.xml?guid=" + strings.ToUpper(hex.EncodeToString(hardware)), Method: http.MethodGet, Operation: "bag"})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load purchase bag: %w", err)
|
||||
}
|
||||
|
||||
_ = response.Body.Close()
|
||||
|
||||
b.mu.Lock()
|
||||
bag = b.bag
|
||||
b.mu.Unlock()
|
||||
}
|
||||
|
||||
input.Bag = bag
|
||||
|
||||
image, prepared, err := b.prepare(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("prepare Store framework: %w", err)
|
||||
}
|
||||
|
||||
guest, err := emulator.Open(ctx, image, prepared)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open Store framework: %w", err)
|
||||
}
|
||||
|
||||
defer guest.Close()
|
||||
|
||||
input.Transport = b.requestTransport(input)
|
||||
|
||||
response, err := guest.Execute(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store request: %w", err)
|
||||
}
|
||||
|
||||
if input.Stream {
|
||||
return response, nil
|
||||
}
|
||||
|
||||
if strings.EqualFold(response.Header.Get("Content-Encoding"), "gzip") {
|
||||
reader, e := gzip.NewReader(response.Body)
|
||||
if e != nil {
|
||||
_ = response.Body.Close()
|
||||
|
||||
return nil, errors.New("invalid compressed Store response")
|
||||
}
|
||||
|
||||
data, e := io.ReadAll(io.LimitReader(reader, (32<<20)+1))
|
||||
_ = reader.Close()
|
||||
_ = response.Body.Close()
|
||||
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("read compressed Store response: %w", e)
|
||||
}
|
||||
|
||||
if len(data) > 32<<20 {
|
||||
return nil, errors.New("store response exceeds size limit")
|
||||
}
|
||||
|
||||
response.Body = io.NopCloser(bytes.NewReader(data))
|
||||
response.Header.Del("Content-Encoding")
|
||||
response.Header.Del("Content-Length")
|
||||
response.ContentLength = int64(len(data))
|
||||
}
|
||||
|
||||
if strings.Contains(input.URL, "init.itunes.apple.com/bag.xml") && response.StatusCode == http.StatusOK {
|
||||
data, e := io.ReadAll(response.Body)
|
||||
_ = response.Body.Close()
|
||||
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("read Store response: %w", e)
|
||||
}
|
||||
|
||||
response.Body = io.NopCloser(bytes.NewReader(data))
|
||||
|
||||
var values map[string]any
|
||||
if e = apphttp.DecodePropertyList(data, &values); e == nil {
|
||||
b.mu.Lock()
|
||||
b.bag = values
|
||||
b.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// CloseIdleConnections releases pooled sockets without interrupting active streams.
|
||||
func (b *Backend) CloseIdleConnections() {
|
||||
b.transport.CloseIdleConnections()
|
||||
b.authTransport.CloseIdleConnections()
|
||||
}
|
||||
|
||||
// Each request owns its timeout; compatible requests share only the connection pool.
|
||||
// Login keeps its existing fresh-connection policy, including framework redirects.
|
||||
func (b *Backend) requestTransport(input emulator.Request) func(*http.Request) (*http.Response, error) {
|
||||
timeout := input.Timeout
|
||||
if timeout == 0 && input.Operation == "api" {
|
||||
timeout = 30 * time.Second
|
||||
}
|
||||
|
||||
transport := b.transport
|
||||
|
||||
if input.Operation == "authenticate" {
|
||||
transport = b.authTransport
|
||||
}
|
||||
|
||||
client := &http.Client{Transport: transport, Timeout: timeout, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
|
||||
return func(request *http.Request) (*http.Response, error) {
|
||||
if b.jar != nil && request.Header.Get("Cookie") == "" {
|
||||
for _, cookie := range b.jar.Cookies(request.URL) {
|
||||
request.AddCookie(cookie)
|
||||
}
|
||||
}
|
||||
|
||||
response, err := client.Do(request)
|
||||
if err == nil && b.jar != nil {
|
||||
b.jar.SetCookies(request.URL, response.Cookies())
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store HTTP transport: %w", err)
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/store/emulator"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestStoreBackend(t *testing.T) { RegisterFailHandler(Fail); RunSpecs(t, "Store Backend") }
|
||||
|
||||
var _ = Describe("Store connection reuse", func() {
|
||||
var backend *Backend
|
||||
var server *httptest.Server
|
||||
BeforeEach(func() {
|
||||
jar, err := cookiejar.New(nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
backend = New(jar, nil)
|
||||
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Connection", r.RemoteAddr)
|
||||
w.Header().Set("X-Received-Cookie", r.Header.Get("Cookie"))
|
||||
switch r.URL.Path {
|
||||
case "/cookie":
|
||||
http.SetCookie(w, &http.Cookie{Name: "session", Value: "fixture", Path: "/"})
|
||||
case "/redirect":
|
||||
w.Header().Set("Location", "/target")
|
||||
w.WriteHeader(http.StatusFound)
|
||||
case "/slow":
|
||||
<-r.Context().Done()
|
||||
|
||||
return
|
||||
case "/stream":
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.(http.Flusher).Flush()
|
||||
<-r.Context().Done()
|
||||
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(w, "fixture response")
|
||||
}))
|
||||
})
|
||||
AfterEach(func() {
|
||||
backend.CloseIdleConnections()
|
||||
server.Close()
|
||||
})
|
||||
get := func(operation, path string) *http.Response {
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, server.URL+path, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
response, err := backend.requestTransport(emulator.Request{Operation: operation})(req)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
_, err = io.Copy(io.Discard, response.Body)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(response.Body.Close()).To(Succeed())
|
||||
|
||||
return response
|
||||
}
|
||||
It("reuses a consumed connection across API and download clients", func() {
|
||||
first := get("request", "/cookie")
|
||||
second := get("transfer", "/")
|
||||
Expect(second.Header.Get("X-Connection")).To(Equal(first.Header.Get("X-Connection")))
|
||||
Expect(second.Header.Get("X-Received-Cookie")).To(Equal("session=fixture"))
|
||||
third := get("bag", "/")
|
||||
Expect(third.Header.Get("X-Connection")).To(Equal(first.Header.Get("X-Connection")))
|
||||
})
|
||||
It("keeps authentication attempts separate without closing the API pool", func() {
|
||||
api := get("request", "/")
|
||||
first := get("authenticate", "/")
|
||||
second := get("authenticate", "/")
|
||||
Expect(first.Header.Get("X-Connection")).NotTo(Equal(api.Header.Get("X-Connection")))
|
||||
Expect(second.Header.Get("X-Connection")).NotTo(Equal(first.Header.Get("X-Connection")))
|
||||
Expect(get("request", "/").Header.Get("X-Connection")).To(Equal(api.Header.Get("X-Connection")))
|
||||
})
|
||||
It("returns redirects to the framework", func() {
|
||||
Expect(get("request", "/redirect").StatusCode).To(Equal(http.StatusFound))
|
||||
})
|
||||
It("preserves explicit cookie headers", func() {
|
||||
get("request", "/cookie")
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, server.URL, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
req.Header.Set("Cookie", "explicit=value")
|
||||
response, err := backend.requestTransport(emulator.Request{})(req)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
defer response.Body.Close()
|
||||
Expect(response.Header.Get("X-Received-Cookie")).To(Equal("explicit=value"))
|
||||
})
|
||||
It("applies timeouts per request without poisoning subsequent requests", func() {
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, server.URL+"/slow", nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
_, err = backend.requestTransport(emulator.Request{Timeout: 20 * time.Millisecond})(req)
|
||||
Expect(err).To(MatchError(ContainSubstring("deadline exceeded")))
|
||||
Expect(get("request", "/").StatusCode).To(Equal(http.StatusOK))
|
||||
})
|
||||
It("cancels an active stream without closing an unrelated pooled connection", func() {
|
||||
api := get("request", "/")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/stream", nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
response, err := backend.requestTransport(emulator.Request{Operation: "transfer"})(req)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
defer response.Body.Close()
|
||||
other := get("request", "/")
|
||||
Expect(other.Header.Get("X-Connection")).NotTo(Equal(api.Header.Get("X-Connection")))
|
||||
cancel()
|
||||
_, err = io.ReadAll(response.Body)
|
||||
Expect(err).To(MatchError(context.Canceled))
|
||||
Expect(response.Body.Close()).To(Succeed())
|
||||
Expect(get("request", "/").Header.Get("X-Connection")).To(Equal(other.Header.Get("X-Connection")))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
package emulator
|
||||
|
||||
import "strings"
|
||||
|
||||
// Ephemeral Accounts-framework values. No host account store or keychain writes.
|
||||
func (r *Runtime) accountMessage(receiver uint64, class, selector string, meta bool) bool {
|
||||
if !meta && (class == "ACAccountStore" || class == "ACDAccountStore") {
|
||||
switch selector {
|
||||
case "accountTypeWithAccountTypeIdentifier:", "accountTypeWithAccountTypeIdentifier:error:":
|
||||
accountType := r.New("ACAccountType", nil)
|
||||
|
||||
r.objects[accountType].Properties = map[string]uint64{"identifier": r.arg(2)}
|
||||
if selector == "accountTypeWithAccountTypeIdentifier:error:" && r.arg(3) != 0 {
|
||||
r.write64(r.arg(3), 0)
|
||||
}
|
||||
|
||||
r.set(accountType)
|
||||
|
||||
return true
|
||||
case "accountsWithAccountType:", "accountsWithAccountType:options:error:", "accountsWithAccountType:options:classification:error:":
|
||||
if selector == "accountsWithAccountType:options:error:" && r.arg(4) != 0 {
|
||||
r.write64(r.arg(4), 0)
|
||||
}
|
||||
|
||||
if selector == "accountsWithAccountType:options:classification:error:" && r.arg(5) != 0 {
|
||||
r.write64(r.arg(5), 0)
|
||||
}
|
||||
|
||||
r.set(r.New("NSArray", []uint64{}))
|
||||
|
||||
return true
|
||||
case "accounts":
|
||||
r.set(r.New("NSArray", []uint64{}))
|
||||
|
||||
return true
|
||||
case "accountWithIdentifier:":
|
||||
r.set(0)
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
if meta || (!r.kindOf(class, "ACAccount") && class != "ACAccountType" && class != "ACAccountCredential") {
|
||||
return false
|
||||
}
|
||||
|
||||
object := r.objects[receiver]
|
||||
|
||||
switch selector {
|
||||
case "initWithIdentifier:description:":
|
||||
object.Properties["identifier"] = r.arg(2)
|
||||
object.Properties["accountTypeDescription"] = r.arg(3)
|
||||
r.set(receiver)
|
||||
case "initWithAccountType:":
|
||||
object.Properties["identifier"] = r.New("NSString", r.newUUIDString())
|
||||
object.Properties["accountType"] = r.arg(2)
|
||||
object.Properties["accountProperties"] = r.New("NSMutableDictionary", map[string]uint64{})
|
||||
r.set(receiver)
|
||||
case "initWithPassword:":
|
||||
object.Properties["password"] = r.arg(2)
|
||||
r.set(receiver)
|
||||
case "accountPropertyForKey:":
|
||||
fields := r.objects[object.Properties["accountProperties"]].Value.(map[string]uint64)
|
||||
r.set(fields[r.String(r.arg(2))])
|
||||
case "setAccountProperty:forKey:":
|
||||
fields := r.objects[object.Properties["accountProperties"]].Value.(map[string]uint64)
|
||||
key := r.String(r.arg(3))
|
||||
|
||||
if r.arg(2) == 0 {
|
||||
delete(fields, key)
|
||||
} else {
|
||||
fields[key] = r.arg(2)
|
||||
}
|
||||
|
||||
r.set(0)
|
||||
case "accountType", "identifier", "username", "credential", "accountProperties", "authenticated", "active", "owningBundleID", "accountDescription", "parentAccount", "isDirty":
|
||||
r.set(object.Properties[selector])
|
||||
default:
|
||||
if strings.HasPrefix(selector, "set") && strings.HasSuffix(selector, ":") && strings.Count(selector, ":") == 1 {
|
||||
key := selector[3 : len(selector)-1]
|
||||
if len(key) < 2 || key[1] < 'A' || key[1] > 'Z' {
|
||||
key = strings.ToLower(key[:1]) + key[1:]
|
||||
}
|
||||
|
||||
object.Properties[key] = r.arg(2)
|
||||
r.set(0)
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package emulator
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// StoreAMDHeaders executes AppleMediaServices' Store anisette provider in the
|
||||
// guest. Type 2 is the Configurator AMD proof, not AuthKit's I-MD proof.
|
||||
func (r *Runtime) StoreAMDHeaders(endpoint string, hardwareID []byte, xpcHandler func(string, []byte) ([]byte, error)) (map[string]string, error) {
|
||||
parsed, err := url.Parse(endpoint)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Host == "" {
|
||||
return nil, errors.New("invalid Store AMD endpoint")
|
||||
}
|
||||
|
||||
if len(hardwareID) != 6 {
|
||||
return nil, errors.New("invalid Store AMD hardware identity")
|
||||
}
|
||||
|
||||
r.hardwareID = append([]byte(nil), hardwareID...)
|
||||
r.xpcSyncHandler = xpcHandler
|
||||
r.installStoreAMDAdapter()
|
||||
|
||||
request, err := r.Invoke(r.ClassAddress("NSURLRequest"), "requestWithURL:", r.New("NSURL", parsed.String()))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create Store AMD request: %w", err)
|
||||
}
|
||||
|
||||
value, err := r.Invoke(r.ClassAddress("AMSAnisette"), "_headersForRequest:account:type:", request, 0, 2)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generate Store AMD proof: %w", err)
|
||||
}
|
||||
|
||||
exported, err := r.Export(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("export Store AMD proof: %w", err)
|
||||
}
|
||||
|
||||
dictionary, ok := exported.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("AppleMediaServices returned no Store AMD proof (%T)", exported)
|
||||
}
|
||||
|
||||
result := make(map[string]string, 2)
|
||||
|
||||
for _, key := range []string{"X-Apple-AMD", "X-Apple-AMD-M"} {
|
||||
text, ok := dictionary[key].(string)
|
||||
if !ok || text == "" || len(text) > 8192 || strings.ContainsAny(text, "\r\n") {
|
||||
return nil, errors.New("AppleMediaServices returned an incomplete Store AMD proof")
|
||||
}
|
||||
|
||||
result[key] = text
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package emulator
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/internal/sap/unicorn"
|
||||
)
|
||||
|
||||
type asyncTask struct {
|
||||
continuation uint64
|
||||
handle, context, entry, closure, result uint64
|
||||
executor [2]uint64
|
||||
done bool
|
||||
}
|
||||
|
||||
func (r *Runtime) asyncSymbol(name string) bool {
|
||||
switch name {
|
||||
case "swift_task_localValueGet":
|
||||
r.set(r.taskLocalValue(r.arg(0)))
|
||||
case "swift_task_localValuePush":
|
||||
key, source, metadata := r.arg(0), r.arg(1), r.arg(2)
|
||||
size := r.read64(r.read64(metadata-8) + 64)
|
||||
value := r.alloc(size)
|
||||
|
||||
data, err := r.engine.MemRead(source, size)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if err = r.MemWrite(value, data); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if r.taskLocalFrames == nil {
|
||||
r.taskLocalFrames = map[uint64][]taskLocalBinding{}
|
||||
}
|
||||
|
||||
id := r.taskLocalOwner()
|
||||
r.taskLocalFrames[id] = append(r.taskLocalFrames[id], taskLocalBinding{key, value})
|
||||
r.set(0)
|
||||
case "swift_task_localValuePop":
|
||||
id := r.taskLocalOwner()
|
||||
|
||||
values := r.taskLocalFrames[id]
|
||||
if len(values) == 0 {
|
||||
panic("empty TaskLocal binding stack")
|
||||
}
|
||||
|
||||
r.taskLocalFrames[id] = values[:len(values)-1]
|
||||
case "swift_task_localsCopyTo":
|
||||
if r.tasks[r.arg(0)] == nil {
|
||||
panic("unknown task for local bindings")
|
||||
}
|
||||
|
||||
if r.taskLocalFrames == nil {
|
||||
r.taskLocalFrames = map[uint64][]taskLocalBinding{}
|
||||
}
|
||||
|
||||
r.taskLocalFrames[r.arg(0)] = append([]taskLocalBinding(nil), r.taskLocalFrames[r.taskLocalOwner()]...)
|
||||
|
||||
case "swift_continuation_init":
|
||||
if r.currentTask == nil {
|
||||
panic("continuation initialized outside task")
|
||||
}
|
||||
|
||||
context, flags := r.arg(0), r.arg(1)
|
||||
if flags&4 != 0 {
|
||||
panic("preawaited continuation unsupported")
|
||||
}
|
||||
|
||||
r.currentTask.continuation = context
|
||||
r.write64(context+16, (flags&1)|((flags&8)>>2))
|
||||
r.write64(context+24, 0)
|
||||
r.write64(context+32, 0)
|
||||
|
||||
if flags&2 == 0 {
|
||||
r.write64(context+48, 0)
|
||||
r.write64(context+56, 0)
|
||||
}
|
||||
|
||||
r.set(r.currentTask.handle)
|
||||
case "swift_continuation_resume", "swift_continuation_throwingResume", "swift_continuation_throwingResumeWithError":
|
||||
task := r.tasks[r.arg(0)]
|
||||
if task == nil || task.continuation == 0 {
|
||||
panic("unknown Swift continuation")
|
||||
}
|
||||
|
||||
context := task.continuation
|
||||
if r.read64(context+24) == 2 {
|
||||
panic("Swift continuation resumed twice")
|
||||
}
|
||||
|
||||
if name == "swift_continuation_throwingResumeWithError" {
|
||||
r.write64(context+32, r.arg(1))
|
||||
}
|
||||
|
||||
r.write64(context+24, 2)
|
||||
r.set(0)
|
||||
case "swift_continuation_await":
|
||||
context := r.arg(0)
|
||||
task := r.currentTask
|
||||
|
||||
if task == nil || task.continuation != context {
|
||||
panic("awaiting unknown Swift continuation")
|
||||
}
|
||||
|
||||
var resume func()
|
||||
resume = func() {
|
||||
if r.read64(context+24) == 2 {
|
||||
task.continuation = 0
|
||||
r.currentTask = task
|
||||
_ = r.engine.RegWrite(unicorn.RegX0+22, context)
|
||||
_ = r.engine.RegWrite(unicorn.RegPC, r.read64(context+8))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
block := r.nextPending()
|
||||
if block == 0 {
|
||||
panic("Swift continuation has no runnable completion")
|
||||
}
|
||||
|
||||
r.currentTask = nil
|
||||
r.pendingCallback(block, func() { r.currentTask = task; resume() })
|
||||
}
|
||||
resume()
|
||||
|
||||
case "swift_task_create":
|
||||
flags, options, resultType, descriptor, closure := r.arg(0), r.arg(1), r.arg(2), r.arg(3), r.arg(4)
|
||||
if options != 0 || flags&^uint64(0x1cff) != 0 {
|
||||
panic("unsupported Swift task options")
|
||||
}
|
||||
|
||||
bits := r.read64(descriptor)
|
||||
|
||||
size := bits >> 32
|
||||
if size < 16 || size > 1<<20 {
|
||||
panic("invalid Swift async context size")
|
||||
}
|
||||
|
||||
task := &asyncTask{handle: r.New("HostSwiftTask", nil), context: r.alloc(size+32) + 32, entry: uint64(int64(descriptor) + int64(int32(bits))), closure: closure}
|
||||
|
||||
valueSize := uint64(0)
|
||||
if resultType != 0 {
|
||||
valueSize = r.read64(r.read64(resultType-8) + 64)
|
||||
}
|
||||
|
||||
task.result = r.alloc(valueSize)
|
||||
|
||||
if r.tasks == nil {
|
||||
r.tasks = map[uint64]*asyncTask{}
|
||||
}
|
||||
|
||||
r.tasks[task.handle] = task
|
||||
if flags&(1<<10) != 0 {
|
||||
if r.taskLocalFrames == nil {
|
||||
r.taskLocalFrames = map[uint64][]taskLocalBinding{}
|
||||
}
|
||||
|
||||
r.taskLocalFrames[task.handle] = append([]taskLocalBinding(nil), r.taskLocalFrames[r.taskLocalOwner()]...)
|
||||
}
|
||||
|
||||
r.pending = append(r.pending, r.hostBlock(func() { r.startAsync(task) }))
|
||||
r.set(task.handle)
|
||||
_ = r.engine.RegWrite(unicorn.RegX1, task.context)
|
||||
case "swift_task_alloc":
|
||||
r.set(r.alloc(r.arg(0)))
|
||||
case "swift_task_dealloc":
|
||||
case "swift_task_getCurrent":
|
||||
if r.currentTask == nil {
|
||||
r.set(0)
|
||||
} else {
|
||||
r.set(r.currentTask.handle)
|
||||
}
|
||||
case "swift_task_isCancelled":
|
||||
r.set(boolValue(r.ctx.Err() != nil))
|
||||
case "swift_task_switch":
|
||||
if r.currentTask == nil {
|
||||
panic("executor switch outside a Swift task")
|
||||
}
|
||||
|
||||
function := r.arg(0)
|
||||
r.currentTask.executor = [2]uint64{r.arg(1), r.arg(2)}
|
||||
_ = r.engine.RegWrite(unicorn.RegPC, function)
|
||||
case "swift_task_getCurrentExecutor":
|
||||
executor := [2]uint64{}
|
||||
if r.currentTask != nil {
|
||||
executor = r.currentTask.executor
|
||||
}
|
||||
|
||||
r.set(executor[0])
|
||||
_ = r.engine.RegWrite(unicorn.RegX1, executor[1])
|
||||
case "swift_task_isCurrentExecutor":
|
||||
executor := [2]uint64{}
|
||||
if r.currentTask != nil {
|
||||
executor = r.currentTask.executor
|
||||
}
|
||||
|
||||
r.set(boolValue(executor == [2]uint64{r.arg(0), r.arg(1)}))
|
||||
default:
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
func (r *Runtime) startAsync(task *asyncTask) {
|
||||
if task.done {
|
||||
panic("attempt to restart a completed Swift task")
|
||||
}
|
||||
|
||||
saved := map[int]uint64{}
|
||||
|
||||
for _, reg := range []int{unicorn.RegSP, unicorn.RegLR, unicorn.RegX29, unicorn.RegX0 + 19, unicorn.RegX0 + 20, unicorn.RegX0 + 21, unicorn.RegX0 + 22, unicorn.RegX0 + 23, unicorn.RegX0 + 24, unicorn.RegX0 + 25, unicorn.RegX0 + 26, unicorn.RegX0 + 27, unicorn.RegX0 + 28} {
|
||||
v, err := r.engine.RegRead(reg)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
saved[reg] = v
|
||||
}
|
||||
|
||||
previous := r.currentTask
|
||||
r.currentTask = task
|
||||
completion := r.alloc(16)
|
||||
|
||||
if err := r.MemWrite(completion, []byte{0xc0, 0x03, 0x5f, 0xd6}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
r.callbacks[completion] = func() {
|
||||
if task.done {
|
||||
panic("Swift task completed twice")
|
||||
}
|
||||
|
||||
task.done = true
|
||||
|
||||
r.currentTask = previous
|
||||
for reg, v := range saved {
|
||||
if err := r.engine.RegWrite(reg, v); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
r.set(0)
|
||||
_ = r.engine.RegWrite(unicorn.RegPC, saved[unicorn.RegLR])
|
||||
}
|
||||
r.write64(task.context, 0)
|
||||
r.write64(task.context+8, completion)
|
||||
r.write64(task.context-32, task.result)
|
||||
r.write64(task.context-24, task.entry)
|
||||
r.write64(task.context-16, task.closure)
|
||||
_ = r.engine.RegWrite(unicorn.RegX0, task.result)
|
||||
_ = r.engine.RegWrite(unicorn.RegX0+20, task.closure)
|
||||
_ = r.engine.RegWrite(unicorn.RegX0+21, 0)
|
||||
_ = r.engine.RegWrite(unicorn.RegX0+22, task.context)
|
||||
_ = r.engine.RegWrite(unicorn.RegPC, task.entry)
|
||||
}
|
||||
|
||||
func (r *Runtime) taskLocalOwner() uint64 {
|
||||
if r.currentTask != nil {
|
||||
return r.currentTask.handle
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
func (r *Runtime) taskLocalValue(key uint64) uint64 {
|
||||
frames := r.taskLocalFrames[r.taskLocalOwner()]
|
||||
for i := len(frames) - 1; i >= 0; i-- {
|
||||
if frames[i].key == key {
|
||||
return frames[i].value
|
||||
}
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package emulator
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
func (r *Runtime) newCredentialTask(account, bag uint64, password string, source uint64) (uint64, error) {
|
||||
if r.ClassAddress("AMSVerifyCredentialsTask") == 0 {
|
||||
return 0, errors.New("authentication plugin is missing from the profile")
|
||||
}
|
||||
|
||||
options, err := r.Invoke(r.New("AMSAuthenticateOptions", nil), "init")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
fields := map[string]uint64{"setEphemeral:": 1, "setCanMakeAccountActive:": 0, "setAllowServerDialogs:": 0, "setPassword:": r.New("NSString", password), "setCredentialSource:": source}
|
||||
for selector, value := range fields {
|
||||
if _, err = r.Invoke(options, selector, value); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
// These entry points consume account/options/bag; the full task initializer
|
||||
// additionally starts analytics and account persistence services. Keep the
|
||||
// request boundary independent of host analytics and account persistence.
|
||||
task, err := r.Invoke(r.New("AMSVerifyCredentialsTask", nil), "init")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
for name, value := range map[string]uint64{"_account": account, "_options": options, "_bag": bag} {
|
||||
if err = r.SetIvar(task, name, value); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
return task, nil
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package emulator
|
||||
|
||||
import "time"
|
||||
|
||||
func (r *Runtime) frozenBagFromValues(values map[string]any) (uint64, error) {
|
||||
var err error
|
||||
|
||||
builder := r.New("AMSBagFrozenDataSourceBuilder", nil)
|
||||
fields := map[string]uint64{"setData:": r.importValue(values), "setProfile:": r.New("NSString", "AMSPurchase"), "setProfileVersion:": r.New("NSString", "1"), "setExpirationDate:": r.New("NSDate", time.Now().Add(5*time.Minute))}
|
||||
|
||||
for selector, value := range fields {
|
||||
if _, err = r.Invoke(builder, selector, value); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
return r.Invoke(builder, "createFrozenBag")
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,136 @@
|
||||
package emulator
|
||||
|
||||
import "github.com/majd/ipatool/v2/internal/sap/unicorn"
|
||||
|
||||
func (r *Runtime) callback(block uint64, args []uint64, after func()) {
|
||||
r.callbackFunction(r.read64(block+16), append([]uint64{block}, args...), after)
|
||||
}
|
||||
func (r *Runtime) callbackFunction(function uint64, args []uint64, after func()) {
|
||||
link, err := r.engine.RegRead(unicorn.RegLR)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
resume := r.alloc(16)
|
||||
if err = r.MemWrite(resume, []byte{0xc0, 0x03, 0x5f, 0xd6}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
r.callbacks[resume] = func() {
|
||||
delete(r.callbacks, resume)
|
||||
_ = r.engine.RegWrite(unicorn.RegLR, link)
|
||||
_ = r.engine.RegWrite(unicorn.RegPC, link)
|
||||
|
||||
after()
|
||||
}
|
||||
for i, v := range args {
|
||||
if err = r.engine.RegWrite(unicorn.RegX0+i, v); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
_ = r.engine.RegWrite(unicorn.RegLR, resume)
|
||||
_ = r.engine.RegWrite(unicorn.RegPC, function)
|
||||
}
|
||||
|
||||
func (r *Runtime) copyBlock(block uint64, after func(uint64)) {
|
||||
if block == 0 {
|
||||
after(0)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
flags := uint32(r.read64(block + 8))
|
||||
if flags&(1<<28) != 0 {
|
||||
after(block)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
descriptor := r.read64(block + 24)
|
||||
|
||||
size := r.read64(descriptor + 8)
|
||||
if size < 32 || size > 1<<20 {
|
||||
panic("invalid guest block size")
|
||||
}
|
||||
|
||||
copied := r.alloc(size)
|
||||
|
||||
data, err := r.engine.MemRead(block, size)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if err = r.MemWrite(copied, data); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if flags&(1<<25) != 0 {
|
||||
r.callbackFunction(r.read64(descriptor+16), []uint64{copied, block}, func() { after(copied) })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
after(copied)
|
||||
}
|
||||
|
||||
func (r *Runtime) copyValue(value uint64, after func(uint64)) {
|
||||
if value == 0 {
|
||||
after(0)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if obj := r.objects[value]; obj != nil {
|
||||
if entry := r.lookup(obj.Class, "copyWithZone:", false); entry != 0 {
|
||||
r.callbackFunction(entry, []uint64{value, r.selector("copyWithZone:"), 0}, func() { after(r.arg(0)) })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
after(value)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
r.copyBlock(value, after)
|
||||
}
|
||||
|
||||
func (r *Runtime) copyByref(value uint64, after func(uint64)) {
|
||||
forwarded := r.read64(value + 8)
|
||||
if forwarded != 0 && forwarded != value {
|
||||
after(forwarded)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
header := r.read64(value + 16)
|
||||
size := header >> 32
|
||||
flags := uint32(header)
|
||||
|
||||
if size < 24 || size > 1<<20 {
|
||||
panic("invalid byref capture size")
|
||||
}
|
||||
|
||||
copied := r.alloc(size)
|
||||
|
||||
data, err := r.engine.MemRead(value, size)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if err = r.MemWrite(copied, data); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
r.write64(copied+8, copied)
|
||||
r.write64(value+8, copied)
|
||||
|
||||
if flags&(1<<25) != 0 {
|
||||
r.callbackFunction(r.read64(value+24), []uint64{copied, value}, func() { after(copied) })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
after(copied)
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
package emulator
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
// Request keeps caller session storage and package assembly outside the guest.
|
||||
// Encoding, protocol handling and response interpretation execute in Apple code.
|
||||
type Request struct {
|
||||
Timeout time.Duration
|
||||
URL, Method, Operation, Format string
|
||||
Headers http.Header
|
||||
Parameters map[string]any
|
||||
Body, HardwareID []byte
|
||||
Bag map[string]any
|
||||
Sign func([]byte) ([]byte, error)
|
||||
Transport func(*http.Request) (*http.Response, error)
|
||||
Stream, Raw, NoRedirects bool
|
||||
}
|
||||
|
||||
//nolint:nonamedreturns // Recovery and streamed-body cleanup must update the returned error.
|
||||
func (r *Runtime) Execute(input Request) (response *http.Response, err error) {
|
||||
defer func() {
|
||||
if failure := recover(); failure != nil {
|
||||
err = recoveredError("Store request preparation", failure)
|
||||
}
|
||||
|
||||
if err != nil && r.lastResponse != nil && r.streamResponse {
|
||||
_ = r.lastResponse.Body.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
if input.Transport == nil {
|
||||
return nil, errors.New("store transport is not configured")
|
||||
}
|
||||
|
||||
if len(input.HardwareID) != 6 {
|
||||
return nil, errors.New("invalid Store hardware identity")
|
||||
}
|
||||
|
||||
r.hardwareID = append([]byte(nil), input.HardwareID...)
|
||||
r.transport = input.Transport
|
||||
r.streamResponse = input.Stream
|
||||
r.noRedirects = input.NoRedirects
|
||||
r.authRequest = input.Operation == "authenticate"
|
||||
|
||||
var saved map[string]any
|
||||
if dsid := input.Headers.Get("X-Dsid"); dsid != "" {
|
||||
saved = map[string]any{"directoryServicesIdentifier": dsid, "passwordToken": input.Headers.Get("X-Token"), "storeFront": input.Headers.Get("X-Apple-Store-Front"), "email": ""}
|
||||
}
|
||||
|
||||
account, err := r.ephemeralAccount(saved)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var bag uint64
|
||||
|
||||
if len(input.Bag) > 0 {
|
||||
values := map[string]any{}
|
||||
for key, value := range input.Bag {
|
||||
values[key] = value
|
||||
}
|
||||
|
||||
if nested, ok := values["urlBag"].(map[string]any); ok {
|
||||
for key, value := range nested {
|
||||
values[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
if input.Operation == "purchase" {
|
||||
values["buyProduct"] = input.URL
|
||||
}
|
||||
|
||||
bag, err = r.frozenBagFromValues(values)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
session, err := r.newSession()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if input.Operation != "authenticate" {
|
||||
if _, err = r.Invoke(session, "setDelegate:", r.interactiveDelegate()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
parameters := input.Parameters
|
||||
|
||||
if input.Operation == "authenticate" {
|
||||
if input.Sign == nil {
|
||||
return nil, errors.New("authentication requires a SAP signer")
|
||||
}
|
||||
|
||||
if _, err = r.Invoke(account, "setUsername:", r.importValue(parameters["appleId"])); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
task, e := r.newCredentialTask(account, bag, fmt.Sprint(parameters["password"]), 0)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
value, e := r.Invoke(task, "_createAuthenticateRequestParametersForAccount:", account)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
built, e := r.Export(value)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
native := built.(map[string]any)
|
||||
if !strings.EqualFold(fmt.Sprint(native["guid"]), hex.EncodeToString(input.HardwareID)) {
|
||||
return nil, errors.New("authentication hardware identity mismatch")
|
||||
}
|
||||
// Preserve the CLI's second credential attempt and 2FA retry contract.
|
||||
for _, key := range []string{"attempt", "why"} {
|
||||
if value, ok := parameters[key]; ok {
|
||||
native[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
parameters = native
|
||||
|
||||
if _, err = r.Invoke(session, "setDelegate:", task); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
var request uint64
|
||||
if input.Operation == "purchase" {
|
||||
request, err = r.purchaseRequest(account, bag, input)
|
||||
} else if parameters != nil {
|
||||
request, err = r.encodeRequest(account, bag, input.Method, input.URL, parameters)
|
||||
} else {
|
||||
request, err = r.Invoke(r.New("AMSURLRequest", nil), "initWithURL:cachePolicy:timeoutInterval:", r.New("NSURL", input.URL), 0)
|
||||
if err == nil {
|
||||
_, err = r.Invoke(request, "setHTTPMethod:", r.New("NSString", input.Method))
|
||||
}
|
||||
|
||||
if err == nil && input.Body != nil {
|
||||
_, err = r.Invoke(request, "setHTTPBody:", r.New("NSData", input.Body))
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = r.configureRequest(request, account, bag, input.Stream || input.Raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for key, values := range input.Headers {
|
||||
if strings.EqualFold(key, "Content-Length") {
|
||||
continue
|
||||
}
|
||||
|
||||
if _, err = r.Invoke(request, "setValue:forHTTPHeaderField:", r.New("NSString", strings.Join(values, ", ")), r.New("NSString", key)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if input.Sign != nil {
|
||||
body, e := r.Invoke(request, "HTTPBody")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
if body == 0 {
|
||||
return nil, errors.New("signed request has no body")
|
||||
}
|
||||
|
||||
signature, e := input.Sign(r.objects[body].Value.([]byte))
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("sign Store request: %w", e)
|
||||
}
|
||||
|
||||
if _, err = r.Invoke(request, "setValue:forHTTPHeaderField:", r.New("NSString", base64.StdEncoding.EncodeToString(signature)), r.New("NSString", "X-Apple-ActionSignature")); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
result, requestErr := r.sendRequest(session, request)
|
||||
|
||||
if r.transportError != nil {
|
||||
return nil, r.transportError
|
||||
}
|
||||
|
||||
if requestErr != nil {
|
||||
// A decoded finance error is a real server response. Return its original
|
||||
// body to the compatibility layer for the existing 2FA/license sentinels.
|
||||
var finance *FrameworkError
|
||||
if errors.As(requestErr, &finance) && r.lastResponse != nil && !input.Stream {
|
||||
return r.lastResponse, nil
|
||||
}
|
||||
|
||||
return nil, requestErr
|
||||
}
|
||||
|
||||
if r.lastResponse == nil {
|
||||
return nil, errors.New("store session returned no HTTP response")
|
||||
}
|
||||
|
||||
if input.Stream || input.Raw {
|
||||
return r.lastResponse, nil
|
||||
}
|
||||
|
||||
object, e := r.Invoke(result, "object")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
if object != 0 {
|
||||
value, e := r.Export(object)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
var encoded []byte
|
||||
if input.Format == "json" || strings.Contains(strings.ToLower(r.lastResponse.Header.Get("Content-Type")), "json") {
|
||||
encoded, e = json.Marshal(value)
|
||||
} else {
|
||||
encoded, e = plist.Marshal(value, plist.XMLFormat)
|
||||
}
|
||||
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("copy decoded Store response: %w", e)
|
||||
}
|
||||
|
||||
r.lastResponse.Body = io.NopCloser(bytes.NewReader(encoded))
|
||||
r.lastResponse.ContentLength = int64(len(encoded))
|
||||
r.lastResponse.Header.Del("Content-Encoding")
|
||||
r.lastResponse.Header.Del("Content-Length")
|
||||
}
|
||||
|
||||
return r.lastResponse, nil
|
||||
}
|
||||
|
||||
func (r *Runtime) encodeRequest(account, bag uint64, method, endpoint string, parameters map[string]any) (uint64, error) {
|
||||
encoder, err := r.Invoke(r.New("AMSURLRequestEncoder", nil), "initWithBag:", bag)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
for selector, value := range map[string]uint64{"setAccount:": account, "setRequestEncoding:": 2, "setAnisetteType:": 0, "setMescalType:": 0, "setEnableRemoteSecuritySigning:": 0, "setUrlKnownToBeTrusted:": 1, "setShouldSetCookieHeader:": 0, "setShouldSetStorefrontHeader:": 0, "setDisableLoadURLMetrics:": 1} {
|
||||
if _, err = r.Invoke(encoder, selector, value); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
methodID := map[string]uint64{"GET": 2, "POST": 4, "PUT": 5}[method]
|
||||
if methodID == 0 {
|
||||
return 0, errors.New("unsupported encoded Store request method")
|
||||
}
|
||||
|
||||
promise, err := r.Invoke(encoder, "requestWithMethod:URL:parameters:", methodID, r.New("NSURL", endpoint), r.importValue(parameters))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return r.resolveAddress(promise)
|
||||
}
|
||||
|
||||
func (r *Runtime) purchaseRequest(account, bag uint64, input Request) (uint64, error) {
|
||||
if bag == 0 {
|
||||
return 0, errors.New("purchase requires a Store bag")
|
||||
}
|
||||
|
||||
if fmt.Sprint(input.Parameters["price"]) != "0" || input.Parameters["productType"] != "C" {
|
||||
return 0, errors.New("purchasing paid apps is not supported")
|
||||
}
|
||||
|
||||
params, err := r.Invoke(r.New("AMSBuyParams", nil), "init")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
for key, value := range input.Parameters {
|
||||
if _, err = r.Invoke(params, "setParameter:forKey:", r.importValue(value), r.New("NSString", key)); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
purchase, err := r.Invoke(r.New("AMSPurchase", nil), "initWithPurchaseType:buyParams:", 0, params)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if _, err = r.Invoke(purchase, "setAccount:", account); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
info, err := r.Invoke(r.New("AMSPurchaseInfo", nil), "initWithPurchase:", purchase)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
for selector, value := range map[string]uint64{"setAddKBSync:": 0, "setHasBeenAuthedForBuy:": 1} {
|
||||
if _, err = r.Invoke(info, selector, value); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
encoder, err := r.configuredPurchaseEncoder(info, bag)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
for selector, value := range map[string]uint64{"setAnisetteType:": 0, "setMescalType:": 0, "setUrlKnownToBeTrusted:": 1, "setEnableRemoteSecuritySigning:": 0, "setDisableLoadURLMetrics:": 1, "setCompressRequestBody:": 0, "setShouldSetStorefrontHeader:": 0, "setShouldSetCookieHeader:": 0} {
|
||||
if _, err = r.Invoke(encoder, selector, value); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
promise, err := r.Invoke(encoder, "encodeRequest")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
request, err := r.resolveAddress(promise)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
body, err := r.Invoke(request, "HTTPBody")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
var encoded map[string]any
|
||||
|
||||
if body == 0 {
|
||||
return 0, errors.New("purchase encoder returned no body")
|
||||
}
|
||||
|
||||
if _, err = plist.Unmarshal(r.objects[body].Value.([]byte), &encoded); err != nil {
|
||||
return 0, errors.New("invalid encoded purchase")
|
||||
}
|
||||
|
||||
for _, key := range []string{"price", "salableAdamId", "pricingParameters", "productType"} {
|
||||
if fmt.Sprint(encoded[key]) != fmt.Sprint(input.Parameters[key]) {
|
||||
return 0, errors.New("purchase encoder changed product or price")
|
||||
}
|
||||
}
|
||||
|
||||
return request, nil
|
||||
}
|
||||
|
||||
func allowedURL(value *url.URL, authenticated bool) bool {
|
||||
if value == nil || value.User != nil || value.Fragment != "" {
|
||||
return false
|
||||
}
|
||||
|
||||
host := strings.ToLower(value.Hostname())
|
||||
if !authenticated {
|
||||
// Package/artwork URLs are supplied by the Store response. Retain the
|
||||
// downloader's support for signed CDN URLs without binding it to one CDN.
|
||||
return host != "" && (value.Scheme == "https" || value.Scheme == "http")
|
||||
}
|
||||
|
||||
apple := host == "apple.com" || strings.HasSuffix(host, ".apple.com") || strings.HasSuffix(host, ".mzstatic.com") || strings.HasSuffix(host, ".cdn-apple.com")
|
||||
|
||||
return apple && value.Scheme == "https"
|
||||
}
|
||||
|
||||
type FrameworkError struct {
|
||||
Domain, Message string
|
||||
Code int64
|
||||
}
|
||||
|
||||
func (e *FrameworkError) Error() string {
|
||||
if e.Message != "" {
|
||||
return fmt.Sprintf("%s (%s/%d)", e.Message, e.Domain, e.Code)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("Store framework error %s/%d", e.Domain, e.Code)
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package emulator
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/flate"
|
||||
"compress/gzip"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
)
|
||||
|
||||
type inflateStream struct {
|
||||
bits int64
|
||||
input, output []byte
|
||||
position int
|
||||
decoded bool
|
||||
}
|
||||
|
||||
func (r *Runtime) write32(address uint64, value uint32) {
|
||||
var b [4]byte
|
||||
|
||||
binary.LittleEndian.PutUint32(b[:], value)
|
||||
|
||||
if err := r.MemWrite(address, b[:]); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
func (r *Runtime) compressionSymbol(name string) bool {
|
||||
switch name {
|
||||
case "inflateInit2_":
|
||||
if r.arg(3) != 112 {
|
||||
panic("unsupported zlib stream ABI")
|
||||
}
|
||||
|
||||
if r.inflaters == nil {
|
||||
r.inflaters = map[uint64]*inflateStream{}
|
||||
}
|
||||
|
||||
r.inflaters[r.arg(0)] = &inflateStream{bits: int64(int32(r.arg(1)))}
|
||||
r.write64(r.arg(0)+16, 0)
|
||||
r.write64(r.arg(0)+40, 0)
|
||||
r.set(0)
|
||||
case "inflateEnd":
|
||||
delete(r.inflaters, r.arg(0))
|
||||
r.set(0)
|
||||
case "inflate":
|
||||
address := r.arg(0)
|
||||
|
||||
state := r.inflaters[address]
|
||||
if state == nil {
|
||||
panic("uninitialized inflate stream")
|
||||
}
|
||||
|
||||
size := uint64(uint32(r.read64(address + 8)))
|
||||
if size > 32<<20 {
|
||||
panic("inflate input exceeds budget")
|
||||
}
|
||||
|
||||
if size != 0 {
|
||||
p := r.read64(address)
|
||||
|
||||
data, err := r.engine.MemRead(p, size)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
state.input = append(state.input, data...)
|
||||
|
||||
r.write64(address, p+size)
|
||||
r.write32(address+8, 0)
|
||||
r.write64(address+16, r.read64(address+16)+size)
|
||||
}
|
||||
|
||||
if !state.decoded {
|
||||
var reader io.ReadCloser
|
||||
|
||||
var err error
|
||||
|
||||
switch state.bits {
|
||||
case 31, 47:
|
||||
reader, err = gzip.NewReader(bytes.NewReader(state.input))
|
||||
case 15:
|
||||
reader, err = zlib.NewReader(bytes.NewReader(state.input))
|
||||
case -15:
|
||||
reader = flate.NewReader(bytes.NewReader(state.input))
|
||||
default:
|
||||
panic("unsupported inflate window size")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
r.set(^uint64(2))
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
state.output, err = io.ReadAll(io.LimitReader(reader, (32<<20)+1))
|
||||
_ = reader.Close()
|
||||
|
||||
if err != nil {
|
||||
r.set(^uint64(2))
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if len(state.output) > 32<<20 {
|
||||
panic("decompressed response exceeds runtime limit")
|
||||
}
|
||||
|
||||
state.decoded = true
|
||||
}
|
||||
|
||||
size = uint64(uint32(r.read64(address + 32)))
|
||||
count := min(size, uint64(len(state.output)-state.position))
|
||||
out := r.read64(address + 24)
|
||||
|
||||
if count != 0 {
|
||||
if err := r.MemWrite(out, state.output[state.position:state.position+int(count)]); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
state.position += int(count)
|
||||
r.write64(address+24, out+count)
|
||||
r.write32(address+32, uint32(size-count))
|
||||
r.write64(address+40, r.read64(address+40)+count)
|
||||
r.set(boolValue(state.position == len(state.output)))
|
||||
default:
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
Loaded 100 of 243 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user