Repository navigation
Expand file tree
/
Copy pathengine.js
More file actions
7776 lines (7216 loc) · 344 KB
/
Copy pathengine.js
File metadata and controls
7776 lines (7216 loc) · 344 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* frida-hook-engine.js
*
* Author / Project:
* Author: MuhammadRizwan from India
* Repository: https://github.com/muhammadrizwan87/frida-hook-engine
* License: Apache-2.0
* Issues: https://github.com/muhammadrizwan87/frida-hook-engine/issues
*
* Companion projects:
* keysigner https://github.com/muhammadrizwan87/keysigner
* APK signing tool
* frida-bridge https://github.com/muhammadrizwan87/frida-bridge
* Native loader for container / virtual-space environments
*
* Built on Frida (https://frida.re) by Ole André Vadla Ravnås and
* contributors.
*
* Purpose:
* A configuration-driven Android instrumentation engine for Frida.
* Supports three deployment modes from a single codebase:
*
* - Gadget, Script interaction mode. Loaded via
* libfrida-gadget.config.so; hook definitions and feature toggles
* are externalized to that config, so no recompilation is needed
* when targets or behaviors change. This is the primary mode.
*
* - Frida CLI, attach / spawn. Loaded directly with
* `frida -U -f <pkg> -l this-file.js`. No config file exists in
* this mode, so every toggle uses its source-level default
* declared in this file.
*
* - Gadget, Listen mode. Pre-built agent driven from a live Frida
* REPL controller. Parameters may be supplied via
* rpc.exports.init(); absent keys fall back to source defaults.
*
* Return-type coverage:
* void; primitives (boolean, byte, short, int, long, float, double);
* java.lang.String; object types and arrays (passthrough).
*
* Configuration-flag pattern:
* Every toggle exposed via parameters is declared as a module-level
* variable with a source-level default, annotated with the parameter
* key that overrides it at init(). This lets the same defaults apply
* in every deployment mode — under Gadget Script mode they are a
* baseline that the config overrides per-key; under CLI attach and
* Listen mode (or any invocation without Gadget-supplied parameters)
* they are the effective values directly. Editing a literal default
* in this file and reloading is therefore sufficient to change a
* behavior without any config edit.
*/
'use strict';
// This file ships in two forms:
// - As-is (this file): plain script, no import. Load directly via
// Frida CLI (`frida -U -f <pkg> -l engine.js`) or Gadget Listen
// mode. `Java` is provided as a runtime global in both cases.
// - As a compiled agent (agent.js, shipped alongside): produced by
// uncommenting the import below, running frida-compile, then
// re-commenting. End users never perform this step — they use the
// pre-built agent.js with Gadget's Script interaction mode.
// Uncomment ONLY during your own release build:
// import Java from 'frida-java-bridge';
// ════════════════════════════════════════════════
// C O N F I G U R A T I O N
// ════════════════════════════════════════════════
// ------------------------------------------------------------------
// Configuration flags (module-level defaults, overridden in init())
//
// Every toggle below has a source-level default declared here, and is
// optionally overridden at init() time by a matching key in Gadget's
// `interaction.parameters` object (libfrida-gadget.config.so). This
// lets the same script run under three deployment styles:
//
// 1. Gadget + config file (recommended for iterative work):
// flags and value maps are driven entirely by
// libfrida-gadget.config.so; nothing in this file needs editing.
//
// 2. Direct-script use — frida CLI attach (`frida -U -f <pkg> -l
// this-script.js`), Gadget without a config file, or any other
// invocation that supplies no parameters: every flag uses the
// default declared below. To enable a module, edit its default
// from `false` to `true` in this file and recompile with
// frida-compile.
//
// 3. Hybrid: defaults here act as a baseline; config overrides
// only the keys it explicitly sets. A parameter key present in
// config always wins over the source-level default; a key
// absent from config leaves the default intact.
//
// Naming convention: booleans end in `Enabled` and gate a module; the
// companion `*Values` object immediately below (when present) supplies
// that module's runtime values and is ignored while its flag is false.
//
// The three config-driven arrays (defaultJavaHooks, nativeHooks,
// nativePatches) carry their full schema and examples inline at each
// declaration below.
// ------------------------------------------------------------------
/** Enables logcat output for this engine. Overridden by parameters.debugLog. */
let debugLoggingEnabled = false;
/** Enables the installer-source spoofing module. Overridden by parameters.installerSpoofEnabled. */
let installerSpoofEnabled = false;
/** Enables the ADB / Developer Options detection bypass module. Overridden by parameters.adbDevSettingsBypassEnabled. */
let adbDevSettingsBypassEnabled = false;
/** Enables the mock-location detection bypass module. Overridden by parameters.mockLocationBypassEnabled. */
let mockLocationBypassEnabled = false;
/** Enables the auto-time / auto-timezone spoofing module — forces Settings.Global "auto_time" and "auto_time_zone" to always report "1" (automatic mode). Apps reading these keys see a device whose clock is not manually managed, a common tamper-detection signal. Overridden by parameters.autoTimeSpoofEnabled. */
let autoTimeSpoofEnabled = false;
/** Enables the PairIP license-check NOP module — replaces com.pairip.licensecheck.LicenseClient.bindToLicensingService(boolean) with an empty implementation; this prevents the app from binding to the PairIP licensing service. Provided as a dedicated toggle (rather than a javaHooks entry) because the target is fixed and the config surface stays minimal. Overridden by parameters.pairipLicenseBypassEnabled. */
let pairipLicenseBypassEnabled = false;
/** Enables the FLAG_SECURE screenshot/screen-recording restriction bypass module. Overridden by parameters.flagSecureBypassEnabled. */
let flagSecureBypassEnabled = false;
/** Enables the VPN/proxy detection bypass module. Overridden by parameters.vpnProxyBypassEnabled. */
let vpnProxyBypassEnabled = false;
/** Enables the SSL/TLS certificate-pinning bypass module. Covers two independent layers: the Android Java/Kotlin TLS stack (SSLContext, TrustManagerFactory, HttpsURLConnection, OkHttp CertificatePinner, Android Network Security Config, TrustKit, Appmattus CT) and the native Flutter/BoringSSL bypass for libflutter.so when that module is loaded. Overridden by parameters.sslPinningBypassEnabled. */
let sslPinningBypassEnabled = false;
/** Enables the geo-restriction bypass module (carrier/network identity). Overridden by parameters.geoRestrictionBypassEnabled. */
let geoRestrictionBypassEnabled = false;
/** Carrier/network identity values used by the geo-restriction bypass module. Overridden per-key by parameters.geoSpoofValues. */
let geoSpoofValues = {
operatorName: "AT&T",
plmn: "310410",
countryIso: "us"
};
/** Enables the locale/timezone spoofing module. Overridden by parameters.localeSpoofEnabled. */
let localeSpoofEnabled = false;
/** Locale/timezone values used by the locale spoofing module. Overridden per-key by parameters.localeSpoofValues. */
let localeSpoofValues = {
country: "US",
language: "en",
timezoneId: "America/New_York"
};
/** Enables the suspicious-package (root/patcher/Xposed/emulator) hiding module. Overridden by parameters.suspiciousPackageSpoofEnabled. */
let suspiciousPackageSpoofEnabled = false;
/** Suspicious package names to hide. Overridden by parameters.suspiciousPackagesCustom. */
let suspiciousPackagesCustom = [
"bin.mt.plus",
"com.network.proxy",
"com.termux"
];
/** Enables the fake-installed-package module — makes listed packages appear installed across PackageManager lookups and enumeration, even though they aren't actually present on the device. The inverse of suspiciousPackageSpoofEnabled. Overridden by parameters.installedPackageSpoofEnabled. */
let installedPackageSpoofEnabled = false;
/** Per-package fabricated identity for the fake-installed-package module. Keys are package names; values are optional-field config objects (all fields strings). Overridden (per-package, per-field) by parameters.installedPackageSpoofValues. */
let installedPackageSpoofValues = {
"com.android.vending": {
"versionName": "53.3.21-34 [0] [PR] 986224237",
"versionCode": "85332140",
"uid": "10159",
"isSystem": "true"
},
"com.google.android.gms": {
"versionName": "26.34.36 (260400-981326859)",
"versionCode": "263436035",
"uid": "14134",
"isSystem": "true"
},
"com.google.android.gsf": {
"versionName": "14134",
"versionCode": "36",
"uid": "14134",
"isSystem": "true"
}
};
/** Enables the device-identifier spoofing module. Overridden by parameters.deviceIdSpoofEnabled. */
let deviceIdSpoofEnabled = false;
/** Selects randomly-generated values over deviceIdSpoofValues. Overridden by parameters.deviceIdSpoofUseRandom. */
let deviceIdSpoofUseRandom = false;
/** Fixed device-identifier values, used when deviceIdSpoofUseRandom is false. Overridden per-key by parameters.deviceIdSpoofValues. */
let deviceIdSpoofValues = {
androidId: "a1b2c3d4e5f6a7b8",
imei: "356938035643809",
meid: "A1000012B3C456",
iccid: "89014103211118510720",
imsi: "310260123456789",
phoneNumber: "+15555215556",
wifiMac: "3C:5A:B4:1E:2F:8D",
bluetoothMac: "AC:37:43:2B:9C:14",
advertisingId: "38400000-8cf0-11bd-b23e-10b96e40000d",
internalIp: "192.168.1.42"
};
/** Enables the build-prop (Tier-A device-identity) spoofing module. Overridden by parameters.buildPropSpoofEnabled. */
let buildPropSpoofEnabled = false;
/** Tier-A device-identity field values. Overridden per-key by parameters.buildPropSpoofValues. */
let buildPropSpoofValues = {
manufacturer: "Google",
model: "Pixel 7 Pro",
brand: "google",
product: "cheetah",
device: "cheetah",
hardware: "cheetah",
board: "cheetah",
bootloader: "unknown",
host: "android-build",
id: "AP4A.241205.013",
fingerprint: "google/cheetah/cheetah:15/AP4A.241205.013/12621605:user/release-keys",
tags: "release-keys",
type: "user",
user: "android-build",
display: "AP4A.241205.013",
release: "15",
securityPatch: "2024-12-05",
incremental: "12621605",
codename: "REL"
};
/** Enables the SystemProperties spoofing module. Overridden by parameters.systemPropertySpoofEnabled. */
let systemPropertySpoofEnabled = false;
/** Spoofed system-property key/value map (open-ended — any ro., persist., or qemu. key may be added). Overridden per-key by parameters.systemPropertySpoofValues. */
let systemPropertySpoofValues = {
"ro.boot.verifiedbootstate": "green",
"ro.boot.flash.locked": "1",
"ro.oem_unlock_supported": "0",
"ro.secureboot.lockstate": "locked",
"ro.kernel.qemu": "0",
"ro.boot.qemu": "0",
"ro.hardware": "cheetah",
"ro.secure": "1",
"ro.debuggable": "0",
"ro.allow.mock.location": "0",
"qemu.hw.mainkeys": "1"
};
/** Enables the hardware-feature spoofing module. Overridden by parameters.hardwareFeatureSpoofEnabled. */
let hardwareFeatureSpoofEnabled = false;
/** Feature strings PackageManager.hasSystemFeature() reports as present regardless of actual state. Overridden by parameters.spoofedHardwareFeatures. */
let spoofedHardwareFeatures = [
"android.hardware.telephony",
"android.hardware.camera",
"android.hardware.camera.any",
"android.hardware.camera.front",
"android.hardware.sensor.accelerometer",
"android.hardware.sensor.gyroscope",
"android.hardware.sensor.proximity",
"android.hardware.bluetooth",
"android.hardware.nfc",
"android.hardware.fingerprint",
"android.hardware.wifi"
];
/** Enables the ContentResolver.query()/call() spoofing module (Settings + GSF providers). Overridden by parameters.contentProviderSpoofEnabled. */
let contentProviderSpoofEnabled = false;
/** Per-authority key/value maps ContentResolver.query()/call() spoofing draws from. The "settings" authority's map is merged with the ADB/mock-location/android_id keys derived from other flags at apply time — see its construction in init(). Overridden (per-authority, per-key) by parameters.contentProviderSpoofValues. */
let contentProviderSpoofValues = {
settings: {
development_settings_enabled: "0",
adb_enabled: "0",
mock_location: "0",
android_id: "a1b2c3d4e5f6a7b8"
},
"com.google.android.gsf.gservices": {
android_id: "3f9d0a2b4c5e6f71"
}
};
/** Enables the config-driven Java hooking module. Overridden by parameters.javaHooksEnabled. */
let javaHooksEnabled = false;
/**
* Default config-driven Java hook definitions, used when
* parameters.javaHooks is absent or invalid — e.g. under Listen mode,
* where no Gadget-supplied parameters exist. Overridden by
* parameters.javaHooks.
*
* Each entry hooks one overload of one Java method. Multiple overloads
* require multiple entries. Entries install with bounded retry (10
* attempts at 500 ms), scheduled via setTimeout so app startup is
* never blocked.
*
* Schema (per entry):
* className REQUIRED unless rawSignature is given — fully-
* qualified Java name with dots, e.g. "com.example.Foo"
* (never JNI form "Lcom/...").
* methodName REQUIRED unless rawSignature is given — exact method
* name as declared. Use "$init" for a constructor and
* "classInitializer" for a static initializer (Frida's
* own names for <init>/<clinit>; rawSignature maps
* these automatically).
* rawSignature OPTIONAL — alternative to supplying className/
* methodName/argTypes/returnType individually: a raw
* JNI/smali method descriptor exactly as shown by
* jadx/MT Manager, e.g.
* "Lcom/example/Foo;->bar(Ljava/lang/String;I)Z".
* Parsed once at config-load time into the four fields
* above — slash->dot class names, JNI primitive
* letters mapped to their Java word form, "<init>"/
* "<clinit>" mapped to "$init"/"classInitializer". Any
* of those four fields given explicitly on the same
* entry wins over the value parsed from rawSignature
* for that field; onCall is unaffected either way.
* argTypes OPTIONAL — required when the method has multiple
* overloads. Omitting the key entirely hooks every
* overload with one implementation (warned about when
* more than one exists); passing [] explicitly instead
* targets that method's own zero-arg overload — the
* two are not treated the same, which matters for
* constructors in particular (a class commonly has
* both a zero-arg and a parameterized one). Java
* source form for primitives ("boolean", "int",
* "long"); JNI form for arrays ("[B",
* "[Ljava.lang.String;"). JNI primitive forms ("Z",
* "I") are NOT accepted here — use the word forms.
* returnType OPTIONAL — used only to coerce forceReturn and to
* detect void; not used by overload resolution.
* Accepts both word form ("void", "int") and JNI
* primitive form ("V", "I"); arrays use JNI form.
* onCall OPTIONAL — absent = observe only (original runs).
* Sub-keys:
* logArgs log every arg with its declared type
* logReturn log the original return
* modifyArgs { "<0-based idx>": <value> } — args
* coerced via argTypes[idx]
* nop skip the original implementation
* forceReturn override the return (applied after
* the original unless nop is also set)
*
* Pairing rules:
* nop + non-void + no forceReturn → returns undefined at the JNI
* boundary; supply forceReturn instead.
* modifyArgs without nop → original still runs and sees the
* modified args.
* forceReturn without nop → original runs (side effects happen);
* only the return value is overridden.
* nop on a constructor ($init) skips the original constructor body
* entirely — including any super() call it would have made — which
* can leave the object only partially initialized; prefer
* forceReturn-free observation or modifyArgs on constructors unless
* you specifically intend to replace construction.
*
* Examples (edit and place inside the array literal):
*
* // Silence a void method call:
* { className: 'com.example.Logger', methodName: 'writeLog',
* argTypes: ['java.lang.String'], returnType: 'void',
* onCall: { logArgs: true, nop: true } },
*
* // Bypass a boolean check (single overload — argTypes omitted):
* { className: 'com.example.RootChecker', methodName: 'isDeviceRooted',
* returnType: 'boolean',
* onCall: { logReturn: true, nop: true, forceReturn: false } },
*
* // Return a spoofed String:
* { className: 'com.example.Utils', methodName: 'getDeviceId',
* argTypes: [], returnType: 'java.lang.String',
* onCall: { logReturn: true,
* forceReturn: '00000000-0000-0000-0000-000000000000' } },
*
* // Modify one argument then force the return (multi-overload —
* // argTypes required to disambiguate):
* { className: 'com.example.LicenseManager', methodName: 'isValidLicense',
* argTypes: ['java.lang.String', 'int'], returnType: 'boolean',
* onCall: { logArgs: true, logReturn: true,
* modifyArgs: { '1': 9999 }, forceReturn: true } },
*
* // Same hook as above, pasted straight from jadx's smali view
* // instead of hand-translated — equivalent to the entry above:
* { rawSignature: 'Lcom/example/LicenseManager;->isValidLicense(Ljava/lang/String;I)Z',
* onCall: { logArgs: true, logReturn: true,
* modifyArgs: { '1': 9999 }, forceReturn: true } },
*
* // Log every call to a specific constructor (zero-arg only — note
* // argTypes: [] below targets just that overload, not every
* // constructor this class has):
* { rawSignature: 'Lcom/example/App;-><init>()V',
* onCall: { logArgs: true } }
*/
let defaultJavaHooks = [];
/** Enables the config-driven native (.so-level) hooking module. Overridden by parameters.nativeHooksEnabled. */
let nativeHooksEnabled = false;
/**
* Native hook definitions — see resolveTargetAddress() /
* applyTypedNativeHook() / applyRawNativeHook() for the runtime
* implementation. Overridden by parameters.nativeHooks.
*
* Two modes, selected per entry:
* Typed mode — both argTypes AND returnType present. Full type
* safety, chains to the original via NativeFunction,
* supports onCall.nop.
* Raw mode — otherwise. Pointer-sized args/return only. onCall.nop
* is ignored with a warning (attach cannot skip the
* call it observes).
*
* Schema (per entry):
* moduleName REQUIRED — e.g. "libc.so", "libtarget.so". Must
* already be loaded when the hook is installed.
* Target locator REQUIRED — exactly ONE of:
* symbolName exported symbol name (ASLR-safe; best choice)
* offset hex string offset from module base, e.g.
* "0x1234" (ASLR-safe; use for non-exported
* functions located via reverse engineering)
* absoluteAddress raw pointer (NOT ASLR-safe; testing only)
* argTypes typed mode only. Array of Frida native type
* strings: "void" "bool" "int8" "uint8" "int16"
* "uint16" "int32" "uint32" "int64" "uint64" "int"
* "uint" "char" "uchar" "float" "double" "pointer".
* returnType typed mode only. Single type from the list above.
* onCall OPTIONAL. Same sub-keys as javaHooks, except that
* modifyArgs values are coerced via argTypes and
* forceReturn via returnType, both using Frida
* native type rules. int64 / uint64 values should
* be supplied as strings for anything beyond 2^53.
* rawArgCount OPTIONAL, raw mode only (ignored in typed mode,
* which already knows its arity from argTypes). How
* many pointer-sized arg slots onCall.logArgs logs.
* Non-negative integer; defaults to 4 if omitted.
*
* Examples (edit and place inside the array literal):
*
* // Typed — void return, no args (observe only):
* { moduleName: 'libc.so', symbolName: 'srand',
* argTypes: [], returnType: 'void',
* onCall: { logArgs: true } },
*
* // Typed — int return forced to 1 (original still runs):
* { moduleName: 'libtarget.so', offset: '0x1234',
* argTypes: ['int'], returnType: 'int',
* onCall: { logArgs: true, forceReturn: 1 } },
*
* // Raw — pointer-sized observe only (no argTypes/returnType):
* { moduleName: 'libc.so', symbolName: 'malloc',
* onCall: { logArgs: true, logReturn: true } }
*/
let nativeHooks = [];
/** Enables the native code-patching module (Memory.patchCode()). Overridden by parameters.nativePatchesEnabled. */
let nativePatchesEnabled = false;
/**
* Native patch definitions — see applyNativePatches() for the runtime
* implementation. Overridden by parameters.nativePatches.
*
* Direct instruction-byte edits at a specific address — not a function
* hook. The engine cannot validate that the bytes are well-formed for
* the target CPU architecture; a malformed patch can corrupt execution.
* Original bytes are captured before patching and restored verbatim on
* revert.
*
* Schema (per entry):
* moduleName REQUIRED — same rule as nativeHooks.
* Target locator REQUIRED — exactly ONE of symbolName / offset /
* absoluteAddress (same rules as nativeHooks).
* patchBytes REQUIRED — accepts two equivalent forms:
* ['1F', '20', '03', 'D5'] array of 2-char hex
* byte strings
* '1F2003D5' single concatenated
* hex string
* The string form must be non-empty and even-length;
* a malformed string is rejected before any memory
* is written, so no partial patch is ever applied.
*
* Common ARM64 idioms:
* NOP 1F 20 03 D5
* RET C0 03 5F D6
* MOV W0, #0 ; RET 00 00 80 D2 C0 03 5F D6
* MOV W0, #1 ; RET 20 00 80 52 C0 03 5F D6
*
* Examples (edit and place inside the array literal):
*
* // NOP — array form:
* { moduleName: 'libtarget.so', offset: '0x2A10',
* patchBytes: ['1F', '20', '03', 'D5'] },
*
* // MOV W0,#1 ; RET — array form:
* { moduleName: 'libtarget.so', offset: '0x5678',
* patchBytes: ['20', '00', '80', '52', 'C0', '03', '5F', 'D6'] },
*
* // MOV W0,#1 ; RET — string form (equivalent to the array above):
* { moduleName: 'libtarget.so', offset: '0x5678',
* patchBytes: '20008052C0035FD6' }
*/
let nativePatches = [];
/**
* Enables the RegisterNatives discovery/logging module.
* Overridden by parameters.registerNativesLogEnabled.
*
* Credit: Module concept and implementation contributed by Marc Nin (@mragonias).
*/
let registerNativesLogEnabled = false;
/**
* Class names to restrict logging to; empty (the default) logs every
* RegisterNatives call process-wide — including system/Play Services
* libraries, not only the target app, which can be noisy.
* Overridden by parameters.registerNativesLogClassFilter.
*/
let registerNativesLogClassFilter = [];
/**
* Optional manual override for locating RegisterNatives in libart.so,
* for when the default symbol-name heuristic in applyRegisterNativesLog()
* finds zero matches (symbols stripped on this build) or more than one
* candidate (picks the wrong one for this ART version). Exactly one of
* symbolName/offset is used if set; both empty means "use the heuristic".
* Overridden per-key by parameters.registerNativesLogLocator.
*/
let registerNativesLogLocator = { symbolName: "", offset: "" };
/** Enables the camera-input mock module — Layer 1 (intent-based capture redirect) and Layer 2 (Camera2 in-process still-capture substitution). Overridden by parameters.cameraMockEnabled. */
let cameraMockEnabled = false;
/** Configuration values for the camera-mock module. Overridden per-key by parameters.cameraMockValues. See resolveTypedMap() for merge semantics. */
let cameraMockValues = {
layer1Enabled: true,
layer2Enabled: true,
// Substitution source image. Accepted forms (see normalizeSourceUri()):
// 'placeholder' -> synthesized placeholder JPEG (default)
// '/sdcard/Pictures/mock.jpg' -> plain absolute file path (no prefix needed;
// normalizeSourceUri() adds 'file://' itself)
// 'file:///sdcard/Pictures/mock.jpg' -> explicit file:// URI (also accepted as-is)
// 'content://media/external/images/media/123' -> content:// URI (also accepted as-is)
// A bare path MUST start with '/' (absolute). Relative paths (e.g. 'mock.jpg') are
// rejected at runtime with a warning - there is no implied base directory.
jpegSource: 'placeholder',
toastOnReady: true,
toastReadyText: 'cam-mock: ready',
toastOnFailure: true,
toastFailText: 'cam-mock: NOT READY - real image will be captured',
};
// ════════════════════════════════════════════════
// E N D C O N F I G U R A T I O N
// ════════════════════════════════════════════════
// ------------------------------------------------------------------
// Logging
//
// Dual-output routing:
// 1. console.log() — visible immediately in the terminal for users
// running via Frida CLI (spawn/attach) or Gadget Listen mode.
// 2. android.util.Log — visible via `adb logcat -s FridaHookEngine:V`
// for users running in Gadget Script mode (no attached controller).
//
// Both are fired simultaneously. The android.util.Log call is wrapped
// in a try/catch because Java.use() requires VM access; if a log fires
// before the VM is fully attached during early startup, the console.log
// above it still guarantees the message is emitted to any attached
// controller, preventing silent failures.
// ------------------------------------------------------------------
const LOG_TAG = 'FridaHookEngine';
let AndroidLog = null; // resolved lazily; Java.use requires VM access
function log(level, message) {
if (!debugLoggingEnabled) return;
// Console output — visible to attached controller (spawn/listen)
console.log(`[${LOG_TAG}] ${message}`);
// Logcat output — visible via adb logcat (all modes)
try {
if (!AndroidLog) {
AndroidLog = Java.use('android.util.Log');
}
AndroidLog[level](LOG_TAG, message);
} catch (e) {
// VM not attached yet; console.log above already emitted it.
}
}
const logD = (msg) => log('d', msg);
const logI = (msg) => log('i', msg);
const logW = (msg) => log('w', msg);
const logE = (msg) => log('e', msg);
// ------------------------------------------------------------------
// Hook bookkeeping — enables dispose() to restore original method
// implementations on script unload or Gadget-triggered reload.
// ------------------------------------------------------------------
const appliedHooks = []; // { target: Method, originalImpl: Function|null }
// Field-mutation bookkeeping for the build-prop module's dispose()-time
// reversion — separate from appliedHooks since these are static field
// writes (BuildClass.FIELD.value = ...), not method-implementation
// replacements.
const originalBuildPropFieldValues = {}; // fieldName ('VERSION.'-prefixed for Build$VERSION) -> original value
const appliedBuildMethodHooks = []; // overload targets, for Build.getSerial/getRadioVersion
const appliedSystemPropertyHooks = []; // overload targets, for SystemProperties.get overloads
const appliedDeviceIdHooks = []; // overload targets, for device-identifier method hooks
const appliedHardwareFeatureHooks = []; // overload targets, for hasSystemFeature overloads
const appliedContentProviderHooks = []; // ContentResolver/ContentProviderClient query()/call() hook targets
const appliedTypedNativeHookAddresses = []; // NativePointer[], reverted via Interceptor.revert()
const appliedRawNativeHookListeners = []; // InvocationListener[], reverted via .detach()
const appliedRegisterNativesListeners = []; // InvocationListener[], reverted via .detach()
const appliedNativePatches = []; // { address, originalBytes }
// Bookkeeping for the modules below that predate the applied*Hooks
// convention above (and the three added after it) — each previously set
// `.implementation = fn` directly with no tracked target, so dispose()
// had no way to revert them. Same convention as appliedHooks/
// appliedDeviceIdHooks/etc.: push the resolved overload target right
// after assigning its .implementation, revert with `.implementation = null`.
const appliedSecureSettingsHooks = []; // overload targets, for applySecureSettingsSpoof() (shared by ADB/mock-location/auto-time/android_id)
const appliedInstallerHooks = []; // overload targets, for applyInstallerSpoof()
const appliedFlagSecureHooks = []; // overload targets, for applyFlagSecureBypass()
const appliedVpnProxyHooks = []; // overload targets, for applyVpnProxyDetectionBypass()
const appliedGeoHooks = []; // overload targets, for applyGeoRestrictionBypass()
const appliedLocaleHooks = []; // overload targets, for applyLocaleSpoof()'s method-hook half
let originalDefaultLocale = null; // captured Locale, for applyLocaleSpoof()'s Locale.setDefault() mutation half
let originalDisplayLocale = null; // captured Locale, for the DISPLAY category default
let originalFormatLocale = null; // captured Locale, for the FORMAT category default
const appliedSuspiciousPackageHooks = []; // overload targets, for applySuspiciousPackageSpoofing()
const appliedMockLocationHooks = []; // overload targets, for applyMockLocationBypass()
const appliedPairipHooks = []; // overload targets, for applyPairipLicenseBypass()
const appliedInstalledPackageHooks = []; // overload targets, for applyInstalledPackageSpoof()
const appliedSslJavaHooks = []; // overload targets, for applySslPinningBypass()'s Java/Kotlin layer
const appliedSslNativeAddresses = []; // InvocationListener[], for applySslPinningBypass()'s Flutter/BoringSSL Interceptor.attach hook — reverted via .detach()
// Camera-mock module bookkeeping. Two arrays cover Java method hooks
// (reverted via .implementation = null); the runtime Maps/Sets below
// cover shadow ImageReader/ImageWriter pairs, per-shadow-Image spoofed
// geometry, in-flight capture-intent launches, and the synthesized-JPEG
// cache. cameraMockApplied is a double-init guard (same pattern as
// contentProviderHooksApplied).
const appliedCameraIntentHooks = []; // L1: intent-handler hook targets
const appliedCamera2Hooks = []; // L2: ImageReader + dynamic Image hook targets
let cameraMockApplied = false;
const cameraPendingLaunches = new Map(); // L1: "<callingClass>#<requestCode>" -> launch entries
const cameraReaderRegistry = new Map(); // L2: readerId -> { w, h, format, realReader, shadowSize, shadow, ... }
const cameraShadowReaderIds = new Set(); // L2: readerIds WE created (ignore our own newInstance calls)
const cameraShadowImageInfo = new Map(); // L2: imageId -> { w, h, format, timestamp, spawnedAt }
const cameraHookedReaderClasses = new Set();
const cameraHookedImageClasses = new Set();
const cameraJpegCache = new Map(); // L2: "WxH" -> synthesized JPEG bytes
let cameraLastPickedBytes = null; // L1 -> L2 shared source
let cameraLastPickedSource = null;
/**
* Serializes a value for logging without permitting a failing
* toString() implementation to abort hook execution.
*/
function safeStringify(val) {
if (val === null || val === undefined) return String(val);
try {
if (Array.isArray(val)) return `[Array len=${val.length}]`;
return val.toString();
} catch (e) {
return `<unstringifiable: ${e.message}>`;
}
}
function isVoidType(type) {
return type === 'void' || type === 'V';
}
/**
* Lazily-cached java.lang.* wrapper class references, populated on
* first use inside coerceValueForType(). Java.use() is cheap but not
* free, and this avoids re-resolving the same class on every hook
* invocation. Safe to call from here without an explicit Java.perform
* wrapper: coerceValueForType() only ever runs from a thread that is
* already JVM-attached — either inside a hooked method's own
* implementation (attached by definition, since the original method
* call arrived there) or from applyJavaHook()'s nop/forceReturn path,
* which executes in that same context.
*/
const wrapperClassCache = {};
function getWrapperClass(className) {
if (!wrapperClassCache[className]) {
wrapperClassCache[className] = Java.use(className);
}
return wrapperClassCache[className];
}
/**
* Coerces a JSON configuration value into the representation expected
* by the declared Java/Kotlin type, for use as either an argument or
* a return value.
*
* Primitive types (boolean, int, long, ...) convert to plain JS
* values — Frida's own argument/return marshalling handles the JNI
* conversion for those automatically. Boxed wrapper types
* (java.lang.Boolean, java.lang.Integer, ...) do NOT get this
* treatment from Frida: autoboxing is a javac bytecode-generation
* feature, not a JVM/ART runtime behavior, so a method whose declared
* type is a wrapper class must be handed an actual boxed object —
* passing a bare JS boolean/number where a java.lang.Boolean/Integer
* is expected fails at the JNI boundary. This matters in practice
* because Kotlin's nullable primitives (Boolean?, Int?, Long?,
* Double?) compile to exactly these wrapper types, so hooking a
* Kotlin-compiled method commonly means hitting this path.
*/
function coerceValueForType(type, rawValue) {
if (isVoidType(type)) return undefined;
switch (type) {
case 'boolean':
case 'Z':
return !!rawValue;
case 'byte':
case 'B':
case 'short':
case 'S':
case 'int':
case 'I':
return rawValue | 0;
case 'long':
case 'J':
// Values exceeding JavaScript's safe integer range should be
// supplied as strings in the configuration to preserve precision.
return typeof rawValue === 'string'
? Java.use('java.lang.Long').parseLong(rawValue)
: rawValue;
case 'float':
case 'F':
case 'double':
case 'D':
return typeof rawValue === 'number' ? rawValue : parseFloat(rawValue);
case 'char':
case 'C':
// Java char is a single UTF-16 code unit; Frida represents it as
// a 1-character JS string on both the read and write side. A
// malformed config value is caught here rather than silently
// forwarded to the JNI boundary.
if (typeof rawValue !== 'string' || rawValue.length !== 1) {
logW(`[coerceValueForType] 'char' expects a 1-character string, got ${safeStringify(rawValue)} — using '\\u0000'`);
return '\u0000';
}
return rawValue;
case 'java.lang.String':
return rawValue === null ? null : String(rawValue);
// --- Boxed wrapper types — require explicit boxing (see doc above) ---
case 'java.lang.Boolean':
return rawValue === null ? null : getWrapperClass('java.lang.Boolean').valueOf(!!rawValue);
case 'java.lang.Byte':
return rawValue === null ? null : getWrapperClass('java.lang.Byte').valueOf(rawValue | 0);
case 'java.lang.Short':
return rawValue === null ? null : getWrapperClass('java.lang.Short').valueOf(rawValue | 0);
case 'java.lang.Integer':
return rawValue === null ? null : getWrapperClass('java.lang.Integer').valueOf(rawValue | 0);
case 'java.lang.Long':
if (rawValue === null) return null;
return getWrapperClass('java.lang.Long').valueOf(
typeof rawValue === 'string'
? Java.use('java.lang.Long').parseLong(rawValue)
: rawValue
);
case 'java.lang.Float':
if (rawValue === null) return null;
return getWrapperClass('java.lang.Float').valueOf(
typeof rawValue === 'number' ? rawValue : parseFloat(rawValue)
);
case 'java.lang.Double':
if (rawValue === null) return null;
return getWrapperClass('java.lang.Double').valueOf(
typeof rawValue === 'number' ? rawValue : parseFloat(rawValue)
);
case 'java.lang.Character':
if (rawValue === null) return null;
if (typeof rawValue !== 'string' || rawValue.length !== 1) {
logW(`[coerceValueForType] java.lang.Character expects a 1-character string, got ${safeStringify(rawValue)} — using '\\u0000'`);
return getWrapperClass('java.lang.Character').valueOf('\u0000');
}
return getWrapperClass('java.lang.Character').valueOf(rawValue);
default:
// Object types (custom classes) and arrays are passed through
// unmodified. Arrays are deliberately left to Frida's own
// argument/return marshalling, which already converts plain JS
// arrays to/from Java arrays based on the declared signature.
// Forcing a return value of a custom object type requires
// construction logic specific to that class and is outside this
// generic path — see the javaHooks schema doc above
// applyJavaHook() for the documented scope of this limitation.
return rawValue;
}
}
/**
* Resolves a method reference to a specific overload when argTypes are
* supplied, or to the unqualified method group otherwise.
*
* Omitting argTypes against a method group that actually has more than
* one overload is valid Frida usage — assigning .implementation to an
* unresolved group hooks every overload with the same function — but
* it is rarely what a config author intends, since the same declared
* returnType then gets used to coerce forceReturn/modifyArgs for every
* overload, which silently produces wrong values for any overload
* whose real return type differs. className is passed through purely
* for a clearer warning message.
*
* argTypesProvided distinguishes "argTypes key omitted entirely" from
* "argTypes: [] supplied explicitly" — both produce an empty array,
* but only the former is ambiguous. An explicit [] targets that
* method's zero-arg overload specifically via .overload() with no
* arguments, which matters for constructors ($init) in particular:
* a class commonly has both a zero-arg and a parameterized
* constructor, so collapsing the two cases would silently hook every
* constructor overload instead of just the zero-arg one.
*/
function resolveOverload(className, target, methodName, argTypes, argTypesProvided) {
const methodGroup = target[methodName];
if (!methodGroup) {
throw new Error(`Method not found: ${methodName}`);
}
if (argTypesProvided) {
return methodGroup.overload(...argTypes);
}
const overloadCount = Array.isArray(methodGroup.overloads) ? methodGroup.overloads.length : 1;
if (overloadCount > 1) {
logW(`[resolveOverload] ${className}.${methodName} has ${overloadCount} overloads but argTypes ` +
`was omitted — hooking ALL of them with one implementation and one declared returnType. ` +
`If the overloads don't all share that return type, forceReturn/modifyArgs coercion will ` +
`be wrong for the mismatched ones. Supply argTypes to target a single overload.`);
}
return methodGroup;
}
/**
* Applies a single hook definition from the configuration's javaHooks
* array: resolves the target overload, installs a replacement
* implementation honoring the declared onCall behavior (argument
* logging/modification, return logging/forcing, or unconditional
* bypass of the original implementation), and records the original
* implementation for later reversal.
*/
function applyJavaHook(hookConfig) {
const { className, methodName, returnType, onCall = {} } = hookConfig;
const argTypesProvided = Object.prototype.hasOwnProperty.call(hookConfig, 'argTypes');
const argTypes = argTypesProvided ? hookConfig.argTypes : [];
const target = Java.use(className);
const boundMethod = resolveOverload(className, target, methodName, argTypes, argTypesProvided);
const voidReturn = isVoidType(returnType);
const originalImpl = boundMethod.implementation;
boundMethod.implementation = function (...args) {
const tag = `${className}.${methodName}`;
// Pre-original phase — argument logging and mutation. Guarded
// separately from the original call so that a failure here
// falls through to the original with (possibly mutated) args,
// rather than aborting the call entirely. If the original runs
// and then the post-original phase fails, retrying the original
// would double its side effects — so the two phases are split
// deliberately instead of wrapping the whole body in one block.
try {
if (onCall.logArgs) {
if (args.length === 0) {
logD(`[${tag}] (no args)`);
}
args.forEach((a, i) => {
const t = argTypes[i] || '?';
logD(`[${tag}] arg[${i}] (${t}) = ${safeStringify(a)}`);
});
}
if (onCall.modifyArgs) {
for (const [idxStr, newVal] of Object.entries(onCall.modifyArgs)) {
const idx = parseInt(idxStr, 10);
const t = argTypes[idx];
const coerced = coerceValueForType(t, newVal);
logD(`[${tag}] overriding arg[${idx}] (${t}) -> ${safeStringify(coerced)}`);
args[idx] = coerced;
}
}
} catch (preErr) {
logE(`[${tag}] pre-call processing threw: ${preErr.message}`);
// Fall through to original — args may be partially mutated.
}
// Unconditional bypass of the original implementation. Independent
// of modifyArgs: argument modification above still applies even
// when nop is set, though it has no observable effect unless the
// caller inspects the (mutated) argument objects itself.
if (onCall.nop) {
logD(`[${tag}] NOP — original implementation skipped`);
if (voidReturn) return undefined;
if (Object.prototype.hasOwnProperty.call(onCall, 'forceReturn')) {
try {
return coerceValueForType(returnType, onCall.forceReturn);
} catch (nopErr) {
logE(`[${tag}] nop forceReturn coercion threw: ${nopErr.message}`);
return undefined;
}
}
return undefined;
}
// Original call — intentionally unguarded. An exception thrown by
// the original is the app's own behavior and must propagate to the
// caller, not be swallowed by this engine.
const result = this[methodName].apply(this, args);
// Post-original phase — return logging and forced return. Guarded
// separately so that a failure here returns the original result
// instead of retrying the original (which would double side effects).
try {
if (onCall.logReturn && !voidReturn) {
logD(`[${tag}] original return = ${safeStringify(result)}`);
}
if (!voidReturn && Object.prototype.hasOwnProperty.call(onCall, 'forceReturn')) {
const forced = coerceValueForType(returnType, onCall.forceReturn);
logD(`[${tag}] forced return -> ${safeStringify(forced)}`);
return forced;
}
} catch (postErr) {
logE(`[${tag}] post-call processing threw: ${postErr.message}`);
}
return voidReturn ? undefined : result;
};
appliedHooks.push({ target: boundMethod, originalImpl });
}
/**
* Applies a hook definition with bounded retry, accommodating the
* case where the target class has not yet been loaded by the Android
* Runtime at the time init() is invoked. Retries are scheduled via
* setTimeout and therefore do not extend the synchronous execution
* time of init(), which Gadget waits on before releasing the host
* application's entrypoint.
*/
function applyHookWithRetry(hookConfig, attempt = 0) {
const MAX_ATTEMPTS = 10;
const RETRY_DELAY_MS = 500;
try {
applyJavaHook(hookConfig);
logI(`[+] Hooked ${hookConfig.className}.${hookConfig.methodName}`);
} catch (e) {
if (attempt < MAX_ATTEMPTS) {
logW(`[~] Retry ${attempt + 1}/${MAX_ATTEMPTS} for ${hookConfig.className}.${hookConfig.methodName}: ${e.message}`);
setTimeout(() => applyHookWithRetry(hookConfig, attempt + 1), RETRY_DELAY_MS);
} else {
logE(`[-] Failed to hook ${hookConfig.className}.${hookConfig.methodName} after ${MAX_ATTEMPTS} attempts: ${e.message}`);
}
}
}
function applyAllJavaHooks(hooks) {
Java.perform(function () {
logI(`[*] Loading ${hooks.length} Java hook(s)...`);
for (const hook of hooks) {
applyHookWithRetry(hook);
}
});
}
function revertAllHooks() {
Java.perform(function () {
logI(`[*] Reverting ${appliedHooks.length} applied hook(s)...`);
for (const { target, originalImpl } of appliedHooks) {
try {
target.implementation = originalImpl;