tzero-mcp 12.3.3 → 12.3.6
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/CONTRIBUTING.md +1 -1
- package/README.md +4 -0
- package/package.json +3 -4
- package/src/addmcp.py +2 -2
- package/src/app.py +1 -1
- package/src/main.py +4 -0
- package/src/tzero/__init__.py +1 -1
- package/src/tzero/desktop_updater.py +6 -0
- package/src/tzero/tzero_benchmark.py +1 -1
- package/src/tzero/tzero_budget.py +1 -1
- package/src/tzero/tzero_ci.py +1 -1
- package/src/tzero/tzero_contracts.py +2 -2
- package/src/tzero/tzero_dashboard.py +4 -4
- package/src/tzero/tzero_debt.py +1 -1
- package/src/tzero/tzero_deps.py +1 -0
- package/src/tzero/tzero_explain.py +1 -1
- package/src/tzero/tzero_features.py +31 -74
- package/src/tzero/tzero_golden.py +2 -2
- package/src/tzero/tzero_growth.py +1 -1
- package/src/tzero/tzero_jarvis/orchestrator.py +1 -1
- package/src/tzero/tzero_jarvis/workspace_orchestrator.py +10 -21
- package/src/tzero/tzero_lsp.py +1 -1
- package/src/tzero/tzero_mcp.py +47 -215
- package/src/tzero/tzero_promo.py +1 -1
- package/src/tzero/tzero_security.py +3 -3
- package/src/tzero/tzero_sync.py +73 -148
- package/src/tzero/tzero_task_benchmark.py +2 -2
- package/src/tzero/tzero_traffic.py +1 -1
- package/src/tzero/tzero_tui.py +2 -13
- package/src/tzero/tzero_v3.py +322 -556
- package/src/tzero/tzero_welcome.py +1 -1
- package/src/tzero/anti_rea/__init__.py +0 -84
- package/src/tzero/anti_rea/algebraic_mutator.py +0 -107
- package/src/tzero/anti_rea/anti_agent_guard.py +0 -96
- package/src/tzero/anti_rea/anti_debugger.py +0 -272
- package/src/tzero/anti_rea/anti_vm.py +0 -160
- package/src/tzero/anti_rea/asar_shield.py +0 -122
- package/src/tzero/anti_rea/auditor.py +0 -208
- package/src/tzero/anti_rea/bpe_disrupter.py +0 -48
- package/src/tzero/anti_rea/bytecode_trap.py +0 -85
- package/src/tzero/anti_rea/canary_beacon.py +0 -167
- package/src/tzero/anti_rea/cli.py +0 -134
- package/src/tzero/anti_rea/confusables.py +0 -130
- package/src/tzero/anti_rea/crypto_loader.py +0 -132
- package/src/tzero/anti_rea/engine.py +0 -304
- package/src/tzero/anti_rea/extractor_shield.py +0 -180
- package/src/tzero/anti_rea/flattener.py +0 -136
- package/src/tzero/anti_rea/gui.py +0 -264
- package/src/tzero/anti_rea/honeypot.py +0 -58
- package/src/tzero/anti_rea/integrity_guard.py +0 -78
- package/src/tzero/anti_rea/jailbreak_decoy.py +0 -77
- package/src/tzero/anti_rea/mcp_poison.py +0 -41
- package/src/tzero/anti_rea/native_bridge.py +0 -169
- package/src/tzero/anti_rea/rdtsc_guard.py +0 -77
- package/src/tzero/anti_rea/string_vault.py +0 -97
- package/src/tzero/anti_rea/sybil_network.py +0 -53
- package/src/tzero/anti_rea/tier_catalog.py +0 -388
- package/src/tzero/anti_rea/timing_guard.py +0 -46
- package/src/tzero/anti_rea/token_bomb.py +0 -65
- package/src/tzero/anti_rea/traps.py +0 -76
- package/src/tzero/anti_rea/vm_obfuscator.py +0 -182
- package/src/tzero/tzero_armor.py +0 -187
|
@@ -1,304 +0,0 @@
|
|
|
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 ast
|
|
13
|
-
import os
|
|
14
|
-
import tempfile
|
|
15
|
-
from typing import Dict, Any, List, Optional, Tuple
|
|
16
|
-
|
|
17
|
-
from .traps import AdversarialTrapGenerator
|
|
18
|
-
from .extractor_shield import ExtractorShield
|
|
19
|
-
from .flattener import ControlFlowFlattener
|
|
20
|
-
from .token_bomb import TokenBombGenerator
|
|
21
|
-
from .confusables import HomoglyphDesynchronizer
|
|
22
|
-
from .honeypot import HoneypotGenerator
|
|
23
|
-
from .mcp_poison import MCPProtocolPoisoner
|
|
24
|
-
from .sybil_network import SybilNetworkGenerator
|
|
25
|
-
from .timing_guard import TimingGuard
|
|
26
|
-
from .auditor import AIResistanceAuditor
|
|
27
|
-
from .vm_obfuscator import DynamicVMObfuscator
|
|
28
|
-
from .bytecode_trap import BytecodeTrap
|
|
29
|
-
from .jailbreak_decoy import CognitiveJailbreakDecoy
|
|
30
|
-
from .anti_agent_guard import AntiAgentGuard
|
|
31
|
-
from .algebraic_mutator import AlgebraicMutator
|
|
32
|
-
from .integrity_guard import MemoryIntegrityGuard
|
|
33
|
-
from .bpe_disrupter import BPETokenDisrupter
|
|
34
|
-
from .native_bridge import NativeBridge
|
|
35
|
-
from .anti_debugger import AntiDebugger
|
|
36
|
-
from .canary_beacon import CanaryBeacon
|
|
37
|
-
from .string_vault import StringVault
|
|
38
|
-
from .asar_shield import AsarShield
|
|
39
|
-
from .anti_vm import AntiVMGuard
|
|
40
|
-
from .rdtsc_guard import RDTSCTimingGuard
|
|
41
|
-
from .crypto_loader import CryptoBytecodeEnvelope
|
|
42
|
-
from .tier_catalog import TOTAL_TIER_COUNT, get_tier_catalog
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
class AntiREAEngine:
|
|
46
|
-
"""Master engine orchestrating 180-Tier Anti-REA code and binary protection."""
|
|
47
|
-
|
|
48
|
-
@classmethod
|
|
49
|
-
def _extract_python_prologue(cls, source_code: str) -> Tuple[str, str, str]:
|
|
50
|
-
"""Preserve encoding/shebang header and mandatory `from __future__` imports at module top."""
|
|
51
|
-
lines = source_code.splitlines(keepends=True)
|
|
52
|
-
head_comments: List[str] = []
|
|
53
|
-
idx = 0
|
|
54
|
-
while idx < len(lines):
|
|
55
|
-
s = lines[idx].strip()
|
|
56
|
-
if idx == 0 and s.startswith("#!"):
|
|
57
|
-
head_comments.append(lines[idx])
|
|
58
|
-
idx += 1
|
|
59
|
-
elif s.startswith("#") and ("coding" in s or idx < 2):
|
|
60
|
-
head_comments.append(lines[idx])
|
|
61
|
-
idx += 1
|
|
62
|
-
elif not s:
|
|
63
|
-
head_comments.append(lines[idx])
|
|
64
|
-
idx += 1
|
|
65
|
-
else:
|
|
66
|
-
break
|
|
67
|
-
|
|
68
|
-
rest_code = "".join(lines[idx:])
|
|
69
|
-
future_lines: List[str] = []
|
|
70
|
-
body_code = rest_code
|
|
71
|
-
try:
|
|
72
|
-
tree = ast.parse(rest_code)
|
|
73
|
-
future_indices = set()
|
|
74
|
-
for node in tree.body:
|
|
75
|
-
if isinstance(node, ast.ImportFrom) and node.module == "__future__":
|
|
76
|
-
for ln in range(node.lineno, (node.end_lineno or node.lineno) + 1):
|
|
77
|
-
future_indices.add(ln)
|
|
78
|
-
if future_indices:
|
|
79
|
-
r_lines = rest_code.splitlines(keepends=True)
|
|
80
|
-
kept = []
|
|
81
|
-
for ln_no, ln_txt in enumerate(r_lines, 1):
|
|
82
|
-
if ln_no in future_indices:
|
|
83
|
-
future_lines.append(ln_txt if ln_txt.endswith("\n") else ln_txt + "\n")
|
|
84
|
-
else:
|
|
85
|
-
kept.append(ln_txt)
|
|
86
|
-
body_code = "".join(kept)
|
|
87
|
-
except Exception:
|
|
88
|
-
pass
|
|
89
|
-
return "".join(head_comments), "".join(future_lines), body_code
|
|
90
|
-
|
|
91
|
-
@classmethod
|
|
92
|
-
def protect_python_source(
|
|
93
|
-
cls,
|
|
94
|
-
source_code: str,
|
|
95
|
-
flatten: bool = True,
|
|
96
|
-
token_chaff: bool = True,
|
|
97
|
-
prompt_traps: bool = True,
|
|
98
|
-
homoglyphs: bool = True,
|
|
99
|
-
honeypot: bool = True,
|
|
100
|
-
mcp_poison: bool = True,
|
|
101
|
-
sybil_mesh: bool = True,
|
|
102
|
-
timing_guard: bool = True,
|
|
103
|
-
decompiler_trap: bool = True,
|
|
104
|
-
jailbreak_decoy: bool = True,
|
|
105
|
-
anti_agent_guard: bool = True,
|
|
106
|
-
vm_container: bool = True,
|
|
107
|
-
algebraic_mutation: bool = True,
|
|
108
|
-
integrity_guard: bool = True,
|
|
109
|
-
bpe_disrupt: bool = True,
|
|
110
|
-
anti_debugger: bool = True,
|
|
111
|
-
string_vault: bool = True,
|
|
112
|
-
anti_vm: bool = True,
|
|
113
|
-
rdtsc_guard: bool = True,
|
|
114
|
-
sealed_envelope: bool = True,
|
|
115
|
-
webhook_canary: Optional[str] = None,
|
|
116
|
-
seed: int = 42,
|
|
117
|
-
) -> str:
|
|
118
|
-
"""Applies comprehensive 180-Tier Anti-REA protection while preserving full Python compatibility."""
|
|
119
|
-
head_comments, future_block, code = cls._extract_python_prologue(source_code)
|
|
120
|
-
|
|
121
|
-
# 1. Type-Safe Algebraic Identity Mutation (Mixed Boolean-Arithmetic)
|
|
122
|
-
if algebraic_mutation:
|
|
123
|
-
code = AlgebraicMutator.mutate_source_code(code)
|
|
124
|
-
|
|
125
|
-
# 2. Inner Control Flow Flattening
|
|
126
|
-
if flatten:
|
|
127
|
-
code = ControlFlowFlattener.flatten_source_code(code, seed=seed)
|
|
128
|
-
|
|
129
|
-
# 3. Inner In-Flight String Vault (Memory Dump & String Erasure)
|
|
130
|
-
if string_vault:
|
|
131
|
-
code = StringVault.vault_source_code(code, seed=seed)
|
|
132
|
-
|
|
133
|
-
# 4. Homoglyph Tokenizer Desynchronization
|
|
134
|
-
if homoglyphs:
|
|
135
|
-
code = HomoglyphDesynchronizer.desynchronize_source(code, seed=seed)
|
|
136
|
-
|
|
137
|
-
# 5. Seal hardened application body inside authenticated HKDF-SHA256 + HMAC bytecode envelope
|
|
138
|
-
if sealed_envelope:
|
|
139
|
-
code = CryptoBytecodeEnvelope.seal_source(code, seed=seed, future_block=future_block)
|
|
140
|
-
if homoglyphs:
|
|
141
|
-
code = "_ѕеаl_verified = True\n" + code
|
|
142
|
-
|
|
143
|
-
# 6. Outer Type-Safe MBA Runtime Marker (guarantees static & runtime D06 coverage)
|
|
144
|
-
if algebraic_mutation and "_tzero_mba_add" not in code:
|
|
145
|
-
from .algebraic_mutator import _MBA_RUNTIME_HEADER
|
|
146
|
-
code = f"{_MBA_RUNTIME_HEADER}\n{code}"
|
|
147
|
-
|
|
148
|
-
# 7. Outer Control-Flow State Dispatcher Verification (D02)
|
|
149
|
-
if flatten and "_cff_state_" not in code:
|
|
150
|
-
code = (
|
|
151
|
-
"_cff_state_boot = 1\n"
|
|
152
|
-
"while _cff_state_boot != 0:\n"
|
|
153
|
-
" if _cff_state_boot == 1:\n"
|
|
154
|
-
" _cff_state_boot = 2\n"
|
|
155
|
-
" elif _cff_state_boot == 2:\n"
|
|
156
|
-
" _cff_state_boot = 0\n"
|
|
157
|
-
f"{code}"
|
|
158
|
-
)
|
|
159
|
-
|
|
160
|
-
# 8. Decompiler Crash Barrier (D05)
|
|
161
|
-
if decompiler_trap:
|
|
162
|
-
code = BytecodeTrap.inject_decompiler_crash_constructs(code, seed=seed)
|
|
163
|
-
|
|
164
|
-
# 9. In-Memory Code Integrity Attestation (D10)
|
|
165
|
-
if integrity_guard:
|
|
166
|
-
code = MemoryIntegrityGuard.inject_integrity_check_code(code)
|
|
167
|
-
|
|
168
|
-
# 10. Native Ring-3 Anti-Debugger Gate (D07)
|
|
169
|
-
if anti_debugger:
|
|
170
|
-
code = AntiDebugger.inject_anti_debugger_into_source(code)
|
|
171
|
-
|
|
172
|
-
# 11. Hypervisor & Virtual Machine Guard (D08)
|
|
173
|
-
if anti_vm:
|
|
174
|
-
code = AntiVMGuard.generate_guard_code() + "\n" + code
|
|
175
|
-
|
|
176
|
-
# 12. RDTSC Instruction Cycle & Stepping Timing Guard (D09)
|
|
177
|
-
if rdtsc_guard:
|
|
178
|
-
code = RDTSCTimingGuard.wrap_source_with_rdtsc_guard(code)
|
|
179
|
-
|
|
180
|
-
# 13. Opt-In Tamper Alert Webhook (Disabled by Default)
|
|
181
|
-
if webhook_canary:
|
|
182
|
-
code = CanaryBeacon.inject_beacon_into_source(code, webhook_url=webhook_canary)
|
|
183
|
-
|
|
184
|
-
# 14. Anti-Agent Sandbox & Emulation Guard (D08)
|
|
185
|
-
if anti_agent_guard:
|
|
186
|
-
code = AntiAgentGuard.inject_guard_into_source(code)
|
|
187
|
-
|
|
188
|
-
# 15. Timing Guard (D09)
|
|
189
|
-
if timing_guard:
|
|
190
|
-
code = TimingGuard.inject_timing_check_into_source(code)
|
|
191
|
-
|
|
192
|
-
# 16. Sybil Mesh (D12)
|
|
193
|
-
if sybil_mesh:
|
|
194
|
-
code = SybilNetworkGenerator.inject_sybil_mesh(code, node_count=4, seed=seed)
|
|
195
|
-
|
|
196
|
-
# 17. Cognitive Jailbreak Decoy (D12)
|
|
197
|
-
if jailbreak_decoy:
|
|
198
|
-
code = CognitiveJailbreakDecoy.inject_decoy_into_source(code, seed=seed)
|
|
199
|
-
|
|
200
|
-
# 18. Token Chaff (D12)
|
|
201
|
-
if token_chaff:
|
|
202
|
-
code = TokenBombGenerator.inject_chaff_into_source(code, count=3, seed=seed)
|
|
203
|
-
|
|
204
|
-
# 19. Honeypot Decoy (D12)
|
|
205
|
-
if honeypot:
|
|
206
|
-
code = HoneypotGenerator.inject_honeypot_into_source(code)
|
|
207
|
-
|
|
208
|
-
# 20. MCP Protocol Poison (D12)
|
|
209
|
-
if mcp_poison:
|
|
210
|
-
code = MCPProtocolPoisoner.inject_mcp_poison_constant(code)
|
|
211
|
-
|
|
212
|
-
# 21. Dynamic PolyVM Bytecode Container (D03)
|
|
213
|
-
if vm_container:
|
|
214
|
-
code = DynamicVMObfuscator.protect_source_with_vm(code, seed=seed)
|
|
215
|
-
|
|
216
|
-
# 22. BPE Token Collision Disruptor (D12)
|
|
217
|
-
if bpe_disrupt:
|
|
218
|
-
code = BPETokenDisrupter.inject_bpe_bomb_comment(code, length=50, seed=seed)
|
|
219
|
-
|
|
220
|
-
# Strip redundant coding header inserted mid-file by VM header before placing valid top prologue
|
|
221
|
-
if future_block:
|
|
222
|
-
code_lines = code.splitlines(keepends=True)
|
|
223
|
-
if code_lines and "coding" in code_lines[0]:
|
|
224
|
-
code = "".join(code_lines[1:])
|
|
225
|
-
|
|
226
|
-
# Module docstring MUST come before `from __future__ import ...`, which MUST come before code
|
|
227
|
-
trap_doc = ""
|
|
228
|
-
if prompt_traps:
|
|
229
|
-
trap_doc = f'"""\n{AdversarialTrapGenerator.get_trap_payload(0)}\n"""\n'
|
|
230
|
-
|
|
231
|
-
header = head_comments
|
|
232
|
-
if not header or "coding" not in header:
|
|
233
|
-
header = "# -*- coding: utf-8 -*-\n" + header
|
|
234
|
-
return f"{header}{trap_doc}{future_block}{code}"
|
|
235
|
-
|
|
236
|
-
@classmethod
|
|
237
|
-
def protect_file(
|
|
238
|
-
cls,
|
|
239
|
-
file_path: str,
|
|
240
|
-
output_path: Optional[str] = None,
|
|
241
|
-
**options: Any
|
|
242
|
-
) -> Dict[str, Any]:
|
|
243
|
-
"""Protects a Python source file, compiled executable, or Electron archive on disk."""
|
|
244
|
-
if not os.path.isfile(file_path):
|
|
245
|
-
return {"success": False, "error": f"File not found: {file_path}"}
|
|
246
|
-
|
|
247
|
-
out = output_path or file_path
|
|
248
|
-
|
|
249
|
-
# If it's an Electron .asar archive, apply AsarShield
|
|
250
|
-
if file_path.lower().endswith(".asar"):
|
|
251
|
-
return AsarShield.shield_asar_file(file_path, output_path=out)
|
|
252
|
-
|
|
253
|
-
# If it's a binary executable, apply ExtractorShield
|
|
254
|
-
if file_path.lower().endswith((".exe", ".bin", ".elf", ".so", ".pyd")):
|
|
255
|
-
return ExtractorShield.shield_file(file_path, output_path=out)
|
|
256
|
-
|
|
257
|
-
# Otherwise assume Python source code: transform, compile-verify in temp staging, then write atomically
|
|
258
|
-
staged_path = None
|
|
259
|
-
try:
|
|
260
|
-
with open(file_path, "r", encoding="utf-8", errors="strict") as f:
|
|
261
|
-
content = f.read()
|
|
262
|
-
|
|
263
|
-
protected = cls.protect_python_source(content, **options)
|
|
264
|
-
|
|
265
|
-
# Verify transformed Python compiles cleanly BEFORE replacing target file
|
|
266
|
-
compile(protected, out, "exec")
|
|
267
|
-
|
|
268
|
-
out_dir = os.path.dirname(os.path.abspath(out)) or "."
|
|
269
|
-
os.makedirs(out_dir, exist_ok=True)
|
|
270
|
-
with tempfile.NamedTemporaryFile("w", dir=out_dir, delete=False, encoding="utf-8", prefix=".tzero_armor_") as tf:
|
|
271
|
-
tf.write(protected)
|
|
272
|
-
staged_path = tf.name
|
|
273
|
-
os.replace(staged_path, out)
|
|
274
|
-
staged_path = None
|
|
275
|
-
|
|
276
|
-
audit_before = AIResistanceAuditor.audit_python_source(content)
|
|
277
|
-
audit_after = AIResistanceAuditor.audit_python_source(protected)
|
|
278
|
-
|
|
279
|
-
return {
|
|
280
|
-
"success": True,
|
|
281
|
-
"input_file": file_path,
|
|
282
|
-
"output_file": out,
|
|
283
|
-
"score_before": audit_before["score"],
|
|
284
|
-
"score_after": audit_after["score"],
|
|
285
|
-
"rating": audit_after["rating"],
|
|
286
|
-
"tier_rating": audit_after.get("tier_rating", audit_after["rating"]),
|
|
287
|
-
"tiers_active": audit_after.get("tiers_active", 0),
|
|
288
|
-
"tiers_total": audit_after.get("tiers_total", TOTAL_TIER_COUNT),
|
|
289
|
-
"domains_active": audit_after.get("domains_active", 0),
|
|
290
|
-
"domains_total": audit_after.get("domains_total", 12),
|
|
291
|
-
"status": "PROTECTED_MILITARY_GRADE" if audit_after["score"] >= 80 else "PROTECTED"
|
|
292
|
-
}
|
|
293
|
-
except Exception as e:
|
|
294
|
-
if staged_path and os.path.exists(staged_path):
|
|
295
|
-
try:
|
|
296
|
-
os.remove(staged_path)
|
|
297
|
-
except OSError:
|
|
298
|
-
pass
|
|
299
|
-
return {"success": False, "error": str(e)}
|
|
300
|
-
|
|
301
|
-
@classmethod
|
|
302
|
-
def audit_target(cls, path: str) -> Dict[str, Any]:
|
|
303
|
-
"""Runs the AI Resistance Auditor on a target file or directory."""
|
|
304
|
-
return AIResistanceAuditor.audit_file(path)
|
|
@@ -1,180 +0,0 @@
|
|
|
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 _find_all_pe_slack_offsets(cls, data_array: bytearray, max_offset: int, max_caves: int = 4) -> List[int]:
|
|
44
|
-
"""Locates unused all-zero PE section alignment caves before the CArchive overlay."""
|
|
45
|
-
if len(data_array) < 0x100 or data_array[:2] != b"MZ":
|
|
46
|
-
return []
|
|
47
|
-
found: List[int] = []
|
|
48
|
-
try:
|
|
49
|
-
e_lfanew = struct.unpack_from("<I", data_array, 0x3C)[0]
|
|
50
|
-
if e_lfanew + 24 > len(data_array) or data_array[e_lfanew:e_lfanew + 4] != b"PE\x00\x00":
|
|
51
|
-
return []
|
|
52
|
-
num_sec = struct.unpack_from("<H", data_array, e_lfanew + 6)[0]
|
|
53
|
-
opt_size = struct.unpack_from("<H", data_array, e_lfanew + 20)[0]
|
|
54
|
-
sec_off = e_lfanew + 24 + opt_size
|
|
55
|
-
if sec_off + num_sec * 40 > len(data_array):
|
|
56
|
-
return []
|
|
57
|
-
preferred = (".rdata", ".rsrc", ".pdata", ".fptable", ".data")
|
|
58
|
-
for i in range(num_sec):
|
|
59
|
-
s = sec_off + i * 40
|
|
60
|
-
name = data_array[s:s + 8].rstrip(b"\x00").decode("ascii", errors="ignore")
|
|
61
|
-
vsize, _vaddr, rsize, rptr = struct.unpack_from("<IIII", data_array, s + 8)
|
|
62
|
-
if name in preferred and rsize > vsize + 32:
|
|
63
|
-
slack_start = rptr + ((vsize + 15) & ~15)
|
|
64
|
-
slack_end = min(rptr + rsize, max_offset)
|
|
65
|
-
if slack_end - slack_start >= 32:
|
|
66
|
-
zero_idx = data_array[slack_start:slack_end].find(b"\x00" * 32)
|
|
67
|
-
if zero_idx != -1:
|
|
68
|
-
found.append(slack_start + zero_idx)
|
|
69
|
-
if len(found) >= max_caves:
|
|
70
|
-
break
|
|
71
|
-
except Exception:
|
|
72
|
-
return found
|
|
73
|
-
return found
|
|
74
|
-
|
|
75
|
-
@classmethod
|
|
76
|
-
def _scrub_pe_toolchain_metadata(cls, data_array: bytearray) -> int:
|
|
77
|
-
"""Zeroes MSVC Rich/DanS header & COFF TimeDateStamp cleanly without altering sections."""
|
|
78
|
-
scrubbed = 0
|
|
79
|
-
if len(data_array) < 0x100 or data_array[:2] != b"MZ":
|
|
80
|
-
return 0
|
|
81
|
-
try:
|
|
82
|
-
e_lfanew = struct.unpack_from("<I", data_array, 0x3C)[0]
|
|
83
|
-
if e_lfanew + 24 > len(data_array) or data_array[e_lfanew:e_lfanew + 4] != b"PE\x00\x00":
|
|
84
|
-
return 0
|
|
85
|
-
# Zero MSVC Rich header between 0x80 and e_lfanew if present
|
|
86
|
-
if e_lfanew > 0x80 and b"Rich" in data_array[0x80:e_lfanew]:
|
|
87
|
-
for pos in range(0x80, e_lfanew):
|
|
88
|
-
data_array[pos] = 0
|
|
89
|
-
scrubbed += 1
|
|
90
|
-
# Zero COFF TimeDateStamp (offset +8 from PE\0\0)
|
|
91
|
-
ts_off = e_lfanew + 8
|
|
92
|
-
if any(data_array[ts_off:ts_off + 4]):
|
|
93
|
-
data_array[ts_off:ts_off + 4] = b"\x00\x00\x00\x00"
|
|
94
|
-
scrubbed += 1
|
|
95
|
-
except Exception:
|
|
96
|
-
pass
|
|
97
|
-
return scrubbed
|
|
98
|
-
|
|
99
|
-
@classmethod
|
|
100
|
-
def _find_pe_slack_offset(cls, data_array: bytearray, max_offset: int) -> int:
|
|
101
|
-
caves = cls._find_all_pe_slack_offsets(data_array, max_offset, max_caves=1)
|
|
102
|
-
return caves[0] if caves else -1
|
|
103
|
-
|
|
104
|
-
@classmethod
|
|
105
|
-
def shield_binary_bytes(cls, binary_data: bytes) -> Tuple[bytes, Dict[str, Any]]:
|
|
106
|
-
"""Applies multi-cave decoy cookie injection & PE metadata scrubbing without corrupting runtime."""
|
|
107
|
-
offsets = cls.scan_cookie(binary_data)
|
|
108
|
-
if not offsets:
|
|
109
|
-
return binary_data, {
|
|
110
|
-
"shielded": False,
|
|
111
|
-
"reason": "PyInstaller cookie not found (pure native or already shielded)"
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
data_array = bytearray(binary_data)
|
|
115
|
-
mutations_applied = 0
|
|
116
|
-
is_pe = len(data_array) >= 0x100 and data_array[:2] == b"MZ"
|
|
117
|
-
pe_scrubs = cls._scrub_pe_toolchain_metadata(data_array) if is_pe else 0
|
|
118
|
-
|
|
119
|
-
for cookie_offset in offsets:
|
|
120
|
-
padding_start = max(0, cookie_offset - 128)
|
|
121
|
-
padding_chunk = data_array[padding_start:cookie_offset]
|
|
122
|
-
|
|
123
|
-
decoy_offsets: List[int] = []
|
|
124
|
-
zero_idx = padding_chunk.find(b"\x00" * 32)
|
|
125
|
-
if zero_idx != -1:
|
|
126
|
-
decoy_offsets.append(padding_start + zero_idx)
|
|
127
|
-
|
|
128
|
-
if not decoy_offsets and is_pe:
|
|
129
|
-
pkg_start = cookie_offset
|
|
130
|
-
if cookie_offset + 12 <= len(data_array):
|
|
131
|
-
try:
|
|
132
|
-
pkg_len = struct.unpack_from(">I", data_array, cookie_offset + 8)[0]
|
|
133
|
-
trailer_end = min(len(data_array), cookie_offset + 88)
|
|
134
|
-
if 0 < pkg_len <= trailer_end:
|
|
135
|
-
pkg_start = trailer_end - pkg_len
|
|
136
|
-
except Exception:
|
|
137
|
-
pass
|
|
138
|
-
decoy_offsets.extend(
|
|
139
|
-
cls._find_all_pe_slack_offsets(data_array, min(cookie_offset, pkg_start), max_caves=4)
|
|
140
|
-
)
|
|
141
|
-
|
|
142
|
-
for decoy_offset in decoy_offsets:
|
|
143
|
-
if decoy_offset != -1 and decoy_offset + PYINSTALLER_COOKIE_LEN + 8 <= cookie_offset:
|
|
144
|
-
data_array[decoy_offset:decoy_offset + PYINSTALLER_COOKIE_LEN] = PYINSTALLER_COOKIE
|
|
145
|
-
corrupted_header = struct.pack(">II", 0xFFFFFFFF, 0x00000000)
|
|
146
|
-
data_array[decoy_offset + PYINSTALLER_COOKIE_LEN:decoy_offset + PYINSTALLER_COOKIE_LEN + 8] = corrupted_header
|
|
147
|
-
mutations_applied += 1
|
|
148
|
-
|
|
149
|
-
return bytes(data_array), {
|
|
150
|
-
"shielded": mutations_applied > 0,
|
|
151
|
-
"cookies_found": len(offsets),
|
|
152
|
-
"decoy_traps_injected": mutations_applied,
|
|
153
|
-
"pe_metadata_scrubbed": pe_scrubs,
|
|
154
|
-
"status": "EXTRACTOR_POISONED" if mutations_applied > 0 else "SKIPPED"
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
@classmethod
|
|
158
|
-
def shield_file(cls, file_path: str, output_path: Optional[str] = None) -> Dict[str, Any]:
|
|
159
|
-
"""Shields a compiled executable file on disk against pyinstxtractor."""
|
|
160
|
-
if not os.path.isfile(file_path):
|
|
161
|
-
return {"success": False, "error": f"File not found: {file_path}"}
|
|
162
|
-
|
|
163
|
-
with open(file_path, "rb") as f:
|
|
164
|
-
content = f.read()
|
|
165
|
-
|
|
166
|
-
shielded_content, meta = cls.shield_binary_bytes(content)
|
|
167
|
-
target_path = output_path or file_path
|
|
168
|
-
|
|
169
|
-
if meta.get("shielded"):
|
|
170
|
-
with open(target_path, "wb") as f:
|
|
171
|
-
f.write(shielded_content)
|
|
172
|
-
meta["output_path"] = target_path
|
|
173
|
-
meta["success"] = True
|
|
174
|
-
return meta
|
|
175
|
-
|
|
176
|
-
return {"success": False, "reason": meta.get("reason", "No mutations applied")}
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
# Type alias helper
|
|
180
|
-
List_Int = list
|
|
@@ -1,136 +0,0 @@
|
|
|
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
|