Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 174 additions & 0 deletions Access/AmethystBridge.m
Original file line number Diff line number Diff line change
@@ -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 <UIKit/UIKit.h>
#import <dlfcn.h>
#import <sys/mount.h>
#import <unistd.h>
#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<UIApplicationDelegate> 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
}
}];
}
41 changes: 41 additions & 0 deletions Access/AmethystInterface.h
Original file line number Diff line number Diff line change
@@ -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 <Foundation/Foundation.h>

// 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.
50 changes: 42 additions & 8 deletions Access/StorageAccess.swift
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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 }
Expand Down Expand Up @@ -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)
Expand Down
8 changes: 6 additions & 2 deletions App/Pages.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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] {
Expand Down
Loading
Loading