-
Notifications
You must be signed in to change notification settings - Fork 271
Expand file tree
/
Copy pathbuild.py
More file actions
2029 lines (1800 loc) · 76.9 KB
/
Copy pathbuild.py
File metadata and controls
2029 lines (1800 loc) · 76.9 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
#!/usr/bin/env python3
"""
Custom Frida Builder — build anti-detection Frida server from source.
Extended beyond ajeossida with additional stealth techniques.
Compatibility target: Frida 17.16.4.
Usage (run in WSL Ubuntu):
python3 build.py --version 17.16.4
python3 build.py --version 17.16.4 --name stealth --port 27142
python3 build.py --version 17.16.4 --arch android-arm64,android-arm --extended
python3 build.py --version 17.16.4 --skip-build # only patch, don't compile
Requirements:
- Ubuntu 22.04+ (WSL works)
- Python 3.10+
- Git
- ~20GB free disk space
- Internet connection (clones Frida + downloads NDK)
"""
import argparse
import gzip
import hashlib
import json
import os
import re
import shlex
import shutil
import struct
import subprocess
from collections.abc import Iterator, Mapping, Sequence
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from tempfile import TemporaryDirectory
from patches import (
DETECTION_VECTORS,
MEMFD_PATCHES,
SELINUX_PATCHES,
get_binary_patches,
get_binary_string_patches,
get_internal_patches,
get_memory_signature_patches,
get_port_patches,
get_required_file_patches,
get_rollback_patches,
get_source_patches,
get_stability_patches_17,
get_targeted_patches,
get_temp_path_patches,
)
# --- Constants ---
NDK_VERSION = "r29"
NDK_REVISION = "29.0.14206865"
NDK_URL = f"https://dl.google.com/android/repository/android-ndk-{NDK_VERSION}-linux.zip"
NDK_ARCHIVE_SHA1 = "87e2bb7e9be5d6a1c6cdf5ec40dd4e0c6d07c30b"
ALL_ARCHS = ["android-arm64", "android-arm", "android-x86_64", "android-x86"]
VERSION_PATTERN = re.compile(r"^\d+\.\d+\.\d+$")
NAME_PATTERN = re.compile(r"^[a-z][a-z0-9]{2,19}$")
ANDROID_FALLBACK_ROOTS = (
Path("/usr/local/lib/android/sdk"),
Path("/usr/local/lib/android"),
)
FORBIDDEN_BINARY_MARKERS = (
b"frida\x00",
b"frida-zymbiote",
b"re/frida/HelperBackend",
b"frida-server",
b"frida-helper",
b"frida-agent",
b"frida-gadget",
b"frida-eternal-agent",
b"frida-generate-certificate",
b"frida-main-loop",
b"frida:rpc",
b"FridaScriptEngine",
b"GLib-GIO",
b"GDBusProxy",
b"GumScript",
b"Frida/",
b"gum-js-loop",
b"gmain\x00",
b"gdbus\x00",
b"pool-frida",
b"pool-spawner",
b"jit-cache\x00",
)
ZYMBIOTE_ARCHITECTURES = ("arm", "arm64", "x86", "x86_64")
ZYMBIOTE_SOCKET_FIELD_SIZE = 64
ZYMBIOTE_SOCKET_TOKEN = b"0" * 32
class BuildError(RuntimeError):
"""Expected build failure that should be shown without a traceback."""
def log(msg: str, level: str = "INFO"):
colors = {
"INFO": "\033[36m",
"OK": "\033[32m",
"WARN": "\033[33m",
"ERROR": "\033[31m",
"STEP": "\033[35m",
"HEADER": "\033[1;37m",
}
reset = "\033[0m"
color = colors.get(level, "")
print(f"{color}[{level}]{reset} {msg}", flush=True)
def run(
command: Sequence[str | os.PathLike[str]],
cwd: str | os.PathLike[str] | None = None,
env: Mapping[str, str] | None = None,
check: bool = True,
capture_output: bool = False,
) -> subprocess.CompletedProcess[str]:
"""Run an argument vector with inherited environment plus overrides."""
if isinstance(command, (str, bytes)):
raise BuildError("Commands must be passed as an argument vector")
argv = [os.fspath(part) for part in command]
if not argv:
raise BuildError("Command argument vector must not be empty")
full_env = os.environ.copy()
if env:
full_env.update(env)
rendered_command = shlex.join(argv)
log(f"$ {rendered_command}", "INFO")
try:
result = subprocess.run(
argv,
cwd=cwd,
env=full_env,
capture_output=capture_output,
text=True,
)
except OSError as error:
raise BuildError(f"Unable to run command: {rendered_command}: {error}") from error
if check and result.returncode != 0:
raise BuildError(f"Command failed with exit code {result.returncode}: {rendered_command}")
return result
def validate_version(value: str) -> str:
"""Accept only concrete Frida release tags such as 17.16.4."""
if VERSION_PATTERN.fullmatch(value) is None:
raise BuildError("Frida version must use the numeric X.Y.Z release format")
return value
def validate_custom_name(value: str) -> str:
"""Normalize and validate the identifier used in paths, packages, and symbols."""
normalized = value.lower()
if NAME_PATTERN.fullmatch(normalized) is None:
raise BuildError(
"Custom name must be 3-20 lowercase letters or digits and start with a letter"
)
return normalized
def validate_port(value: int | None) -> int | None:
"""Validate an optional TCP port."""
if value is not None and not 1 <= value <= 65535:
raise BuildError("Port must be between 1 and 65535")
return value
def parse_architectures(value: str) -> list[str]:
"""Parse and validate the requested Android architecture list."""
architectures = [architecture.strip() for architecture in value.split(",")]
invalid = [architecture for architecture in architectures if architecture not in ALL_ARCHS]
if invalid:
shown = invalid[0] or "<empty>"
raise BuildError(f"Unknown architecture: {shown}. Valid: {', '.join(ALL_ARCHS)}")
return architectures
def validate_directory_layout(
repository_dir: Path, work_dir: Path, output_dir: Path
) -> tuple[Path, Path]:
"""Resolve build paths and reject layouts that publication could destroy."""
repository_dir = repository_dir.resolve()
work_dir = work_dir.resolve()
output_dir = output_dir.resolve()
if output_dir == repository_dir or output_dir in repository_dir.parents:
raise BuildError("Output directory must not contain the repository")
if work_dir == output_dir or work_dir in output_dir.parents or output_dir in work_dir.parents:
raise BuildError("Work and output directories must not overlap")
return work_dir, output_dir
def require_executable(name: str) -> str:
"""Resolve a mandatory executable or fail with its name."""
path = shutil.which(name)
if path is None:
raise BuildError(f"Required executable is missing: {name}")
return path
def _android_sdk_roots() -> tuple[Path, ...]:
roots: list[Path] = []
for variable in ("ANDROID_SDK_ROOT", "ANDROID_HOME"):
value = os.environ.get(variable)
if value:
roots.append(Path(value))
roots.extend(ANDROID_FALLBACK_ROOTS)
return tuple(dict.fromkeys(roots))
def _sdk_version_key(path: Path) -> tuple[int, ...]:
"""Sort SDK package paths by their numeric version components."""
package_dir = path.parent.parent if path.name == "d8.jar" else path.parent
return tuple(int(component) for component in re.findall(r"\d+", package_dir.name))
def find_android_jar() -> Path:
"""Find the newest available Android platform API JAR."""
candidates = {
candidate
for root in _android_sdk_roots()
if root.exists()
for candidate in root.glob("platforms/*/android.jar")
if candidate.is_file()
}
if not candidates:
raise BuildError("Required Android SDK platform file is missing: android.jar")
return max(candidates, key=_sdk_version_key)
def find_d8_command() -> list[str]:
"""Resolve D8 as an executable or its JAR entry point."""
executable = shutil.which("d8")
if executable is not None:
return [executable]
roots = [root for root in _android_sdk_roots() if root.exists()]
executables: set[Path] = {
candidate
for root in roots
for candidate in root.glob("build-tools/*/d8")
if candidate.is_file() and os.access(candidate, os.X_OK)
}
if executables:
d8_executable = max(executables, key=_sdk_version_key)
return [os.fspath(d8_executable)]
jars: set[Path] = {
candidate
for root in roots
for candidate in root.glob("build-tools/*/lib/d8.jar")
if candidate.is_file()
}
if jars:
d8_jar = max(jars, key=_sdk_version_key)
return [
require_executable("java"),
"-cp",
os.fspath(d8_jar),
"com.android.tools.r8.D8",
]
raise BuildError("Required Android build tool is missing: d8")
def validate_build_prerequisites(*, skip_build: bool) -> None:
"""Fail before downloads or patching when required build tools are absent."""
for executable in ("git", "java", "javac", "jar"):
require_executable(executable)
if not skip_build:
for executable in ("make", "node"):
require_executable(executable)
find_android_jar()
find_d8_command()
def detect_frida_major(version: str) -> int:
return int(version.split(".")[0])
# ============================================================================
# File operations
# ============================================================================
def replace_in_file(filepath: Path, old: str, new: str) -> int:
"""Replace string in a single file. Returns number of replacements."""
try:
content = filepath.read_text(encoding="utf-8", errors="ignore")
except (PermissionError, IsADirectoryError, OSError):
return 0
if old not in content:
return 0
count = content.count(old)
content = content.replace(old, new)
filepath.write_text(content, encoding="utf-8")
return count
def replace_in_tree(root: Path, old: str, new: str, include_build: bool = False) -> int:
"""Recursively replace string in all text files under root."""
total = 0
skip_dirs = {".git", "node_modules", "__pycache__", ".venv"}
if not include_build:
skip_dirs.add("build")
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [d for d in dirnames if d not in skip_dirs]
for fname in filenames:
fpath = Path(dirpath) / fname
if fpath.is_symlink():
continue
# Skip binary files by extension
if fpath.suffix in {
".o",
".a",
".so",
".gz",
".zip",
".png",
".jpg",
".pyc",
".dex",
".jar",
".class",
".elf",
".wasm",
".dylib",
".dll",
}:
continue
total += replace_in_file(fpath, old, new)
return total
# ============================================================================
# NDK
# ============================================================================
def validate_ndk(ndk_dir: Path) -> Path:
"""Require the exact NDK revision used by the supported build."""
properties = ndk_dir / "source.properties"
if not properties.is_file():
raise BuildError(f"NDK source.properties is missing: {properties}")
expected = f"Pkg.Revision = {NDK_REVISION}"
lines = properties.read_text(encoding="utf-8").splitlines()
if expected not in lines:
actual = next(
(line for line in lines if line.startswith("Pkg.Revision")),
"revision not declared",
)
raise BuildError(f"NDK revision mismatch: expected {NDK_REVISION}, found {actual}")
return ndk_dir
def find_llvm_strip(ndk_dir: Path) -> Path:
"""Locate the host llvm-strip shipped with the validated Android NDK."""
candidates = sorted(
candidate
for prebuilt in (ndk_dir / "toolchains" / "llvm" / "prebuilt").glob("*")
for candidate in (
prebuilt / "bin" / "llvm-strip",
prebuilt / "bin" / "llvm-strip.exe",
)
if candidate.is_file()
)
if not candidates:
raise BuildError(f"NDK llvm-strip is missing under {ndk_dir}")
return candidates[0]
def verify_file_checksum(path: Path, expected: str, algorithm: str) -> None:
"""Verify a file digest without loading a large archive into memory."""
digest = hashlib.new(algorithm)
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
actual = digest.hexdigest()
if actual != expected:
raise BuildError(f"{path.name} checksum mismatch: expected {expected}, found {actual}")
def ensure_ndk(work_dir: Path) -> Path:
"""Download and extract Android NDK if needed."""
ndk_dir = work_dir / f"android-ndk-{NDK_VERSION}"
if ndk_dir.exists():
validate_ndk(ndk_dir)
log(f"NDK already at {ndk_dir}", "OK")
return ndk_dir
ndk_zip = work_dir / f"android-ndk-{NDK_VERSION}-linux.zip"
if not ndk_zip.exists():
log(f"Downloading NDK {NDK_VERSION} (~1.5 GB)...", "STEP")
partial = ndk_zip.with_suffix(f"{ndk_zip.suffix}.part")
run(
[
"curl",
"--fail",
"--location",
"--retry",
"3",
"--retry-all-errors",
"--output",
partial,
NDK_URL,
],
cwd=work_dir,
)
verify_file_checksum(partial, NDK_ARCHIVE_SHA1, "sha1")
os.replace(partial, ndk_zip)
else:
verify_file_checksum(ndk_zip, NDK_ARCHIVE_SHA1, "sha1")
log("Extracting NDK...", "STEP")
run(["unzip", "-q", ndk_zip], cwd=work_dir)
if ndk_dir.exists():
validate_ndk(ndk_dir)
log(f"NDK ready at {ndk_dir}", "OK")
ndk_zip.unlink(missing_ok=True)
return ndk_dir
raise BuildError(f"NDK extraction did not create expected directory: {ndk_dir}")
# ============================================================================
# Clone
# ============================================================================
def clone_frida(version: str, work_dir: Path) -> Path:
"""Clone Frida source at the specified version tag."""
frida_dir = work_dir / "frida"
if frida_dir.exists():
log(f"Frida source already at {frida_dir}", "OK")
return frida_dir
log(f"Cloning Frida {version} (with submodules)...", "STEP")
run(
[
"git",
"clone",
"--recurse-submodules",
"--branch",
version,
"--depth",
"1",
"https://github.com/frida/frida.git",
frida_dir,
],
cwd=work_dir,
)
log(f"Frida {version} cloned", "OK")
return frida_dir
# ============================================================================
# PHASE 1: Source-level patches (before build)
# ============================================================================
def rename_frida_files(frida_dir: Path, custom_name: str):
"""
Rename files on disk whose names contain 'frida-helper' or 'frida-agent' etc.
After global source patches rename references in meson.build/Vala/C files,
the actual files on disk must also be renamed to match.
IMPORTANT: Skip build system files (.symbols, .version, .def, .plist, .xcent)
because rollback patches revert their references to original names.
Also skip releng/frida_version.py (not renamed by our patches).
"""
rename_patterns = [
("frida-helper", f"{custom_name}-helper"),
("frida-agent", f"{custom_name}-agent"),
("frida-gadget", f"{custom_name}-gadget"),
("frida-server", f"{custom_name}-server"),
]
# Build system file extensions that rollback patches keep with original names
skip_extensions = {".symbols", ".version", ".def", ".plist", ".xcent"}
skip_dirs = {".git", "node_modules", "__pycache__", ".venv", "build"}
# Specific files to never rename
skip_names = {"frida_version.py", "frida-version.py"}
renamed_count = 0
for dirpath, dirnames, filenames in os.walk(frida_dir, topdown=True):
dirnames[:] = [d for d in dirnames if d not in skip_dirs]
for fname in filenames:
if fname in skip_names:
continue
# Skip build system files (rollback patches keep their original names)
if Path(fname).suffix in skip_extensions:
continue
new_fname = fname
for old_pat, new_pat in rename_patterns:
if old_pat in new_fname:
new_fname = new_fname.replace(old_pat, new_pat)
if new_fname != fname:
old_path = Path(dirpath) / fname
new_path = Path(dirpath) / new_fname
if old_path.exists() and not new_path.exists():
old_path.rename(new_path)
renamed_count += 1
if renamed_count:
log(f" Renamed {renamed_count} files on disk", "OK")
def _require_success(tool: str, result: subprocess.CompletedProcess[str]) -> None:
if result.returncode == 0:
return
details = (result.stderr or result.stdout or "").strip()
suffix = f": {details}" if details else ""
raise BuildError(f"{tool} failed with exit code {result.returncode}{suffix}")
def rebuild_helper_dex(frida_dir: Path, custom_name: str) -> Path:
"""Rebuild the Android helper DEX with renamed Java package.
The pre-compiled helper.dex in the repo contains 're.frida.Helper'.
We need to recompile it with the new package name so that:
1. The DEX string table doesn't contain 'frida' (binary sweep safe)
2. The class name matches what the renamed Vala code expects
"""
helper_dir = frida_dir / "subprojects" / "frida-core" / "src" / "android-helper"
old_pkg_dir = helper_dir / "re" / "frida"
new_pkg_dir = helper_dir / "re" / custom_name
java_file = old_pkg_dir / "Helper.java"
if not java_file.exists():
# Package might already be renamed (e.g., from cache)
java_file = new_pkg_dir / "Helper.java"
if not java_file.exists():
raise BuildError(f"Required Android helper source is missing: {java_file}")
# Rename directory: re/frida/ -> re/{name}/
if old_pkg_dir.exists() and new_pkg_dir.exists():
raise BuildError(f"Both helper package directories exist: {old_pkg_dir}, {new_pkg_dir}")
if old_pkg_dir.exists():
old_pkg_dir.rename(new_pkg_dir)
log(f" Renamed {old_pkg_dir.name}/ -> {new_pkg_dir.name}/", "OK")
java_file = new_pkg_dir / "Helper.java"
if not java_file.exists():
raise BuildError(f"Required Android helper source is missing after rename: {java_file}")
# The Java source was already patched by replace_in_tree:
# "package re.frida;" -> "package re.{name};"
# "re.frida.Helper" -> "re.{name}.Helper"
# Verify:
content = java_file.read_text(encoding="utf-8")
if f"package re.{custom_name};" not in content:
content = content.replace("package re.frida;", f"package re.{custom_name};")
if f"package re.{custom_name};" not in content:
raise BuildError(f"Could not patch Android helper package in {java_file}")
java_file.write_text(content, encoding="utf-8")
dex_file = helper_dir / "helper.dex"
if not dex_file.is_file():
raise BuildError(f"Required precompiled Android helper DEX is missing: {dex_file}")
javac_path = require_executable("javac")
jar_path = require_executable("jar")
android_jar = find_android_jar()
d8_command = find_d8_command()
log(f" Recompiling helper DEX (android.jar: {android_jar.name})...", "STEP")
with TemporaryDirectory(dir=helper_dir, prefix=".dex-build-") as temporary:
build_dir = Path(temporary)
java_build = build_dir / "java"
dex_build = build_dir / "dex"
java_build.mkdir()
dex_build.mkdir()
javac_result = run(
[
javac_path,
"-cp",
f".{os.pathsep}{android_jar}",
"-bootclasspath",
android_jar,
"-source",
"1.8",
"-target",
"1.8",
"-Xlint:-options",
java_file,
"-d",
java_build,
],
cwd=helper_dir,
check=False,
capture_output=True,
)
_require_success("javac", javac_result)
class_files = list((java_build / "re" / custom_name).glob("*.class"))
if not class_files:
raise BuildError(f"javac generated no helper classes under re/{custom_name}")
log(f" Compiled {len(class_files)} helper class files", "OK")
jar_file = build_dir / f"{custom_name}-helper.jar"
jar_result = run(
[jar_path, "cfe", jar_file, f"re.{custom_name}.Helper", "-C", java_build, "."],
cwd=helper_dir,
check=False,
capture_output=True,
)
_require_success("jar", jar_result)
d8_result = run(
[*d8_command, "--lib", android_jar, "--output", dex_build, jar_file],
cwd=helper_dir,
check=False,
capture_output=True,
)
_require_success("d8", d8_result)
new_dex = dex_build / "classes.dex"
if not new_dex.is_file():
raise BuildError(f"d8 did not generate expected output: {new_dex}")
shutil.copy2(new_dex, dex_file)
log(
f" Helper DEX rebuilt: {dex_file.stat().st_size} bytes (package: re.{custom_name})",
"OK",
)
return dex_file
def apply_required_file_patches(frida_dir: Path, custom_name: str) -> None:
"""Apply source contracts that must match the supported Frida source shape."""
for patch in get_required_file_patches(custom_name):
target = frida_dir / patch.relative_path
if not target.is_file():
raise BuildError(f"Required patch file is missing: {patch.relative_path}")
count = replace_in_file(target, patch.old, patch.new)
if count < patch.minimum:
raise BuildError(
f"Required pattern {patch.old!r} occurred {count} times in "
f"{patch.relative_path}; expected at least {patch.minimum}"
)
log(f" [required] {patch.relative_path}: {count} replacement(s)", "OK")
def patch_zymbiote_artifacts(frida_dir: Path, custom_name: str) -> None:
"""Patch the fixed-size socket field in Frida's tracked helper ELFs."""
old_socket = b"/frida-zymbiote-" + ZYMBIOTE_SOCKET_TOKEN
new_socket = f"/{custom_name}-zymbiote-".encode() + ZYMBIOTE_SOCKET_TOKEN
if len(new_socket) >= ZYMBIOTE_SOCKET_FIELD_SIZE:
raise BuildError("Custom name does not fit the zymbiote socket field")
old_field = old_socket.ljust(ZYMBIOTE_SOCKET_FIELD_SIZE, b"\0")
new_field = new_socket.ljust(ZYMBIOTE_SOCKET_FIELD_SIZE, b"\0")
artifacts = frida_dir / "subprojects/frida-core/src/linux/helpers/artifacts/native"
for architecture in ZYMBIOTE_ARCHITECTURES:
target = artifacts / architecture / "zymbiote.elf"
relative_path = target.relative_to(frida_dir).as_posix()
if not target.is_file():
raise BuildError(f"Required zymbiote artifact is missing: {relative_path}")
data = target.read_bytes()
count = data.count(old_field)
if count != 1:
raise BuildError(
f"Required socket field occurred {count} times in {relative_path}; expected 1"
)
patched = data.replace(old_field, new_field)
with TemporaryDirectory(dir=target.parent, prefix=".zymbiote-patch-") as temporary:
staged = Path(temporary) / target.name
staged.write_bytes(patched)
shutil.copymode(target, staged)
os.replace(staged, target)
log(f" [required] {relative_path}: socket field patched", "OK")
def apply_source_patches(frida_dir: Path, custom_name: str):
"""Apply global recursive string replacements across the source tree."""
log("=" * 60, "HEADER")
log("PHASE 1: Global source patches", "STEP")
log("=" * 60, "HEADER")
apply_required_file_patches(frida_dir, custom_name)
patch_zymbiote_artifacts(frida_dir, custom_name)
cap_name = custom_name[0].upper() + custom_name[1:]
patches = get_source_patches(custom_name, cap_name)
for old, new in patches:
count = replace_in_tree(frida_dir, old, new)
if count:
log(f" {old} -> {new} ({count})", "OK")
else:
log(f" {old} -> (not found)", "WARN")
# Rollback accidental renames of build system files
log("Rolling back build file renames...", "STEP")
rollbacks = get_rollback_patches(custom_name)
for old, new in rollbacks:
count = replace_in_tree(frida_dir, old, new)
if count:
log(f" [rollback] {old} ({count})", "INFO")
# Rename actual files on disk to match source references
rename_frida_files(frida_dir, custom_name)
# Rebuild helper DEX with renamed Java package
rebuild_helper_dex(frida_dir, custom_name)
log("Global source patches complete", "OK")
def apply_targeted_patches(frida_dir: Path, custom_name: str, frida_major: int):
"""Apply patches to specific files (memfd, libc hooks, SELinux, build system)."""
log("=" * 60, "HEADER")
log("PHASE 2: Targeted file patches", "STEP")
log("=" * 60, "HEADER")
cap_name = custom_name[0].upper() + custom_name[1:]
core_dir = frida_dir / "subprojects" / "frida-core"
# --- memfd_create: hide agent name in /proc/pid/fd ---
memfd_cfg = MEMFD_PATCHES.get(frida_major, MEMFD_PATCHES[17])
memfd_file = core_dir / memfd_cfg["file"]
if memfd_file.exists():
count = replace_in_file(memfd_file, memfd_cfg["old"], memfd_cfg["new"])
if count:
log(f" memfd_create -> 'jit-code-cache' in {memfd_cfg['file']}", "OK")
else:
log(f" memfd_create: pattern not found in {memfd_cfg['file']}", "WARN")
else:
log(f" memfd file missing: {memfd_cfg['file']}", "WARN")
# --- SELinux labels (in linjector.vala for 17.x) ---
for old, new in SELINUX_PATCHES(custom_name):
count = replace_in_tree(frida_dir, old, new)
if count:
log(f" SELinux: {old} -> {new} ({count})", "OK")
# --- Build system files ---
targets = {
"server_meson": core_dir / "server" / "meson.build",
"compat_build": core_dir / "compat" / "build.py",
"core_meson": core_dir / "meson.build",
"gadget_meson": core_dir / "lib" / "gadget" / "meson.build",
"agent_meson": core_dir / "lib" / "agent" / "meson.build",
}
for target_name, target_file in targets.items():
if target_file.exists():
patches = get_targeted_patches(custom_name, cap_name, target_name)
applied = 0
for old, new in patches:
applied += replace_in_file(target_file, old, new)
if applied:
log(f" {target_name}: {applied} patches", "OK")
else:
log(f" {target_name}: file not found", "WARN")
log("Targeted patches complete", "OK")
def apply_strict_wx_patch(frida_dir: Path, custom_name: str) -> None:
"""Disable persistent anonymous RWX mappings owned by Frida on Android."""
helper_backend = Path(f"subprojects/frida-core/src/linux/{custom_name}-helper-backend.vala")
allocator_boxed_types = (
"G_DEFINE_BOXED_TYPE (GumCodeSlice, gum_code_slice, gum_code_slice_ref,\n"
" gum_code_slice_unref)\n"
"G_DEFINE_BOXED_TYPE (GumCodeDeflector, gum_code_deflector,\n"
" gum_code_deflector_ref, gum_code_deflector_unref)\n\n"
)
patches = (
(
Path("subprojects/frida-gum/gum/gumcodeallocator.c"),
"gum_query_is_rwx_supported ()",
"gum_code_allocator_is_rwx_supported ()",
3,
"code pools use RW then RX",
),
(
Path("subprojects/frida-gum/gum/gumcodeallocator.c"),
allocator_boxed_types + "void\ngum_code_allocator_init",
allocator_boxed_types + "static gboolean\n"
"gum_code_allocator_is_rwx_supported (void)\n"
"{\n"
"#if defined (HAVE_ANDROID)\n"
" return FALSE;\n"
"#else\n"
" return gum_query_is_rwx_supported ();\n"
"#endif\n"
"}\n\n"
"void\n"
"gum_code_allocator_init",
1,
"Android allocator policy scoped",
),
(
Path("subprojects/frida-gum/gum/gummemory.c"),
" restored = ((original_protections[i] & GUM_PAGE_WRITE) != 0)\n"
" ? GUM_PAGE_RWX\n"
" : GUM_PAGE_RX;",
"#if defined (HAVE_ANDROID)\n"
" restored = ((original_protections[i] & GUM_PAGE_WRITE) != 0 &&\n"
" (original_protections[i] & GUM_PAGE_EXECUTE) != 0)\n"
" ? GUM_PAGE_RWX\n"
" : GUM_PAGE_RX;\n"
"#else\n"
" restored = ((original_protections[i] & GUM_PAGE_WRITE) != 0)\n"
" ? GUM_PAGE_RWX\n"
" : GUM_PAGE_RX;\n"
"#endif",
1,
"new Android code pages finish RX",
),
(
Path("subprojects/frida-gum/gum/gum-init.h"),
"GUM_API void _gum_register_early_destructor (GumDestructorFunc destructor);\n"
"GUM_API void _gum_register_destructor (GumDestructorFunc destructor);\n\n"
"G_END_DECLS",
"GUM_API void _gum_register_early_destructor (GumDestructorFunc destructor);\n"
"GUM_API void _gum_register_destructor (GumDestructorFunc destructor);\n\n"
"#if defined (HAVE_ANDROID)\n"
"G_GNUC_INTERNAL gpointer _gum_android_ffi_closure_make_executable (\n"
" gpointer closure, gpointer code, gsize closure_size,\n"
" gpointer * code_page);\n"
"G_GNUC_INTERNAL void _gum_android_ffi_closure_free_executable (\n"
" gpointer code_page);\n"
"#endif\n\n"
"G_END_DECLS",
1,
"declare Android NativeCallback W^X helpers",
),
(
Path("subprojects/frida-gum/gum/gum.c"),
"static void\n"
"gum_on_ffi_deallocate (void * base_address,\n"
" size_t size)\n"
"{\n"
" GumMemoryRange range;\n"
" range.base_address = GUM_ADDRESS (base_address);\n"
" range.size = size;\n"
" gum_cloak_remove_range (&range);\n"
"}\n\n"
"#endif",
"static void\n"
"gum_on_ffi_deallocate (void * base_address,\n"
" size_t size)\n"
"{\n"
" GumMemoryRange range;\n"
" range.base_address = GUM_ADDRESS (base_address);\n"
" range.size = size;\n"
" gum_cloak_remove_range (&range);\n"
"}\n\n"
"#endif\n\n"
"#ifdef HAVE_ANDROID\n\n"
"gpointer\n"
"_gum_android_ffi_closure_make_executable (gpointer closure,\n"
" gpointer code,\n"
" gsize closure_size,\n"
" gpointer * code_page)\n"
"{\n"
" gsize page_size, closure_region_size;\n"
" guintptr closure_address, closure_page_address, code_address;\n"
" guintptr normalized_code_address, code_state, code_offset;\n"
" gpointer executable_page;\n"
" GumMemoryRange range;\n"
" GumPageProtection closure_protection, code_protection;\n\n"
" *code_page = NULL;\n"
" page_size = gum_query_page_size ();\n"
" if (closure_size > page_size)\n"
" return NULL;\n\n"
" closure_address = GPOINTER_TO_SIZE (closure);\n"
" closure_page_address = closure_address & ~((guintptr) page_size - 1);\n"
" closure_region_size =\n"
" ((closure_address - closure_page_address + closure_size + page_size - 1) /\n"
" page_size) * page_size;\n"
" code_address = GPOINTER_TO_SIZE (code);\n"
" code_state = code_address & 1;\n"
" normalized_code_address = code_address - code_state;\n"
" if (normalized_code_address < closure_address ||\n"
" normalized_code_address - closure_address >= closure_size)\n"
" {\n"
" if (!gum_memory_query_protection (closure, &closure_protection) ||\n"
" !gum_memory_query_protection (\n"
" GSIZE_TO_POINTER (normalized_code_address), &code_protection) ||\n"
" (closure_protection & GUM_PAGE_WRITE) == 0 ||\n"
" (closure_protection & GUM_PAGE_EXECUTE) != 0 ||\n"
" (code_protection & GUM_PAGE_WRITE) != 0 ||\n"
" (code_protection & GUM_PAGE_EXECUTE) == 0)\n"
" return NULL;\n"
" return code;\n"
" }\n"
" code_offset = normalized_code_address - closure_address;\n\n"
" executable_page = gum_memory_allocate (NULL, page_size, page_size,\n"
" GUM_PAGE_RW);\n"
" if (executable_page == NULL)\n"
" return NULL;\n"
" memcpy (executable_page, closure, closure_size);\n\n"
" if (!gum_try_mprotect (GSIZE_TO_POINTER (closure_page_address),\n"
" closure_region_size, GUM_PAGE_RW) ||\n"
" !gum_try_mprotect (executable_page, page_size, GUM_PAGE_RX))\n"
" {\n"
" gum_memory_free (executable_page, page_size);\n"
" return NULL;\n"
" }\n"
" gum_clear_cache (executable_page, closure_size);\n\n"
" range.base_address = GUM_ADDRESS (executable_page);\n"
" range.size = page_size;\n"
" gum_cloak_add_range (&range);\n\n"
" *code_page = executable_page;\n"
" return GSIZE_TO_POINTER (GPOINTER_TO_SIZE (executable_page) +\n"
" code_offset + code_state);\n"
"}\n\n"
"void\n"
"_gum_android_ffi_closure_free_executable (gpointer code_page)\n"
"{\n"
" gsize page_size = gum_query_page_size ();\n"
" GumMemoryRange range;\n\n"
" range.base_address = GUM_ADDRESS (code_page);\n"
" range.size = page_size;\n"
" gum_cloak_remove_range (&range);\n"
" gum_memory_free (code_page, page_size);\n"
"}\n\n"
"#endif",
1,
"NativeCallback closures use separate RW and RX pages",
),
(
Path("subprojects/frida-gum/bindings/gumjs/gumquickcore.h"),
" JSValue wrapper;\n JSValue func;\n ffi_closure * closure;\n ffi_cif cif;",
" JSValue wrapper;\n"
" JSValue func;\n"
" ffi_closure * closure;\n"
"#if defined (HAVE_ANDROID)\n"
" gpointer code_page;\n"
"#endif\n"
" ffi_cif cif;",
1,
"track QuickJS NativeCallback RX page",
),
(
Path("subprojects/frida-gum/bindings/gumjs/gumquickcore.c"),
"#include <string.h>\n#include <glib/gprintf.h>",
"#include <string.h>\n"
"#include <glib/gprintf.h>\n"
"#if defined (HAVE_ANDROID)\n"
"# include <gum/gum-init.h>\n"
"#endif",
1,
"import QuickJS NativeCallback W^X helpers",
),
(
Path("subprojects/frida-gum/bindings/gumjs/gumquickcore.c"),
" if (ffi_prep_closure_loc (cb->closure, &cb->cif,\n"
" gum_quick_native_callback_invoke, cb, ptr->value) != FFI_OK)\n"
" goto prepare_failed;",
" if (ffi_prep_closure_loc (cb->closure, &cb->cif,\n"
" gum_quick_native_callback_invoke, cb, ptr->value) != FFI_OK)\n"
" goto prepare_failed;\n"
"#if defined (HAVE_ANDROID)\n"
" ptr->value = _gum_android_ffi_closure_make_executable (cb->closure,\n"
" ptr->value, sizeof (ffi_closure), &cb->code_page);\n"
" if (ptr->value == NULL)\n"
" goto prepare_failed;\n"
"#endif",
1,
"QuickJS NativeCallback code finishes RX",
),
(
Path("subprojects/frida-gum/bindings/gumjs/gumquickcore.c"),
"gum_quick_native_callback_finalize (GumQuickNativeCallback * callback)\n"
"{\n"
" g_clear_pointer (&callback->closure, ffi_closure_free);",
"gum_quick_native_callback_finalize (GumQuickNativeCallback * callback)\n"
"{\n"
"#if defined (HAVE_ANDROID)\n"
" g_clear_pointer (&callback->code_page,\n"
" _gum_android_ffi_closure_free_executable);\n"
"#endif\n"
" g_clear_pointer (&callback->closure, ffi_closure_free);",
1,
"free QuickJS NativeCallback RX page",
),
(
Path("subprojects/frida-gum/bindings/gumjs/gumv8core.cpp"),
" v8::Global<v8::Function> * func;\n ffi_closure * closure;\n ffi_cif cif;",
" v8::Global<v8::Function> * func;\n"
" ffi_closure * closure;\n"
"#if defined (HAVE_ANDROID)\n"
" gpointer code_page;\n"