-
-
Notifications
You must be signed in to change notification settings - Fork 222
Expand file tree
/
Copy pathindex.ts
More file actions
337 lines (289 loc) · 9.63 KB
/
Copy pathindex.ts
File metadata and controls
337 lines (289 loc) · 9.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import { EventEmitter } from "events";
import { createWriteStream, type PathLike } from "fs";
import { resolve } from "path";
import { Transform } from "stream";
import { pipeline } from "stream/promises";
import chalk from "chalk";
import type { Application, Device, Script } from "frida";
import Controller from "frida-remote-stream";
import { debug, directoryExists, readFromPackage, sleep } from "./lib/utils.ts";
const MH_EXECUTE = 0x2;
const MAX_DECRYPT_RETRIES = 3;
export type DumpMode = "all" | "main" | "extensions" | "binaries";
interface Extension {
id: string;
path: string;
abs: string;
}
interface BinaryInfo {
type: number;
[key: string]: unknown;
}
interface PrepareResult {
base: string;
root: string;
tasks: Record<string, BinaryInfo>;
extensions: Extension[];
mainBinary: string;
}
export class BagBak extends EventEmitter {
#device: Device;
#app: Application;
constructor(device: Device, app: Application) {
super();
this.#app = app;
this.#device = device;
}
get bundle() {
return this.#app.identifier;
}
get remote() {
return this.#app.parameters.path as string;
}
async #attach() {
const session = await this.#device.attach("SpringBoard");
const code = await readFromPackage("agent", "dist", "springboard.js");
const script = await session.createScript(code.toString());
script.logHandler = (level, text) =>
console.log("[springboard]", level, text);
await script.load();
return { session, script };
}
async #decrypt(
pid: number,
remoteRoot: string,
root: string,
binaries: Record<string, BinaryInfo>,
isExtension: boolean,
) {
const session = await this.#device.attach(pid);
const code = await readFromPackage("agent", "dist", "app.js");
const script = await session.createScript(code.toString());
script.logHandler = (level, text) => debug("[app]", level, text);
script.message.connect((message) => {
if (message.type === "send" && message.payload?.event === "patch") {
this.emit("patch", message.payload.name);
script.post({ type: "ack" });
}
});
await script.load();
if (isExtension) {
await script.exports.hookExtensionMain();
} else {
await script.exports.hookAppMain();
}
await this.#device.resume(pid);
const result = await script.exports.dump(
remoteRoot,
root,
binaries,
isExtension,
);
debug("dump result =>", result);
await script.unload();
await session.detach();
}
async #decryptWithRetry(
label: string,
spawnTarget: string | string[],
remoteRoot: string,
root: string,
binaries: Record<string, BinaryInfo>,
isExtension: boolean,
): Promise<void> {
let lastError: unknown;
for (let attempt = 1; attempt <= MAX_DECRYPT_RETRIES; attempt++) {
const pid = await this.#device.spawn(spawnTarget, {
env: { DISABLE_TWEAKS: "1" },
});
debug("spawned", label, "pid =>", pid);
try {
await this.#decrypt(pid, remoteRoot, root, binaries, isExtension);
return;
} catch (e) {
lastError = e;
if (attempt < MAX_DECRYPT_RETRIES) {
this.emit(
"status",
`Retry ${attempt}/${MAX_DECRYPT_RETRIES} for ${label}...`,
);
await sleep(1000);
}
} finally {
await this.#device.kill(pid).catch(() => {});
}
}
throw lastError;
}
async #pull(coordScript: Script, zipPath: string, destPath: string) {
const controller = new Controller();
const done = new Promise<void>((resolve, reject) => {
controller.events.on("stream", (source: any) => {
const totalSize: number = source.details.size;
this.emit("streaming", totalSize);
let transferred = 0;
const progress = new Transform({
transform(chunk, _encoding, callback) {
transferred += chunk.length;
this.push(chunk);
callback();
},
});
const interval = setInterval(() => {
this.emit("progress", transferred, totalSize);
}, 200);
pipeline(source, progress, createWriteStream(destPath)).then(
() => {
clearInterval(interval);
this.emit("progress", totalSize, totalSize);
resolve();
},
(err) => {
clearInterval(interval);
reject(err);
},
);
});
});
controller.events.on("send", (packet: any) => {
coordScript.post({ type: "stream", ...packet.stanza }, packet.data);
});
const handler = (message: any, data: any) => {
if (
message.type === "send" &&
typeof message.payload?.name === "string"
) {
controller.receive({ stanza: message.payload, data });
}
};
coordScript.message.connect(handler);
try {
await coordScript.exports.stream(zipPath);
await done;
} finally {
coordScript.message.disconnect(handler);
}
}
async pack(suggested?: PathLike, mode: DumpMode = "all", removeKeys: string[] = []): Promise<string> {
const { session: coordSession, script: coordScript } = await this.#attach();
try {
this.emit("status", "Preparing app bundle...");
const { base, root, tasks, extensions, mainBinary } =
(await coordScript.exports.prepare(
this.remote,
this.bundle,
removeKeys,
)) as PrepareResult;
const taskCount = Object.keys(tasks).length;
debug("root", root);
debug("tasks", taskCount, "encrypted binaries");
debug("extensions", extensions.length);
if (taskCount === 0) {
this.emit("status", "No encrypted binaries found");
}
const groupByExtensions = new Map<string, Record<string, BinaryInfo>>(
extensions.map((ext) => [ext.id, {}]),
);
const binariesForMain: Record<string, BinaryInfo> = {};
for (const [relative, info] of Object.entries(tasks)) {
const absolute = this.remote + "/" + relative;
const ext = extensions.find((ext) => absolute.startsWith(ext.path));
if (ext) {
debug("scope for", chalk.green(relative), "is", chalk.gray(ext.id));
groupByExtensions.get(ext.id)![relative] = info;
} else if (
info.type === MH_EXECUTE &&
absolute !== this.remote + "/" + mainBinary
) {
console.error(chalk.red("Executable"), chalk.yellowBright(relative));
console.error(
chalk.red(
"is not within any extension. Likely requires higher MinimumOSVersion.",
),
);
console.error(chalk.red("This binary will be left encrypted."));
} else {
debug("scope for", relative, "is", chalk.green("main app"));
binariesForMain[relative] = info;
}
}
const decryptMain = mode !== "extensions";
const decryptExtensions = mode !== "main";
if (decryptMain && Object.keys(binariesForMain).length) {
this.emit("status", "Decrypting main app...");
await this.#decryptWithRetry(
"main app",
this.bundle,
this.remote,
root,
binariesForMain,
false,
);
}
if (decryptExtensions) {
for (const [extId, binaries] of groupByExtensions.entries()) {
if (Object.keys(binaries).length === 0) continue;
const ext = extensions.find((e) => e.id === extId)!;
this.emit("status", `Decrypting extension ${extId}...`);
await this.#decryptWithRetry(
extId,
[ext.abs],
this.remote,
root,
binaries,
true,
);
}
}
const ver = (this.#app.parameters.version as string) || "Unknown";
let remotePath: string;
let defaultFilename: string;
let ext: string;
if (mode === "all") {
this.emit("status", "Packaging IPA...");
remotePath = (await coordScript.exports.zip(base)) as string;
ext = ".ipa";
defaultFilename = `${this.bundle}-${ver}.ipa`;
} else {
const files: string[] = [];
if (mode === "main" || mode === "binaries") {
files.push(...Object.keys(binariesForMain));
}
if (mode === "extensions" || mode === "binaries") {
for (const [extId, binaries] of groupByExtensions.entries()) {
files.push(...Object.keys(binaries));
}
}
const plists = new Set<string>();
for (const f of files) {
const dir = f.lastIndexOf("/");
plists.add(dir === -1 ? "Info.plist" : f.substring(0, dir) + "/Info.plist");
}
files.push(...plists);
this.emit("status", `Compressing ${files.length} files...`);
remotePath = (await coordScript.exports.zipFiles(
root,
files,
)) as string;
ext = ".zip";
defaultFilename = `${this.bundle}-${ver}-${mode}.zip`;
}
debug("remote path:", remotePath);
const suggestedStr = suggested?.toString();
const dest = suggestedStr
? (await directoryExists(suggestedStr))
? suggestedStr + "/" + defaultFilename
: suggestedStr
: defaultFilename;
if (ext && !dest.endsWith(ext))
throw new Error(`Invalid filename ${dest}, expected ${ext} extension`);
this.emit("status", "Downloading...");
await this.#pull(coordScript, remotePath, resolve(process.cwd(), dest));
await coordScript.exports.cleanup(base);
return dest;
} finally {
await coordScript.unload().catch(() => {});
await coordSession.detach().catch(() => {});
}
}
}