-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodular-frida-hooking-pattern.js
More file actions
307 lines (268 loc) · 10.5 KB
/
modular-frida-hooking-pattern.js
File metadata and controls
307 lines (268 loc) · 10.5 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
/**
* Modular Frida Script for Pattern-Based Method Hooking
* Designed for penetration testing and reverse engineering
*/
class PatternHooker {
constructor(config = {}) {
this.config = {
logLevel: config.logLevel || 'INFO',
hookTimeout: config.hookTimeout || 100,
maxMatches: config.maxMatches || 50,
enableStackTrace: config.enableStackTrace || false,
enableArgDump: config.enableArgDump || true,
...config
};
this.hooks = new Map();
this.patterns = new Map();
}
log(level, message) {
const levels = { ERROR: 0, WARN: 1, INFO: 2, DEBUG: 3 };
if (levels[level] <= levels[this.config.logLevel]) {
console.log(`[${level}] ${new Date().toISOString()} - ${message}`);
}
}
/**
* Add pattern with metadata
* @param {string} name - Pattern identifier
* @param {string} pattern - Hex pattern (spaces optional)
* @param {Object} options - Hook options
*/
addPattern(name, pattern, options = {}) {
const cleanPattern = pattern.replace(/\s+/g, ' ').trim();
this.patterns.set(name, {
pattern: cleanPattern,
regex: options.regex || null,
description: options.description || name,
onEnter: options.onEnter || this.defaultOnEnter.bind(this),
onLeave: options.onLeave || this.defaultOnLeave.bind(this),
enabled: options.enabled !== false
});
this.log('DEBUG', `Added pattern: ${name} - ${cleanPattern}`);
}
/**
* Default onEnter handler
*/
defaultOnEnter(args, context) {
this.log('INFO', `[${context.patternName}] Method called at ${context.address}`);
if (this.config.enableArgDump) {
// TODO FIX HERE
let argsLength = 0;
try {
argsLength = args.length || 0;
} catch (e) {
this.log('DEBUG', ' Cannot determine args length, skipping argument dump');
return;
}
for (let i = 0; i < Math.min(argsLength, 6); i++) {
try {
const arg = args[i];
let argInfo = `x${i}: ${arg}`;
// Try to read as string
if (arg && !arg.isNull()) {
try {
const str = Memory.readUtf8String(arg, 100);
if (str && str.length > 0 && /^[\x20-\x7E]*$/.test(str)) {
argInfo += ` ("${str}")`;
}
} catch (e) {
// Try as pointer
try {
const ptr = Memory.readPointer(arg);
argInfo += ` (ptr: ${ptr})`;
} catch (e2) {
// Just show raw value
}
}
}
this.log('INFO', ` ${argInfo}`);
} catch (e) {
this.log('DEBUG', ` x${i}: <unreadable>`);
}
}
}
if (this.config.enableStackTrace) {
this.log('DEBUG', 'Stack trace:');
Thread.backtrace(this.context(), Backtracer.ACCURATE)
.map(DebugSymbol.fromAddress)
.forEach(symbol => this.log('DEBUG', ` ${symbol}`));
}
}
/**
* Default onLeave handler
*/
defaultOnLeave(retval, context) {
this.log('INFO', `[${context.patternName}] Return value: ${retval}`);
}
/**
* Hook a specific method by address
*/
hookMethod(address, patternName, patternConfig) {
if (this.hooks.has(address.toString())) {
this.log('WARN', `Address ${address} already hooked`);
return;
}
try {
const self = this; // Capture reference for closure
const hook = Interceptor.attach(address, {
onEnter: function(args) {
const context = {
address: address.toString(),
patternName: patternName,
timestamp: Date.now()
};
// Store context in a way that works with Frida's Interceptor
this.hookContext = context;
patternConfig.onEnter.call(this, args, context);
},
onLeave: function(retval) {
// Retrieve context from the stored property
const context = this.hookContext || {
address: address.toString(),
patternName: patternName,
timestamp: Date.now()
};
patternConfig.onLeave.call(this, retval, context);
}
});
this.hooks.set(address.toString(), {
hook: hook,
patternName: patternName,
address: address.toString()
});
this.log('INFO', `[${patternName}] Hooked method at ${address}`);
} catch (e) {
this.log('ERROR', `Failed to hook ${address}: ${e.message}`);
}
}
/**
* Search for patterns in memory ranges
*/
searchPatterns(rangeFilter = null) {
this.log('INFO', 'Starting pattern search...');
const ranges = Process.enumerateRangesSync('r-x').filter(range => {
if (rangeFilter) {
return rangeFilter(range);
}
return range.size > 0x1000; // Skip small ranges
});
this.log('INFO', `Scanning ${ranges.length} memory ranges`);
let totalMatches = 0;
for (const [patternName, patternConfig] of this.patterns) {
if (!patternConfig.enabled) continue;
this.log('DEBUG', `Searching for pattern: ${patternName}`);
let patternMatches = 0;
for (const range of ranges) {
try {
const matches = Memory.scanSync(range.base, range.size, patternConfig.pattern);
for (const match of matches) {
if (totalMatches >= this.config.maxMatches) {
this.log('WARN', `Reached maximum matches limit (${this.config.maxMatches})`);
return totalMatches;
}
// Apply regex filter if specified
if (patternConfig.regex) {
const symbol = DebugSymbol.fromAddress(match.address);
if (!patternConfig.regex.test(symbol.name || '')) {
continue;
}
}
this.log('INFO', `[${patternName}] Pattern found at: ${match.address} (${range.file?.path || 'unknown'})`);
this.hookMethod(match.address, patternName, patternConfig);
patternMatches++;
totalMatches++;
}
} catch (e) {
this.log('DEBUG', `Error scanning range ${range.base}: ${e.message}`);
}
}
this.log('INFO', `[${patternName}] Found ${patternMatches} matches`);
}
this.log('INFO', `Pattern search complete. Total matches: ${totalMatches}`);
return totalMatches;
}
/**
* Remove all hooks
*/
unhookAll() {
this.log('INFO', 'Removing all hooks...');
for (const [address, hookInfo] of this.hooks) {
try {
hookInfo.hook.detach();
this.log('DEBUG', `Unhooked ${hookInfo.patternName} at ${address}`);
} catch (e) {
this.log('ERROR', `Failed to unhook ${address}: ${e.message}`);
}
}
this.hooks.clear();
}
/**
* Get statistics
*/
getStats() {
return {
totalPatterns: this.patterns.size,
enabledPatterns: Array.from(this.patterns.values()).filter(p => p.enabled).length,
activeHooks: this.hooks.size,
patterns: Object.fromEntries(this.patterns)
};
}
}
// Export for use
const hooker = new PatternHooker({
logLevel: 'INFO',
enableStackTrace: false,
enableArgDump: true,
maxMatches: 100
});
// Example usage patterns
function setupCommonPatterns() {
// Password-related patterns
hooker.addPattern('CFG_GetLicenseAccountPassword',
'f4 4f be a9 fd 7b 01 a9 fd 43 00 91 f3 03 00 aa dc c2 1d 94',
{
description: 'Pattern for CFG_GetLicenseAccountPassword',
onEnter: function(args, context) {
console.log('[CFG_GetLicenseAccountPassword] Hooked!');
hooker.defaultOnEnter.call(this, args, context);
},
onLeave: function(retval, context) {
const passwordString = ObjC.Object(retval).toString();
console.log(`Password: ${retval.toString()}`);
console.log(`Password: ${retval}`);
hooker.defaultOnLeave.call(this, retval, context);
}
}
);
hooker.addPattern('CFG_GetLicenseAccountUsername',
'f4 4f be a9 fd 7b 01 a9 fd 43 00 91 f3 03 00 aa f9 c2 1d 94',
{
description: 'Pattern for CFG_GetLicenseAccountUsername',
onEnter: function(args, context) {
console.log('[CFG_GetLicenseAccountUsername] Hooked!');
hooker.defaultOnEnter.call(this, args, context);
},
onLeave: function(retval, context) {
const usernameString = ObjC.Object(retval).toString();
console.log(`Username: ${retval}`);
hooker.defaultOnLeave.call(this, retval, context);
}
}
);
}
// Main execution - No Java.perform needed for native/iOS
function initializeHooker() {
setupCommonPatterns();
setTimeout(() => {
const matches = hooker.searchPatterns();
console.log(`[SUMMARY] Setup complete. Found ${matches} matches.`);
console.log('[STATS]', JSON.stringify(hooker.getStats(), null, 2));
}, hooker.config.hookTimeout);
}
// Auto-initialize
initializeHooker();
// Global functions for interactive use
globalThis.hooker = hooker;
globalThis.addPattern = hooker.addPattern.bind(hooker);
globalThis.searchPatterns = hooker.searchPatterns.bind(hooker);
globalThis.unhookAll = hooker.unhookAll.bind(hooker);
globalThis.getStats = hooker.getStats.bind(hooker);