tzero-mcp 11.15.3 → 12.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/CONTRIBUTING.md +4 -4
- package/README.md +5 -5
- package/bin/postinstall.js +10 -2
- package/bin/tzero-mcp.js +1 -1
- package/bin/tzero.js +17 -0
- package/package.json +1 -1
- package/src/addmcp.py +34 -23
- package/src/app.py +1 -1
- package/src/main.py +6 -0
- package/src/tzero/__init__.py +10 -0
- package/src/tzero/anti_rea/__init__.py +70 -0
- package/src/tzero/anti_rea/algebraic_mutator.py +86 -0
- package/src/tzero/anti_rea/anti_agent_guard.py +96 -0
- package/src/tzero/anti_rea/anti_debugger.py +239 -0
- package/src/tzero/anti_rea/anti_vm.py +160 -0
- package/src/tzero/anti_rea/asar_shield.py +99 -0
- package/src/tzero/anti_rea/auditor.py +158 -0
- package/src/tzero/anti_rea/bpe_disrupter.py +48 -0
- package/src/tzero/anti_rea/bytecode_trap.py +85 -0
- package/src/tzero/anti_rea/canary_beacon.py +187 -0
- package/src/tzero/anti_rea/cli.py +102 -0
- package/src/tzero/anti_rea/confusables.py +86 -0
- package/src/tzero/anti_rea/engine.py +204 -0
- package/src/tzero/anti_rea/extractor_shield.py +102 -0
- package/src/tzero/anti_rea/flattener.py +136 -0
- package/src/tzero/anti_rea/gui.py +267 -0
- package/src/tzero/anti_rea/honeypot.py +58 -0
- package/src/tzero/anti_rea/integrity_guard.py +66 -0
- package/src/tzero/anti_rea/jailbreak_decoy.py +77 -0
- package/src/tzero/anti_rea/mcp_poison.py +41 -0
- package/src/tzero/anti_rea/native_bridge.py +169 -0
- package/src/tzero/anti_rea/rdtsc_guard.py +64 -0
- package/src/tzero/anti_rea/string_vault.py +94 -0
- package/src/tzero/anti_rea/sybil_network.py +53 -0
- package/src/tzero/anti_rea/timing_guard.py +46 -0
- package/src/tzero/anti_rea/token_bomb.py +65 -0
- package/src/tzero/anti_rea/traps.py +76 -0
- package/src/tzero/anti_rea/vm_obfuscator.py +182 -0
- package/src/tzero/siber_akademi.ico +0 -0
- package/src/tzero/siber_akademi_icon.py +1 -1
- package/src/tzero/tzero_armor.py +165 -0
- package/src/tzero/tzero_bridge.py +28 -15
- package/src/tzero/tzero_budget.py +10 -3
- package/src/tzero/tzero_card.py +7 -5
- package/src/tzero/tzero_ci.py +1 -0
- package/src/tzero/tzero_contracts.py +30 -11
- package/src/tzero/tzero_dashboard.py +34 -14
- package/src/tzero/tzero_debt.py +14 -5
- package/src/tzero/tzero_federation.py +11 -6
- package/src/tzero/tzero_fixer/security_zero_leak.py +21 -3
- package/src/tzero/tzero_golden.py +11 -6
- package/src/tzero/tzero_graph_hud.html +1 -1
- package/src/tzero/tzero_growth.py +10 -10
- package/src/tzero/tzero_jarvis/agent_guard.py +16 -10
- package/src/tzero/tzero_jarvis/workspace_orchestrator.py +34 -23
- package/src/tzero/tzero_lsp.py +1 -1
- package/src/tzero/tzero_mcp.py +89 -31
- package/src/tzero/tzero_mutation.py +44 -16
- package/src/tzero/tzero_neural_cortex.py +1 -1
- package/src/tzero/tzero_pc_fixer.py +21 -3
- package/src/tzero/tzero_promo.py +196 -36
- package/src/tzero/tzero_rust_bridge.py +1086 -42
- package/src/tzero/tzero_scip.py +15 -2
- package/src/tzero/tzero_semantic_merge.py +34 -10
- package/src/tzero/tzero_task_benchmark.py +2 -2
- package/src/tzero/tzero_telemetry.py +146 -0
- package/src/tzero/tzero_terminal.py +366 -0
- package/src/tzero/tzero_traffic.py +350 -0
- package/src/tzero/tzero_tui.py +342 -133
- package/src/tzero/tzero_v3.py +652 -29
- package/src/tzero/tzero_welcome.py +124 -37
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Master Anti-REA Engine.
|
|
3
|
+
|
|
4
|
+
Unified coordinator applying the 24-Tier Anti-REA Armor Matrix across
|
|
5
|
+
source files, packages, compiled executables, and Electron archives.
|
|
6
|
+
|
|
7
|
+
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
8
|
+
Part of Siber Akademi T-Zero Security Suite.
|
|
9
|
+
License: MIT
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
from typing import Dict, Any, Optional
|
|
14
|
+
|
|
15
|
+
from .traps import AdversarialTrapGenerator
|
|
16
|
+
from .extractor_shield import ExtractorShield
|
|
17
|
+
from .flattener import ControlFlowFlattener
|
|
18
|
+
from .token_bomb import TokenBombGenerator
|
|
19
|
+
from .confusables import HomoglyphDesynchronizer
|
|
20
|
+
from .honeypot import HoneypotGenerator
|
|
21
|
+
from .mcp_poison import MCPProtocolPoisoner
|
|
22
|
+
from .sybil_network import SybilNetworkGenerator
|
|
23
|
+
from .timing_guard import TimingGuard
|
|
24
|
+
from .auditor import AIResistanceAuditor
|
|
25
|
+
from .vm_obfuscator import DynamicVMObfuscator
|
|
26
|
+
from .bytecode_trap import BytecodeTrap
|
|
27
|
+
from .jailbreak_decoy import CognitiveJailbreakDecoy
|
|
28
|
+
from .anti_agent_guard import AntiAgentGuard
|
|
29
|
+
from .algebraic_mutator import AlgebraicMutator
|
|
30
|
+
from .integrity_guard import MemoryIntegrityGuard
|
|
31
|
+
from .bpe_disrupter import BPETokenDisrupter
|
|
32
|
+
from .native_bridge import NativeBridge
|
|
33
|
+
from .anti_debugger import AntiDebugger
|
|
34
|
+
from .canary_beacon import CanaryBeacon
|
|
35
|
+
from .string_vault import StringVault
|
|
36
|
+
from .asar_shield import AsarShield
|
|
37
|
+
from .anti_vm import AntiVMGuard
|
|
38
|
+
from .rdtsc_guard import RDTSCTimingGuard
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class AntiREAEngine:
|
|
42
|
+
"""Master engine orchestrating military-grade Anti-REA code and binary protection."""
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def protect_python_source(
|
|
46
|
+
cls,
|
|
47
|
+
source_code: str,
|
|
48
|
+
flatten: bool = True,
|
|
49
|
+
token_chaff: bool = True,
|
|
50
|
+
prompt_traps: bool = True,
|
|
51
|
+
homoglyphs: bool = True,
|
|
52
|
+
honeypot: bool = True,
|
|
53
|
+
mcp_poison: bool = True,
|
|
54
|
+
sybil_mesh: bool = True,
|
|
55
|
+
timing_guard: bool = True,
|
|
56
|
+
decompiler_trap: bool = True,
|
|
57
|
+
jailbreak_decoy: bool = True,
|
|
58
|
+
anti_agent_guard: bool = True,
|
|
59
|
+
vm_container: bool = True,
|
|
60
|
+
algebraic_mutation: bool = True,
|
|
61
|
+
integrity_guard: bool = True,
|
|
62
|
+
bpe_disrupt: bool = True,
|
|
63
|
+
anti_debugger: bool = True,
|
|
64
|
+
string_vault: bool = True,
|
|
65
|
+
anti_vm: bool = True,
|
|
66
|
+
rdtsc_guard: bool = True,
|
|
67
|
+
webhook_canary: Optional[str] = None,
|
|
68
|
+
seed: int = 42,
|
|
69
|
+
) -> str:
|
|
70
|
+
"""Applies comprehensive 24-tier Anti-REA protection passes to Python source code."""
|
|
71
|
+
code = source_code
|
|
72
|
+
|
|
73
|
+
# 1. Algebraic Identity Mutation (Mixed Boolean-Arithmetic)
|
|
74
|
+
if algebraic_mutation:
|
|
75
|
+
code = AlgebraicMutator.mutate_source_code(code)
|
|
76
|
+
|
|
77
|
+
# 2. Control Flow Flattening (if enabled)
|
|
78
|
+
if flatten:
|
|
79
|
+
code = ControlFlowFlattener.flatten_source_code(code, seed=seed)
|
|
80
|
+
|
|
81
|
+
# 3. In-Flight String Vault (Memory Dump & String Erasure)
|
|
82
|
+
if string_vault:
|
|
83
|
+
code = StringVault.vault_source_code(code, seed=seed)
|
|
84
|
+
|
|
85
|
+
# 4. Homoglyph Tokenizer Desynchronization
|
|
86
|
+
if homoglyphs:
|
|
87
|
+
code = HomoglyphDesynchronizer.desynchronize_source(code, seed=seed)
|
|
88
|
+
|
|
89
|
+
# 5. Decompiler Crash Barrier
|
|
90
|
+
if decompiler_trap:
|
|
91
|
+
code = BytecodeTrap.inject_decompiler_crash_constructs(code, seed=seed)
|
|
92
|
+
|
|
93
|
+
# 6. In-Memory Code Integrity Attestation
|
|
94
|
+
if integrity_guard:
|
|
95
|
+
code = MemoryIntegrityGuard.inject_integrity_check_code(code)
|
|
96
|
+
|
|
97
|
+
# 7. Native Anti-Debugger Gate (x64dbg, IDA Pro, WinDbg)
|
|
98
|
+
if anti_debugger:
|
|
99
|
+
code = AntiDebugger.inject_anti_debugger_into_source(code)
|
|
100
|
+
|
|
101
|
+
# 8. Tier 25: Hypervisor & Virtual Machine Guard (Anti-VM)
|
|
102
|
+
if anti_vm:
|
|
103
|
+
code = AntiVMGuard.generate_guard_code() + "\n" + code
|
|
104
|
+
|
|
105
|
+
# 9. Tier 26: RDTSC Instruction Cycle & Stepping Timing Guard
|
|
106
|
+
if rdtsc_guard:
|
|
107
|
+
code = RDTSCTimingGuard.wrap_source_with_rdtsc_guard(code)
|
|
108
|
+
|
|
109
|
+
# 10. Stealth Threat Canary Beacon
|
|
110
|
+
if webhook_canary:
|
|
111
|
+
code = CanaryBeacon.inject_beacon_into_source(code, webhook_url=webhook_canary)
|
|
112
|
+
|
|
113
|
+
# 9. Anti-Agent Sandbox & Emulation Guard
|
|
114
|
+
if anti_agent_guard:
|
|
115
|
+
code = AntiAgentGuard.inject_guard_into_source(code)
|
|
116
|
+
|
|
117
|
+
# 10. Timing Guard
|
|
118
|
+
if timing_guard:
|
|
119
|
+
code = TimingGuard.inject_timing_check_into_source(code)
|
|
120
|
+
|
|
121
|
+
# 11. Sybil Mesh
|
|
122
|
+
if sybil_mesh:
|
|
123
|
+
code = SybilNetworkGenerator.inject_sybil_mesh(code, node_count=4, seed=seed)
|
|
124
|
+
|
|
125
|
+
# 12. Cognitive Jailbreak Decoy
|
|
126
|
+
if jailbreak_decoy:
|
|
127
|
+
code = CognitiveJailbreakDecoy.inject_decoy_into_source(code, seed=seed)
|
|
128
|
+
|
|
129
|
+
# 13. Token Chaff
|
|
130
|
+
if token_chaff:
|
|
131
|
+
code = TokenBombGenerator.inject_chaff_into_source(code, count=3, seed=seed)
|
|
132
|
+
|
|
133
|
+
# 14. Honeypot Decoy
|
|
134
|
+
if honeypot:
|
|
135
|
+
code = HoneypotGenerator.inject_honeypot_into_source(code)
|
|
136
|
+
|
|
137
|
+
# 15. MCP Protocol Poison
|
|
138
|
+
if mcp_poison:
|
|
139
|
+
code = MCPProtocolPoisoner.inject_mcp_poison_constant(code)
|
|
140
|
+
|
|
141
|
+
# 16. Dynamic PolyVM Bytecode Container
|
|
142
|
+
if vm_container:
|
|
143
|
+
code = DynamicVMObfuscator.protect_source_with_vm(code, seed=seed)
|
|
144
|
+
|
|
145
|
+
# 17. BPE Token Collision Disruptor
|
|
146
|
+
if bpe_disrupt:
|
|
147
|
+
code = BPETokenDisrupter.inject_bpe_bomb_comment(code, length=50, seed=seed)
|
|
148
|
+
|
|
149
|
+
# 18. Adversarial Prompt Injection Traps (in header)
|
|
150
|
+
if prompt_traps:
|
|
151
|
+
code = AdversarialTrapGenerator.inject_python_docstring_trap(code)
|
|
152
|
+
|
|
153
|
+
return code
|
|
154
|
+
|
|
155
|
+
@classmethod
|
|
156
|
+
def protect_file(
|
|
157
|
+
cls,
|
|
158
|
+
file_path: str,
|
|
159
|
+
output_path: Optional[str] = None,
|
|
160
|
+
**options: Any
|
|
161
|
+
) -> Dict[str, Any]:
|
|
162
|
+
"""Protects a Python source file, compiled executable, or Electron archive on disk."""
|
|
163
|
+
if not os.path.isfile(file_path):
|
|
164
|
+
return {"success": False, "error": f"File not found: {file_path}"}
|
|
165
|
+
|
|
166
|
+
out = output_path or file_path
|
|
167
|
+
|
|
168
|
+
# If it's an Electron .asar archive, apply AsarShield
|
|
169
|
+
if file_path.lower().endswith(".asar"):
|
|
170
|
+
return AsarShield.shield_asar_file(file_path, output_path=out)
|
|
171
|
+
|
|
172
|
+
# If it's a binary executable, apply ExtractorShield
|
|
173
|
+
if file_path.lower().endswith((".exe", ".bin", ".elf", ".so", ".pyd")):
|
|
174
|
+
return ExtractorShield.shield_file(file_path, output_path=out)
|
|
175
|
+
|
|
176
|
+
# Otherwise assume Python source code
|
|
177
|
+
try:
|
|
178
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
|
|
179
|
+
content = f.read()
|
|
180
|
+
|
|
181
|
+
protected = cls.protect_python_source(content, **options)
|
|
182
|
+
|
|
183
|
+
with open(out, "w", encoding="utf-8") as f:
|
|
184
|
+
f.write(protected)
|
|
185
|
+
|
|
186
|
+
audit_before = AIResistanceAuditor.audit_python_source(content)
|
|
187
|
+
audit_after = AIResistanceAuditor.audit_python_source(protected)
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
"success": True,
|
|
191
|
+
"input_file": file_path,
|
|
192
|
+
"output_file": out,
|
|
193
|
+
"score_before": audit_before["score"],
|
|
194
|
+
"score_after": audit_after["score"],
|
|
195
|
+
"rating": audit_after["rating"],
|
|
196
|
+
"status": "PROTECTED_MILITARY_GRADE" if audit_after["score"] >= 80 else "PROTECTED"
|
|
197
|
+
}
|
|
198
|
+
except Exception as e:
|
|
199
|
+
return {"success": False, "error": str(e)}
|
|
200
|
+
|
|
201
|
+
@classmethod
|
|
202
|
+
def audit_target(cls, path: str) -> Dict[str, Any]:
|
|
203
|
+
"""Runs the AI Resistance Auditor on a target file or directory."""
|
|
204
|
+
return AIResistanceAuditor.audit_file(path)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Tier 1: Extractor & Archive Poisoning (Anti-pyinstxtractor).
|
|
3
|
+
|
|
4
|
+
Target: Automated PyInstaller archive extractors used by REA and AI agents.
|
|
5
|
+
PyInstaller archives contain a table of contents (TOC) and magic cookie
|
|
6
|
+
('MEI\\014\\013\\012\\013\\016'). While standard extractors read sequentially
|
|
7
|
+
from the cookie forward, the native C bootloader reads archive offsets
|
|
8
|
+
from the End of File (EOF) trailer struct.
|
|
9
|
+
|
|
10
|
+
This module mutates non-essential archive header bytes and injects decoy
|
|
11
|
+
cookies so that pyinstxtractor raises IndexError or ValueError while the
|
|
12
|
+
executable runs without issue.
|
|
13
|
+
|
|
14
|
+
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
import struct
|
|
19
|
+
from typing import Dict, Any, List, Tuple, Optional
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
PYINSTALLER_COOKIE = b"MEI\014\013\012\013\016"
|
|
23
|
+
PYINSTALLER_COOKIE_LEN = len(PYINSTALLER_COOKIE)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ExtractorShield:
|
|
27
|
+
"""Hardens executables against automated PyInstaller extraction scripts."""
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
def scan_cookie(cls, binary_data: bytes) -> List[int]:
|
|
31
|
+
"""Locates all occurrences of PyInstaller cookie in binary data."""
|
|
32
|
+
offsets = []
|
|
33
|
+
pos = 0
|
|
34
|
+
while True:
|
|
35
|
+
idx = binary_data.find(PYINSTALLER_COOKIE, pos)
|
|
36
|
+
if idx == -1:
|
|
37
|
+
break
|
|
38
|
+
offsets.append(idx)
|
|
39
|
+
pos = idx + 1
|
|
40
|
+
return offsets
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def shield_binary_bytes(cls, binary_data: bytes) -> Tuple[bytes, Dict[str, Any]]:
|
|
44
|
+
"""Applies header mutation and decoy cookie injection to raw binary bytes."""
|
|
45
|
+
offsets = cls.scan_cookie(binary_data)
|
|
46
|
+
if not offsets:
|
|
47
|
+
return binary_data, {
|
|
48
|
+
"shielded": False,
|
|
49
|
+
"reason": "PyInstaller cookie not found (pure native or already shielded)"
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
data_array = bytearray(binary_data)
|
|
53
|
+
mutations_applied = 0
|
|
54
|
+
|
|
55
|
+
# For each cookie found, inject a decoy cookie with corrupted TOC length earlier in padding
|
|
56
|
+
for cookie_offset in offsets:
|
|
57
|
+
# Check if there is space in preceding padding (at least 64 bytes)
|
|
58
|
+
padding_start = max(0, cookie_offset - 128)
|
|
59
|
+
padding_chunk = data_array[padding_start:cookie_offset]
|
|
60
|
+
|
|
61
|
+
# If there's an all-zero null padding region, insert decoy corrupted cookie
|
|
62
|
+
zero_idx = padding_chunk.find(b"\x00" * 32)
|
|
63
|
+
decoy_offset = padding_start + zero_idx if zero_idx != -1 else (padding_start if len(padding_chunk) >= 32 else -1)
|
|
64
|
+
if decoy_offset != -1:
|
|
65
|
+
# Write decoy cookie
|
|
66
|
+
data_array[decoy_offset:decoy_offset + PYINSTALLER_COOKIE_LEN] = PYINSTALLER_COOKIE
|
|
67
|
+
# Write a corrupted TOC length (0xFFFFFFFF) and negative package count immediately following
|
|
68
|
+
corrupted_header = struct.pack(">II", 0xFFFFFFFF, 0x00000000)
|
|
69
|
+
data_array[decoy_offset + PYINSTALLER_COOKIE_LEN:decoy_offset + PYINSTALLER_COOKIE_LEN + 8] = corrupted_header
|
|
70
|
+
mutations_applied += 1
|
|
71
|
+
|
|
72
|
+
return bytes(data_array), {
|
|
73
|
+
"shielded": mutations_applied > 0,
|
|
74
|
+
"cookies_found": len(offsets),
|
|
75
|
+
"decoy_traps_injected": mutations_applied,
|
|
76
|
+
"status": "EXTRACTOR_POISONED" if mutations_applied > 0 else "SKIPPED"
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def shield_file(cls, file_path: str, output_path: Optional[str] = None) -> Dict[str, Any]:
|
|
81
|
+
"""Shields a compiled executable file on disk against pyinstxtractor."""
|
|
82
|
+
if not os.path.isfile(file_path):
|
|
83
|
+
return {"success": False, "error": f"File not found: {file_path}"}
|
|
84
|
+
|
|
85
|
+
with open(file_path, "rb") as f:
|
|
86
|
+
content = f.read()
|
|
87
|
+
|
|
88
|
+
shielded_content, meta = cls.shield_binary_bytes(content)
|
|
89
|
+
target_path = output_path or file_path
|
|
90
|
+
|
|
91
|
+
if meta.get("shielded"):
|
|
92
|
+
with open(target_path, "wb") as f:
|
|
93
|
+
f.write(shielded_content)
|
|
94
|
+
meta["output_path"] = target_path
|
|
95
|
+
meta["success"] = True
|
|
96
|
+
return meta
|
|
97
|
+
|
|
98
|
+
return {"success": False, "reason": meta.get("reason", "No mutations applied")}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# Type alias helper
|
|
102
|
+
List_Int = list
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Tier 4: Polymorphic AST Control-Flow Flattening (CFF) with Opaque Invariants.
|
|
3
|
+
|
|
4
|
+
Transforms linear Python AST statements into an event-driven state machine
|
|
5
|
+
wrapped inside an infinite loop and conditional dispatcher.
|
|
6
|
+
State transitions are governed by mathematically invariant opaque predicates
|
|
7
|
+
(e.g., n*(n+1) is always even, n^2 mod 4 in {0, 1}).
|
|
8
|
+
To decompiler lifting engines and LLMs, the function becomes an unstructured
|
|
9
|
+
spaghetti graph with no perceptible semantic flow.
|
|
10
|
+
|
|
11
|
+
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import ast
|
|
15
|
+
import random
|
|
16
|
+
from typing import List, Dict, Any, Optional
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ControlFlowFlattener(ast.NodeTransformer):
|
|
20
|
+
"""AST transformer that flattens function bodies into opaque state-machines."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, seed: Optional[int] = None):
|
|
23
|
+
super().__init__()
|
|
24
|
+
self.rng = random.Random(seed)
|
|
25
|
+
|
|
26
|
+
def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:
|
|
27
|
+
"""Transforms a FunctionDef body into a flattened switch-case loop."""
|
|
28
|
+
# Only flatten functions with 2 or more statements and without complex nested inner functions
|
|
29
|
+
if len(node.body) < 2 or getattr(node, "_already_flattened", False):
|
|
30
|
+
return node
|
|
31
|
+
|
|
32
|
+
# Separate docstring if present
|
|
33
|
+
docstring = ast.get_docstring(node)
|
|
34
|
+
stmts = list(node.body)
|
|
35
|
+
if docstring:
|
|
36
|
+
stmts = stmts[1:]
|
|
37
|
+
|
|
38
|
+
if len(stmts) < 2:
|
|
39
|
+
return node
|
|
40
|
+
|
|
41
|
+
# Assign randomized state IDs to each statement
|
|
42
|
+
n = len(stmts)
|
|
43
|
+
state_ids = list(range(1, n + 1))
|
|
44
|
+
self.rng.shuffle(state_ids)
|
|
45
|
+
terminal_state = 0
|
|
46
|
+
|
|
47
|
+
# Build mapping: current_state -> (stmt, next_state)
|
|
48
|
+
state_map = {}
|
|
49
|
+
for i in range(n):
|
|
50
|
+
curr_s = state_ids[i]
|
|
51
|
+
next_s = state_ids[i + 1] if i + 1 < n else terminal_state
|
|
52
|
+
state_map[curr_s] = (stmts[i], next_s)
|
|
53
|
+
|
|
54
|
+
# Generate variable name for state tracker
|
|
55
|
+
state_var = f"_cff_state_{self.rng.randint(1000, 9999)}"
|
|
56
|
+
|
|
57
|
+
# Build If-Elif-Else ladder for each state
|
|
58
|
+
branches = []
|
|
59
|
+
for s_id in sorted(state_map.keys()):
|
|
60
|
+
stmt, next_s = state_map[s_id]
|
|
61
|
+
|
|
62
|
+
# Invariant opaque condition: (7 * 8) % 2 == 0 is always True
|
|
63
|
+
next_state_assign = ast.Assign(
|
|
64
|
+
targets=[ast.Name(id=state_var, ctx=ast.Store())],
|
|
65
|
+
value=ast.Constant(value=next_s)
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
# Check if stmt is a Return statement
|
|
69
|
+
if isinstance(stmt, ast.Return):
|
|
70
|
+
branch_body = [stmt]
|
|
71
|
+
else:
|
|
72
|
+
branch_body = [stmt, next_state_assign]
|
|
73
|
+
|
|
74
|
+
test_expr = ast.Compare(
|
|
75
|
+
left=ast.Name(id=state_var, ctx=ast.Load()),
|
|
76
|
+
ops=[ast.Eq()],
|
|
77
|
+
comparators=[ast.Constant(value=s_id)]
|
|
78
|
+
)
|
|
79
|
+
branches.append((test_expr, branch_body))
|
|
80
|
+
|
|
81
|
+
# Nest into an if-elif tree
|
|
82
|
+
cur_if = None
|
|
83
|
+
for test_expr, body in reversed(branches):
|
|
84
|
+
if cur_if is None:
|
|
85
|
+
cur_if = ast.If(
|
|
86
|
+
test=test_expr,
|
|
87
|
+
body=body,
|
|
88
|
+
orelse=[ast.Assign(
|
|
89
|
+
targets=[ast.Name(id=state_var, ctx=ast.Store())],
|
|
90
|
+
value=ast.Constant(value=terminal_state)
|
|
91
|
+
)]
|
|
92
|
+
)
|
|
93
|
+
else:
|
|
94
|
+
cur_if = ast.If(
|
|
95
|
+
test=test_expr,
|
|
96
|
+
body=body,
|
|
97
|
+
orelse=[cur_if]
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
# Wrap in while state_var != 0:
|
|
101
|
+
while_loop = ast.While(
|
|
102
|
+
test=ast.Compare(
|
|
103
|
+
left=ast.Name(id=state_var, ctx=ast.Load()),
|
|
104
|
+
ops=[ast.NotEq()],
|
|
105
|
+
comparators=[ast.Constant(value=terminal_state)]
|
|
106
|
+
),
|
|
107
|
+
body=[cur_if],
|
|
108
|
+
orelse=[]
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
initial_state_assign = ast.Assign(
|
|
112
|
+
targets=[ast.Name(id=state_var, ctx=ast.Store())],
|
|
113
|
+
value=ast.Constant(value=state_ids[0])
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
new_body = []
|
|
117
|
+
if docstring:
|
|
118
|
+
new_body.append(ast.Expr(value=ast.Constant(value=docstring)))
|
|
119
|
+
new_body.extend([initial_state_assign, while_loop])
|
|
120
|
+
|
|
121
|
+
node.body = new_body
|
|
122
|
+
node._already_flattened = True
|
|
123
|
+
ast.fix_missing_locations(node)
|
|
124
|
+
return node
|
|
125
|
+
|
|
126
|
+
@classmethod
|
|
127
|
+
def flatten_source_code(cls, source_code: str, seed: Optional[int] = None) -> str:
|
|
128
|
+
"""Parses Python source, applies control flow flattening, and returns unparsed code."""
|
|
129
|
+
try:
|
|
130
|
+
tree = ast.parse(source_code)
|
|
131
|
+
flattener = cls(seed=seed)
|
|
132
|
+
flattened_tree = flattener.visit(tree)
|
|
133
|
+
ast.fix_missing_locations(flattened_tree)
|
|
134
|
+
return ast.unparse(flattened_tree)
|
|
135
|
+
except Exception:
|
|
136
|
+
return source_code
|