-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathextract.js
220 lines (175 loc) · 6.44 KB
/
extract.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
const fs = require('fs');
const zlib = require('zlib');
const crypto = require('crypto');
const readline = require('readline');
console.log('\n\x1b[1mAndroid Backup Extractor\x1b[0m\n');
// Get the backup file name from the command line arguments
const args = process.argv.slice(2);
if (args.length < 2) {
console.error('Usage: adb_extract.exe <backup.ab> <output.tar> [password]');
process.exit(1);
}
async function extractAsTar(backupFilename, outputFile, password) {
try {
// Check if the backup file exists
if (!fs.existsSync(backupFilename)) {
throw new Error(`Backup file does not exist: ${backupFilename}`);
}
console.log(`Input File: ${backupFilename.split('\\').pop().split('/').pop()}`);
/* console.log(`Output File: ${outputFile.split('\\').pop().split('/').pop()}\n`); */
if (fs.statSync(backupFilename).size === 0) {
throw new Error("File too small in size");
}
const fileSize = fs.statSync(backupFilename).size;
const headerData = await readHeaderData(backupFilename);
const magicStr = headerData[0];
if (magicStr !== 'ANDROID BACKUP') {
throw new Error(`Invalid magic string: ${magicStr}`);
}
const versionStr = headerData[1];
console.log(`File Version: ${versionStr}`);
const version = parseInt(versionStr, 10);
if (version < 1 || version > 5) {
throw new Error(`Don't know how to process version ${versionStr}`);
}
const compressedStr = headerData[2];
const isCompressed = parseInt(compressedStr, 10) === 1;
console.log(`Compressed: ${isCompressed}`);
const encryptionStr = headerData[3];
console.log(`Encryption: ${encryptionStr}`);
let isEncrypted = encryptionStr === 'AES-256';
// Calculate header data length to use as the data offset
// Length of each headerData line + 1 for the 0x0A line break
let offset = 0;
for (let i = 0; i < headerData.length; i++) {
offset += headerData[i].length + 1;
}
console.log(`Header length: ${offset} bytes`);
// Log backup file size in MB
console.log(`Backup size: ${Math.round(fileSize / 1024 / 1024)} MB`);
console.log(`\n\x1b[32mBackup file appears to be valid!\x1b[0m`);
//process.exit(0);
let rawInStream = fs.createReadStream(backupFilename, { start: offset });
const baseStream = isEncrypted ? await decryptBackup(rawInStream, headerData, password) : rawInStream;
const outStream = fs.createWriteStream(outputFile);
let streamToWrite = baseStream;
let inflate;
if (isCompressed) {
inflate = zlib.createInflate();
inflate.on('error', (err) => {
console.error('\n\nError: ' + err.message);
console.log(`\x1b[31m\x1b[1m✗ Something went wrong while unpacking. The backup file may be corrupted.\x1b[0m`);
process.exit(1);
});
streamToWrite = baseStream.pipe(inflate);
}
console.log(`\nCreating \x1b[3m${outputFile.split('\\').pop().split('/').pop()}\x1b[0m, please wait...\n`);
const progressChunk = '░';
const progressCompleteChunk = '█';
const progressBar = {
update: function (value) {
const progress = Math.round((value / fileSize) * 100);
const totalChunks = 40;
const completeChunks = Math.round((progress / 100) * totalChunks);
const incompleteChunks = 40 - completeChunks;
const progressStr = progressCompleteChunk.repeat(completeChunks) + progressChunk.repeat(incompleteChunks);
process.stdout.write(`\r\x1b[2K\x1b[36m${progressStr} \x1b[0m${progress}% `);
},
stop: function () {
process.stdout.write('\n');
}
};
streamToWrite.on('data', (chunk) => {
outStream.write(chunk);
progressBar.update(inflate.bytesWritten);
});
streamToWrite.on('end', () => {
outStream.end();
progressBar.stop();
console.log(`\n\x1b[32m\x1b[1m✓ Backup extraction complete!\x1b[0m`);
process.exit(0);
});
} catch (e) {
throw e;
}
}
async function decryptBackup(rawInStream, headerData, password) {
async function askForPassword() {
const readInput = readline.createInterface({
input: process.stdin,
output: process.stdout
});
console.log(`\n\x1b[33mBackup is encrypted. Please enter the password to decrypt.\x1b[0m`)
password = await new Promise((resolve) => {
readInput.question(`\n\x1b[1mPassword: \x1b[0m`, userInput => {
readInput.close();
resolve(userInput);
});
});
readline.moveCursor(process.stdout, 0, -4);
readline.clearScreenDown(process.stdout);
}
if (!password) await askForPassword();
const userSalt = Buffer.from(headerData[4], 'hex');
if (userSalt.length !== 64) {
throw new Error(`Invalid salt length: ${userSalt.length}`);
}
//const ckSalt = Buffer.from(headerData[5], 'hex');
const rounds = parseInt(headerData[6], 10);
const iv = Buffer.from(headerData[7], 'hex');
const mkCipher = Buffer.from(headerData[8], 'hex');
const userKey = crypto.pbkdf2Sync(password, userSalt, rounds, 32, 'sha1');
const decipher = crypto.createDecipheriv('aes-256-cbc', userKey, iv);
let mkBlob = null;
try {
mkBlob = Buffer.concat([decipher.update(mkCipher), decipher.final()]);
} catch (e) {
console.log(`\n\x1b[31m\x1b[1m✗ Incorrect password. Please try again.\x1b[0m`);
return await decryptBackup(rawInStream, headerData);
}
console.log(`\n\x1b[32mBackup decrypted!\x1b[0m`);
let offset = 0;
let len = mkBlob[offset++];
const mkIv = mkBlob.subarray(offset, offset + len);
offset += len;
len = mkBlob[offset++];
const mk = mkBlob.subarray(offset, offset + len);
const masterDecipher = crypto.createDecipheriv('aes-256-cbc', mk, mkIv);
return rawInStream.pipe(masterDecipher);
}
async function readHeaderData(filename) {
return new Promise((resolve, reject) => {
const readStream = fs.createReadStream(filename);
const reader = readline.createInterface({
input: readStream,
crlfDelay: Infinity
});
let maxLinesToRead = 4;
let linesRead = 0;
let dataRead = [];
// Read data until the next line break (0x0A)
reader.on('line', (line) => {
if (linesRead >= maxLinesToRead) {
reader.close();
readStream.destroy();
} else {
if (linesRead === 3 && line === 'AES-256') {
// If the backup is encrypted, there are more lines containing encryption data
maxLinesToRead = 9;
}
dataRead.push(line);
linesRead++;
}
});
reader.on('close', () => resolve(dataRead));
reader.on('error', (err) => reject(err));
});
}
(async () => {
try {
await extractAsTar(args[0], args[1], args[2]);
} catch (error) {
console.error(`\n\x1b[31m${error.message}\n\n\x1b[1m✗ Something went wrong!\x1b[0m\n`);
//console.log(`\x1b[31m\x1b[1m✗ Something went wrong!\x1b[0m`);
}
})();