Compare commits

...
11 Commits
157 changed files with 76971 additions and 2066 deletions

No files matched your search

+4 -4
View File
@@ -17,7 +17,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go build -o ipatool-$GOOS-$GOARCH.exe
env:
@@ -38,7 +38,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go build -o ipatool-linux-$GOARCH
env:
@@ -54,7 +54,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go build -o ipatool-$GOOS-$GOARCH
env:
@@ -70,7 +70,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: brew install ldid cmake
- run: ./tools/build-ios.sh
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go build -o ipatool
env:
+2 -2
View File
@@ -13,9 +13,9 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go generate github.com/majd/ipatool/...
- run: go generate ./...
- uses: golangci/golangci-lint-action@v8
with:
version: v2.9
+6 -6
View File
@@ -21,10 +21,10 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go generate github.com/majd/ipatool/...
- run: go test -v github.com/majd/ipatool/...
- run: go generate ./...
- run: go test -v -timeout 20m ./...
build:
name: Build
runs-on: macos-latest
@@ -33,7 +33,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-windows-arm64.exe
env:
@@ -97,7 +97,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
go-version: "1.26.5"
cache: true
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-linux-$GOARCH
env:
@@ -116,7 +116,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: brew install ldid cmake
- run: ./tools/build-ios.sh "ipatool-$VERSION-ios-arm64"
+42 -3
View File
@@ -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
View File
@@ -4,4 +4,4 @@
.vscode/
.idea/
**/*_mock.go
exp/
exp/
+16
View File
@@ -50,6 +50,7 @@ Available Commands:
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
@@ -67,6 +68,21 @@ 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.
+36 -22
View File
@@ -1,6 +1,6 @@
module github.com/majd/ipatool/v2
go 1.25.0
go 1.26.5
require (
github.com/avast/retry-go v3.0.0+incompatible
@@ -8,36 +8,46 @@ require (
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/sys v0.45.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-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
@@ -45,41 +55,45 @@ require (
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/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.20.0 // indirect
golang.org/x/text v0.37.0 // indirect
golang.org/x/sync v0.23.0 // indirect
golang.org/x/time v0.15.0 // indirect
golang.org/x/tools v0.44.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
+148 -56
View File
@@ -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=
@@ -52,85 +81,117 @@ 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/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 h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
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/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/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
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=
@@ -139,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=
@@ -150,12 +213,23 @@ 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=
@@ -166,49 +240,67 @@ 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/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.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
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/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.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
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=
+641
View File
@@ -0,0 +1,641 @@
//nolint:wsl // Binary format parsing is clearer when related bounds checks remain adjacent.
package assets
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/ecdh"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/hkdf"
"crypto/hmac"
"crypto/hpke"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/binary"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"github.com/go-compressions/lzfse"
)
const (
aeaMagic = "AEA1"
aeaSymmetricProfile = 1
aeaMainKeyInfo = "AEA_AMK"
aeaRootKeyInfo = "AEA_RHEK"
aeaClusterKeyInfo = "AEA_CK"
aeaClusterHeaderKeyInfo = "AEA_CHEK"
aeaSegmentKeyInfo = "AEA_SK"
aeaLZFSECompression = 'e'
aeaSHA256Checksum = 2
aeaDecodedSegmentCacheCount = 64
maxAEAAuthDataSize = 1 << 20
maxFCSKeySize = 64 << 10
)
type aeaHeader struct {
Magic [4]byte
ProfileAndScryptStrength uint32
AuthDataLength uint32
}
type aeaMAC [sha256.Size]byte
type encryptedAEARootHeader struct {
MAC aeaMAC
Data [48]byte
ClusterMAC aeaMAC
}
type aeaRootHeader struct {
FileSize uint64
EncryptedSize uint64
SegmentSize uint32
SegmentsPerCluster uint32
Compression uint8
Checksum uint8
_ [22]byte
}
type aeaHeaderKey struct {
MAC aeaMAC
Key [32]byte
IV [aes.BlockSize]byte
}
type aeaSegmentHeader struct {
DecompressedSize uint32
CompressedSize uint32
Checksum [sha256.Size]byte
}
type aeaSegment struct {
inputOffset int64
outputOffset int64
compressedSize uint32
decompressedSize uint32
checksum [sha256.Size]byte
mac aeaMAC
cluster uint32
index uint32
}
type aeaReader struct {
source io.ReaderAt
size int64
segmentSize uint32
mainKey []byte
segments []aeaSegment
cache map[int][]byte
cacheOrder []int
cacheMu sync.Mutex
}
type fcsResponse struct {
EncRequest string `json:"enc-request"`
WrappedKey string `json:"wrapped-key"`
}
func newAEAReader(ctx context.Context, client *http.Client, source io.ReaderAt, sourceSize int64) (*aeaReader, error) {
var header aeaHeader
if err := readBinaryAt(source, 0, &header); err != nil {
return nil, fmt.Errorf("read AEA header: %w", err)
}
if string(header.Magic[:]) != aeaMagic {
return nil, fmt.Errorf("invalid AEA magic %q", header.Magic)
}
if header.ProfileAndScryptStrength&0xffffff != aeaSymmetricProfile {
return nil, fmt.Errorf("unsupported AEA profile %d", header.ProfileAndScryptStrength&0xffffff)
}
if header.AuthDataLength > maxAEAAuthDataSize {
return nil, fmt.Errorf("AEA authentication data is too large: %d", header.AuthDataLength)
}
headerSize := int64(binary.Size(header))
authData := make([]byte, header.AuthDataLength)
if _, err := source.ReadAt(authData, headerSize); err != nil {
return nil, fmt.Errorf("read AEA authentication data: %w", err)
}
metadata, err := parseAEAMetadata(authData)
if err != nil {
return nil, err
}
symmetricKey, err := resolveAEASymmetricKey(ctx, client, metadata)
if err != nil {
return nil, err
}
mainSaltOffset := headerSize + int64(len(authData))
mainSalt := make([]byte, sha256.Size)
if _, err := source.ReadAt(mainSalt, mainSaltOffset); err != nil {
return nil, fmt.Errorf("read AEA main salt: %w", err)
}
mainKey, err := deriveAEAKey(symmetricKey, mainSalt, binary.LittleEndian.AppendUint32([]byte(aeaMainKeyInfo), header.ProfileAndScryptStrength), len(symmetricKey))
if err != nil {
return nil, fmt.Errorf("derive AEA main key: %w", err)
}
rootOffset := mainSaltOffset + int64(len(mainSalt))
var encryptedRoot encryptedAEARootHeader
if err := readBinaryAt(source, rootOffset, &encryptedRoot); err != nil {
return nil, fmt.Errorf("read encrypted AEA root header: %w", err)
}
rootKey, err := deriveAEAHeaderKey(mainKey, []byte(aeaRootKeyInfo))
if err != nil {
return nil, fmt.Errorf("derive AEA root key: %w", err)
}
rootSalt := make([]byte, 0, len(encryptedRoot.ClusterMAC)+len(authData))
rootSalt = append(rootSalt, encryptedRoot.ClusterMAC[:]...)
rootSalt = append(rootSalt, authData...)
computedRootMAC := calculateAEAMAC(rootKey.MAC[:], encryptedRoot.Data[:], rootSalt)
if !hmac.Equal(encryptedRoot.MAC[:], computedRootMAC[:]) {
return nil, errors.New("AEA root header failed authentication")
}
rootData, err := decryptAEACTR(encryptedRoot.Data[:], rootKey.Key[:], rootKey.IV[:])
if err != nil {
return nil, fmt.Errorf("decrypt AEA root header: %w", err)
}
var root aeaRootHeader
if err := binary.Read(bytes.NewReader(rootData), binary.LittleEndian, &root); err != nil {
return nil, fmt.Errorf("decode AEA root header: %w", err)
}
if root.FileSize == 0 || root.FileSize > ^uint64(0)>>1 {
return nil, fmt.Errorf("invalid AEA output size %d", root.FileSize)
}
if root.EncryptedSize != uint64(sourceSize) {
return nil, fmt.Errorf("AEA encrypted size is %d, expected %d", root.EncryptedSize, sourceSize)
}
if root.SegmentSize == 0 || root.SegmentsPerCluster == 0 {
return nil, errors.New("AEA has an invalid segment layout")
}
if root.Compression != aeaLZFSECompression || root.Checksum != aeaSHA256Checksum {
return nil, fmt.Errorf("unsupported AEA encoding: compression %q, checksum %d", root.Compression, root.Checksum)
}
reader := &aeaReader{
source: source,
size: int64(root.FileSize),
segmentSize: root.SegmentSize,
mainKey: mainKey,
segments: make([]aeaSegment, (root.FileSize+uint64(root.SegmentSize)-1)/uint64(root.SegmentSize)),
cache: make(map[int][]byte, aeaDecodedSegmentCacheCount),
}
clusterOffset := rootOffset + int64(binary.Size(encryptedRoot))
if err := reader.indexClusters(clusterOffset, encryptedRoot.ClusterMAC, root, sourceSize); err != nil {
return nil, err
}
return reader, nil
}
func parseAEAMetadata(data []byte) (map[string][]byte, error) {
metadata := make(map[string][]byte)
reader := bytes.NewReader(data)
for reader.Len() != 0 {
var length uint32
if err := binary.Read(reader, binary.LittleEndian, &length); err != nil {
return nil, fmt.Errorf("read AEA metadata length: %w", err)
}
if length < 5 || uint64(length-4) > uint64(reader.Len()) {
return nil, fmt.Errorf("invalid AEA metadata record length %d", length)
}
record := make([]byte, length-4)
if _, err := io.ReadFull(reader, record); err != nil {
return nil, fmt.Errorf("read AEA metadata record: %w", err)
}
key, value, ok := bytes.Cut(record, []byte{0})
if !ok || len(key) == 0 {
return nil, errors.New("invalid AEA metadata record")
}
metadata[string(key)] = value
}
return metadata, nil
}
// resolveAEASymmetricKey downloads the Apple-published FCS P-256 private key
// identified by the AEA metadata. That key is the HPKE recipient key for this
// image's wrapped symmetric key; the unwrapped key is then used to derive the
// AES and HMAC keys that decrypt and authenticate the AEA headers and segments.
// It is restore-image key material, not a user credential.
func resolveAEASymmetricKey(ctx context.Context, client *http.Client, metadata map[string][]byte) ([]byte, error) {
keyURLData, ok := metadata["com.apple.wkms.fcs-key-url"]
if !ok {
return nil, errors.New("AEA metadata does not contain an FCS key URL")
}
keyURL, err := url.Parse(string(keyURLData))
if err != nil || keyURL.Scheme != "https" || keyURL.Hostname() != "wkms-public.apple.com" {
return nil, fmt.Errorf("invalid Apple FCS key URL %q", keyURLData)
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, keyURL.String(), nil)
if err != nil {
return nil, fmt.Errorf("create Apple FCS key request: %w", err)
}
response, err := client.Do(request)
if err != nil {
return nil, fmt.Errorf("download Apple FCS key: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("download Apple FCS key: server returned %s", response.Status)
}
pemData, err := io.ReadAll(io.LimitReader(response.Body, maxFCSKeySize+1))
if err != nil {
return nil, fmt.Errorf("read Apple FCS key: %w", err)
}
if len(pemData) > maxFCSKeySize {
return nil, errors.New("apple FCS key response is too large")
}
block, _ := pem.Decode(pemData)
if block == nil {
return nil, errors.New("apple FCS key response is not PEM encoded")
}
privateKeyValue, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("parse Apple FCS private key: %w", err)
}
privateKey, ok := privateKeyValue.(*ecdsa.PrivateKey)
if !ok || privateKey.Curve != elliptic.P256() {
return nil, errors.New("apple FCS key is not a P-256 private key")
}
responseData, ok := metadata["com.apple.wkms.fcs-response"]
if !ok {
return nil, errors.New("AEA metadata does not contain an FCS response")
}
var wrapped fcsResponse
if err := json.Unmarshal(responseData, &wrapped); err != nil {
return nil, fmt.Errorf("parse AEA FCS response: %w", err)
}
encapsulation, err := base64.StdEncoding.DecodeString(wrapped.EncRequest)
if err != nil {
return nil, fmt.Errorf("decode AEA FCS encapsulation: %w", err)
}
wrappedKey, err := base64.StdEncoding.DecodeString(wrapped.WrappedKey)
if err != nil {
return nil, fmt.Errorf("decode AEA wrapped key: %w", err)
}
kem := hpke.DHKEM(ecdh.P256())
ecdhPrivateKey, err := privateKey.ECDH()
if err != nil {
return nil, fmt.Errorf("convert AEA FCS private key: %w", err)
}
hpkePrivateKey, err := kem.NewPrivateKey(ecdhPrivateKey.Bytes())
if err != nil {
return nil, fmt.Errorf("load AEA FCS private key: %w", err)
}
recipient, err := hpke.NewRecipient(encapsulation, hpkePrivateKey, hpke.HKDFSHA256(), hpke.AES256GCM(), nil)
if err != nil {
return nil, fmt.Errorf("initialize AEA FCS recipient: %w", err)
}
symmetricKey, err := recipient.Open(nil, wrappedKey)
if err != nil {
return nil, fmt.Errorf("unwrap AEA symmetric key: %w", err)
}
return symmetricKey, nil
}
func (r *aeaReader) indexClusters(offset int64, clusterMAC aeaMAC, root aeaRootHeader, sourceSize int64) error {
const segmentHeaderSize = 8 + sha256.Size
headerSize := int64(segmentHeaderSize*root.SegmentsPerCluster + sha256.Size + sha256.Size*root.SegmentsPerCluster)
outputSize := uint64(0)
clusterIndex := uint32(0)
for outputSize < root.FileSize {
if offset < 0 || headerSize > sourceSize-offset {
return errors.New("AEA cluster header extends beyond the encrypted image")
}
headerData := make([]byte, headerSize)
if _, err := r.source.ReadAt(headerData, offset); err != nil {
return fmt.Errorf("read AEA cluster %d header: %w", clusterIndex, err)
}
clusterKey, err := deriveAEAKey(r.mainKey, nil, binary.LittleEndian.AppendUint32([]byte(aeaClusterKeyInfo), clusterIndex), len(r.mainKey))
if err != nil {
return fmt.Errorf("derive AEA cluster %d key: %w", clusterIndex, err)
}
clusterHeaderKey, err := deriveAEAHeaderKey(clusterKey, []byte(aeaClusterHeaderKeyInfo))
if err != nil {
return fmt.Errorf("derive AEA cluster %d header key: %w", clusterIndex, err)
}
encryptedHeadersSize := int(segmentHeaderSize * root.SegmentsPerCluster)
encryptedHeaders := headerData[:encryptedHeadersSize]
var nextClusterMAC aeaMAC
copy(nextClusterMAC[:], headerData[encryptedHeadersSize:encryptedHeadersSize+sha256.Size])
segmentMACData := headerData[encryptedHeadersSize+sha256.Size:]
hmacSalt := make([]byte, 0, len(nextClusterMAC)+len(segmentMACData))
hmacSalt = append(hmacSalt, nextClusterMAC[:]...)
hmacSalt = append(hmacSalt, segmentMACData...)
computedMAC := calculateAEAMAC(clusterHeaderKey.MAC[:], encryptedHeaders, hmacSalt)
if !hmac.Equal(clusterMAC[:], computedMAC[:]) {
return fmt.Errorf("AEA cluster %d failed authentication", clusterIndex)
}
decryptedHeaders, err := decryptAEACTR(encryptedHeaders, clusterHeaderKey.Key[:], clusterHeaderKey.IV[:])
if err != nil {
return fmt.Errorf("decrypt AEA cluster %d headers: %w", clusterIndex, err)
}
dataOffset := offset + headerSize
for segmentIndex := range root.SegmentsPerCluster {
start := int(segmentIndex) * segmentHeaderSize
var segmentHeader aeaSegmentHeader
if err := binary.Read(bytes.NewReader(decryptedHeaders[start:start+segmentHeaderSize]), binary.LittleEndian, &segmentHeader); err != nil {
return fmt.Errorf("decode AEA cluster %d segment %d header: %w", clusterIndex, segmentIndex, err)
}
if segmentHeader.DecompressedSize == 0 {
if segmentHeader.CompressedSize != 0 {
return fmt.Errorf("AEA cluster %d segment %d has compressed data without output", clusterIndex, segmentIndex)
}
continue
}
if segmentHeader.DecompressedSize > root.SegmentSize || segmentHeader.CompressedSize == 0 {
return fmt.Errorf("AEA cluster %d segment %d has invalid sizes", clusterIndex, segmentIndex)
}
if int64(segmentHeader.CompressedSize) > sourceSize-dataOffset {
return fmt.Errorf("AEA cluster %d segment %d extends beyond the encrypted image", clusterIndex, segmentIndex)
}
var segmentMAC aeaMAC
copy(segmentMAC[:], segmentMACData[int(segmentIndex)*sha256.Size:(int(segmentIndex)+1)*sha256.Size])
globalIndex := uint64(clusterIndex)*uint64(root.SegmentsPerCluster) + uint64(segmentIndex)
if globalIndex >= uint64(len(r.segments)) {
return fmt.Errorf("AEA cluster %d segment %d is outside the declared output", clusterIndex, segmentIndex)
}
outputOffset := int64(globalIndex * uint64(root.SegmentSize))
if uint64(outputOffset)+uint64(segmentHeader.DecompressedSize) > root.FileSize {
return fmt.Errorf("AEA cluster %d segment %d extends beyond the declared output", clusterIndex, segmentIndex)
}
r.segments[globalIndex] = aeaSegment{
inputOffset: dataOffset,
outputOffset: outputOffset,
compressedSize: segmentHeader.CompressedSize,
decompressedSize: segmentHeader.DecompressedSize,
checksum: segmentHeader.Checksum,
mac: segmentMAC,
cluster: clusterIndex,
index: segmentIndex,
}
dataOffset += int64(segmentHeader.CompressedSize)
outputSize += uint64(segmentHeader.DecompressedSize)
if outputSize > root.FileSize {
return errors.New("AEA segment data exceeds the declared output size")
}
}
offset = dataOffset
clusterMAC = nextClusterMAC
clusterIndex++
}
if outputSize != root.FileSize {
return fmt.Errorf("AEA segment data has size %d, expected %d", outputSize, root.FileSize)
}
return nil
}
func (r *aeaReader) ReadAt(data []byte, offset int64) (int, error) {
if len(data) == 0 {
return 0, nil
}
if offset < 0 {
return 0, errors.New("negative AEA output offset")
}
if offset >= r.size {
return 0, io.EOF
}
wanted := len(data)
if remaining := r.size - offset; int64(wanted) > remaining {
wanted = int(remaining)
}
written := 0
for written < wanted {
segmentIndex := int((offset + int64(written)) / int64(r.segmentSize))
if segmentIndex >= len(r.segments) {
return written, errors.New("AEA segment index is incomplete")
}
segment := r.segments[segmentIndex]
if segment.decompressedSize == 0 {
return written, fmt.Errorf("AEA segment %d is missing", segmentIndex)
}
decoded, err := r.decodeSegment(segmentIndex, segment)
if err != nil {
return written, err
}
inside := int(offset + int64(written) - segment.outputOffset)
if inside < 0 || inside >= len(decoded) {
return written, errors.New("AEA segment has an invalid output offset")
}
count := min(wanted-written, len(decoded)-inside)
copy(data[written:written+count], decoded[inside:inside+count])
written += count
}
if wanted != len(data) {
return written, io.EOF
}
return written, nil
}
func (r *aeaReader) decodeSegment(cacheIndex int, segment aeaSegment) ([]byte, error) {
r.cacheMu.Lock()
defer r.cacheMu.Unlock()
if data, ok := r.cache[cacheIndex]; ok {
return data, nil
}
encrypted := make([]byte, segment.compressedSize)
if _, err := r.source.ReadAt(encrypted, segment.inputOffset); err != nil {
return nil, fmt.Errorf("read AEA cluster %d segment %d: %w", segment.cluster, segment.index, err)
}
clusterKey, err := deriveAEAKey(r.mainKey, nil, binary.LittleEndian.AppendUint32([]byte(aeaClusterKeyInfo), segment.cluster), len(r.mainKey))
if err != nil {
return nil, fmt.Errorf("derive AEA cluster %d key: %w", segment.cluster, err)
}
segmentKey, err := deriveAEAHeaderKey(clusterKey, binary.LittleEndian.AppendUint32([]byte(aeaSegmentKeyInfo), segment.index))
if err != nil {
return nil, fmt.Errorf("derive AEA cluster %d segment %d key: %w", segment.cluster, segment.index, err)
}
computedMAC := calculateAEAMAC(segmentKey.MAC[:], encrypted, nil)
if !hmac.Equal(segment.mac[:], computedMAC[:]) {
return nil, fmt.Errorf("AEA cluster %d segment %d failed authentication", segment.cluster, segment.index)
}
compressed, err := decryptAEACTR(encrypted, segmentKey.Key[:], segmentKey.IV[:])
if err != nil {
return nil, fmt.Errorf("decrypt AEA cluster %d segment %d: %w", segment.cluster, segment.index, err)
}
var decoded []byte
if segment.compressedSize == segment.decompressedSize {
decoded = compressed
} else {
decoded, err = lzfse.Decompress(compressed)
if err != nil && strings.Contains(err.Error(), "fse: stream too short") {
padded, e := padLZFSEStreams(compressed)
if e == nil {
decoded, err = lzfse.Decompress(padded)
}
}
if err != nil {
return nil, fmt.Errorf("decompress AEA cluster %d segment %d: %w", segment.cluster, segment.index, err)
}
if len(decoded) != int(segment.decompressedSize) {
return nil, fmt.Errorf("decompress AEA cluster %d segment %d: produced %d bytes, expected %d", segment.cluster, segment.index, len(decoded), segment.decompressedSize)
}
}
if sha256.Sum256(decoded) != segment.checksum {
return nil, fmt.Errorf("AEA cluster %d segment %d failed checksum verification", segment.cluster, segment.index)
}
if len(r.cacheOrder) == aeaDecodedSegmentCacheCount {
delete(r.cache, r.cacheOrder[0])
copy(r.cacheOrder, r.cacheOrder[1:])
r.cacheOrder = r.cacheOrder[:len(r.cacheOrder)-1]
}
r.cache[cacheIndex] = decoded
r.cacheOrder = append(r.cacheOrder, cacheIndex)
return decoded, nil
}
func deriveAEAKey(key, salt, info []byte, size int) ([]byte, error) {
derived, err := hkdf.Key(sha256.New, key, salt, string(info), size)
if err != nil {
return nil, fmt.Errorf("expand AEA key: %w", err)
}
return derived, nil
}
func deriveAEAHeaderKey(key, info []byte) (aeaHeaderKey, error) {
var headerKey aeaHeaderKey
derived, err := deriveAEAKey(key, nil, info, binary.Size(headerKey))
if err != nil {
return aeaHeaderKey{}, fmt.Errorf("derive AEA header key: %w", err)
}
if err := binary.Read(bytes.NewReader(derived), binary.LittleEndian, &headerKey); err != nil {
return aeaHeaderKey{}, fmt.Errorf("decode AEA header key: %w", err)
}
return headerKey, nil
}
func calculateAEAMAC(key, data, salt []byte) aeaMAC {
mac := hmac.New(sha256.New, key)
_, _ = mac.Write(salt)
_, _ = mac.Write(data)
var length [8]byte
binary.LittleEndian.PutUint64(length[:], uint64(len(salt)))
_, _ = mac.Write(length[:])
return aeaMAC(mac.Sum(nil))
}
func decryptAEACTR(data, key, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("initialize AEA cipher: %w", err)
}
decrypted := make([]byte, len(data))
cipher.NewCTR(block, iv).XORKeyStream(decrypted, data)
return decrypted, nil
}
func readBinaryAt(source io.ReaderAt, offset int64, value any) error {
size := binary.Size(value)
if size < 0 {
return errors.New("invalid binary value")
}
data := make([]byte, size)
if _, err := source.ReadAt(data, offset); err != nil {
return fmt.Errorf("read binary value: %w", err)
}
if err := binary.Read(bytes.NewReader(data), binary.LittleEndian, value); err != nil {
return fmt.Errorf("decode binary value: %w", err)
}
return nil
}
+864
View File
@@ -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 -161
View File
@@ -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,117 +105,13 @@ func Load(ctx context.Context) (Bundle, error) {
return bundle, nil
}
func download(ctx context.Context) (Bundle, error) {
found, err := downloadFiles(ctx, requiredFiles, "download Apple SAP assets")
if err != nil {
return Bundle{}, err
}
bundle := bundleFrom(found)
if err := validate(bundle); err != nil {
return Bundle{}, err
}
return bundle, nil
}
func downloadFiles(ctx context.Context, specs []fileSpec, operation string) (map[string][]byte, error) {
parsed, err := url.Parse(updateURL)
if err != nil {
return nil, 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 nil, fmt.Errorf("open Apple software update: %w", err)
}
length, err := remote.Length()
if err != nil {
return nil, fmt.Errorf("measure Apple software update: %w", err)
}
container, err := xar.NewReader(remote, length)
if err != nil {
return nil, 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 nil, &fs.PathError{Op: "open", Path: payloadName, Err: fs.ErrNotExist}
}
raw := payload.OpenRaw()
if _, err := raw.Seek(payloadBZOffset, io.SeekStart); err != nil {
return nil, 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 nil, fmt.Errorf("seek Apple payload archive: %w", err)
}
wanted := make(map[string]fileSpec, len(specs))
for _, spec := range specs {
wanted[spec.path] = spec
}
found := make(map[string][]byte, len(specs))
reader := cpio.NewReader(archive)
for len(found) != len(wanted) {
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("%s: %w", operation, err)
}
path, body, err := reader.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, 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 nil, fmt.Errorf("read %s: %w", spec.name, err)
}
found[spec.name] = data
}
return found, 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) {
@@ -338,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,
}
}
@@ -370,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
}
+691
View File
@@ -0,0 +1,691 @@
//nolint:wsl // Binary format parsing is clearer when related bounds checks remain adjacent.
package assets
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"os"
"strings"
"github.com/blacktop/go-macho"
"github.com/blacktop/go-macho/pkg/fixupchains"
machotypes "github.com/blacktop/go-macho/types"
)
const (
dyldHeaderSize = 568
dyldMappingSize = 56
dyldImageInfoSize = 32
dyldSubcacheEntrySize = 56
dyldMaximumMappings = 64
dyldMaximumImages = 100_000
dyldMaximumSubcaches = 128
dyldMaximumPathLength = 4096
dyldSlideInfo5Size = 24
dyldMachHeader64Size = 32
dyldMachSegment64Command = 0x19
dyldMaximumLoadCommandsSize = 16 << 20
dyldMaximumSlideChainPointers = 1 << 16
)
type dyldCache struct {
members []*dyldCacheMember
primary *dyldCacheMember
slide5 *dyldSlideInfo5
relativeSelectorBase uint64
}
type dyldCacheMember struct {
file io.ReaderAt
close func() error
size int64
uuid [16]byte
mappings []dyldCacheMapping
}
type dyldCacheMapping struct {
member *dyldCacheMember
address uint64
size uint64
fileOffset uint64
slideInfoOffset uint64
slideInfoSize uint64
}
type dyldSlideInfo5 struct {
pageSize uint32
pageStartsCount uint32
valueAdd uint64
}
type dyldCacheFile struct {
reader io.ReaderAt
size int64
close func() error
}
type dyldCacheOpener func(suffix string) (*dyldCacheFile, error)
type dyldImage struct {
member *dyldCacheMember
address uint64
offset uint64
}
type dyldRebase struct {
address uint64
target uint64
}
func extractDyldImageFromFiles(opener dyldCacheOpener, imagePath, outputPath string) error {
cache, err := openDyldCache(opener)
if err != nil {
return fmt.Errorf("open shared cache: %w", err)
}
defer cache.Close()
image, err := cache.image(imagePath)
if err != nil {
return fmt.Errorf("find %s in shared cache: %w", imagePath, err)
}
imageMachO, err := cache.openImage(image, machotypes.LC_SYMTAB, machotypes.LC_DYSYMTAB)
if err != nil {
return fmt.Errorf("read %s from shared cache: %w", imagePath, err)
}
defer imageMachO.Close()
if err = cache.imageSymbols(image, imageMachO); err != nil {
return fmt.Errorf("read %s symbols: %w", imagePath, err)
}
var chainedFixups *fixupchains.DyldChainedFixups
if imageMachO.HasFixups() {
chainedFixups, err = imageMachO.DyldChainedFixups()
if err != nil {
return fmt.Errorf("read %s chained fixups: %w", imagePath, err)
}
}
if err := imageMachO.Export(outputPath, chainedFixups, imageMachO.GetBaseAddress(), nil); err != nil {
return fmt.Errorf("export %s from shared cache: %w", imagePath, err)
}
if err := cache.applySlide(outputPath); err != nil {
return fmt.Errorf("apply %s shared-cache pointers: %w", imagePath, err)
}
return nil
}
func (c *dyldCache) openImage(image *dyldImage, excluding ...machotypes.LoadCmd) (*macho.File, error) {
linkeditAddress, err := image.linkeditAddress()
if err != nil {
return nil, err
}
linkedit, err := c.mappingForAddress(linkeditAddress)
if err != nil {
return nil, err
}
reader := &dyldCacheReader{cache: c, member: linkedit.member, offset: 0}
converter := machotypes.VMAddrConverter{
Converter: c.slidePointer,
VMAddr2Offet: func(address uint64) (uint64, error) {
mapping, err := c.mappingForAddress(address)
if err != nil {
return 0, err
}
return mapping.fileOffset + address - mapping.address, nil
},
Offet2VMAddr: func(offset uint64) (uint64, error) {
return c.addressForOffset(image.member, offset)
},
}
sectionReader := machotypes.NewCustomSectionReader(image.member.file, &converter, 0, image.member.size)
file, err := macho.NewFile(
io.NewSectionReader(image.member.file, int64(image.offset), image.member.size-int64(image.offset)),
macho.FileConfig{
Offset: int64(image.offset),
SectionReader: sectionReader,
CacheReader: reader,
VMAddrConverter: converter,
RelativeSelectorBase: c.relativeSelectorBase,
LoadExcluding: excluding,
},
)
if err != nil {
return nil, fmt.Errorf("parse shared-cache image: %w", err)
}
return file, nil
}
func openDyldCache(opener dyldCacheOpener) (*dyldCache, error) {
primary, header, err := openDyldCacheMember(opener, "")
if err != nil {
return nil, err
}
cache := &dyldCache{members: []*dyldCacheMember{primary}, primary: primary}
complete := false
defer func() {
if !complete {
_ = cache.Close()
}
}()
subcacheOffset := uint64(binary.LittleEndian.Uint32(header[392:]))
subcacheCount := uint64(binary.LittleEndian.Uint32(header[396:]))
if subcacheCount > dyldMaximumSubcaches || subcacheCount > 0 && !validDyldRange(primary.size, subcacheOffset, subcacheCount*dyldSubcacheEntrySize) {
return nil, fmt.Errorf("shared cache has an invalid subcache table")
}
entries := make([]byte, subcacheCount*dyldSubcacheEntrySize)
if len(entries) > 0 {
if _, err := primary.file.ReadAt(entries, int64(subcacheOffset)); err != nil {
return nil, fmt.Errorf("read shared-cache subcache table: %w", err)
}
}
for index := uint64(0); index < subcacheCount; index++ {
entry := entries[index*dyldSubcacheEntrySize : (index+1)*dyldSubcacheEntrySize]
suffix := strings.TrimRight(string(entry[24:56]), "\x00")
if suffix == "" || strings.ContainsAny(suffix, `/\\`) {
return nil, fmt.Errorf("shared cache has an invalid subcache suffix")
}
member, _, err := openDyldCacheMember(opener, suffix)
if err != nil {
return nil, fmt.Errorf("open shared-cache member %s: %w", suffix, err)
}
if !bytes.Equal(member.uuid[:], entry[:16]) {
_ = member.close()
return nil, fmt.Errorf("shared-cache member %s has an unexpected UUID", suffix)
}
cache.members = append(cache.members, member)
}
for _, member := range cache.members {
for _, mapping := range member.mappings {
if mapping.slideInfoSize == 0 {
continue
}
version, err := readDyldSlideVersion(mapping)
if err != nil {
return nil, err
}
if version != 5 {
return nil, fmt.Errorf("unsupported shared-cache slide version %d", version)
}
slide, err := readDyldSlideInfo5(mapping)
if err != nil {
return nil, err
}
if cache.slide5 == nil {
cache.slide5 = slide
} else if cache.slide5.pageSize != slide.pageSize || cache.slide5.valueAdd != slide.valueAdd {
return nil, fmt.Errorf("shared-cache members use incompatible slide information")
}
}
}
if cache.slide5 == nil {
return nil, fmt.Errorf("shared cache has no slide information")
}
complete = true
return cache, nil
}
func openDyldCacheMember(opener dyldCacheOpener, suffix string) (*dyldCacheMember, []byte, error) {
opened, err := opener(suffix)
if err != nil {
return nil, nil, err
}
fail := func(err error) (*dyldCacheMember, []byte, error) {
_ = opened.close()
return nil, nil, err
}
if opened.size < dyldHeaderSize {
return fail(fmt.Errorf("shared-cache member is too small"))
}
header := make([]byte, dyldHeaderSize)
if _, err := opened.reader.ReadAt(header, 0); err != nil {
return fail(err)
}
magic := strings.TrimRight(string(header[:16]), "\x00")
if magic != "dyld_v1 arm64e" {
return fail(fmt.Errorf("unsupported shared-cache format %q", magic))
}
mappingOffset := uint64(binary.LittleEndian.Uint32(header[312:]))
mappingCount := uint64(binary.LittleEndian.Uint32(header[316:]))
if mappingCount == 0 || mappingCount > dyldMaximumMappings || !validDyldRange(opened.size, mappingOffset, mappingCount*dyldMappingSize) {
return fail(fmt.Errorf("shared-cache member has an invalid mapping table"))
}
mappingData := make([]byte, mappingCount*dyldMappingSize)
if _, err := opened.reader.ReadAt(mappingData, int64(mappingOffset)); err != nil {
return fail(err)
}
member := &dyldCacheMember{file: opened.reader, close: opened.close, size: opened.size}
copy(member.uuid[:], header[88:104])
for index := uint64(0); index < mappingCount; index++ {
data := mappingData[index*dyldMappingSize : (index+1)*dyldMappingSize]
mapping := dyldCacheMapping{
member: member,
address: binary.LittleEndian.Uint64(data[0:]),
size: binary.LittleEndian.Uint64(data[8:]),
fileOffset: binary.LittleEndian.Uint64(data[16:]),
slideInfoOffset: binary.LittleEndian.Uint64(data[24:]),
slideInfoSize: binary.LittleEndian.Uint64(data[32:]),
}
if mapping.size == 0 || mapping.address+mapping.size < mapping.address || !validDyldRange(opened.size, mapping.fileOffset, mapping.size) || mapping.slideInfoSize != 0 && !validDyldRange(opened.size, mapping.slideInfoOffset, mapping.slideInfoSize) {
return fail(fmt.Errorf("shared-cache member has an invalid mapping"))
}
member.mappings = append(member.mappings, mapping)
}
return member, header, nil
}
func validDyldRange(size int64, offset, length uint64) bool {
return size >= 0 && offset <= uint64(size) && length <= uint64(size)-offset
}
func (c *dyldCache) Close() error {
var first error
for _, member := range c.members {
if err := member.close(); err != nil && first == nil {
first = err
}
}
return first
}
func (c *dyldCache) image(path string) (*dyldImage, error) {
header := make([]byte, dyldHeaderSize)
if _, err := c.primary.file.ReadAt(header, 0); err != nil {
return nil, fmt.Errorf("read shared-cache header: %w", err)
}
imagesOffset := uint64(binary.LittleEndian.Uint32(header[448:]))
imagesCount := uint64(binary.LittleEndian.Uint32(header[452:]))
if imagesCount == 0 || imagesCount > dyldMaximumImages || !validDyldRange(c.primary.size, imagesOffset, imagesCount*dyldImageInfoSize) {
return nil, fmt.Errorf("shared cache has an invalid image table")
}
images := make([]byte, imagesCount*dyldImageInfoSize)
if _, err := c.primary.file.ReadAt(images, int64(imagesOffset)); err != nil {
return nil, fmt.Errorf("read shared-cache image table: %w", err)
}
for index := uint64(0); index < imagesCount; index++ {
data := images[index*dyldImageInfoSize : (index+1)*dyldImageInfoSize]
address := binary.LittleEndian.Uint64(data)
pathOffset := uint64(binary.LittleEndian.Uint32(data[24:]))
name, err := readDyldCString(c.primary.file, c.primary.size, pathOffset)
if err != nil {
return nil, err
}
if name != path {
continue
}
mapping, err := c.mappingForAddress(address)
if err != nil {
return nil, err
}
return &dyldImage{
member: mapping.member,
address: address,
offset: mapping.fileOffset + address - mapping.address,
}, nil
}
return nil, fmt.Errorf("image was not found")
}
func readDyldCString(file io.ReaderAt, size int64, offset uint64) (string, error) {
if !validDyldRange(size, offset, 1) {
return "", fmt.Errorf("shared cache contains an invalid string offset")
}
limit := min(uint64(dyldMaximumPathLength), uint64(size)-offset)
data := make([]byte, limit)
n, err := file.ReadAt(data, int64(offset))
if err != nil && err != io.EOF {
return "", fmt.Errorf("read shared-cache string: %w", err)
}
data = data[:n]
if end := bytes.IndexByte(data, 0); end >= 0 {
return string(data[:end]), nil
}
return "", fmt.Errorf("shared-cache string is not terminated")
}
func (c *dyldCache) mappingForAddress(address uint64) (*dyldCacheMapping, error) {
for _, member := range c.members {
for index := range member.mappings {
mapping := &member.mappings[index]
if mapping.address <= address && address < mapping.address+mapping.size {
return mapping, nil
}
}
}
return nil, fmt.Errorf("address %#x is outside the shared cache", address)
}
func (c *dyldCache) addressForOffset(member *dyldCacheMember, offset uint64) (uint64, error) {
for _, mapping := range member.mappings {
if mapping.fileOffset <= offset && offset < mapping.fileOffset+mapping.size {
return mapping.address + offset - mapping.fileOffset, nil
}
}
return 0, fmt.Errorf("offset %#x is outside the shared-cache member", offset)
}
func (c *dyldCache) slidePointer(pointer uint64) uint64 {
if pointer == 0 {
return 0
}
if _, err := c.mappingForAddress(pointer); err == nil {
return pointer
}
return c.slide5.decode(pointer)
}
func (i *dyldImage) linkeditAddress() (uint64, error) {
header := make([]byte, dyldMachHeader64Size)
if _, err := i.member.file.ReadAt(header, int64(i.offset)); err != nil {
return 0, fmt.Errorf("read Mach-O header: %w", err)
}
if binary.LittleEndian.Uint32(header) != uint32(machotypes.Magic64) {
return 0, fmt.Errorf("image has an invalid Mach-O magic")
}
commandCount := binary.LittleEndian.Uint32(header[16:])
commandsSize := uint64(binary.LittleEndian.Uint32(header[20:]))
if commandsSize > dyldMaximumLoadCommandsSize || !validDyldRange(i.member.size, i.offset+dyldMachHeader64Size, commandsSize) {
return 0, fmt.Errorf("image has invalid load commands")
}
commands := make([]byte, commandsSize)
if _, err := i.member.file.ReadAt(commands, int64(i.offset+dyldMachHeader64Size)); err != nil {
return 0, fmt.Errorf("read Mach-O load commands: %w", err)
}
for index, offset := uint32(0), uint64(0); index < commandCount; index++ {
if offset+8 > uint64(len(commands)) {
return 0, fmt.Errorf("image load commands are truncated")
}
commandSize := uint64(binary.LittleEndian.Uint32(commands[offset+4:]))
if commandSize < 8 || offset+commandSize > uint64(len(commands)) {
return 0, fmt.Errorf("image has an invalid load command")
}
if binary.LittleEndian.Uint32(commands[offset:]) == dyldMachSegment64Command && commandSize >= 72 {
name := strings.TrimRight(string(commands[offset+8:offset+24]), "\x00")
if name == "__LINKEDIT" {
return binary.LittleEndian.Uint64(commands[offset+24:]), nil
}
}
offset += commandSize
}
return 0, fmt.Errorf("image has no __LINKEDIT segment")
}
type dyldCacheReader struct {
cache *dyldCache
member *dyldCacheMember
offset int64
}
func (r *dyldCacheReader) Read(data []byte) (int, error) {
n, err := r.member.file.ReadAt(data, r.offset)
r.offset += int64(n)
return n, err //nolint:wrapcheck // Reader adapters must preserve io.EOF.
}
func (r *dyldCacheReader) Seek(offset int64, whence int) (int64, error) {
switch whence {
case io.SeekStart:
case io.SeekCurrent:
offset += r.offset
case io.SeekEnd:
offset += r.member.size
default:
return 0, fmt.Errorf("invalid seek mode")
}
if offset < 0 {
return 0, fmt.Errorf("negative shared-cache offset")
}
r.offset = offset
return offset, nil
}
func (r *dyldCacheReader) ReadAt(data []byte, offset int64) (int, error) {
return r.member.file.ReadAt(data, offset) //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
}
func (r *dyldCacheReader) SeekToAddr(address uint64) error {
mapping, err := r.cache.mappingForAddress(address)
if err != nil {
return err
}
r.member = mapping.member
r.offset = int64(mapping.fileOffset + address - mapping.address)
return nil
}
func (r *dyldCacheReader) ReadAtAddr(data []byte, address uint64) (int, error) {
written := 0
for written < len(data) {
mapping, err := r.cache.mappingForAddress(address)
if err != nil {
return written, err
}
available := mapping.address + mapping.size - address
count := min(uint64(len(data)-written), available)
offset := mapping.fileOffset + address - mapping.address
n, err := mapping.member.file.ReadAt(data[written:written+int(count)], int64(offset))
written += n
address += uint64(n)
if err != nil {
return written, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
}
if n != int(count) {
return written, io.ErrUnexpectedEOF
}
}
return written, nil
}
func readDyldSlideVersion(mapping dyldCacheMapping) (uint32, error) {
if mapping.slideInfoSize < 4 {
return 0, fmt.Errorf("shared cache has truncated slide information")
}
var data [4]byte
if _, err := mapping.member.file.ReadAt(data[:], int64(mapping.slideInfoOffset)); err != nil {
return 0, fmt.Errorf("read shared-cache slide version: %w", err)
}
return binary.LittleEndian.Uint32(data[:]), nil
}
func readDyldSlideInfo5(mapping dyldCacheMapping) (*dyldSlideInfo5, error) {
if mapping.slideInfoSize < dyldSlideInfo5Size {
return nil, fmt.Errorf("shared cache has truncated slide information")
}
data := make([]byte, dyldSlideInfo5Size)
if _, err := mapping.member.file.ReadAt(data, int64(mapping.slideInfoOffset)); err != nil {
return nil, fmt.Errorf("read shared-cache slide information: %w", err)
}
if binary.LittleEndian.Uint32(data) != 5 {
return nil, fmt.Errorf("unsupported shared-cache slide version %d", binary.LittleEndian.Uint32(data))
}
slide := &dyldSlideInfo5{
pageSize: binary.LittleEndian.Uint32(data[4:]),
pageStartsCount: binary.LittleEndian.Uint32(data[8:]),
valueAdd: binary.LittleEndian.Uint64(data[16:]),
}
if slide.pageSize == 0 || uint64(dyldSlideInfo5Size)+uint64(slide.pageStartsCount)*2 > mapping.slideInfoSize {
return nil, fmt.Errorf("shared cache has invalid slide information")
}
return slide, nil
}
func (s *dyldSlideInfo5) decode(pointer uint64) uint64 {
if pointer == 0 {
return 0
}
target := pointer & ((uint64(1) << 34) - 1)
if pointer>>63 == 0 {
target |= (pointer >> 34 & 0xff) << 56
}
return s.valueAdd + target
}
func (c *dyldCache) applySlide(path string) error {
file, err := os.OpenFile(path, os.O_RDWR, 0o600)
if err != nil {
return fmt.Errorf("open exported image: %w", err)
}
defer file.Close()
exported, err := macho.NewFile(file)
if err != nil {
return fmt.Errorf("parse exported image: %w", err)
}
defer exported.Close()
for _, segment := range exported.Segments() {
mapping, err := c.mappingForAddress(segment.Addr)
if err != nil {
return err
}
if mapping.slideInfoOffset == 0 {
continue
}
pageSize, err := c.slidePageSize(*mapping)
if err != nil {
return err
}
start := (segment.Addr - mapping.address) / pageSize
end := (segment.Addr + segment.Memsz - mapping.address + pageSize) / pageSize
rebases, err := c.rebases(*mapping, start, end)
if err != nil {
return err
}
for _, rebase := range rebases {
offset, err := exported.GetOffset(rebase.address)
if err != nil {
continue
}
if _, err := file.Seek(int64(offset), io.SeekStart); err != nil {
return fmt.Errorf("seek to exported pointer %#x: %w", offset, err)
}
if err := binary.Write(file, binary.LittleEndian, rebase.target); err != nil {
return fmt.Errorf("write exported pointer %#x: %w", rebase.target, err)
}
}
}
if err := file.Sync(); err != nil {
return fmt.Errorf("sync exported image: %w", err)
}
return nil
}
func (c *dyldCache) rebases(mapping dyldCacheMapping, startPage, endPage uint64) ([]dyldRebase, error) {
version, err := readDyldSlideVersion(mapping)
if err != nil {
return nil, err
}
if version != 5 {
return nil, fmt.Errorf("unsupported shared-cache slide version %d", version)
}
slide, err := readDyldSlideInfo5(mapping)
if err != nil {
return nil, err
}
starts, err := readDyldSlideArray(mapping, dyldSlideInfo5Size, slide.pageStartsCount)
if err != nil {
return nil, err
}
if endPage == 0 || endPage > uint64(len(starts)) {
endPage = uint64(len(starts))
}
if startPage > endPage {
return nil, fmt.Errorf("invalid shared-cache slide page range")
}
var rebases []dyldRebase
for page := startPage; page < endPage; page++ {
start := starts[page]
if start == 0xffff {
continue
}
pageFileOffset := mapping.fileOffset + page*uint64(slide.pageSize)
pageAddress := mapping.address + page*uint64(slide.pageSize)
offset := uint64(start)
for count := 0; count < dyldMaximumSlideChainPointers; count++ {
if offset+8 > uint64(slide.pageSize) {
return nil, fmt.Errorf("shared-cache slide chain leaves its page")
}
var data [8]byte
if _, err := mapping.member.file.ReadAt(data[:], int64(pageFileOffset+offset)); err != nil {
return nil, fmt.Errorf("read shared-cache slide pointer: %w", err)
}
pointer := binary.LittleEndian.Uint64(data[:])
rebases = append(rebases, dyldRebase{
address: pageAddress + offset,
target: slide.decode(pointer),
})
next := pointer >> 52 & 0x7ff
if next == 0 {
break
}
offset += next * 8
if count == dyldMaximumSlideChainPointers-1 {
return nil, fmt.Errorf("shared-cache slide chain is too long")
}
}
}
return rebases, nil
}
func (c *dyldCache) slidePageSize(mapping dyldCacheMapping) (uint64, error) {
slide, err := readDyldSlideInfo5(mapping)
if err != nil {
return 0, err
}
return uint64(slide.pageSize), nil
}
func readDyldSlideArray(mapping dyldCacheMapping, offset, count uint32) ([]uint16, error) {
if count == 0 {
return nil, nil
}
data := make([]byte, uint64(count)*2)
if _, err := mapping.member.file.ReadAt(data, int64(mapping.slideInfoOffset+uint64(offset))); err != nil {
return nil, fmt.Errorf("read shared-cache slide table: %w", err)
}
values := make([]uint16, count)
for index := range values {
values[index] = binary.LittleEndian.Uint16(data[index*2:])
}
return values, nil
}
+166
View File
@@ -0,0 +1,166 @@
package assets
import (
"bytes"
"encoding/binary"
"fmt"
"strings"
"github.com/blacktop/go-macho"
machotypes "github.com/blacktop/go-macho/types"
)
// imageSymbols restores symbol load commands without allocating the cache-wide string table.
// Export needs only this image's nlists and the strings they actually reference.
func (c *dyldCache) imageSymbols(image *dyldImage, f *macho.File) error {
header := make([]byte, dyldMachHeader64Size)
if _, err := image.member.file.ReadAt(header, int64(image.offset)); err != nil {
return fmt.Errorf("read image header: %w", err)
}
size := uint64(binary.LittleEndian.Uint32(header[20:]))
if size > dyldMaximumLoadCommandsSize {
return fmt.Errorf("invalid image load command size")
}
commands := make([]byte, size)
if _, err := image.member.file.ReadAt(commands, int64(image.offset)+dyldMachHeader64Size); err != nil {
return fmt.Errorf("read image commands: %w", err)
}
address, err := image.linkeditAddress()
if err != nil {
return err
}
mapping, err := c.mappingForAddress(address)
if err != nil {
return err
}
loads := make([]macho.Load, 0, len(f.Loads)+2)
index := 0
for offset := 0; offset < len(commands); {
if len(commands)-offset < 8 {
return fmt.Errorf("truncated image command")
}
length := int(binary.LittleEndian.Uint32(commands[offset+4:]))
if length < 8 || length > len(commands)-offset {
return fmt.Errorf("invalid image command size")
}
raw := commands[offset : offset+length]
offset += length
command := machotypes.LoadCmd(binary.LittleEndian.Uint32(raw))
switch command {
case machotypes.LC_SYMTAB:
table, err := readImageSymbols(mapping.member, raw)
if err != nil {
return err
}
f.Symtab = table
loads = append(loads, table)
case machotypes.LC_DYSYMTAB:
table := &macho.Dysymtab{LoadBytes: raw}
if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &table.DysymtabCmd); err != nil {
return fmt.Errorf("decode dynamic symbols: %w", err)
}
if f.Symtab == nil || uint64(table.Iundefsym)+uint64(table.Nundefsym) > uint64(len(f.Symtab.Syms)) || table.Nindirectsyms > 4<<20 {
return fmt.Errorf("invalid dynamic symbol table")
}
if !validDyldRange(mapping.member.size, uint64(table.Indirectsymoff), uint64(table.Nindirectsyms)*4) {
return fmt.Errorf("indirect symbols exceed cache member")
}
encoded := make([]byte, int(table.Nindirectsyms)*4)
if _, err := mapping.member.file.ReadAt(encoded, int64(table.Indirectsymoff)); err != nil {
return fmt.Errorf("read indirect symbols: %w", err)
}
table.IndirectSyms = make([]uint32, table.Nindirectsyms)
if err := binary.Read(bytes.NewReader(encoded), binary.LittleEndian, table.IndirectSyms); err != nil {
return fmt.Errorf("decode indirect symbols: %w", err)
}
f.Dysymtab = table
loads = append(loads, table)
default:
if index >= len(f.Loads) || f.Loads[index].Command() != command {
return fmt.Errorf("image load command order changed")
}
loads = append(loads, f.Loads[index])
index++
}
}
f.Loads = loads
return nil
}
// readImageSymbols decodes just the referenced names, preserving go-macho's symbol normalization.
func readImageSymbols(member *dyldCacheMember, raw []byte) (*macho.Symtab, error) {
table := &macho.Symtab{LoadBytes: raw}
if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &table.SymtabCmd); err != nil {
return nil, fmt.Errorf("decode symbols: %w", err)
}
if table.Nsyms > 4<<20 || !validDyldRange(member.size, uint64(table.Symoff), uint64(table.Nsyms)*16) || !validDyldRange(member.size, uint64(table.Stroff), uint64(table.Strsize)) {
return nil, fmt.Errorf("invalid image symbol table")
}
encoded := make([]byte, int(table.Nsyms)*16)
if _, err := member.file.ReadAt(encoded, int64(table.Symoff)); err != nil {
return nil, fmt.Errorf("read image symbols: %w", err)
}
readName := func(offset uint64) (string, error) {
if offset >= uint64(table.Strsize) {
return "", nil
}
name, err := readDyldCString(member.file, int64(uint64(table.Stroff)+uint64(table.Strsize)), uint64(table.Stroff)+offset)
if err != nil {
return "", err
}
if strings.HasPrefix(name, "_") && strings.Contains(name, ".") {
name = name[1:]
}
return name, nil
}
reader := bytes.NewReader(encoded)
table.Syms = make([]macho.Symbol, 0, table.Nsyms)
for i := uint32(0); i < table.Nsyms; i++ {
var n machotypes.Nlist64
if err := binary.Read(reader, binary.LittleEndian, &n); err != nil {
return nil, fmt.Errorf("decode image symbol: %w", err)
}
name, err := readName(uint64(n.Name))
if err != nil {
return nil, err
}
indirect := ""
if n.Type.IsIndirectSym() {
indirect, err = readName(n.Value)
if err != nil {
return nil, err
}
}
table.Syms = append(table.Syms, macho.Symbol{Name: name, IndirectName: indirect, Type: n.Type, Sect: n.Sect, Desc: n.Desc, Value: n.Value})
}
return table, nil
}
+63
View File
@@ -0,0 +1,63 @@
package assets
import (
"bytes"
"encoding/binary"
"io"
machotypes "github.com/blacktop/go-macho/types"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
type sparseSymbols struct {
data []byte
largest int
}
// ReadAt simulates a large sparse cache and records the largest requested allocation.
func (s *sparseSymbols) ReadAt(output []byte, offset int64) (int, error) {
s.largest = max(s.largest, len(output))
if offset < 0 {
return 0, io.EOF
}
clear(output)
if offset < int64(len(s.data)) {
copy(output, s.data[offset:])
}
return len(output), nil
}
var _ = Describe("Shared-cache symbol loading", func() {
It("reads only referenced strings from a gigabyte-sized string table", func() {
raw := &sparseSymbols{data: make([]byte, 2048)}
names := []byte("\x00_regular\x00_Go.symbol\x00_target.symbol\x00")
copy(raw.data[1024:], names)
entries := []machotypes.Nlist64{{Nlist: machotypes.Nlist{Name: 1, Type: 0x0f}, Value: 0x180001000}, {Nlist: machotypes.Nlist{Name: 10, Type: 0x0b}, Value: 21}}
var table bytes.Buffer
for _, entry := range entries {
Expect(binary.Write(&table, binary.LittleEndian, entry)).To(Succeed())
}
copy(raw.data[128:], table.Bytes())
var command bytes.Buffer
header := machotypes.SymtabCmd{LoadCmd: machotypes.LC_SYMTAB, Len: 24, Symoff: 128, Nsyms: 2, Stroff: 1024, Strsize: 1 << 30}
Expect(binary.Write(&command, binary.LittleEndian, header)).To(Succeed())
result, err := readImageSymbols(&dyldCacheMember{file: raw, size: 2 << 30}, command.Bytes())
Expect(err).NotTo(HaveOccurred())
Expect(result.Syms).To(HaveLen(2))
Expect(result.Syms[0].Name).To(Equal("_regular"))
Expect(result.Syms[1].Name).To(Equal("Go.symbol"))
Expect(result.Syms[1].IndirectName).To(Equal("target.symbol"))
Expect(raw.largest).To(BeNumerically("<=", 4096))
})
It("rejects symbol data extending beyond the cache member", func() {
var command bytes.Buffer
Expect(binary.Write(&command, binary.LittleEndian, machotypes.SymtabCmd{LoadCmd: machotypes.LC_SYMTAB, Len: 24, Symoff: 128, Nsyms: 10, Stroff: 256, Strsize: 128})).To(Succeed())
_, err := readImageSymbols(&dyldCacheMember{file: bytes.NewReader(make([]byte, 256)), size: 256}, command.Bytes())
Expect(err).To(MatchError(ContainSubstring("invalid image symbol table")))
})
})
+163
View File
@@ -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
}
+172
View File
@@ -0,0 +1,172 @@
package assets
import (
"archive/zip"
"bytes"
"encoding/asn1"
"errors"
"fmt"
"io"
"os"
"github.com/blacktop/go-macho"
"github.com/blacktop/go-macho/pkg/fixupchains"
"github.com/blacktop/go-macho/types"
"github.com/go-compressions/lzfse"
)
const (
kernelCacheName = "kernelcache.release.mac13j"
kernelCacheCompressedSize = 33043908
kernelCacheArchiveSize = 33096787
kernelCachePayloadSize = 33096384
kernelCacheImageSize = 124354560
fairPlayKextIdentifier = "com.apple.driver.FairPlayIOKit"
maximumKernelCacheSymbols = 1 << 20
)
func extractFairPlayKext(archive *zip.Reader, destination string) error {
entry, err := pinnedZipEntry(archive, kernelCacheName, kernelCacheCompressedSize, kernelCacheArchiveSize)
if err != nil {
return err
}
reader, err := entry.Open()
if err != nil {
return fmt.Errorf("open pinned kernel collection: %w", err)
}
data, readErr := io.ReadAll(io.LimitReader(reader, kernelCacheArchiveSize+1))
closeErr := reader.Close()
if readErr != nil || closeErr != nil {
return fmt.Errorf("read pinned kernel collection: %w", errors.Join(readErr, closeErr))
}
if len(data) != kernelCacheArchiveSize {
return fmt.Errorf("pinned kernel collection has size %d, expected %d", len(data), kernelCacheArchiveSize)
}
payload, err := im4pPayload(data)
if err != nil {
return fmt.Errorf("decode pinned kernel collection: %w", err)
}
if len(payload) != kernelCachePayloadSize {
return fmt.Errorf("pinned kernel payload has size %d, expected %d", len(payload), kernelCachePayloadSize)
}
image, err := lzfse.Decompress(payload)
if err != nil {
return fmt.Errorf("decompress pinned kernel collection: %w", err)
}
if len(image) != kernelCacheImageSize {
return fmt.Errorf("pinned kernel image has size %d, expected %d", len(image), kernelCacheImageSize)
}
collection, err := macho.NewFile(bytes.NewReader(image))
if err != nil {
return fmt.Errorf("open pinned kernel collection Mach-O: %w", err)
}
defer collection.Close()
if collection.Type != types.MH_FILESET {
return errors.New("pinned kernel collection is not a fileset")
}
var fixups *fixupchains.DyldChainedFixups
if collection.HasFixups() {
fixups, err = collection.DyldChainedFixups()
if err != nil {
return fmt.Errorf("read pinned kernel fixups: %w", err)
}
}
symbols := make(map[string]macho.Symbol)
for _, entry := range collection.FileSets() {
member, openErr := collection.GetFileSetFileByName(entry.EntryID)
if openErr != nil || member.Symtab == nil {
continue
}
for _, symbol := range member.Symtab.Syms {
if symbol.Type.IsExternalSym() && !symbol.Type.IsUndefinedSym() && symbol.Value != 0 {
symbols[symbol.Name] = symbol
if len(symbols) > maximumKernelCacheSymbols {
return errors.New("pinned kernel symbol table exceeds the limit")
}
}
}
}
member, err := collection.GetFileSetFileByName(fairPlayKextIdentifier)
if err != nil {
return fmt.Errorf("find FairPlayIOKit in pinned kernel collection: %w", err)
}
var resolved []macho.Symbol
if member.Symtab != nil {
for _, symbol := range member.Symtab.Syms {
if !symbol.Type.IsUndefinedSym() || symbol.Name == "" {
continue
}
if target, ok := symbols[symbol.Name]; ok {
resolved = append(resolved, macho.Symbol{
Name: symbol.Name,
Type: types.N_ABS | types.N_EXT,
Desc: symbol.Desc,
Value: target.Value,
})
}
}
}
if err := member.Export(destination, fixups, collection.GetBaseAddress(), resolved); err != nil {
return fmt.Errorf("export FairPlayIOKit from pinned kernel collection: %w", err)
}
info, err := os.Stat(destination)
if err != nil {
return fmt.Errorf("inspect exported FairPlayIOKit: %w", err)
}
if !info.Mode().IsRegular() {
return errors.New("exported FairPlayIOKit is not a regular file")
}
return nil
}
func im4pPayload(data []byte) ([]byte, error) {
var container asn1.RawValue
rest, err := asn1.Unmarshal(data, &container)
if err != nil || len(rest) != 0 || container.Tag != asn1.TagSequence || !container.IsCompound {
return nil, errors.New("invalid IM4P container")
}
contents := container.Bytes
fields := make([]asn1.RawValue, 0, 4)
for len(contents) != 0 && len(fields) < 4 {
var field asn1.RawValue
contents, err = asn1.Unmarshal(contents, &field)
if err != nil {
return nil, fmt.Errorf("decode IM4P field: %w", err)
}
fields = append(fields, field)
}
if len(fields) != 4 || fields[0].Tag != asn1.TagIA5String || string(fields[0].Bytes) != "IM4P" || fields[1].Tag != asn1.TagIA5String || string(fields[1].Bytes) != "krnl" || fields[3].Tag != asn1.TagOctetString {
return nil, errors.New("invalid IM4P kernel payload")
}
return append([]byte(nil), fields[3].Bytes...), nil
}
+98
View File
@@ -0,0 +1,98 @@
package assets
import (
"encoding/binary"
"errors"
)
// padLZFSEStreams supplies unused low accumulator bytes for short FSE streams.
// Apple's decoder can read those bytes before the payload; the pure Go decoder
// bounds each stream separately and otherwise rejects valid short payloads.
// This is only used on authenticated AEA data, whose decoded SHA-256 is checked.
func padLZFSEStreams(src []byte) ([]byte, error) {
var out []byte
for len(src) >= 4 {
magic := binary.LittleEndian.Uint32(src)
if magic == 0x24787662 {
return append(out, src...), nil
}
if len(src) < 12 {
return nil, errors.New("short LZFSE block")
}
if magic == 0x2d787662 || magic == 0x6e787662 {
size := 8 + int(binary.LittleEndian.Uint32(src[4:]))
if magic == 0x6e787662 {
size = 12 + int(binary.LittleEndian.Uint32(src[8:]))
}
if size > len(src) {
return nil, errors.New("truncated LZFSE block")
}
out = append(out, src[:size]...)
src = src[size:]
continue
}
var header, literals, matches int
var v0, v1 uint64
switch magic {
case 0x32787662:
if len(src) < 32 {
return nil, errors.New("short LZFSE V2 header")
}
v0 = binary.LittleEndian.Uint64(src[8:])
v1 = binary.LittleEndian.Uint64(src[16:])
header = int(binary.LittleEndian.Uint32(src[24:]))
literals = int(v0 >> 20 & 0xfffff)
matches = int(v1 >> 40 & 0xfffff)
if header < 32 {
return nil, errors.New("invalid LZFSE V2 header")
}
case 0x31787662:
header = 772
if len(src) < header {
return nil, errors.New("short LZFSE V1 header")
}
literals = int(binary.LittleEndian.Uint32(src[20:]))
matches = int(binary.LittleEndian.Uint32(src[24:]))
default:
return nil, errors.New("unknown LZFSE block")
}
if header > len(src) || literals > len(src)-header || matches > len(src)-header-literals {
return nil, errors.New("truncated LZFSE payload")
}
lp, mp := max(0, 8-literals), max(0, 8-matches)
h := append([]byte(nil), src[:header]...)
if magic == 0x32787662 {
binary.LittleEndian.PutUint64(h[8:], v0&^(uint64(0xfffff)<<20)|uint64(literals+lp)<<20)
binary.LittleEndian.PutUint64(h[16:], v1&^(uint64(0xfffff)<<40)|uint64(matches+mp)<<40)
} else {
binary.LittleEndian.PutUint32(h[8:], uint32(literals+lp+matches+mp))
binary.LittleEndian.PutUint32(h[20:], uint32(literals+lp))
binary.LittleEndian.PutUint32(h[24:], uint32(matches+mp))
}
out = append(out, h...)
out = append(out, make([]byte, lp)...)
out = append(out, src[header:header+literals]...)
out = append(out, make([]byte, mp)...)
out = append(out, src[header+literals:header+literals+matches]...)
src = src[header+literals+matches:]
}
return nil, errors.New("missing LZFSE end marker")
}
+33
View File
@@ -0,0 +1,33 @@
package assets
import (
"encoding/binary"
"github.com/go-compressions/lzfse"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Short LZFSE entropy streams", func() {
It("decodes a valid short literal payload without changing its output", func() {
original := make([]byte, 65536)
encoded, err := lzfse.Compress(original)
Expect(err).NotTo(HaveOccurred())
Expect(binary.LittleEndian.Uint32(encoded)).To(Equal(uint32(0x32787662)))
word := binary.LittleEndian.Uint64(encoded[8:])
Expect(word >> 20 & 0xfffff).To(BeZero())
header := int(binary.LittleEndian.Uint32(encoded[24:]))
short := append([]byte(nil), encoded[:header]...)
short = append(short, make([]byte, 4)...)
short = append(short, encoded[header:]...)
binary.LittleEndian.PutUint64(short[8:], word|4<<20)
_, err = lzfse.Decompress(short)
Expect(err).To(MatchError(ContainSubstring("stream too short")))
padded, err := padLZFSEStreams(short)
Expect(err).NotTo(HaveOccurred())
decoded, err := lzfse.Decompress(padded)
Expect(err).NotTo(HaveOccurred())
Expect(decoded).To(Equal(original))
})
It("rejects truncated block payloads", func() { _, err := padLZFSEStreams([]byte{'b', 'v', 'x', '2'}); Expect(err).To(HaveOccurred()) })
})
+180
View File
@@ -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
}
+58
View File
@@ -0,0 +1,58 @@
package assets
import (
"bytes"
"encoding/binary"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("native remote image reader", func() {
DescribeTable("parses complete Content-Range values",
func(value string, expectedStart, expectedEnd, expectedSize int64) {
start, end, size, err := parseContentRange(value)
Expect(err).NotTo(HaveOccurred())
Expect(start).To(Equal(expectedStart))
Expect(end).To(Equal(expectedEnd))
Expect(size).To(Equal(expectedSize))
},
Entry("single byte", "bytes 0-0/26637307067", int64(0), int64(0), int64(26637307067)),
Entry("middle range", "bytes 100-199/1000", int64(100), int64(199), int64(1000)),
)
DescribeTable("rejects incomplete Content-Range values",
func(value string) {
_, _, _, err := parseContentRange(value)
Expect(err).To(HaveOccurred())
},
Entry("missing total", "bytes 0-0/*"),
Entry("missing separator", "bytes 0-0"),
Entry("zero length", "bytes 0-0/0"),
Entry("wrong unit", "items 0-0/1"),
Entry("range beyond total", "bytes 0-1/1"),
Entry("backwards range", "bytes 2-1/3"),
)
It("parses bounded AEA metadata records", func() {
var data bytes.Buffer
for key, value := range map[string]string{"first": "value", "second": "another"} {
record := append(append([]byte(key), 0), value...)
Expect(binary.Write(&data, binary.LittleEndian, uint32(len(record)+4))).To(Succeed())
_, err := data.Write(record)
Expect(err).NotTo(HaveOccurred())
}
metadata, err := parseAEAMetadata(data.Bytes())
Expect(err).NotTo(HaveOccurred())
Expect(metadata).To(HaveKeyWithValue("first", []byte("value")))
Expect(metadata).To(HaveKeyWithValue("second", []byte("another")))
})
It("rejects an AEA metadata record outside the authentication block", func() {
data := make([]byte, 8)
binary.LittleEndian.PutUint32(data, 32)
_, err := parseAEAMetadata(data)
Expect(err).To(MatchError(ContainSubstring("invalid AEA metadata record length")))
})
})
+267
View File
@@ -0,0 +1,267 @@
package assets
import (
"archive/zip"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"net/http"
"os"
)
const authenticationPluginImage = "/System/Library/Accounts/Authentication/AMSAccountAuthenticationPlugin.bundle/Contents/MacOS/AMSAccountAuthenticationPlugin"
// StoreCache reads the pinned shared-cache data without loading host frameworks.
// It is used both by the profile generator and the portable asset installer.
type StoreCache struct {
cache *dyldCache
ctx context.Context
opener dyldCacheOpener
cleanup func() error
slides map[uint64]map[uint64]uint64
images map[string]uint64
readSystemFile func(string) ([]byte, error)
}
// OpenLocalStoreCache opens shared-cache files for offline profile generation.
func OpenLocalStoreCache(ctx context.Context, path string) (*StoreCache, error) {
opener := func(suffix string) (*dyldCacheFile, error) {
file, err := os.Open(path + suffix)
if err != nil {
return nil, fmt.Errorf("open Store cache member: %w", err)
}
info, err := file.Stat()
if err != nil {
_ = file.Close()
return nil, fmt.Errorf("inspect Store cache member: %w", err)
}
return &dyldCacheFile{reader: file, size: info.Size(), close: file.Close}, nil
}
s, err := newStoreCache(ctx, opener, func() error { return nil })
if err == nil {
s.readSystemFile = os.ReadFile
}
return s, err
}
// OpenRemoteStoreCache obtains data directly from Apple's pinned restore image.
func OpenRemoteStoreCache(ctx context.Context) (*StoreCache, error) {
if ctx == nil {
return nil, errors.New("store asset context is nil")
}
client := &http.Client{}
remote, err := openRemoteFile(ctx, client)
if err != nil {
return nil, fmt.Errorf("open Store restore image: %w", err)
}
archive, err := zip.NewReader(remote, remote.size)
if err != nil {
return nil, fmt.Errorf("read Store restore archive: %w", err)
}
entry, err := pinnedZipEntry(archive, systemOSImageName, systemOSArchiveSize, systemOSArchiveSize)
if err != nil {
return nil, err
}
offset, err := entry.DataOffset()
if err != nil {
return nil, fmt.Errorf("locate Store cryptex: %w", err)
}
image, err := newAEAReader(ctx, client, io.NewSectionReader(remote, offset, int64(entry.CompressedSize64)), int64(entry.CompressedSize64))
if err != nil {
return nil, fmt.Errorf("open Store cryptex: %w", err)
}
if image.size != systemOSImageSize {
return nil, errors.New("store cryptex does not match the pinned image")
}
extractor, closeExtractor, err := newAPFSExtractor(image, image.size)
if err != nil {
return nil, err
}
opener := func(suffix string) (*dyldCacheFile, error) {
file, err := extractor.openFile(ctx, arm64CachePath+suffix)
if err != nil {
return nil, fmt.Errorf("open Store cache member: %w", err)
}
return &dyldCacheFile{reader: file, size: file.size, close: func() error { return nil }}, nil
}
var systemExtractor *apfsExtractor
var closeSystem func() error
cleanup := func() error {
err := closeExtractor()
if closeSystem != nil {
err = errors.Join(err, closeSystem())
}
return err
}
s, err := newStoreCache(ctx, opener, cleanup)
if err == nil {
s.readSystemFile = func(path string) ([]byte, error) {
if systemExtractor == nil {
entry, e := pinnedZipEntry(archive, fileSystemImageName, fileSystemArchiveSize, fileSystemArchiveSize)
if e != nil {
return nil, e
}
offset, e := entry.DataOffset()
if e != nil {
return nil, fmt.Errorf("locate Store filesystem: %w", e)
}
image, e := newAEAReader(ctx, client, io.NewSectionReader(remote, offset, int64(entry.CompressedSize64)), int64(entry.CompressedSize64))
if e != nil {
return nil, e
}
if image.size != fileSystemImageSize {
return nil, errors.New("store filesystem does not match pinned image")
}
systemExtractor, closeSystem, e = newAPFSExtractor(image, image.size)
if e != nil {
return nil, e
}
}
f, e := systemExtractor.openFile(ctx, path)
if e != nil {
return nil, e
}
if f.size > 4<<20 {
return nil, errors.New("store system file exceeds size limit")
}
return io.ReadAll(io.NewSectionReader(f, 0, f.size))
}
}
return s, err
}
func newStoreCache(ctx context.Context, opener dyldCacheOpener, cleanup func() error) (*StoreCache, error) {
if ctx == nil {
_ = cleanup()
return nil, errors.New("store asset context is nil")
}
if err := ctx.Err(); err != nil {
_ = cleanup()
return nil, fmt.Errorf("open Store cache: %w", err)
}
cache, err := openDyldCache(opener)
if err != nil {
_ = cleanup()
return nil, fmt.Errorf("open Store shared cache: %w", err)
}
return &StoreCache{cache: cache, ctx: ctx, opener: opener, cleanup: cleanup, slides: make(map[uint64]map[uint64]uint64)}, nil
}
func (s *StoreCache) Close() error {
return errors.Join(s.cache.Close(), s.cleanup())
}
// Page returns one unslid 4 KiB data page. Runtime-initialized metadata is applied
// separately by the versioned Store profile; these bytes always come from Apple.
func (s *StoreCache) Page(address uint64) ([]byte, error) {
if err := s.ctx.Err(); err != nil {
return nil, fmt.Errorf("read Store page: %w", err)
}
if address&4095 != 0 {
return nil, errors.New("unaligned Store page")
}
mapping, err := s.cache.mappingForAddress(address)
if err != nil {
return nil, err
}
data := make([]byte, 4096)
reader := &dyldCacheReader{cache: s.cache}
if _, err = reader.ReadAtAddr(data, address); err != nil {
return nil, fmt.Errorf("read Store page: %w", err)
}
if mapping.slideInfoSize == 0 {
return data, nil
}
pageSize, err := s.cache.slidePageSize(*mapping)
if err != nil {
return nil, err
}
index := (address - mapping.address) / pageSize
base := mapping.address + index*pageSize
rebases, ok := s.slides[base]
if !ok {
values, err := s.cache.rebases(*mapping, index, index+1)
if err != nil {
return nil, err
}
rebases = make(map[uint64]uint64, len(values))
for _, value := range values {
rebases[value.address] = value.target
}
s.slides[base] = rebases
}
for location, target := range rebases {
if location >= address && location+8 <= address+4096 {
binary.LittleEndian.PutUint64(data[location-address:], target)
}
}
return data, nil
}
// ExtractAuthenticationPlugin exports the same image on every host platform.
func (s *StoreCache) ExtractAuthenticationPlugin(destination string) error {
if err := s.ctx.Err(); err != nil {
return fmt.Errorf("extract authentication plugin: %w", err)
}
return extractDyldImageFromFiles(s.opener, authenticationPluginImage, destination)
}
// FeatureFlags reads the pinned operating system defaults used by Store metadata.
func (s *StoreCache) FeatureFlags(domain string) ([]byte, error) {
switch domain {
case "AppleMediaServices", "Foundation", "CFNetwork":
default:
return nil, errors.New("unsupported Store feature domain")
}
return s.readSystemFile("/System/Library/FeatureFlags/Domain/" + domain + ".plist")
}
+131
View File
@@ -0,0 +1,131 @@
package assets
import (
"encoding/binary"
"fmt"
"github.com/blacktop/go-macho"
machotypes "github.com/blacktop/go-macho/types"
)
// AddressRange reports the unslid virtual range occupied by cache mappings.
func (s *StoreCache) AddressRange() (uint64, uint64) {
start, end := ^uint64(0), uint64(0)
for _, member := range s.cache.members {
for _, mapping := range member.mappings {
start = min(start, mapping.address)
end = max(end, mapping.address+mapping.size)
}
}
return start, end - start
}
// Images lists the image install names recorded in the downloaded shared cache.
func (s *StoreCache) Images() (map[string]uint64, error) {
if s.images != nil {
return s.images, nil
}
header := make([]byte, dyldHeaderSize)
if _, err := s.cache.primary.file.ReadAt(header, 0); err != nil {
return nil, fmt.Errorf("read Store cache header: %w", err)
}
offset := uint64(binary.LittleEndian.Uint32(header[448:]))
count := uint64(binary.LittleEndian.Uint32(header[452:]))
if count == 0 || count > dyldMaximumImages || !validDyldRange(s.cache.primary.size, offset, count*dyldImageInfoSize) {
return nil, fmt.Errorf("invalid Store image table")
}
data := make([]byte, count*dyldImageInfoSize)
if _, err := s.cache.primary.file.ReadAt(data, int64(offset)); err != nil {
return nil, fmt.Errorf("read Store image table: %w", err)
}
images := make(map[string]uint64, count)
for index := uint64(0); index < count; index++ {
entry := data[index*dyldImageInfoSize:]
name, err := readDyldCString(s.cache.primary.file, s.cache.primary.size, uint64(binary.LittleEndian.Uint32(entry[24:])))
if err != nil {
return nil, err
}
images[name] = binary.LittleEndian.Uint64(entry)
}
s.images = images
return images, nil
}
// OpenImage exposes Mach-O metadata directly from the cache; no host image is loaded.
func (s *StoreCache) OpenImage(name string) (*macho.File, error) {
if s.cache.relativeSelectorBase == 0 {
objc, err := s.cache.image("/usr/lib/libobjc.A.dylib")
if err != nil {
return nil, err
}
f, err := s.cache.openImage(objc, machotypes.LC_SYMTAB, machotypes.LC_DYSYMTAB)
if err != nil {
return nil, err
}
defer f.Close()
for _, section := range f.Sections {
if section.Name == "__objc_opt_ro" {
page, err := s.Page(section.Addr &^ 4095)
if err != nil {
return nil, err
}
off := section.Addr & 4095
if off+48 > uint64(len(page)) || section.Size < 48 {
return nil, fmt.Errorf("invalid ObjC optimization header")
}
if binary.LittleEndian.Uint32(page[off:]) != 16 {
return nil, fmt.Errorf("unsupported ObjC optimization version")
}
s.cache.relativeSelectorBase = section.Addr + binary.LittleEndian.Uint64(page[off+40:])
}
}
}
images, err := s.Images()
if err != nil {
return nil, err
}
address, ok := images[name]
if !ok {
return nil, fmt.Errorf("image %s was not found", name)
}
mapping, err := s.cache.mappingForAddress(address)
if err != nil {
return nil, err
}
return s.cache.openImage(&dyldImage{member: mapping.member, address: address, offset: mapping.fileOffset + address - mapping.address}, machotypes.LC_SYMTAB, machotypes.LC_DYSYMTAB)
}
// Contains reports whether a range is backed by one shared-cache mapping.
func (s *StoreCache) Contains(address, size uint64) bool {
for _, member := range s.cache.members {
for _, m := range member.mappings {
if address >= m.address && address-m.address <= m.size && size <= m.size-(address-m.address) {
return true
}
}
}
return false
}
-86
View File
@@ -1,86 +0,0 @@
package assets
import (
"context"
"crypto/sha256"
"fmt"
"os"
"path/filepath"
)
const storeAgentCacheDirectory = "apple-storeagent-v1"
var storeAgentSpec = fileSpec{
name: "storeagent",
path: "./System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/Resources/storeagent",
size: 2580176,
digest: mustDigest("70ce036f9dbcbc04db9511ebd08de0dd3cbc35ccc9d44b089c90170cb5453c59"),
}
// LoadStoreAgent loads the pinned StoreAgent image from its separate cache or Apple payload.
func LoadStoreAgent(ctx context.Context) ([]byte, error) {
directory, err := storeAgentDirectory()
if err != nil {
return nil, err
}
path := filepath.Join(directory, storeAgentSpec.name)
if data, err := readStoreAgent(path); err == nil {
return data, nil
}
files, err := downloadFiles(ctx, []fileSpec{storeAgentSpec}, "download Apple StoreAgent asset")
if err != nil {
return nil, err
}
data := files[storeAgentSpec.name]
if err := VerifyStoreAgent(data); err != nil {
return nil, err
}
if err := os.MkdirAll(directory, 0o700); err != nil {
return nil, fmt.Errorf("create StoreAgent asset cache: %w", err)
}
if err := replaceFile(path, data); err != nil {
return nil, fmt.Errorf("cache Apple StoreAgent asset: %w", err)
}
return data, nil
}
func storeAgentDirectory() (string, error) {
root, err := os.UserCacheDir()
if err != nil {
return "", fmt.Errorf("find user cache directory: %w", err)
}
return filepath.Join(root, "ipatool", "sap", storeAgentCacheDirectory), nil
}
func readStoreAgent(path string) ([]byte, error) {
data, err := readCacheFile(path, storeAgentSpec.size)
if err != nil {
return nil, fmt.Errorf("read cached Apple StoreAgent asset: %w", err)
}
if err := VerifyStoreAgent(data); err != nil {
return nil, err
}
return data, nil
}
// VerifyStoreAgent verifies the image profile required by the StoreAgent runtime.
func VerifyStoreAgent(data []byte) error {
if len(data) != storeAgentSpec.size {
return fmt.Errorf("apple StoreAgent asset has size %d, expected %d", len(data), storeAgentSpec.size)
}
if sha256.Sum256(data) != storeAgentSpec.digest {
return fmt.Errorf("apple StoreAgent asset failed integrity verification")
}
return nil
}
+27 -16
View File
@@ -1,32 +1,43 @@
package assets
import (
"bytes"
"crypto/sha256"
"archive/zip"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("StoreAgent asset profile", func() {
It("pins the verified Apple payload asset", func() {
Expect(storeAgentSpec.name).To(Equal("storeagent"))
Expect(storeAgentSpec.path).To(Equal("./System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/Resources/storeagent"))
Expect(storeAgentSpec.size).To(Equal(2580176))
Expect(storeAgentSpec.digest).To(Equal(mustDigest("70ce036f9dbcbc04db9511ebd08de0dd3cbc35ccc9d44b089c90170cb5453c59")))
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("rejects an asset with the wrong size", func() {
Expect(VerifyStoreAgent(nil)).To(MatchError(ContainSubstring("has size 0, expected 2580176")))
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("rejects an asset with the wrong digest", func() {
data := bytes.Repeat([]byte{0xa5}, storeAgentSpec.size)
Expect(sha256.Sum256(data)).NotTo(Equal(storeAgentSpec.digest))
Expect(VerifyStoreAgent(data)).To(MatchError("apple StoreAgent asset failed integrity verification"))
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("uses a cache namespace separate from ordinary SAP assets", func() {
Expect(storeAgentCacheDirectory).NotTo(Equal("apple-assets-v2"))
It("rejects an incomplete bundle", func() {
Expect(validate(Bundle{})).To(MatchError(ContainSubstring("AppleMediaServices has size 0")))
})
})
-86
View File
@@ -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
}
-52
View File
@@ -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
View File
@@ -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 {
+40
View File
@@ -0,0 +1,40 @@
package machine
import (
"encoding/binary"
"encoding/hex"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("portable IOAES", func() {
DescribeTable("evaluates FairPlay hardware handles with the emulated key",
func(handle uint32) {
keyData := make([]byte, 40)
binary.LittleEndian.PutUint32(keyData[36:40], handle)
plaintext := make([]byte, 16)
iv := make([]byte, 16)
expected, err := hex.DecodeString("66e94bd4ef8a2c3b884cfa59ca342b2e")
Expect(err).NotTo(HaveOccurred())
ciphertext, outputIV, err := emulateIOAES(plaintext, iv, 0, keyData)
Expect(err).NotTo(HaveOccurred())
Expect(ciphertext).To(Equal(expected))
Expect(outputIV).To(Equal(expected))
decrypted, outputIV, err := emulateIOAES(ciphertext, iv, 1, keyData)
Expect(err).NotTo(HaveOccurred())
Expect(decrypted).To(Equal(plaintext))
Expect(outputIV).To(Equal(ciphertext))
},
Entry("commerce", commerceAESHandle),
)
It("rejects unrelated key handles", func() {
keyData := make([]byte, 40)
binary.LittleEndian.PutUint32(keyData[36:40], 1)
_, _, err := emulateIOAES(make([]byte, 16), make([]byte, 16), 0, keyData)
Expect(err).To(MatchError("unsupported IOAES key handle 0x1"))
})
})
+227
View File
@@ -0,0 +1,227 @@
//nolint:wsl // Instruction decoding is clearer when related operations stay together.
package machine
import (
"encoding/binary"
"fmt"
"github.com/majd/ipatool/v2/internal/sap/unicorn"
)
const (
arm64AtomicMask = uint32(0xffe0fc00)
arm64CASAL32 = uint32(0x88e0fc00)
arm64CASAL64 = uint32(0xc8e0fc00)
arm64SWPAL32 = uint32(0xb8e08000)
arm64SWPAL64 = uint32(0xf8e08000)
arm64EOR3Mask = uint32(0xffe08000)
arm64EOR3 = uint32(0xce000000)
)
type arm64Compatibility struct {
engine *unicorn.Engine
}
func newARM64Compatibility(engine *unicorn.Engine) *arm64Compatibility {
return &arm64Compatibility{engine: engine}
}
func (c *arm64Compatibility) emulateInvalidInstruction() (bool, error) {
pc, err := c.engine.RegRead(unicorn.RegPC)
if err != nil {
return false, fmt.Errorf("read arm64 instruction address: %w", err)
}
data, err := c.engine.MemRead(pc, 4)
if err != nil {
return false, nil
}
instruction := binary.LittleEndian.Uint32(data)
if instruction&arm64EOR3Mask == arm64EOR3 {
if err := c.emulateEOR3(instruction); err != nil {
return false, err
}
if err := c.engine.RegWrite(unicorn.RegPC, pc+4); err != nil {
return false, fmt.Errorf("advance arm64 instruction address: %w", err)
}
return true, nil
}
opcode := instruction & arm64AtomicMask
var width uint64
switch opcode {
case arm64CASAL32, arm64SWPAL32:
width = 4
case arm64CASAL64, arm64SWPAL64:
width = 8
default:
return false, nil
}
source := (instruction >> 16) & 31
base := (instruction >> 5) & 31
destination := instruction & 31
address, err := c.readBaseRegister(base)
if err != nil {
return false, err
}
memory, err := c.engine.MemRead(address, width)
if err != nil {
return false, fmt.Errorf("read arm64 atomic operand at %#x: %w", address, err)
}
oldValue := binary.LittleEndian.Uint64(append(memory, make([]byte, 8-width)...))
sourceValue, err := c.readValueRegister(source)
if err != nil {
return false, err
}
if width == 4 {
sourceValue = uint64(uint32(sourceValue))
}
switch opcode {
case arm64CASAL32, arm64CASAL64:
newValue, readErr := c.readValueRegister(destination)
if readErr != nil {
return false, readErr
}
if width == 4 {
newValue = uint64(uint32(newValue))
}
if oldValue == sourceValue {
if err := c.writeMemoryValue(address, newValue, width); err != nil {
return false, err
}
}
if err := c.writeValueRegister(source, oldValue); err != nil {
return false, err
}
case arm64SWPAL32, arm64SWPAL64:
if err := c.writeMemoryValue(address, sourceValue, width); err != nil {
return false, err
}
if err := c.writeValueRegister(destination, oldValue); err != nil {
return false, err
}
}
if err := c.engine.RegWrite(unicorn.RegPC, pc+4); err != nil {
return false, fmt.Errorf("advance arm64 instruction address: %w", err)
}
return true, nil
}
func (c *arm64Compatibility) emulateEOR3(instruction uint32) error {
destination := instruction & 31
first := (instruction >> 5) & 31
third := (instruction >> 10) & 31
second := (instruction >> 16) & 31
firstValue, err := c.engine.RegRead128(unicorn.RegV0 + int(first))
if err != nil {
return fmt.Errorf("read arm64 vector register %d: %w", first, err)
}
secondValue, err := c.engine.RegRead128(unicorn.RegV0 + int(second))
if err != nil {
return fmt.Errorf("read arm64 vector register %d: %w", second, err)
}
thirdValue, err := c.engine.RegRead128(unicorn.RegV0 + int(third))
if err != nil {
return fmt.Errorf("read arm64 vector register %d: %w", third, err)
}
var result [16]byte
for index := range result {
result[index] = firstValue[index] ^ secondValue[index] ^ thirdValue[index]
}
if err := c.engine.RegWrite128(unicorn.RegV0+int(destination), result); err != nil {
return fmt.Errorf("write arm64 vector register %d: %w", destination, err)
}
return nil
}
func (c *arm64Compatibility) readBaseRegister(index uint32) (uint64, error) {
register := unicorn.RegSP
if index != 31 {
var ok bool
register, ok = arm64GeneralRegister(index)
if !ok {
return 0, fmt.Errorf("invalid arm64 base register %d", index)
}
}
value, err := c.engine.RegRead(register)
if err != nil {
return 0, fmt.Errorf("read arm64 base register %d: %w", index, err)
}
return value, nil
}
func (c *arm64Compatibility) readValueRegister(index uint32) (uint64, error) {
if index == 31 {
return 0, nil
}
register, ok := arm64GeneralRegister(index)
if !ok {
return 0, fmt.Errorf("invalid arm64 value register %d", index)
}
value, err := c.engine.RegRead(register)
if err != nil {
return 0, fmt.Errorf("read arm64 value register %d: %w", index, err)
}
return value, nil
}
func (c *arm64Compatibility) writeValueRegister(index uint32, value uint64) error {
if index == 31 {
return nil
}
register, ok := arm64GeneralRegister(index)
if !ok {
return fmt.Errorf("invalid arm64 value register %d", index)
}
if err := c.engine.RegWrite(register, value); err != nil {
return fmt.Errorf("write arm64 value register %d: %w", index, err)
}
return nil
}
func (c *arm64Compatibility) writeMemoryValue(address, value, width uint64) error {
var data [8]byte
binary.LittleEndian.PutUint64(data[:], value)
if err := c.engine.MemWrite(address, data[:width]); err != nil {
return fmt.Errorf("write arm64 atomic operand at %#x: %w", address, err)
}
return nil
}
func arm64GeneralRegister(index uint32) (int, bool) {
switch {
case index <= 28:
return unicorn.RegX0 + int(index), true
case index == 29:
return unicorn.RegX29, true
case index == 30:
return unicorn.RegLR, true
default:
return 0, false
}
}
+45
View File
@@ -0,0 +1,45 @@
package machine
import (
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"errors"
"fmt"
)
const commerceAESHandle = uint32(0x89c)
// emulateIOAES evaluates the device-key handle used by the pinned FairPlay
// runtime without delegating to the host operating system.
func emulateIOAES(source, iv []byte, operation uint32, keyData []byte) ([]byte, []byte, error) {
if len(source) == 0 || len(source)%aes.BlockSize != 0 || len(iv) != aes.BlockSize || len(keyData) != 40 {
return nil, nil, errors.New("invalid IOAES parameters")
}
handle := binary.LittleEndian.Uint32(keyData[36:40])
if handle != commerceAESHandle {
return nil, nil, fmt.Errorf("unsupported IOAES key handle %#x", handle)
}
block, err := aes.NewCipher(make([]byte, aes.BlockSize))
if err != nil {
return nil, nil, fmt.Errorf("initialize IOAES cipher: %w", err)
}
destination := make([]byte, len(source))
outputIV := make([]byte, aes.BlockSize)
switch operation {
case 0:
cipher.NewCBCEncrypter(block, iv).CryptBlocks(destination, source)
copy(outputIV, destination[len(destination)-aes.BlockSize:])
case 1:
copy(outputIV, source[len(source)-aes.BlockSize:])
cipher.NewCBCDecrypter(block, iv).CryptBlocks(destination, source)
default:
return nil, nil, fmt.Errorf("unsupported IOAES operation %#x", operation)
}
return destination, outputIV, nil
}
+1 -6
View File
@@ -23,12 +23,7 @@ func GenerateKBSync(ctx context.Context, bundle assets.Bundle, hardwareID []byte
return nil, errors.New("kbsync requires a nonzero account DSID")
}
image, err := assets.LoadStoreAgent(ctx)
if err != nil {
return nil, fmt.Errorf("load Apple StoreAgent asset: %w", err)
}
agent, globalContext, err := openStoreAgentGlobal(ctx, bundle, image, hardwareID)
agent, globalContext, err := openStoreAgentGlobal(ctx, bundle, hardwareID)
if err != nil {
return nil, err
}
+1 -1
View File
@@ -11,7 +11,7 @@ import (
var _ = Describe("StoreAgent kbsync", func() {
It("pins the kbsync entry in the verified StoreAgent image", func() {
Expect(storeAgentKBSyncEntry).To(Equal(storeAgentBase + 0x0c93c0))
Expect(storeAgentKBSyncEntry).To(Equal(storeAgentBase + 0x19ae34))
})
It("rejects a canceled context before loading assets", func() {
+160 -43
View File
@@ -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,6 +48,7 @@ type entryPoints struct {
type Machine struct {
engine *unicorn.Engine
arm64 *arm64Compatibility
services *shims
entry entryPoints
scratchCursor uint64
@@ -57,9 +56,13 @@ type Machine struct {
}
type imageSpec struct {
name string
data []byte
base uint64
name string
data []byte
base uint64
prelinked map[uint64]string
slots map[uint64]string
functions map[uint64]string
kernelBase uint64
}
type runtimeOptions struct {
@@ -93,11 +96,16 @@ func openRuntime(ctx context.Context, bundle assets.Bundle, options runtimeOptio
return nil, nil, fmt.Errorf("open SAP runtime: %w", err)
}
imageSpecs := make([]imageSpec, 0, 3+len(options.extraImages))
imageSpecs := make([]imageSpec, 0, 2+len(options.extraImages))
imageSpecs = append(imageSpecs,
imageSpec{name: "CoreFP", data: bundle.CoreFP, base: coreFPBase},
imageSpec{name: "CommerceCore", data: bundle.CommerceCore, base: commerceBase},
imageSpec{name: "CommerceKit", data: bundle.CommerceKit, base: kitBase},
imageSpec{
name: "AppleMediaServices",
data: bundle.AppleMediaServices,
prelinked: macOS27SharedCacheFunctions,
slots: macOS27SharedCacheSlots,
functions: macOS27SharedCacheFunctions,
},
)
imageSpecs = append(imageSpecs, options.extraImages...)
@@ -126,16 +134,7 @@ func openRuntime(ctx context.Context, bundle assets.Bundle, options runtimeOptio
coreExports[name] = address
}
commerceCore := images["CommerceCore"]
macAddress, err := commerceCore.Export("_get_mac_address", commerceBase)
if err != nil {
return nil, nil, fmt.Errorf("resolve CommerceCore MAC address export: %w", err)
}
exports["_get_mac_address"] = macAddress
commerceKit := images["CommerceKit"]
appleMediaServices := images["AppleMediaServices"]
for _, name := range []string{
"_cp2g1b9ro",
"_Mib5yocT",
@@ -143,9 +142,9 @@ func openRuntime(ctx context.Context, bundle assets.Bundle, options runtimeOptio
"_IPaI1oem5iL",
"_jEHf8Xzsv8K",
} {
address, err := commerceKit.Export(name, kitBase)
address, err := appleMediaServices.Export(name, appleMediaServices.Base())
if err != nil {
return nil, 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
@@ -160,7 +159,7 @@ func openRuntime(ctx context.Context, bundle assets.Bundle, options runtimeOptio
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() {
@@ -183,7 +182,7 @@ func openRuntime(ctx context.Context, bundle assets.Bundle, options runtimeOptio
}
}
if err := engine.MemWrite(returnAddress, []byte{0xF4}); err != nil {
if err := engine.MemWrite(returnAddress, []byte{0x00, 0x00, 0x20, 0xd4}); err != nil {
return nil, nil, fmt.Errorf("write SAP guest return instruction: %w", err)
}
@@ -200,12 +199,37 @@ func openRuntime(ctx context.Context, bundle assets.Bundle, options runtimeOptio
return machine.services.resolve(name)
}
for _, spec := range imageSpecs {
if err := loadPrelinkedSlots(engine, spec.slots, resolver); err != nil {
return nil, nil, fmt.Errorf("load %s shared-cache slots: %w", spec.name, err)
}
if err := loadPrelinkedFunctions(engine, spec.functions, resolver); err != nil {
return nil, nil, fmt.Errorf("load %s shared-cache functions: %w", spec.name, err)
}
}
for _, spec := range imageSpecs {
image := images[spec.name]
if err := image.Relocate(spec.base, resolver); err != nil {
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)
}
@@ -216,6 +240,69 @@ func openRuntime(ctx context.Context, bundle assets.Bundle, options runtimeOptio
return machine, exports, nil
}
func loadPrelinkedFunctions(engine *unicorn.Engine, functions map[uint64]string, resolve func(string) (uint64, error)) error {
pages := make(map[uint64]struct{})
for address := range functions {
pages[address-address%pageSize] = struct{}{}
end := address + 15
pages[end-end%pageSize] = struct{}{}
}
for address := range pages {
if err := engine.MemMap(address, pageSize); err != nil {
return fmt.Errorf("map function page at %#x: %w", address, err)
}
}
for address, name := range functions {
target, err := resolve(name)
if err != nil {
return fmt.Errorf("resolve %s: %w", name, err)
}
trampoline := make([]byte, 16)
binary.LittleEndian.PutUint32(trampoline[0:4], 0x58000050) // ldr x16, #8
binary.LittleEndian.PutUint32(trampoline[4:8], 0xd61f0200) // br x16
binary.LittleEndian.PutUint64(trampoline[8:16], target)
if err := engine.MemWrite(address, trampoline); err != nil {
return fmt.Errorf("write %s trampoline at %#x: %w", name, address, err)
}
}
return nil
}
func loadPrelinkedSlots(engine *unicorn.Engine, slots map[uint64]string, resolve func(string) (uint64, error)) error {
pages := make(map[uint64]struct{})
for address := range slots {
pages[address-address%pageSize] = struct{}{}
}
for address := range pages {
if err := engine.MemMap(address, pageSize); err != nil {
return fmt.Errorf("map slot page at %#x: %w", address, err)
}
}
for address, name := range slots {
value, err := resolve(name)
if err != nil {
return fmt.Errorf("resolve %s: %w", name, err)
}
var data [8]byte
binary.LittleEndian.PutUint64(data[:], value)
if err := engine.MemWrite(address, data[:]); err != nil {
return fmt.Errorf("write %s slot at %#x: %w", name, address, err)
}
}
return nil
}
func (m *Machine) Initialize(hardwareID []byte) (uint64, error) {
hardware, err := hardwareBlock(hardwareID)
if err != nil {
@@ -402,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")
@@ -412,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
@@ -432,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)
}
@@ -477,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)
}
+1 -1
View File
@@ -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)
+37
View File
@@ -0,0 +1,37 @@
package machine
// macOS27SharedCacheFunctions maps the external function pointers used by the
// AppleMediaServices image extracted from the macOS 27.0.1 (26A434) arm64e
// shared cache. The extraction has its cache slide applied, so these values are
// stable for this exact build and are replaced with emulator services at load
// time.
var macOS27SharedCacheFunctions = map[uint64]string{
0x0000000180675ce8: "_malloc",
0x00000001806766f0: "_free",
0x00000001806cf570: "_dispatch_once",
0x000000018071acc8: "_sysctlbyname",
0x000000018071bec4: "_gettimeofday",
0x0000000180721fb8: "_arc4random",
0x00000001807238a4: "___memset_chk",
0x00000001807903c4: "_abort",
0x0000000180849604: "___error",
0x0000000180889bc4: "_pthread_once",
0x000000018088a6f8: "_pthread_rwlock_unlock",
0x000000018088a7c0: "_pthread_rwlock_wrlock",
0x000000018088b2d8: "_pthread_rwlock_init",
0x0000000180894b40: "_strlen",
0x00000001808cf540: "_CFStringCreateWithCString",
0x00000001808d4200: "_CFStringGetLength",
0x00000001808d44dc: "_CFStringGetCString",
0x00000001808d7278: "_CFRelease",
0x00000001808e89e8: "_CFDataGetLength",
0x0000000184d6b4cc: "_IOServiceMatching",
0x0000000184d6c168: "_IOServiceGetMatchingServices",
0x0000000184d6c4fc: "_IOIteratorNext",
0x0000000184d6cb50: "_IOObjectRelease",
}
var macOS27SharedCacheSlots = map[uint64]string{
0x00000001e02205c0: "___stack_chk_guard",
0x00000001e800c958: "___chkstk_darwin",
}
+662
View File
@@ -0,0 +1,662 @@
package machine
import (
"context"
"encoding/binary"
"errors"
"fmt"
"path/filepath"
"github.com/majd/ipatool/v2/internal/sap/assets"
)
const (
modernADIStartEntry = storeAgentBase + 0x1b4400
modernADIEndEntry = storeAgentBase + 0x1d5124
modernADIOTPEntry = storeAgentBase + 0x1dab04
modernKeyBagEntry = storeAgentBase + 0x16e0f8
modernADIStatePath = "/var/db/fpsd/adi/adi.pb"
modernADIDBase = uint64(0x0000200000000000)
modernADIDEntry = modernADIDBase + 0x11180
modernFairPlayDBase = uint64(0x0000600000000000)
modernFairPlayDEntry = modernFairPlayDBase + 0x332040
// Preserve the prelinked image's original 0x510 page offset so its ADRP
// references retain the same slide as its data segments.
modernFairPlayKextBase = uint64(0x0000700000000510)
modernFairPlayKextStart = modernFairPlayKextBase + 0x2bca984
modernFairPlayKextSetup = modernFairPlayKextBase + 0x2c67e50
modernFairPlayKextInit = modernFairPlayKextBase + 0x2bca714
modernFairPlayKextEntry = modernFairPlayKextBase + 0x2cf978c
)
// ModernADI runs the ADI implementation embedded in the pinned macOS 27
// commerce image. Apple Store otp/1.5 provisioning requires this generation;
// the Sierra implementation cannot consume its settingInfo payload.
type ModernADI struct {
runtime *Machine
daemon *Machine
fairplay *Machine
kernel *Machine
kernelContext uint64
storeGlobal uint32
daemonHandler uint64
}
func OpenModernADI(ctx context.Context, bundle assets.Bundle, identifier, state []byte) (*ModernADI, error) {
if len(identifier) != 16 {
return nil, errors.New("modern ADI host UUID must be 16 bytes")
}
runtime, _, err := openRuntime(ctx, bundle, runtimeOptions{
extraImages: []imageSpec{{name: "commerce", data: bundle.Commerce, base: storeAgentBase}},
shims: shimOptions{zeroReturnAliases: storeAgentZeroReturnAliases},
})
if err != nil {
return nil, err
}
ready := false
defer func() {
if !ready {
_ = runtime.Close()
}
}()
daemon, _, err := openRuntime(ctx, bundle, runtimeOptions{
extraImages: []imageSpec{{name: "adid", data: bundle.ADID, base: modernADIDBase}},
shims: shimOptions{pauseRunLoop: true},
})
if err != nil {
return nil, fmt.Errorf("open modern ADI daemon: %w", err)
}
defer func() {
if !ready {
_ = daemon.Close()
}
}()
fairplay, _, err := openRuntime(ctx, bundle, runtimeOptions{
extraImages: []imageSpec{{name: "fairplayd", data: bundle.FairPlayD, base: modernFairPlayDBase}},
shims: shimOptions{pauseRunLoop: true},
})
if err != nil {
return nil, fmt.Errorf("open modern FairPlay daemon: %w", err)
}
defer func() {
if !ready {
_ = fairplay.Close()
}
}()
copy(runtime.services.hostUUID[:], identifier)
copy(daemon.services.hostUUID[:], identifier)
copy(fairplay.services.hostUUID[:], identifier)
if len(state) != 0 {
daemon.services.adiFiles[modernADIStatePath] = append([]byte(nil), state...)
}
var kernel *Machine
if len(bundle.FairPlayKext) != 0 {
kernel, _, err = openRuntime(ctx, bundle, runtimeOptions{
extraImages: []imageSpec{{name: "FairPlayIOKit", data: bundle.FairPlayKext, base: modernFairPlayKextBase, kernelBase: 0xfffffe0007004000}},
})
if err != nil {
return nil, fmt.Errorf("open modern FairPlay kernel client: %w", err)
}
defer func() {
if !ready {
_ = kernel.Close()
}
}()
copy(kernel.services.hostUUID[:], identifier)
}
adi := &ModernADI{runtime: runtime, daemon: daemon, fairplay: fairplay, kernel: kernel}
if kernel != nil {
kernel.services.machRPCHandler = adi.handleFairPlayMachRPC
if err := adi.initializeFairPlayKernel(); err != nil {
return nil, err
}
}
fairplay.services.fairPlayHandler = adi.handleFairPlayMessage
if _, err = fairplay.invoke(modernFairPlayDEntry, 0, 0, 0); err != nil {
return nil, fmt.Errorf("initialize modern FairPlay daemon: %w", err)
}
daemon.services.fairPlayHandler = adi.handleFairPlayMessage
runtime.services.fairPlayHandler = adi.handleFairPlayMessage
if err := adi.initializeDaemon(); err != nil {
return nil, err
}
ready = true
return adi, nil
}
func (a *ModernADI) initializeFairPlayKernel() error {
a.kernel.beginCall()
defer a.kernel.clearScratch()
if _, err := a.kernel.invoke(modernFairPlayKextStart); err != nil {
return fmt.Errorf("start modern FairPlay kernel: %w", err)
}
status, err := a.kernel.invoke(modernFairPlayKextSetup)
if err != nil {
return fmt.Errorf("set up modern FairPlay kernel: %w", err)
}
if int32(status) != 0 {
return fmt.Errorf("set up modern FairPlay kernel: status %d", int32(status))
}
output, err := a.kernel.scratch(nil, 8)
if err != nil {
return err
}
task, err := a.kernel.services.allocate(0x1000)
if err != nil {
return fmt.Errorf("allocate modern FairPlay kernel task: %w", err)
}
if err := a.kernel.engine.MemWrite(task, make([]byte, 0x1000)); err != nil {
return fmt.Errorf("initialize modern FairPlay kernel task: %w", err)
}
status, err = a.kernel.invoke(modernFairPlayKextInit, 0, output, 0, task)
if err != nil {
return fmt.Errorf("initialize modern FairPlay kernel session: %w", err)
}
if int32(status) != 0 {
return fmt.Errorf("initialize modern FairPlay kernel session: status %d", int32(status))
}
context, err := a.kernel.readUint64(output)
if err != nil {
return err
}
if context == 0 {
return errors.New("modern FairPlay kernel returned no session context")
}
a.kernelContext = context
return nil
}
func (a *ModernADI) ImportKeyBag(hardwareID, keyBag []byte) error {
if a == nil || a.runtime == nil {
return errors.New("modern ADI runtime is unavailable")
}
hardware, err := hardwareBlock(hardwareID)
if err != nil {
return err
}
a.runtime.beginCall()
defer a.runtime.clearScratch()
hardwareAddress, err := a.runtime.scratch(hardware, uint64(len(hardware)))
if err != nil {
return err
}
path := append([]byte(storeAgentSCInfoPath), 0)
pathAddress, err := a.runtime.scratch(path, uint64(len(path)))
if err != nil {
return err
}
contextField, err := a.runtime.scratch(nil, 4)
if err != nil {
return err
}
status, err := a.runtime.invoke(storeAgentGlobalInit, 0, hardwareAddress, pathAddress, contextField)
if err != nil {
return fmt.Errorf("initialize FairPlay keybag context: %w", err)
}
if int32(status) != 0 {
return fmt.Errorf("initialize FairPlay keybag context: status %d", int32(status))
}
global, err := a.runtime.readUint32(contextField)
if err != nil {
return err
}
if global == 0 {
return errors.New("initialize FairPlay keybag context: null context")
}
keyBagAddress, err := a.runtime.scratch(keyBag, uint64(len(keyBag)))
if err != nil {
return err
}
status, err = a.runtime.invoke(modernKeyBagEntry, uint64(global), keyBagAddress, uint64(len(keyBag)))
if err != nil {
return fmt.Errorf("import FairPlay keybag: %w", err)
}
if int32(status) != 0 {
return fmt.Errorf("import FairPlay keybag: status %d", int32(status))
}
a.storeGlobal = global
return nil
}
func (a *ModernADI) handleFairPlayMessage(input, indirect []byte, outputSize int) ([]byte, []byte, int32, error) {
if a.kernel != nil {
stackProbe, _ := a.kernel.readUint64(modernFairPlayKextBase + 0xb8c028)
if stackProbe != modernFairPlayKextBase+0x2c66248 {
return nil, nil, 0, fmt.Errorf("modern FairPlay kernel stack probe is %#x", stackProbe)
}
a.kernel.beginCall()
defer a.kernel.clearScratch()
message, err := a.kernel.scratch(indirect, uint64(len(indirect)))
if err != nil {
return nil, nil, 0, err
}
status, err := a.kernel.invoke(modernFairPlayKextEntry, message, uint64(len(indirect)), a.kernelContext)
if err != nil {
return nil, nil, 0, fmt.Errorf("run modern FairPlay kernel message: %w", err)
}
updated, err := a.kernel.engine.MemRead(message, uint64(len(indirect)))
if err != nil {
return nil, nil, 0, fmt.Errorf("read modern FairPlay kernel message: %w", err)
}
output := append([]byte(nil), input...)
if len(output) > outputSize {
output = output[:outputSize]
}
return output, updated, int32(status), nil
}
if a.fairplay.services.machPortCallback == 0 {
return nil, nil, 0, errors.New("modern FairPlay daemon installed no message callback")
}
a.fairplay.beginCall()
defer a.fairplay.clearScratch()
message, err := a.fairplay.scratch(indirect, uint64(len(indirect)))
if err != nil {
return nil, nil, 0, err
}
_, err = a.fairplay.invoke(
a.fairplay.services.machPortCallback,
fakeHandle,
message,
uint64(len(indirect)),
a.fairplay.services.machPortInfo,
)
if err != nil {
return nil, nil, 0, fmt.Errorf("run modern FairPlay message callback: %w", err)
}
updated, err := a.fairplay.engine.MemRead(message, uint64(len(indirect)))
if err != nil {
return nil, nil, 0, fmt.Errorf("read modern FairPlay daemon message: %w", err)
}
output := append([]byte(nil), input...)
if len(output) > outputSize {
output = output[:outputSize]
}
return output, updated, 0, nil
}
func (a *ModernADI) handleFairPlayMachRPC(request []byte, receiveSize int) ([]byte, error) {
if a.fairplay.services.machPortCallback == 0 {
return nil, errors.New("modern FairPlay daemon installed no message callback")
}
a.fairplay.beginCall()
defer a.fairplay.clearScratch()
message, err := a.fairplay.scratch(request, uint64(max(len(request), receiveSize)))
if err != nil {
return nil, err
}
a.fairplay.services.machMessageReply = nil
_, err = a.fairplay.invoke(
a.fairplay.services.machPortCallback,
fakeHandle,
message,
uint64(len(request)),
a.fairplay.services.machPortInfo,
)
if err != nil {
return nil, fmt.Errorf("run modern FairPlay Mach callback: %w", err)
}
if len(a.fairplay.services.machMessageReply) == 0 {
return nil, errors.New("modern FairPlay daemon returned no Mach reply")
}
return append([]byte(nil), a.fairplay.services.machMessageReply...), nil
}
func (a *ModernADI) initializeDaemon() error {
_, entryErr := a.daemon.invoke(modernADIDEntry, 0, 0, 0, 0)
if a.daemon.services.xpcEventHandler == 0 {
return fmt.Errorf("initialize modern ADI daemon: %w", entryErr)
}
listener := a.daemon.services.xpcEventHandler
connection := a.daemon.services.newXPCObject(nil)
if err := a.invokeDaemonBlock(listener, connection); err != nil {
return fmt.Errorf("accept modern ADI daemon connection: %w", err)
}
if a.daemon.services.xpcEventHandler == listener {
return errors.New("modern ADI daemon did not install a request handler")
}
a.daemonHandler = a.daemon.services.xpcEventHandler
return nil
}
func (a *ModernADI) invokeDaemonBlock(block, argument uint64) error {
handler, err := a.daemon.readUint64(block + 16)
if err != nil {
return err
}
_, err = a.daemon.invoke(handler, block, argument)
return err
}
func (a *ModernADI) invoke(function uint64, arguments ...uint64) (uint64, error) {
a.runtime.services.xpcData = nil
a.runtime.services.xpcSyncReply = nil
_, firstErr := a.runtime.invoke(function, arguments...)
request := append([]byte(nil), a.runtime.services.xpcData...)
if len(request) == 0 {
return 0, fmt.Errorf("modern ADI client created no daemon request: %w", firstErr)
}
a.daemon.services.xpcReply = nil
a.daemon.services.xpcReplied = false
requestObject := a.daemon.services.newXPCObject(request)
if err := a.invokeDaemonBlock(a.daemonHandler, requestObject); err != nil {
return 0, fmt.Errorf("run modern ADI daemon request: %w", err)
}
if !a.daemon.services.xpcReplied || len(a.daemon.services.xpcReply) == 0 {
return 0, errors.New("modern ADI daemon returned no reply")
}
a.runtime.services.xpcSyncReply = append([]byte(nil), a.daemon.services.xpcReply...)
return a.runtime.invoke(function, arguments...)
}
// ExchangeXPC sends the opaque data payload used by AppleMediaServices to the
// emulated com.apple.adid service and returns its opaque reply payload.
func (a *ModernADI) ExchangeXPC(request []byte) ([]byte, error) {
if a == nil || a.daemon == nil || a.daemonHandler == 0 {
return nil, errors.New("modern ADI daemon is unavailable")
}
if len(request) == 0 || len(request) > 1<<20 {
return nil, errors.New("modern ADI XPC request is invalid")
}
a.daemon.services.xpcReply = nil
a.daemon.services.xpcReplied = false
requestObject := a.daemon.services.newXPCObject(request)
if err := a.invokeDaemonBlock(a.daemonHandler, requestObject); err != nil {
return nil, fmt.Errorf("run modern ADI XPC request: %w", err)
}
if !a.daemon.services.xpcReplied || len(a.daemon.services.xpcReply) == 0 {
return nil, errors.New("modern ADI XPC service returned no reply")
}
return append([]byte(nil), a.daemon.services.xpcReply...), nil
}
func (a *ModernADI) StartProvisioning(dsid uint64, spim []byte) ([]byte, uint32, error) {
if a == nil || a.runtime == nil {
return nil, 0, errors.New("modern ADI runtime is unavailable")
}
a.runtime.beginCall()
defer a.runtime.clearScratch()
input, err := a.runtime.scratch(spim, uint64(len(spim)))
if err != nil {
return nil, 0, err
}
pointerField, err := a.runtime.scratch(nil, 8)
if err != nil {
return nil, 0, err
}
lengthField, err := a.runtime.scratch(nil, 4)
if err != nil {
return nil, 0, err
}
sessionField, err := a.runtime.scratch(nil, 4)
if err != nil {
return nil, 0, err
}
status, err := a.invoke(modernADIStartEntry, dsid, input, uint64(len(spim)), pointerField, lengthField, sessionField)
if err != nil {
return nil, 0, err
}
if int32(status) != 0 {
return nil, 0, fmt.Errorf("start modern ADI provisioning: status %d", int32(status))
}
output, err := a.readOutput(pointerField, lengthField)
if err != nil {
return nil, 0, err
}
session, err := a.runtime.engine.MemRead(sessionField, 4)
if err != nil {
return nil, 0, fmt.Errorf("read modern ADI provisioning session: %w", err)
}
return output, binary.LittleEndian.Uint32(session), nil
}
func (a *ModernADI) EndProvisioning(session uint32, settingInfo, transportKey []byte) error {
if a == nil || a.runtime == nil {
return errors.New("modern ADI runtime is unavailable")
}
a.runtime.beginCall()
defer a.runtime.clearScratch()
settingAddress, err := a.runtime.scratch(settingInfo, uint64(len(settingInfo)))
if err != nil {
return err
}
keyAddress, err := a.runtime.scratch(transportKey, uint64(len(transportKey)))
if err != nil {
return err
}
status, err := a.invoke(modernADIEndEntry, uint64(session), settingAddress, uint64(len(settingInfo)), keyAddress, uint64(len(transportKey)))
if err != nil {
return err
}
if int32(status) != 0 {
return fmt.Errorf("finish modern ADI provisioning: status %d", int32(status))
}
return nil
}
func (a *ModernADI) RequestOTP(dsid uint64) ([]byte, []byte, error) {
if a == nil || a.runtime == nil {
return nil, nil, errors.New("modern ADI runtime is unavailable")
}
a.runtime.beginCall()
defer a.runtime.clearScratch()
midPointer, err := a.runtime.scratch(nil, 8)
if err != nil {
return nil, nil, err
}
midLength, err := a.runtime.scratch(nil, 4)
if err != nil {
return nil, nil, err
}
otpPointer, err := a.runtime.scratch(nil, 8)
if err != nil {
return nil, nil, err
}
otpLength, err := a.runtime.scratch(nil, 4)
if err != nil {
return nil, nil, err
}
status, err := a.invoke(modernADIOTPEntry, dsid, midPointer, midLength, otpPointer, otpLength)
if err != nil {
return nil, nil, err
}
if int32(status) != 0 {
return nil, nil, fmt.Errorf("request modern ADI OTP: status %d", int32(status))
}
mid, err := a.readOutput(midPointer, midLength)
if err != nil {
return nil, nil, err
}
otp, err := a.readOutput(otpPointer, otpLength)
if err != nil {
return nil, nil, err
}
return mid, otp, nil
}
func (a *ModernADI) readOutput(pointerField, lengthField uint64) ([]byte, error) {
pointer, err := a.runtime.readUint64(pointerField)
if err != nil {
return nil, err
}
length, err := a.runtime.readUint32(lengthField)
if err != nil {
return nil, err
}
if pointer == 0 || length == 0 || length > 1<<20 {
return nil, errors.New("modern ADI returned invalid output")
}
output, err := a.runtime.engine.MemRead(pointer, uint64(length))
if err != nil {
return nil, fmt.Errorf("read modern ADI output: %w", err)
}
return output, nil
}
func (a *ModernADI) State() ([]byte, error) {
if a == nil || a.runtime == nil {
return nil, errors.New("modern ADI runtime is unavailable")
}
if state := a.daemon.services.adiFiles[modernADIStatePath]; len(state) != 0 {
return append([]byte(nil), state...), nil
}
for path, state := range a.daemon.services.adiFiles {
if filepath.Base(path) == "adi.pb" && len(state) != 0 {
return append([]byte(nil), state...), nil
}
}
return nil, errors.New("modern ADI state was not created")
}
func (a *ModernADI) Close() error {
if a == nil || a.runtime == nil {
return nil
}
var err error
if a.storeGlobal != 0 {
if status, closeErr := a.runtime.invoke(storeAgentGlobalClose, uint64(a.storeGlobal)); closeErr != nil {
err = errors.Join(err, fmt.Errorf("close FairPlay keybag context: %w", closeErr))
} else if int32(status) != 0 {
err = errors.Join(err, fmt.Errorf("close FairPlay keybag context: status %d", int32(status)))
}
}
err = errors.Join(err, a.runtime.Close())
err = errors.Join(err, a.daemon.Close())
err = errors.Join(err, a.fairplay.Close())
if a.kernel != nil {
err = errors.Join(err, a.kernel.Close())
}
a.runtime = nil
a.daemon = nil
a.fairplay = nil
a.kernel = nil
return err
}
+225 -2
View File
@@ -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)))
})
})
+70 -34
View File
@@ -10,7 +10,7 @@ import (
)
const (
shimBase = uint64(0x0000200000000000)
shimBase = uint64(0x00007ff880000000)
shimCodeSize = uint64(0x0000000000080000)
shimSize = uint64(0x0000000000100000)
shimSlotSize = uint64(16)
@@ -33,26 +33,55 @@ 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) {
@@ -65,15 +94,20 @@ func newShimsWithOptions(engine *unicorn.Engine, coreExports map[string]uint64,
}
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
}
@@ -143,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)
}
@@ -204,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])
@@ -224,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)
}
@@ -238,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)
}
+20 -25
View File
@@ -12,11 +12,11 @@ import (
const (
storeAgentBase = uint64(0x00001000c0000000)
storeAgentGlobalInit = storeAgentBase + 0x0c5fc0
storeAgentKBSyncEntry = storeAgentBase + 0x0c93c0
storeAgentSessionInit = storeAgentBase + 0x0debd0
storeAgentDecryptEntry = storeAgentBase + 0x0ee700
storeAgentSessionClose = storeAgentBase + 0x1212d0
storeAgentGlobalInit = storeAgentBase + 0x1312fc
storeAgentKBSyncEntry = storeAgentBase + 0x19ae34
storeAgentSessionInit = storeAgentBase + 0x13ac60
storeAgentDecryptEntry = storeAgentBase + 0x175390
storeAgentGlobalClose = storeAgentBase + 0x130eb4
storeAgentChunkSize = 0x8000
storeAgentSCInfoPath = "/Users/Shared/SC Info"
)
@@ -32,6 +32,7 @@ var storeAgentZeroReturnAliases = []string{
type StoreAgent struct {
mu sync.Mutex
guest *Machine
global uint32
session uint64
decryptEntry uint64
closeEntry uint64
@@ -47,20 +48,15 @@ func OpenStoreAgent(ctx context.Context, bundle assets.Bundle, hardwareID, dpInf
return nil, fmt.Errorf("open StoreAgent runtime: %w", err)
}
image, err := assets.LoadStoreAgent(ctx)
if err != nil {
return nil, fmt.Errorf("load Apple StoreAgent asset: %w", err)
}
return openStoreAgent(ctx, bundle, image, hardwareID, dpInfo)
return openStoreAgent(ctx, bundle, hardwareID, dpInfo)
}
func openStoreAgent(ctx context.Context, bundle assets.Bundle, image, hardwareID, dpInfo []byte) (*StoreAgent, error) {
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, image, hardwareID)
agent, globalContext, err := openStoreAgentGlobal(ctx, bundle, hardwareID)
if err != nil {
return nil, err
}
@@ -75,7 +71,7 @@ func openStoreAgent(ctx context.Context, bundle assets.Bundle, image, hardwareID
return agent, nil
}
func openStoreAgentGlobal(ctx context.Context, bundle assets.Bundle, image, hardwareID []byte) (*StoreAgent, uint32, error) {
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")
}
@@ -84,17 +80,13 @@ func openStoreAgentGlobal(ctx context.Context, bundle assets.Bundle, image, hard
return nil, 0, fmt.Errorf("open StoreAgent runtime: %w", err)
}
if err := assets.VerifyStoreAgent(image); err != nil {
return nil, 0, fmt.Errorf("verify Apple StoreAgent profile: %w", err)
}
hardware, err := hardwareBlock(hardwareID)
if err != nil {
return nil, 0, err
}
guest, exports, err := openRuntime(ctx, bundle, runtimeOptions{
extraImages: []imageSpec{{name: "storeagent", data: image, base: storeAgentBase}},
extraImages: []imageSpec{{name: "commerce", data: bundle.Commerce, base: storeAgentBase}},
shims: shimOptions{
zeroReturnAliases: storeAgentZeroReturnAliases,
},
@@ -108,7 +100,7 @@ func openStoreAgentGlobal(ctx context.Context, bundle assets.Bundle, image, hard
agent := &StoreAgent{
guest: guest,
decryptEntry: storeAgentDecryptEntry,
closeEntry: storeAgentSessionClose,
closeEntry: storeAgentGlobalClose,
}
globalContext, err := agent.initializeGlobal(hardware)
@@ -118,6 +110,8 @@ func openStoreAgentGlobal(ctx context.Context, bundle assets.Bundle, image, hard
return nil, 0, err
}
agent.global = globalContext
return agent, globalContext, nil
}
@@ -319,15 +313,16 @@ func (s *StoreAgent) Close() error {
var errs []error
if s.guest != nil && s.session != 0 {
session := s.session
if s.guest != nil && s.global != 0 {
global := s.global
s.global = 0
s.session = 0
status, err := s.guest.invoke(s.closeEntry, session)
status, err := s.guest.invoke(s.closeEntry, uint64(global))
if err != nil {
errs = append(errs, fmt.Errorf("close StoreAgent session: %w", err))
errs = append(errs, fmt.Errorf("close StoreAgent global context: %w", err))
} else if int32(status) != 0 {
errs = append(errs, fmt.Errorf("StoreAgent session close returned %d", int32(status)))
errs = append(errs, fmt.Errorf("StoreAgent global context close returned %d", int32(status)))
}
}
+11 -17
View File
@@ -6,7 +6,6 @@ import (
"errors"
"io"
"github.com/majd/ipatool/v2/internal/sap/assets"
"github.com/majd/ipatool/v2/internal/sap/unicorn"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@@ -16,16 +15,10 @@ 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 + 0x0c5fc0))
Expect(storeAgentSessionInit).To(Equal(storeAgentBase + 0x0debd0))
Expect(storeAgentDecryptEntry).To(Equal(storeAgentBase + 0x0ee700))
Expect(storeAgentSessionClose).To(Equal(storeAgentBase + 0x1212d0))
})
It("re-verifies the pinned image before opening the runtime", func() {
_, err := openStoreAgent(context.Background(), assets.Bundle{}, []byte("wrong image"), []byte{1}, []byte{1})
Expect(err).To(MatchError(ContainSubstring("verify Apple StoreAgent profile")))
Expect(err).To(MatchError(ContainSubstring("has size")))
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() {
@@ -135,24 +128,25 @@ var _ = Describe("StoreAgent", func() {
})
})
It("closes the session and machine idempotently", func() {
It("closes the global context and machine idempotently", func() {
machine := newGinkgoServiceMachine(shimOptions{})
var closedSession uint64
var closedContext uint64
closeEntry, err := machine.services.addFunction("test.storeagent.close", func() error {
value, argumentErr := machine.services.argument(0)
if argumentErr != nil {
return argumentErr
}
closedSession = value
closedContext = value
return machine.services.setResult(0)
})
Expect(err).NotTo(HaveOccurred())
agent := &StoreAgent{guest: machine, session: 0x1234, closeEntry: closeEntry}
agent := &StoreAgent{guest: machine, global: 0x1234, session: 0x5678, closeEntry: closeEntry}
Expect(agent.Close()).To(Succeed())
Expect(closedSession).To(Equal(uint64(0x1234)))
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())
@@ -189,7 +183,7 @@ func newGinkgoServiceMachine(options shimOptions) *Machine {
Expect(engine.MemMap(region.address, region.size)).To(Succeed())
}
Expect(engine.MemWrite(returnAddress, []byte{0xF4})).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())
+3 -1
View File
@@ -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) {
+4
View File
@@ -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
+45 -37
View File
@@ -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))
})
})
+3
View File
@@ -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 {
+90 -26
View File
@@ -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
}
+12 -12
View File
@@ -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)
}
}
+33 -5
View File
@@ -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
+7 -7
View File
@@ -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)
}
+95
View File
@@ -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
}
+125
View File
@@ -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())
}
})
})
+51
View File
@@ -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())
})
})
+324
View File
@@ -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
}
}
+117
View File
@@ -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")))
})
})
+95
View File
@@ -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
}
+58
View File
@@ -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
}
+273
View File
@@ -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
}
+38
View File
@@ -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
}
+18
View File
@@ -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
+136
View File
@@ -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)
}
+396
View File
@@ -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)
}
+132
View File
@@ -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
}
+149
View File
@@ -0,0 +1,149 @@
package emulator
import (
"fmt"
"time"
)
// The CLI owns interactive authentication. A caller delegate declines native UI
// so Apple's session can finish with an error and the existing CLI can interpret
// the server's 2FA, expired-token, or license response.
func (r *Runtime) interactiveDelegate() uint64 {
const name = "IPAToolStoreDelegate"
if r.classes[name] == nil {
address := r.alloc(16)
r.classes[name] = &Class{Name: name, Address: address, Super: "NSObject", Size: 16, Ivars: map[string]uint64{}}
r.classNames[address] = name
for index, selector := range []string{"AMSURLSession:task:handleAuthenticateRequest:completion:", "AMSURLSession:task:handleDialogRequest:completion:"} {
code := int64(index + 1)
method := selector
block := r.hostBlock(func() {
completion := r.arg(5)
failure := r.New("NSError", map[string]uint64{"domain": r.New("NSString", "IPAToolStoreInteraction"), "code": r.New("NSNumber", code), "userInfo": r.New("NSDictionary", map[string]uint64{})})
r.callback(completion, []uint64{0, failure}, func() { r.set(0) })
})
r.methods[methodKey(name, method, false)] = r.read64(block + 16)
}
}
return r.New(name, nil)
}
func (r *Runtime) installStoreAMDAdapter() {
install := func(address uint64, callback func()) {
page := address &^ 4095
if !r.pages[page] {
if err := r.MemMap(page, 4096); err != nil {
panic(err)
}
}
if err := r.MemWrite(address, []byte{0xc0, 0x03, 0x5f, 0xd6}); err != nil {
panic(err)
}
r.callbacks[address] = callback
}
install(0x180574a18, func() {
r.set(r.New("HostXPCDictionary", map[string]uint64{}))
})
install(0x180553470, func() {
dictionary := r.objects[r.arg(0)].Value.(map[string]uint64)
length := r.arg(3)
if length > 1<<20 {
panic("XPC data exceeds runtime limit")
}
data, err := r.engine.MemRead(r.arg(2), length)
if err != nil {
panic(err)
}
dictionary[r.cstring(r.arg(1))] = r.New("NSData", data)
r.set(0)
})
install(0x180553a00, func() {
dictionary := r.objects[r.arg(0)].Value.(map[string]uint64)
dataObject := r.objects[dictionary[r.cstring(r.arg(1))]]
if dataObject == nil {
if out := r.arg(2); out != 0 {
r.write64(out, 0)
}
r.set(0)
return
}
data := dataObject.Value.([]byte)
pointer := r.alloc(uint64(max(len(data), 1)))
if len(data) != 0 {
if err := r.MemWrite(pointer, data); err != nil {
panic(err)
}
}
if out := r.arg(2); out != 0 {
r.write64(out, uint64(len(data)))
}
r.set(pointer)
})
install(0x18054c6b8, func() { r.set(0) })
install(0x180554c88, func() {
connection := r.New("HostXPCConnection", r.cstring(r.arg(0)))
r.objects[connection].Properties["targetQueue"] = r.arg(1)
r.objects[connection].Properties["flags"] = r.arg(2)
r.set(connection)
})
install(0x180554dac, func() {
r.objects[r.arg(0)].Properties["eventHandler"] = r.arg(1)
r.set(0)
})
install(0x1805550b4, func() { r.set(0) })
install(0x180556440, func() {
connection := r.objects[r.arg(0)]
message := r.objects[r.arg(1)].Value.(map[string]uint64)
dataObject := r.objects[message["data"]]
if r.xpcSyncHandler == nil || dataObject == nil {
panic("Store AMD XPC handler is unavailable")
}
reply, err := r.xpcSyncHandler(fmt.Sprint(connection.Value), dataObject.Value.([]byte))
if err != nil {
panic(err)
}
r.set(r.New("HostXPCDictionary", map[string]uint64{"data": r.New("NSData", reply)}))
})
install(0x184e50b38, func() {
if token := r.arg(1); token != 0 {
r.write64(token, 1)
}
r.set(0)
})
install(0x184e51370, func() {
if changed := r.arg(1); changed != 0 {
r.write64(changed, 0)
}
r.set(0)
})
install(0x18073bc1c, func() { r.set(0) })
install(0x18071bec4, func() {
now := time.Now()
if value := r.arg(0); value != 0 {
r.write64(value, uint64(now.Unix()))
r.write64(value+8, uint64(now.Nanosecond()/1000))
}
r.set(0)
})
}
+242
View File
@@ -0,0 +1,242 @@
package emulator
import (
"fmt"
"math"
"sort"
"strconv"
"strings"
"golang.org/x/text/unicode/norm"
)
// A bounded implementation of Swift native dictionary storage. Metadata and
// strides come from the matching runtime. References live for the VM lifetime,
// so copying these observed pointer-only key/value layouts is bitwise safe.
func (r *Runtime) ensureUniqueDictionary(self uint64, unique bool, capacity, metadata uint64) {
old := r.read64(self)
oldCapacity := r.read64(old + 24)
if unique && capacity <= oldCapacity {
r.set(0)
return
}
layout, ok := r.profile.SwiftDictionaries[strconv.FormatUint(metadata, 10)]
if !ok {
panic(fmt.Sprintf("unprepared dictionary metadata %#x", metadata))
}
if (layout.KeyStride != 16 && layout.KeyStride != 32 && layout.KeyStride != 40) || (layout.ValueStride != 8 && layout.ValueStride != 16 && layout.ValueStride != 32) {
panic("unsupported dictionary copy layout")
}
const buckets = uint64(1024)
const storageCapacity = buckets * 3 / 4
if capacity > storageCapacity {
panic("dictionary exceeds runtime capacity")
}
count := r.read64(old + 16)
if count != 0 && oldCapacity != storageCapacity {
panic("dictionary resizing requires rehash")
}
headerSize := 64 + buckets/8
size := headerSize + buckets*(layout.KeyStride+layout.ValueStride)
storage := r.alloc(size)
r.write64(storage, layout.Metadata)
r.write64(storage+8, 3)
r.write64(storage+16, count)
r.write64(storage+24, storageCapacity)
r.write64(storage+32, 10)
r.write64(storage+40, r.read64(old+40))
keys := storage + headerSize
values := keys + buckets*layout.KeyStride
r.write64(storage+48, keys)
r.write64(storage+56, values)
if count != 0 {
for _, span := range [][3]uint64{{storage + 64, old + 64, buckets / 8}, {keys, r.read64(old + 48), buckets * layout.KeyStride}, {values, r.read64(old + 56), buckets * layout.ValueStride}} {
data, err := r.engine.MemRead(span[1], span[2])
if err != nil {
panic(err)
}
if err = r.MemWrite(span[0], data); err != nil {
panic(err)
}
}
}
r.write64(self, storage)
r.set(boolValue(oldCapacity != storageCapacity))
}
func (r *Runtime) bridgeDictionaryToSwift(object, keyType, valueType uint64) uint64 {
empty := r.profile.Symbols["_swiftEmptyDictionarySingleton"]
if object == 0 {
return empty
}
values := r.objects[object].Value.(map[string]uint64)
if len(values) == 0 {
return empty
}
typeRef, keyStride := uint64(0x1a2e1d5d6), uint64(16)
valueStride := uint64(32)
if valueType == r.profile.Symbols["$sSSN"] {
if keyType != valueType {
panic("unsupported typed dictionary bridge")
}
typeRef, valueStride = 0x1a2e1d7c6, 16
}
if keyType == r.profile.Symbols["$ss11AnyHashableVN"] {
typeRef, keyStride = 0x1a2e1db1a, 40
}
metadata := r.profile.SwiftTypes[strconv.FormatUint(typeRef, 10)]
if metadata == 0 {
panic("String/Any dictionary metadata not prepared")
}
slot := r.alloc(8)
r.write64(slot, empty)
r.ensureUniqueDictionary(slot, false, uint64(len(values)), metadata)
storage := r.read64(slot)
keys, items := r.read64(storage+48), r.read64(storage+56)
seed := r.read64(storage + 40)
buckets := uint64(1) << uint8(r.read64(storage+32))
names := make([]string, 0, len(values))
for key := range values {
names = append(names, key)
}
sort.Strings(names)
for _, key := range names {
hasher := r.alloc(72)
r.initHasher(hasher, seed)
r.hashBytes(hasher, append([]byte(norm.NFC.String(key)), 255))
hash := r.hashCompress(hasher, r.read64(hasher), true)
index := hash & (buckets - 1)
for r.read64(storage+64+(index/64)*8)&(1<<(index%64)) != 0 {
index = (index + 1) & (buckets - 1)
}
bitmap := storage + 64 + (index/64)*8
r.write64(bitmap, r.read64(bitmap)|(1<<(index%64)))
r.returnSwiftString(key)
r.write64(keys+index*keyStride, r.arg(0))
r.write64(keys+index*keyStride+8, r.arg(1))
if keyStride == 40 {
r.write64(keys+index*keyStride+24, r.profile.Bridges["anyHashableStringMetadata"])
r.write64(keys+index*keyStride+32, r.profile.Bridges["anyHashableStringWitness"])
}
if valueStride == 16 {
value, ok := r.objects[values[key]].Value.(string)
if !ok {
panic("non-string value in typed dictionary bridge")
}
r.returnSwiftString(value)
r.write64(items+index*16, r.arg(0))
r.write64(items+index*16+8, r.arg(1))
} else {
r.storeSwiftAny(items+index*32, values[key])
}
}
r.write64(storage+16, uint64(len(values)))
return storage
}
func (r *Runtime) storeSwiftAny(destination, object uint64) {
value := r.objects[object]
if value == nil {
panic("unknown object bridged to Swift Any")
}
var metadata uint64
switch v := value.Value.(type) {
case string:
r.returnSwiftString(v)
r.write64(destination, r.arg(0))
r.write64(destination+8, r.arg(1))
metadata = r.profile.Symbols["$sSSN"]
case int64:
r.write64(destination, uint64(v))
metadata = r.profile.Symbols["$sSiN"]
case bool:
r.write64(destination, boolValue(v))
metadata = r.profile.Symbols["$sSbN"]
case float64:
r.write64(destination, math.Float64bits(v))
metadata = r.profile.Symbols["$sSdN"]
default:
class := value.Class
if strings.Contains(class, "Dictionary") {
class = "NSDictionary"
} else if strings.Contains(class, "Array") {
class = "NSArray"
} else if strings.Contains(class, "Data") {
class = "NSData"
}
metadata = r.profile.ObjCMetadata[class]
r.write64(destination, object)
}
if metadata == 0 {
panic("unprepared Swift Any metadata")
}
r.write64(destination+24, metadata)
}
func (r *Runtime) bridgeDictionaryToObjC(storage, keyType, valueType uint64) uint64 {
result := map[string]uint64{}
count := r.read64(storage + 16)
if count == 0 {
return r.New("NSDictionary", result)
}
if keyType != r.profile.Symbols["$sSSN"] || valueType != r.profile.Symbols["$sSSN"] {
panic(fmt.Sprintf("unsupported dictionary Objective-C bridge types %#x/%#x", keyType, valueType))
}
if count > 768 || r.read64(storage+32)&255 > 10 {
panic("dictionary bridge exceeds budget")
}
keys, values := r.read64(storage+48), r.read64(storage+56)
buckets := uint64(1) << uint8(r.read64(storage+32))
for index := uint64(0); index < buckets; index++ {
if r.read64(storage+64+(index/64)*8)&(1<<(index%64)) == 0 {
continue
}
key := r.swiftString(r.read64(keys+index*16), r.read64(keys+index*16+8))
value := r.swiftString(r.read64(values+index*16), r.read64(values+index*16+8))
result[key] = r.New("NSString", value)
}
if uint64(len(result)) != count {
panic("Swift dictionary count mismatch")
}
return r.New("NSDictionary", result)
}
@@ -0,0 +1,128 @@
package emulator
import (
"context"
"encoding/json"
"io"
"net/http"
"slices"
"strings"
"github.com/majd/ipatool/v2/internal/sap/assets"
"github.com/majd/ipatool/v2/internal/store/profile"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Generated Store profile", func() {
DescribeTable("encodes and handles responses through the pinned frameworks", func(operation string, savedAccount bool) {
ctx := context.Background()
bundle, err := assets.Load(ctx)
Expect(err).NotTo(HaveOccurred())
prepared, err := profile.Load(ctx)
Expect(err).NotTo(HaveOccurred())
guest, err := open(ctx, bundle.AppleMediaServices, prepared, true)
Expect(err).NotTo(HaveOccurred())
DeferCleanup(guest.Close)
calls := 0
input := Request{Operation: operation, URL: "https://buy.itunes.apple.com/request", Method: http.MethodPost, HardwareID: []byte{0, 1, 2, 3, 4, 5}, Headers: http.Header{}, Parameters: map[string]any{"salableAdamId": "1234", "pricingParameters": "STDQ", "price": "0", "productType": "C", "appleId": "test@example.com", "password": "test"}, Bag: map[string]any{"buyProduct": "https://buy.itunes.apple.com/request"}, Sign: func([]byte) ([]byte, error) { return []byte{1, 2, 3}, nil }, Transport: func(request *http.Request) (*http.Response, error) {
calls++
Expect(request.URL.Scheme).To(Equal("https"))
Expect(request.URL.Host).To(Equal("buy.itunes.apple.com"))
Expect(request.Method).To(Equal(http.MethodPost))
return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/x-apple-plist"}}, Body: io.NopCloser(strings.NewReader(`<?xml version="1.0"?><plist version="1.0"><dict><key>status</key><integer>0</integer></dict></plist>`))}, nil
}}
if savedAccount {
input.Headers.Set("X-Dsid", "123456")
input.Headers.Set("X-Token", "test-token")
input.Headers.Set("X-Apple-Store-Front", "143441-1,29")
}
response, err := guest.Execute(input)
Expect(err).NotTo(HaveOccurred())
DeferCleanup(response.Body.Close)
Expect(calls).To(Equal(1))
Expect(response.StatusCode).To(Equal(http.StatusOK))
}, Entry("authentication", "authenticate", false), Entry("authentication with a saved account", "authenticate", true), Entry("free purchases", "purchase", true), Entry("downloads", "download", true), Entry("search", "search", true), Entry("lookup", "lookup", false))
})
var _ = Describe("Generated profile response branches", func() {
DescribeTable("preserves catalog, transfer, and finance responses", func(operation, method, contentType, body string, status int, stream bool) {
ctx := context.Background()
bundle, err := assets.Load(ctx)
Expect(err).NotTo(HaveOccurred())
prepared, err := profile.Load(ctx)
Expect(err).NotTo(HaveOccurred())
guest, err := open(ctx, bundle.AppleMediaServices, prepared, true)
Expect(err).NotTo(HaveOccurred())
DeferCleanup(guest.Close)
input := Request{
Operation: operation, URL: "https://buy.itunes.apple.com/request", Method: method,
HardwareID: []byte{0, 1, 2, 3, 4, 5}, Headers: http.Header{}, Stream: stream,
Bag: map[string]any{"buyProduct": "https://buy.itunes.apple.com/request"},
Transport: func(request *http.Request) (*http.Response, error) {
Expect(request.Method).To(Equal(method))
return &http.Response{StatusCode: status, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(body))}, nil
},
}
if operation == "authenticate" || operation == "purchase" {
input.Parameters = map[string]any{"appleId": "test@example.com", "password": "test", "salableAdamId": "1234", "pricingParameters": "STDQ", "price": "0", "productType": "C"}
input.Sign = func([]byte) ([]byte, error) { return []byte{1, 2, 3}, nil }
}
response, err := guest.Execute(input)
Expect(err).NotTo(HaveOccurred())
DeferCleanup(response.Body.Close)
Expect(response.StatusCode).To(Equal(status))
actual, err := io.ReadAll(response.Body)
Expect(err).NotTo(HaveOccurred())
if stream {
Expect(actual).To(Equal([]byte(body)))
} else {
Expect(string(actual)).To(ContainSubstring("fixture-value"))
}
},
Entry("catalog GET", "search", http.MethodGet, "application/json", `{"resultCount":1,"results":[{"bundleId":"fixture-value"}]}`, http.StatusOK, false),
Entry("version lookup GET", "lookup", http.MethodGet, "application/json", `{"results":{"fixture-value":{"offers":[]}}}`, http.StatusOK, false),
Entry("streamed package range", "download", http.MethodGet, "application/octet-stream", "fixture-value\x00\xff", http.StatusPartialContent, true),
Entry("authentication failure", "authenticate", http.MethodPost, "application/x-apple-plist", `<plist version="1.0"><dict><key>failureType</key><string>2034</string><key>customerMessage</key><string>fixture-value</string></dict></plist>`, http.StatusOK, false),
Entry("purchase failure", "purchase", http.MethodPost, "application/x-apple-plist", `<plist version="1.0"><dict><key>failureType</key><string>9610</string><key>customerMessage</key><string>fixture-value</string></dict></plist>`, http.StatusOK, false),
)
})
var _ = Describe("Missing profile snapshots", func() {
It("rejects an omitted page even though its neighbors share a grouped mapping", func() {
ctx := context.Background()
bundle, err := assets.Load(ctx)
Expect(err).NotTo(HaveOccurred())
prepared, err := profile.Load(ctx)
Expect(err).NotTo(HaveOccurred())
var metadata Profile
Expect(json.Unmarshal(prepared.Metadata, &metadata)).To(Succeed())
// Bootstrap heap pages are outside both Apple images and the guest heap.
// Drop an interior page so its neighbors still map the omitted address.
var missing uint64
for i := 1; i+1 < len(metadata.Pages); i++ {
address := metadata.Pages[i].Address
if address > 1<<40 && address < heapBase && metadata.Pages[i-1].Address+4096 == address && metadata.Pages[i+1].Address == address+4096 {
missing = address
metadata.Pages = slices.Delete(metadata.Pages, i, i+1)
break
}
}
Expect(missing).NotTo(BeZero())
prepared.Metadata, err = json.Marshal(metadata)
Expect(err).NotTo(HaveOccurred())
guest, err := open(ctx, bundle.AppleMediaServices, prepared, true)
Expect(err).NotTo(HaveOccurred())
DeferCleanup(guest.Close)
Expect(guest.pages[missing]).To(BeTrue())
_, err = guest.engine.MemRead(missing, 8)
Expect(err).To(MatchError(ContainSubstring("missing Store profile page")))
})
})
+87
View File
@@ -0,0 +1,87 @@
package emulator
import "math/bits"
// Swift's Hasher uses SipHash-1-3 with a 72-byte ABI buffer. This implements the
// runtime primitive used by guest dictionaries; no Store signature uses it.
func (r *Runtime) initHasher(address, seed uint64) {
var a, b uint64
if p := r.profile.Symbols["_swift_stdlib_Hashing_parameters"]; p != 0 {
a = r.read64(p)
b = r.read64(p + 8)
}
a ^= seed
values := []uint64{0, 0x736f6d6570736575 ^ a, 0x646f72616e646f6d ^ b, 0x6c7967656e657261 ^ a, 0x7465646279746573 ^ b, 0, 0, 0, 0}
for i, v := range values {
r.write64(address+uint64(i)*8, v)
}
}
func sipRound(v *[4]uint64) {
v[0] += v[1]
v[1] = bits.RotateLeft64(v[1], 13) ^ v[0]
v[0] = bits.RotateLeft64(v[0], 32)
v[2] += v[3]
v[3] = bits.RotateLeft64(v[3], 16) ^ v[2]
v[0] += v[3]
v[3] = bits.RotateLeft64(v[3], 21) ^ v[0]
v[2] += v[1]
v[1] = bits.RotateLeft64(v[1], 17) ^ v[2]
v[2] = bits.RotateLeft64(v[2], 32)
}
func (r *Runtime) hashCompress(address, word uint64, final bool) uint64 {
var v [4]uint64
for i := range v {
v[i] = r.read64(address + 8 + uint64(i)*8)
}
v[3] ^= word
sipRound(&v)
v[0] ^= word
if final {
v[2] ^= 255
for i := 0; i < 3; i++ {
sipRound(&v)
}
}
for i, w := range v {
r.write64(address+8+uint64(i)*8, w)
}
return v[0] ^ v[1] ^ v[2] ^ v[3]
}
func (r *Runtime) hashWord(address, word uint64) {
tail := r.read64(address)
count := tail >> 56
shift := (count & 7) * 8
chunk := word
if shift != 0 {
chunk = (tail & 0xffffffffffffff) | (word << shift)
tail = ((count + 8) << 56) | (word >> (64 - shift))
} else {
tail += (8 << 56)
}
r.write64(address, tail)
r.hashCompress(address, chunk, false)
}
func (r *Runtime) hashBytes(address uint64, data []byte) {
for _, b := range data {
tail := r.read64(address)
count := tail >> 56
shift := (count & 7) * 8
word := (tail & 0xffffffffffffff) | (uint64(b) << shift)
if shift == 56 {
r.hashCompress(address, word, false)
r.write64(address, (count+1)<<56)
} else {
r.write64(address, ((count+1)<<56)|word)
}
}
}
+76
View File
@@ -0,0 +1,76 @@
package emulator
import (
"errors"
"fmt"
"slices"
)
const (
profilePageSize = uint64(4096)
maxRegionGap = uint64(1 << 20)
maxRegionSize = uint64(32 << 20)
maxProfileSpan = uint64(1 << 30)
)
type memoryRegion struct{ address, size uint64 }
// Group nearby pages to avoid rebuilding Unicorn's memory topology thousands of
// times during both mapping and teardown. Bound individual and total spans so a
// chain of small gaps cannot silently reserve an arbitrarily large address range.
// Executable addresses are still checked against the pinned code ranges by step.
func groupPages(addresses []uint64) ([]memoryRegion, error) {
slices.Sort(addresses)
for _, address := range addresses {
if address%profilePageSize != 0 || address > ^uint64(0)-profilePageSize {
return nil, errors.New("invalid Store profile page address")
}
}
var regions []memoryRegion
var total uint64
for start := 0; start < len(addresses); {
end := start + 1
for end < len(addresses) && addresses[end]-addresses[end-1] <= maxRegionGap && addresses[end]-addresses[start]+profilePageSize <= maxRegionSize {
end++
}
size := addresses[end-1] - addresses[start] + profilePageSize
if size > maxProfileSpan-total {
return nil, errors.New("store profile mapping exceeds size limit")
}
total += size
regions = append(regions, memoryRegion{address: addresses[start], size: size})
start = end
}
return regions, nil
}
// checkProfileAccess checks every touched page, including accesses that start in
// a valid page and cross a gap. Grouping padding is never a valid dependency.
func checkProfileAccess(allowed map[uint64]bool, address, size uint64) error {
if size == 0 {
return nil
}
if size-1 > ^uint64(0)-address {
return errors.New("store memory access overflows address space")
}
last := (address + size - 1) &^ (profilePageSize - 1)
for page := address &^ (profilePageSize - 1); ; page += profilePageSize {
if !allowed[page] {
return fmt.Errorf("missing Store profile page %#x for access %#x (%d bytes)", page, address, size)
}
if page == last {
return nil
}
}
}
+66
View File
@@ -0,0 +1,66 @@
package emulator
import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Store memory grouping", func() {
It("groups nearby unsorted pages and tolerates duplicates", func() {
regions, err := groupPages([]uint64{0x3000, 0x1000, 0x1000, 0x800000})
Expect(err).NotTo(HaveOccurred())
Expect(regions).To(Equal([]memoryRegion{{0x1000, 0x3000}, {0x800000, 4096}}))
})
It("bounds groups even when many nearby pages form a long chain", func() {
var pages []uint64
for address := uint64(0); address < 3*maxRegionSize; address += maxRegionGap {
pages = append(pages, address)
}
regions, err := groupPages(pages)
Expect(err).NotTo(HaveOccurred())
for _, region := range regions {
Expect(region.size).To(BeNumerically("<=", maxRegionSize))
}
for _, address := range pages {
covered := false
for _, region := range regions {
covered = covered || address >= region.address && address+profilePageSize <= region.address+region.size
}
Expect(covered).To(BeTrue())
}
})
It("rejects excessive total mapped memory", func() {
var pages []uint64
for address := uint64(0); address < 2*maxProfileSpan; address += maxRegionGap {
pages = append(pages, address)
}
_, err := groupPages(pages)
Expect(err).To(MatchError(ContainSubstring("size limit")))
})
It("rejects unaligned and overflowing pages", func() {
for _, address := range []uint64{1, ^uint64(0) - 4095} {
_, err := groupPages([]uint64{address})
Expect(err).To(MatchError(ContainSubstring("page address")))
}
})
It("still rejects execution in padding outside the pinned code", func() {
guest := &Runtime{codeRanges: [][2]uint64{{0x1000, 0x2000}}}
guest.step(0x3000, 4)
Expect(guest.fault).To(MatchError(ContainSubstring("execution outside the pinned image")))
})
})
var _ = Describe("Profile dependency checks", func() {
It("checks the complete range rather than just the first or last page", func() {
allowed := map[uint64]bool{0x1000: true, 0x3000: true}
Expect(checkProfileAccess(allowed, 0x1ffc, 8)).To(MatchError(ContainSubstring("missing Store profile page 0x2000")))
Expect(checkProfileAccess(allowed, 0x1000, 0x2001)).To(MatchError(ContainSubstring("missing Store profile page 0x2000")))
Expect(checkProfileAccess(allowed, 0x1000, 4096)).To(Succeed())
Expect(checkProfileAccess(allowed, 0x3000, 4096)).To(Succeed())
})
It("handles empty accesses and rejects wrapping ranges", func() {
Expect(checkProfileAccess(nil, ^uint64(0), 0)).To(Succeed())
Expect(checkProfileAccess(nil, ^uint64(0), 2)).To(MatchError(ContainSubstring("overflows")))
Expect(checkProfileAccess(map[uint64]bool{^uint64(4095): true}, ^uint64(0), 1)).To(Succeed())
})
})
+171
View File
@@ -0,0 +1,171 @@
package emulator
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
"strconv"
)
// Keep one immutable template, bounded independently of the number of requests.
// The content digest prevents stale metadata reuse when callers change profiles.
var cachedMetadata = metadataCache{gate: make(chan struct{}, 1)}
type metadataCache struct {
gate chan struct{}
digest [sha256.Size]byte
prepared *runtimeMetadata
}
type runtimeMetadata struct {
profile Profile
classes map[string]*Class
classNames map[uint64]string
methods map[string]uint64
calls map[uint64]Call
selectors map[uint64]string
selectorAddresses map[string]uint64
objects map[uint64]Object
entries map[uint64]string
}
func (c *metadataCache) load(ctx context.Context, raw []byte) (*runtimeMetadata, error) {
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("load Store metadata: %w", err)
}
digest := sha256.Sum256(raw)
select {
case c.gate <- struct{}{}:
case <-ctx.Done():
return nil, fmt.Errorf("load Store metadata: %w", ctx.Err())
}
defer func() { <-c.gate }()
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("load Store metadata: %w", err)
}
if c.prepared != nil && c.digest == digest {
return c.prepared, nil
}
prepared, err := prepareMetadata(raw)
if err != nil {
return nil, err
}
if err = ctx.Err(); err != nil {
return nil, fmt.Errorf("load Store metadata: %w", err)
}
c.prepared, c.digest = prepared, digest
return prepared, nil
}
func prepareMetadata(raw []byte) (*runtimeMetadata, error) {
var profile Profile
if err := json.Unmarshal(raw, &profile); err != nil {
return nil, fmt.Errorf("decode Store metadata: %w", err)
}
if profile.UUID != "5DFC37A5-4689-3F9D-9655-D4774E1D8D08" {
return nil, errors.New("unsupported Store profile UUID")
}
// Pinned dyld lazy-import thunk, verified against its resolved import slot
// (0x1eaaee178). This is a host diagnostics preference, not Store logic.
profile.Calls = append(profile.Calls, Call{Address: 0x1a2d0fb94, Symbol: "CRIsAutoSubmitEnabled"})
m := &runtimeMetadata{profile: profile, classes: map[string]*Class{}, classNames: map[uint64]string{}, methods: map[string]uint64{}, calls: map[uint64]Call{}, selectors: map[uint64]string{}, selectorAddresses: map[string]uint64{}, objects: map[uint64]Object{}, entries: map[uint64]string{}}
for i := range m.profile.Classes {
class := &m.profile.Classes[i]
m.classes[class.Name] = class
m.classNames[class.Address] = class.Name
if class.MetaAddress != 0 {
m.classNames[class.MetaAddress] = class.Name
}
for _, method := range class.Methods {
key := methodKey(class.Name, method.Selector, method.ClassMethod)
m.methods[key] = method.Address
m.entries[method.Address] = key
}
}
for key, value := range profile.Strings {
address, err := strconv.ParseUint(key, 10, 64)
if err != nil {
return nil, fmt.Errorf("decode Store string address: %w", err)
}
m.objects[address] = Object{Class: "NSString", Value: value}
}
for key, value := range profile.Constants {
address, err := strconv.ParseUint(key, 10, 64)
if err != nil {
return nil, fmt.Errorf("decode Store constant address: %w", err)
}
var data any
switch value.Kind {
case "NSString":
data = value.Text
case "NSNumber":
data = value.Number
if value.IsBoolean {
data = value.Boolean
}
case "NSDictionary":
data = value.Entries
case "NSArray", "NSSet":
data = value.Items
}
m.objects[address] = Object{Class: value.Kind, Value: data}
}
for _, call := range profile.Calls {
m.calls[call.Address] = call
if call.Selector != "" {
m.selectors[call.SelectorAddress] = call.Selector
m.selectorAddresses[call.Selector] = call.SelectorAddress
}
}
// These JSON tables have been converted to address-indexed templates above.
// Retain only that representation for the lifetime of the process.
m.profile.Strings = nil
m.profile.Constants = nil
return m, nil
}
func (m *runtimeMetadata) newRuntime() *Runtime {
// Class definitions, call sites and entry names are immutable. The maps used
// for dynamic classes, methods and selectors belong to each individual VM.
r := &Runtime{profile: m.profile, classes: maps.Clone(m.classes), classNames: maps.Clone(m.classNames), methods: maps.Clone(m.methods), calls: m.calls, selectors: maps.Clone(m.selectors), selectorAddresses: maps.Clone(m.selectorAddresses), entries: m.entries, objects: make(map[uint64]*Object, len(m.objects)), pages: map[uint64]bool{}}
for address, object := range m.objects {
instance := object
switch value := object.Value.(type) {
case map[string]uint64:
instance.Value = maps.Clone(value)
case []uint64:
instance.Value = slices.Clone(value)
}
r.objects[address] = &instance
}
return r
}
+95
View File
@@ -0,0 +1,95 @@
package emulator
import (
"context"
"encoding/json"
"sync"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Prepared Store metadata", func() {
var cache metadataCache
var raw []byte
BeforeEach(func() {
cache = metadataCache{gate: make(chan struct{}, 1)}
var err error
raw, err = json.Marshal(Profile{
UUID: "5DFC37A5-4689-3F9D-9655-D4774E1D8D08",
Strings: map[string]string{"8192": "original"},
Constants: map[string]Constant{
"4096": {Kind: "NSDictionary", Entries: map[string]uint64{"value": 8192}},
"12288": {Kind: "NSArray", Items: []uint64{8192}},
},
Classes: []Class{{Name: "NSObject", Address: 16384, Size: 16}},
})
Expect(err).NotTo(HaveOccurred())
})
It("reuses metadata by content and rejects changed invalid metadata", func() {
first, err := cache.load(context.Background(), raw)
Expect(err).NotTo(HaveOccurred())
second, err := cache.load(context.Background(), append([]byte(nil), raw...))
Expect(err).NotTo(HaveOccurred())
Expect(second).To(BeIdenticalTo(first))
_, err = cache.load(context.Background(), []byte(`{"UUID":"wrong"}`))
Expect(err).To(MatchError(ContainSubstring("unsupported Store profile")))
_, err = cache.load(context.Background(), []byte(`invalid json`))
Expect(err).To(HaveOccurred())
second, err = cache.load(context.Background(), raw)
Expect(err).NotTo(HaveOccurred())
Expect(second).To(BeIdenticalTo(first))
})
It("does not share mutable constants or dynamic registrations between VMs", func() {
prepared, err := cache.load(context.Background(), raw)
Expect(err).NotTo(HaveOccurred())
first, second := prepared.newRuntime(), prepared.newRuntime()
first.objects[4096].Value.(map[string]uint64)["value"] = 99
first.objects[12288].Value.([]uint64)[0] = 99
first.objects[8192].Value = "changed"
first.objects[8192].Properties = map[string]uint64{"account": 99}
first.classes["OnlyFirst"] = &Class{Name: "OnlyFirst"}
first.classNames[99] = "OnlyFirst"
first.methods["dynamic"] = 99
first.selectors[99] = "dynamic"
first.selectorAddresses["dynamic"] = 99
for _, guest := range []*Runtime{second, prepared.newRuntime()} {
Expect(guest.objects[4096].Value.(map[string]uint64)["value"]).To(Equal(uint64(8192)))
Expect(guest.objects[12288].Value).To(Equal([]uint64{8192}))
Expect(guest.objects[8192].Value).To(Equal("original"))
Expect(guest.objects[8192].Properties).To(BeEmpty())
Expect(guest.classes).NotTo(HaveKey("OnlyFirst"))
Expect(guest.classNames).NotTo(HaveKey(uint64(99)))
Expect(guest.methods).NotTo(HaveKey("dynamic"))
Expect(guest.selectors).NotTo(HaveKey(uint64(99)))
Expect(guest.selectorAddresses).NotTo(HaveKey("dynamic"))
}
})
It("prepares one template for concurrent independent runtimes", func() {
var wg sync.WaitGroup
prepared := make([]*runtimeMetadata, 8)
for i := range prepared {
wg.Go(func() {
defer GinkgoRecover()
var err error
prepared[i], err = cache.load(context.Background(), raw)
Expect(err).NotTo(HaveOccurred())
guest := prepared[i].newRuntime()
guest.objects[4096].Value.(map[string]uint64)["value"] = uint64(i)
})
}
wg.Wait()
for _, value := range prepared {
Expect(value).To(BeIdenticalTo(prepared[0]))
}
Expect(prepared[0].objects[4096].Value.(map[string]uint64)["value"]).To(Equal(uint64(8192)))
})
It("honors cancellation while another preparation holds the cache", func() {
cache.gate <- struct{}{}
defer func() { <-cache.gate }()
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := cache.load(ctx, raw)
Expect(err).To(MatchError(context.Canceled))
})
})
+990
View File
@@ -0,0 +1,990 @@
package emulator
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math"
"net/http"
"net/url"
"strings"
"time"
"github.com/majd/ipatool/v2/internal/sap/unicorn"
"howett.net/plist"
)
func (r *Runtime) hostBlock(fn func()) uint64 {
function := r.alloc(16)
if err := r.MemWrite(function, []byte{0xc0, 0x03, 0x5f, 0xd6}); err != nil {
panic(err)
}
r.callbacks[function] = fn
descriptor := r.alloc(16)
r.write64(descriptor+8, 32)
block := r.alloc(32)
r.write64(block+8, 1<<28)
r.write64(block+16, function)
r.write64(block+24, descriptor)
return block
}
func (r *Runtime) importValue(value any) uint64 {
switch v := value.(type) {
case nil:
return 0
case string:
return r.New("NSString", v)
case []byte:
return r.New("NSData", v)
case time.Time:
return r.New("NSDate", v)
case bool:
return r.New("NSNumber", v)
case int:
return r.New("NSNumber", int64(v))
case int64:
return r.New("NSNumber", v)
case uint64:
return r.New("NSNumber", int64(v))
case float64:
if math.Trunc(v) == v && v >= math.MinInt64 && v < math.MaxInt64 {
return r.New("NSNumber", int64(v))
}
return r.New("NSNumber", v)
case []any:
result := make([]uint64, len(v))
for i, x := range v {
result[i] = r.importValue(x)
}
return r.New("NSArray", result)
case map[string]any:
result := map[string]uint64{}
for k, x := range v {
result[k] = r.importValue(x)
}
return r.New("NSDictionary", result)
default:
panic(fmt.Sprintf("unsupported Foundation import %T", v))
}
}
func (r *Runtime) networkMessage(receiver uint64, class, selector string, meta bool) bool {
object := r.objects[receiver]
if !meta && class == "NSURLSessionConfiguration" && (selector == "_allowsTCPFastOpen" || selector == "_allowsTLSSessionTickets" || selector == "URLCache") {
// These optional CFNetwork facilities are absent from the transport.
r.set(0)
return true
}
if !meta && class == "NSHTTPURLResponse" && selector == "_CFURLResponse" {
r.set(receiver)
return true
}
if !meta && class == "NSURLSessionDataTask" && selector == "_timingData" {
// The portable transport has no CFNetwork timing-data object.
r.set(0)
return true
}
if !meta && class == "AKAppleIDSession" && selector == "handleResponse:forRequest:shouldRetry:" {
// Pinned AuthKit _canHandleAnisetteURLResponse: accepts exactly these
// challenge status codes. All other responses leave shouldRetry false.
status := r.objects[r.arg(2)].Properties["statusCode"]
switch status {
case 431, 433, 434, 441, 442, 443, 444:
panic("AuthKit anisette challenge is not supported")
}
if out := r.arg(4); out != 0 {
if err := r.MemWrite(out, []byte{0}); err != nil {
panic(err)
}
}
r.set(0)
return true
}
if meta {
switch {
case class == "NSURLComponents" && selector == "componentsWithURL:resolvingAgainstBaseURL:":
value, err := url.Parse(r.String(r.arg(2)))
if err != nil {
r.set(0)
} else {
r.set(r.New("NSURLComponents", value))
}
case class == "NSURLCache" && selector == "sharedURLCache":
r.set(0)
case class == "NSJSONSerialization" && selector == "isValidJSONObject:":
r.set(boolValue(r.validJSONObject(r.arg(2), true, 0)))
case class == "NSURLQueryItem" && selector == "queryItemWithName:value:":
item := r.New(class, nil)
r.objects[item].Properties = map[string]uint64{"name": r.arg(2), "value": r.arg(3)}
r.set(item)
case class == "NSHTTPCookie" && selector == "cookieWithProperties:":
fields := r.objects[r.arg(2)].Value.(map[string]uint64)
cookie := &http.Cookie{Name: r.String(fields["Name"]), Value: r.String(fields["Value"]), Domain: r.String(fields["Domain"]), Path: r.String(fields["Path"])}
if value := fields["Secure"]; value != 0 {
cookie.Secure = strings.EqualFold(fmt.Sprint(r.objects[value].Value), "TRUE")
}
if value := fields["HttpOnly"]; value != 0 {
cookie.HttpOnly = strings.EqualFold(fmt.Sprint(r.objects[value].Value), "TRUE")
}
if value := fields["Expires"]; value != 0 {
cookie.Expires, _ = r.objects[value].Value.(time.Time)
}
r.set(r.New("NSHTTPCookie", cookie))
case class == "NSHTTPCookie" && selector == "requestHeaderFieldsWithCookies:":
request := &http.Request{Header: http.Header{}}
for _, item := range r.objects[r.arg(2)].Value.([]uint64) {
request.AddCookie(r.objects[item].Value.(*http.Cookie))
}
fields := map[string]uint64{}
if value := request.Header.Get("Cookie"); value != "" {
fields["Cookie"] = r.New("NSString", value)
}
r.set(r.New("NSDictionary", fields))
case class == "NSHTTPCookie" && selector == "cookiesWithResponseHeaderFields:forURL:":
h := http.Header{}
for k, v := range r.objects[r.arg(2)].Value.(map[string]uint64) {
h.Set(k, r.String(v))
}
if raw := r.responseHeaders[r.arg(2)]; raw != nil {
h = raw.Clone()
}
response := &http.Response{Header: h}
cookies := response.Cookies()
items := make([]uint64, 0, len(cookies))
for _, cookie := range cookies {
origin, _ := url.Parse(r.String(r.arg(3)))
if cookie.Domain == "" {
cookie.Domain = origin.Hostname()
} else if !strings.HasPrefix(cookie.Domain, ".") {
cookie.Domain = "." + cookie.Domain
}
if cookie.Path == "" {
cookie.Path = "/"
}
items = append(items, r.New("NSHTTPCookie", cookie))
}
r.set(r.New("NSArray", items))
case class == "NSURLSession" && selector == "sessionWithConfiguration:delegate:delegateQueue:":
session := r.New("NSURLSession", nil)
r.objects[session].Properties = map[string]uint64{"configuration": r.arg(2), "delegate": r.arg(3), "delegateQueue": r.arg(4)}
r.set(session)
case (class == "NSURLRequest" || class == "NSMutableURLRequest") && selector == "requestWithURL:":
req := r.New(class, nil)
r.objects[req].Properties = map[string]uint64{"URL": r.arg(2), "HTTPMethod": r.New("NSString", "GET"), "allHTTPHeaderFields": r.New("NSMutableDictionary", map[string]uint64{})}
r.set(req)
case class == "NSJSONSerialization" && selector == "JSONObjectWithData:options:error:":
var v any
err := json.Unmarshal(r.objects[r.arg(2)].Value.([]byte), &v)
if err != nil {
r.parserError(r.arg(4))
r.set(0)
return true
}
r.set(r.importValue(v))
case class == "NSPropertyListSerialization" && selector == "propertyList:isValidForFormat:":
v, err := r.Export(r.arg(2))
if err == nil {
_, err = plist.Marshal(v, plist.XMLFormat)
}
r.set(boolValue(err == nil))
case class == "NSPropertyListSerialization" && selector == "propertyListWithData:options:format:error:":
var v any
_, err := plist.Unmarshal(r.objects[r.arg(2)].Value.([]byte), &v)
if err != nil {
r.parserError(r.arg(5))
r.set(0)
return true
}
r.set(r.importValue(v))
case class == "NSPropertyListSerialization" && selector == "dataWithPropertyList:format:options:error:":
v, err := r.Export(r.arg(2))
if err != nil {
panic(err)
}
format := plist.XMLFormat
if r.arg(3) == 200 {
format = plist.BinaryFormat
}
data, err := plist.Marshal(v, format)
if err != nil {
panic(err)
}
r.set(r.New("NSData", data))
default:
return false
}
return true
}
if selector == "initWithIndexesInRange:" && class == "NSIndexSet" {
object.Value = [2]uint64{r.arg(2), r.arg(3)}
r.set(receiver)
return true
}
if selector == "containsIndex:" && class == "NSIndexSet" {
v := object.Value.([2]uint64)
r.set(boolValue(r.arg(2) >= v[0] && r.arg(2)-v[0] < v[1]))
return true
}
if selector == "initWithURL:" && r.kindOf(class, "NSURLRequest") {
_ = r.engine.RegWrite(unicorn.RegX3, 0)
_ = r.engine.RegWrite(40, math.Float64bits(60))
r.message(receiver, "initWithURL:cachePolicy:timeoutInterval:", false)
return true
}
if selector == "initWithURL:cachePolicy:timeoutInterval:" && r.kindOf(class, "NSURLRequest") {
object.Properties = map[string]uint64{"URL": r.arg(2), "cachePolicy": r.arg(3), "HTTPMethod": r.New("NSString", "GET"), "allHTTPHeaderFields": r.New("NSMutableDictionary", map[string]uint64{})}
r.set(receiver)
return true
}
if class == "NSHTTPURLResponse" && selector == "valueForHTTPHeaderField:" {
fields := r.objects[object.Properties["allHeaderFields"]].Value.(map[string]uint64)
for k, v := range fields {
if strings.EqualFold(k, r.String(r.arg(2))) {
r.set(v)
return true
}
}
r.set(0)
return true
}
if r.kindOf(class, "NSURLRequest") {
switch selector {
case "HTTPBody", "HTTPBodyStream":
// Bodyless requests have nil bodies. The framework inspects these
// optional properties when handling redirects, even if no setter ran.
r.set(object.Properties[selector])
return true
case "copy", "copyWithZone:", "mutableCopy", "mutableCopyWithZone:":
if selector == "copy" || selector == "mutableCopy" {
zone := selector + "WithZone:"
if entry := r.lookup(class, zone, false); entry != 0 {
_ = r.engine.RegWrite(unicorn.RegX2, 0)
r.jump(entry, receiver, zone)
return true
}
}
copied := r.New(class, object.Value)
for key, value := range object.Properties {
r.objects[copied].Properties[key] = value
}
if h := object.Properties["allHTTPHeaderFields"]; h != 0 {
r.objects[copied].Properties["allHTTPHeaderFields"] = r.foundationCopy(h, true)
}
r.set(copied)
return true
case "_CFURLRequest":
r.set(receiver)
return true
case "_initWithCFURLRequest:":
source := r.objects[r.arg(2)]
object.Properties = map[string]uint64{}
for k, v := range source.Properties {
object.Properties[k] = v
}
if h := object.Properties["allHTTPHeaderFields"]; h != 0 {
object.Properties["allHTTPHeaderFields"] = r.foundationCopy(h, true)
}
r.set(receiver)
return true
case "setValue:forHTTPHeaderField:", "addValue:forHTTPHeaderField:":
if object.Properties["allHTTPHeaderFields"] == 0 {
object.Properties["allHTTPHeaderFields"] = r.New("NSMutableDictionary", map[string]uint64{})
}
fields := r.objects[object.Properties["allHTTPHeaderFields"]].Value.(map[string]uint64)
key := http.CanonicalHeaderKey(r.String(r.arg(3)))
if r.arg(2) == 0 {
delete(fields, key)
} else {
fields[key] = r.arg(2)
}
r.set(0)
return true
case "valueForHTTPHeaderField:":
fields := r.objects[object.Properties["allHTTPHeaderFields"]].Value.(map[string]uint64)
r.set(fields[http.CanonicalHeaderKey(r.String(r.arg(2)))])
return true
}
}
if class == "NSURLSession" && selector == "dataTaskWithRequest:" {
task := r.New("NSURLSessionDataTask", nil)
r.objects[task].Properties = map[string]uint64{"currentRequest": r.arg(2), "originalRequest": r.arg(2), "session": receiver, "taskIdentifier": task, "state": 1}
r.set(task)
return true
}
if class == "NSURLSessionDataTask" && selector == "resume" {
if object.Properties["state"] != 1 {
panic("task resumed twice")
}
object.Properties["state"] = 0
r.pending = append(r.pending, r.hostBlock(func() { r.performHTTP(receiver) }))
r.set(0)
return true
}
if (class == "NSURLSession" && (selector == "invalidateAndCancel" || selector == "finishTasksAndInvalidate")) || (class == "NSURLSessionDataTask" && selector == "cancel") {
r.set(0)
return true
}
if class == "NSURLSession" || class == "NSURLSessionDataTask" || class == "NSHTTPURLResponse" || class == "NSURLResponse" || r.kindOf(class, "NSURLRequest") {
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
}
if value, ok := object.Properties[selector]; ok {
r.set(value)
return true
}
}
if class == "NSHTTPCookie" {
if selector == "initWithProperties:" {
fields := r.objects[r.arg(2)].Value.(map[string]uint64)
cookie := &http.Cookie{Name: r.String(fields["Name"]), Value: r.String(fields["Value"]), Domain: r.String(fields["Domain"]), Path: r.String(fields["Path"])}
if p := fields["Secure"]; p != 0 {
cookie.Secure = strings.EqualFold(fmt.Sprint(r.objects[p].Value), "TRUE")
}
if p := fields["HttpOnly"]; p != 0 {
cookie.HttpOnly = strings.EqualFold(fmt.Sprint(r.objects[p].Value), "TRUE")
}
if p := fields["Expires"]; p != 0 {
cookie.Expires, _ = r.objects[p].Value.(time.Time)
}
object.Value = cookie
r.set(receiver)
return true
}
cookie := object.Value.(*http.Cookie)
switch selector {
case "properties":
fields := map[string]any{"Name": cookie.Name, "Value": cookie.Value, "Domain": cookie.Domain, "Path": cookie.Path, "Created": time.Now().Unix() - 978307200}
if cookie.Secure {
fields["Secure"] = "TRUE"
}
if cookie.HttpOnly {
fields["HttpOnly"] = "TRUE"
}
if cookie.Expires.IsZero() {
fields["Discard"] = "TRUE"
} else {
fields["Expires"] = cookie.Expires
}
r.set(r.importValue(fields))
return true
case "name":
r.set(r.New("NSString", cookie.Name))
return true
case "domain":
r.set(r.New("NSString", cookie.Domain))
return true
case "path":
r.set(r.New("NSString", cookie.Path))
return true
case "value":
r.set(r.New("NSString", cookie.Value))
return true
case "expiresDate":
if cookie.Expires.IsZero() {
r.set(0)
} else {
r.set(r.New("NSDate", cookie.Expires))
}
return true
case "isSessionOnly":
r.set(boolValue(cookie.Expires.IsZero()))
return true
case "version":
r.set(0)
return true
case "isSecure":
r.set(boolValue(cookie.Secure))
return true
case "isHTTPOnly":
r.set(boolValue(cookie.HttpOnly))
return true
}
}
if class == "NSURLQueryItem" && (selector == "name" || selector == "value") {
r.set(object.Properties[selector])
return true
}
if class == "NSURLComponents" {
if selector == "initWithURL:resolvingAgainstBaseURL:" {
u, err := url.Parse(r.String(r.arg(2)))
if err != nil {
panic(err)
}
object.Value = u
r.set(receiver)
return true
}
u := object.Value.(*url.URL)
switch selector {
case "setQuery:":
u.RawQuery = ""
u.ForceQuery = r.arg(2) != 0
if r.arg(2) != 0 {
u.RawQuery = encodeComponentQuery(r.String(r.arg(2)))
}
r.set(0)
return true
case "query", "percentEncodedQuery":
if u.RawQuery == "" && !u.ForceQuery {
r.set(0)
} else {
value := u.RawQuery
if selector == "query" {
var err error
value, err = url.PathUnescape(value)
if err != nil {
panic("invalid URL query encoding")
}
}
r.set(r.New("NSString", value))
}
return true
case "setFragment:":
u.Fragment = r.String(r.arg(2))
u.RawFragment = ""
r.set(0)
return true
case "URL":
r.set(r.New("NSURL", u.String()))
return true
case "queryItems", "percentEncodedQueryItems":
items := []uint64{}
if u.RawQuery != "" {
for _, part := range strings.Split(u.RawQuery, "&") {
key, value, hasValue := strings.Cut(part, "=")
if selector == "queryItems" {
key, _ = url.QueryUnescape(strings.ReplaceAll(key, "+", "%2B"))
value, _ = url.QueryUnescape(strings.ReplaceAll(value, "+", "%2B"))
}
item := r.New("NSURLQueryItem", nil)
r.objects[item].Properties["name"] = r.New("NSString", key)
if hasValue {
r.objects[item].Properties["value"] = r.New("NSString", value)
}
items = append(items, item)
}
}
r.set(r.New("NSArray", items))
return true
case "setQueryItems:", "setPercentEncodedQueryItems:":
parts := []string{}
if r.arg(2) != 0 {
for _, item := range r.objects[r.arg(2)].Value.([]uint64) {
p := r.objects[item].Properties
part := strings.ReplaceAll(url.QueryEscape(r.String(p["name"])), "+", "%20")
if p["value"] != 0 {
part += "=" + strings.ReplaceAll(url.QueryEscape(r.String(p["value"])), "+", "%20")
}
if selector == "setPercentEncodedQueryItems:" {
part = r.String(p["name"])
if p["value"] != 0 {
part += "=" + r.String(p["value"])
}
}
parts = append(parts, part)
}
}
u.RawQuery = strings.Join(parts, "&")
r.set(0)
return true
}
}
if class == "NSURL" {
u, err := url.Parse(object.Value.(string))
if err != nil {
panic(err)
}
switch selector {
case "URLByAppendingPathComponent:", "URLByAppendingPathComponent:isDirectory:":
value, err := url.JoinPath(u.String(), r.String(r.arg(2)))
if err != nil {
panic(err)
}
r.set(r.New("NSURL", value))
return true
case "fileSystemRepresentation":
value := append([]byte(u.Path), 0)
p := r.alloc(uint64(len(value)))
_ = r.MemWrite(p, value)
r.set(p)
return true
case "isFileURL":
r.set(boolValue(u.Scheme == "file"))
return true
case "fragment":
if u.Fragment == "" {
r.set(0)
} else {
r.set(r.New("NSString", u.Fragment))
}
return true
case "host":
r.set(r.New("NSString", u.Hostname()))
return true
case "scheme":
r.set(r.New("NSString", u.Scheme))
return true
case "query":
r.set(r.New("NSString", u.RawQuery))
return true
}
}
if class == "NSData" || class == "NSMutableData" {
switch selector {
case "bytes":
data, _ := object.Value.([]byte)
p := r.alloc(uint64(len(data)))
_ = r.MemWrite(p, data)
r.set(p)
return true
case "appendBytes:length:":
size := r.arg(3)
if size > 32<<20 {
panic("data append exceeds budget")
}
other, err := r.engine.MemRead(r.arg(2), size)
if err != nil {
panic(err)
}
data, _ := object.Value.([]byte)
object.Value = append(data, other...)
r.set(0)
return true
case "appendData:":
other := r.objects[r.arg(2)].Value.([]byte)
data, _ := object.Value.([]byte)
object.Value = append(data, other...)
r.set(0)
return true
}
}
return false
}
func encodeComponentQuery(query string) string {
const hexadecimal = "0123456789ABCDEF"
var encoded strings.Builder
for index := 0; index < len(query); index++ {
character := query[index]
if character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' ||
character >= '0' && character <= '9' || strings.IndexByte("-._~!$&'()*+,;=:@/?", character) >= 0 {
encoded.WriteByte(character)
} else {
encoded.WriteByte('%')
encoded.WriteByte(hexadecimal[character>>4])
encoded.WriteByte(hexadecimal[character&15])
}
}
return encoded.String()
}
func (r *Runtime) validJSONObject(address uint64, top bool, depth int) bool {
if depth > 64 {
return false
}
object := r.objects[address]
if object == nil {
return false
}
switch value := object.Value.(type) {
case map[string]uint64:
for _, child := range value {
if !r.validJSONObject(child, false, depth+1) {
return false
}
}
return true
case []uint64:
if !strings.Contains(object.Class, "Array") {
return false
}
for _, child := range value {
if !r.validJSONObject(child, false, depth+1) {
return false
}
}
return true
case string, bool, int64:
return !top
case float64:
return !top && !math.IsInf(value, 0) && !math.IsNaN(value)
default:
return !top && object.Class == "NSNull"
}
}
func (r *Runtime) performHTTP(task uint64) {
t := r.objects[task]
req := r.objects[t.Properties["currentRequest"]]
endpoint := r.String(req.Properties["URL"])
u, err := url.Parse(endpoint)
if err != nil || !allowedURL(u, r.authRequest || !r.streamResponse) {
panic("unsupported transport URL")
}
var body []byte
if p := req.Properties["HTTPBody"]; p != 0 {
body = r.objects[p].Value.([]byte)
}
request, err := http.NewRequestWithContext(r.ctx, r.String(req.Properties["HTTPMethod"]), endpoint, bytes.NewReader(body))
if err != nil {
panic("cannot construct transport request")
}
if p := req.Properties["allHTTPHeaderFields"]; p != 0 {
for k, v := range r.objects[p].Value.(map[string]uint64) {
request.Header.Set(k, r.String(v))
}
}
var response *http.Response
response, err = r.transport(request)
if err != nil {
r.transportError = err
panic("Store HTTP transport failed")
}
redirect := response.StatusCode == http.StatusMovedPermanently || response.StatusCode == http.StatusFound || response.StatusCode == http.StatusSeeOther || response.StatusCode == http.StatusTemporaryRedirect || response.StatusCode == http.StatusPermanentRedirect
var data []byte
if r.streamResponse && !redirect {
r.lastResponse = response
} else {
data, err = io.ReadAll(io.LimitReader(response.Body, (32<<20)+1))
_ = response.Body.Close()
if err != nil {
r.transportError = err
panic("Store HTTP response read failed")
}
if len(data) > 32<<20 {
panic("Store API response exceeds size limit")
}
copied := *response
copied.Header = response.Header.Clone()
copied.Body = io.NopCloser(bytes.NewReader(data))
r.lastResponse = &copied
}
headers := map[string]uint64{}
for k, v := range response.Header {
headers[k] = r.New("NSString", strings.Join(v, ", "))
}
headerObject := r.New("NSDictionary", headers)
if r.responseHeaders == nil {
r.responseHeaders = map[uint64]http.Header{}
}
r.responseHeaders[headerObject] = response.Header.Clone()
res := r.New("NSHTTPURLResponse", nil)
r.objects[res].Properties = map[string]uint64{"statusCode": uint64(response.StatusCode), "allHeaderFields": headerObject, "URL": req.Properties["URL"], "MIMEType": r.New("NSString", strings.Split(response.Header.Get("Content-Type"), ";")[0]), "expectedContentLength": uint64(response.ContentLength)}
t.Properties["response"] = res
session := t.Properties["session"]
delegate := r.objects[session].Properties["delegate"]
completion := r.hostBlock(func() {
if r.arg(1) != 1 {
panic("framework rejected response")
}
r.pending = append(r.pending, r.hostBlock(func() {
r.delegateCall(delegate, "URLSession:dataTask:didReceiveData:", []uint64{session, task, r.New("NSData", data)}, func() {
r.pending = append(r.pending, r.hostBlock(func() {
t.Properties["state"] = 3
r.delegateCall(delegate, "URLSession:task:didCompleteWithError:", []uint64{session, task, 0}, func() { r.set(0) })
}))
r.set(0)
})
}))
r.set(0)
})
deliver := func() {
r.delegateCall(delegate, "URLSession:dataTask:didReceiveResponse:completionHandler:", []uint64{session, task, res, completion}, func() { r.set(0) })
}
if redirect && !r.noRedirects {
destination, e := response.Location()
if e != nil {
deliver()
return
}
if t.Properties["redirectCount"] >= 4 {
panic("redirect limit exceeded")
}
if !allowedURL(destination, r.authRequest || !r.streamResponse) || (r.authRequest && (response.StatusCode == http.StatusSeeOther || destination.Port() != "" && destination.Port() != "443" || destination.RawPath != "" || !strings.HasSuffix(destination.Hostname(), "buy.itunes.apple.com") || strings.TrimRight(destination.Path, "/") != "/WebObjects/MZFinance.woa/wa/authenticate")) {
panic("invalid Store redirect destination")
}
proposed := r.New("NSMutableURLRequest", nil)
p := r.objects[proposed]
for k, v := range req.Properties {
p.Properties[k] = v
}
p.Properties["URL"] = r.New("NSURL", destination.String())
fields := map[string]uint64{}
if h := req.Properties["allHTTPHeaderFields"]; h != 0 {
for k, v := range r.objects[h].Value.(map[string]uint64) {
fields[k] = v
}
}
if destination.Hostname() != u.Hostname() {
for _, k := range []string{"Authorization", "Cookie", "X-Token", "X-Dsid", "Icloud-Dsid"} {
delete(fields, k)
}
}
if response.StatusCode == http.StatusSeeOther || ((response.StatusCode == http.StatusMovedPermanently || response.StatusCode == http.StatusFound) && r.String(req.Properties["HTTPMethod"]) == "POST") {
p.Properties["HTTPMethod"] = r.New("NSString", "GET")
p.Properties["HTTPBody"] = 0
delete(fields, "Content-Length")
delete(fields, "Content-Type")
}
p.Properties["allHTTPHeaderFields"] = r.New("NSMutableDictionary", fields)
redirectCompletion := r.hostBlock(func() {
next := r.arg(1)
if next == 0 {
deliver()
return
}
if r.objects[next] == nil {
panic("invalid redirected request")
}
t.Properties["currentRequest"] = next
t.Properties["redirectCount"]++
r.queuePending(r.hostBlock(func() { r.performHTTP(task) }), 0)
r.set(0)
})
r.delegateCall(delegate, "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:", []uint64{session, task, res, proposed, redirectCompletion}, func() { r.set(0) })
return
}
deliver()
}
func (r *Runtime) delegateCall(receiver uint64, selector string, args []uint64, after func()) {
obj := r.objects[receiver]
if obj == nil {
panic("missing transport delegate")
}
entry := r.lookup(obj.Class, selector, false)
if entry == 0 {
forward := r.lookup(obj.Class, "forwardingTargetForSelector:", false)
if forward == 0 {
panic("missing transport delegate method " + selector)
}
r.callbackFunction(forward, []uint64{receiver, r.selector("forwardingTargetForSelector:"), r.selector(selector)}, func() {
target := r.arg(0)
if target == 0 || target == receiver {
panic("transport delegate cannot forward " + selector)
}
r.delegateCall(target, selector, args, after)
})
return
}
r.callbackFunction(entry, append([]uint64{receiver, r.selector(selector)}, args...), after)
}
func (r *Runtime) parserError(out uint64) {
if out == 0 {
return
}
errorObject := r.New("NSError", map[string]uint64{"domain": r.New("NSString", "NSCocoaErrorDomain"), "code": r.New("NSNumber", int64(3840)), "userInfo": r.New("NSDictionary", map[string]uint64{})})
r.write64(out, errorObject)
}
+79
View File
@@ -0,0 +1,79 @@
package emulator
func (r *Runtime) notificationMessage(receiver uint64, class, selector string, meta bool) bool {
if meta && class == "NSNotificationCenter" && selector == "defaultCenter" {
if r.notificationCenter == 0 {
r.notificationCenter = r.New(class, nil)
}
r.set(r.notificationCenter)
return true
}
if class == "NSNotification" {
switch selector {
case "name", "object", "userInfo":
r.set(r.objects[receiver].Properties[selector])
return true
}
return false
}
if meta || class != "NSNotificationCenter" {
return false
}
switch selector {
case "addObserver:selector:name:object:":
observer := r.New("HostObserver", nil)
o := r.objects[observer]
o.Properties = map[string]uint64{"observer": r.arg(2), "selector": r.arg(3), "name": r.arg(4), "object": r.arg(5)}
if r.observers == nil {
r.observers = map[uint64]*Object{}
}
r.observers[observer] = o
r.set(0)
case "postNotificationName:object:userInfo:", "postNotificationName:object:":
name, object := r.arg(2), r.arg(3)
info := uint64(0)
if selector == "postNotificationName:object:userInfo:" {
info = r.arg(4)
}
notification := r.New("NSNotification", nil)
r.objects[notification].Properties = map[string]uint64{"name": name, "object": object, "userInfo": info}
for _, o := range r.observers {
if p := o.Properties["name"]; p != 0 && r.String(p) != r.String(name) {
continue
}
if p := o.Properties["object"]; p != 0 && p != object {
continue
}
target, selector := o.Properties["observer"], r.cstring(o.Properties["selector"])
r.pending = append(r.pending, r.hostBlock(func() { r.delegateCall(target, selector, []uint64{notification}, func() { r.set(0) }) }))
}
r.set(0)
case "removeObserver:", "removeObserver:name:object:":
for key, o := range r.observers {
if key == r.arg(2) || o.Properties["observer"] == r.arg(2) {
delete(r.observers, key)
}
}
r.set(0)
default:
return false
}
return true
}
@@ -0,0 +1,40 @@
package emulator
// The purchase factory configures request properties after encoder options.
// A caller subclass reapplies the explicit legacy-client signing policy before
// Apple's base encoder runs. No signature or authentication result is fabricated.
func (r *Runtime) configuredPurchaseEncoder(info, bag uint64) (uint64, error) {
const className = "IPAToolPurchaseRequestEncoder"
const selector = "requestByEncodingRequestAndReturnSigningErrors:parameters:"
if r.classes[className] == nil {
base := r.classes["AMSPurchaseRequestEncoder"]
address := r.alloc(16)
r.classes[className] = &Class{Name: className, Address: address, Super: base.Name, Size: base.Size, Ivars: map[string]uint64{}}
r.classNames[address] = className
implementation := r.lookup("AMSURLRequestEncoder", selector, false)
block := r.hostBlock(func() {
receiver, request, parameters := r.arg(0), r.arg(2), r.arg(3)
r.delegateCall(receiver, "setAnisetteType:", []uint64{0}, func() {
r.delegateCall(receiver, "setMescalType:", []uint64{0}, func() {
r.delegateCall(request, "properties", nil, func() {
properties := r.arg(0)
r.delegateCall(properties, "setAnisetteType:", []uint64{0}, func() {
r.delegateCall(properties, "setMescalType:", []uint64{0}, func() {
r.delegateCall(properties, "setDisableLoadURLMetrics:", []uint64{1}, func() {
r.delegateCall(receiver, "setDisableLoadURLMetrics:", []uint64{1}, func() {
r.callbackFunction(implementation, []uint64{receiver, r.selector(selector), request, parameters}, func() {})
})
})
})
})
})
})
})
})
r.methods[methodKey(className, selector, false)] = r.read64(block + 16)
}
return r.Invoke(r.New(className, nil), "initWithPurchaseInfo:bag:", info, bag)
}
+800
View File
@@ -0,0 +1,800 @@
// Package emulator is the Objective-C runtime bridge for the pinned Store image.
package emulator
import (
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"maps"
"net/http"
"strings"
"time"
"github.com/blacktop/go-macho"
"github.com/majd/ipatool/v2/internal/sap/machimage"
"github.com/majd/ipatool/v2/internal/sap/unicorn"
storeprofile "github.com/majd/ipatool/v2/internal/store/profile"
profileformat "github.com/majd/ipatool/v2/internal/store/profile/format"
)
const heapBase = uint64(0x400000000000)
const heapSize = uint64(64 << 20)
const stackBase = uint64(0x500000000000)
const stackSize = uint64(8 << 20)
const returnPC = uint64(0x100000000)
type Method = profileformat.Method
type Class = profileformat.Class
type Call = profileformat.Call
type Page = profileformat.Page
type Constant = profileformat.Constant
type DictionaryLayout = profileformat.DictionaryLayout
type MetadataPatch = profileformat.MetadataPatch
type Profile = profileformat.Profile
type Object struct {
Class string
Value any
Properties map[string]uint64
}
type timer struct{ at, block uint64 }
type taskLocalBinding struct{ key, value uint64 }
type Runtime struct {
lastResponse *http.Response
transportError error
streamResponse, noRedirects, authRequest bool
taskLocalFrames map[uint64][]taskLocalBinding
transport func(*http.Request) (*http.Response, error)
xpcSyncHandler func(string, []byte) ([]byte, error)
inflaters map[uint64]*inflateStream
responseHeaders map[uint64]http.Header
tasks map[uint64]*asyncTask
currentTask *asyncTask
nullObject uint64
associations map[uint64]map[uint64]uint64
currentQueue, selectedQueue uint64
preferences map[string]uint64
notificationCenter uint64
observers map[uint64]*Object
pendingQueues map[uint64]uint64
allocations map[uint64]uint64
ctx context.Context
codeRanges [][2]uint64
steps uint64
timers []timer
callbacks map[uint64]func()
pending []uint64
hardwareID []byte
engine *unicorn.Engine
profile Profile
classes map[string]*Class
classNames map[uint64]string
methods map[string]uint64
calls map[uint64]Call
selectors map[uint64]string
selectorAddresses map[string]uint64
objects map[uint64]*Object
pages map[uint64]bool
cursor uint64
fault error
trace []string
entries map[uint64]string
hook *unicorn.Hook
}
func Open(ctx context.Context, imageData []byte, prepared storeprofile.Data) (*Runtime, error) {
return open(ctx, imageData, prepared, false)
}
// open optionally guards accesses against the exported page set. Validation and
// production use the same grouped mappings to stay within Unicorn section limits.
func open(ctx context.Context, imageData []byte, prepared storeprofile.Data, strict bool) (*Runtime, error) {
if ctx == nil {
return nil, errors.New("emulator context is nil")
}
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
if fmt.Sprintf("%x", sha256.Sum256(imageData)) != "95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4" {
return nil, errors.New("AppleMediaServices does not match the pinned 26A434 image")
}
metadata, err := cachedMetadata.load(ctx, prepared.Metadata)
if err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
profile := metadata.profile
imageInputs := map[string][]byte{"AppleMediaServices": imageData}
if profile.PluginUUID != "" {
if profile.PluginUUID != "B8C07F94-4868-3CD7-A59A-F01E8C24C1B7" {
return nil, errors.New("unsupported authentication plugin UUID")
}
plugin := prepared.Plugin
if fmt.Sprintf("%x", sha256.Sum256(plugin)) != "e33fff05a6e6593dd91e33fd103b5d3068b62a787c680df33b859f19b3acc4ea" {
return nil, errors.New("authentication plugin does not match the pinned image")
}
imageInputs["AMSAccountAuthenticationPlugin"] = plugin
}
engine, err := unicorn.New(ctx)
if err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
r := metadata.newRuntime()
r.engine = engine
r.ctx = ctx
r.callbacks = map[uint64]func(){}
ready := false
defer func() {
if !ready {
_ = r.Close()
}
}()
for _, region := range [][2]uint64{{heapBase, heapSize}, {stackBase, stackSize}, {returnPC, 4096}} {
if err = r.MemMap(region[0], region[1]); err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
}
for name, data := range imageInputs {
image, e := machimage.Open(name, data)
if e != nil {
return nil, fmt.Errorf("prepare store runtime: %w", e)
}
if e = image.PreparePrelinked(nil, func(symbol string) (uint64, error) { return 0, fmt.Errorf("unexpected relocation %s", symbol) }); e != nil {
return nil, fmt.Errorf("prepare store runtime: %w", e)
}
if e = image.Load(r); e != nil {
return nil, fmt.Errorf("prepare store runtime: %w", e)
}
}
pageData := prepared.Pages
addresses := make([]uint64, 0, len(profile.Pages))
for _, page := range profile.Pages {
if !r.pages[page.Address] {
addresses = append(addresses, page.Address)
}
}
for _, call := range profile.Calls {
page := call.Address &^ 4095
if !r.pages[page] {
addresses = append(addresses, page)
}
}
if strict {
allowed := maps.Clone(r.pages)
for _, address := range addresses {
allowed[address] = true
}
if err = engine.GuardMemory(func(address, size uint64) error {
return checkProfileAccess(allowed, address, size)
}); err != nil {
return nil, fmt.Errorf("guard Store memory: %w", err)
}
}
regions, err := groupPages(addresses)
if err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
for _, region := range regions {
if err = ctx.Err(); err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
if err = r.MemMap(region.address, region.size); err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
}
for _, page := range profile.Pages {
if page.Offset+4096 > uint64(len(pageData)) {
return nil, errors.New("profile page exceeds data")
}
if err = r.MemWrite(page.Address, pageData[page.Offset:page.Offset+4096]); err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
}
for _, call := range profile.Calls {
page := call.Address &^ 4095
if !r.pages[page] {
if err = r.MemMap(page, 4096); err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
}
if err = r.MemWrite(call.Address, []byte{0xc0, 0x03, 0x5f, 0xd6}); err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
}
// Non-fragile ivar offsets are fixed by the Objective-C loader on macOS.
for _, imageBytes := range imageInputs {
file, err := macho.NewFile(bytes.NewReader(imageBytes))
if err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
defer file.Close()
for _, section := range file.Sections {
if section.Flags.IsPureInstructions() || section.Flags.IsSomeInstructions() {
r.codeRanges = append(r.codeRanges, [2]uint64{section.Addr, section.Addr + section.Size})
}
}
if file.Symtab != nil {
for _, sym := range file.Symtab.Syms {
if !strings.HasPrefix(sym.Name, "_OBJC_IVAR_$_") {
continue
}
parts := strings.SplitN(strings.TrimPrefix(sym.Name, "_OBJC_IVAR_$_"), ".", 2)
if len(parts) != 2 {
continue
}
if c := r.classes[parts[0]]; c != nil {
if offset, ok := c.Ivars[parts[1]]; ok {
data := make([]byte, 4)
binary.LittleEndian.PutUint32(data, uint32(offset))
if err = r.MemWrite(sym.Value, data); err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
}
}
}
}
}
for _, patch := range profile.MetadataPatches {
if e := r.MemWrite(patch.Address, patch.Data); e != nil {
return nil, fmt.Errorf("prepare store runtime: %w", e)
}
}
r.hook, err = engine.AddCodeHook(0, ^uint64(0), r.step)
if err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
ready = true
return r, nil
}
func methodKey(class, selector string, meta bool) string {
prefix := "-"
if meta {
prefix = "+"
}
return prefix + "[" + class + " " + selector + "]"
}
func (r *Runtime) Close() error {
if r.engine == nil {
return nil
}
// Guest objects live for one request. Release their host references on close.
clear(r.objects)
clear(r.callbacks)
clear(r.responseHeaders)
clear(r.inflaters)
clear(r.preferences)
clear(r.associations)
clear(r.observers)
clear(r.tasks)
r.pending = nil
r.timers = nil
err := r.engine.Close()
r.engine = nil
if err != nil {
return fmt.Errorf("close store runtime: %w", err)
}
return nil
}
func (r *Runtime) MemMap(address, size uint64) error {
overlap := false
for page := address; page < address+size; page += 4096 {
overlap = overlap || r.pages[page]
}
if !overlap {
if err := r.engine.MemMap(address, size); err != nil {
return fmt.Errorf("map guest memory: %w", err)
}
for page := address; page < address+size; page += 4096 {
r.pages[page] = true
}
return nil
}
for page := address; page < address+size; {
if r.pages[page] {
page += 4096
continue
}
end := page + 4096
for end < address+size && !r.pages[end] {
end += 4096
}
if err := r.engine.MemMap(page, end-page); err != nil {
return fmt.Errorf("map guest memory: %w", err)
}
for ; page < end; page += 4096 {
r.pages[page] = true
}
}
return nil
}
func (r *Runtime) MemWrite(address uint64, data []byte) error {
if err := r.engine.MemWrite(address, data); err != nil {
return fmt.Errorf("write guest memory: %w", err)
}
return nil
}
func (r *Runtime) alloc(size uint64) uint64 {
if size > heapSize {
panic("guest allocation exceeds heap budget")
}
size = (size + 15) &^ 15
if size == 0 {
size = 16
}
if size > heapSize-r.cursor {
panic("guest heap exhausted")
}
address := heapBase + r.cursor
r.cursor += size
if r.allocations == nil {
r.allocations = map[uint64]uint64{}
}
r.allocations[address] = size
return address
}
func (r *Runtime) read64(address uint64) uint64 {
b, e := r.engine.MemRead(address, 8)
if e != nil {
panic(fmt.Sprintf("read guest pointer %#x: %v", address, e))
}
return binary.LittleEndian.Uint64(b)
}
func (r *Runtime) write64(address, value uint64) {
var b [8]byte
binary.LittleEndian.PutUint64(b[:], value)
if e := r.MemWrite(address, b[:]); e != nil {
panic(e)
}
}
func (r *Runtime) arg(i int) uint64 {
reg := unicorn.RegX0 + i
if i >= 8 {
sp, _ := r.engine.RegRead(unicorn.RegSP)
return r.read64(sp + uint64(i-8)*8)
}
v, e := r.engine.RegRead(reg)
if e != nil {
panic(e)
}
return v
}
func (r *Runtime) set(value uint64) {
if e := r.engine.RegWrite(unicorn.RegX0, value); e != nil {
panic(e)
}
}
func (r *Runtime) cstring(address uint64) string {
if address == 0 {
return ""
}
if value, ok := r.selectors[address]; ok {
return value
}
var b []byte
for i := uint64(0); i < 16384; i++ {
v, e := r.engine.MemRead(address+i, 1)
if e != nil {
panic(fmt.Sprintf("read C string %#x: %v", address, e))
}
if v[0] == 0 {
return string(b)
}
b = append(b, v[0])
}
panic("unterminated guest string")
}
func (r *Runtime) selector(value string) uint64 {
if addr := r.selectorAddresses[value]; addr != 0 {
return addr
}
addr := r.alloc(uint64(len(value) + 1))
if err := r.MemWrite(addr, append([]byte(value), 0)); err != nil {
panic(err)
}
r.selectorAddresses[value] = addr
r.selectors[addr] = value
return addr
}
func (r *Runtime) New(class string, value any) uint64 {
size := uint64(256)
if c := r.classes[class]; c != nil {
size = max(c.Size, 16)
}
address := r.alloc(size)
obj := &Object{Class: class, Value: value, Properties: map[string]uint64{}}
r.objects[address] = obj
if c := r.classes[class]; c != nil {
r.write64(address, c.Address)
}
return address
}
func (r *Runtime) SetIvar(object uint64, name string, value uint64) error {
obj := r.objects[object]
if obj == nil {
return errors.New("unknown guest object")
}
for class := obj.Class; class != ""; {
c := r.classes[class]
if c == nil {
break
}
if offset, ok := c.Ivars[name]; ok {
r.write64(object+offset, value)
return nil
}
class = c.Super
}
return fmt.Errorf("unknown ivar %s.%s", obj.Class, name)
}
func (r *Runtime) String(address uint64) string {
if address == 0 {
return ""
}
obj := r.objects[address]
if obj == nil {
panic(fmt.Sprintf("unknown string object %#x", address))
}
value, ok := obj.Value.(string)
if !ok {
panic(fmt.Sprintf("object %s is not a string", obj.Class))
}
return value
}
func (r *Runtime) lookup(class, selector string, meta bool) uint64 {
for class != "" {
if address := r.methods[methodKey(class, selector, meta)]; address != 0 {
return address
}
c := r.classes[class]
if c == nil {
break
}
class = c.Super
}
return 0
}
//nolint:nonamedreturns // Panic recovery must return an error from the ABI boundary.
func (r *Runtime) Invoke(object uint64, selector string, args ...uint64) (result uint64, err error) {
defer func() {
if p := recover(); p != nil {
err = recoveredError("guest setup", p)
}
}()
class, meta := r.classNames[object]
if !meta {
obj := r.objects[object]
if obj == nil {
return 0, fmt.Errorf("unknown receiver %#x for %s", object, selector)
}
class = obj.Class
}
entry := r.lookup(class, selector, meta)
if entry == 0 {
block := r.hostBlock(func() { r.message(object, selector, false) })
entry = r.read64(block + 16)
}
arguments := append([]uint64{object, r.selector(selector)}, args...)
return r.call(entry, arguments...)
}
func (r *Runtime) call(entry uint64, arguments ...uint64) (uint64, error) {
var err error
for i := 0; i < 8; i++ {
var v uint64
if i < len(arguments) {
v = arguments[i]
}
if e := r.engine.RegWrite(unicorn.RegX0+i, v); e != nil {
return 0, fmt.Errorf("write guest register: %w", e)
}
}
sp := stackBase + stackSize - 4096
for i := 8; i < len(arguments); i++ {
r.write64(sp+uint64(i-8)*8, arguments[i])
}
_ = r.engine.RegWrite(unicorn.RegSP, sp)
_ = r.engine.RegWrite(unicorn.RegLR, returnPC)
r.fault = nil
err = r.engine.StartBounded(entry, returnPC, 2*time.Minute, 20_000_000)
if r.fault != nil {
return 0, r.fault
}
pc, _ := r.engine.RegRead(unicorn.RegPC)
if err != nil {
lr, _ := r.engine.RegRead(unicorn.RegLR)
return 0, fmt.Errorf("guest stopped at %#x from %#x: %w; recent=%v", pc, lr, err, r.trace)
}
if pc != returnPC {
return 0, fmt.Errorf("instruction budget exhausted at %#x", pc)
}
value, err := r.engine.RegRead(unicorn.RegX0)
if err != nil {
return 0, fmt.Errorf("read guest return register: %w", err)
}
return value, nil
}
func (r *Runtime) step(address uint64, _ uint32) {
defer func() {
if p := recover(); p != nil {
r.fault = fmt.Errorf("guest bridge at %#x: %w; recent=%v", address, recoveredError("runtime", p), r.trace)
_ = r.engine.Stop()
}
}()
if callback := r.callbacks[address]; callback != nil {
callback()
return
}
if name := r.entries[address]; name != "" {
r.trace = append(r.trace, name)
if len(r.trace) > 12 {
r.trace = r.trace[len(r.trace)-12:]
}
}
call, ok := r.calls[address]
if !ok {
allowed := false
for _, region := range r.codeRanges {
if address >= region[0] && address < region[1] {
allowed = true
break
}
}
if !allowed {
panic(fmt.Sprintf("execution outside the pinned image at %#x", address))
}
r.steps++
if r.steps%4096 == 0 {
if err := r.ctx.Err(); err != nil {
panic(err)
}
}
return
}
if call.Selector != "" {
r.message(r.arg(0), call.Selector, false)
return
}
r.symbol(strings.TrimLeft(call.Symbol, "_"))
}
func (r *Runtime) jump(entry, receiver uint64, selector string) {
_ = r.engine.RegWrite(unicorn.RegX0, receiver)
_ = r.engine.RegWrite(unicorn.RegX1, r.selector(selector))
_ = r.engine.RegWrite(unicorn.RegPC, entry)
}
func (r *Runtime) ClassAddress(name string) uint64 {
if c := r.classes[name]; c != nil {
return c.Address
}
return 0
}
// Export copies a Foundation value out of the guest without exposing guest pointers.
func (r *Runtime) Export(address uint64) (any, error) {
return r.export(address, map[uint64]bool{}, 0)
}
func (r *Runtime) export(address uint64, active map[uint64]bool, depth int) (any, error) {
if address == 0 {
return nil, nil
}
if depth > 32 || active[address] {
return nil, errors.New("cyclic or excessively nested guest value")
}
obj := r.objects[address]
if obj == nil {
return nil, fmt.Errorf("unknown exported object %#x", address)
}
active[address] = true
defer delete(active, address)
switch v := obj.Value.(type) {
case map[string]uint64:
result := map[string]any{}
for k, p := range v {
item, e := r.export(p, active, depth+1)
if e != nil {
return nil, e
}
result[k] = item
}
return result, nil
case []uint64:
result := make([]any, len(v))
for i, p := range v {
item, e := r.export(p, active, depth+1)
if e != nil {
return nil, e
}
result[i] = item
}
return result, nil
default:
return v, nil
}
}
func (r *Runtime) queuePending(block, queue uint64) {
if r.pendingQueues == nil {
r.pendingQueues = map[uint64]uint64{}
}
r.pendingQueues[block] = queue
r.pending = append(r.pending, block)
}
func (r *Runtime) nextPending() uint64 {
for i, block := range r.pending {
if q := r.objects[r.pendingQueues[block]]; q != nil && q.Properties["suspendCount"] != 0 {
continue
}
r.pending = append(r.pending[:i], r.pending[i+1:]...)
r.selectedQueue = r.pendingQueues[block]
delete(r.pendingQueues, block)
return block
}
return 0
}
func (r *Runtime) pendingCallback(block uint64, after func()) {
previous := r.currentQueue
r.currentQueue = r.selectedQueue
r.callback(block, nil, func() { r.currentQueue = previous; after() })
}
func (r *Runtime) queueIsWithin(queue, target uint64) bool {
for depth := 0; depth < 32; depth++ {
if queue == target {
return true
}
object := r.objects[queue]
if object == nil {
return false
}
queue = object.Properties["targetQueue"]
if queue == 0 {
return false
}
}
panic("cyclic dispatch queue targets")
}
func recoveredError(stage string, value any) error {
if cause, ok := value.(error); ok {
return fmt.Errorf("%s: %w", stage, cause)
}
return fmt.Errorf("%s: %v", stage, value)
}
+10
View File
@@ -0,0 +1,10 @@
package emulator
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestStoreRuntime(t *testing.T) { RegisterFailHandler(Fail); RunSpecs(t, "Store Runtime") }
+102
View File
@@ -0,0 +1,102 @@
package emulator
import (
"errors"
"fmt"
"strconv"
)
func (r *Runtime) resolveAddress(promise uint64) (uint64, error) {
// Apple's resultWithError: starts lazy promises and drives their wait. The
// NSCondition bridge runs queued callbacks until that operation completes.
// Draining every unrelated background task first can fail after success.
failure := r.alloc(8)
result, err := r.Invoke(promise, "resultWithError:", failure)
if err != nil {
return 0, err
}
if p := r.read64(failure); p != 0 {
domain, e := r.Invoke(p, "domain")
if e != nil {
return 0, errors.New("framework returned an error")
}
code, e := r.Invoke(p, "code")
if e != nil {
return 0, errors.New("framework returned an error")
}
failure := &FrameworkError{Domain: r.String(domain), Code: int64(code)}
if message, e := r.Invoke(p, "localizedDescription"); e == nil && message != 0 {
failure.Message = r.String(message)
}
return 0, failure
}
if result == 0 {
return 0, errors.New("framework returned no result")
}
return result, nil
}
func (r *Runtime) ephemeralAccount(saved map[string]any) (uint64, error) {
account, err := r.Invoke(r.ClassAddress("ACAccount"), "ams_createEphemeralAccount")
if err != nil {
return 0, err
}
if saved == nil {
return account, nil
}
dsid, err := strconv.ParseInt(fmt.Sprint(saved["directoryServicesIdentifier"]), 10, 64)
if err != nil {
return 0, errors.New("invalid saved account identifier")
}
fields := map[string]uint64{"setUsername:": r.importValue(saved["email"]), "ams_setDSID:": r.New("NSNumber", dsid), "ams_setPassword:": r.importValue(saved["passwordToken"]), "ams_setStorefront:": r.importValue(saved["storeFront"])}
for selector, value := range fields {
if _, err = r.Invoke(account, selector, value); err != nil {
return 0, err
}
}
return account, nil
}
func (r *Runtime) configureRequest(request, account, bag uint64, raw bool) error {
properties, err := r.Invoke(request, "properties")
if err != nil {
return err
}
fields := map[string]uint64{"setAccount:": account, "setBag:": bag, "setKnownToBeTrusted:": 1, "setShouldSetCookiesFromResponse:": 0, "setShouldSetStorefrontFromResponse:": 0, "setDisableLoadURLMetrics:": 1, "setDisableBiometricsResponseHandling:": 1, "setMaxRetryCount:": 0, "setDisableResponseDecoding:": boolValue(raw)}
for selector, value := range fields {
if _, err = r.Invoke(properties, selector, value); err != nil {
return err
}
}
return nil
}
func (r *Runtime) newSession() (uint64, error) {
session, err := r.Invoke(r.New("AMSURLSession", nil), "initWithConfiguration:delegate:delegateQueue:", 0, 0, 0)
if err != nil {
return 0, err
}
_, err = r.Invoke(session, "setUseFallbackBag:", 0)
return session, err
}
func (r *Runtime) sendRequest(session, request uint64) (uint64, error) {
promise, err := r.Invoke(session, "dataTaskPromiseWithRequest:", request)
if err != nil {
return 0, err
}
return r.resolveAddress(promise)
}
+796
View File
@@ -0,0 +1,796 @@
package emulator
import (
"encoding/binary"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"unicode/utf8"
profileformat "github.com/majd/ipatool/v2/internal/store/profile/format"
"github.com/majd/ipatool/v2/internal/sap/unicorn"
"golang.org/x/text/unicode/norm"
)
// The runtime owns all allocations until Close, including Swift references.
// These are ABI services, not replacements for AMS request or response methods.
func (r *Runtime) swiftSymbol(name string) bool {
if r.asyncSymbol(name) {
return true
}
switch name {
case "$ss27_stringCompareWithSmolCheck__9expectingSbs11_StringGutsV_ADs01_G16ComparisonResultOtF":
left, right := norm.NFC.String(r.swiftString(r.arg(0), r.arg(1))), norm.NFC.String(r.swiftString(r.arg(2), r.arg(3)))
switch r.arg(4) {
case 0:
r.set(boolValue(left == right))
case 1:
r.set(boolValue(left < right))
default:
panic("unsupported Swift string comparison")
}
case "$ss18_DictionaryStorageC6resize8original8capacity4moveAByxq_Gs05__RawaB0C_SiSbtFZ":
storageType, capacity := r.arg(3), r.arg(1)
var metadata uint64
for key, layout := range r.profile.SwiftDictionaries {
if layout.Metadata == storageType {
metadata, _ = strconv.ParseUint(key, 10, 64)
break
}
}
if metadata == 0 {
panic(fmt.Sprintf("unprepared dictionary storage %#x", storageType))
}
slot := r.alloc(8)
r.write64(slot, r.profile.Symbols["_swiftEmptyDictionarySingleton"])
r.ensureUniqueDictionary(slot, false, capacity, metadata)
r.set(r.read64(slot))
case "swift_dynamicCast":
destination, source, sourceType, targetType := r.arg(0), r.arg(1), r.arg(2), r.arg(3)
if sourceType == r.profile.Symbols["$ss11AnyHashableVN"] && targetType == r.profile.Symbols["$sSSN"] {
if r.read64(source+24) != r.profile.Bridges["anyHashableStringMetadata"] {
panic("unsupported AnyHashable cast box")
}
sourceType = targetType
} else if sourceType == r.profile.Symbols["$sypN"]+8 {
sourceType = r.read64(source + 24)
}
if sourceType == targetType {
size := r.read64(r.read64(sourceType-8) + 64)
if size > 24 {
panic("unsupported Swift cast value size")
}
data, err := r.engine.MemRead(source, size)
if err != nil {
panic(err)
}
if err = r.MemWrite(destination, data); err != nil {
panic(err)
}
r.set(1)
} else if targetType == r.profile.Symbols["$sSSN"] && (sourceType == r.profile.Symbols["$sSiN"] || sourceType == r.profile.Symbols["$sSbN"] || sourceType == r.profile.Symbols["$sSdN"]) && r.arg(4)&1 == 0 {
r.set(0)
} else {
panic(fmt.Sprintf("unsupported Swift cast metadata %#x -> %#x flags=%d", sourceType, targetType, r.arg(4)))
}
case "$ss17CodingUserInfoKeyVwCP", "$sSSwCP", "$sSSwcp", "$sSSwca":
// The pinned runtime shares this witness with String: two words,
// followed by a retain that our scoped allocation lifetime subsumes.
data, err := r.engine.MemRead(r.arg(1), 16)
if err != nil {
panic(err)
}
if err = r.MemWrite(r.arg(0), data); err != nil {
panic(err)
}
case "$ss11AnyHashableVwxx", "$sSSwxx":
// References remain alive until this runtime closes.
case "$ss11AnyHashableVwcp", "$ss11AnyHashableVwca":
// This bridge currently constructs only inline String-backed boxes.
if r.read64(r.arg(1)+24) != r.profile.Bridges["anyHashableStringMetadata"] {
panic("unsupported AnyHashable copy layout")
}
data, err := r.engine.MemRead(r.arg(1), 40)
if err != nil {
panic(err)
}
if err = r.MemWrite(r.arg(0), data); err != nil {
panic(err)
}
case "$sSD10FoundationE36_unconditionallyBridgeFromObjectiveCySDyxq_GSo12NSDictionaryCSgFZ":
if (r.arg(1) != r.profile.Symbols["$sSSN"] && r.arg(1) != r.profile.Symbols["$ss11AnyHashableVN"]) || (r.arg(2) != r.profile.Symbols["$sypN"]+8 && r.arg(2) != r.profile.Symbols["$sSSN"]) {
panic(fmt.Sprintf("unsupported dictionary bridge metadata %#x/%#x", r.arg(1), r.arg(2)))
}
r.set(r.bridgeDictionaryToSwift(r.arg(0), r.arg(1), r.arg(2)))
case "$sSo13os_log_type_ta0A0E5errorABvgZ":
r.set(16)
case "$sSo13os_log_type_ta0A0E5faultABvgZ":
r.set(17)
case "$sSo13os_log_type_ta0A0E4infoABvgZ":
r.set(1)
case "$sSo13os_log_type_ta0A0E5debugABvgZ":
r.set(2)
case "$sSo13os_log_type_ta0A0E7defaultABvgZ":
r.set(0)
case "$sSS6appendyySSF":
self, _ := r.engine.RegRead(unicorn.RegX0 + 20)
value := r.swiftString(r.read64(self), r.read64(self+8)) + r.swiftString(r.arg(0), r.arg(1))
r.returnSwiftString(value)
r.write64(self, r.arg(0))
r.write64(self+8, r.arg(1))
case "$ss9_typeName_9qualifiedSSypXp_SbtF":
name := r.classNames[r.arg(0)]
if name == "" && r.read64(r.arg(0)) == 0x305 {
name = r.classNames[r.read64(r.arg(0)+8)]
}
if name == "" {
panic(fmt.Sprintf("unprepared Swift type name %#x", r.arg(0)))
}
r.returnSwiftString(name)
case "$ss9TaskLocalC12wrappedValueAByxGx_tcfc":
self, _ := r.engine.RegRead(unicorn.RegX0 + 20)
metadata := r.read64(self)
valueType := r.read64(metadata + 80)
size := r.read64(r.read64(valueType-8) + 64)
if size > r.allocations[self]-16 {
panic("TaskLocal value exceeds allocation")
}
data, err := r.engine.MemRead(r.arg(0), size)
if err != nil {
panic(err)
}
if err = r.MemWrite(self+16, data); err != nil {
panic(err)
}
r.objects[self] = &Object{Class: "HostSwiftTaskLocal", Properties: map[string]uint64{"valueSize": size, "defaultValue": self + 16}}
r.set(self)
case "$ss9TaskLocalC3getxyF", "$ss9TaskLocalC12wrappedValuexvg":
self, _ := r.engine.RegRead(unicorn.RegX0 + 20)
obj := r.objects[self]
if obj == nil {
panic("unknown TaskLocal")
}
out, _ := r.engine.RegRead(unicorn.RegX0 + 8)
source := r.taskLocalValue(self)
if source == 0 {
source = obj.Properties["defaultValue"]
}
data, err := r.engine.MemRead(source, obj.Properties["valueSize"])
if err != nil {
panic(err)
}
if err = r.MemWrite(out, data); err != nil {
panic(err)
}
case "$sSo9OS_os_logC0B0E9subsystem8categoryABSS_SStcfC":
r.set(r.New("HostOSLog", nil))
case "$s10Foundation10URLRequestV8setValue_18forHTTPHeaderFieldySSSg_SStF":
copied := r.mutableSwiftRequest()
object := r.objects[copied]
if object.Properties["allHTTPHeaderFields"] == 0 {
object.Properties["allHTTPHeaderFields"] = r.New("NSMutableDictionary", map[string]uint64{})
}
fields := r.objects[object.Properties["allHTTPHeaderFields"]].Value.(map[string]uint64)
key := http.CanonicalHeaderKey(r.swiftString(r.arg(2), r.arg(3)))
if r.arg(1) == 0 {
delete(fields, key)
} else {
fields[key] = r.New("NSString", r.swiftString(r.arg(0), r.arg(1)))
}
case "swift_initWithCopy_strong", "swift_initWithTake_strong", "swift_assignWithCopy_strong", "swift_assignWithTake_strong":
r.write64(r.arg(0), r.read64(r.arg(1)))
case "$s10Foundation3URLV14absoluteStringSSvg":
self, _ := r.engine.RegRead(unicorn.RegX0 + 20)
r.returnSwiftString(r.String(r.read64(self)))
case "$s10Foundation10URLRequestV3urlAA3URLVSgvg":
self, _ := r.engine.RegRead(unicorn.RegX0 + 20)
object := r.objects[r.read64(self)]
if object == nil {
panic("invalid Swift URLRequest value")
}
out, _ := r.engine.RegRead(unicorn.RegX0 + 8)
r.write64(out, object.Properties["URL"])
r.write64(out+8, 0)
case "swift_getSingletonMetadata":
value := r.profile.SwiftSingletons[strconv.FormatUint(r.arg(1), 10)]
if value == 0 {
panic(fmt.Sprintf("unprepared singleton metadata %#x", r.arg(1)))
}
r.set(value)
_ = r.engine.RegWrite(unicorn.RegX1, 0)
case "$s10Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF":
value := r.arg(0)
for depth := 0; depth < 16; depth++ {
object := r.objects[value]
if object == nil {
panic("unknown Swift error value")
}
if r.kindOf(object.Class, "NSError") {
r.set(value)
return true
}
if object.Class != "HostSwiftError" || object.Properties["metadata"] != r.profile.SwiftTypes[strconv.FormatUint(0x1a2e1c7fa, 10)] {
panic(fmt.Sprintf("unsupported Swift error bridge %s metadata %#x", object.Class, object.Properties["metadata"]))
}
value = r.read64(object.Properties["value"])
}
panic("recursive Swift error box")
case "$ss38_bridgeAnythingNonVerbatimToObjectiveCyyXlxnlF":
source, metadata := r.arg(0), r.arg(1)
switch metadata {
case r.profile.Symbols["$sSSN"]:
r.set(r.New("NSString", r.swiftString(r.read64(source), r.read64(source+8))))
case r.profile.Symbols["$sSiN"]:
r.set(r.New("NSNumber", int64(r.read64(source))))
default:
panic(fmt.Sprintf("unsupported nonverbatim bridge metadata %#x", metadata))
}
case "$sSD10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF":
r.set(r.bridgeDictionaryToObjC(r.arg(0), r.arg(1), r.arg(2)))
case "$sSS4hash4intoys6HasherVz_tF":
value := norm.NFC.String(r.swiftString(r.arg(1), r.arg(2)))
r.hashBytes(r.arg(0), append([]byte(value), 255))
case "swift_allocError":
metadata, witness, source := r.arg(0), r.arg(1), r.arg(2)
size := r.read64(r.read64(metadata-8) + 64)
if size > 1<<20 {
panic("Swift error exceeds budget")
}
value := r.alloc(size)
box := r.New("HostSwiftError", nil)
r.objects[box].Properties = map[string]uint64{"metadata": metadata, "witness": witness, "value": value}
if source != 0 {
data, err := r.engine.MemRead(source, size)
if err != nil {
panic(err)
}
if err = r.MemWrite(value, data); err != nil {
panic(err)
}
}
r.set(box)
_ = r.engine.RegWrite(unicorn.RegX1, value)
case "swift_getErrorValue":
box := r.objects[r.arg(0)]
if box == nil || box.Class != "HostSwiftError" {
panic("unsupported unboxed Swift error")
}
out := r.arg(2)
r.write64(out, box.Properties["value"])
r.write64(out+8, box.Properties["metadata"])
r.write64(out+16, box.Properties["witness"])
case "swift_errorRetain", "swift_errorRelease", "swift_willThrow":
case "$s10Foundation10URLRequestV36_unconditionallyBridgeFromObjectiveCyACSo12NSURLRequestCSgFZ":
value := r.arg(0)
if obj := r.objects[value]; obj == nil || !r.kindOf(obj.Class, "NSURLRequest") {
panic("invalid Swift request bridge input")
}
out, _ := r.engine.RegRead(unicorn.RegX0 + 8)
r.write64(out, value)
case "$s10Foundation10URLRequestV19_bridgeToObjectiveCSo12NSURLRequestCyF":
self, _ := r.engine.RegRead(unicorn.RegX0 + 20)
r.set(r.read64(self))
case "$sScPwst":
if r.arg(2) != 1 || r.arg(1) > 1 {
panic("unsupported task priority optional tag")
}
size := r.read64(r.read64(r.arg(3)-8) + 64)
if size != 1 {
panic("unexpected priority size")
}
if err := r.MemWrite(r.arg(0)+size, []byte{byte(r.arg(1))}); err != nil {
panic(err)
}
case "$sScPwet":
size := r.read64(r.read64(r.arg(2)-8) + 64)
data, err := r.engine.MemRead(r.arg(0)+size, 1)
if err != nil {
panic(err)
}
r.set(uint64(data[0]))
case "$s10Foundation3URLV06isFileB0Sbvg":
self, _ := r.engine.RegRead(unicorn.RegX0 + 20)
u, err := url.Parse(r.String(r.read64(self)))
if err != nil {
panic(err)
}
r.set(boolValue(u.Scheme == "file"))
case "$s10Foundation3URLV19_bridgeToObjectiveCSo5NSURLCyF":
self, _ := r.engine.RegRead(unicorn.RegX0 + 20)
r.set(r.read64(self))
case "$sSqwta", "$sSqwca", "$sSqwcp", "$sSqwtk", "swift_cvw_initWithCopy", "swift_cvw_assignWithCopy", "swift_cvw_initWithTake", "swift_cvw_assignWithTake":
size := r.read64(r.read64(r.arg(2)-8) + 64)
if size > 1024 {
panic("Swift value copy exceeds budget")
}
data, err := r.engine.MemRead(r.arg(1), size)
if err != nil {
panic(err)
}
if err = r.MemWrite(r.arg(0), data); err != nil {
panic(err)
}
case "$s10Foundation3URLVwst":
if r.arg(2) != 1 || r.arg(1) > 1 {
panic("unsupported URL optional tag")
}
if r.arg(1) == 1 {
r.write64(r.arg(0), 0)
r.write64(r.arg(0)+8, 0)
}
case "$s10Foundation3URLVwet":
if r.arg(1) != 1 {
panic("unsupported URL optional tag")
}
r.set(boolValue(r.read64(r.arg(0)) == 0))
case "$s10Foundation3URLV9appending10components13directoryHintACxd_AC09DirectoryF0OtSyRzlF", "$s10Foundation3URLV6append10components13directoryHintyxd_AC09DirectoryF0OtSyRzlF":
self, _ := r.engine.RegRead(unicorn.RegX0 + 20)
array := r.arg(0)
count := r.read64(array + 16)
if count > 32 {
panic("URL component count exceeds budget")
}
value := r.String(r.read64(self))
for i := uint64(0); i < count; i++ {
p := array + 32 + i*16
component := r.swiftString(r.read64(p), r.read64(p+8))
var err error
value, err = url.JoinPath(value, component)
if err != nil {
panic(err)
}
}
if strings.Contains(name, "9appending") {
self, _ = r.engine.RegRead(unicorn.RegX0 + 8)
}
r.write64(self, r.New("NSURL", value))
r.write64(self+8, 0)
case "$s10Foundation3URLV36_unconditionallyBridgeFromObjectiveCyACSo5NSURLCSgFZ":
if r.objects[r.arg(0)] == nil || r.objects[r.arg(0)].Class != "NSURL" {
panic("invalid Swift URL bridge input")
}
out, _ := r.engine.RegRead(unicorn.RegX0 + 8)
r.write64(out, r.arg(0))
r.write64(out+8, 0)
case "$s10ObjectiveC8SelectorV2eeoiySbAC_ACtFZ":
r.set(boolValue(r.arg(0) == r.arg(1)))
case "$ss17_NativeDictionaryV12ensureUnique02isD08capacityS2b_SitF":
self, _ := r.engine.RegRead(unicorn.RegX0 + 20)
r.ensureUniqueDictionary(self, r.arg(0) != 0, r.arg(1), r.arg(2))
case "$ss6HasherV5_seedABSi_tcfC":
out, _ := r.engine.RegRead(unicorn.RegX0 + 8)
r.initHasher(out, r.arg(0))
case "$ss6HasherV8_combineyySuF":
self, _ := r.engine.RegRead(unicorn.RegX0 + 20)
r.hashWord(self, r.arg(0))
case "$ss6HasherV9_finalizeSiyF":
self, _ := r.engine.RegRead(unicorn.RegX0 + 20)
r.set(r.hashCompress(self, r.read64(self), true))
case "$s10ObjectiveC8SelectorV4hash4intoys6HasherVz_tF":
r.hashWord(r.arg(0), r.arg(1))
case "$sSo17OS_dispatch_queueC8DispatchE5async5group3qos5flags7executeySo0a1_b1_F0CSg_AC0D3QoSVAC0D13WorkItemFlagsVyyXBtF":
if r.arg(0) != 0 {
panic("Swift dispatch group unsupported")
}
queue, _ := r.engine.RegRead(unicorn.RegX0 + 20)
r.copyBlock(r.arg(3), func(block uint64) { r.queuePending(block, queue); r.set(0) })
case "$sSo17OS_dispatch_queueC8DispatchE5label3qos10attributes20autoreleaseFrequency6targetABSS_AC0D3QoSVAbCE10AttributesVAbCE011AutoreleaseI0OABSgtcfC", "$sSo24OS_dispatch_queue_serialC8DispatchE5label3qos10attributes20autoreleaseFrequency6targetABSS_AC0E3QoSVAbCE10AttributesVSo0a1_b1_C0CACE011AutoreleaseJ0OANSgtcfC":
target := r.arg(5)
queue := r.New("HostQueue", r.swiftString(r.arg(0), r.arg(1)))
r.objects[queue].Properties["targetQueue"] = target
r.set(queue)
case "$ss10SetAlgebraPyxqd__ncSTRd__7ElementQyd__ACRtzlufCTj":
if (r.arg(3) != r.profile.SwiftAccessors["$sSo24OS_dispatch_queue_serialC8DispatchE10AttributesVMa"] && r.arg(3) != r.profile.SwiftAccessors["$sSo17OS_dispatch_queueC8DispatchE10AttributesVMa"] && r.arg(3) != r.profile.SwiftAccessors["$s8Dispatch0A13WorkItemFlagsVMa"]) || r.read64(r.read64(r.arg(0))+16) != 0 {
panic("unsupported SetAlgebra initializer")
}
out, _ := r.engine.RegRead(unicorn.RegX0 + 8)
r.write64(out, 0)
case "$s8Dispatch0A3QoSV11unspecifiedACvgZ":
out, _ := r.engine.RegRead(unicorn.RegX0 + 8)
r.write64(out, 5)
r.write64(out+8, 0)
case "swift_isUniquelyReferenced_nonNull_native", "swift_isUniquelyReferenced_nonNull_bridgeObject":
// Conservatively copy; host handles can retain aliases for VM lifetime.
r.set(0)
case "swift_retain_n", "swift_bridgeObjectRetain_n", "swift_retain", "swift_bridgeObjectRetain", "swift_unknownObjectRetain":
case "swift_destroy_strong", "$ss15CollectionOfOneV8IteratorVwxx", "swift_pod_destroy", "swift_arrayDestroy", "swift_deallocPartialClassInstance", "swift_cvw_destroy", "swift_noop_void_return", "swift_release_n", "swift_bridgeObjectRelease_n", "swift_release", "swift_bridgeObjectRelease", "swift_unknownObjectRelease", "swift_deallocObject":
case "swift_arrayInitWithCopy", "swift_arrayInitWithTakeFrontToBack", "swift_arrayInitWithTakeBackToFront":
destination, source, count, metadata := r.arg(0), r.arg(1), r.arg(2), r.arg(3)
if count == 0 {
r.set(destination)
break
}
witnesses := r.read64(metadata - 8)
stride := r.read64(witnesses + 72)
if count > 65536 || stride > 1<<20 {
panic("Swift array copy exceeds budget")
}
index := uint64(0)
offset := uint64(16)
if name != "swift_arrayInitWithCopy" {
offset = 32
}
var next func()
next = func() {
if index == count {
r.set(destination)
return
}
i := index
if name == "swift_arrayInitWithTakeBackToFront" {
i = count - index - 1
}
index++
r.callbackFunction(r.read64(witnesses+offset), []uint64{destination + i*stride, source + i*stride, metadata}, next)
}
next()
case "swift_allocObject":
metadata, size := r.arg(0), r.arg(1)
if size < 16 {
panic("invalid Swift object size")
}
object := r.alloc(size)
r.write64(object, metadata)
r.write64(object+8, 3) // inline refcount: one strong reference, live object
r.set(object)
case "swift_getForeignTypeMetadata":
candidate := r.arg(1)
if value := r.profile.SwiftForeign[strconv.FormatUint(candidate, 10)]; value != 0 {
r.set(value)
_ = r.engine.RegWrite(unicorn.RegX1, 0)
break
}
// AMSErrorCode: the pinned native runtime returns this complete, static enum
// metadata unchanged. Do not generalize to foreign classes with initializers.
if candidate != 0x1eaa52f08 || r.read64(candidate) != 0x201 {
panic(fmt.Sprintf("unsupported foreign metadata %#x", candidate))
}
r.set(candidate)
_ = r.engine.RegWrite(unicorn.RegX1, 0)
case "swift_getWitnessTable":
value := r.profile.SwiftWitnesses[profileformat.WitnessKey(r.arg(0), r.arg(1))]
if value == 0 {
panic(fmt.Sprintf("unprepared witness descriptor %#x for metadata %#x", r.arg(0), r.arg(1)))
}
r.set(value)
case "$sSD17dictionaryLiteralSDyxq_Gx_q_td_tcfC":
if r.read64(r.arg(0)+16) != 0 {
panic("nonempty Swift dictionary literal unsupported")
}
r.set(r.profile.Symbols["_swiftEmptyDictionarySingleton"])
case "swift_defaultActor_initialize":
// Serial host scheduler: freshly allocated actor has an empty mailbox.
// Enqueue/async entry points remain explicit unsupported services.
r.objects[r.arg(0)] = &Object{Class: "HostSwiftActor", Properties: map[string]uint64{}}
case "swift_getObjectType":
r.set(r.read64(r.arg(0)))
case "swift_getObjCClassFromMetadata":
if r.classNames[r.arg(0)] != "" {
break
}
if r.read64(r.arg(0)) == 0x305 {
r.set(r.read64(r.arg(0) + 8))
break
}
panic("unknown Objective-C class metadata")
case "swift_getObjCClassMetadata":
// Objective-C compatible class metadata uses the class address itself.
case "swift_getTypeByMangledNameInContext2":
value := r.profile.SwiftTypes[strconv.FormatUint(r.arg(0), 10)]
if value == 0 || r.arg(2) != 0 || r.arg(3) != 0 {
panic(fmt.Sprintf("unprepared Swift type %#x/%d", r.arg(0), r.arg(1)))
}
r.set(value)
case "$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ":
r.returnSwiftString(r.String(r.arg(0)))
case "$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF":
r.set(r.New("NSString", r.swiftString(r.arg(0), r.arg(1))))
default:
if strings.Contains(name, "NativeBoxIyLm8ELm8ELm8E") && strings.Contains(name, "initializeBufferWithCopyOfBuffer") {
r.write64(r.arg(0), r.read64(r.arg(1)))
return true
}
if strings.Contains(name, "BridgeObjectBox") && (strings.Contains(name, "initializeWithCopy") || strings.Contains(name, "assignWithCopy")) {
r.write64(r.arg(0), r.read64(r.arg(1)))
return true
}
if strings.Contains(name, "BridgeObjectBox") && strings.Contains(name, "destroy") {
return true
}
if strings.Contains(name, "tuple_initializeWithCopy") || strings.Contains(name, "tuple_assignWithCopy") {
size := r.read64(r.read64(r.arg(2)-8) + 64)
if size > 1024 {
panic("tuple copy exceeds budget")
}
data, err := r.engine.MemRead(r.arg(1), size)
if err != nil {
panic(err)
}
if err = r.MemWrite(r.arg(0), data); err != nil {
panic(err)
}
return true
}
if strings.HasPrefix(name, "swift_memcpy") {
var size, alignment uint64
if _, err := fmt.Sscanf(name, "swift_memcpy%d_%d", &size, &alignment); err != nil || size > 1024 {
panic("unsupported Swift copy size")
}
data, err := r.engine.MemRead(r.arg(1), size)
if err != nil {
panic(err)
}
if err = r.MemWrite(r.arg(0), data); err != nil {
panic(err)
}
return true
}
if strings.Contains(name, "SwiftRetainableBox") && strings.Contains(name, "7destroy") {
return true
}
if strings.Contains(name, "SwiftRetainableBox") && strings.Contains(name, "initializeBufferWithCopyOfBuffer") {
r.write64(r.arg(0), r.read64(r.arg(1)))
return true
}
if value := r.profile.SwiftGlobals[name]; value != 0 {
r.set(value)
return true
}
if (strings.HasPrefix(name, "$sSo17OS_dispatch_queueC8DispatchE") || strings.HasPrefix(name, "$s10Foundation3URLV13DirectoryHintO")) && strings.HasSuffix(name, "Owui") {
metadata := r.arg(2)
if r.read64(r.read64(metadata-8)+64) != 1 {
panic("unexpected dispatch enum size")
}
if err := r.MemWrite(r.arg(0), []byte{byte(r.arg(1))}); err != nil {
panic(err)
}
return true
}
if value := r.profile.SwiftAccessors[name]; value != 0 {
r.set(value)
_ = r.engine.RegWrite(unicorn.RegX1, 0)
return true
}
return false
}
return true
}
func (r *Runtime) returnSwiftString(value string) {
var words [16]byte
if len(value) <= 15 {
copy(words[:], value)
words[15] = 0xa0 | byte(len(value))
if isASCII(value) {
words[15] |= 0x40
}
r.set(binary.LittleEndian.Uint64(words[:8]))
_ = r.engine.RegWrite(unicorn.RegX1, binary.LittleEndian.Uint64(words[8:]))
return
}
// Immortal native UTF-8 uses an address biased by the 32-byte storage header.
p := r.alloc(uint64(len(value) + 33))
if err := r.MemWrite(p+32, append([]byte(value), 0)); err != nil {
panic(err)
}
flags := uint64(len(value)) | 0x3000000000000000
if isASCII(value) {
flags |= 0xc000000000000000
}
r.set(flags)
_ = r.engine.RegWrite(unicorn.RegX1, p|0x8000000000000000)
}
func isASCII(s string) bool {
for _, b := range []byte(s) {
if b >= utf8.RuneSelf {
return false
}
}
return true
}
func (r *Runtime) swiftString(first, second uint64) string {
if second&(1<<61) != 0 {
var b [16]byte
binary.LittleEndian.PutUint64(b[:8], first)
binary.LittleEndian.PutUint64(b[8:], second)
return string(b[:(second>>56)&15])
}
ptr := second & 0x0fffffffffffffff
if second&(1<<60) != 0 {
return r.String(ptr)
}
if second&(1<<63) == 0 {
panic("unsupported mortal Swift string")
}
n := first & 0x0000ffffffffffff
if n > 1<<20 {
panic("Swift string exceeds runtime limit")
}
data, err := r.engine.MemRead(ptr+32, n)
if err != nil {
panic(err)
}
return string(data)
}
func (r *Runtime) mutableSwiftRequest() uint64 {
self, _ := r.engine.RegRead(unicorn.RegX0 + 20)
source := r.read64(self)
object := r.objects[source]
if object == nil {
panic("invalid Swift request storage")
}
copied := r.New(object.Class, object.Value)
if c := r.classes[object.Class]; c != nil {
data, err := r.engine.MemRead(source, c.Size)
if err != nil {
panic(err)
}
if err = r.MemWrite(copied, data); err != nil {
panic(err)
}
}
for k, v := range object.Properties {
r.objects[copied].Properties[k] = v
}
if p := object.Properties["allHTTPHeaderFields"]; p != 0 {
r.objects[copied].Properties["allHTTPHeaderFields"] = r.foundationCopy(p, true)
}
r.write64(self, copied)
return copied
}
File diff suppressed because it is too large. Load diff
+63
View File
@@ -0,0 +1,63 @@
// Package format defines the portable Store runtime profile.
package format
import "strconv"
type Method struct {
Selector string
Address uint64
ClassMethod bool
Types string
}
type Class struct {
MetaAddress uint64
Name string
Address uint64
Super string
Size uint64
Ivars map[string]uint64
Methods []Method
}
type Call struct {
Address uint64
Symbol, Selector string
SelectorAddress uint64
}
type Page struct{ Address, Offset uint64 }
type Constant struct {
IsBoolean bool `json:",omitempty"`
Boolean bool `json:",omitempty"`
Kind string
Text string `json:",omitempty"`
Number int64 `json:",omitempty"`
Entries map[string]uint64 `json:",omitempty"`
Items []uint64 `json:",omitempty"`
}
type DictionaryLayout struct{ Metadata, KeyStride, ValueStride uint64 }
type MetadataPatch struct {
Address uint64
Data []byte
}
type Profile struct {
Bridges map[string]uint64
ObjCMetadata map[string]uint64
SwiftSingletons map[string]uint64
MetadataPatches []MetadataPatch
SwiftForeign map[string]uint64
PluginUUID string
SwiftDictionaries map[string]DictionaryLayout
SwiftGlobals, SwiftTypes, SwiftWitnesses, SwiftAccessors map[string]uint64
Symbols map[string]uint64
Features map[string]bool
Constants map[string]Constant
UUID string
Classes []Class
Calls []Call
Strings map[string]string
Pages []Page
}
// WitnessKey distinguishes conformances instantiated for different generic types.
func WitnessKey(descriptor, metadata uint64) string {
return strconv.FormatUint(descriptor, 10) + ":" + strconv.FormatUint(metadata, 10)
}
+178
View File
@@ -0,0 +1,178 @@
// Package profile loads the precomputed Store profile compiled into the program.
package profile
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"github.com/klauspost/compress/zstd"
)
// Data contains immutable metadata, initialized guest pages, and the plugin image.
type Data struct{ Metadata, Pages, Plugin []byte }
type artifact struct {
Name, SHA256, Encoded string
Size int
}
type loader struct {
gate chan struct{}
installed *Data
decode func(context.Context) (Data, error)
}
var defaultLoader = loader{gate: make(chan struct{}, 1), decode: decodeGenerated}
// Load decodes the committed profile once per process. It performs no file access,
// downloads, or metadata generation.
func Load(ctx context.Context) (Data, error) { return defaultLoader.load(ctx) }
func (l *loader) load(ctx context.Context) (Data, error) {
if ctx == nil {
return Data{}, errors.New("store profile context is nil")
}
select {
case l.gate <- struct{}{}:
case <-ctx.Done():
return Data{}, fmt.Errorf("load Store profile: %w", ctx.Err())
}
defer func() { <-l.gate }()
if err := ctx.Err(); err != nil {
return Data{}, fmt.Errorf("load Store profile: %w", err)
}
if l.installed != nil {
return *l.installed, nil
}
data, err := l.decode(ctx)
if err != nil {
return Data{}, err
}
if err := ctx.Err(); err != nil {
return Data{}, fmt.Errorf("load Store profile: %w", err)
}
l.installed = &data
return data, nil
}
func decodeGenerated(ctx context.Context) (Data, error) {
metadata, err := decodeArtifact(ctx, generatedMetadata, 128<<20)
if err != nil {
return Data{}, err
}
pages, err := decodeArtifact(ctx, generatedPages, 256<<20)
if err != nil {
return Data{}, err
}
plugin, err := decodeArtifact(ctx, generatedPlugin, 64<<20)
if err != nil {
return Data{}, err
}
result := Data{Metadata: metadata, Pages: pages, Plugin: plugin}
if err = validateData(result); err != nil {
return Data{}, err
}
return result, nil
}
// decodeArtifact bounds decompression by the committed size and checks the raw
// digest in addition to the compressed frame's checksum.
func decodeArtifact(ctx context.Context, item artifact, limit int) ([]byte, error) {
if item.Size <= 0 || item.Size > limit {
return nil, fmt.Errorf("invalid compiled %s size", item.Name)
}
input := base64.NewDecoder(base64.StdEncoding, strings.NewReader(item.Encoded))
decoder, err := zstd.NewReader(contextReader{ctx: ctx, reader: input}, zstd.WithDecoderConcurrency(1), zstd.WithDecoderMaxMemory(uint64(limit)))
if err != nil {
return nil, fmt.Errorf("open compiled %s: %w", item.Name, err)
}
defer decoder.Close()
data := make([]byte, item.Size+1)
n, err := io.ReadFull(decoder, data)
if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) && !errors.Is(err, io.EOF) {
return nil, fmt.Errorf("decode compiled %s: %w", item.Name, err)
}
if n != item.Size {
return nil, fmt.Errorf("compiled %s has an invalid decoded size", item.Name)
}
data = data[:n:n]
if fmt.Sprintf("%x", sha256.Sum256(data)) != item.SHA256 {
return nil, fmt.Errorf("compiled %s failed integrity verification", item.Name)
}
return data, nil
}
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, fmt.Errorf("read compiled Store profile: %w", err)
}
n, err := r.reader.Read(data)
if errors.Is(err, io.EOF) {
return n, io.EOF
}
if err != nil {
return n, fmt.Errorf("read compiled Store profile: %w", err)
}
return n, nil
}
func validateData(data Data) error {
var metadata struct {
UUID, PluginUUID string
Pages []struct{ Address, Offset uint64 }
}
if err := json.Unmarshal(data.Metadata, &metadata); err != nil {
return fmt.Errorf("decode Store metadata: %w", err)
}
if metadata.UUID != generatedFrameworkUUID || metadata.PluginUUID != generatedPluginUUID {
return errors.New("compiled Store profile uses unexpected Apple images")
}
if len(metadata.Pages) == 0 || len(metadata.Pages) != len(data.Pages)/4096 || len(data.Pages)%4096 != 0 || len(data.Plugin) == 0 {
return errors.New("incomplete compiled Store profile")
}
for i, page := range metadata.Pages {
if page.Address%4096 != 0 || page.Offset != uint64(i)*4096 {
return errors.New("invalid Store page index")
}
}
return nil
}
+134
View File
@@ -0,0 +1,134 @@
package profile
import (
"context"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"sync/atomic"
"testing"
"time"
"github.com/klauspost/compress/zstd"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestStoreProfile(t *testing.T) { RegisterFailHandler(Fail); RunSpecs(t, "Store Profile") }
func fixtureArtifact(data []byte) artifact {
encoder, err := zstd.NewWriter(nil, zstd.WithEncoderConcurrency(1))
Expect(err).NotTo(HaveOccurred())
defer encoder.Close()
return artifact{Name: "fixture", Size: len(data), SHA256: fmt.Sprintf("%x", sha256.Sum256(data)), Encoded: base64.StdEncoding.EncodeToString(encoder.EncodeAll(data, nil))}
}
var _ = Describe("Compiled Store profile", func() {
It("loads and validates the complete committed profile without setup", func() {
data, err := Load(context.Background())
Expect(err).NotTo(HaveOccurred())
Expect(validateData(data)).To(Succeed())
Expect(data.Metadata).To(HaveLen(generatedMetadata.Size))
Expect(data.Pages).To(HaveLen(generatedPages.Size))
Expect(data.Plugin).To(HaveLen(generatedPlugin.Size))
})
It("honors cancellation before decoding", func() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := Load(ctx)
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
})
It("rejects a nil context", func() {
_, err := Load(nil) //nolint:staticcheck // Verify rejection of invalid caller input.
Expect(err).To(MatchError(ContainSubstring("context is nil")))
})
})
var _ = Describe("Compiled artifact integrity", func() {
It("decodes binary data and rejects a mismatched digest", func() {
original := []byte{0, 1, 2, 0xff, '\n', '`'}
item := fixtureArtifact(original)
actual, err := decodeArtifact(context.Background(), item, 1<<20)
Expect(err).NotTo(HaveOccurred())
Expect(actual).To(Equal(original))
item.SHA256 = "invalid"
_, err = decodeArtifact(context.Background(), item, 1<<20)
Expect(err).To(MatchError(ContainSubstring("integrity verification")))
})
DescribeTable("rejects incorrect decoded sizes", func(delta int) {
item := fixtureArtifact([]byte("encoded data"))
item.Size += delta
_, err := decodeArtifact(context.Background(), item, 1<<20)
Expect(err).To(MatchError(ContainSubstring("decoded size")))
}, Entry("too short", -1), Entry("too long", 1))
It("rejects an artifact above its allowed limit before decoding", func() {
_, err := decodeArtifact(context.Background(), artifact{Name: "fixture", Size: 100}, 99)
Expect(err).To(MatchError(ContainSubstring("size")))
})
It("rejects corrupt compressed data", func() {
item := fixtureArtifact([]byte("encoded data"))
item.Encoded = base64.StdEncoding.EncodeToString([]byte("invalid frame"))
_, err := decodeArtifact(context.Background(), item, 1<<20)
Expect(err).To(HaveOccurred())
})
It("propagates cancellation through the decoder", func() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := decodeArtifact(ctx, fixtureArtifact([]byte("encoded data")), 1<<20)
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
})
})
var _ = Describe("Profile loading concurrency", func() {
It("shares one successful decode and lets a waiter cancel independently", func() {
var calls atomic.Int32
entered, release := make(chan struct{}), make(chan struct{})
data := Data{Metadata: []byte("ready")}
instance := &loader{gate: make(chan struct{}, 1), decode: func(context.Context) (Data, error) {
calls.Add(1)
close(entered)
<-release
return data, nil
}}
finished := make(chan error, 1)
go func() { _, err := instance.load(context.Background()); finished <- err }()
Eventually(entered).Should(BeClosed())
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
_, err := instance.load(ctx)
Expect(errors.Is(err, context.DeadlineExceeded)).To(BeTrue())
close(release)
Eventually(finished).Should(Receive(BeNil()))
actual, err := instance.load(context.Background())
Expect(err).NotTo(HaveOccurred())
Expect(actual).To(Equal(data))
Expect(calls.Load()).To(Equal(int32(1)))
})
It("does not cache a decode canceled before publication", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
calls := 0
instance := &loader{gate: make(chan struct{}, 1), decode: func(context.Context) (Data, error) {
calls++
cancel()
return Data{Metadata: []byte("ready")}, nil
}}
_, err := instance.load(ctx)
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
Expect(instance.installed).To(BeNil())
_, err = instance.load(context.Background())
Expect(err).NotTo(HaveOccurred())
Expect(calls).To(Equal(2))
})
})
+43
View File
@@ -0,0 +1,43 @@
package profilegen
import (
"sort"
profileformat "github.com/majd/ipatool/v2/internal/store/profile/format"
)
// reachableClasses retains Store implementations, referenced class identities,
// and their complete superclass chains. Imported classes without Store methods
// still need their layouts when the bridge allocates or inspects their objects.
func reachableClasses(classes []profileformat.Class, names map[string]bool) []profileformat.Class {
byName := make(map[string]profileformat.Class, len(classes))
for _, class := range classes {
byName[class.Name] = class
if len(class.Methods) != 0 {
names[class.Name] = true
}
}
kept := map[string]bool{}
for name := range names {
for name != "" && !kept[name] {
class, ok := byName[name]
if !ok {
break
}
kept[name] = true
name = class.Super
}
}
result := make([]profileformat.Class, 0, len(kept))
for name := range kept {
result = append(result, byName[name])
}
sort.Slice(result, func(i, j int) bool { return result[i].Name < result[j].Name })
return result
}
+24
View File
@@ -0,0 +1,24 @@
package profilegen
import (
profileformat "github.com/majd/ipatool/v2/internal/store/profile/format"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Referenced Objective-C classes", func() {
It("keeps referenced layouts, Store categories and superclasses while dropping unrelated classes", func() {
classes := []profileformat.Class{
{Name: "Unrelated"},
{Name: "Category", Super: "Root", Methods: []profileformat.Method{{Selector: "storeMethod"}}},
{Name: "Imported", Super: "Root", Size: 48, Ivars: map[string]uint64{"value": 16}},
{Name: "Root", Size: 16},
}
actual := reachableClasses(classes, map[string]bool{"Imported": true, "Missing": true})
Expect(actual).To(Equal([]profileformat.Class{classes[1], classes[2], classes[3]}))
})
It("terminates cyclic superclass chains deterministically", func() {
classes := []profileformat.Class{{Name: "B", Super: "A"}, {Name: "A", Super: "B"}}
Expect(reachableClasses(classes, map[string]bool{"B": true})).To(Equal([]profileformat.Class{classes[1], classes[0]}))
})
})
@@ -0,0 +1,146 @@
// Command profilegen regenerates the committed Store profile from pinned Apple
// binaries under Unicorn. Normal builds and library consumers do not run it.
package main
import (
"bytes"
"context"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"github.com/majd/ipatool/v2/internal/sap/assets"
"github.com/majd/ipatool/v2/internal/store/profilegen"
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
cachePath := flag.String("cache", "", "optional offline copy of the pinned dyld shared cache")
output := flag.String("output", "internal/store/profile/data_generated.go", "generated Go source file")
check := flag.Bool("check", false, "regenerate and compare with the committed output without writing files")
flag.Parse()
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
fmt.Fprintln(os.Stderr, "Generating Store profile from pinned Apple binaries under Unicorn...")
var cache *assets.StoreCache
var err error
if *cachePath == "" {
cache, err = assets.OpenRemoteStoreCache(ctx)
} else {
cache, err = assets.OpenLocalStoreCache(ctx, *cachePath)
}
if err != nil {
return fmt.Errorf("open profile inputs: %w", err)
}
defer cache.Close()
result, err := profilegen.Generate(ctx, cache)
if err != nil {
return fmt.Errorf("generate profile: %w", err)
}
workspace, err := os.MkdirTemp("", "ipatool-profile-")
if err != nil {
return fmt.Errorf("create profile workspace: %w", err)
}
defer os.RemoveAll(workspace)
pluginPath := filepath.Join(workspace, "AMSAccountAuthenticationPlugin")
if err = cache.ExtractAuthenticationPlugin(pluginPath); err != nil {
return fmt.Errorf("extract authentication plugin: %w", err)
}
plugin, err := os.ReadFile(pluginPath)
if err != nil {
return fmt.Errorf("read authentication plugin: %w", err)
}
source, err := result.GoSource(ctx, plugin)
if err != nil {
return fmt.Errorf("encode profile source: %w", err)
}
current, err := os.ReadFile(*output)
if err == nil && bytes.Equal(current, source) {
fmt.Fprintln(os.Stderr, "Store profile is up to date.")
return nil
}
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("read generated profile: %w", err)
}
if *check {
return fmt.Errorf("generated Store profile differs from %s; regenerate it before committing", *output)
}
if err = writeSource(ctx, *output, source); err != nil {
return err
}
fmt.Fprintf(os.Stderr, "Wrote %s (%d bytes).\n", *output, len(source))
return nil
}
// writeSource replaces the complete Go file atomically after generation succeeds.
func writeSource(ctx context.Context, path string, source []byte) error {
if err := ctx.Err(); err != nil {
return fmt.Errorf("write profile source: %w", err)
}
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return fmt.Errorf("create profile output directory: %w", err)
}
file, err := os.CreateTemp(filepath.Dir(path), ".profile-source-*")
if err != nil {
return fmt.Errorf("create profile output: %w", err)
}
defer os.Remove(file.Name())
defer file.Close()
if err = file.Chmod(0644); err != nil {
return fmt.Errorf("set profile source permissions: %w", err)
}
if _, err = file.Write(source); err != nil {
return fmt.Errorf("write profile source: %w", err)
}
if err = file.Sync(); err != nil {
return fmt.Errorf("sync profile source: %w", err)
}
if err = file.Close(); err != nil {
return fmt.Errorf("close profile source: %w", err)
}
if err = ctx.Err(); err != nil {
return fmt.Errorf("write profile source: %w", err)
}
if err = os.Rename(file.Name(), path); err != nil {
return fmt.Errorf("install profile source: %w", err)
}
return nil
}
+526
View File
@@ -0,0 +1,526 @@
package profilegen
import (
"encoding/binary"
"fmt"
"sort"
"strconv"
"strings"
"unicode/utf16"
profileformat "github.com/majd/ipatool/v2/internal/store/profile/format"
)
type collector struct {
v *bootstrapVM
p *profileformat.Profile
pages map[uint64]bool
metadataPages map[uint64]bool
calls map[uint64]profileformat.Call
classes map[uint64]string
references map[uint64]bool
classNames map[uint64]string
neededClasses map[string]bool
}
func adrp(word uint32, pc uint64) uint64 {
imm := int64((word>>5&0x7ffff)<<2 | word>>29&3)
if imm&(1<<20) != 0 {
imm -= 1 << 21
}
return uint64(int64(pc&^4095) + (imm << 12))
}
// addPage excludes objects represented by the host bridge. Their class layouts
// and values are exported separately; copying their runtime internals pulls in
// unrelated Objective-C registries and methods from other frameworks.
func (c *collector) addPage(a uint64) {
if c.classNames[a] != "" {
return
}
key := strconv.FormatUint(a, 10)
if _, ok := c.p.Strings[key]; ok {
return
}
if _, ok := c.p.Constants[key]; ok {
return
}
c.rawPage(a)
}
// rawPage retains storage required by native Swift metadata even when its
// address also identifies a class handled by the Objective-C bridge.
func (c *collector) rawPage(a uint64) {
if !inside(a, c.v.source.target) && !inside(a, c.v.source.code) && c.inCache(a) {
c.pages[a&^4095] = true
}
if a >= bootHeap && a < bootHeap+c.v.cursor {
c.pages[a&^4095] = true
}
}
// reference records an actual address operand or pointer slot. Object graphs
// start at these roots, never at incidental pointers elsewhere in a copied page.
func (c *collector) reference(a uint64) {
for !c.references[a] && c.inCache(a) && !inside(a, c.v.source.code) {
c.references[a] = true
if name := c.classNames[a]; name != "" {
c.neededClasses[name] = true
return
}
if c.recordString(a) {
return
}
c.constant(a, 0)
if _, ok := c.p.Constants[strconv.FormatUint(a, 10)]; ok {
return
}
c.addPage(a)
// An imported global can add multiple indirections before the object.
// Follow that chain, rather than scanning neighboring pointer slots.
a = c.v.source.u64(a)
}
c.addPage(a)
}
func (c *collector) inCache(a uint64) bool {
return c.v.source.cache.Contains(a, 32)
}
func (c *collector) metadata(a uint64) {
if a != 0 {
c.rawPage(a)
c.reference(a)
c.metadataPages[a&^4095] = true
}
}
func (c *collector) resolve(a uint64) {
s := c.v.source
if inside(a, s.target) {
return
}
if _, ok := c.calls[a]; ok {
return
}
b := s.read(a, 16)
w0, w1, w2 := binary.LittleEndian.Uint32(b), binary.LittleEndian.Uint32(b[4:]), binary.LittleEndian.Uint32(b[8:])
if w0&0x9f000000 == 0x90000000 {
ptr := adrp(w0, a)
switch w1 & 0xffc00000 {
case 0x91000000:
ptr += uint64(w1 >> 10 & 0xfff)
case 0xf9400000:
ptr = s.u64(ptr + uint64(w1>>10&0xfff)*8)
default:
ptr = 0
}
if ptr != 0 && w0&31 == 1 {
c.calls[a] = profileformat.Call{Address: a, Selector: s.cstring(ptr), SelectorAddress: ptr}
return
}
if ptr != 0 && w0&31 == 17 && w2&0xffc00000 == 0xf9400000 {
ptr = s.u64(ptr)
name := s.symbol(ptr)
if name == "" {
name = fmt.Sprintf("unresolved_%x", ptr)
}
c.calls[a] = profileformat.Call{Address: a, Symbol: canonicalSymbol(name)}
return
}
}
if name := s.symbol(a); name != "" {
c.calls[a] = profileformat.Call{Address: a, Symbol: canonicalSymbol(name)}
}
}
func (c *collector) constant(a uint64, depth int) {
if a == 0 || depth > 16 || !c.inCache(a) {
return
}
key := strconv.FormatUint(a, 10)
if _, ok := c.p.Constants[key]; ok {
return
}
s := c.v.source
name := c.classes[s.u64(a)]
item := profileformat.Constant{}
switch name {
case "__NSCFConstantString", "NSConstantString":
item.Kind = "NSString"
item.Text, _ = c.stringValue(a)
case "NSConstantIntegerNumber":
item.Kind = "NSNumber"
item.Number = int64(s.u64(a + 16))
case "__NSCFBoolean":
item.Kind = "NSNumber"
item.IsBoolean = true
item.Boolean = a == s.u64(s.exports["_kCFBooleanTrue"])
if item.Boolean {
item.Number = 1
}
case "__NSDictionary0":
item.Kind = "NSDictionary"
item.Entries = map[string]uint64{}
case "__NSArray0":
item.Kind = "NSArray"
item.Items = []uint64{}
case "NSConstantDictionary":
item.Kind = "NSDictionary"
item.Entries = map[string]uint64{}
c.p.Constants[key] = item
n, keys, values := s.u64(a+16), s.u64(a+24), s.u64(a+32)
if n > 1<<20 {
panic("constant dictionary too large")
}
for i := uint64(0); i < n; i++ {
k, val := s.u64(keys+i*8), s.u64(values+i*8)
c.constant(val, depth+1)
if text, ok := c.stringValue(k); ok {
item.Entries[text] = val
}
}
case "NSConstantArray":
item.Kind = "NSArray"
item.Items = []uint64{}
c.p.Constants[key] = item
n, values := s.u64(a+8), s.u64(a+16)
if n > 1<<20 {
panic("constant array too large")
}
for i := uint64(0); i < n; i++ {
val := s.u64(values + i*8)
c.constant(val, depth+1)
item.Items = append(item.Items, val)
}
default:
return
}
c.p.Constants[key] = item
}
func (v *bootstrapVM) collect(p *profileformat.Profile, classes []profileformat.Class) []byte {
s := v.source
p.Classes = classes
p.UUID = s.images[amsImage].UUID().String()
p.PluginUUID = s.images[authImage].UUID().String()
p.Strings = map[string]string{}
p.Constants = map[string]profileformat.Constant{}
c := &collector{v: v, p: p, pages: map[uint64]bool{}, metadataPages: map[uint64]bool{}, calls: map[uint64]profileformat.Call{}, classes: map[uint64]string{}, references: map[uint64]bool{}, classNames: map[uint64]string{}, neededClasses: map[string]bool{}}
for _, class := range classes {
c.classes[class.Address] = class.Name
c.classNames[class.Address] = class.Name
c.classNames[class.MetaAddress] = class.Name
}
for _, name := range []string{amsImage, authImage} {
for _, sec := range s.images[name].Sections {
if sec.Flags.IsPureInstructions() || sec.Flags.IsSomeInstructions() {
b := s.read(sec.Addr, sec.Size)
dataReferences(b, sec.Addr, c.reference)
for off := uint64(0); off+4 <= sec.Size; off += 4 {
word := binary.LittleEndian.Uint32(b[off:])
pc := sec.Addr + off
if word&0x7c000000 == 0x14000000 {
imm := int64(word & 0x3ffffff)
if imm&(1<<25) != 0 {
imm -= 1 << 26
}
c.resolve(uint64(int64(pc) + imm*4))
}
}
} else if sec.Name != "__bss" && sec.Name != "__common" {
b := s.read(sec.Addr, sec.Size)
if sec.Name == "__cstring" || sec.Name == "__objc_classname" {
for _, name := range strings.Split(string(b), "\x00") {
c.neededClasses[className(name)] = true
}
}
for off := uint64(0); off+8 <= sec.Size; off += 8 {
if sec.Name == "__cfstring" && off%32 == 0 {
c.recordString(sec.Addr + off)
}
switch sec.Name {
case "__got", "__auth_got", "__objc_classrefs", "__objc_superrefs", "__objc_selrefs", "__la_symbol_ptr", "__nl_symbol_ptr":
c.reference(binary.LittleEndian.Uint64(b[off:]))
}
name := c.classes[binary.LittleEndian.Uint64(b[off:])]
if name == "NSConstantDictionary" || name == "NSConstantArray" || name == "NSConstantIntegerNumber" {
c.constant(sec.Addr+off, 0)
}
}
}
}
}
for _, call := range c.calls {
if a := s.exports["_"+call.Symbol]; a != 0 && !inside(a, s.target) {
c.calls[a] = profileformat.Call{Address: a, Symbol: canonicalSymbol(call.Symbol)}
}
}
for _, name := range []string{"___chkstk_darwin", "gmtime_r", "localtime_r"} {
if a := s.exports["_"+name]; a != 0 {
c.calls[a] = profileformat.Call{Address: a, Symbol: canonicalSymbol(name)}
}
}
for _, m := range []map[string]uint64{p.SwiftTypes, p.SwiftAccessors, p.SwiftSingletons, p.SwiftForeign, p.ObjCMetadata} {
for _, a := range m {
c.metadata(a)
c.metadata(v.u64(a - 8))
}
}
for _, a := range p.Bridges {
c.metadata(a)
}
c.metadata(v.u64(p.Bridges["anyHashableStringMetadata"] - 8))
for _, a := range p.SwiftWitnesses {
c.metadata(a)
}
for _, a := range p.SwiftGlobals {
c.metadata(a)
c.metadata(v.u64(a))
}
for _, layout := range p.SwiftDictionaries {
c.metadata(layout.Metadata)
}
for name, a := range p.Symbols {
c.reference(a)
if strings.HasSuffix(name, "N") {
off := uint64(8)
if name == "$sypN" {
off = 0
}
c.metadata(v.u64(a - off))
}
}
// Preserve initialized metadata inside the executable images, including Swift
// field offsets. Executable pages are supplied separately by the image loader.
for page := range v.mapped {
if inside(page, s.target) && !inside(page, s.code) {
b := v.read(page, 4096)
original := s.read(page, 4096)
for off := 0; off < 4096; off += 8 {
if binary.LittleEndian.Uint64(b[off:]) != binary.LittleEndian.Uint64(original[off:]) {
p.MetadataPatches = append(p.MetadataPatches, profileformat.MetadataPatch{Address: page + uint64(off), Data: append([]byte(nil), b[off:off+8]...)})
}
}
}
}
sort.Slice(p.MetadataPatches, func(i, j int) bool { return p.MetadataPatches[i].Address < p.MetadataPatches[j].Address })
var pages []byte
done := map[uint64]bool{}
for pass := 0; pass < 2; pass++ {
addresses := make([]uint64, 0, len(c.pages))
for a := range c.pages {
addresses = append(addresses, a)
}
sort.Slice(addresses, func(i, j int) bool { return addresses[i] < addresses[j] })
for _, a := range addresses {
if done[a] {
continue
}
done[a] = true
b := v.snapshotPage(a)
for off := 0; off < 4096; off += 8 {
ptr := binary.LittleEndian.Uint64(b[off:])
if name := c.classNames[ptr]; name != "" {
c.neededClasses[name] = true
}
if c.inCache(ptr) {
if c.metadataPages[a] && !inside(ptr, s.target) && inside(ptr, s.code) {
if name := s.symbol(ptr); name != "" {
c.calls[ptr] = profileformat.Call{Address: ptr, Symbol: canonicalSymbol(name)}
}
}
}
// Swift metadata contains dynamically indexed tables. Preserve
// their pointer dependencies; ordinary data pages are rooted at
// the exact operands above, not every neighboring pointer.
if pass == 0 && c.metadataPages[a] {
c.addPage(ptr)
}
}
p.Pages = append(p.Pages, profileformat.Page{Address: a, Offset: uint64(len(pages))})
pages = append(pages, b...)
}
}
for _, name := range []string{"_kCFBooleanTrue", "_kCFBooleanFalse"} {
if a := s.exports[name]; a != 0 {
c.constant(s.u64(a), 0)
}
}
for _, call := range c.calls {
p.Calls = append(p.Calls, call)
}
sort.Slice(p.Calls, func(i, j int) bool { return p.Calls[i].Address < p.Calls[j].Address })
for name := range p.ObjCMetadata {
c.neededClasses[name] = true
}
if len(p.Strings) != 0 {
c.neededClasses["NSString"] = true
}
for _, constant := range p.Constants {
c.neededClasses[constant.Kind] = true
}
p.Classes = reachableClasses(classes, c.neededClasses)
return pages
}
// Snapshot untouched pages directly from the binary. Mapping thousands of
// read-only pages into Unicorn here would make export needlessly quadratic.
func (v *bootstrapVM) snapshotPage(a uint64) []byte {
if !v.mapped[a] && (a < bootHeap || a >= bootHeap+v.cursor) {
return v.source.read(a, 4096)
}
b := v.read(a, 4096)
if v.source.cache.Contains(a, 4096) {
for off := uint64(0); off < 4096; off += 4 {
if inside(a+off, v.source.code) {
copy(b[off:off+4], v.source.read(a+off, 4))
}
}
}
return b
}
func canonicalSymbol(name string) string {
switch name {
case "swift_release_preservemost":
return "swift_release"
case "swift_retain_preservemost":
return "swift_retain"
case "dispatch_channel_async":
return "dispatch_async"
case "dispatch_queue_create_with_target$V2":
return "dispatch_queue_create_with_target"
case "exp2l":
return "exp2"
case "_platform_bzero":
return "__bzero"
case "objc_release_x0":
return "objc_release"
case "objc_retain_x0":
return "objc_retain"
case "powl":
return "pow"
case "dispatch_assert_queue$V2":
return "dispatch_assert_queue"
case "dispatch_assert_queue_not$V2":
return "dispatch_assert_queue_not"
}
return name
}
func (c *collector) stringValue(a uint64) (string, bool) {
if a == 0 || !c.inCache(a) {
return "", false
}
s := c.v.source
name := c.classes[s.u64(a)]
if name != "__NSCFConstantString" && name != "NSConstantString" {
return "", false
}
ptr, n := s.u64(a+16), s.u64(a+24)
if n > 1<<20 {
panic("constant string too large")
}
if s.u32(a+8)&0x10 != 0 {
b := s.read(ptr, n*2)
u := make([]uint16, n)
for i := range u {
u[i] = binary.LittleEndian.Uint16(b[i*2:])
}
return string(utf16.Decode(u)), true
}
return string(s.read(ptr, n)), true
}
func (c *collector) recordString(a uint64) bool {
key := strconv.FormatUint(a, 10)
if _, ok := c.p.Strings[key]; ok {
return true
}
if text, ok := c.stringValue(a); ok {
c.p.Strings[key] = text
return true
}
return false
}
+261
View File
@@ -0,0 +1,261 @@
package profilegen
import (
"encoding/binary"
"fmt"
"sort"
"strings"
profileformat "github.com/majd/ipatool/v2/internal/store/profile/format"
)
type typeRequest struct{ Address, Length uint64 }
type metadataAccessor struct{ Descriptor, Address uint64 }
type globalRequest struct {
Name string
Address uint64
}
type swiftRequests struct {
Types []typeRequest
Accessors []string
Globals []globalRequest
Nominals []metadataAccessor
Conformances []uint64
}
// mangledNameLength honors the embedded relative and absolute symbolic references
// described by Swift's ABI; their payloads can contain zero bytes.
func mangledNameLength(data []byte) (int, error) {
for i := 0; i < len(data); {
b := data[i]
if b == 0 {
return i, nil
}
i++
size := 0
switch {
case b >= 1 && b <= 0x17:
size = 4
case b >= 0x18 && b <= 0x1f:
size = 8
}
if size > len(data)-i {
return 0, fmt.Errorf("truncated Swift symbolic reference")
}
i += size
}
return 0, fmt.Errorf("unterminated Swift mangled name")
}
// concreteTypeRecords reads the compiler's relative-name/length records. Matching
// both fields against actual typeref boundaries excludes reflection records and
// unrelated constants; no virtual addresses are supplied by the host.
func concreteTypeRecords(base uint64, data []byte, names map[uint64]uint64) []typeRequest {
var result []typeRequest
for off := 0; off+8 <= len(data); off += 4 {
address := uint64(int64(base+uint64(off)) + int64(int32(binary.LittleEndian.Uint32(data[off:]))))
length := uint64(binary.LittleEndian.Uint32(data[off+4:]))
if length != 0 && names[address] == length {
result = append(result, typeRequest{address, length})
}
}
return result
}
// discoverSwiftRequests inventories the concrete metadata records, nominal type
// descriptors, imported accessors, and protocol conformances of the Store images.
func (s *source) discoverSwiftRequests() (*swiftRequests, error) {
req := &swiftRequests{}
types := map[uint64]uint64{}
conformances := map[uint64]bool{}
exportedConformances := map[uint64]bool{}
for name, a := range s.exports {
if strings.HasSuffix(name, "Mc") && strings.HasPrefix(name, "_$s") {
exportedConformances[a] = true
}
}
for _, name := range []string{amsImage, authImage} {
f := s.images[name]
names := map[uint64]uint64{}
for _, sec := range f.Sections {
if sec.Name != "__swift5_typeref" {
continue
}
data := s.read(sec.Addr, sec.Size)
for off := 0; off < len(data); {
if data[off] == 0 || data[off] == 0xff {
off++
continue
}
n, err := mangledNameLength(data[off:])
if err != nil {
return nil, fmt.Errorf("read %s type references: %w", name, err)
}
names[sec.Addr+uint64(off)] = uint64(n)
off += n + 1
}
}
for _, sec := range f.Sections {
if sec.Flags.IsPureInstructions() || sec.Flags.IsSomeInstructions() {
data := s.read(sec.Addr, sec.Size)
for off := 0; off+8 <= len(data); off += 4 {
slot, ok := referencedPointer(binary.LittleEndian.Uint32(data[off:]), binary.LittleEndian.Uint32(data[off+4:]), sec.Addr+uint64(off))
if ok && s.cache.Contains(slot, 8) {
if a := s.u64(slot); exportedConformances[a] {
conformances[a] = true
}
}
}
}
switch sec.Name {
case "__const":
if sec.Seg != "__TEXT" {
continue
}
for _, r := range concreteTypeRecords(sec.Addr, s.read(sec.Addr, sec.Size), names) {
types[r.Address] = r.Length
}
case "__swift5_types":
for off := uint64(0); off+4 <= sec.Size; off += 4 {
d := s.relative(sec.Addr + off)
flags := s.u32(d)
if flags&0x80 != 0 || flags&0x1f < 16 || flags&0x1f > 18 || s.u32(d+12) == 0 {
continue
}
req.Nominals = append(req.Nominals, metadataAccessor{d, s.relative(d + 12)})
}
case "__swift5_proto":
for off := uint64(0); off+4 <= sec.Size; off += 4 {
conformances[s.relative(sec.Addr+off)] = true
}
case "__got", "__auth_got":
for off := uint64(0); off+8 <= sec.Size; off += 8 {
a := s.u64(sec.Addr + off)
if exportedConformances[a] {
conformances[a] = true
}
}
}
}
}
for a, n := range types {
req.Types = append(req.Types, typeRequest{a, n})
}
for a := range conformances {
req.Conformances = append(req.Conformances, a)
}
calls := s.storeCalls()
accessors, globals := map[string]bool{}, map[string]bool{}
for _, c := range calls {
name := c.Symbol
if !strings.HasPrefix(name, "$s") {
continue
}
if strings.HasSuffix(name, "Ma") {
d := s.exports["_"+strings.TrimSuffix(name, "Ma")+"Mn"]
if d != 0 && s.u32(d)&0x80 == 0 {
accessors[name] = true
}
}
if strings.HasSuffix(name, "vau") {
globals[name] = true
}
}
for name := range accessors {
req.Accessors = append(req.Accessors, name)
}
for name := range globals {
a := s.exports["_"+name]
if a == 0 {
return nil, fmt.Errorf("missing Swift global accessor %s", name)
}
req.Globals = append(req.Globals, globalRequest{name, a})
}
sort.Slice(req.Types, func(i, j int) bool { return req.Types[i].Address < req.Types[j].Address })
sort.Slice(req.Nominals, func(i, j int) bool { return req.Nominals[i].Descriptor < req.Nominals[j].Descriptor })
sort.Slice(req.Conformances, func(i, j int) bool { return req.Conformances[i] < req.Conformances[j] })
sort.Strings(req.Accessors)
sort.Slice(req.Globals, func(i, j int) bool { return req.Globals[i].Name < req.Globals[j].Name })
if len(req.Types) == 0 {
return nil, fmt.Errorf("store images have no concrete Swift type records")
}
return req, nil
}
func (s *source) relative(address uint64) uint64 {
return uint64(int64(address) + int64(int32(s.u32(address))))
}
// storeCalls resolves imported branch targets, including shared-cache stubs that
// no longer appear in the individual image's symbol or import tables.
func (s *source) storeCalls() map[uint64]profileformat.Call {
c := &collector{v: &bootstrapVM{source: s}, calls: map[uint64]profileformat.Call{}}
for _, name := range []string{amsImage, authImage} {
for _, sec := range s.images[name].Sections {
if !sec.Flags.IsPureInstructions() && !sec.Flags.IsSomeInstructions() {
continue
}
data := s.read(sec.Addr, sec.Size)
for off := uint64(0); off+4 <= sec.Size; off += 4 {
w := binary.LittleEndian.Uint32(data[off:])
if w&0x7c000000 != 0x14000000 {
continue
}
imm := int64(w & 0x3ffffff)
if imm&(1<<25) != 0 {
imm -= 1 << 26
}
c.resolve(uint64(int64(sec.Addr+off) + imm*4))
}
}
}
return c.calls
}
// referencedPointer recognizes compiler loads from dyld-coalesced GOT slots,
// which may live outside the importing image's own GOT sections.
func referencedPointer(page, load uint32, pc uint64) (uint64, bool) {
if page&0x9f000000 != 0x90000000 || load&0xffc00000 != 0xf9400000 || page&31 != (load>>5)&31 {
return 0, false
}
return adrp(page, pc) + uint64(load>>10&0xfff)*8, true
}
+100
View File
@@ -0,0 +1,100 @@
package profilegen
import (
"context"
"encoding/binary"
"github.com/majd/ipatool/v2/internal/sap/unicorn"
profileformat "github.com/majd/ipatool/v2/internal/store/profile/format"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Swift bootstrap discovery", func() {
DescribeTable("measures symbolic mangled names without treating payload zeros as terminators", func(data []byte, length int) {
n, err := mangledNameLength(data)
Expect(err).NotTo(HaveOccurred())
Expect(n).To(Equal(length))
}, Entry("plain", []byte{'S', 'S', 0}, 2), Entry("relative", []byte{2, 0, 0, 0, 0, 'y', 'S', 'S', 'G', 0}, 9), Entry("absolute", []byte{0x18, 0, 0, 0, 0, 0, 0, 0, 0, 'G', 0}, 10))
DescribeTable("rejects malformed symbolic names", func(data []byte) { _, err := mangledNameLength(data); Expect(err).To(HaveOccurred()) }, Entry("missing terminator", []byte{'S', 'S'}), Entry("short relative", []byte{1, 0, 0}), Entry("short absolute", []byte{0x18, 0, 0, 0, 0}))
It("discovers relocated relative records and excludes invalid lengths and interior references", func() {
for _, base := range []uint64{0x2000, 0x140000000} {
data := make([]byte, 32)
binary.LittleEndian.PutUint32(data, 0xfffffff0)
binary.LittleEndian.PutUint32(data[4:], 9)
binary.LittleEndian.PutUint32(data[8:], 0x100)
binary.LittleEndian.PutUint32(data[12:], 3)
binary.LittleEndian.PutUint32(data[16:], 0xffffffe0)
binary.LittleEndian.PutUint32(data[20:], 8)
binary.LittleEndian.PutUint32(data[24:], 0xffffffda)
binary.LittleEndian.PutUint32(data[28:], 7)
names := map[uint64]uint64{base - 16: 9, base + 0x108: 3}
Expect(concreteTypeRecords(base, data, names)).To(Equal([]typeRequest{{base - 16, 9}, {base + 0x108, 3}}))
}
})
It("finds coalesced GOT references only when the address register matches", func() {
a, ok := referencedPointer(0x90000001, 0xf9402420, 0x2000)
Expect(ok).To(BeTrue())
Expect(a).To(Equal(uint64(0x2048)))
_, ok = referencedPointer(0x90000002, 0xf9402420, 0x2000)
Expect(ok).To(BeFalse())
_, ok = referencedPointer(0x90000001, 0xf9002420, 0x2000)
Expect(ok).To(BeFalse())
})
})
var _ = Describe("Observed Swift metadata", func() {
It("keeps generic witness instantiations separate and records only complete foreign metadata", func() {
engine, err := unicorn.New(context.Background())
Expect(err).NotTo(HaveOccurred())
DeferCleanup(engine.Close)
Expect(engine.MemMap(bootHeap, 4096)).To(Succeed())
v := &bootstrapVM{engine: engine, metadata: newMetadataProfile(), allocations: map[uint64]uint64{}, callbacks: map[uint64]func(){}}
for _, m := range []uint64{100, 200} {
v.set(0, 10)
v.set(1, m)
v.writeRegister(unicorn.RegLR, bootReturn)
v.observeMetadataCall("swift_getWitnessTable")
link, err := engine.RegRead(unicorn.RegLR)
Expect(err).NotTo(HaveOccurred())
Expect(link).To(Equal(bootReturn))
v.set(0, m+1000)
v.observeMetadataReturn(bootReturn)
}
Expect(v.metadata.SwiftWitnesses[profileformat.WitnessKey(10, 100)]).To(Equal(uint64(1100)))
Expect(v.metadata.SwiftWitnesses[profileformat.WitnessKey(10, 200)]).To(Equal(uint64(1200)))
for _, state := range []uint64{1, 0} {
v.set(1, 42)
v.observeMetadataCall("swift_getForeignTypeMetadata")
link, err := engine.RegRead(unicorn.RegLR)
Expect(err).NotTo(HaveOccurred())
Expect(link).To(Equal(bootReturn))
v.set(0, 900)
v.set(1, state)
v.observeMetadataReturn(bootReturn)
if state != 0 {
Expect(v.metadata.SwiftForeign).To(BeEmpty())
}
}
Expect(v.metadata.SwiftForeign).To(HaveKeyWithValue("42", uint64(900)))
})
})
var _ = Describe("Swift metadata allocation", func() {
DescribeTable("uses the size argument after alignment for zone allocations with options", func(name string) {
engine, err := unicorn.New(context.Background())
Expect(err).NotTo(HaveOccurred())
DeferCleanup(engine.Close)
v := &bootstrapVM{engine: engine, allocations: map[uint64]uint64{}, cursor: 16}
v.set(0, 0)
v.set(1, 4096)
v.set(2, 16384)
v.set(3, 2)
v.set(4, 2)
Expect(v.host(name)).To(BeTrue())
address := v.arg(0)
Expect(address % 4096).To(BeZero())
Expect(v.allocations[address]).To(Equal(uint64(16384)))
Expect(v.alloc(16)).To(BeNumerically(">=", address+16384))
}, Entry("typed", "malloc_type_zone_malloc_with_options"), Entry("untyped", "malloc_zone_malloc_with_options"))
})
+83
View File
@@ -0,0 +1,83 @@
package profilegen
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"go/format"
"strings"
"github.com/klauspost/compress/zstd"
)
// GoSource emits a complete precomputed profile as ordinary Go declarations.
// JSON map ordering, single-threaded compression, and fixed line wrapping keep
// the output independent of host paths, clocks, and map iteration order.
func (r *Result) GoSource(ctx context.Context, plugin []byte) ([]byte, error) {
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("encode Store profile: %w", err)
}
if r == nil || r.Profile == nil || r.Profile.UUID != FrameworkUUID || r.Profile.PluginUUID != PluginUUID {
return nil, fmt.Errorf("profile does not match pinned Apple images")
}
if len(r.Pages) == 0 || len(r.Pages)%4096 != 0 || len(r.Profile.Pages) != len(r.Pages)/4096 || len(plugin) == 0 {
return nil, fmt.Errorf("incomplete profile output")
}
for i, page := range r.Profile.Pages {
if page.Address%4096 != 0 || page.Offset != uint64(i)*4096 {
return nil, fmt.Errorf("invalid profile page index")
}
}
metadata, err := json.Marshal(r.Profile)
if err != nil {
return nil, fmt.Errorf("encode profile metadata: %w", err)
}
encoder, err := zstd.NewWriter(nil, zstd.WithEncoderLevel(zstd.SpeedBestCompression), zstd.WithEncoderConcurrency(1), zstd.WithEncoderCRC(true))
if err != nil {
return nil, fmt.Errorf("create profile encoder: %w", err)
}
defer encoder.Close()
var source strings.Builder
source.WriteString("// Code generated by go run ./internal/store/profilegen/cmd/profilegen; DO NOT EDIT.\n")
fmt.Fprintf(&source, "// Pinned inputs: %s\n\npackage profile\n\n", Version())
fmt.Fprintf(&source, "const generatedFrameworkUUID = %q\nconst generatedPluginUUID = %q\n\n", FrameworkUUID, PluginUUID)
for _, part := range []struct {
identifier, name string
data []byte
}{{"generatedMetadata", "Store metadata", metadata}, {"generatedPages", "Store pages", r.Pages}, {"generatedPlugin", "Store authentication plugin", plugin}} {
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("encode Store profile: %w", err)
}
encoded := base64.StdEncoding.EncodeToString(encoder.EncodeAll(part.data, nil))
fmt.Fprintf(&source, "var %s = artifact{\nName: %q,\nSize: %d,\nSHA256: %q,\nEncoded: `\n", part.identifier, part.name, len(part.data), digest(part.data))
for start := 0; start < len(encoded); start += 120 {
source.WriteString(encoded[start:min(start+120, len(encoded))])
source.WriteByte('\n')
}
source.WriteString("`,\n}\n\n")
}
result, err := format.Source([]byte(source.String()))
if err != nil {
return nil, fmt.Errorf("format generated profile: %w", err)
}
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("encode Store profile: %w", err)
}
return result, nil
}
+109
View File
@@ -0,0 +1,109 @@
package profilegen
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"go/ast"
"go/parser"
"go/token"
"strconv"
"github.com/klauspost/compress/zstd"
profileformat "github.com/majd/ipatool/v2/internal/store/profile/format"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func sourceFixture() *Result {
return &Result{Profile: &profileformat.Profile{UUID: FrameworkUUID, PluginUUID: PluginUUID, Pages: []profileformat.Page{{Address: 0x180000000}}}, Pages: make([]byte, 4096)}
}
// generatedPayloads reads actual Go declarations, so the test also checks that
// binary payloads are carried by valid source rather than external asset files.
func generatedPayloads(source []byte) map[string][]byte {
file, err := parser.ParseFile(token.NewFileSet(), "data_generated.go", source, 0)
Expect(err).NotTo(HaveOccurred())
Expect(file.Name.Name).To(Equal("profile"))
decoder, err := zstd.NewReader(nil)
Expect(err).NotTo(HaveOccurred())
defer decoder.Close()
result := map[string][]byte{}
for _, decl := range file.Decls {
group, ok := decl.(*ast.GenDecl)
if !ok || group.Tok != token.VAR {
continue
}
for _, spec := range group.Specs {
value := spec.(*ast.ValueSpec)
for _, element := range value.Values[0].(*ast.CompositeLit).Elts {
entry := element.(*ast.KeyValueExpr)
if entry.Key.(*ast.Ident).Name != "Encoded" {
continue
}
encoded, err := strconv.Unquote(entry.Value.(*ast.BasicLit).Value)
Expect(err).NotTo(HaveOccurred())
compressed, err := base64.StdEncoding.DecodeString(encoded)
Expect(err).NotTo(HaveOccurred())
data, err := decoder.DecodeAll(compressed, nil)
Expect(err).NotTo(HaveOccurred())
result[value.Names[0].Name] = data
}
}
}
return result
}
var _ = Describe("Generated Go profile source", func() {
It("is byte-identical across map insertion orders and round-trips every artifact", func() {
first, second := sourceFixture(), sourceFixture()
first.Profile.Symbols = map[string]uint64{}
first.Profile.Symbols["a"] = 1
first.Profile.Symbols["z"] = 2
second.Profile.Symbols = map[string]uint64{}
second.Profile.Symbols["z"] = 2
second.Profile.Symbols["a"] = 1
plugin := []byte{0, 0xff, '`', '"', '\\', '\n'}
a, err := first.GoSource(context.Background(), plugin)
Expect(err).NotTo(HaveOccurred())
b, err := second.GoSource(context.Background(), plugin)
Expect(err).NotTo(HaveOccurred())
Expect(b).To(Equal(a))
payloads := generatedPayloads(a)
metadata, err := json.Marshal(first.Profile)
Expect(err).NotTo(HaveOccurred())
Expect(payloads).To(Equal(map[string][]byte{"generatedMetadata": metadata, "generatedPages": first.Pages, "generatedPlugin": plugin}))
})
It("rejects incomplete output and inconsistent page offsets", func() {
input := sourceFixture()
_, err := input.GoSource(context.Background(), nil)
Expect(err).To(HaveOccurred())
input.Profile.Pages[0].Offset = 4096
_, err = input.GoSource(context.Background(), []byte("plugin"))
Expect(err).To(MatchError(ContainSubstring("page index")))
})
It("rejects images from a different binary version", func() {
input := sourceFixture()
input.Profile.UUID = "different"
_, err := input.GoSource(context.Background(), []byte("plugin"))
Expect(err).To(MatchError(ContainSubstring("pinned Apple images")))
})
It("honors cancellation before encoding", func() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := sourceFixture().GoSource(ctx, []byte("plugin"))
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
})
})
+40
View File
@@ -0,0 +1,40 @@
package profilegen
import (
"fmt"
"howett.net/plist"
)
func (s *source) features() (map[string]bool, error) {
result := map[string]bool{}
for _, domain := range []string{"AppleMediaServices", "CFNetwork", "Foundation"} {
b, err := s.cache.FeatureFlags(domain)
if err != nil {
return nil, fmt.Errorf("read Store feature defaults: %w", err)
}
var flags map[string]struct{ DevelopmentPhase string }
if _, err = plist.Unmarshal(b, &flags); err != nil {
return nil, fmt.Errorf("read Store feature defaults: %w", err)
}
for key, flag := range flags {
switch flag.DevelopmentPhase {
case "FeatureComplete":
result[domain+"/"+key] = true
default:
return nil, fmt.Errorf("unsupported feature phase %s for %s/%s", flag.DevelopmentPhase, domain, key)
}
}
}
// Absent flags are disabled, matching the public feature-query ABI.
for _, key := range []string{"UseNewNetworkStack", "AppendWithUnmodifiedParameters", "CompressPurchaseRequestBodies"} {
if _, ok := result["AppleMediaServices/"+key]; !ok {
result["AppleMediaServices/"+key] = false
}
}
return result, nil
}
+70
View File
@@ -0,0 +1,70 @@
package profilegen
import (
"context"
"crypto/sha256"
"fmt"
"github.com/majd/ipatool/v2/internal/sap/assets"
profileformat "github.com/majd/ipatool/v2/internal/store/profile/format"
)
// Result contains a self-contained metadata profile and its reconstructed pages.
// No native reference data is accepted during generation.
type Result struct {
Profile *profileformat.Profile
Pages []byte
}
// Generate executes the pinned Swift runtime under Unicorn and inspects the
// downloaded Mach-O metadata. The host never loads an Apple framework.
//
//nolint:nonamedreturns // Convert binary decoding panics to a contextual error.
func Generate(ctx context.Context, cache *assets.StoreCache) (result *Result, err error) {
defer func() {
if p := recover(); p != nil {
result = nil
err = fmt.Errorf("generate Store profile: %v", p)
}
}()
s, err := newSource(ctx, cache)
if err != nil {
return nil, fmt.Errorf("generate Store assets: %w", err)
}
defer s.close()
req, err := s.discoverSwiftRequests()
if err != nil {
return nil, fmt.Errorf("discover Swift metadata: %w", err)
}
classes := s.objcClasses()
v, err := newBootstrapVM(ctx, s)
if err != nil {
return nil, fmt.Errorf("generate Store assets: %w", err)
}
defer v.engine.Close()
if err = v.realizeStoreClasses(classes); err != nil {
return nil, fmt.Errorf("generate Store assets: %w", err)
}
p, err := v.swiftMetadata(req)
if err != nil {
return nil, fmt.Errorf("generate Store assets: %w", err)
}
p.Features, err = s.features()
if err != nil {
return nil, fmt.Errorf("generate Store assets: %w", err)
}
pages := v.collect(p, classes)
return &Result{Profile: p, Pages: pages}, nil
}
func digest(data []byte) string { return fmt.Sprintf("%x", sha256.Sum256(data)) }
+228
View File
@@ -0,0 +1,228 @@
package profilegen
import (
"fmt"
"sort"
"strconv"
"strings"
profileformat "github.com/majd/ipatool/v2/internal/store/profile/format"
)
func (s *source) objcClass(address uint64) *profileformat.Class {
if address == 0 {
return nil
}
if c := s.classes[address]; c != nil {
return c
}
data := s.u64(address+32) &^ 7
c := &profileformat.Class{Address: address, MetaAddress: s.u64(address), Ivars: map[string]uint64{}}
s.classes[address] = c
c.Name = className(s.cstring(s.u64(data + 24)))
c.Size = (uint64(s.u32(data+8)) + 7) &^ 7
if c.Name == "" {
panic(fmt.Sprintf("class at %#x has no name (ro %#x)", address, data))
}
if superclass := s.objcClass(s.u64(address + 8)); superclass != nil {
c.Super = superclass.Name
}
c.Methods = append(c.Methods, s.methods(s.u64(data+32), false)...)
metaData := s.u64(c.MetaAddress+32) &^ 7
c.Methods = append(c.Methods, s.methods(s.u64(metaData+32), true)...)
if list := s.u64(data + 48); list != 0 {
stride, count := s.u32(list), s.u32(list+4)
if stride < 32 || count > 1<<16 {
panic("invalid ivar list")
}
for i := uint32(0); i < count; i++ {
entry := list + 8 + uint64(i)*uint64(stride)
name := s.cstring(s.u64(entry + 8))
offset := s.u64(entry)
if offset != 0 {
c.Ivars[name] = uint64(s.u32(offset))
}
}
}
return c
}
func (s *source) methods(list uint64, meta bool) []profileformat.Method {
if list == 0 {
return nil
}
if list&1 != 0 {
list &^= 1
count := s.u32(list + 4)
if count > 1<<16 {
panic("invalid attached method lists")
}
var result []profileformat.Method
for i := uint32(0); i < count; i++ {
entry := list + 8 + uint64(i)*8
offset := int64(s.u64(entry)) >> 16
result = append(result, s.methods(uint64(int64(entry)+offset), meta)...)
}
return result
}
flags, count := s.u32(list), s.u32(list+4)
if count == 0 {
return nil
}
stride := uint64(flags & 0xfffc)
if stride < 12 || count > 1<<18 {
panic(fmt.Sprintf("invalid method list %#x (%x,%d)", list, flags, count))
}
var result []profileformat.Method
for i := uint32(0); i < count; i++ {
entry := list + 8 + uint64(i)*stride
var sel, types, imp uint64
if flags&0x80000000 != 0 {
if flags&0x40000000 != 0 {
sel = s.selectorBase + uint64(s.u32(entry))
} else {
sel = s.u64(uint64(int64(entry) + int64(int32(s.u32(entry)))))
}
if flags&0x20000000 != 0 {
types = s.selectorBase + uint64(s.u32(entry+4))
} else {
types = uint64(int64(entry+4) + int64(int32(s.u32(entry+4))))
}
imp = uint64(int64(entry+8) + int64(int32(s.u32(entry+8))))
} else {
sel = s.u64(entry)
types = s.u64(entry + 8)
imp = s.u64(entry + 16)
}
if inside(imp, s.target) {
result = append(result, profileformat.Method{Selector: s.cstring(sel), Types: s.cstring(types), Address: imp, ClassMethod: meta})
}
}
return result
}
func (s *source) objcClasses() []profileformat.Class {
for _, name := range s.imageNames() {
f := s.images[name]
for _, sec := range f.Sections {
if sec.Name == "__objc_classlist" {
for off := uint64(0); off < sec.Size; off += 8 {
s.objcClass(s.u64(sec.Addr + off))
}
}
}
}
// Categories can install Store methods on Foundation classes.
for _, name := range []string{amsImage, authImage} {
for _, sec := range s.images[name].Sections {
if sec.Name == "__objc_catlist" {
for off := uint64(0); off < sec.Size; off += 8 {
cat := s.u64(sec.Addr + off)
class := s.objcClass(s.u64(cat + 8))
if class == nil {
panic("unresolved category class")
}
class.Methods = append(class.Methods, s.methods(s.u64(cat+16), false)...)
class.Methods = append(class.Methods, s.methods(s.u64(cat+24), true)...)
}
}
}
}
classes := make([]profileformat.Class, 0, len(s.classes))
for _, c := range s.classes {
seen := map[string]bool{}
methods := c.Methods[:0]
for _, m := range c.Methods {
key := strconv.FormatBool(m.ClassMethod) + m.Selector
if !seen[key] {
seen[key] = true
methods = append(methods, m)
}
}
c.Methods = methods
sort.Slice(c.Methods, func(i, j int) bool {
a, b := c.Methods[i], c.Methods[j]
if a.ClassMethod != b.ClassMethod {
return !a.ClassMethod
}
return a.Selector < b.Selector
})
classes = append(classes, *c)
}
sort.Slice(classes, func(i, j int) bool { return classes[i].Name < classes[j].Name })
return classes
}
// The ObjC runtime exposes public Swift class names in qualified form. Private
// and generic encodings remain mangled; their dynamic metadata is handled later.
func className(name string) string {
if !strings.HasPrefix(name, "_TtC") {
return name
}
value := strings.TrimPrefix(name, "_TtC")
var parts []string
if strings.HasPrefix(value, "s") {
parts = append(parts, "Swift")
value = value[1:]
}
for value != "" {
i := 0
for i < len(value) && value[i] >= '0' && value[i] <= '9' {
i++
}
if i == 0 {
return name
}
n, e := strconv.Atoi(value[:i])
if e != nil || n > len(value)-i {
return name
}
parts = append(parts, value[i:i+n])
value = value[i+n:]
}
if len(parts) < 2 {
return name
}
return strings.Join(parts, ".")
}
@@ -0,0 +1,85 @@
package profilegen
import (
"context"
"testing"
"github.com/majd/ipatool/v2/internal/sap/unicorn"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestProfileGeneration(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Store Profile Generation Suite")
}
var _ = Describe("Bootstrap binary decoding", func() {
It("decodes negative ADRP page displacements", func() { Expect(adrp(0xf0ffffe0, 0x2001234)).To(Equal(uint64(0x2000000))) })
It("preserves ordinary instructions and lowers RCpc loads", func() {
Expect(bootstrapInstruction(0xf8bfc115)).To(Equal(uint32(0xf9400115)))
Expect(bootstrapInstruction(0xd503201f)).To(Equal(uint32(0xd503201f)))
})
It("rejects overflowing guest heap allocations", func() {
v := &bootstrapVM{allocations: map[uint64]uint64{}}
Expect(func() { v.alloc(^uint64(0)) }).To(Panic())
v.cursor = bootHeapSize + 1
Expect(func() { v.alloc(16) }).To(Panic())
})
It("looks up sorted noncontiguous image ranges", func() {
ranges := [][2]uint64{{8, 16}, {24, 40}}
Expect(inside(7, ranges)).To(BeFalse())
Expect(inside(8, ranges)).To(BeTrue())
Expect(inside(16, ranges)).To(BeFalse())
Expect(inside(39, ranges)).To(BeTrue())
Expect(inside(40, ranges)).To(BeFalse())
})
})
var _ = Describe("Single-threaded bootstrap atomics", func() {
var v *bootstrapVM
BeforeEach(func() {
engine, err := unicorn.New(context.Background())
Expect(err).NotTo(HaveOccurred())
DeferCleanup(engine.Close)
Expect(engine.MemMap(bootHeap, 4096)).To(Succeed())
v = &bootstrapVM{engine: engine}
})
It("performs compare-and-swap with the observed value on failure", func() {
v.put(bootHeap, 41)
v.setReg(3, bootHeap)
v.setReg(1, 41)
v.setReg(2, 99)
v.atomic(0xc8e1fc62) // casal x1, x2, [x3]
Expect(v.u64(bootHeap)).To(Equal(uint64(99)))
Expect(v.reg(1)).To(Equal(uint64(41)))
v.setReg(1, 42)
v.setReg(2, 100)
v.atomic(0xc8e1fc62)
Expect(v.u64(bootHeap)).To(Equal(uint64(99)))
Expect(v.reg(1)).To(Equal(uint64(99)))
})
It("updates both words of an ARM64 CASP atomically", func() {
v.put(bootHeap, 11)
v.put(bootHeap+8, 12)
v.setReg(4, bootHeap)
v.setReg(0, 11)
v.setReg(1, 12)
v.setReg(2, 21)
v.setReg(3, 22)
v.atomic(0x4860fc82) // caspal x0, x1, x2, x3, [x4]
Expect(v.u64(bootHeap)).To(Equal(uint64(21)))
Expect(v.u64(bootHeap + 8)).To(Equal(uint64(22)))
Expect(v.reg(0)).To(Equal(uint64(11)))
Expect(v.reg(1)).To(Equal(uint64(12)))
})
It("wraps a 32-bit atomic add without overwriting adjacent memory", func() {
v.put(bootHeap, 0xabcdef01ffffffff)
v.setReg(19, bootHeap)
v.setReg(8, 2)
v.atomic(0xb8a80268) // ldadda w8, w8, [x19]
Expect(v.u64(bootHeap)).To(Equal(uint64(0xabcdef0100000001)))
Expect(v.reg(8)).To(Equal(uint64(0xffffffff)))
})
})
+64
View File
@@ -0,0 +1,64 @@
package profilegen
import (
"encoding/binary"
"fmt"
profileformat "github.com/majd/ipatool/v2/internal/store/profile/format"
)
func (v *bootstrapVM) realizeStoreClasses(classes []profileformat.Class) error {
for i := range classes {
c := &classes[i]
if len(c.Methods) == 0 || v.u64(c.Address+32)&2 == 0 {
continue
}
descriptor := v.u64(c.Address + 64)
if descriptor == 0 {
continue
}
flags := binary.LittleEndian.Uint32(v.read(descriptor, 4))
if flags&0x80 != 0 {
continue
}
relative := int32(binary.LittleEndian.Uint32(v.read(descriptor+12, 4)))
if relative == 0 {
continue
}
accessor := uint64(int64(descriptor+12) + int64(relative))
address, state, err := v.callAddress(accessor, 0)
if err != nil {
return fmt.Errorf("realize %s: %w", c.Name, err)
}
if address != c.Address || state != 0 {
return fmt.Errorf("unexpected class metadata for %s: %#x state %d", c.Name, address, state)
}
c.Size = max(c.Size, (uint64(binary.LittleEndian.Uint32(v.read(c.Address+48, 4)))+7)&^7)
ro := v.u64(c.Address+32) &^ 7
list := v.u64(ro + 48)
if list != 0 {
count := binary.LittleEndian.Uint32(v.read(list+4, 4))
stride := binary.LittleEndian.Uint32(v.read(list, 4))
for j := uint32(0); j < count; j++ {
entry := list + 8 + uint64(j)*uint64(stride)
name := v.string(v.u64(entry + 8))
offset := v.u64(entry)
if offset != 0 {
c.Ivars[name] = uint64(binary.LittleEndian.Uint32(v.read(offset, 4)))
}
}
}
}
return nil
}
+164
View File
@@ -0,0 +1,164 @@
package profilegen
import "encoding/binary"
// pageReference tracks an ADRP-derived address within a basic block. Unresolved
// uses retain the old conservative window; understood address arithmetic and
// memory operands retain only the pages they actually address.
type pageReference struct {
address uint64
valid bool
resolved bool
}
// dataReferences decodes immediate ARM64 address construction without executing
// a particular operation. Every basic block in both Store images is scanned, so
// collection also covers server-dependent branches not taken by our tests.
func dataReferences(code []byte, pc uint64, add func(uint64)) {
var registers [32]pageReference
forget := func(register uint32) {
ref := registers[register]
if ref.valid && !ref.resolved {
for offset := uint64(0); offset < 16*4096; offset += 4096 {
add(ref.address + offset)
}
}
registers[register] = pageReference{}
}
uncertain := func(register uint32) {
// An earlier understood access does not prove that a surviving
// address won't be indexed differently in another basic block.
registers[register].resolved = false
forget(register)
}
flush := func() {
for register := range registers {
uncertain(uint32(register))
}
}
access := func(register uint32, offset int64, size uint64) {
ref := &registers[register]
if ref.valid {
address := uint64(int64(ref.address) + offset)
add(address)
add(address + size - 1)
ref.resolved = true
}
}
for off := 0; off+4 <= len(code); off += 4 {
word := binary.LittleEndian.Uint32(code[off:])
rd, rn := word&31, word>>5&31
switch {
case word&0x9f000000 == 0x90000000: // ADRP
forget(rd)
address := adrp(word, pc+uint64(off))
add(address)
registers[rd] = pageReference{address: address, valid: rd != 31}
case word&0x9f000000 == 0x10000000: // ADR (signed, byte-relative)
forget(rd)
imm := int64(word>>5&0x7ffff)<<2 | int64(word>>29&3)
if imm&(1<<20) != 0 {
imm -= 1 << 21
}
address := uint64(int64(pc) + int64(off) + imm)
add(address)
registers[rd] = pageReference{address: address, valid: rd != 31, resolved: true}
case word&0x9f000000 == 0x91000000: // 64-bit ADD/SUB immediate
ref := registers[rn]
if ref.valid {
imm := int64(word >> 10 & 0xfff)
if word&(1<<22) != 0 {
imm <<= 12
}
if word&(1<<30) != 0 {
imm = -imm
}
access(rn, imm, 1)
ref.address = uint64(int64(ref.address) + imm)
ref.resolved = true
}
forget(rd)
registers[rd] = ref
case word&0x3b000000 == 0x39000000: // unsigned-immediate LDR/STR (including SIMD)
scale := word >> 30
if word&(1<<26) != 0 && word&(1<<23) != 0 {
scale = 4
}
access(rn, int64(word>>10&0xfff)<<scale, 1<<scale)
if word&(1<<26) == 0 && word&0x00c00000 != 0 {
forget(rd)
}
case word&0x3b200000 == 0x38000000: // unscaled/pre/post-indexed load/store
imm := int64(int32(word<<11) >> 23)
mode := word >> 10 & 3
if mode == 1 { // post-index uses the original address
access(rn, 0, 16)
} else {
access(rn, imm, 16)
}
if (mode == 1 || mode == 3) && registers[rn].valid {
registers[rn].address = uint64(int64(registers[rn].address) + imm)
}
if word&(1<<26) == 0 && word&0x00c00000 != 0 {
forget(rd)
}
case word&0x3a000000 == 0x28000000: // load/store pair
scale := uint32(2) + word>>31
if word&(1<<26) != 0 {
scale = 2 + word>>30
}
imm := int64(int32(word<<10)>>25) << scale
mode := word >> 23 & 3
if mode == 1 {
access(rn, 0, 2<<scale)
} else {
access(rn, imm, 2<<scale)
}
if (mode == 1 || mode == 3) && registers[rn].valid {
registers[rn].address = uint64(int64(registers[rn].address) + imm)
}
if word&(1<<26) == 0 && word&(1<<22) != 0 {
forget(rd)
forget(word >> 10 & 31)
}
case word&0x1f800000 == 0x12800000: // MOVN/MOVZ/MOVK immediate
forget(rd)
case word == 0xd503201f: // NOP
case word&0x1c000000 == 0x14000000: // branch, exception, or system instruction
flush()
default:
// Preserve independent registers across intervening instructions.
// Potential operands of an unknown instruction fall back instead
// of propagating an address through unrecognized arithmetic.
uncertain(rn)
uncertain(word >> 16 & 31)
forget(rd)
}
}
for register := range registers {
forget(uint32(register))
}
}
@@ -0,0 +1,64 @@
package profilegen
import (
"encoding/binary"
"sort"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
// referencePages collects page addresses from synthetic instructions so boundary
// and fallback behavior is checked independently of the pinned framework build.
func referencePages(words ...uint32) []uint64 {
code := make([]byte, len(words)*4)
for i, word := range words {
binary.LittleEndian.PutUint32(code[i*4:], word)
}
pages := map[uint64]bool{}
dataReferences(code, 0x100000, func(address uint64) { pages[address&^4095] = true })
result := make([]uint64, 0, len(pages))
for page := range pages {
result = append(result, page)
}
sort.Slice(result, func(i, j int) bool { return result[i] < result[j] })
return result
}
var _ = Describe("Store data references", func() {
It("retains the addressed page for an ADRP and ADD pair", func() {
Expect(referencePages(0x90000000, 0x91040000)).To(Equal([]uint64{0x100000})) // add x0, x0, #256
})
It("tracks addresses across independent instructions", func() {
Expect(referencePages(0x90000000, 0xd2800021, 0xd503201f, 0x91040000)).To(Equal([]uint64{0x100000})) // mov x1, #1; nop; add x0, x0, #256
})
It("includes scaled load offsets beyond the ADRP page", func() {
Expect(referencePages(0x90000000, 0xf95ffc00)).To(Equal([]uint64{0x100000, 0x103000})) // ldr x0, [x0, #16376]
})
It("includes shifted immediate address arithmetic", func() {
Expect(referencePages(0x90000000, 0x91400800)).To(Equal([]uint64{0x100000, 0x102000})) // add x0, x0, #2, lsl #12
})
It("includes both pages of an unaligned load", func() {
Expect(referencePages(0x90000000, 0x913ff000, 0xf9400000)).To(Equal([]uint64{0x100000, 0x101000})) // add x0, x0, #4092; ldr x0, [x0]
})
It("sign extends unscaled negative load offsets", func() {
Expect(referencePages(0x90000000, 0xf85f8000)).To(Equal([]uint64{0xff000, 0x100000})) // ldur x0, [x0, #-8]
})
It("retains the full conservative range for an unknown consumer", func() {
pages := referencePages(0x90000000, 0x8b010000)
Expect(pages).To(HaveLen(16))
Expect(pages[0]).To(Equal(uint64(0x100000)))
Expect(pages[15]).To(Equal(uint64(0x10f000)))
})
It("keeps a conservative range for addresses still live at a branch after a known access", func() {
Expect(referencePages(0x90000000, 0xf9400001, 0x14000001)).To(HaveLen(16)) // ldr x1, [x0]; b next
})
It("does not propagate register values across branches", func() {
Expect(referencePages(0x90000000, 0x14000001, 0xf97ffc00)).To(HaveLen(16))
})
})
+239
View File
@@ -0,0 +1,239 @@
// Package profilegen bootstraps Store metadata from pinned, on-disk Apple images.
package profilegen
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"sort"
"strings"
"github.com/blacktop/go-macho"
"github.com/majd/ipatool/v2/internal/sap/assets"
profileformat "github.com/majd/ipatool/v2/internal/store/profile/format"
)
const amsImage = "/System/Library/PrivateFrameworks/AppleMediaServices.framework/Versions/A/AppleMediaServices"
const authImage = "/System/Library/Accounts/Authentication/AMSAccountAuthenticationPlugin.bundle/Contents/MacOS/AMSAccountAuthenticationPlugin"
type source struct {
ctx context.Context
cache *assets.StoreCache
pages map[uint64][]byte
images map[string]*macho.File
exports map[string]uint64
symbols map[uint64]string
symbolsLoaded map[string]bool
code [][2]uint64
target [][2]uint64
selectorBase uint64
classes map[uint64]*profileformat.Class
}
func newSource(ctx context.Context, cache *assets.StoreCache) (*source, error) {
s := &source{ctx: ctx, cache: cache, pages: map[uint64][]byte{}, images: map[string]*macho.File{}, exports: map[string]uint64{}, symbols: map[uint64]string{}, symbolsLoaded: map[string]bool{}, classes: map[uint64]*profileformat.Class{}}
if e := s.loadImage(amsImage); e != nil {
s.close()
return nil, fmt.Errorf("load bootstrap metadata: %w", e)
}
if e := s.loadImage(authImage); e != nil {
s.close()
return nil, fmt.Errorf("load bootstrap metadata: %w", e)
}
if s.images[amsImage].UUID().String() != FrameworkUUID || s.images[authImage].UUID().String() != PluginUUID {
s.close()
return nil, fmt.Errorf("store images do not match pinned macOS 26A434")
}
objc := s.images["/usr/lib/libobjc.A.dylib"]
if objc == nil {
return nil, fmt.Errorf("libobjc is not a Store dependency")
}
for _, sec := range objc.Sections {
if sec.Name == "__objc_opt_ro" {
s.selectorBase = sec.Addr + s.u64(sec.Addr+40)
}
}
sort.Slice(s.code, func(i, j int) bool { return s.code[i][0] < s.code[j][0] })
sort.Slice(s.target, func(i, j int) bool { return s.target[i][0] < s.target[j][0] })
return s, nil
}
func (s *source) close() {
for _, f := range s.images {
_ = f.Close()
}
}
func (s *source) loadImage(name string) error {
if _, ok := s.images[name]; ok {
return nil
}
if e := s.ctx.Err(); e != nil {
return fmt.Errorf("load bootstrap metadata: %w", e)
}
f, e := s.cache.OpenImage(name)
if e != nil {
return fmt.Errorf("load %s: %w", name, e)
}
s.images[name] = f
exports, e := f.DyldExports()
if e != nil && f.DyldExportsTrie() != nil {
return fmt.Errorf("load bootstrap metadata: %w", e)
}
for _, v := range exports {
if v.Address != 0 && !v.Flags.ReExport() {
s.exports[v.Name] = v.Address
s.symbols[v.Address] = strings.TrimPrefix(v.Name, "_")
}
}
for _, sec := range f.Sections {
if sec.Flags.IsPureInstructions() || sec.Flags.IsSomeInstructions() {
s.code = append(s.code, [2]uint64{sec.Addr, sec.Addr + sec.Size})
}
}
if name == amsImage || name == authImage {
for _, seg := range f.Segments() {
if seg.Name != "__LINKEDIT" {
s.target = append(s.target, [2]uint64{seg.Addr, seg.Addr + seg.Memsz})
}
}
}
weak := map[string]bool{}
delayed := map[string]bool{}
for _, load := range f.Loads {
switch d := load.(type) {
case *macho.WeakDylib:
weak[d.Name] = true
case *macho.LoadDylib:
if uint32(d.Flags)&8 != 0 {
delayed[d.Name] = true
}
if uint32(d.Flags)&1 != 0 {
weak[d.Name] = true
}
}
}
for _, dep := range f.ImportedLibraries() {
if delayed[dep] {
continue
}
if weak[dep] {
images, err := s.cache.Images()
if err != nil {
return fmt.Errorf("load bootstrap metadata: %w", err)
}
if _, ok := images[dep]; !ok {
continue
}
}
if e = s.loadImage(dep); e != nil {
return fmt.Errorf("dependency of %s: %w", name, e)
}
}
return nil
}
func (s *source) read(address, size uint64) []byte {
if size > 64<<20 {
panic("bootstrap read exceeds size limit")
}
data := make([]byte, size)
for offset := uint64(0); offset < size; {
addr := address + offset
base := addr &^ 4095
p, ok := s.pages[base]
if !ok {
var e error
p, e = s.cache.Page(base)
if e != nil {
panic(e)
}
s.pages[base] = p
}
n := min(size-offset, 4096-(addr&4095))
copy(data[offset:offset+n], p[addr&4095:(addr&4095)+n])
offset += n
}
return data
}
func (s *source) u64(a uint64) uint64 { return binary.LittleEndian.Uint64(s.read(a, 8)) }
func (s *source) u32(a uint64) uint32 { return binary.LittleEndian.Uint32(s.read(a, 4)) }
func (s *source) cstring(a uint64) string {
if a == 0 {
return ""
}
var out []byte
for len(out) < 1<<20 {
n := uint64(4096) - (a & 4095)
p := s.read(a, n)
if i := bytes.IndexByte(p, 0); i >= 0 {
return string(append(out, p[:i]...))
}
out = append(out, p...)
a += n
}
panic("unterminated bootstrap string")
}
func inside(a uint64, regions [][2]uint64) bool {
i := sort.Search(len(regions), func(i int) bool { return regions[i][0] > a }) - 1
return i >= 0 && a < regions[i][1]
}
func (s *source) imageNames() []string {
names := make([]string, 0, len(s.images))
for name := range s.images {
names = append(names, name)
}
sort.Strings(names)
return names
}
func (s *source) describe(a uint64) string {
var best uint64
var name string
for address, n := range s.symbols {
if address <= a && address > best {
best = address
name = n
}
}
return fmt.Sprintf("%s+%#x", name, a-best)
}
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff. Show more