From a837becbf4b24b26b2d175e0dcdcbd64513f074f Mon Sep 17 00:00:00 2001 From: Henrik Klee Date: Fri, 4 Dec 2026 15:41:51 +0800 Subject: [PATCH] Add the Amethyst route: storage access without DFU on iOS 12.2 to 13.7 The route without DFU so far needs Dopamine, iOS 15 and later. iOS 12 and 13 devices could make room only through checkra1n, whose Linux build leaves out A7 (iPhone 5s, iPad Air, iPad mini 2 and 3) and whose iOS boot panics on the iPad mini 2 and 3 (orchard#401). Amethyst is the same kind of app for iOS 12.0 to 13.7 on every device (OrchardLinux/tools#115). The app is the official Amethyst 1.1 release with Resize APFS in it, installed with the user's Apple ID through xtool (Xcode builds nothing for iOS 12 and 13). Amethyst's released executable is stripped, so its jailbreak functions have no names to call: scripts/build-amethyst.sh compiles the same tag's source, unchanged, with clang for iOS 12.0, and embed.py puts that executable in place of the official one, refusing a stripped one. Every other file is the official release's. Access/AmethystBridge.m is the Amethyst counterpart of AccessBridge.m. It hides Amethyst's window, answers its first-run question (no Sileo, no Zebra), installs the helper from Amethyst's "fade" notification right before the userspace reboot that ends its run, and restarts the whole device on the first run, when Amethyst sets the system snapshot aside as orig-fs. The storage access page then says "Your iPad restarts once. Open Resize APFS again when it's back." (iPhone on an iPhone). Amethyst is rootful, so the helper and daemon go under / instead of /var/jb; StorageAccess learns that from two optional bridge methods, so other apps' bridges keep working. iOS 12.0 and 12.1 are left out: the library needs the Swift runtime iOS has from 12.2 on, and Amethyst's executable brings none. Not run on a device yet. Assisted-by: LLM --- Access/AmethystBridge.m | 174 ++++++++++++++++++++ Access/AmethystInterface.h | 41 +++++ Access/StorageAccess.swift | 50 +++++- App/Pages.swift | 8 +- Device/README.md | 35 ++++ README.md | 23 +++ THIRD_PARTY_NOTICES.md | 28 ++++ Tests/ReleaseTests/access_fixtures.py | 29 ++++ Tests/ReleaseTests/test_amethyst_route.py | 180 +++++++++++++++++++++ Tests/ReleaseTests/test_checkra1n_route.py | 2 +- docs/updating-amethyst.md | 22 +++ scripts/amethyst_route.py | 43 +++++ scripts/build-amethyst.sh | 49 ++++++ scripts/build-device-ios12.sh | 32 +++- scripts/embed.py | 56 +++++-- scripts/launcher.py | 28 +++- scripts/package_release.py | 2 +- scripts/sideload.py | 43 +++-- scripts/tools.py | 24 ++- 19 files changed, 818 insertions(+), 51 deletions(-) create mode 100644 Access/AmethystBridge.m create mode 100644 Access/AmethystInterface.h create mode 100644 Tests/ReleaseTests/test_amethyst_route.py create mode 100644 docs/updating-amethyst.md create mode 100644 scripts/amethyst_route.py create mode 100755 scripts/build-amethyst.sh diff --git a/Access/AmethystBridge.m b/Access/AmethystBridge.m new file mode 100644 index 0000000..6d36e50 --- /dev/null +++ b/Access/AmethystBridge.m @@ -0,0 +1,174 @@ +// Resize APFS inside the Amethyst app, for iOS 12 and 13 (scripts/embed.py adds this library to +// its executable). The counterpart of Access/AccessBridge.m for Dopamine, with the same class +// for Access/StorageAccess.swift: it reaches Amethyst only through what AmethystInterface.h lists. +// +// Amethyst's app delegate always makes its own window. This library hides it once the app has +// launched and puts up the Resize APFS window instead; Amethyst's screen stays loaded behind, +// because its jailbreak asks its first-run question there (answered here, see `obtain`). +#import +#import +#import +#import +#import "AmethystInterface.h" + +@interface RAFAccessBridge : NSObject +@end + +// libSystem's, as Amethyst's own screen calls it; the iOS SDK has no header for it. +extern int reboot(int howto); + +static void *amethystSymbol(const char *name) { + return dlsym(RTLD_MAIN_ONLY, name); +} + +/// One of Amethyst's two global objects (`amethyst`, `mainController`), or nil. +static id amethystObject(const char *name) { + void **global = amethystSymbol(name); + return global ? (__bridge id)*global : nil; +} + +static NSString *errorName(int error) { + NSArray *names = @[@"success", @"exploit", @"permission", @"patchfinder", @"trustcache", @"PPL", @"remount", + @"restore", @"OTA", @"remount (restart needed)", @"restore (restart needed)", @"handoff", @"dyld", + @"bootstrap", @"Sileo", @"Zebra", @"libswift", @"unsupported install"]; + return error >= 0 && error < (int)names.count ? names[error] : @"unknown"; +} + +@implementation RAFAccessBridge { + BOOL _elevated; + uid_t _user; + gid_t _group; +} + +/// Storage access is there: the helper can be started and reached. +- (BOOL)isReady { + AmethystHeartbeat heartbeat = amethystSymbol("jbserver_heartbeat"); + return heartbeat && heartbeat() == 0x1337; +} + +/// Amethyst needs no screen restart before it runs. +- (BOOL)needsScreenRestart { + return NO; +} + +- (void)restartScreen { +} + +/// The device restarts once during the first run: iOS still runs from its system snapshot, +/// which Amethyst sets aside as orig-fs (its remount_rootfs). A root mounted from a snapshot +/// names it in front of the device ("com.apple.os.update-…@/dev/disk0s1s1"). +- (BOOL)needsDeviceRestart { + struct statfs root; + return statfs("/", &root) == 0 && strchr(root.f_mntfromname, '@') != NULL; +} + +/// Amethyst's files live in the root of the system, not under /var/jb. +- (NSString *)jailbreakRoot { + return @""; +} + +/// Obtains access. `prepare` runs as root right before the screen restart that ends a +/// successful run, which the app does not survive; nil is returned only if Amethyst returns +/// after success all the same. On a device's first run the device restarts instead (see +/// needsDeviceRestart). Blocks for the whole run; call it off the main thread. +- (NSString *)obtain:(void (^)(void))prepare { + AmethystRunJailbreak run = amethystSymbol("run_jailbreak"); + id config = amethystObject("amethyst"); + id controller = amethystObject("mainController"); + if (!run || !config || !controller) return @"This copy of the app lacks its access component."; + NSInteger exploit = [[config valueForKey:@"exploit"] integerValue]; + uint32_t flags = exploit == 1 ? AMETHYST_FLAG_EXPLOIT_TRIGON : AMETHYST_FLAG_EXPLOIT_HEMLOCK; + char *generator = strdup([[config valueForKey:@"generator"] UTF8String] ?: "0x1111111111111111"); + + // The first run asks whether to install Sileo and Zebra, on Amethyst's hidden screen, and + // waits for the answer: no to both, and the question closed as soon as it opens. + id question = [controller valueForKey:@"installAlert"]; + dispatch_sync(dispatch_get_main_queue(), ^{ + for (NSString *option in @[@"installSileo", @"installZebra"]) { + id control = [question valueForKey:option]; + if ([control respondsToSelector:@selector(setSwitchValue:)]) { + ((void (*)(id, SEL, BOOL))[control methodForSelector:@selector(setSwitchValue:)])(control, @selector(setSwitchValue:), NO); + } + } + }); + dispatch_source_t answer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); + dispatch_source_set_timer(answer, DISPATCH_TIME_NOW, 200 * NSEC_PER_MSEC, 50 * NSEC_PER_MSEC); + dispatch_source_set_event_handler(answer, ^{ + if ([question respondsToSelector:@selector(isOpen)] && ((BOOL (*)(id, SEL))[question methodForSelector:@selector(isOpen)])(question, @selector(isOpen))) { + NSLog(@"Resize APFS: answering Amethyst's first-run question (no Sileo, no Zebra)"); + [question performSelector:@selector(closeAlert)]; + } + }); + dispatch_resume(answer); + + __block BOOL prepared = NO; + id observer = [NSNotificationCenter.defaultCenter addObserverForName:AMETHYST_FADE object:nil queue:nil usingBlock:^(NSNotification *note) { + if (prepared) return; + prepared = YES; + NSLog(@"Resize APFS: access obtained, uid %d; preparing before the screen restart", geteuid()); + prepare(); + }]; + int error = run(flags, generator); + [NSNotificationCenter.defaultCenter removeObserver:observer]; + dispatch_source_cancel(answer); + free(generator); + + if (error == AMETHYST_ERROR_REMOUNT_REBOOT) { + // As Amethyst's own screen does after this answer: restart the whole device. The + // process still has the jailbreak's root here. + NSLog(@"Resize APFS: the system snapshot was set aside; restarting the device"); + sync(); + reboot(0); + return @"The device must restart now: restart it, then open Resize APFS again."; + } + if (error != AMETHYST_ERROR_SUCCESS) return [NSString stringWithFormat:@"Amethyst stopped at step %@ (error %d).", errorName(error), error]; + return prepared ? nil : @"Amethyst finished without the moment to put the helper in place."; +} + +/// Restarts the screen; the app ends with it. +- (void)finish { + AmethystPostJailbreak post = amethystSymbol("jbserver_post_jailbreak"); + AmethystRunUtility utility = amethystSymbol("run_jbutil"); + if (!post || !utility) return; + post(false, true); + utility("--userspace-reboot", NULL, true); +} + +/// Runs `block` as root and outside the app sandbox, when access is there. Amethyst makes the +/// whole process root for good; between blocks it acts as the app's own user again. +- (void)privileged:(void (^)(void))block { + if (!_elevated) { + AmethystPostJailbreak post = amethystSymbol("jbserver_post_jailbreak"); + if (!post) return; + uid_t user = getuid(); + gid_t group = getgid(); + post(true, true); + if (getuid() != 0) return; + _elevated = YES; + _user = user; + _group = group; + } + seteuid(0); + setegid(0); + block(); + setegid(_group); + seteuid(_user); +} + +@end + +__attribute__((constructor)) static void RAFAccessLoad(void) { + [NSNotificationCenter.defaultCenter addObserverForName:UIApplicationDidFinishLaunchingNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) { + // Amethyst's window, made by its app delegate before this notification. + id delegate = UIApplication.sharedApplication.delegate; + if ([delegate respondsToSelector:@selector(window)]) delegate.window.hidden = YES; + Class app = NSClassFromString(@"RAFEmbeddedApp"); + SEL start = NSSelectorFromString(@"startWithBridge:"); + if ([app respondsToSelector:start]) { + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Warc-performSelector-leaks" + [app performSelector:start withObject:[RAFAccessBridge new]]; + #pragma clang diagnostic pop + } + }]; +} diff --git a/Access/AmethystInterface.h b/Access/AmethystInterface.h new file mode 100644 index 0000000..5a90cad --- /dev/null +++ b/Access/AmethystInterface.h @@ -0,0 +1,41 @@ +// Everything Resize APFS uses from the Amethyst app it is loaded into (Amethyst 1.1, iOS 12 and +// 13): five functions and two objects of its own, declared as its source declares them +// (Amethyst/Amethyst/jailbreak/jailbreak.h, jailbreak/handoff.c, ui/MainController.m, +// AppDelegate.h and ui/Utilities.h). Nothing else of Amethyst is called. +// +// Amethyst's released executable is stripped, so these functions cannot be found in it. The +// release build compiles Amethyst's own source at the pinned tag, unchanged and unstripped +// (scripts/build-amethyst.sh); the functions are then looked up by name at run time, so this file +// needs no Amethyst source. scripts/embed.py refuses an executable that lacks one of the names +// (AMETHYST_INTERFACE there lists the same ones). +#import + +// jailbreak/jailbreak.h. Runs the whole jailbreak and, when it succeeds, ends with a restart of +// the screen (a userspace reboot) that the app does not survive: it returns only on failure, or +// with JB_ERROR_REMOUNT_REBOOT on a device's first run, after it has set iOS's system snapshot +// aside as orig-fs and before the device restarts. Blocks; any thread but main. +typedef int (*AmethystRunJailbreak)(uint32_t flags, char *generator); +#define AMETHYST_FLAG_EXPLOIT_HEMLOCK 0x1 +#define AMETHYST_FLAG_EXPLOIT_TRIGON 0x2 +#define AMETHYST_ERROR_SUCCESS 0 +#define AMETHYST_ERROR_REMOUNT_REBOOT 9 + +// jailbreak/handoff.c. 0x1337 once the device is jailbroken (Amethyst's server answers). +typedef int (*AmethystHeartbeat)(void); +// jailbreak/handoff.c. Makes this process a platform process, outside the sandbox +// (`unsandbox`) and root (`root`), for the rest of its life. +typedef void (*AmethystPostJailbreak)(bool root, bool unsandbox); +// ui/MainController.m. Runs Amethyst's helper program; "--userspace-reboot" restarts the screen. +typedef int (*AmethystRunUtility)(char *command, char *argument, bool wait); + +// The notification Amethyst's jailbreak posts, on the jailbreak's own thread, right before the +// screen restart that ends a successful run (ui/MainController.m, FadeDisplay). The process +// still has the jailbreak's root then. +#define AMETHYST_FADE @"fade" + +// AppDelegate.h: the global `amethyst` (AmethystConfig *), its settings as Amethyst's app keeps +// them: `exploit` (0 Hemlock, 1 Trigon; set for the chip at its first launch) and `generator`. +// ui/MainController.m: the global `mainController`; its `installAlert` (ui/Utilities.h, +// InstallAlert) is the question Amethyst asks on a device's first run, whether to install Sileo +// and Zebra. The jailbreak waits for it to close, reading the two switches `installSileo` and +// `installZebra` (PopupOption, `setSwitchValue:`); `isOpen` and `closeAlert` close it. diff --git a/Access/StorageAccess.swift b/Access/StorageAccess.swift index bff0dfc..eae238d 100644 --- a/Access/StorageAccess.swift +++ b/Access/StorageAccess.swift @@ -1,5 +1,6 @@ -// Shared by every app that is installed without DFU inside the Dopamine app: Resize APFS -// here, the Orchard installer in the tools repository (which compiles this file and +// Shared by every app that is installed without DFU inside the Dopamine app (iOS 15 and +// later, Access/AccessBridge.m) or the Amethyst app (iOS 12 and 13, Access/AmethystBridge.m): +// Resize APFS here, the Orchard installer in the tools repository (which compiles this file and // AccessBridge.m from a checkout of this one). Each app brings a Configuration and its own // pages and start (`RAFEmbeddedApp`, App/EmbeddedApp.swift here). import UIKit @@ -12,6 +13,12 @@ import UIKit func obtain(_ prepare: @escaping () -> Void) -> String? func finish() func privileged(_ block: () -> Void) + /// The device itself restarts once while access is obtained (Amethyst's first run). An + /// optional method: Dopamine's bridge, and an older copy of another app's, lack it. + @objc optional func needsDeviceRestart() -> Bool + /// Where the jailbreak keeps its files: "" for the root of the system (Amethyst). Without + /// it, /var/jb (Dopamine). + @objc optional func jailbreakRoot() -> String } /// Storage access for an app installed without DFU: the app obtains it once the user has @@ -26,7 +33,7 @@ final class StorageAccess: @unchecked Sendable { var state: String /// The helper's folder on the data partition: its log and, in `run`, its socket. var folder: String - /// The launch daemon's label; its file is this name in Dopamine's LaunchDaemons. + /// The launch daemon's label; its file is this name in the jailbreak's LaunchDaemons. var label: String /// What the app brings in its bundle (`resource`.payload) and where each goes. The /// first is the helper. Inside the jailbreak root: iOS 15 and later lets launchd start @@ -43,9 +50,25 @@ final class StorageAccess: @unchecked Sendable { /// `--ssh`) when asked to, and removes it again when it does not. An app that never /// carries it leaves another app's server alone. var ssh = false + /// The jailbreak's own root, which `payloads` and `leftovers` name: /var/jb unless the + /// bridge says otherwise (`rooted(at:)`). + var root = "/var/jb" var helper: String { payloads[0].path } - var daemon: String { "/var/jb/Library/LaunchDaemons/\(label).plist" } + var daemon: String { "\(root)/Library/LaunchDaemons/\(label).plist" } + + /// The same app where the jailbreak keeps its files in `root` instead (Amethyst: the + /// root of the system). The SSH server is built for /var/jb only, so it stays off. + func rooted(at root: String) -> Configuration { + guard root != self.root else { return self } + func move(_ path: String) -> String { path.hasPrefix(self.root + "/") ? root + path.dropFirst(self.root.count) : path } + var moved = self + moved.root = root + moved.payloads = payloads.map { ($0.resource, move($0.path)) } + moved.leftovers = leftovers.map(move) + moved.ssh = false + return moved + } /// Where the helper publishes its socket and credentials. Not /var/run: the helper /// starts early in the screen restart, and iOS empties /var/run after that, leaving /// the helper listening on a socket nobody can find. @@ -89,22 +112,27 @@ final class StorageAccess: @unchecked Sendable { /// UserDefaults stops reaching the app's settings). private let folder: URL /// The last attempt, kept across launches: "started" while one runs (it stays if the - /// device restarted during it), "failed", or "restarted" after the screen restart some - /// older devices need first. No file when access was obtained or never tried. + /// device restarted during it), "failed", "restarted" after the screen restart some + /// older devices need first, or "rebooting" while a run that restarts the whole device + /// goes on (the app then starts from its first page). No file when access was obtained or + /// never tried. private var attemptFile: URL { folder.appendingPathComponent("attempt") } /// What happened, step by step, for whoever looks into a failure. The pages say little. private var logFile: URL { folder.appendingPathComponent("access.log") } init(bridge: AccessBridge, configuration: Configuration) { self.bridge = bridge - self.configuration = configuration + self.configuration = configuration.rooted(at: bridge.jailbreakRoot?() ?? configuration.root) folder = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library/Application Support/" + configuration.state) try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) // Made here, as the app's user: later lines may come from root. if !FileManager.default.fileExists(atPath: logFile.path) { FileManager.default.createFile(atPath: logFile.path, contents: nil) } - log("launch, pid \(getpid())") + log("launch, pid \(getpid()), jailbreak root \(self.configuration.root.isEmpty ? "/" : self.configuration.root)") } + /// The device restarts once before access is there (Amethyst's first run): the pages say so. + var restartsDevice: Bool { bridge.needsDeviceRestart?() ?? false } + func log(_ text: String) { NSLog("%@: %@", configuration.name, text) guard let handle = try? FileHandle(forWritingTo: logFile) else { return } @@ -178,6 +206,12 @@ final class StorageAccess: @unchecked Sendable { bridge.restartScreen() return } + // The device restarts during this run: opened again, the app shows its first page, + // and Continue goes on with access. + if restartsDevice { + log("the device restarts once during this run") + record("rebooting") + } var prepared = false if let error = bridge.obtain({ [self] in prepared = true; installHelper(elevated: true) }) { return fail(error, update) } record(nil) diff --git a/App/Pages.swift b/App/Pages.swift index 469edc6..8951a5c 100644 --- a/App/Pages.swift +++ b/App/Pages.swift @@ -248,9 +248,13 @@ struct Pages { } /// Some devices restart their screen once before access; nothing can open the app again - /// then, and Dopamine holds what that restart was for only about 20 seconds. + /// then, and Dopamine holds what that restart was for only about 20 seconds. Amethyst's + /// first run restarts the whole device instead, and the app is opened again by hand. private func reopenNotice() -> UIView { - WarningBox(m, icon: .timer, title: "If Resize APFS doesn’t open again by itself, reopen it within 20 seconds.", paragraphs: []) + if model.access?.restartsDevice == true { + return WarningBox(m, icon: .timer, title: "Your \(UIDevice.current.model) restarts once. Open Resize APFS again when it’s back.", paragraphs: []) + } + return WarningBox(m, icon: .timer, title: "If Resize APFS doesn’t open again by itself, reopen it within 20 seconds.", paragraphs: []) } private func accessFailed() -> [UIView] { diff --git a/Device/README.md b/Device/README.md index a08c6ea..7cb3302 100644 --- a/Device/README.md +++ b/Device/README.md @@ -194,6 +194,41 @@ scene even without a scene configuration; the Resize APFS window joins that scen **Moving to a newer Dopamine:** [docs/updating-dopamine.md](../docs/updating-dopamine.md) has the steps, what we depend on and what to do when something changed. +### Amethyst (iOS 12 and 13) + +On iOS 12.2 to 13.7 the app is the official [Amethyst](https://github.com/staturnzz/amethyst) +release (1.1, pinned in `scripts/tools.py` like Dopamine) with Resize APFS in it, installed the +same way (`scripts/amethyst_route.py`; xtool always signs, as Xcode builds nothing for iOS 12 +and 13). The differences: + +- **The executable is built from source.** The released one is stripped, so the functions the + bridge calls have no names. `scripts/build-amethyst.sh` compiles Amethyst's source at the + pinned commit (`AMETHYST_SOURCE`), unchanged, with clang for iOS 12.0 (current Xcode refuses + the project's deployment target), and checks the names are exported. It goes into + `out/device-ios12/access/host/Amethyst`; `embed.py` puts it in place of the official one and + refuses a stripped executable. Every other file is the official release's. +- **The interface** is `Access/AmethystInterface.h` and `Access/AmethystBridge.m`: five + functions and two objects, looked up by name; `embed.py` and a test keep the names the same. + Amethyst's app delegate always makes its window; the bridge hides it and Resize APFS's window + takes its place. Amethyst's first-run question (install Sileo and Zebra) is answered no and + closed by the bridge. +- **The helper goes in before the screen restart.** Amethyst's run ends with a userspace + reboot itself; right before it, it posts `fade` on its own thread with root, and the bridge + installs the helper then. Amethyst is rootful: the helper and its launch daemon go to + `/usr/libexec` and `/Library/LaunchDaemons` (`StorageAccess.Configuration.rooted(at:)`, + asked from the bridge's `jailbreakRoot`), and the SSH server for developers is not offered. +- **The first run restarts the device.** While iOS runs from its system snapshot, Amethyst + renames it to orig-fs and needs a full restart (`JB_ERROR_REMOUNT_REBOOT`); the bridge + restarts the device as Amethyst's screen would. The page says so beforehand + (`needsDeviceRestart`: `/` mounted from a snapshot), the attempt is noted as `rebooting`, and + opened again the app starts from its first page. Afterwards iOS runs from the live volume, + so the app's existing "Remove snapshot" frees orig-fs before a shrink (Amethyst's own + restore-rootfs needs orig-fs and stops working then). +- **iOS 12.2 and later only:** the library needs the Swift runtime that iOS 12.0 and 12.1 lack, + and Amethyst's executable brings none. The checkra1n route covers those versions. + +Moving to a newer Amethyst: [docs/updating-amethyst.md](../docs/updating-amethyst.md). + ### On the device `Access/StorageAccess.swift` runs when the app opens: diff --git a/README.md b/README.md index a0d7f5b..cb73057 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ open Terminal in the `ResizeAPFS-v…` folder. Then pick the method for your dev | **DFU** (checkra1n) | A7 to A11 | 12 to 14 | | **Dopamine**, no DFU | A8 to A13 | 15.0 to 18.7.1, 26.0 to 26.0.1 | | | A14 and later | 15.0 to 17.3.1 | +| **Amethyst**, no DFU | every device | 12.2 to 13.7 | ### Via DFU (checkra1n / palera1n) @@ -54,6 +55,28 @@ again when it stops opening. Storage access comes from [Dopamine](https://github.com/opa334/Dopamine), which the app carries inside. +### Via Amethyst + +For iOS 12.2 to 13.7, the iPhone 5s, iPad Air and iPad mini 2 and 3 included. + +1. Connect the device, unlock it and trust the computer. +2. Run `./resize-apfs boot --amethyst`. +3. Sign in with your Apple ID when asked; it goes only to Apple. Resize APFS is + installed on the device. +4. Trust your Apple ID on the device: **Settings > General > Profiles & Device + Management**. +5. Open Resize APFS and tap **Continue**. The first time, the device restarts once: + open Resize APFS again when it is back and tap **Continue** again. Then the screen + restarts; unlock the device when it comes back, and Resize APFS opens again and + shows your storage. + +Before a shrink, Resize APFS offers to remove the `orig-fs` snapshot made in step 5: +iOS can't shrink while it is there. A free Apple ID signs the app for 7 days; run step +2 again when it stops opening. + +Storage access comes from [Amethyst](https://github.com/staturnzz/amethyst), which the +app carries inside. + ### In the app Choose **Adjust size**, enter the new size, confirm, and wait for **Completed and diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 958756d..2affc69 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -20,6 +20,34 @@ from its own release page, not included in our release ZIP; its license and thos components stay in the app bundle as its authors ship them. https://github.com/opa334/Dopamine +Without DFU on iOS 12 and 13, the app the user installs is the official Amethyst release +(https://github.com/staturnzz/amethyst) with Resize APFS added on the user's computer. The +release is downloaded from Amethyst's own release page, except its executable: our release ZIP +contains that executable compiled, unchanged, from Amethyst's source at the v1.1 tag +(`out/device-ios12/access/host/Amethyst`), under Amethyst's license: + +MIT License + +Copyright (c) 2026 staturnz + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + Linux host image tools use `libdmg-hfsplus` under GPL-3.0: https://github.com/planetbeing/libdmg-hfsplus diff --git a/Tests/ReleaseTests/access_fixtures.py b/Tests/ReleaseTests/access_fixtures.py index 4c894cb..6937760 100644 --- a/Tests/ReleaseTests/access_fixtures.py +++ b/Tests/ReleaseTests/access_fixtures.py @@ -50,3 +50,32 @@ def make_payload(folder): 'UIAppFonts': ['Fonts/Mono.ttf'], 'CFBundleIdentifier': 'org.orchardlinux.resize-apfs', 'OrchardSystem': 'Omarchy A', 'CFBundleIcons': {'CFBundlePrimaryIcon': {'CFBundleIconFiles': ['AppIcon60x60'], 'CFBundleIconName': 'AppIcon'}}})) return folder + + +def amethyst_executable(stripped=False, room=256): + """Amethyst's executable as scripts/build-amethyst.sh builds it (its functions and globals + exported, so named with a leading underscore), or as the official release has it: stripped.""" + symbols = () if stripped else tuple('_' + name for name in embed.AMETHYST_SYMBOLS) + return macho(symbols + embed.AMETHYST_NAMES, room) + + +def make_amethyst_ipa(path): + info = {'CFBundleExecutable': 'Amethyst', 'CFBundleIdentifier': embed.AMETHYST, 'CFBundleDisplayName': 'Amethyst', + 'MinimumOSVersion': '12.0'} + with zipfile.ZipFile(path, 'w') as archive: + member = zipfile.ZipInfo('Payload/Amethyst.app/Amethyst') + member.external_attr = 0o755 << 16 + archive.writestr(member, amethyst_executable(stripped=True)) + archive.writestr('Payload/Amethyst.app/Info.plist', plistlib.dumps(info)) + archive.writestr('Payload/Amethyst.app/Base.lproj/LaunchScreen.storyboardc/Info.plist', b'theirs') + archive.writestr('Payload/Amethyst.app/basebins.tar', b'basebins') + archive.writestr('Payload/Amethyst.app/bootstrap-1600.tar.lzfse', b'bootstrap') + return path + + +def make_amethyst_payload(folder): + """The payload for iOS 12 and 13 (out/device-ios12/access), with the executable built from source.""" + folder = make_payload(folder) + (folder / embed.HOST).mkdir() + (folder / embed.HOST / 'Amethyst').write_bytes(amethyst_executable()) + return folder diff --git a/Tests/ReleaseTests/test_amethyst_route.py b/Tests/ReleaseTests/test_amethyst_route.py new file mode 100644 index 0000000..9e73c45 --- /dev/null +++ b/Tests/ReleaseTests/test_amethyst_route.py @@ -0,0 +1,180 @@ +import io +import pathlib +import plistlib +import re +import sys +import tempfile +import unittest +import zipfile +from unittest import mock + +ROOT = pathlib.Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / 'scripts')) +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +import amethyst_route # noqa: E402 +import embed # noqa: E402 +import launcher # noqa: E402 +import sideload # noqa: E402 +import tools # noqa: E402 +from access_fixtures import amethyst_executable, make_amethyst_ipa, make_amethyst_payload, make_ipa, make_payload # noqa: E402 +from test_embed import libraries # noqa: E402 + + +class EmbedTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = pathlib.Path(self.temporary.name) + self.ipa = make_amethyst_ipa(self.root / 'Amethyst.ipa') + self.payload = make_amethyst_payload(self.root / 'payload') + + def prepared(self): + return zipfile.ZipFile(embed.prepared_ipa(self.ipa, self.root / 'work', self.payload)) + + def test_the_executable_built_from_source_takes_the_official_ones_place(self): + with self.prepared() as archive: + app = 'Payload/Amethyst.app/' + executable = archive.read(app + 'Amethyst') + self.assertIn(b'_run_jailbreak\0', executable) + self.assertEqual(libraries(executable), [embed.LIBRARY]) + self.assertEqual(archive.getinfo(app + 'Amethyst').external_attr >> 16 & 0o777, 0o755) + info = plistlib.loads(archive.read(app + 'Info.plist')) + self.assertEqual(info['CFBundleDisplayName'], 'Resize APFS') + self.assertEqual(info['CFBundleIdentifier'], embed.AMETHYST, 'the signer sets the identifier') + # Everything else of Amethyst is the official release's. + self.assertEqual(archive.read(app + 'basebins.tar'), b'basebins') + self.assertEqual(archive.read(app + 'bootstrap-1600.tar.lzfse'), b'bootstrap') + self.assertEqual(archive.read(app + 'Frameworks/ResizeAccess.dylib'), b'\xcf\xfa\xed\xfe library') + self.assertEqual(archive.read(app + 'Base.lproj/LaunchScreen.storyboardc/Info.plist'), b'ours') + self.assertNotIn(app + embed.HOST + '/Amethyst', archive.namelist()) + + def test_the_official_stripped_executable_is_refused(self): + with self.assertRaisesRegex(ValueError, 'run_jailbreak.*built from its source'): + embed.check_amethyst(amethyst_executable(stripped=True)) + embed.check_amethyst(amethyst_executable()) + + def test_a_payload_without_the_built_executable_is_refused(self): + payload = make_payload(self.root / 'dopamine-payload') + with self.assertRaisesRegex(ValueError, 'out/device-ios12/access'): + embed.prepared_ipa(self.ipa, self.root / 'work', payload) + + def test_dopamine_does_not_take_the_amethyst_payload(self): + dopamine = make_ipa(self.root / 'Dopamine.ipa') + with self.assertRaisesRegex(ValueError, 'for Amethyst'): + embed.prepared_ipa(dopamine, self.root / 'work', self.payload) + + def test_the_ssh_server_is_only_for_dopamine(self): + with self.assertRaisesRegex(ValueError, 'SSH'): + embed.prepared_ipa(self.ipa, self.root / 'work', self.payload, ssh={'ssh-authorized_keys': b'key'}) + + def test_the_checked_names_are_the_ones_the_bridge_looks_up(self): + bridge = (ROOT / 'Access/AmethystBridge.m').read_text() + looked_up = set(re.findall(r'amethyst(?:Symbol|Object)\("(\w+)"\)', bridge)) + self.assertEqual(looked_up, set(embed.AMETHYST_SYMBOLS)) + for name in embed.AMETHYST_NAMES: + self.assertIn(name, bridge + (ROOT / 'Access/AmethystInterface.h').read_text()) + + def test_the_build_checks_the_same_exports(self): + script = (ROOT / 'scripts/build-amethyst.sh').read_text() + line = re.search(r'for name in ([\w ]+); do', script).group(1).split() + self.assertEqual(sorted(line), sorted(embed.AMETHYST_SYMBOLS)) + + +class FakeSigner: + def __init__(self, available): + self.is_available, self.calls = available, [] + + def available(self): + return self.is_available + + def install(self, ipa, udid, ask, payload=None, host=None): + self.calls.append((ipa, udid, payload, host)) + + +class RunTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = pathlib.Path(self.temporary.name) + self.ipa = make_amethyst_ipa(self.root / 'Amethyst.ipa') + self.payload = make_amethyst_payload(self.root / 'payload') + + def run_route(self, signer, devices, asked): + out = io.StringIO() + with mock.patch('sys.stdout', out): + amethyst_route.run(self.ipa, ask=asked.append, signer=signer, devices=devices, + work=self.root / 'work', payload=self.payload) + return out.getvalue() + + def test_the_app_is_signed_for_the_connected_device_without_developer_mode(self): + asked, signer = [], FakeSigner(True) + said = self.run_route(signer, lambda: [(3, 'UDID-1')], asked) + self.assertEqual(asked, [], 'iOS 12 and 13 have no Developer Mode') + self.assertEqual(signer.calls, [(self.ipa, 'UDID-1', self.payload, 'amethyst')]) + self.assertIn('the device restarts once', said) + + def test_where_nothing_can_sign_the_prepared_app_is_left_for_the_user(self): + asked = [] + self.run_route(FakeSigner(False), lambda: self.fail('no device needed'), asked) + self.assertEqual(len(asked), 1) + with zipfile.ZipFile(self.root / 'work/ResizeAPFS.ipa') as archive: + self.assertIn('Payload/Amethyst.app/Frameworks/ResizeAccess.dylib', archive.namelist()) + + def test_the_user_never_reads_the_word_jailbreak(self): + asked = [] + said = self.run_route(FakeSigner(False), None, asked) + for text in asked + [said]: + self.assertNotIn('jailbreak', text.lower()) + self.assertNotIn('Amethyst', text) + + +class SigningTests(unittest.TestCase): + def test_xtool_signs_under_amethysts_identifier_never_xcode(self): + with tempfile.TemporaryDirectory() as folder: + root = pathlib.Path(folder) + ipa = make_amethyst_ipa(root / 'Amethyst.ipa') + payload = make_amethyst_payload(root / 'payload') + calls = [] + def run(argv, **kwargs): + calls.append([str(a) for a in argv]) + return mock.Mock(returncode=0, stdout='Logged in.', stderr='') + with mock.patch('sys.stdout', io.StringIO()), mock.patch.object(sideload, 'describe', lambda udid, run: 'iPad'), \ + mock.patch.object(sideload, 'xcode_team', lambda *a: self.fail('Xcode cannot sign for iOS 12')), \ + mock.patch.object(sideload, 'installed', lambda *a: None): + sideload.install(ipa, 'UDID-1', ask=lambda text: None, run=run, root=root, payload=payload, + provide=lambda tool: 'xtool', host='amethyst') + self.assertEqual(calls[-1][:5], ['xtool', 'install', '--usb', '--udid', 'UDID-1']) + self.assertTrue(sideload.record_path('UDID-1', root, 'amethyst').is_file()) + self.assertFalse(sideload.record_path('UDID-1', root).exists(), 'the Dopamine record stays apart') + + +class ChoiceAndPinTests(unittest.TestCase): + def test_the_answer_and_the_option_pick_amethyst(self): + with mock.patch('builtins.input', return_value='4'), mock.patch('sys.stdout', io.StringIO()): + self.assertEqual(launcher.route(None), 'amethyst') + with mock.patch('builtins.input', side_effect=AssertionError('asked')): + self.assertEqual(launcher.route(None, amethyst=True), 'amethyst') + self.assertEqual(launcher.route(12, amethyst=True), 'amethyst') + + def test_other_versions_and_both_options_are_refused(self): + for given in (11, 14, 15): + with self.assertRaises(ValueError): + launcher.route(given, amethyst=True) + with self.assertRaises(ValueError): + launcher.route(None, dopamine=True, amethyst=True) + + def test_the_release_ipa_and_its_source_are_pinned(self): + for system in ('macos', 'linux'): + for arch in ('arm64', 'x86_64'): + pin = tools.PINS[('amethyst', system, arch)] + self.assertEqual(pin['url'], 'https://github.com/staturnzz/amethyst/releases/download/v1.1/Amethyst.ipa') + self.assertEqual(pin['size'], 115_881_245) + self.assertRegex(tools.AMETHYST_SOURCE['commit'], r'^[0-9a-f]{40}$') + + def test_the_release_carries_the_route(self): + self.assertIn("'amethyst_route.py'", (ROOT / 'scripts/package_release.py').read_text()) + + +if __name__ == '__main__': + unittest.main() diff --git a/Tests/ReleaseTests/test_checkra1n_route.py b/Tests/ReleaseTests/test_checkra1n_route.py index 4b6c401..b8d3283 100644 --- a/Tests/ReleaseTests/test_checkra1n_route.py +++ b/Tests/ReleaseTests/test_checkra1n_route.py @@ -134,7 +134,7 @@ def test_older_than_12_and_other_answers_are_refused(self): launcher.route(11) with self.assertRaises(ValueError): launcher.route(14, dopamine=True) - with mock.patch('builtins.input', return_value='4'), mock.patch('sys.stdout', io.StringIO()), self.assertRaises(ValueError): + with mock.patch('builtins.input', return_value='5'), mock.patch('sys.stdout', io.StringIO()), self.assertRaises(ValueError): launcher.route(None) diff --git a/docs/updating-amethyst.md b/docs/updating-amethyst.md new file mode 100644 index 0000000..ddfd368 --- /dev/null +++ b/docs/updating-amethyst.md @@ -0,0 +1,22 @@ +# Updating Amethyst + +The route without DFU on iOS 12 and 13 uses the official Amethyst release with one file +replaced: its executable, compiled from the same tag's source (Device/README.md, "Amethyst"). +Both are pinned in `scripts/tools.py`. + +1. Take the new release's `Amethyst.ipa`: put its URL, size and SHA-256 in `AMETHYST`. +2. Put the full commit of the same tag in `AMETHYST_SOURCE`. The executable must come from the + source of the release whose other files it runs with: `basebins.tar` and the bootstraps talk + to it. +3. Read what changed in the files `Access/AmethystInterface.h` names: `run_jailbreak` and its + flags and error numbers (`jailbreak/jailbreak.h`), `jbserver_post_jailbreak` and + `jbserver_heartbeat` (`jailbreak/handoff.c`), `run_jbutil`, `ProgressLog`/`FadeDisplay` + and `get_install_options` (`ui/MainController.m`), `AmethystConfig` (`AppDelegate.h`) and + `InstallAlert` (`ui/Utilities.h`). Update the header and `Access/AmethystBridge.m` where they + changed; `AMETHYST_SYMBOLS` and `AMETHYST_NAMES` in `scripts/embed.py` follow them (a test + checks the bridge and the build script name the same). +4. If the project's sources, frameworks or flags changed (`Amethyst/Amethyst.xcodeproj`), + follow them in `scripts/build-amethyst.sh`. +5. Build the iOS 12 payload in CI and run the route once on a device on iOS 12 and one on + iOS 13, from a device that never ran Amethyst (the first run restarts the device) and again + from one that did. diff --git a/scripts/amethyst_route.py b/scripts/amethyst_route.py new file mode 100644 index 0000000..1614dea --- /dev/null +++ b/scripts/amethyst_route.py @@ -0,0 +1,43 @@ +"""Resize APFS without DFU on iOS 12 and 13: one app, installed with the user's Apple ID. + +The Dopamine route (dopamine_route.py) for the devices Dopamine does not reach: the app is the +pinned Amethyst (every device on iOS 12.0 to 13.7) with Resize APFS in it (embed.py), and +Amethyst's executable built from its own source (scripts/build-amethyst.sh). Opened on the +device, it shows only Resize APFS, obtains storage access through Amethyst by itself, installs +its storage helper as a launch daemon and talks to it as root (Access/StorageAccess.swift, +Access/AmethystBridge.m). On a device's first run the whole device restarts once, while +Amethyst sets iOS's system snapshot aside; the user opens the app again afterwards. + +iOS 12.0 and 12.1 are not served: the app's library needs the Swift runtime that iOS has from +12.2 on, and Amethyst's executable brings none (the checkra1n route covers them). + +xtool signs the app with the user's Apple ID and installs it, after one confirmation +(sideload.py); where xtool has no release, the prepared app is left for the user to sign and +install themselves. iOS 12 and 13 have no Developer Mode. +""" +import pathlib + +import dopamine_route +import embed +import sideload +import usbmux + +ROOT = pathlib.Path(__file__).resolve().parents[1] + +OPEN = ('Open {app} on the device and tap Continue. The first time, the device restarts once: open {app} ' + 'again when it is back and tap Continue again. Then the screen restarts; unlock the device when it ' + 'comes back. If {app} does not open again by itself, open it within 20 seconds.') + + +def run(ipa, ask=input, signer=sideload, devices=usbmux.devices, work=None, payload=None): + """Install the app on the connected device; the user confirms each step.""" + payload = sideload.HOSTS['amethyst']['payload'] if payload is None else payload + sideload.payload_key(payload) + if signer.available(): + signer.install(ipa, dopamine_route.device(devices), ask, payload=payload, host='amethyst') + else: + work = pathlib.Path(work or ROOT / '.work/sideload') + work.mkdir(parents=True, exist_ok=True) + prepared = embed.prepared_ipa(ipa, work, payload, name=sideload.APP.replace(' ', '')) + ask(dopamine_route.SIGN.format(app=sideload.APP, path=prepared)) + print(OPEN.format(app=sideload.APP), flush=True) diff --git a/scripts/build-amethyst.sh b/scripts/build-amethyst.sh new file mode 100755 index 0000000..a71daed --- /dev/null +++ b/scripts/build-amethyst.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# Amethyst's executable, for the route without DFU on iOS 12 and 13: compiled from the pinned +# commit of Amethyst's source (tools.py, AMETHYST_SOURCE), with nothing of it changed, into the +# file given. The official release's executable is stripped, so Access/AmethystBridge.m could not +# find the functions it calls; this one keeps their names. scripts/embed.py puts it in place of +# the official executable on the user's computer; every other file of the app is the official +# release's. +# +# Amethyst's Xcode project cannot be used: current Xcode refuses its iOS 12.0 deployment target. +# So the sources are compiled as the project does (Release, ARC, arm64, the frameworks and +# run path it names), with clang for arm64-apple-ios12.0. Only the source files are fetched, +# not the bootstrap and packages, which come with the official release. +set -euo pipefail +cd "$(dirname "$0")/.." +output=${1:?usage: build-amethyst.sh OUTPUT} +source=.work/amethyst-source +read -r repository commit < <(python3 -c 'import sys; sys.path.insert(0, "scripts"); import tools; print(tools.AMETHYST_SOURCE["repository"], tools.AMETHYST_SOURCE["commit"])') +if [[ "$(git -C "$source" rev-parse HEAD 2>/dev/null)" != "$commit" ]]; then + rm -rf "$source" + git clone --quiet --filter=blob:none --no-checkout "$repository" "$source" + git -C "$source" sparse-checkout set --no-cone '/Amethyst/Amethyst/**/*.[chms]' '/Amethyst/Amethyst/*.[chms]' + git -C "$source" -c advice.detachedHead=false checkout --quiet "$commit" +fi +[[ "$(git -C "$source" rev-parse HEAD)" == "$commit" ]] || { echo "Amethyst source is not at $commit." >&2; exit 1; } +[[ -z "$(git -C "$source" status --porcelain)" ]] || { echo 'Amethyst source has local changes.' >&2; exit 1; } + +sdk=$(xcrun --sdk iphoneos --show-sdk-path) +code="$source/Amethyst/Amethyst" +includes=() +while IFS= read -r folder; do includes+=("-I$folder"); done < <(find "$code" -type d) +sources=() +while IFS= read -r file; do sources+=("$file"); done < <(find "$code" -name '*.c' -o -name '*.m' -o -name '*.s' | sort) +mkdir -p "$(dirname "$output")" +# -w: Amethyst's own warnings are not ours to fix here. +xcrun --sdk iphoneos clang -target arm64-apple-ios12.0 -isysroot "$sdk" -Os -fobjc-arc -fmodules -w \ + "${includes[@]}" "${sources[@]}" \ + -framework UIKit -framework Foundation -framework CoreFoundation -framework IOKit -framework IOSurface \ + -Xlinker -rpath -Xlinker @executable_path/Frameworks -o "$output" +# Debug maps only (they name the builder's folders); the exported names stay. +xcrun --sdk iphoneos strip -S "$output" +minos=$(xcrun vtool -show-build "$output" | awk '/minos/ {print $2}') +[[ "$minos" == 12.0 ]] || { echo "Amethyst is built for iOS $minos, not 12.0." >&2; exit 1; } +# What Access/AmethystBridge.m looks up (Access/AmethystInterface.h). +exported=$(xcrun nm -gU "$output") +for name in run_jailbreak jbserver_heartbeat jbserver_post_jailbreak run_jbutil amethyst mainController; do + grep -q " _$name\$" <<<"$exported" || { echo "Amethyst's executable does not export $name." >&2; exit 1; } +done +codesign --force --sign - --timestamp=none "$output" +echo "Built Amethyst's executable from $commit: $output" diff --git a/scripts/build-device-ios12.sh b/scripts/build-device-ios12.sh index e23e55b..105432f 100755 --- a/scripts/build-device-ios12.sh +++ b/scripts/build-device-ios12.sh @@ -1,6 +1,7 @@ #!/bin/bash # The iOS 12-14 payload for scripts/checkra1n_route.py: out/device-ios12/ResizeAPFS.app -# and out/device-ios12/resize-helper. Current Xcode only accepts iOS 15+ deployment +# and out/device-ios12/resize-helper; and out/device-ios12/access, the app without DFU on +# iOS 12 and 13 for scripts/amethyst_route.py. Current Xcode only accepts iOS 15+ deployment # targets, so everything is compiled with swiftc/clang for arm64-apple-ios12.0, which # also makes the compiler reject any API newer than iOS 12. # @@ -95,6 +96,35 @@ for binary in "$app/ResizeAPFS" "$out/resize-helper"; do minos=$(xcrun vtool -show-build "$binary" | awk '/minos/ {print $2}') [[ "$minos" == 12.0 ]] || { echo "$binary is built for iOS $minos, not 12.0." >&2; exit 1; } done +# The app without DFU on iOS 12 and 13 (scripts/embed.py puts this into the pinned Amethyst app +# on the user's computer): the interface as a library, the resources it needs, the helper, and +# Amethyst's executable built from its source (scripts/build-amethyst.sh). The library needs +# Swift in iOS (12.2 and later): it is loaded by Amethyst's executable, which brings no runtime. +access="$out/access" +mkdir -p "$access/Resources" "$access/host" +xcrun --sdk iphoneos clang -target "$target" -isysroot "$sdk" -Os -fobjc-arc -fmodules \ + -c Access/AmethystBridge.m -o "$build/AmethystBridge.o" +# AppDelegate.swift is the other start of the app (its own executable); here Amethyst's runs. +swiftc -parse-as-library -emit-library -module-name ResizeAccess -I "$build" -L "$build" -lResizeCore \ + $(ls App/*.swift | grep -v '^App/AppDelegate.swift$') Access/StorageAccess.swift "$build/AmethystBridge.o" \ + -Xlinker -install_name -Xlinker @executable_path/Frameworks/ResizeAccess.dylib \ + -o "$access/ResizeAccess.dylib" +first=$(xcrun otool -l "$access/ResizeAccess.dylib" | awk '/cmd LC_RPATH/ {getline; getline; print $2; exit}') +[[ "$first" == /usr/lib/swift ]] || { echo "ResizeAccess.dylib must search /usr/lib/swift first, not $first." >&2; exit 1; } +xcrun --sdk iphoneos strip -x "$access/ResizeAccess.dylib" +codesign --force --sign - --timestamp=none "$access/ResizeAccess.dylib" +cp "$app/Info.plist" "$access/Info.plist" +for resource in "$app"/*; do + case "$(basename "$resource")" in + # Assets.car holds only the icon, which also ships as loose files; Amethyst's stays in place. + ResizeAPFS|Info.plist|PkgInfo|_CodeSignature|Frameworks|Assets.car) ;; + *) ditto "$resource" "$access/Resources/$(basename "$resource")" ;; + esac +done +# Behind a prefix, so signing the app with an Apple ID leaves the helper's own signature alone. +{ printf 'RESIZE-APFS-HELPER\n'; cat "$out/resize-helper"; } > "$access/Resources/resize-helper.payload" +bash scripts/build-amethyst.sh "$access/host/Amethyst" + python3 - <<'PY' import hashlib,json,pathlib root=pathlib.Path('out/device-ios12') diff --git a/scripts/embed.py b/scripts/embed.py index fbbbb75..195beb7 100644 --- a/scripts/embed.py +++ b/scripts/embed.py @@ -1,5 +1,11 @@ -"""An app inside the pinned Dopamine app: one app for the route without DFU. Resize APFS -here; the Orchard installer (tools repository) uses this file from a checkout of this one. +"""An app inside the pinned Dopamine app (iOS 15 and later) or the pinned Amethyst app (iOS 12 +and 13): one app for the route without DFU. Resize APFS here; the Orchard installer (tools +repository) uses this file from a checkout of this one. + +Amethyst is handled as Dopamine is below, with one difference: its released executable is +stripped, so the payload brings the same executable built from Amethyst's source at the pinned +tag (`host/Amethyst`, scripts/build-amethyst.sh), which takes the official one's place. Its +interface is Access/AmethystInterface.h, its bridge Access/AmethystBridge.m. The official Dopamine release (tools.py pins it by size and SHA-256) stays as it is, except: @@ -42,6 +48,15 @@ def library(payload): 'DOPreferenceManager', 'setPreferenceValue:forKey:') # Dopamine's own setting that keeps its logo off the screen restart (Access/AccessBridge.m sets it). SETTING = 'bootlogoEnabled' +# What Access/AmethystBridge.m looks up in Amethyst, as Access/AmethystInterface.h declares it: +# the exported functions and globals, then the names of the objects' properties and methods. +AMETHYST = 'com.staturnz.amethyst' +AMETHYST_SYMBOLS = ('run_jailbreak', 'jbserver_heartbeat', 'jbserver_post_jailbreak', 'run_jbutil', 'amethyst', + 'mainController') +AMETHYST_NAMES = ('exploit', 'generator', 'installAlert', 'installSileo', 'installZebra', 'setSwitchValue:', + 'isOpen', 'closeAlert', 'fade') +# The payload's folder with the host app's executable, where one replaces the official one. +HOST = 'host' # Taken from the Resize APFS Info.plist; a key it lacks is removed. INFO_KEYS = ('CFBundleDisplayName', 'CFBundleName', 'CFBundleShortVersionString', 'CFBundleVersion', 'CFBundleIcons', 'CFBundleIcons~ipad', 'CFBundleIconFiles', 'UILaunchStoryboardName', 'UIAppFonts', @@ -75,6 +90,15 @@ def check_interface(executable): require(not missing, 'This Dopamine release does not fit this Resize APFS: it has no ' + ', '.join(missing) + '.') +def check_amethyst(executable): + """Refuse an Amethyst executable that lacks something Resize APFS calls: one stripped (as + the official release's is) has none of the functions.""" + missing = [name for name in AMETHYST_SYMBOLS if b'_' + name.encode() + b'\0' not in executable] + missing += [name for name in AMETHYST_NAMES if name.encode() + b'\0' not in executable] + require(not missing, "This Amethyst executable does not fit this Resize APFS: it has no " + ', '.join(missing) + + '. Use the one built from its source (scripts/build-amethyst.sh), not the official stripped one.') + + def load_command(path): name = path.encode() + b'\0' name += b'\0' * (-(24 + len(name)) % 8) @@ -86,12 +110,12 @@ def add_to_slice(data, path): """A 64-bit Mach-O with `path` added to the libraries it loads, in the unused space between its load commands and its first section. Its size and offsets stay the same.""" magic, _, _, _, count, size, _, _ = struct.unpack_from('= 8 and offset + length <= HEADER + size, 'The Dopamine executable has damaged load commands.') + require(length >= 8 and offset + length <= HEADER + size, 'The app\'s executable has damaged load commands.') if command == LC_LOAD_DYLIB: start = offset + struct.unpack_from('> 16 for info in archive.infolist()} apps = list((folder / 'Payload').glob('*.app')) - require(len(apps) == 1, 'The Dopamine IPA does not hold exactly one app.') + require(len(apps) == 1, 'The IPA does not hold exactly one app.') return apps[0], modes @@ -194,14 +218,24 @@ def pack(folder, output, modes): def merge(app, payload, ssh=None): - """Put Resize APFS (`payload`: out/device/access) into the unpacked Dopamine `app`, and - the SSH server's files (`ssh`: ssh_resources) when given.""" + """Put Resize APFS (`payload`: out/device/access, or out/device-ios12/access for Amethyst) + into the unpacked Dopamine or Amethyst `app`, and the SSH server's files (`ssh`: + ssh_resources) when given.""" app, payload = pathlib.Path(app), pathlib.Path(payload) info = plistlib.loads((app / 'Info.plist').read_bytes()) ours = plistlib.loads((payload / 'Info.plist').read_bytes()) executable = app / info['CFBundleExecutable'] - data = executable.read_bytes() - check_interface(data) + if info.get('CFBundleIdentifier') == AMETHYST: + built = payload / HOST / info['CFBundleExecutable'] + require(built.is_file(), 'This payload has no Amethyst executable built from source (host/Amethyst): ' + 'Amethyst needs the payload for iOS 12 and 13 (out/device-ios12/access).') + require(not ssh, 'The SSH server is only for the Dopamine route.') + data = built.read_bytes() + check_amethyst(data) + else: + require(not (payload / HOST).exists(), 'This payload is for Amethyst (iOS 12 and 13), not Dopamine.') + data = executable.read_bytes() + check_interface(data) source, loaded = library(payload) executable.write_bytes(add_library(data, loaded)) (app / 'Frameworks').mkdir(exist_ok=True) diff --git a/scripts/launcher.py b/scripts/launcher.py index cbcf7f6..b8b788c 100644 --- a/scripts/launcher.py +++ b/scripts/launcher.py @@ -38,31 +38,39 @@ def made_by(overlay, info): return False -def route(given, dopamine=False): - """'palera1n', 'checkra1n' or 'dopamine': --dopamine, --ios, or the user's answer.""" +def route(given, dopamine=False, amethyst=False): + """'palera1n', 'checkra1n', 'dopamine' or 'amethyst': --dopamine, --amethyst, --ios, or the + user's answer.""" + require(not (dopamine and amethyst), 'Choose one of --dopamine and --amethyst.') if dopamine: require(given is None or given >= 15, 'The Dopamine route needs iOS/iPadOS 15 or later.') return 'dopamine' + if amethyst: + require(given is None or given in (12, 13), 'The Amethyst route needs iOS/iPadOS 12.2 to 13.7.') + return 'amethyst' if given is None: print('iOS/iPadOS version on the device (Settings > General > About):\n' ' 1) 15 or later\n' ' 2) 12, 13 or 14\n' - ' 3) 15 or later, without DFU: Dopamine (also iPhone XS, XR, 11 and other A12/A13 devices)') + ' 3) 15 or later, without DFU: Dopamine (also iPhone XS, XR, 11 and other A12/A13 devices)\n' + ' 4) 12.2 to 13.7, without DFU: Amethyst (also iPhone 5s, iPad Air, iPad mini 2 and 3)') answer = input('> ').strip() - require(answer in ('1', '2', '3'), 'Please answer 1, 2 or 3.') - return {'1': 'palera1n', '2': 'checkra1n', '3': 'dopamine'}[answer] + require(answer in ('1', '2', '3', '4'), 'Please answer 1, 2, 3 or 4.') + return {'1': 'palera1n', '2': 'checkra1n', '3': 'dopamine', '4': 'amethyst'}[answer] require(given >= 12, 'Resize APFS needs iOS/iPadOS 12 or later.') return 'palera1n' if given >= 15 else 'checkra1n' def main(): parser = argparse.ArgumentParser(description='Prepare and boot Resize APFS: palera1n for iOS 15+, checkra1n for iOS 12-14, ' - 'Dopamine for iOS 15+ without DFU.') + 'Dopamine for iOS 15+ and Amethyst for iOS 12.2-13.7 without DFU.') parser.add_argument('action', choices=['prepare', 'boot']) parser.add_argument('--ios', type=int, metavar='VERSION', help='the installed iOS major version (e.g. 15 or 12); skips the question') parser.add_argument('--dopamine', action='store_true', help='use Dopamine instead of DFU: the app installed with your Apple ID (iOS 15 or later); skips the question') + parser.add_argument('--amethyst', action='store_true', + help='use Amethyst instead of DFU: the app installed with your Apple ID (iOS 12.2 to 13.7); skips the question') parser.add_argument('--ssh', action='store_true', help='for developers, with Dopamine: also install an SSH server for root, reachable over USB ' 'only and only with your SSH public key (~/.ssh/id_ed25519.pub)') @@ -70,7 +78,7 @@ def main(): require(sys.version_info >= (3, 9), 'Python 3.9 or later is required.') require(sys.platform == 'darwin' or sys.platform.startswith('linux'), 'Use Linux or macOS to prepare the overlay.') payload = verify_package() - chosen = route(args.ios, args.dopamine) + chosen = route(args.ios, args.dopamine, args.amethyst) require(not args.ssh or chosen == 'dopamine', '--ssh is for the route without DFU (--dopamine).') if chosen == 'dopamine': import dopamine_route @@ -81,6 +89,12 @@ def main(): if args.action == 'boot': dopamine_route.run(ipa, ssh=ssh) return + if chosen == 'amethyst': + import amethyst_route + ipa = pinned.provide('amethyst') + if args.action == 'boot': + amethyst_route.run(ipa) + return if chosen == 'checkra1n': import checkra1n_route checkra1n_route.payload() diff --git a/scripts/package_release.py b/scripts/package_release.py index b1594ec..6431007 100644 --- a/scripts/package_release.py +++ b/scripts/package_release.py @@ -49,7 +49,7 @@ scripts = ['launcher.py', 'palera.py', 'boot_device.py', 'boot-device.sh', 'build-overlay.py', 'extract-binpack.py', 'overlay_linux.py', 'overlay_macos.py', 'image_format.py', 'hfs-root-ownership.py', 'audit-overlay.py', 'build-linux-tools.sh', - 'tools.py', 'usbmux.py', 'checkra1n_route.py', 'dopamine_route.py', 'embed.py', 'sideload.py', 'xcode_signing.py', 'boot_run.py'] + 'tools.py', 'usbmux.py', 'checkra1n_route.py', 'dopamine_route.py', 'amethyst_route.py', 'embed.py', 'sideload.py', 'xcode_signing.py', 'boot_run.py'] for script in scripts: shutil.copy2(ROOT / 'scripts' / script, package / 'scripts' / script) for file in ['upstream.lock.json', 'org.orchardlinux.resize-apfs.helper.plist', 'README.md']: diff --git a/scripts/sideload.py b/scripts/sideload.py index fdf386d..b623df6 100644 --- a/scripts/sideload.py +++ b/scripts/sideload.py @@ -1,7 +1,9 @@ """Sign Resize APFS with the user's own Apple ID and install it, on Linux and macOS. -The app is the pinned Dopamine with Resize APFS in it (embed.py). On a Mac whose Xcode is -signed in to an Apple ID, that account signs it (xcode_signing.py): nothing new to sign in to. +The app is the pinned Dopamine with Resize APFS in it (embed.py), or on iOS 12 and 13 the pinned +Amethyst. On a Mac whose Xcode is signed in to an Apple ID, that account signs the Dopamine app +(xcode_signing.py): nothing new to sign in to. Xcode builds nothing for iOS 12 and 13 any more, +so xtool always signs the Amethyst app. Otherwise xtool (pinned in tools.py) does the Apple side: `xtool auth login` signs in once (two-factor included) and keeps the session; `xtool install` registers the device, makes the App ID and provisioning profile, signs the app and installs it over the cable. The App ID is @@ -45,6 +47,12 @@ ROOT = pathlib.Path(__file__).resolve().parents[1] # The Resize APFS side of the app (scripts/build-device.sh). PAYLOAD = ROOT / 'out/device/access' +# The host apps: the bundle identifier xtool signs it under (earlier releases signed the plain +# Dopamine under the same one), the Resize APFS side for it, and whether Xcode can sign it. +HOSTS = { + 'dopamine': dict(identifier='com.opa334.Dopamine', payload=PAYLOAD, xcode=True), + 'amethyst': dict(identifier='com.staturnz.amethyst', payload=ROOT / 'out/device-ios12/access', xcode=False), +} def available(host=tools.host): @@ -91,7 +99,7 @@ def payload_key(payload): """One hash over every file of the Resize APFS payload.""" payload = pathlib.Path(payload) files = sorted(path for path in payload.rglob('*') if path.is_file()) - require(files, 'This folder has no app for the route without DFU (out/device/access). ' + require(files, 'This folder has no app for the route without DFU (out/device/access, or out/device-ios12/access for Amethyst). ' 'Use the release ZIP, or build it with scripts/build-device.sh.') return hashlib.sha256(''.join(f'{path.relative_to(payload).as_posix()} {tools.sha256_file(path)}\n' for path in files).encode()).hexdigest() @@ -134,15 +142,15 @@ def describe(udid, run=subprocess.run): return f'{name} ({model})' if model else name -def record_path(udid, root=None): - return (root or tools.cache_root()) / 'sideload' / f'dopamine-{udid}.json' +def record_path(udid, root=None, host='dopamine'): + return (root or tools.cache_root()) / 'sideload' / f'{host}-{udid}.json' -def still_signed(key, udid, now=None, root=None, run=subprocess.run, identifier='com.opa334.Dopamine'): +def still_signed(key, udid, now=None, root=None, run=subprocess.run, identifier='com.opa334.Dopamine', host='dopamine'): """The expiry of the installed app when it is this one and has over a day left, else None. Where the device cannot be asked whether it is still installed, the record decides.""" try: - record = json.loads(record_path(udid, root).read_text()) + record = json.loads(record_path(udid, root, host).read_text()) expires = datetime.datetime.fromisoformat(record['expires']) if record['key'] != key: return None @@ -154,14 +162,17 @@ def still_signed(key, udid, now=None, root=None, run=subprocess.run, identifier= def install(ipa, udid, ask=input, run=subprocess.run, root=None, payload=None, provide=tools.provide, - team=None, ssh=None): - """Put Resize APFS into the Dopamine `ipa`, sign it with the user's Apple ID and install it - on `udid` after one confirmation, unless a signed copy is still installed. `team`: Xcode's - account (xcode_team), or None for xtool. `ssh`: the opt-in SSH server's files - (embed.ssh_resources), or None.""" - payload = PAYLOAD if payload is None else payload + team=None, ssh=None, host='dopamine'): + """Put Resize APFS into the `host` app's `ipa` (HOSTS), sign it with the user's Apple ID and + install it on `udid` after one confirmation, unless a signed copy is still installed. + `team`: Xcode's account (xcode_team), or None for xtool. `ssh`: the opt-in SSH server's + files (embed.ssh_resources), or None.""" + pinned = HOSTS[host] + payload = pinned['payload'] if payload is None else payload + if not pinned['xcode']: + team = '' team = xcode_team(ask, run) if team is None else (team or None) - identifier = xcode_signing.bundle_id(team[0]) if team else 'com.opa334.Dopamine' + identifier = xcode_signing.bundle_id(team[0]) if team else pinned['identifier'] # The installed copy is kept only when it was made from the same Dopamine and payload, the same way. parts = [identifier, tools.sha256_file(ipa), payload_key(payload)] # With or without the SSH server is a different app: switching either way installs again. @@ -169,7 +180,7 @@ def install(ipa, udid, ask=input, run=subprocess.run, root=None, payload=None, p parts.append(hashlib.sha256(b''.join(name.encode() + b' ' + hashlib.sha256(data).digest() for name, data in sorted(ssh.items()))).hexdigest()) key = hashlib.sha256(' '.join(parts).encode()).hexdigest() - expires = still_signed(key, udid, root=root, run=run, identifier=identifier) + expires = still_signed(key, udid, root=root, run=run, identifier=identifier, host=host) if expires: print(f'{APP} is installed and signed until {expires:%d %b %Y}.') return @@ -182,7 +193,7 @@ def install(ipa, udid, ask=input, run=subprocess.run, root=None, payload=None, p when = install_with_xcode(prepared, work / 'xcode', team[0], identifier, udid, run) else: when = install_with_xtool(prepared, udid, run, provide) - record = record_path(udid, root) + record = record_path(udid, root, host) record.parent.mkdir(parents=True, exist_ok=True) record.write_text(json.dumps({'expires': when.isoformat(), 'key': key})) print(f'{APP} is installed, signed until about {when:%d %b %Y}.') diff --git a/scripts/tools.py b/scripts/tools.py index 829e0e8..a6afeed 100644 --- a/scripts/tools.py +++ b/scripts/tools.py @@ -1,4 +1,4 @@ -"""The pinned palera1n, checkra1n and Dopamine, downloaded once into the shared Orchard cache. +"""The pinned palera1n, checkra1n, Dopamine and Amethyst, downloaded once into the shared Orchard cache. The cache is the graphical installer's (orchard): `~/Library/Caches/orchard` on macOS, `$XDG_CACHE_HOME/orchard` or `~/.cache/orchard` elsewhere, or the one there under its old @@ -24,6 +24,7 @@ PALERA1N_RELEASE = 'https://github.com/palera1n/palera1n/releases/download/v3.0.0-beta.4' CHECKRA1N_RELEASE = 'https://assets.checkra.in/downloads' DOPAMINE_RELEASE = 'https://github.com/opa334/Dopamine/releases/download/3.0.13' +AMETHYST_RELEASE = 'https://github.com/staturnzz/amethyst/releases/download/v1.1' XTOOL_RELEASE = 'https://github.com/xtool-org/xtool/releases/download/2.0.0-beta.2' # Kept identical to OrchardLinux/tools' crates/flow/src/assets.rs PALERA1N_PINS (v3.0.0-beta.4). @@ -71,6 +72,20 @@ for _system in ('macos', 'linux'): for _arch in ('arm64', 'x86_64'): PINS[('dopamine', _system, _arch)] = DOPAMINE +# Amethyst 1.1, the route without DFU on iOS 12 and 13: the official release's files serve as +# they are, except its executable, which is stripped and so has no names to call. The release +# build compiles that executable from the same tag's source, unchanged and unstripped +# (build-amethyst.sh, AMETHYST_SOURCE), and embed.py puts it in place of the official one. +# Changing this pin: docs/updating-amethyst.md. +AMETHYST = dict(url=AMETHYST_RELEASE + '/Amethyst.ipa', size=115_881_245, + sha256='65fad9542e3d73246d602b7ee259055928978650f4e93b8f93a513da8266f3b4', package='file', + member=None, executable_sha256=None) +for _system in ('macos', 'linux'): + for _arch in ('arm64', 'x86_64'): + PINS[('amethyst', _system, _arch)] = AMETHYST +# The commit of Amethyst's v1.1 tag, whose source build-amethyst.sh compiles. +AMETHYST_SOURCE = dict(repository='https://github.com/staturnzz/amethyst.git', + commit='61ce86d7d3f00e5395f4d42bebda0e5dce04946a') # xtool 2.0.0-beta.2 signs the app with the user's Apple ID and installs it (sideload.py). # The beta, not 1.24.0: it has the anisette crash fix (#422) and the provisioning-profile # conflict fix (#430) that re-signing every 7 days runs into; its Apple login already @@ -109,7 +124,8 @@ executable_sha256='59953f9ce6c92918c78200e72ba24308228cb1d58c083f5a7a4eda9ff8609608'), } -OVERRIDES = {'palera1n': 'PALERA1N', 'checkra1n': 'CHECKRA1N', 'dopamine': 'DOPAMINE', 'xtool': 'XTOOL'} +OVERRIDES = {'palera1n': 'PALERA1N', 'checkra1n': 'CHECKRA1N', 'dopamine': 'DOPAMINE', 'amethyst': 'AMETHYST', + 'xtool': 'XTOOL'} def host(): @@ -216,9 +232,9 @@ def unpack(package, pin, destination): def provide(tool, root=None, fetch=None): - """The path of the pinned tool's executable, ready to run; for Dopamine, its verified IPA. + """The path of the pinned tool's executable, ready to run; for Dopamine and Amethyst, the verified IPA. - `PALERA1N` / `CHECKRA1N` / `DOPAMINE` point to a developer's own build instead and skip the download. + `PALERA1N` / `CHECKRA1N` / `DOPAMINE` / `AMETHYST` point to a developer's own build instead and skip the download. """ override = os.environ.get(OVERRIDES[tool]) if tool in OVERRIDES else None if override: