tzero-mcp 12.2.2 → 12.3.3

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 (44) 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 +2 -2
  6. package/src/app.py +1 -1
  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 +21 -0
  12. package/src/tzero/anti_rea/auditor.py +20 -0
  13. package/src/tzero/anti_rea/canary_beacon.py +33 -61
  14. package/src/tzero/anti_rea/cli.py +30 -4
  15. package/src/tzero/anti_rea/crypto_loader.py +132 -0
  16. package/src/tzero/anti_rea/engine.py +51 -20
  17. package/src/tzero/anti_rea/extractor_shield.py +60 -25
  18. package/src/tzero/anti_rea/tier_catalog.py +388 -0
  19. package/src/tzero/tzero_armor.py +3 -3
  20. package/src/tzero/tzero_benchmark.py +1 -1
  21. package/src/tzero/tzero_budget.py +1 -1
  22. package/src/tzero/tzero_ci.py +2 -2
  23. package/src/tzero/tzero_contracts.py +2 -2
  24. package/src/tzero/tzero_dashboard.py +3 -3
  25. package/src/tzero/tzero_debt.py +85 -7
  26. package/src/tzero/tzero_deps.py +109 -87
  27. package/src/tzero/tzero_explain.py +1 -1
  28. package/src/tzero/tzero_golden.py +2 -2
  29. package/src/tzero/tzero_graph_hud.html +4 -4
  30. package/src/tzero/tzero_growth.py +1 -1
  31. package/src/tzero/tzero_jarvis/swarm.py +23 -2
  32. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1 -1
  33. package/src/tzero/tzero_jarvis/zero_key_router.py +10 -78
  34. package/src/tzero/tzero_lsp.py +1 -1
  35. package/src/tzero/tzero_mcp.py +28 -10
  36. package/src/tzero/tzero_mutation.py +6 -2
  37. package/src/tzero/tzero_promo.py +1 -1
  38. package/src/tzero/tzero_security.py +40 -11
  39. package/src/tzero/tzero_task_benchmark.py +2 -2
  40. package/src/tzero/tzero_traffic.py +1 -1
  41. package/src/tzero/tzero_tui.py +5 -5
  42. package/src/tzero/tzero_v3.py +418 -275
  43. package/src/tzero/tzero_welcome.py +1 -1
  44. package/bin/postinstall.js +0 -30
@@ -40,21 +40,21 @@ class ExtractorShield:
40
40
  return offsets
41
41
 
42
42
  @classmethod
43
- def _find_pe_slack_offset(cls, data_array: bytearray, max_offset: int) -> int:
44
- """Locates an unused all-zero PE section alignment cave before the CArchive overlay."""
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
45
  if len(data_array) < 0x100 or data_array[:2] != b"MZ":
46
- return -1
46
+ return []
47
+ found: List[int] = []
47
48
  try:
48
49
  e_lfanew = struct.unpack_from("<I", data_array, 0x3C)[0]
49
50
  if e_lfanew + 24 > len(data_array) or data_array[e_lfanew:e_lfanew + 4] != b"PE\x00\x00":
50
- return -1
51
+ return []
51
52
  num_sec = struct.unpack_from("<H", data_array, e_lfanew + 6)[0]
52
53
  opt_size = struct.unpack_from("<H", data_array, e_lfanew + 20)[0]
53
54
  sec_off = e_lfanew + 24 + opt_size
54
55
  if sec_off + num_sec * 40 > len(data_array):
55
- return -1
56
- preferred = (".rdata", ".rsrc", ".pdata", ".fptable")
57
- candidates = []
56
+ return []
57
+ preferred = (".rdata", ".rsrc", ".pdata", ".fptable", ".data")
58
58
  for i in range(num_sec):
59
59
  s = sec_off + i * 40
60
60
  name = data_array[s:s + 8].rstrip(b"\x00").decode("ascii", errors="ignore")
@@ -63,18 +63,47 @@ class ExtractorShield:
63
63
  slack_start = rptr + ((vsize + 15) & ~15)
64
64
  slack_end = min(rptr + rsize, max_offset)
65
65
  if slack_end - slack_start >= 32:
66
- candidates.append((slack_start, slack_end))
67
- for slack_start, slack_end in candidates:
68
- zero_idx = data_array[slack_start:slack_end].find(b"\x00" * 32)
69
- if zero_idx != -1:
70
- return slack_start + zero_idx
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
71
  except Exception:
72
- return -1
73
- return -1
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
74
103
 
75
104
  @classmethod
76
105
  def shield_binary_bytes(cls, binary_data: bytes) -> Tuple[bytes, Dict[str, Any]]:
77
- """Applies non-destructive decoy cookie injection strictly into null-byte caves."""
106
+ """Applies multi-cave decoy cookie injection & PE metadata scrubbing without corrupting runtime."""
78
107
  offsets = cls.scan_cookie(binary_data)
79
108
  if not offsets:
80
109
  return binary_data, {
@@ -84,17 +113,19 @@ class ExtractorShield:
84
113
 
85
114
  data_array = bytearray(binary_data)
86
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
87
118
 
88
119
  for cookie_offset in offsets:
89
120
  padding_start = max(0, cookie_offset - 128)
90
121
  padding_chunk = data_array[padding_start:cookie_offset]
91
122
 
92
- # 1. Inject only if a genuine 32-byte null region exists before the cookie (e.g. mock/aligned cave)
123
+ decoy_offsets: List[int] = []
93
124
  zero_idx = padding_chunk.find(b"\x00" * 32)
94
- decoy_offset = padding_start + zero_idx if zero_idx != -1 else -1
125
+ if zero_idx != -1:
126
+ decoy_offsets.append(padding_start + zero_idx)
95
127
 
96
- # 2. For real PyInstaller PE executables, use unmapped .rdata/.rsrc section alignment slack
97
- if decoy_offset == -1 and len(data_array) >= 0x100 and data_array[:2] == b"MZ":
128
+ if not decoy_offsets and is_pe:
98
129
  pkg_start = cookie_offset
99
130
  if cookie_offset + 12 <= len(data_array):
100
131
  try:
@@ -104,18 +135,22 @@ class ExtractorShield:
104
135
  pkg_start = trailer_end - pkg_len
105
136
  except Exception:
106
137
  pass
107
- decoy_offset = cls._find_pe_slack_offset(data_array, min(cookie_offset, pkg_start))
138
+ decoy_offsets.extend(
139
+ cls._find_all_pe_slack_offsets(data_array, min(cookie_offset, pkg_start), max_caves=4)
140
+ )
108
141
 
109
- if decoy_offset != -1 and decoy_offset + PYINSTALLER_COOKIE_LEN + 8 <= cookie_offset:
110
- data_array[decoy_offset:decoy_offset + PYINSTALLER_COOKIE_LEN] = PYINSTALLER_COOKIE
111
- corrupted_header = struct.pack(">II", 0xFFFFFFFF, 0x00000000)
112
- data_array[decoy_offset + PYINSTALLER_COOKIE_LEN:decoy_offset + PYINSTALLER_COOKIE_LEN + 8] = corrupted_header
113
- mutations_applied += 1
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
114
148
 
115
149
  return bytes(data_array), {
116
150
  "shielded": mutations_applied > 0,
117
151
  "cookies_found": len(offsets),
118
152
  "decoy_traps_injected": mutations_applied,
153
+ "pe_metadata_scrubbed": pe_scrubs,
119
154
  "status": "EXTRACTOR_POISONED" if mutations_applied > 0 else "SKIPPED"
120
155
  }
121
156
 
@@ -0,0 +1,388 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Canonical 180-Tier Anti-REA Defense Catalog & Taxonomy (v5.0.0).
3
+
4
+ Defines 12 sovereign security domains x 15 verified enforcement layers = 180 tiers
5
+ (REA-001 through REA-180) spanning binary extractors, PolyVM virtualization,
6
+ authenticated bytecode encryption, decompiler crashers, MBA algebraic mutation,
7
+ native Ring-3 anti-debugging, anti-VM filters, RDTSC hardware timing, memory
8
+ integrity attestation, Electron ASAR shielding, and AI/LLM protocol traps.
9
+
10
+ Developer: Toprak Ahmet Aydogmus (Siber Akademi)
11
+ Part of Siber Akademi T-Zero Security Suite.
12
+ License: MIT
13
+ """
14
+
15
+ from typing import Dict, Any, List, Tuple
16
+
17
+
18
+ ANTI_REA_DOMAINS: List[Dict[str, Any]] = [
19
+ {
20
+ "id": "D01",
21
+ "name": "Archive & PE Binary Hardening",
22
+ "tier_range": (1, 15),
23
+ "marker_tokens": ("MEI", "EXTRACTOR_POISONED", "ExtractorShield"),
24
+ "tiers": [
25
+ ("Primary Cookie Offset Guard", "Locates and protects primary PyInstaller magic cookie offsets"),
26
+ ("Decoy MEI Pre-Overlay Poison", "Injects malformed MEI magic headers into PE slack caves"),
27
+ ("Multi-Cave Decoy Saturation", "Injects up to 4 independent decoy CArchive cookies per PE binary"),
28
+ ("CArchive Length Mismatch Trap", "Writes oversized 0xFFFFFFFF CArchive payload lengths to abort unpackers"),
29
+ ("PYZ Validation Decoy Header", "Prepends zeroed CArchive size hints in decoy headers"),
30
+ ("PE Section Alignment Cave Finder", "Targets .rdata, .rsrc, .pdata, .fptable slack without resizing PE sections"),
31
+ ("Rich Header Zeroization", "Scrubs MSVC Rich/DanS compiler toolchain metadata between DOS stub and PE header"),
32
+ ("COFF TimeDateStamp Scrubbing", "Zeroes PE COFF TimeDateStamp telemetry cleanly"),
33
+ ("PyInstaller Boundary Protection", "Preserves pkg_start offsets so native C bootloader executes unharmed"),
34
+ ("Non-Zero Archive Safety Guard", "Refuses destructive overwrites when no clean null alignment cave exists"),
35
+ ("ELF / Shared Lib Entry Routing", "Routes .elf, .so, .pyd, and .bin targets cleanly to binary extractor shield"),
36
+ ("PE DOS Magic Validation", "Verifies MZ and PE\\x00\\x00 signatures before binary mutation"),
37
+ ("Bounded Section Table Parsing", "Validates section header table bounds against buffer truncation"),
38
+ ("Trailing Junk / PYC Opcode Guard", "Appends invalid 0xFF 0xFE trailing opcodes to crash linear .pyc sweepers"),
39
+ ("Deterministic Atomic Binary Write", "Writes hardened binary atomically preserving original size invariants"),
40
+ ],
41
+ },
42
+ {
43
+ "id": "D02",
44
+ "name": "Control-Flow Flattening & Opaque Predicates",
45
+ "tier_range": (16, 30),
46
+ "marker_tokens": ("_cff_state_", "while "),
47
+ "tiers": [
48
+ ("Linear Statement Shuffling", "Reorders AST statement blocks under randomized integer state labels"),
49
+ ("Randomized State ID Space", "Seeded Fisher-Yates state label allocation per protected function"),
50
+ ("Nested Elif State Dispatcher", "Builds multi-level if/elif dispatcher tree inside bounded while loop"),
51
+ ("Modulo-2 Parity Predicate", "Anchors state flow transitions on invariant integer parity"),
52
+ ("Terminal Exit State Routing", "Assigns deterministic terminal state exit cleanly ending execution loop"),
53
+ ("Return Short-Circuit Dispatch", "Preserves early function return statements inside dispatcher branches"),
54
+ ("Docstring Prologue Isolation", "Preserves function docstrings ahead of flattened dispatcher loop"),
55
+ ("AsyncFunctionDef Safe Handling", "Keeps async coroutine signatures intact without syntax distortion"),
56
+ ("Generator / Yield Safe Routing", "Maintains generator yield suspension semantics inside dispatcher"),
57
+ ("Class Method Binding Preservation", "Preserves self/cls method descriptors across flattened classes"),
58
+ ("Closure & Nested Scope Integrity", "Safely flattens multi-statement routines while keeping nested scopes valid"),
59
+ ("Zero Deadlock State Advance", "Appends fallback terminal state on else edge preventing infinite loops"),
60
+ ("Idempotent Double-Flatten Guard", "Marks flattened functions (_already_flattened) to avoid AST blowup"),
61
+ ("Location Fixup Reconstruction", "Recomputes AST line/column offsets via ast.fix_missing_locations"),
62
+ ("Graceful Syntax Fallback", "Falls back cleanly on single-statement or unparseable edge constructs"),
63
+ ],
64
+ },
65
+ {
66
+ "id": "D03",
67
+ "name": "Dynamic PolyVM Bytecode Virtualizer",
68
+ "tier_range": (31, 45),
69
+ "marker_tokens": ("_polyvm_runtime", "POLYVM SECURE BYTECODE"),
70
+ "tiers": [
71
+ ("Seeded Opcode Permutation", "Generates unique per-build opcode byte table from range 10..249"),
72
+ ("Stack VM Register Emulator", "Executes arithmetic, store, load, and return ops inside custom interpreter loop"),
73
+ ("Encrypted Integer Constant Pool", "Masks integer constants using per-index rolling 16-bit XOR schedule"),
74
+ ("Encrypted UTF-8 String Constant Pool", "Encrypts VM string literals cleanly preserving UTF-8 decoding"),
75
+ ("OP_ADD Virtualized Handler", "Executes stack addition without exposing native Python ADD semantics"),
76
+ ("OP_SUB Virtualized Handler", "Executes stack subtraction through dynamic opcode branching"),
77
+ ("OP_MUL Virtualized Handler", "Executes stack multiplication via dynamic VM dispatch"),
78
+ ("OP_DIV Zero-Safe Virtual Handler", "Executes integer floor division with safe divisor guard"),
79
+ ("OP_MOD Zero-Safe Virtual Handler", "Executes modulo reduction cleanly inside VM loop"),
80
+ ("OP_XOR Bitwise Virtual Handler", "Executes XOR state mixing inside PolyVM instruction pipeline"),
81
+ ("Dynamic Var Load/Store Table", "Binds positional arg_i and kwargs inside isolated VM locals_map"),
82
+ ("Load-Time Self-Attestation", "Executes encrypted PolyVM check bytecode before module activation"),
83
+ ("OP_NOP Polymorphic Padding", "Supports dead NOP bytecode instructions confusing pattern scanners"),
84
+ ("Clean Fallback Pass-Through", "Preserves non-int/non-str constants cleanly via raw table tagging"),
85
+ ("Integrity Exception Gate", "Aborts module boot immediately if VM integrity check diverges"),
86
+ ],
87
+ },
88
+ {
89
+ "id": "D04",
90
+ "name": "HKDF-SHA256 & HMAC Bytecode Envelope",
91
+ "tier_range": (46, 60),
92
+ "marker_tokens": ("_tzero_decrypt_and_exec", "HMAC-SHA256"),
93
+ "tiers": [
94
+ ("Per-Build CSPRNG Salt Generation", "Generates unique 16-byte cryptographic salt for each protected build"),
95
+ ("Multi-Share Split Key Material", "Splits secret seed bytes across independent encoded shares"),
96
+ ("SHA-256 Iterative Key Derivation", "Derives independent cipher and MAC keys via domain-separated SHA-256"),
97
+ ("SHA-256 CTR Keystream Cipher", "Encrypts compressed marshal bytecode using counter-mode SHA-256 keystream"),
98
+ ("HMAC-SHA256 Envelope Authentication", "Authenticates encrypted capsule + salt to reject any byte tampering"),
99
+ ("Constant-Time Digest Verification", "Uses hmac.compare_digest preventing timing side-channel leaks"),
100
+ ("Zlib Level-9 Bytecode Compression", "Compresses compiled Python code object before encryption"),
101
+ ("Marshal Native CodeObj Execution", "Restores authentic Python AST/code object cleanly inside target globals"),
102
+ ("Full UTF-8 & Unicode Fidelity", "Preserves all Turkish/Unicode string constants verbatim at runtime"),
103
+ ("Class, Super & Dataclass Parity", "Executes classes, dataclasses, properties, and inheritance natively"),
104
+ ("Async, Await & Generator Parity", "Preserves coroutines, async iterators, and yield generators losslessly"),
105
+ ("Caller __name__ & sys.argv Parity", "Executes inside real module globals maintaining __main__ & CLI args"),
106
+ ("Base85 Compact Armor Encoding", "Encodes ciphertext cleanly as ASCII85 safe inside UTF-8 Python source"),
107
+ ("Bytearray RAM Buffer Zeroization", "Overwrites decrypted plaintext & keystream buffers with zeros in finally"),
108
+ ("Pre-Decrypt Anti-Trace Lockout", "Aborts capsule decryption immediately if sys.gettrace() is attached"),
109
+ ],
110
+ },
111
+ {
112
+ "id": "D05",
113
+ "name": "Decompiler & AST Parser Crash Barriers",
114
+ "tier_range": (61, 75),
115
+ "marker_tokens": ("_anti_decompiler_guard_gate", "yield from"),
116
+ "tiers": [
117
+ ("Recursive Try-Finally CFG Trap", "Injects nested try/except cycles crashing linear CFG reconstruction"),
118
+ ("Unreachable Yield-From Generator", "Embeds dead lambda yield-from loop defeating uncompyle6 grammars"),
119
+ ("Uncompyle6 Stack Underflow Vector", "Forces control-flow stack depth skew in unreachable branches"),
120
+ ("Pycdc Exception Table Overload", "Generates multi-exception tuple catches (GeneratorExit, SystemExit, Exception)"),
121
+ ("Seeded Gate Identifier Salting", "Randomizes crasher gate function hex suffix per build"),
122
+ ("Dead Magic Sentinel Return", "Includes 0xDEADBEEF decoy return inside dead CFG branch"),
123
+ ("Zero-Runtime-Cost Trap Flag", "Guards unreachable decompiler trap behind runtime constant False"),
124
+ ("Import-Time Gate Verification", "Verifies crasher gate return at boot without measurable overhead"),
125
+ ("PEP-552 .pyc Invalid Opcode Tail", "Appends 0xFF 0xFE 0xFD invalid opcodes beyond STOP bytecode return"),
126
+ ("Ghidra Python Loader Confusion", "Disrupts linear bytecode sweep at EOF boundary cleanly"),
127
+ ("Lambda Closure Indirection", "Wraps dead generator inside anonymous lambda expression"),
128
+ ("Loop-Inside-Try Nesting", "Creates non-reducible nested while-True/try/except structure"),
129
+ ("Static Analyzer Complexity Spike", "Elevates static CFG cyclomatic branching inside dead barrier"),
130
+ ("Bytecode Resistance Self-Audit", "Exposes audit_decompiler_resistance programmatic readiness probe"),
131
+ ("Clean Compile Verification", "Staged compile() check confirms CPython accepts injected barriers"),
132
+ ],
133
+ },
134
+ {
135
+ "id": "D06",
136
+ "name": "Mixed Boolean-Arithmetic (MBA) Mutation",
137
+ "tier_range": (76, 90),
138
+ "marker_tokens": ("_tzero_mba_add", "<<"),
139
+ "tiers": [
140
+ ("Bitwise Addition MBA Identity", "Rewrites integer a + b into (a ^ b) + ((a & b) << 1)"),
141
+ ("Bitwise Subtraction MBA Identity", "Rewrites integer a - b into (a ^ b) - (((~a) & b) << 1)"),
142
+ ("Power-of-Two Multiply Shift", "Rewrites integer multiplication by 2, 4, 8 into bitwise left shifts"),
143
+ ("Type-Safe Runtime MBA Wrapper", "Verifies strict int (non-bool) operand identity before MBA execution"),
144
+ ("Zero Str/Float/List TypeError Risk", "Falls back cleanly to native + / - / * for str, float, list, Path"),
145
+ ("Bool Subclass Exclusion Guard", "Prevents True + True from entering bitwise ~bool inversion pitfalls"),
146
+ ("Static Integer Literal Unfolding", "Rewrites known pure integer constants directly in AST"),
147
+ ("Nested BinOp Expression Support", "Applies MBA recursively across compound arithmetic AST subtrees"),
148
+ ("Angr Symbolic Path Bloat", "Expands linear arithmetic into bitwise carry chains for SMT solvers"),
149
+ ("Z3 Bitvector Solver Friction", "Increases bitvector width reasoning depth against symbolic deobfuscators"),
150
+ ("Preserve Negative Operand Semantics", "Matches Python arbitrary-precision two's-complement arithmetic exactly"),
151
+ ("Preserve Operator Precedence", "Explicitly preserves AST parent/child grouping via BinOp nodes"),
152
+ ("Zero Constant Folding Leak", "Evades naive constant peephole elimination with dynamic helper dispatch"),
153
+ ("AST Location Repair", "Repairs AST line numbers cleanly via ast.fix_missing_locations"),
154
+ ("Fallback Syntax Safety", "Leaves exotic constructs intact instead of corrupting target code"),
155
+ ],
156
+ },
157
+ {
158
+ "id": "D07",
159
+ "name": "Native Ring-3 & POSIX Anti-Debugger",
160
+ "tier_range": (91, 105),
161
+ "marker_tokens": ("_verify_bare_metal_execution_environment", "IsDebuggerPresent"),
162
+ "tiers": [
163
+ ("Win32 IsDebuggerPresent Gate", "Queries kernel32.IsDebuggerPresent directly via ctypes"),
164
+ ("Win32 Remote Debugger Check", "Invokes CheckRemoteDebuggerPresent against current process handle"),
165
+ ("NtSetInformationThread Hide", "Calls ntdll.NtSetInformationThread(0x11) to hide thread from debuggers"),
166
+ ("PEB BeingDebugged / Heap Flag Guard", "Checks Win32 native debugger artifacts without trusting Python env"),
167
+ ("Native Toolhelp32 Snapshot Scan", "Scans Win32 process list in <2ms natively with zero subprocess spawn"),
168
+ ("x64dbg / x32dbg / OllyDbg Block", "Detects x64dbg, x32dbg, scylla, and ollydbg active host processes"),
169
+ ("IDA Pro & Ghidra Process Block", "Detects ida.exe, ida64.exe, idag, idaw, ghidra, cutter, radare2"),
170
+ ("WinDbg & Cheat Engine Block", "Detects windbg, windbgx, processhacker, procmon, cheatengine"),
171
+ ("POSIX /proc TracerPid Inspection", "Reads /proc/self/status TracerPid on Linux for active ptrace/gdb"),
172
+ ("POSIX /proc/*/comm Process Scan", "Scans active POSIX /proc process command names for reverse tools"),
173
+ ("Python sys.gettrace() Trap", "Aborts execution immediately when Python line/call tracer is active"),
174
+ ("Python sys.monitoring Tool Lock", "Detects Python 3.12+ sys.monitoring debugger registrations"),
175
+ ("Preload Injector Env Check", "Flags LD_PRELOAD, DYLD_INSERT_LIBRARIES, and PYTHONINSPECT"),
176
+ ("0xC0000409 Hard Exit Termination", "Terminates cleanly via ExitProcess/os._exit without readable tracebacks"),
177
+ ("Silent Divergence Alt Policy", "Supports stealth divergence flag mode alongside hard termination"),
178
+ ],
179
+ },
180
+ {
181
+ "id": "D08",
182
+ "name": "Anti-VM, Hypervisor & Sandbox Filter",
183
+ "tier_range": (106, 120),
184
+ "marker_tokens": ("_verify_bare_metal_hardware", "VBoxMouse"),
185
+ "tiers": [
186
+ ("VirtualBox Driver Artifact Scan", "Checks VBoxMouse.sys, VBoxGuest.sys, and VBoxSF.sys kernel drivers"),
187
+ ("VMware Driver Artifact Scan", "Checks vmmouse.sys, vmhgfs.sys, and vmusbmouse.sys drivers"),
188
+ ("Hypervisor Toolhelp32 Scan", "Detects vboxservice, vboxtray, vmtoolsd, qemu-ga, xenservice, prl_tools"),
189
+ ("NIC Virtual MAC OUI Registry", "Monitors VMware, VirtualBox, QEMU/KVM, and Xen IEEE MAC prefixes"),
190
+ ("Sandbox Hardware Exit Enforcement", "Triggers 0xC0000409 fast exit or SystemExit when VM sandbox matches"),
191
+ ("Anti-Agent Env Marker Scan", "Detects REA_SESSION, GHIDRA_HEADLESS, FRIDA_VERSION, ANGR_EXPLORE"),
192
+ ("MCP Agent Invocation Probe Check", "Detects MCP_INVOCATION_AGENT, UNICORN_EMU, and IDA_PYTHON flags"),
193
+ ("Symbolic Execution Micro-Cadence", "Measures 500-cycle XOR loop latency (<100ms native vs >100ms angr)"),
194
+ ("Timing Differential Cadence Check", "Measures 1000-cycle emulation variance preventing step-emulation"),
195
+ ("Silent Divergence Sentinel", "Records _SANDBOX_CLEAN sentinel for stealth deceptive divergence"),
196
+ ("Zero False-Positive CI Support", "Avoids false triggers on standard physical desktops or standard Python runs"),
197
+ ("Toolhelp32 ctypes Struct Alignment", "Uses exact pointer-width c_size_t on 64-bit Windows hosts"),
198
+ ("Handle Cleanup Discipline", "Always invokes CloseHandle on Win32 snapshots preventing handle leaks"),
199
+ ("Headless Ghidra Root Guard", "Detects GHIDRA_ROOT instrumentation markers in host env"),
200
+ ("Structured Environment Audit API", "Exposes inspectable scan_debugger_environment & check_hypervisor APIs"),
201
+ ],
202
+ },
203
+ {
204
+ "id": "D09",
205
+ "name": "RDTSC & Hardware Stepping Timing Guards",
206
+ "tier_range": (121, 135),
207
+ "marker_tokens": ("_rdtsc_checkpoint", "perf_counter_ns"),
208
+ "tiers": [
209
+ ("Nanosecond QPC / perf_counter Gate", "Measures monotonic nanosecond deltas between sensitive execution checkpoints"),
210
+ ("Single-Step F7/F8 Detection", "Aborts immediately if step pause exceeds 50,000,000 ns (50ms) threshold"),
211
+ ("Inline AST Checkpoint Injection", "Inserts _t_gate timestamps directly after function docstrings"),
212
+ ("0xC0000409 Hard Breakpoint Kill", "Executes os._exit(0xC0000409) upon single-step latency spike"),
213
+ ("Callable Timing Probe Helper", "Measures arbitrary block timing cleanly via measure_block_timing"),
214
+ ("AsyncFunctionDef Compatible Gate", "Injects valid timing guards without invalidating coroutine objects"),
215
+ ("Low-Overhead Native Execution", "Sub-microsecond overhead during normal bare-metal runtime execution"),
216
+ ("AST Location Repair Post-Wrap", "Applies ast.fix_missing_locations after checkpoint insertion"),
217
+ ("Graceful Syntax Fallback Wrap", "Falls back cleanly on exotic AST trees while preserving runtime"),
218
+ ("Configurable Stepping Budget", "Supports custom max_allowed_ns tolerances for heavy initialization"),
219
+ ("Return Monotonic Timestamp", "Chains checkpoint timestamps cleanly across multi-step blocks"),
220
+ ("Debugger Breakpoint Stall Trap", "Catches interactive breakpoint suspension inside critical code blocks"),
221
+ ("Emulator Sleep-Skip Counter", "Identifies synthetic clock distortion under instruction stepping"),
222
+ ("Cross-Platform Monotonic Backend", "Operates identically across Windows QPC and POSIX clock_gettime"),
223
+ ("Zero Network Dependency", "Executes 100% locally in nanosecond hardware timers"),
224
+ ],
225
+ },
226
+ {
227
+ "id": "D10",
228
+ "name": "Memory Integrity & In-Flight String Vault",
229
+ "tier_range": (136, 150),
230
+ "marker_tokens": ("_attest_memory_bytecode_fingerprints", "_vault_decrypt_string"),
231
+ "tiers": [
232
+ ("Live co_code SHA-256 Digest", "Computes SHA-256 over live Python function co_code instruction bytes"),
233
+ ("Persistent Fingerprint Registry", "Registers baseline bytecode hashes in module _ATTESTATION_FINGERPRINTS"),
234
+ ("Re-Verification Tamper Trap", "Detects subsequent in-memory function patching / Frida hooks cleanly"),
235
+ ("Module Namespace Introspection", "Validates all active user functions dynamically via sys.modules"),
236
+ ("String Literal AST Extraction", "Replaces static plaintext string literals with encrypted byte blobs"),
237
+ ("Per-Literal Seeded Salt XOR", "Assigns distinct PRNG salt per string literal for keyed rolling XOR"),
238
+ ("UTF-8 Multi-Byte Strict Decode", "Preserves multi-byte Unicode / Turkish characters verbatim via strict UTF-8"),
239
+ ("In-Place Buffer RAM Zeroization", "Wipes encrypted input bytearray to 0 byte-by-byte during decode loop"),
240
+ ("Finally-Block Plaintext Wipe", "Wipes decoded bytearray buffer cleanly in finally upon string construction"),
241
+ ("Docstring & Magic Name Guard", "Preserves __dunder__ attributes and docstrings cleanly during AST pass"),
242
+ ("Vault Function Self-Exclusion", "Excludes _vault_* internal runtime helpers from recursive tampering"),
243
+ ("Direct Static Strings Erasure", "Eliminates plaintext API strings/secrets from disk & .rodata scans"),
244
+ ("Compile-Time Attestation Verify", "Tracks attestation count verifying at least one live function hash"),
245
+ ("Registry Verify Callable API", "Exposes MemoryIntegrityGuard.verify_integrity for hot-path callables"),
246
+ ("Safe String Vault Fallback", "Preserves source gracefully if malformed input fails AST parsing"),
247
+ ],
248
+ },
249
+ {
250
+ "id": "D11",
251
+ "name": "Electron .ASAR & JS Archive Shield",
252
+ "tier_range": (151, 165),
253
+ "marker_tokens": ("ASAR_EXTRACTOR_POISONED", "AsarShield"),
254
+ "tiers": [
255
+ ("ASAR Binary Signature Check", "Verifies valid Electron 4-byte little-endian pickle magic header"),
256
+ ("ASAR Header Poison Transform", "Mutates ASAR pickle JSON length field cleanly to break naive extractors"),
257
+ ("Corrupted Canary Trailer Append", "Appends ELECTRON_ASAR_SHIELD_CANARY trailer blocking EOF dumpers"),
258
+ ("ASAR Decoy Traversal Key Guard", "Injects optional non-extractable traversal JSON keys for unpackers"),
259
+ ("JavaScript Debugger Timing Guard", "Generates JS perf timing trap aborting DevTools/Node inspection"),
260
+ ("JS Function.prototype Integrity Trap", "Detects Monkey-Patched inspect/toString overrides in Node/Electron"),
261
+ ("JS Object Prototype Freeze Seal", "Seals critical runtime prototypes against dynamic Electron injection"),
262
+ ("Pre-Unpack Crash Before Extract", "Causes npx asar extract / Python ASAR parsers to abort before output"),
263
+ ("Non-Mutation On Non-ASAR Input", "Refuses corrupting non-ASAR binaries via strict magic validation"),
264
+ ("Atomic Output Path Routing", "Supports protecting ASAR archives cleanly into separate output paths"),
265
+ ("Original Size Telemetry Capture", "Logs original pickle header fields cleanly in protection metadata"),
266
+ ("Zero External Node Dependencies", "Operates purely in Python stdlib with zero npm runtime requirement"),
267
+ ("Renderer Isolation JS Guard", "Verifies strict absence of exposed Node inspector globals in JS wrapper"),
268
+ ("DevTools Open Latency Trap", "Identifies debugger pause spikes inside JS runtime guard loops"),
269
+ ("Clean Metadata Audit Reporting", "Returns structured shielding status & fields via AsarShield API"),
270
+ ],
271
+ },
272
+ {
273
+ "id": "D12",
274
+ "name": "Adversarial AI, LLM & MCP Neutralizers",
275
+ "tier_range": (166, 180),
276
+ "marker_tokens": ("CRITICAL_SYSTEM_OVERRIDE", "MCP_SYSTEM_SIGNAL"),
277
+ "tiers": [
278
+ ("Adversarial Prompt Override Doc", "Injects RFC-AI-GUARD override directives inside module header docstring"),
279
+ ("MCP JSON-RPC Delimiter Poison", "Embeds spoofed MCP_SYSTEM_SIGNAL completion constants confusing agents"),
280
+ ("Cognitive Jailbreak Canary Decoy", "Injects plausible decoy algorithm satisfying jailbroken LLM queries"),
281
+ ("Cryptographic Provenance Honeypot", "Embeds PROVENANCE_SIG_0x watermark functions trapping code clones"),
282
+ ("Sybil Circular Call Mesh", "Injects N-node mutually referencing dead callgraphs stalling subagents"),
283
+ ("Semantic Math Chaff Exhaustion", "Injects dense polynomial dead routines inflating agent token budgets"),
284
+ ("Internal Identifier Homoglyphs", "Replaces private _vars with visually identical Cyrillic homoglyphs"),
285
+ ("Builtin & Decorator Preservation", "Strictly protects builtins, @classmethod, self/cls, and public APIs"),
286
+ ("Zero-Width BPE Collision Bomb", "Injects adversarial zero-width Unicode comments breaking BPE merges"),
287
+ ("Natural Comment Exclusion Audit", "Prevents non-ASCII natural-language comments from inflating audit score"),
288
+ ("Opt-In Disabled-by-Default Canary", "Webhook/DNS canary telemetry disabled unless explicitly configured"),
289
+ ("Minimal Safe Telemetry Metadata", "Only emits threat/OS/host[:16] metadata when webhook opt-in is active"),
290
+ ("Prologue Shebang & Future Order", "Keeps coding, docstring, and from __future__ legally ordered"),
291
+ ("Staging Compile Verification", "Compiles protected output cleanly before atomic os.replace write"),
292
+ ("Honest Static Indicator Attribution", "Reports static_textual_indicator score & unverified runtime layers transparently"),
293
+ ],
294
+ },
295
+ ]
296
+
297
+
298
+ def _build_tiers() -> List[Dict[str, Any]]:
299
+ tiers: List[Dict[str, Any]] = []
300
+ for dom in ANTI_REA_DOMAINS:
301
+ start_num, end_num = dom["tier_range"]
302
+ for offset, (title, summary) in enumerate(dom["tiers"]):
303
+ num = start_num + offset
304
+ if num > end_num:
305
+ raise ValueError(f"Domain {dom['id']} exceeds tier_range {dom['tier_range']}")
306
+ tiers.append(
307
+ {
308
+ "id": f"REA-{num:03d}",
309
+ "number": num,
310
+ "domain_id": dom["id"],
311
+ "domain_name": dom["name"],
312
+ "title": title,
313
+ "summary": summary,
314
+ "marker_tokens": dom["marker_tokens"],
315
+ }
316
+ )
317
+ return tiers
318
+
319
+
320
+ ANTI_REA_TIERS: List[Dict[str, Any]] = _build_tiers()
321
+ TOTAL_TIER_COUNT: int = len(ANTI_REA_TIERS) # Strictly 180 Tiers
322
+
323
+
324
+ def get_tier_catalog() -> Dict[str, Any]:
325
+ """Returns structured metadata for all 12 security domains and 180 Anti-REA tiers."""
326
+ return {
327
+ "version": "5.0.0",
328
+ "total_domains": len(ANTI_REA_DOMAINS),
329
+ "total_tiers": TOTAL_TIER_COUNT,
330
+ "domains": [
331
+ {
332
+ "id": d["id"],
333
+ "name": d["name"],
334
+ "tier_range": f"REA-{d['tier_range'][0]:03d}..REA-{d['tier_range'][1]:03d}",
335
+ "count": len(d["tiers"]),
336
+ }
337
+ for d in ANTI_REA_DOMAINS
338
+ ],
339
+ "tiers": ANTI_REA_TIERS,
340
+ }
341
+
342
+
343
+ def evaluate_static_tier_coverage(
344
+ source_code: str,
345
+ *,
346
+ has_homoglyphs: bool = False,
347
+ ) -> Dict[str, Any]:
348
+ """Evaluates static marker coverage across all 12 domains / 180 Anti-REA tiers."""
349
+ active_domains: Dict[str, bool] = {}
350
+ domain_details: List[Dict[str, Any]] = []
351
+ tiers_active = 0
352
+
353
+ for dom in ANTI_REA_DOMAINS:
354
+ dom_id = dom["id"]
355
+ markers = dom["marker_tokens"]
356
+ matched = any(tok in source_code for tok in markers)
357
+ if dom_id == "D12" and has_homoglyphs:
358
+ matched = True
359
+ if dom_id == "D02":
360
+ matched = ("_cff_state_" in source_code or "state_" in source_code) and "while " in source_code
361
+ if dom_id == "D06":
362
+ matched = (
363
+ "_tzero_mba_add" in source_code
364
+ or ("^" in source_code and "&" in source_code)
365
+ or ("<<" in source_code and "~" in source_code)
366
+ )
367
+ active_domains[dom_id] = matched
368
+ count = len(dom["tiers"]) if matched else 0
369
+ tiers_active += count
370
+ domain_details.append(
371
+ {
372
+ "domain_id": dom_id,
373
+ "name": dom["name"],
374
+ "active": matched,
375
+ "tiers_active": count,
376
+ "tiers_total": len(dom["tiers"]),
377
+ }
378
+ )
379
+
380
+ return {
381
+ "tiers_active": tiers_active,
382
+ "tiers_total": TOTAL_TIER_COUNT,
383
+ "domains_active": sum(1 for v in active_domains.values() if v),
384
+ "domains_total": len(ANTI_REA_DOMAINS),
385
+ "coverage_pct": round((tiers_active / max(1, TOTAL_TIER_COUNT)) * 100.0, 2),
386
+ "domain_map": active_domains,
387
+ "domain_breakdown": domain_details,
388
+ }
@@ -1,14 +1,14 @@
1
1
  # -*- coding: utf-8 -*-
2
- """Siber Akademi T-Zero — Anti-REA Defense & Armor Engine.
2
+ """Siber Akademi T-Zero — 180-Tier Ultra Anti-REA Defense & Armor Engine.
3
3
 
4
4
  Military-grade defense engine protecting codebases and executables
5
5
  against AI-driven automated reverse engineering (e.g. morluto/rea,
6
6
  Ghidra MCP bridge, IDA Pro LLM plugins, pyinstxtractor) and uncensored/jailbroken LLMs.
7
7
  Includes native Ring-3 anti-debugging against x64dbg, IDA Pro, WinDbg, and Cheat Engine,
8
- stealth canary beacon telemetry, in-flight string vault, and Electron asar shielding.
8
+ opt-in tamper alert webhook, in-flight string vault, and Electron asar shielding.
9
9
 
10
10
  Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
11
- Part of Siber Akademi T-Zero Context Architect v12.2.2 Master Edition.
11
+ Part of Siber Akademi T-Zero Context Architect v12.3.3 Master Edition.
12
12
  License: MIT
13
13
  """
14
14
 
@@ -2,7 +2,7 @@
2
2
  """
3
3
  Siber Akademi — T-Zero Autonomous Benchmark & Performance Optimization Engine.
4
4
  Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
- Version: 12.2.2
5
+ Version: 12.3.3
6
6
  License: MIT
7
7
 
8
8
  Performs quantitative multi-model benchmarks comparing raw codebase context
@@ -12,7 +12,7 @@ Capabilities:
12
12
  - 100% Offline, $0 cost, zero cloud dependencies (Python standard library only).
13
13
 
14
14
  Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
15
- Part of T-Zero Context Architect v12.2.2 Master Edition.
15
+ Part of T-Zero Context Architect v12.3.3 Master Edition.
16
16
  """
17
17
 
18
18
  import hashlib
@@ -712,7 +712,7 @@ exit 0
712
712
  lines = []
713
713
  lines.append("\033[36m┌────────────────────────────────────────────────────────────────────────┐\033[0m")
714
714
  lines.append("\033[36m│\033[0m \033[1;37m⚡ T-ZERO LOCAL CI & PRE-PUSH VERIFICATION RUNNER\033[0m \033[36m│\033[0m")
715
- lines.append("\033[36m│\033[0m \033[32mZero Quota Burn\033[0m • \033[33m100% Offline\033[0m • \033[35mZero-Leak Guaranteed\033[0m \033[36m│\033[0m")
715
+ lines.append("\033[36m│\033[0m \033[32mLocal AST Analysis\033[0m • \033[33mToken Estimates\033[0m \033[36m│\033[0m")
716
716
  lines.append("\033[36m└────────────────────────────────────────────────────────────────────────┘\033[0m")
717
717
  lines.append("")
718
718
 
@@ -755,7 +755,7 @@ def main():
755
755
  prog="tzero-ci",
756
756
  description="Siber Akademi T-Zero Local CI Pipeline & Pre-Push Verification Shield"
757
757
  )
758
- parser.add_argument("--version", "-v", action="version", version="%(prog)s 12.2.2")
758
+ parser.add_argument("--version", "-v", action="version", version="%(prog)s 12.3.3")
759
759
  parser.add_argument("--quick", "-q", action="store_true", help="Run fast verification battery (seconds)")
760
760
  parser.add_argument("--all", "-a", action="store_true", help="Run full matrix verification battery")
761
761
  parser.add_argument("--fix", action="store_true", help="Attempt auto-repair for auto-fixable gates (metadata sync)")
@@ -13,7 +13,7 @@ Capabilities:
13
13
  - 100% Offline, $0 cost, zero external dependencies (pure Python standard library).
14
14
 
15
15
  Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
16
- Part of T-Zero Context Architect v12.2.2 Master Edition.
16
+ Part of T-Zero Context Architect v12.3.3 Master Edition.
17
17
  """
18
18
 
19
19
  import ast
@@ -1056,7 +1056,7 @@ class ASTContractComparator:
1056
1056
  "tool": {
1057
1057
  "driver": {
1058
1058
  "name": "T-Zero Contract Guardian",
1059
- "version": "12.2.2",
1059
+ "version": "12.3.3",
1060
1060
  "rules": rules_list
1061
1061
  }
1062
1062
  },
@@ -457,7 +457,7 @@ HTML_PAGE = """<!DOCTYPE html>
457
457
  <div class="brand-logo">T0</div>
458
458
  <div>
459
459
  <div class="brand-title">T-Zero Developer Console</div>
460
- <div class="brand-sub" id="headerBrandSub">Enterprise AST Context Architect &bull; v12.2.2</div>
460
+ <div class="brand-sub" id="headerBrandSub">Enterprise AST Context Architect &bull; v12.3.3</div>
461
461
  </div>
462
462
  </div>
463
463
  <div class="header-actions">
@@ -850,7 +850,7 @@ x = 2
850
850
  </main>
851
851
 
852
852
  <footer>
853
- <span id="footerBrand">T-Zero Context Architect v12.2.2</span> &bull; Developer: Toprak Ahmet Aydoğmuş &bull; Siber Akademi
853
+ <span id="footerBrand">T-Zero Context Architect v12.3.3</span> &bull; Developer: Toprak Ahmet Aydoğmuş &bull; Siber Akademi
854
854
  </footer>
855
855
 
856
856
  <script>
@@ -1481,7 +1481,7 @@ def compute_live_dashboard_stats(workspace_dir: str = ".") -> Dict[str, Any]:
1481
1481
  if cached is not None and (now - _DASHBOARD_STATS_CACHE["ts"]) < 60.0:
1482
1482
  return cached
1483
1483
 
1484
- version = "12.2.2"
1484
+ version = "12.3.3"
1485
1485
  tools_count = 57
1486
1486
  try:
1487
1487
  from tzero import tzero_mcp