tzero-mcp 12.2.1 → 12.3.2

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.
Files changed (55) hide show
  1. package/README.md +6 -30
  2. package/bin/tzero-mcp.js +2 -2
  3. package/bin/tzero.js +11 -6
  4. package/package.json +1 -2
  5. package/src/addmcp.py +10 -5
  6. package/src/app.py +3 -9
  7. package/src/tzero/__init__.py +1 -1
  8. package/src/tzero/anti_rea/__init__.py +16 -2
  9. package/src/tzero/anti_rea/algebraic_mutator.py +65 -44
  10. package/src/tzero/anti_rea/anti_debugger.py +51 -18
  11. package/src/tzero/anti_rea/asar_shield.py +24 -1
  12. package/src/tzero/anti_rea/auditor.py +62 -12
  13. package/src/tzero/anti_rea/canary_beacon.py +56 -76
  14. package/src/tzero/anti_rea/cli.py +37 -5
  15. package/src/tzero/anti_rea/confusables.py +62 -18
  16. package/src/tzero/anti_rea/crypto_loader.py +132 -0
  17. package/src/tzero/anti_rea/engine.py +129 -29
  18. package/src/tzero/anti_rea/extractor_shield.py +91 -13
  19. package/src/tzero/anti_rea/gui.py +1 -4
  20. package/src/tzero/anti_rea/integrity_guard.py +17 -5
  21. package/src/tzero/anti_rea/rdtsc_guard.py +21 -8
  22. package/src/tzero/anti_rea/string_vault.py +10 -7
  23. package/src/tzero/anti_rea/tier_catalog.py +388 -0
  24. package/src/tzero/siber_akademi.ico +0 -0
  25. package/src/tzero/siber_akademi_icon.py +14 -8
  26. package/src/tzero/tzero_armor.py +29 -7
  27. package/src/tzero/tzero_benchmark.py +4 -2
  28. package/src/tzero/tzero_budget.py +14 -5
  29. package/src/tzero/tzero_ci.py +2 -2
  30. package/src/tzero/tzero_contracts.py +7 -5
  31. package/src/tzero/tzero_dashboard.py +28 -9
  32. package/src/tzero/tzero_debt.py +19 -4
  33. package/src/tzero/tzero_deps.py +109 -87
  34. package/src/tzero/tzero_explain.py +1 -1
  35. package/src/tzero/tzero_features.py +43 -29
  36. package/src/tzero/tzero_federation.py +9 -2
  37. package/src/tzero/tzero_fixer/mcp_server.py +10 -0
  38. package/src/tzero/tzero_golden.py +37 -9
  39. package/src/tzero/tzero_growth.py +166 -8
  40. package/src/tzero/tzero_guard.py +147 -46
  41. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1 -1
  42. package/src/tzero/tzero_jarvis/zero_key_router.py +10 -78
  43. package/src/tzero/tzero_lsp.py +1 -1
  44. package/src/tzero/tzero_mcp.py +71 -23
  45. package/src/tzero/tzero_mutation.py +92 -15
  46. package/src/tzero/tzero_promo.py +1 -1
  47. package/src/tzero/tzero_proxy.py +105 -12
  48. package/src/tzero/tzero_scip.py +12 -6
  49. package/src/tzero/tzero_security.py +404 -60
  50. package/src/tzero/tzero_task_benchmark.py +2 -2
  51. package/src/tzero/tzero_traffic.py +35 -10
  52. package/src/tzero/tzero_tui.py +20 -11
  53. package/src/tzero/tzero_v3.py +304 -153
  54. package/src/tzero/tzero_welcome.py +12 -4
  55. package/bin/postinstall.js +0 -30
@@ -0,0 +1,132 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Tier 46-60 (Domain D04): Authenticated HKDF-SHA256 + CTR Bytecode Envelope.
3
+
4
+ Compiles protected Python application bodies into compressed marshal bytecode
5
+ encrypted with a per-build SHA-256 CTR keystream and authenticated via HMAC-SHA256.
6
+
7
+ Key guarantees:
8
+ 1. Preserves 100% native Python runtime semantics for protected applications:
9
+ - classes, inheritance & super(), @dataclass, @property, decorators
10
+ - async def / await, yield / yield from generators, closures
11
+ - full UTF-8 strings, sys.argv, __name__ == "__main__", relative imports
12
+ 2. Leaves ZERO plaintext user functions, constants, strings, or AST structure
13
+ visible to static scanners, decompilers (uncompyle6/pycdc), or LLM agents.
14
+ 3. Enforces active pre-decryption tracer checks (sys.gettrace & sys.monitoring)
15
+ and scrubs decrypted plaintext buffers in memory right after marshal load.
16
+
17
+ Developer: Toprak Ahmet Aydogmus (Siber Akademi)
18
+ Part of Siber Akademi T-Zero Security Suite.
19
+ License: MIT
20
+ """
21
+
22
+ import ast
23
+ import base64
24
+ import hashlib
25
+ import hmac
26
+ import marshal
27
+ import random
28
+ import zlib
29
+ from typing import Tuple
30
+
31
+
32
+ class CryptoBytecodeEnvelope:
33
+ """Seals Python module bodies inside an authenticated encrypted bytecode envelope."""
34
+
35
+ ENVELOPE_MARKER = "SIBER AKADEMI HMAC-SHA256 AUTHENTICATED ENVELOPE"
36
+
37
+ @staticmethod
38
+ def _derive_keys(secret: bytes, salt: bytes) -> Tuple[bytes, bytes]:
39
+ enc_key = hashlib.sha256(b"tzero-enc-v5|" + secret + salt).digest()
40
+ mac_key = hashlib.sha256(b"tzero-mac-v5|" + secret + salt).digest()
41
+ return enc_key, mac_key
42
+
43
+ @staticmethod
44
+ def _ctr_xor(data: bytes, enc_key: bytes, salt: bytes) -> bytes:
45
+ out = bytearray(len(data))
46
+ block_size = 32
47
+ offset = 0
48
+ counter = 0
49
+ while offset < len(data):
50
+ block = hashlib.sha256(enc_key + salt + counter.to_bytes(4, "big")).digest()
51
+ take = min(block_size, len(data) - offset)
52
+ for idx in range(take):
53
+ out[offset + idx] = data[offset + idx] ^ block[idx]
54
+ offset += take
55
+ counter += 1
56
+ return bytes(out)
57
+
58
+ @classmethod
59
+ def seal_source(cls, source_code: str, *, seed: int = 42, future_block: str = "") -> str:
60
+ """Compiles user module code cleanly and seals it inside an authenticated envelope."""
61
+ # Compile clean AST with optional future flags preserved at outer prologue
62
+ unit_src = f"{future_block}{source_code}" if future_block else source_code
63
+ tree = ast.parse(unit_src)
64
+ code_obj = compile(tree, "<tzero_sealed_module>", "exec")
65
+ compressed = zlib.compress(marshal.dumps(code_obj), level=9)
66
+
67
+ rng = random.Random(seed ^ (len(compressed) << 8))
68
+ salt = bytes(rng.getrandbits(8) for _ in range(16))
69
+ share_a = bytes(rng.getrandbits(8) for _ in range(32))
70
+ share_b = bytes(rng.getrandbits(8) for _ in range(32))
71
+ secret = bytes(a ^ b for a, b in zip(share_a, share_b))
72
+
73
+ enc_key, mac_key = cls._derive_keys(secret, salt)
74
+ ciphertext = cls._ctr_xor(compressed, enc_key, salt)
75
+ tag_hex = hmac.new(mac_key, salt + ciphertext, hashlib.sha256).hexdigest()
76
+
77
+ b85_payload = base64.b85encode(ciphertext).decode("ascii")
78
+ b85_salt = base64.b85encode(salt).decode("ascii")
79
+ b85_a = base64.b85encode(share_a).decode("ascii")
80
+ b85_b = base64.b85encode(share_b).decode("ascii")
81
+
82
+ return f'''# --- {cls.ENVELOPE_MARKER} (D04: REA-046..060) ---
83
+ def _tzero_decrypt_and_exec(_p_b85: str, _s_b85: str, _ka_b85: str, _kb_b85: str, _sig_hex: str, _ns: dict) -> None:
84
+ import base64, hashlib, hmac, marshal, os, sys, zlib
85
+ if sys.gettrace() is not None:
86
+ os._exit(0xC0000409)
87
+ _mon = getattr(sys, "monitoring", None)
88
+ if _mon is not None:
89
+ try:
90
+ for _tid in range(6):
91
+ if _mon.get_tool(_tid) is not None and _tid != 5:
92
+ os._exit(0xC0000409)
93
+ except Exception:
94
+ pass
95
+ _salt = base64.b85decode(_s_b85)
96
+ _sa = bytearray(base64.b85decode(_ka_b85))
97
+ _sb = bytearray(base64.b85decode(_kb_b85))
98
+ _sec = bytearray(len(_sa))
99
+ _raw = bytearray()
100
+ _plain = bytearray()
101
+ try:
102
+ for _i in range(len(_sa)):
103
+ _sec[_i] = _sa[_i] ^ _sb[_i]
104
+ _sa[_i] = 0
105
+ _sb[_i] = 0
106
+ _sec_bytes = bytes(_sec)
107
+ _ek = hashlib.sha256(b"tzero-enc-v5|" + _sec_bytes + _salt).digest()
108
+ _mk = hashlib.sha256(b"tzero-mac-v5|" + _sec_bytes + _salt).digest()
109
+ _ct = base64.b85decode(_p_b85)
110
+ _calc = hmac.new(_mk, _salt + _ct, hashlib.sha256).hexdigest()
111
+ if not hmac.compare_digest(_calc, _sig_hex):
112
+ raise RuntimeError("Anti-REA Envelope Integrity Tamper Detected")
113
+ _raw = bytearray(len(_ct))
114
+ _off = 0
115
+ _ctr = 0
116
+ while _off < len(_ct):
117
+ _blk = hashlib.sha256(_ek + _salt + _ctr.to_bytes(4, "big")).digest()
118
+ _take = min(32, len(_ct) - _off)
119
+ for _j in range(_take):
120
+ _raw[_off + _j] = _ct[_off + _j] ^ _blk[_j]
121
+ _off += _take
122
+ _ctr += 1
123
+ _plain = bytearray(zlib.decompress(bytes(_raw)))
124
+ _code_obj = marshal.loads(bytes(_plain))
125
+ exec(_code_obj, _ns, _ns)
126
+ finally:
127
+ for _buf in (_sec, _raw, _plain):
128
+ for _k in range(len(_buf)):
129
+ _buf[_k] = 0
130
+
131
+ _tzero_decrypt_and_exec({repr(b85_payload)}, {repr(b85_salt)}, {repr(b85_a)}, {repr(b85_b)}, {repr(tag_hex)}, globals())
132
+ '''
@@ -9,8 +9,10 @@ Part of Siber Akademi T-Zero Security Suite.
9
9
  License: MIT
10
10
  """
11
11
 
12
+ import ast
12
13
  import os
13
- from typing import Dict, Any, Optional
14
+ import tempfile
15
+ from typing import Dict, Any, List, Optional, Tuple
14
16
 
15
17
  from .traps import AdversarialTrapGenerator
16
18
  from .extractor_shield import ExtractorShield
@@ -36,10 +38,55 @@ from .string_vault import StringVault
36
38
  from .asar_shield import AsarShield
37
39
  from .anti_vm import AntiVMGuard
38
40
  from .rdtsc_guard import RDTSCTimingGuard
41
+ from .crypto_loader import CryptoBytecodeEnvelope
42
+ from .tier_catalog import TOTAL_TIER_COUNT, get_tier_catalog
39
43
 
40
44
 
41
45
  class AntiREAEngine:
42
- """Master engine orchestrating military-grade Anti-REA code and binary protection."""
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
43
90
 
44
91
  @classmethod
45
92
  def protect_python_source(
@@ -64,21 +111,22 @@ class AntiREAEngine:
64
111
  string_vault: bool = True,
65
112
  anti_vm: bool = True,
66
113
  rdtsc_guard: bool = True,
114
+ sealed_envelope: bool = True,
67
115
  webhook_canary: Optional[str] = None,
68
116
  seed: int = 42,
69
117
  ) -> str:
70
- """Applies comprehensive 24-tier Anti-REA protection passes to Python source code."""
71
- code = source_code
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)
72
120
 
73
- # 1. Algebraic Identity Mutation (Mixed Boolean-Arithmetic)
121
+ # 1. Type-Safe Algebraic Identity Mutation (Mixed Boolean-Arithmetic)
74
122
  if algebraic_mutation:
75
123
  code = AlgebraicMutator.mutate_source_code(code)
76
124
 
77
- # 2. Control Flow Flattening (if enabled)
125
+ # 2. Inner Control Flow Flattening
78
126
  if flatten:
79
127
  code = ControlFlowFlattener.flatten_source_code(code, seed=seed)
80
128
 
81
- # 3. In-Flight String Vault (Memory Dump & String Erasure)
129
+ # 3. Inner In-Flight String Vault (Memory Dump & String Erasure)
82
130
  if string_vault:
83
131
  code = StringVault.vault_source_code(code, seed=seed)
84
132
 
@@ -86,71 +134,104 @@ class AntiREAEngine:
86
134
  if homoglyphs:
87
135
  code = HomoglyphDesynchronizer.desynchronize_source(code, seed=seed)
88
136
 
89
- # 5. Decompiler Crash Barrier
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)
90
161
  if decompiler_trap:
91
162
  code = BytecodeTrap.inject_decompiler_crash_constructs(code, seed=seed)
92
163
 
93
- # 6. In-Memory Code Integrity Attestation
164
+ # 9. In-Memory Code Integrity Attestation (D10)
94
165
  if integrity_guard:
95
166
  code = MemoryIntegrityGuard.inject_integrity_check_code(code)
96
167
 
97
- # 7. Native Anti-Debugger Gate (x64dbg, IDA Pro, WinDbg)
168
+ # 10. Native Ring-3 Anti-Debugger Gate (D07)
98
169
  if anti_debugger:
99
170
  code = AntiDebugger.inject_anti_debugger_into_source(code)
100
171
 
101
- # 8. Tier 25: Hypervisor & Virtual Machine Guard (Anti-VM)
172
+ # 11. Hypervisor & Virtual Machine Guard (D08)
102
173
  if anti_vm:
103
174
  code = AntiVMGuard.generate_guard_code() + "\n" + code
104
175
 
105
- # 9. Tier 26: RDTSC Instruction Cycle & Stepping Timing Guard
176
+ # 12. RDTSC Instruction Cycle & Stepping Timing Guard (D09)
106
177
  if rdtsc_guard:
107
178
  code = RDTSCTimingGuard.wrap_source_with_rdtsc_guard(code)
108
179
 
109
- # 10. Stealth Threat Canary Beacon
180
+ # 13. Opt-In Tamper Alert Webhook (Disabled by Default)
110
181
  if webhook_canary:
111
182
  code = CanaryBeacon.inject_beacon_into_source(code, webhook_url=webhook_canary)
112
183
 
113
- # 9. Anti-Agent Sandbox & Emulation Guard
184
+ # 14. Anti-Agent Sandbox & Emulation Guard (D08)
114
185
  if anti_agent_guard:
115
186
  code = AntiAgentGuard.inject_guard_into_source(code)
116
187
 
117
- # 10. Timing Guard
188
+ # 15. Timing Guard (D09)
118
189
  if timing_guard:
119
190
  code = TimingGuard.inject_timing_check_into_source(code)
120
191
 
121
- # 11. Sybil Mesh
192
+ # 16. Sybil Mesh (D12)
122
193
  if sybil_mesh:
123
194
  code = SybilNetworkGenerator.inject_sybil_mesh(code, node_count=4, seed=seed)
124
195
 
125
- # 12. Cognitive Jailbreak Decoy
196
+ # 17. Cognitive Jailbreak Decoy (D12)
126
197
  if jailbreak_decoy:
127
198
  code = CognitiveJailbreakDecoy.inject_decoy_into_source(code, seed=seed)
128
199
 
129
- # 13. Token Chaff
200
+ # 18. Token Chaff (D12)
130
201
  if token_chaff:
131
202
  code = TokenBombGenerator.inject_chaff_into_source(code, count=3, seed=seed)
132
203
 
133
- # 14. Honeypot Decoy
204
+ # 19. Honeypot Decoy (D12)
134
205
  if honeypot:
135
206
  code = HoneypotGenerator.inject_honeypot_into_source(code)
136
207
 
137
- # 15. MCP Protocol Poison
208
+ # 20. MCP Protocol Poison (D12)
138
209
  if mcp_poison:
139
210
  code = MCPProtocolPoisoner.inject_mcp_poison_constant(code)
140
211
 
141
- # 16. Dynamic PolyVM Bytecode Container
212
+ # 21. Dynamic PolyVM Bytecode Container (D03)
142
213
  if vm_container:
143
214
  code = DynamicVMObfuscator.protect_source_with_vm(code, seed=seed)
144
215
 
145
- # 17. BPE Token Collision Disruptor
216
+ # 22. BPE Token Collision Disruptor (D12)
146
217
  if bpe_disrupt:
147
218
  code = BPETokenDisrupter.inject_bpe_bomb_comment(code, length=50, seed=seed)
148
219
 
149
- # 18. Adversarial Prompt Injection Traps (in header)
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 = ""
150
228
  if prompt_traps:
151
- code = AdversarialTrapGenerator.inject_python_docstring_trap(code)
229
+ trap_doc = f'"""\n{AdversarialTrapGenerator.get_trap_payload(0)}\n"""\n'
152
230
 
153
- return code
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}"
154
235
 
155
236
  @classmethod
156
237
  def protect_file(
@@ -173,15 +254,24 @@ class AntiREAEngine:
173
254
  if file_path.lower().endswith((".exe", ".bin", ".elf", ".so", ".pyd")):
174
255
  return ExtractorShield.shield_file(file_path, output_path=out)
175
256
 
176
- # Otherwise assume Python source code
257
+ # Otherwise assume Python source code: transform, compile-verify in temp staging, then write atomically
258
+ staged_path = None
177
259
  try:
178
- with open(file_path, "r", encoding="utf-8", errors="replace") as f:
260
+ with open(file_path, "r", encoding="utf-8", errors="strict") as f:
179
261
  content = f.read()
180
262
 
181
263
  protected = cls.protect_python_source(content, **options)
182
264
 
183
- with open(out, "w", encoding="utf-8") as f:
184
- f.write(protected)
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
185
275
 
186
276
  audit_before = AIResistanceAuditor.audit_python_source(content)
187
277
  audit_after = AIResistanceAuditor.audit_python_source(protected)
@@ -193,9 +283,19 @@ class AntiREAEngine:
193
283
  "score_before": audit_before["score"],
194
284
  "score_after": audit_after["score"],
195
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),
196
291
  "status": "PROTECTED_MILITARY_GRADE" if audit_after["score"] >= 80 else "PROTECTED"
197
292
  }
198
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
199
299
  return {"success": False, "error": str(e)}
200
300
 
201
301
  @classmethod
@@ -39,9 +39,71 @@ class ExtractorShield:
39
39
  pos = idx + 1
40
40
  return offsets
41
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
+
42
104
  @classmethod
43
105
  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."""
106
+ """Applies multi-cave decoy cookie injection & PE metadata scrubbing without corrupting runtime."""
45
107
  offsets = cls.scan_cookie(binary_data)
46
108
  if not offsets:
47
109
  return binary_data, {
@@ -51,28 +113,44 @@ class ExtractorShield:
51
113
 
52
114
  data_array = bytearray(binary_data)
53
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
54
118
 
55
- # For each cookie found, inject a decoy cookie with corrupted TOC length earlier in padding
56
119
  for cookie_offset in offsets:
57
- # Check if there is space in preceding padding (at least 64 bytes)
58
120
  padding_start = max(0, cookie_offset - 128)
59
121
  padding_chunk = data_array[padding_start:cookie_offset]
60
-
61
- # If there's an all-zero null padding region, insert decoy corrupted cookie
122
+
123
+ decoy_offsets: List[int] = []
62
124
  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
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
71
148
 
72
149
  return bytes(data_array), {
73
150
  "shielded": mutations_applied > 0,
74
151
  "cookies_found": len(offsets),
75
152
  "decoy_traps_injected": mutations_applied,
153
+ "pe_metadata_scrubbed": pe_scrubs,
76
154
  "status": "EXTRACTOR_POISONED" if mutations_applied > 0 else "SKIPPED"
77
155
  }
78
156
 
@@ -11,7 +11,6 @@ License: MIT
11
11
  """
12
12
 
13
13
  import os
14
- import sys
15
14
  import threading
16
15
  import tkinter as tk
17
16
  from tkinter import ttk, filedialog, messagebox
@@ -19,8 +18,6 @@ from typing import Optional
19
18
 
20
19
  from .engine import AntiREAEngine
21
20
  from .auditor import AIResistanceAuditor
22
- from .extractor_shield import ExtractorShield
23
- from .anti_debugger import AntiDebugger
24
21
 
25
22
 
26
23
  class AntiREAGUI(tk.Tk):
@@ -225,7 +222,7 @@ class AntiREAGUI(tk.Tk):
225
222
  def _on_simulate_attack(self):
226
223
  target = self.file_entry.get().strip()
227
224
  self._log("==================================================================")
228
- self._log("LAUNCHING SIMULATED REA & ADVERSARIAL ATTACK WAVE...")
225
+ self._log(f"LAUNCHING SIMULATED REA & ADVERSARIAL ATTACK WAVE ({os.path.basename(target) if target else 'default'})...")
229
226
  self._log("==================================================================")
230
227
 
231
228
  def _attack_worker():
@@ -49,17 +49,29 @@ class MemoryIntegrityGuard:
49
49
 
50
50
  @classmethod
51
51
  def inject_integrity_check_code(cls, source_code: str) -> str:
52
- """Injects standalone in-memory integrity attestation boiler into source code."""
52
+ """Injects standalone in-memory integrity attestation into source code."""
53
53
  snippet = '''
54
54
  # --- SIBER AKADEMI IN-MEMORY CODE INTEGRITY ATTESTATION ---
55
+ _ATTESTATION_FINGERPRINTS = {}
56
+
55
57
  def _attest_memory_bytecode_fingerprints():
56
- """Validates that running code objects have not been intercepted by Frida or debuggers."""
58
+ """Validates module function bytecode fingerprints against in-memory tampering."""
57
59
  import sys, hashlib
58
- # Self-attest current module functions
59
60
  mod = sys.modules.get(__name__)
60
61
  if not mod:
61
- return True
62
- return True
62
+ return False
63
+ checked = 0
64
+ for name, obj in list(vars(mod).items()):
65
+ code_obj = getattr(obj, "__code__", None)
66
+ if code_obj is not None and not name.startswith("_vault_"):
67
+ digest = hashlib.sha256(code_obj.co_code).hexdigest()
68
+ expected = _ATTESTATION_FINGERPRINTS.get(name)
69
+ if expected is None:
70
+ _ATTESTATION_FINGERPRINTS[name] = digest
71
+ elif expected != digest:
72
+ return False
73
+ checked += 1
74
+ return checked > 0
63
75
 
64
76
  _ATTESTATION_OK = _attest_memory_bytecode_fingerprints()
65
77
  '''
@@ -13,9 +13,8 @@ Part of Siber Akademi T-Zero Security Suite.
13
13
  License: MIT
14
14
  """
15
15
 
16
+ import ast
16
17
  import time
17
- import os
18
- import sys
19
18
  from typing import Dict, Any, Callable
20
19
 
21
20
 
@@ -56,9 +55,23 @@ def _rdtsc_checkpoint(_t_prev, _threshold_ns={max_allowed_ns}):
56
55
  def wrap_source_with_rdtsc_guard(cls, source_code: str) -> str:
57
56
  """Wraps functions in source code with RDTSC single-stepping checkpoints."""
58
57
  guard_header = cls.generate_stepping_check_code()
59
- trap_insertion = (
60
- "\n _t_gate = time.perf_counter_ns()\n"
61
- " # Critical execution path\n"
62
- " _t_gate = _rdtsc_checkpoint(_t_gate)\n"
63
- )
64
- return f"import time\n{guard_header}\n{source_code}"
58
+ transformed = source_code
59
+ try:
60
+ tree = ast.parse(source_code)
61
+ checkpoint_stmts = ast.parse(
62
+ "_t_gate = time.perf_counter_ns()\n"
63
+ "_t_gate = _rdtsc_checkpoint(_t_gate)\n"
64
+ ).body
65
+ for node in ast.walk(tree):
66
+ if isinstance(node, ast.FunctionDef) and node.body:
67
+ insert_at = 1 if (
68
+ isinstance(node.body[0], ast.Expr)
69
+ and isinstance(getattr(node.body[0], "value", None), ast.Constant)
70
+ and isinstance(node.body[0].value.value, str)
71
+ ) else 0
72
+ node.body[insert_at:insert_at] = [ast.fix_missing_locations(s) for s in checkpoint_stmts]
73
+ ast.fix_missing_locations(tree)
74
+ transformed = ast.unparse(tree)
75
+ except Exception:
76
+ pass
77
+ return f"import time\n{guard_header}\n{transformed}"
@@ -25,15 +25,18 @@ class StringVault:
25
25
  VAULT_RUNTIME_SNIPPET = '''
26
26
  # --- SIBER AKADEMI DYNAMIC IN-FLIGHT STRING VAULT ---
27
27
  def _vault_decrypt_string(enc_blob, salt_key):
28
- """Decrypts string into ephemeral stack frame and scrubs the buffer."""
28
+ """Decrypts UTF-8 string into ephemeral stack frame and scrubs the buffers."""
29
29
  buf = bytearray(enc_blob)
30
+ dec = bytearray(len(buf))
30
31
  k = salt_key & 0xFF
31
- res_chars = []
32
- for i in range(len(buf)):
33
- byte_val = buf[i] ^ ((k + i * 7) & 0xFF)
34
- res_chars.append(chr(byte_val))
35
- buf[i] = 0 # Immediate in-place memory wipe
36
- return "".join(res_chars)
32
+ try:
33
+ for i in range(len(buf)):
34
+ dec[i] = buf[i] ^ ((k + i * 7) & 0xFF)
35
+ buf[i] = 0 # Immediate in-place memory wipe
36
+ return bytes(dec).decode("utf-8", errors="strict")
37
+ finally:
38
+ for i in range(len(dec)):
39
+ dec[i] = 0
37
40
  '''
38
41
 
39
42
  @classmethod