forked from Blank-c/BlankOBF
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlankOBFv3.py
More file actions
1019 lines (866 loc) · 40.9 KB
/
BlankOBFv3.py
File metadata and controls
1019 lines (866 loc) · 40.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
"""
BlankOBF v3 — Production-Grade AST Code Transformer
=======================================================
Single-file, stdlib-only, deterministic, semantically neutral.
Pipeline (12 phases):
1. Input Validation 5. Injection Insert 9. Dead Code Injection
2. AST Enrichment 6. Re-enrichment 10. Unparse + Validate
3. __all__ Extraction 7. Transform Engine 11. Post-processing
4. Scope Analysis 8. fix_missing_locations 12. Final Validation
Transforms (T1–T11):
T1 Local variable renaming T7 If/While double negation
T2 Builtin aliasing T8 Docstring stripping
T3 Integer masking (5 strat) T9 Opaque predicates / dead branches
T4 String encoding (2 strat) T10 Deep integer nesting
T5 Boolean rewriting T11 String splitting (long strings)
T6 Comparison inversion
"""
import ast
import os
import sys
import math
import argparse
import hashlib
import random
import logging
import base64
import builtins as _builtins_module
from typing import Dict, Set, List, Tuple, Any
__version__ = "3.0.0"
logging.basicConfig(level=logging.INFO, format="[%(levelname)s] %(message)s")
log = logging.getLogger("blankobf")
# =========================================================================
# CONSTANTS
# =========================================================================
ABSOLUTE_PROTECTED = frozenset({
"self", "cls", "super",
"__name__", "__main__", "__file__", "__doc__", "__all__",
"__init__", "__new__", "__del__", "__repr__", "__str__",
"__enter__", "__exit__", "__call__", "__iter__", "__next__",
"__getattr__", "__setattr__", "__delattr__", "__getattribute__",
"__get__", "__set__", "__delete__",
"__getitem__", "__setitem__", "__delitem__", "__contains__",
"__len__", "__bool__", "__hash__", "__eq__", "__ne__",
"__lt__", "__le__", "__gt__", "__ge__",
"__add__", "__sub__", "__mul__", "__truediv__", "__floordiv__",
"__mod__", "__pow__", "__and__", "__or__", "__xor__",
"__radd__", "__rsub__", "__rmul__",
"__iadd__", "__isub__", "__imul__",
"__neg__", "__pos__", "__abs__", "__invert__",
"__int__", "__float__", "__complex__", "__index__",
"__class__", "__dict__", "__slots__", "__module__",
"__bases__", "__mro__", "__subclasses__",
"__import__", "__builtins__", "__spec__", "__loader__",
"__package__", "__cached__", "__annotations__",
"__aenter__", "__aexit__", "__aiter__", "__anext__",
"__await__", "__class_getitem__",
"None", "True", "False", "NotImplemented", "Ellipsis", "__debug__",
})
_MATCH_PATTERN_TYPES: Tuple[type, ...] = tuple(
getattr(ast, n) for n in (
"MatchValue", "MatchSingleton", "MatchSequence",
"MatchMapping", "MatchClass", "MatchStar", "MatchAs", "MatchOr",
) if hasattr(ast, n)
)
DYNAMIC_INTROSPECTION = frozenset({
"eval", "exec", "locals", "globals", "vars",
"getattr", "setattr", "delattr", "dir", "compile",
})
SAFE_STRING_PARENTS: Tuple[type, ...] = (
ast.Assign, ast.AugAssign, ast.AnnAssign,
ast.Call, ast.Return, ast.BinOp, ast.BoolOp, ast.UnaryOp,
ast.Subscript, ast.Compare,
ast.Dict, ast.List, ast.Set, ast.Tuple,
ast.Yield, ast.YieldFrom, ast.IfExp,
ast.FormattedValue, ast.keyword,
ast.Assert, ast.Raise, ast.Delete,
)
def _h(seed: int, *parts: Any) -> str:
return hashlib.sha256(f"{seed}|{'|'.join(str(p) for p in parts)}".encode()).hexdigest()
# =========================================================================
# PHASE 1 — AST ENRICHMENT
# =========================================================================
class ASTEnricher(ast.NodeVisitor):
def visit(self, node: ast.AST) -> ast.AST:
for child in ast.iter_child_nodes(node):
child.parent = node
child._depth = getattr(node, "_depth", 0) + 1
self.generic_visit(node)
return node
# =========================================================================
# PHASE 2 — SCOPE ANALYSIS (extended: nested def tracking)
# =========================================================================
class ScopeAnalyzer(ast.NodeVisitor):
def __init__(self, module_all: Set[str]) -> None:
self.scope_stack: List[Dict[str, Any]] = [
{"name": "<module>", "locals": set(), "globals": set(),
"nonlocals": set(), "args": set(), "imports": set()}
]
self.safe_locals: Dict[int, Set[str]] = {}
self.used_builtins: Set[str] = set()
self.import_names: Set[str] = set()
self._all_builtins = frozenset(dir(_builtins_module))
self._module_all = module_all
self._func_counter = 0
self.blocking_names: Dict[int, Set[str]] = {}
def _cur(self) -> Dict[str, Any]:
return self.scope_stack[-1]
def _is_shadowed(self, name: str) -> bool:
for scope in reversed(self.scope_stack):
if name in scope["locals"] or name in scope["args"] or name in scope["imports"]:
return True
return False
def _visit_funcdef(self, node: ast.AST) -> None:
args_set: Set[str] = set()
arguments = node.args
for a in arguments.args + getattr(arguments, "posonlyargs", []) + arguments.kwonlyargs:
args_set.add(a.arg)
if arguments.vararg:
args_set.add(arguments.vararg.arg)
if arguments.kwarg:
args_set.add(arguments.kwarg.arg)
scope = {
"name": node.name, "locals": set(), "globals": set(),
"nonlocals": set(), "args": args_set, "imports": set(),
}
self.scope_stack.append(scope)
self._func_counter += 1
node._stable_id = self._func_counter
# Detect dynamic introspection
has_dynamic = False
for child in ast.walk(node):
if isinstance(child, ast.Call) and isinstance(child.func, ast.Name):
if child.func.id in DYNAMIC_INTROSPECTION:
has_dynamic = True
break
# Collect nested function/class names as locals of THIS scope
for stmt in node.body:
if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
n = stmt.name
if (not (n.startswith("__") and n.endswith("__"))
and n not in self._module_all
and n not in ABSOLUTE_PROTECTED):
scope["locals"].add(n)
# Nonlocal refs from child functions
nonlocal_from_children: Set[str] = set()
for child in ast.iter_child_nodes(node):
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
for gc in ast.walk(child):
if isinstance(gc, ast.Nonlocal):
nonlocal_from_children.update(gc.names)
self.generic_visit(node)
safe = (scope["locals"] - scope["globals"] - scope["nonlocals"]
- scope["args"] - scope["imports"] - nonlocal_from_children
- self._module_all)
if has_dynamic:
log.debug(" ⊘ %s: dynamic scope — renaming disabled", node.name)
safe = set()
self.safe_locals[node._stable_id] = safe
# blocking = any name defined in this scope that should shadow outer renames
self.blocking_names[node._stable_id] = (scope["locals"] | scope["args"] |
scope["imports"] | scope["globals"] |
scope["nonlocals"])
self.scope_stack.pop()
def visit_Lambda(self, node):
args_set: Set[str] = set()
for a in node.args.args + getattr(node.args, "posonlyargs", []) + node.args.kwonlyargs:
args_set.add(a.arg)
if node.args.vararg: args_set.add(node.args.vararg.arg)
if node.args.kwarg: args_set.add(node.args.kwarg.arg)
scope = {
"name": "<lambda>", "locals": set(), "globals": set(),
"nonlocals": set(), "args": args_set, "imports": set(),
}
self.scope_stack.append(scope)
self._func_counter += 1
node._stable_id = self._func_counter
self.generic_visit(node)
# Lambdas don't really have "locals" in the store sense usually, but args shadow.
self.safe_locals[node._stable_id] = set()
self.blocking_names[node._stable_id] = args_set
self.scope_stack.pop()
def visit_ClassDef(self, node):
# Class bodies have their own scope for attributes, but it's complex.
# We at least push a scope so nested functions/classes don't leak out.
scope = {
"name": node.name, "locals": set(), "globals": set(),
"nonlocals": set(), "args": set(), "imports": set(),
}
self.scope_stack.append(scope)
self._func_counter += 1
node._stable_id = self._func_counter
self.generic_visit(node)
self.safe_locals[node._stable_id] = set()
self.blocking_names[node._stable_id] = scope["locals"] | scope["imports"]
self.scope_stack.pop()
def visit_FunctionDef(self, node): self._visit_funcdef(node)
def visit_AsyncFunctionDef(self, node): self._visit_funcdef(node)
def visit_Global(self, node): self._cur()["globals"].update(node.names)
def visit_Nonlocal(self, node): self._cur()["nonlocals"].update(node.names)
def visit_Import(self, node):
for alias in node.names:
n = alias.asname if alias.asname else alias.name.split(".")[0]
self._cur()["imports"].add(n)
self.import_names.add(n)
def visit_ImportFrom(self, node):
for alias in node.names:
n = alias.asname if alias.asname else alias.name
self._cur()["imports"].add(n)
self.import_names.add(n)
def visit_Name(self, node):
if isinstance(node.ctx, ast.Store):
if len(self.scope_stack) > 1:
self._cur()["locals"].add(node.id)
elif isinstance(node.ctx, ast.Load):
if (node.id in self._all_builtins
and not (node.id.startswith("__") and node.id.endswith("__"))
and node.id not in {"super", "eval", "exec", "locals", "globals", "vars"}
and not self._is_shadowed(node.id)):
self.used_builtins.add(node.id)
self.generic_visit(node)
def visit_MatchAs(self, node):
if getattr(node, "name", None) is not None and len(self.scope_stack) > 1:
self._cur()["locals"].add(node.name)
self.generic_visit(node)
def visit_MatchStar(self, node):
if getattr(node, "name", None) is not None and len(self.scope_stack) > 1:
self._cur()["locals"].add(node.name)
self.generic_visit(node)
def visit_MatchMapping(self, node):
if getattr(node, "rest", None) is not None and len(self.scope_stack) > 1:
self._cur()["locals"].add(node.rest)
self.generic_visit(node)
# =========================================================================
# PHASE 3 — INJECTION BUILDER (extended: base85 decoder, noise)
# =========================================================================
class InjectionBuilder:
def __init__(self, seed: int, used_builtins: Set[str],
features: Dict[str, bool]) -> None:
self.seed = seed
self.features = features
self._rng = random.Random(seed)
self.decoder_name = f"_d{_h(seed, 'dec1')[:10]}"
self.decoder2_name = f"_e{_h(seed, 'dec2')[:10]}"
self.alias_map: Dict[str, str] = {}
if features["builtins_alias"] and used_builtins:
for bname in sorted(used_builtins):
self.alias_map[bname] = f"_b{_h(seed, 'ba', bname)[:8]}"
self._noise_names: List[str] = []
if features["dead_code"]:
for i in range(self._rng.randint(3, 8)):
self._noise_names.append(f"_{_h(seed, 'noise', i)[:8]}")
def build_injection_nodes(self) -> List[ast.stmt]:
stmts: List[ast.stmt] = []
# Decoder 1: rotating-key XOR
if self.features["strings"]:
src = (f"def {self.decoder_name}(_d, _k):\n"
f" return bytes([(_b ^ (_k + _i) % 256) for _i, _b in enumerate(_d)]).decode()")
stmts.extend(ast.parse(src).body)
# Decoder 2: base85 + XOR
if self.features["strings"]:
src2 = (f"def {self.decoder2_name}(_s, _k):\n"
f" _r = __import__('base64').b85decode(_s)\n"
f" return bytes([(_b ^ (_k + _i) % 256) for _i, _b in enumerate(_r)]).decode()")
stmts.extend(ast.parse(src2).body)
# Builtin aliases
if self.features["builtins_alias"] and self.alias_map:
bmod = f"_m{_h(self.seed, 'bmod')[:8]}"
lines = [f"{bmod} = __import__('builtins')"]
for orig, alias in sorted(self.alias_map.items()):
lines.append(f"{alias} = {bmod}.{orig}")
stmts.extend(ast.parse("\n".join(lines)).body)
# Dead variable noise
if self.features["dead_code"]:
noise = []
for name in self._noise_names:
s = self._rng.randint(0, 4)
if s == 0: noise.append(f"{name} = lambda *_: None")
elif s == 1: noise.append(f"{name} = ({self._rng.randint(-9999,9999)} ^ {self._rng.randint(-9999,9999)}) or []")
elif s == 2: noise.append(f"{name} = type('', (), {{}})")
elif s == 3: noise.append(f"{name} = (None,) * {self._rng.randint(1,5)}")
else: noise.append(f"{name} = bytes({self._rng.randint(0,8)})")
if noise:
stmts.extend(ast.parse("\n".join(noise)).body)
for stmt in stmts:
for node in ast.walk(stmt):
node._injected = True
return stmts
# =========================================================================
# PHASE 4 — TRANSFORM ENGINE (T1–T11, stats, nested func renaming)
# =========================================================================
class TransformEngine(ast.NodeTransformer):
def __init__(self, seed: int, safe_locals: Dict[int, Set[str]],
blocking_names: Dict[int, Set[str]],
decoder_name: str, decoder2_name: str,
alias_map: Dict[str, str], features: Dict[str, bool]) -> None:
super().__init__()
self.seed = seed
self.safe_locals = safe_locals
self.blocking_names = blocking_names
self.decoder_name = decoder_name
self.decoder2_name = decoder2_name
self.alias_map = alias_map
self.features = features
self._rng = random.Random(seed)
self._func_stack: List[Dict[str, str]] = [{}]
self.stats = {
"strings_encoded": 0, "integers_masked": 0,
"variables_renamed": 0, "functions_renamed": 0,
"booleans_rewritten": 0, "comparisons_inverted": 0,
"docstrings_stripped": 0, "strings_split": 0,
}
# -- helpers ----------------------------------------------------------
def _gen_local(self, original: str, stable_id: int) -> str:
h = _h(self.seed, stable_id, original)[:8]
prefixes = ["_", "_v", "_x", "_q", "_z"]
return f"{prefixes[int(h, 16) % len(prefixes)]}{h}"
def _in_match_pattern(self, node) -> bool:
cur = node
while hasattr(cur, "parent"):
cur = cur.parent
if _MATCH_PATTERN_TYPES and isinstance(cur, _MATCH_PATTERN_TYPES):
return True
return False
def _is_annotation(self, node) -> bool:
p = getattr(node, "parent", None)
if p is None: return False
if isinstance(p, ast.AnnAssign) and p.annotation is node: return True
if isinstance(p, ast.arg) and getattr(p, "annotation", None) is node: return True
if isinstance(p, (ast.FunctionDef, ast.AsyncFunctionDef)):
if getattr(p, "returns", None) is node: return True
return False
def _is_decorator(self, node) -> bool:
p = getattr(node, "parent", None)
if p is None: return False
if isinstance(p, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
if hasattr(p, "decorator_list") and node in p.decorator_list: return True
return False
def _is_fstring(self, node) -> bool:
cur = node
while hasattr(cur, "parent"):
cur = cur.parent
if isinstance(cur, ast.JoinedStr): return True
return False
def _is_docstring(self, node) -> bool:
if not isinstance(node, ast.Expr): return False
if not isinstance(node.value, ast.Constant): return False
if not isinstance(node.value.value, str): return False
p = getattr(node, "parent", None)
if p and isinstance(p, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
body = getattr(p, "body", [])
if body and body[0] is node: return True
return False
def _safe_guard(self, node) -> bool:
return (self._in_match_pattern(node) or self._is_annotation(node)
or self._is_fstring(node) or self._is_decorator(node))
# -- visit guard ------------------------------------------------------
def visit(self, node):
if getattr(node, "_injected", False): return node
return super().visit(node)
# -- T1: Local + nested func/class renaming ---------------------------
def visit_FunctionDef(self, node): return self._handle_funcdef(node)
def visit_AsyncFunctionDef(self, node): return self._handle_funcdef(node)
def _handle_funcdef(self, node):
# Rename this function's name if it's in the parent scope's mapping
if self._func_stack:
parent_map = self._func_stack[-1]
if node.name in parent_map:
node.name = parent_map[node.name]
self.stats["functions_renamed"] += 1
stable_id = getattr(node, "_stable_id", 0)
safe = self.safe_locals.get(stable_id, set())
blocking = self.blocking_names.get(stable_id, set())
mapping: Dict[str, str] = {}
# First, add self-mappings for blocking names to protect them from outer renames
for name in blocking:
mapping[name] = name
# Then, apply renames for safe locals
for var in sorted(safe):
mapping[var] = self._gen_local(var, stable_id)
self.stats["variables_renamed"] += 1
self._func_stack.append(mapping)
self.generic_visit(node)
self._func_stack.pop()
return node
def visit_Lambda(self, node):
stable_id = getattr(node, "_stable_id", 0)
blocking = self.blocking_names.get(stable_id, set())
mapping: Dict[str, str] = {name: name for name in blocking}
self._func_stack.append(mapping)
self.generic_visit(node)
self._func_stack.pop()
return node
def visit_ClassDef(self, node):
# Rename inner class name if in parent scope's mapping
if self._func_stack:
parent_map = self._func_stack[-1]
if node.name in parent_map:
node.name = parent_map[node.name]
self.stats["functions_renamed"] += 1
stable_id = getattr(node, "_stable_id", 0)
blocking = self.blocking_names.get(stable_id, set())
mapping: Dict[str, str] = {name: name for name in blocking}
self._func_stack.append(mapping)
self.generic_visit(node)
self._func_stack.pop()
return node
# -- T2 + T1: Name rewriting ------------------------------------------
def visit_Name(self, node):
if (self.features["builtins_alias"]
and isinstance(node.ctx, ast.Load) and node.id in self.alias_map
and not self._is_annotation(node) and not self._is_decorator(node)):
node.id = self.alias_map[node.id]
return node
for scope_map in reversed(self._func_stack):
if node.id in scope_map:
node.id = scope_map[node.id]
return node
return node
def visit_MatchAs(self, node):
if getattr(node, "name", None) is not None:
for scope_map in reversed(self._func_stack):
if node.name in scope_map:
node.name = scope_map[node.name]
break
self.generic_visit(node)
return node
def visit_MatchStar(self, node):
if getattr(node, "name", None) is not None:
for scope_map in reversed(self._func_stack):
if node.name in scope_map:
node.name = scope_map[node.name]
break
self.generic_visit(node)
return node
def visit_MatchMapping(self, node):
if getattr(node, "rest", None) is not None:
for scope_map in reversed(self._func_stack):
if node.rest in scope_map:
node.rest = scope_map[node.rest]
break
self.generic_visit(node)
return node
# -- T3: Integer masking (5 strategies) + T10: deep nesting -----------
def _make_int_xor(self, value):
k1 = self._rng.randint(0x1000, 0xFFFF)
k2 = self._rng.randint(0x100, 0xFFF)
masked = value ^ k1 ^ k2
return ast.BinOp(
left=ast.BinOp(left=ast.BinOp(
left=ast.Constant(value=masked), op=ast.BitXor(),
right=ast.Constant(value=k1)),
op=ast.BitXor(), right=ast.Constant(value=k2)),
op=ast.BitOr(), right=ast.Constant(value=0))
def _make_int_arith(self, value):
n = self._rng.randint(10000, 99999)
s = self._rng.choice([1, -1])
off = n * s
return ast.BinOp(left=ast.Constant(value=value + off),
op=ast.Sub(), right=ast.Constant(value=off))
def _make_int_mult(self, value):
if value == 0: return self._make_int_arith(value)
n = self._rng.choice([3, 7, 11, 13, 17, 19, 23])
return ast.BinOp(left=ast.BinOp(
left=ast.Constant(value=value * n), op=ast.FloorDiv(),
right=ast.Constant(value=n)),
op=ast.Add(), right=ast.Constant(value=0))
def _make_int_shift(self, value):
"""Strategy using left shift + right shift identity."""
if value < 0: return self._make_int_arith(value)
shift = self._rng.randint(1, 4)
return ast.BinOp(
left=ast.BinOp(left=ast.Constant(value=value << shift),
op=ast.RShift(), right=ast.Constant(value=shift)),
op=ast.BitOr(), right=ast.Constant(value=0))
def _make_int_deep(self, value):
"""T10: deep nested expression (2 layers)."""
inner = self._rng.choice([self._make_int_xor, self._make_int_arith,
self._make_int_shift])(value)
wrap_n = self._rng.randint(1000, 9999)
return ast.BinOp(
left=ast.BinOp(left=inner, op=ast.Add(),
right=ast.Constant(value=wrap_n)),
op=ast.Sub(), right=ast.Constant(value=wrap_n))
# -- T4: String encoding (2 strategies) + T11: splitting ---------------
def _encode_string_xor(self, s: str):
"""Strategy 1: rotating-key XOR list."""
key = self._rng.randint(1, 255)
raw = s.encode("utf-8")
xored = [(b ^ ((key + i) % 256)) for i, b in enumerate(raw)]
self.stats["strings_encoded"] += 1
return ast.Call(
func=ast.Name(id=self.decoder_name, ctx=ast.Load()),
args=[ast.List(elts=[ast.Constant(value=v) for v in xored],
ctx=ast.Load()),
ast.Constant(value=key)],
keywords=[])
def _encode_string_b85(self, s: str):
"""Strategy 2: base85 + rotating XOR."""
key = self._rng.randint(1, 255)
raw = s.encode("utf-8")
xored = bytes([(b ^ ((key + i) % 256)) for i, b in enumerate(raw)])
b85 = base64.b85encode(xored).decode("ascii")
self.stats["strings_encoded"] += 1
return ast.Call(
func=ast.Name(id=self.decoder2_name, ctx=ast.Load()),
args=[ast.Constant(value=b85), ast.Constant(value=key)],
keywords=[])
def _encode_string(self, s: str):
"""Select encoding strategy randomly."""
try:
s.encode("utf-8")
except UnicodeEncodeError:
return None
if len(s) == 0:
return None
return self._rng.choice([self._encode_string_xor, self._encode_string_b85])(s)
def _encode_string_split(self, s: str):
"""T11: Split long strings into encoded chunks joined with +."""
chunk_size = max(3, len(s) // self._rng.randint(2, 3))
parts = [s[i:i+chunk_size] for i in range(0, len(s), chunk_size)]
if len(parts) < 2:
return self._encode_string(s)
self.stats["strings_split"] += 1
nodes = [self._encode_string(p) for p in parts]
if any(n is None for n in nodes):
return self._encode_string(s)
result = nodes[0]
for n in nodes[1:]:
result = ast.BinOp(left=result, op=ast.Add(), right=n)
return result
# -- Constant visitor -------------------------------------------------
def visit_Constant(self, node):
if self._safe_guard(node): return node
parent = getattr(node, "parent", None)
# T5: Boolean rewriting
if isinstance(node.value, bool):
self.stats["booleans_rewritten"] += 1
return ast.UnaryOp(op=ast.Not(),
operand=ast.Constant(value=not node.value))
# T3 + T10: Integer masking
if isinstance(node.value, int) and not isinstance(node.value, bool):
self.stats["integers_masked"] += 1
s = self._rng.randint(0, 4)
if s == 0: return self._make_int_xor(node.value)
elif s == 1: return self._make_int_arith(node.value)
elif s == 2: return self._make_int_mult(node.value)
elif s == 3: return self._make_int_shift(node.value)
else: return self._make_int_deep(node.value)
# T4 + T11: String encoding
if (self.features["strings"] and isinstance(node.value, str)
and parent is not None and isinstance(parent, SAFE_STRING_PARENTS)):
if len(node.value) > self.features.get("split_threshold", 8) and self._rng.random() < 0.5:
result = self._encode_string_split(node.value)
else:
result = self._encode_string(node.value)
if result is not None:
return result
return node
# -- T6: Comparison inversion -----------------------------------------
def visit_Compare(self, node):
self.generic_visit(node)
if not self.features["bool_rewrite"]: return node
if len(node.ops) != 1 or self._rng.random() > 0.40: return node
op = node.ops[0]
if isinstance(op, ast.Eq):
self.stats["comparisons_inverted"] += 1
return ast.UnaryOp(op=ast.Not(), operand=ast.Compare(
left=node.left, ops=[ast.NotEq()], comparators=node.comparators))
if isinstance(op, ast.NotEq):
self.stats["comparisons_inverted"] += 1
return ast.UnaryOp(op=ast.Not(), operand=ast.Compare(
left=node.left, ops=[ast.Eq()], comparators=node.comparators))
return node
# -- T7: If/While double negation -------------------------------------
def visit_If(self, node):
self.generic_visit(node)
if self.features["bool_rewrite"] and self._rng.random() < 0.40:
node.test = ast.UnaryOp(op=ast.Not(),
operand=ast.UnaryOp(op=ast.Not(), operand=node.test))
return node
def visit_While(self, node):
self.generic_visit(node)
if self.features["bool_rewrite"] and self._rng.random() < 0.40:
node.test = ast.UnaryOp(op=ast.Not(),
operand=ast.UnaryOp(op=ast.Not(), operand=node.test))
return node
# -- T8: Docstring stripping ------------------------------------------
def visit_Expr(self, node):
self.generic_visit(node)
if self.features["strip_docstrings"] and self._is_docstring(node):
self.stats["docstrings_stripped"] += 1
return ast.Pass()
return node
# =========================================================================
# PHASE 5 — DEAD CODE INJECTOR (T9: opaque predicates + dead branches)
# =========================================================================
class DeadCodeInjector(ast.NodeVisitor):
"""Injects dead branches and opaque predicates into function bodies."""
def __init__(self, seed: int, features: Dict[str, bool]) -> None:
self._rng = random.Random(seed + 7919)
self.features = features
self.stats = {"dead_branches": 0, "opaque_predicates": 0}
def visit_FunctionDef(self, node):
self._inject(node)
self.generic_visit(node)
def visit_AsyncFunctionDef(self, node):
self._inject(node)
self.generic_visit(node)
def _inject(self, node):
if not self.features.get("dead_code", False):
return
if len(node.body) < 2:
return
n = self._rng.randint(0, min(2, max(1, len(node.body) // 3)))
for _ in range(n):
pos = self._rng.randint(1, len(node.body))
branch = self._make_branch()
node.body.insert(pos, branch)
def _make_branch(self):
s = self._rng.randint(0, 4)
dv = f"_z{self._rng.randint(100000, 999999)}"
if s <= 1:
# Dead branch: if (always-false): dead_code
k = self._rng.randint(1000, 9999)
test = ast.Compare(
left=ast.BinOp(left=ast.Constant(value=k), op=ast.BitXor(),
right=ast.Constant(value=k)),
ops=[ast.NotEq()], comparators=[ast.Constant(value=0)])
body = [ast.Assign(targets=[ast.Name(id=dv, ctx=ast.Store())],
value=ast.Constant(value=None))]
branch = ast.If(test=test, body=body, orelse=[])
self.stats["dead_branches"] += 1
elif s == 2:
# while (0 ^ 0) > 1: break
test = ast.Compare(
left=ast.BinOp(left=ast.Constant(value=0), op=ast.BitXor(), right=ast.Constant(value=0)),
ops=[ast.Gt()], comparators=[ast.Constant(value=1)])
branch = ast.While(test=test, body=[ast.Break()], orelse=[])
self.stats["dead_branches"] += 1
else:
# Opaque predicate: if (always-true): dead_var = noise (harmless)
opaq = self._rng.randint(0, 2)
if opaq == 0:
# id(0) >= 0
test = ast.Compare(
left=ast.Call(func=ast.Name(id="id", ctx=ast.Load()), args=[ast.Constant(value=0)], keywords=[]),
ops=[ast.GtE()], comparators=[ast.Constant(value=0)])
elif opaq == 1:
# isinstance([], list)
test = ast.Call(
func=ast.Name(id="isinstance", ctx=ast.Load()),
args=[ast.List(elts=[], ctx=ast.Load()), ast.Name(id="list", ctx=ast.Load())],
keywords=[])
else:
# len(()) == 0
test = ast.Compare(
left=ast.Call(func=ast.Name(id="len", ctx=ast.Load()), args=[ast.Tuple(elts=[], ctx=ast.Load())], keywords=[]),
ops=[ast.Eq()], comparators=[ast.Constant(value=0)])
body = [ast.Assign(
targets=[ast.Name(id=dv, ctx=ast.Store())],
value=ast.Call(func=ast.Name(id="type", ctx=ast.Load()),
args=[ast.Constant(value=""),
ast.Tuple(elts=[], ctx=ast.Load()),
ast.Dict(keys=[], values=[])],
keywords=[]))]
branch = ast.If(test=test, body=body, orelse=[])
self.stats["opaque_predicates"] += 1
# Mark all nodes as injected
for n in ast.walk(branch):
n._injected = True
return branch
# =========================================================================
# PHASE 6 — POST-PROCESSOR
# =========================================================================
class PostProcessor:
def __init__(self, seed: int, features: Dict[str, bool]) -> None:
self._rng = random.Random(seed)
self.features = features
def process(self, code: str) -> str:
if self.features.get("comment_noise", False):
code = self._inject_comments(code)
return code
def _inject_comments(self, code: str) -> str:
lines = code.split("\n")
decoys = [
"# TODO: refactor this section",
"# FIXME: edge case handling",
"# NOTE: validated upstream",
"# WARNING: do not modify without tests",
"# HACK: temporary workaround",
"# DEPRECATED: will be removed in v4",
"# PERF: optimized path",
"# SECURITY: input sanitized",
"# DEBUG: verified in staging",
"# COMPAT: backwards compatibility shim",
"# REVIEW: pending code review",
"# OPTIMIZE: consider caching",
]
result = []
for line in lines:
result.append(line)
if self._rng.random() < 0.10 and line.strip():
indent = len(line) - len(line.lstrip())
result.append(" " * indent + self._rng.choice(decoys))
return "\n".join(result)
# =========================================================================
# PIPELINE ORCHESTRATOR
# =========================================================================
class Pipeline:
def __init__(self, source: str, seed: int, features: Dict[str, bool]) -> None:
self.source = source
self.seed = seed
self.features = features
self._stats: Dict[str, int] = {}
def _extract_all_names(self, tree: ast.Module) -> Set[str]:
"""Extract names from __all__ = [...] at module level."""
names: Set[str] = set()
for node in tree.body:
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id == "__all__":
if isinstance(node.value, (ast.List, ast.Tuple, ast.Set)):
for elt in node.value.elts:
if isinstance(elt, ast.Constant) and isinstance(elt.value, str):
names.add(elt.value)
return names
def _find_insertion_point(self, tree: ast.Module) -> int:
idx = 0
for node in tree.body:
if (isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant)
and isinstance(node.value.value, str)):
idx += 1; continue
if isinstance(node, (ast.Import, ast.ImportFrom)):
idx += 1; continue
break
return idx
def run(self) -> str:
# Phase 1: Input validation
log.debug("Phase 1: Input validation")
try:
tree = ast.parse(self.source)
compile(self.source, "<input>", "exec")
except SyntaxError as exc:
raise RuntimeError(f"Input has invalid syntax: {exc}") from exc
# Phase 2: AST enrichment
log.debug("Phase 2: AST enrichment")
tree._depth = 0
ASTEnricher().visit(tree)
# Phase 3: __all__ extraction
module_all = self._extract_all_names(tree)
log.debug("Phase 3: __all__ names: %s", module_all or "(none)")
# Phase 4: Scope analysis
log.debug("Phase 4: Scope analysis")
analyzer = ScopeAnalyzer(module_all)
analyzer.visit(tree)
log.debug(" Scopes: %d | Builtins: %d | Imports: %d",
len(analyzer.safe_locals), len(analyzer.used_builtins),
len(analyzer.import_names))
# Phase 5: Build injections
log.debug("Phase 5: Building injections")
injector = InjectionBuilder(self.seed, analyzer.used_builtins, self.features)
inj_nodes = injector.build_injection_nodes()
# Phase 6: Insert injections
if inj_nodes:
idx = self._find_insertion_point(tree)
tree.body[idx:idx] = inj_nodes
log.debug(" Injected %d stmts at index %d", len(inj_nodes), idx)
# Phase 7: Re-enrich
tree._depth = 0
ASTEnricher().visit(tree)
# Phase 8: Transform engine
log.debug("Phase 8: Transform engine")
engine = TransformEngine(
seed=self.seed, safe_locals=analyzer.safe_locals,
blocking_names=analyzer.blocking_names,
decoder_name=injector.decoder_name,
decoder2_name=injector.decoder2_name,
alias_map=injector.alias_map, features=self.features)
transformed = engine.visit(tree)
# Phase 9: Dead code injection
log.debug("Phase 9: Dead code injection")
dc = DeadCodeInjector(self.seed, self.features)
dc.visit(transformed)
ast.fix_missing_locations(transformed)
# Phase 10: Unparse + validate
log.debug("Phase 10: Unparse + output validation")
output = ast.unparse(transformed)
try:
out_tree = ast.parse(output)
compile(out_tree, "<output>", "exec")
except Exception as exc:
raise RuntimeError(f"CRITICAL: output compilation failed.\n{exc}") from exc
# Phase 11: Post-processing
log.debug("Phase 11: Post-processing")
post = PostProcessor(self.seed, self.features)
output = post.process(output)
# Phase 12: Final validation
log.debug("Phase 12: Final validation")
try:
compile(output, "<final>", "exec")
except Exception as exc:
raise RuntimeError(f"CRITICAL: final compilation failed.\n{exc}") from exc
# Aggregate stats
self._stats = {**engine.stats, **dc.stats}
return output
def get_stats(self) -> Dict[str, int]:
return dict(self._stats)
# =========================================================================
# CLI
# =========================================================================
def main() -> None:
parser = argparse.ArgumentParser(
prog="BlankOBFv3",
description="BlankOBF v3 — Production-grade AST code transformer",
)
parser.add_argument("input", help="Python source file")
parser.add_argument("-o", "--output", default=None, help="Output file")
parser.add_argument("--seed", type=int, default=None, help="Deterministic seed")
parser.add_argument("--check", action="store_true", help="Validate only")
parser.add_argument("--dry-run", action="store_true", help="Print to stdout")
parser.add_argument("--verbose", action="store_true", help="Debug logs")
parser.add_argument("--profile", action="store_true", help="Show transform stats")
parser.add_argument("--split-threshold", type=int, default=8, help="Min length for string splitting")
parser.add_argument("--no-strings", action="store_true")
parser.add_argument("--no-builtins", action="store_true")
parser.add_argument("--no-bool-rewrite", action="store_true")
parser.add_argument("--no-dead-code", action="store_true")
parser.add_argument("--no-comments", action="store_true")
parser.add_argument("--no-strip-docs", action="store_true")
args = parser.parse_args()
if args.verbose: log.setLevel(logging.DEBUG)
seed = args.seed if args.seed is not None else random.randint(1, 999_999)
if not os.path.isfile(args.input):
log.error("File not found: %s", args.input); sys.exit(1)
features = {
"strings": not args.no_strings, "builtins_alias": not args.no_builtins,
"bool_rewrite": not args.no_bool_rewrite, "dead_code": not args.no_dead_code,
"comment_noise": not args.no_comments, "strip_docstrings": not args.no_strip_docs,
"split_threshold": args.split_threshold,
}
try:
with open(args.input, "r", encoding="utf-8") as fh:
source = fh.read()
log.info("Processing %s (seed=%d)", args.input, seed)
pipe = Pipeline(source, seed, features)
result = pipe.run()
log.info("Transformation successful ✓")
if args.profile:
stats = pipe.get_stats()
log.info("── Profile ──")
for k, v in sorted(stats.items()):