forked from ChiChou/bagbak
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
280 lines (231 loc) · 7.87 KB
/
index.js
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
import { EventEmitter } from 'events';
import { mkdir, open, rm, rename } from 'fs/promises';
import { tmpdir } from 'os';
import { basename, join, resolve } from 'path';
import { AppBundleVisitor } from './lib/scan.js';
import { Pull, quote } from './lib/scp.js';
import { connect } from './lib/ssh.js';
import { debug, directoryExists, readFromPackage } from './lib/utils.js';
import zip from './lib/zip.js';
/**
* @typedef MessagePayload
* @property {string} event
*/
/**
* main class
*/
export class BagBak extends EventEmitter {
#device;
/**
* @type {import("frida").Application | null}
*/
#app = null;
/**
* @type {import("ssh2").ConnectConfig}
*/
#auth;
/**
* constructor
* @param {import("frida").Device} device
* @param {import("frida").Application} app
*/
constructor(device, app) {
super();
this.#app = app;
this.#device = device;
if ('SSH_USERNAME' in process.env || 'SSH_PASSWORD' in process.env) {
const { SSH_USERNAME, SSH_PASSWORD } = process.env;
if (!SSH_USERNAME || !SSH_PASSWORD)
throw new Error('You have to provide both SSH_USERNAME and SSH_PASSWORD');
this.#auth = {
username: SSH_USERNAME,
password: SSH_PASSWORD
};
} else if ('SSH_PRIVATE_KEY' in process.env) {
throw new Error('key auth not supported yet');
} else {
this.#auth = {
username: 'root',
password: 'alpine'
};
}
}
/**
* scp from remote to local
* @param {string} src
* @param {import("fs").PathLike} dest
*/
async #copyToLocal(src, dest) {
const client = await connect(this.#device, this.#auth);
const pull = new Pull(client, src, dest, true);
const events = ['download', 'mkdir', 'progress', 'done'];
for (const event of events) {
// delegate events
pull.receiver.on(event, (...args) => this.emit(event, ...args));
}
try {
await pull.execute();
} finally {
client.end();
}
}
get bundle() {
return this.#app.identifier;
}
get remote() {
return this.#app.parameters.path;
}
/**
* dump raw app bundle to directory (no ipa)
* @param {import("fs").PathLike} parent path
* @param {boolean} override whether to override existing files
* @param {boolean} abortOnError whether to abort on error
* @returns {Promise<string>}
*/
async dump(parent, override = false, abortOnError = false) {
if (!await directoryExists(parent))
throw new Error('Output directory does not exist');
const launchdSession = await this.#device.attach(1);
const launchdScript = await launchdSession.createScript(
await readFromPackage('agent', 'launchd.js'));
await launchdScript.load();
// for com.apple.private.security.container-manager entitlement
const SpringBoardSession = await this.#device.attach('SpringBoard');
const SpringBoardScript = await SpringBoardSession.createScript(
await readFromPackage('agent', 'SpringBoard.js'));
await SpringBoardScript.load();
// fist, copy directory to local
const remoteRoot = this.remote;
debug('remote root', remoteRoot);
debug('copy to', parent);
const localRoot = join(parent, basename(remoteRoot));
if (await directoryExists(localRoot) && !override)
throw new Error('Destination already exists, use -f to override');
this.emit('sshBegin');
await this.#copyToLocal(remoteRoot, parent);
this.emit('sshFinish');
const visitor = new AppBundleVisitor(localRoot);
await visitor.removeUnwanted();
const map = await visitor.encryptedBinaries();
debug('encrypted binaries', map);
const agentScript = await readFromPackage('agent', 'inject.js');
/**
* @type {Map<string, import("fs/promises").FileHandle>}
*/
const fileHandles = new Map();
/**
* @type {Set<number>}
*/
const childPids = new Set();
// execute dump
for (const [scope, dylibs] of map.entries()) {
const mainExecutable = [remoteRoot, scope].join('/');
debug('main executable =>', mainExecutable);
if (mainExecutable.startsWith('/private/var/containers/Bundle/Application/')) {
SpringBoardScript.exports.chmod(mainExecutable);
}
/**
* @type {number}
*/
let pid;
try {
pid = await launchdScript.exports.spawn(mainExecutable);
} catch (e) {
if (abortOnError) throw e;
console.error(`Failed to spawn executable at ${mainExecutable}, skipping...`);
console.error(`Warning: Unable to dump ${dylibs.map(([path, _]) => path).join('\n')}`);
continue;
}
debug('pid =>', pid);
childPids.add(pid);
/**
* @type {import("frida").Session}
*/
let session;
try {
session = await this.#device.attach(pid);
} catch (e) {
if (abortOnError) throw e;
console.error(`Failed to attach to pid ${pid}, skipping...`);
console.error(`Warning: Unable to dump ${dylibs.map(([path, _]) => path).join('\n')}`);
continue;
}
const script = await session.createScript(agentScript.toString());
script.logHandler = (level, text) => {
debug('[script log]', level, text); // todo: color
};
session.detached.connect((reason, crash) => {
debug('session detached', reason, crash);
});
/**
* @param {function(msg: import("frida").Message, data: ArrayBuffer): void} handler
*/
script.message.connect(async (message, data) => {
if (message.type !== 'send') return;
debug('msg', message, data);
/**
* @type {MessagePayload}
*/
const payload = message.payload;
const key = payload.name;
if (payload.event === 'begin') {
this.emit('patch', key);
debug('patch >>', join(localRoot, key));
const fd = await open(join(localRoot, key), 'r+');
fileHandles.set(key, fd);
} else if (payload.event === 'trunk') {
await fileHandles.get(key).write(data, 0, data.byteLength, payload.fileOffset);
} else if (payload.event === 'end') {
await fileHandles.get(key).close();
fileHandles.delete(key);
}
script.post({ type: 'ack' });
});
await script.load();
const result = await script.exports.newDump(remoteRoot, dylibs);
debug('result =>', result);
await script.unload();
await session.detach();
try {
await this.#device.kill(pid);
} catch(e) {}
}
await SpringBoardScript.unload();
await SpringBoardSession.detach();
// cleanup
for (const pid of childPids) {
const zombieKilled = await launchdScript.exports.cleanup(pid);
debug('kill zombie pid', pid, '=>', zombieKilled ? 'OK' : 'failed');
}
await launchdScript.unload();
await launchdSession.detach();
return localRoot;
}
/**
* dump and pack to ipa. if no name is provided, the bundle id and version will be used
* @param {import("fs").PathLike?} suggested path of ipa
* @returns {Promise<string>} final path of ipa
*/
async pack(suggested) {
const payload = join(tmpdir(), 'bagbak', this.bundle, 'Payload');
await rm(payload, { recursive: true, force: true });
await mkdir(payload, { recursive: true });
await this.dump(payload, true);
debug('payload =>', payload);
const ver = this.#app.parameters.version || 'Unknown';
const defaultTemplate = `${this.bundle}-${ver}.ipa`;
const ipa = suggested ?
(await directoryExists(suggested) ?
join(suggested, defaultTemplate) :
suggested) :
defaultTemplate;
if (!ipa.endsWith('.ipa'))
throw new Error(`Invalid archive name ${suggested}, must end with .ipa`);
const full = resolve(process.cwd(), ipa);
const z = full.slice(0, -4) + '.zip';
await zip(z, payload);
debug('Created zip archive', z);
await rename(z, ipa);
return ipa;
}
}