tzero-mcp 12.3.3 → 12.3.5

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 (62) hide show
  1. package/CONTRIBUTING.md +1 -1
  2. package/README.md +4 -0
  3. package/package.json +3 -4
  4. package/src/addmcp.py +2 -2
  5. package/src/app.py +1 -1
  6. package/src/main.py +4 -0
  7. package/src/tzero/__init__.py +1 -1
  8. package/src/tzero/desktop_updater.py +6 -0
  9. package/src/tzero/tzero_benchmark.py +1 -1
  10. package/src/tzero/tzero_budget.py +1 -1
  11. package/src/tzero/tzero_ci.py +1 -1
  12. package/src/tzero/tzero_contracts.py +2 -2
  13. package/src/tzero/tzero_dashboard.py +3 -3
  14. package/src/tzero/tzero_debt.py +1 -1
  15. package/src/tzero/tzero_deps.py +1 -0
  16. package/src/tzero/tzero_explain.py +1 -1
  17. package/src/tzero/tzero_features.py +31 -74
  18. package/src/tzero/tzero_golden.py +2 -2
  19. package/src/tzero/tzero_growth.py +1 -1
  20. package/src/tzero/tzero_jarvis/orchestrator.py +1 -1
  21. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +10 -21
  22. package/src/tzero/tzero_lsp.py +1 -1
  23. package/src/tzero/tzero_mcp.py +19 -120
  24. package/src/tzero/tzero_promo.py +1 -1
  25. package/src/tzero/tzero_security.py +3 -3
  26. package/src/tzero/tzero_sync.py +73 -148
  27. package/src/tzero/tzero_task_benchmark.py +2 -2
  28. package/src/tzero/tzero_traffic.py +1 -1
  29. package/src/tzero/tzero_tui.py +2 -13
  30. package/src/tzero/tzero_v3.py +56 -187
  31. package/src/tzero/tzero_welcome.py +1 -1
  32. package/src/tzero/anti_rea/__init__.py +0 -84
  33. package/src/tzero/anti_rea/algebraic_mutator.py +0 -107
  34. package/src/tzero/anti_rea/anti_agent_guard.py +0 -96
  35. package/src/tzero/anti_rea/anti_debugger.py +0 -272
  36. package/src/tzero/anti_rea/anti_vm.py +0 -160
  37. package/src/tzero/anti_rea/asar_shield.py +0 -122
  38. package/src/tzero/anti_rea/auditor.py +0 -208
  39. package/src/tzero/anti_rea/bpe_disrupter.py +0 -48
  40. package/src/tzero/anti_rea/bytecode_trap.py +0 -85
  41. package/src/tzero/anti_rea/canary_beacon.py +0 -167
  42. package/src/tzero/anti_rea/cli.py +0 -134
  43. package/src/tzero/anti_rea/confusables.py +0 -130
  44. package/src/tzero/anti_rea/crypto_loader.py +0 -132
  45. package/src/tzero/anti_rea/engine.py +0 -304
  46. package/src/tzero/anti_rea/extractor_shield.py +0 -180
  47. package/src/tzero/anti_rea/flattener.py +0 -136
  48. package/src/tzero/anti_rea/gui.py +0 -264
  49. package/src/tzero/anti_rea/honeypot.py +0 -58
  50. package/src/tzero/anti_rea/integrity_guard.py +0 -78
  51. package/src/tzero/anti_rea/jailbreak_decoy.py +0 -77
  52. package/src/tzero/anti_rea/mcp_poison.py +0 -41
  53. package/src/tzero/anti_rea/native_bridge.py +0 -169
  54. package/src/tzero/anti_rea/rdtsc_guard.py +0 -77
  55. package/src/tzero/anti_rea/string_vault.py +0 -97
  56. package/src/tzero/anti_rea/sybil_network.py +0 -53
  57. package/src/tzero/anti_rea/tier_catalog.py +0 -388
  58. package/src/tzero/anti_rea/timing_guard.py +0 -46
  59. package/src/tzero/anti_rea/token_bomb.py +0 -65
  60. package/src/tzero/anti_rea/traps.py +0 -76
  61. package/src/tzero/anti_rea/vm_obfuscator.py +0 -182
  62. package/src/tzero/tzero_armor.py +0 -187
@@ -1,208 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """Tier 12: AI Reverse-Engineering Resistance Auditor & Scorer (TDQS-REA).
3
-
4
- Performs an empirical static audit on source code or compiled binaries to
5
- calculate an objective 0-100 AI Resistance Score against toolchains like REA,
6
- x64dbg, IDA Pro, and uncensored/jailbroken LLMs:
7
- - Prompt Trap Density (0-10)
8
- - Control-Flow Entropy & Flattening (0-15)
9
- - Context Exhaustion & Token Chaff (0-10)
10
- - Homoglyphs & BPE Token Shattering (0-10)
11
- - MCP Delimiter & Cryptographic Honeypot (0-10)
12
- - Dynamic PolyVM Bytecode Architecture (0-15)
13
- - Decompiler Crash Barrier & Anti-Agent Guard (0-10)
14
- - Algebraic Identity (MBA) Mutation (0-10)
15
- - Native Anti-Debugger Gate (x64dbg/IDA) & Integrity (0-10)
16
-
17
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
18
- Part of Siber Akademi T-Zero Security Suite.
19
- License: MIT
20
- """
21
-
22
- import ast
23
- import os
24
- from typing import Dict, Any, List
25
-
26
- from .tier_catalog import evaluate_static_tier_coverage, TOTAL_TIER_COUNT
27
-
28
-
29
- class AIResistanceAuditor:
30
- """Audits target files for resistance against AI reverse-engineering agents."""
31
-
32
- @classmethod
33
- def audit_python_source(cls, source_code: str) -> Dict[str, Any]:
34
- """Audits Python source code across Anti-REA static dimensions cleanly."""
35
- findings: List[str] = []
36
- score = 0
37
-
38
- parsed_tree = None
39
- syntax_valid = True
40
- try:
41
- parsed_tree = ast.parse(source_code)
42
- except SyntaxError as exc:
43
- syntax_valid = False
44
- findings.append(f"Syntax error prevents clean Python compilation (line {exc.lineno}): {exc.msg}")
45
-
46
- # 1. Prompt Trap Check (0-10)
47
- has_prompt_trap = "CRITICAL_SYSTEM_OVERRIDE" in source_code or "RFC-AI-GUARD" in source_code
48
- if has_prompt_trap:
49
- score += 10
50
- else:
51
- findings.append("No adversarial prompt-injection traps detected in module comments.")
52
-
53
- # 2. Control Flow Flattening (0-15)
54
- has_cff = ("state_" in source_code or "while " in source_code) and (
55
- "elif " in source_code or "switch" in source_code or "if " in source_code
56
- )
57
- if has_cff:
58
- score += 15
59
- else:
60
- findings.append("Functions have linear control flow (vulnerable to decompiler synthesis).")
61
-
62
- # 3. Token Chaff & Context Exhaustion (0-10)
63
- has_chaff = "_verify_matrix_polynomial" in source_code or "_compute_quantum_resilient" in source_code
64
- if has_chaff:
65
- score += 10
66
- else:
67
- findings.append("No semantic token chaff detected to drain agent context window.")
68
-
69
- # 4. Homoglyphs & Confusables in AST identifiers ONLY (do NOT score non-ASCII natural-language comments!)
70
- has_homoglyphs = False
71
- if parsed_tree is not None:
72
- for node in ast.walk(parsed_tree):
73
- ident = ""
74
- if isinstance(node, ast.Name):
75
- ident = node.id
76
- elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
77
- ident = node.name
78
- elif isinstance(node, ast.arg):
79
- ident = node.arg
80
- if ident and any(ord(ch) > 127 for ch in ident):
81
- has_homoglyphs = True
82
- break
83
- if has_homoglyphs:
84
- score += 10
85
- else:
86
- findings.append("Identifiers use standard ASCII (vulnerable to semantic embedding matching).")
87
-
88
- # 5. MCP Protocol / Honeypot Defense (0-10)
89
- has_mcp_or_honeypot = "PROVENANCE_SIG_0x" in source_code or "MCP_SYSTEM_SIGNAL" in source_code
90
- if has_mcp_or_honeypot:
91
- score += 10
92
- else:
93
- findings.append("No cryptographic honeypot or MCP delimiter defenses found.")
94
-
95
- # 6. Dynamic PolyVM Bytecode Architecture (0-15)
96
- has_vm = "_polyvm_runtime" in source_code or "POLYVM SECURE BYTECODE" in source_code
97
- if has_vm:
98
- score += 15
99
- else:
100
- findings.append("No dynamic VM bytecode container detected.")
101
-
102
- # 7. Decompiler Crash Barrier & Anti-Agent Guard (0-10)
103
- has_decompiler_trap = "_anti_decompiler_guard_gate" in source_code or "_verify_execution_integrity" in source_code
104
- if has_decompiler_trap:
105
- score += 10
106
- else:
107
- findings.append("No decompiler recursion traps or anti-agent sandboxes active.")
108
-
109
- # 8. Algebraic Identity (MBA) Mutation (0-10)
110
- has_mba = ("^" in source_code and "&" in source_code) or ("<<" in source_code and "~" in source_code)
111
- if has_mba:
112
- score += 10
113
- else:
114
- findings.append("No Mixed Boolean-Arithmetic (MBA) expressions detected.")
115
-
116
- # 9. Native Anti-Debugger Gate (x64dbg/IDA) & Memory Integrity (0-10)
117
- has_debugger_or_integrity = (
118
- "_verify_bare_metal_execution_environment" in source_code
119
- or "_attest_memory_bytecode_fingerprints" in source_code
120
- or "IsDebuggerPresent" in source_code
121
- )
122
- if has_debugger_or_integrity:
123
- score += 10
124
- else:
125
- findings.append("No native anti-debugger gate (x64dbg/IDA) or memory attestation active.")
126
-
127
- # Special indicators
128
- has_jailbreak_decoy = "CANARY_SIG_0x8F91A2B3" in source_code or "_proprietary_zero_leak_kernel" in source_code
129
- has_anti_agent = "_verify_execution_integrity" in source_code
130
- has_anti_debugger = "_verify_bare_metal_execution_environment" in source_code or "IsDebuggerPresent" in source_code
131
- has_anti_vm = "_verify_bare_metal_hardware" in source_code or "VBoxMouse.sys" in source_code
132
- has_rdtsc = "_rdtsc_checkpoint" in source_code or "perf_counter_ns" in source_code
133
- has_crypto_envelope = "_tzero_decrypt_and_exec" in source_code
134
-
135
- tier_coverage = evaluate_static_tier_coverage(source_code, has_homoglyphs=has_homoglyphs)
136
- tiers_active = tier_coverage["tiers_active"]
137
-
138
- if not syntax_valid:
139
- score = min(score, 20)
140
- rating = "SYNTAX_INVALID"
141
- tier_rating = "SYNTAX_INVALID"
142
- status = "FAIL_SYNTAX_ERROR"
143
- else:
144
- rating = (
145
- "MILITARY_GRADE_IMPREGNABLE" if score >= 90 else
146
- "MILITARY_GRADE" if score >= 80 else
147
- "STRONG" if score >= 60 else
148
- "MODERATE" if score >= 40 else
149
- "VULNERABLE"
150
- )
151
- tier_rating = (
152
- "SOVEREIGN_180_ULTRA_ARMOR" if tiers_active >= 135 else
153
- "MILITARY_GRADE_IMPREGNABLE" if score >= 90 else
154
- rating
155
- )
156
- status = "PASS" if score >= 60 else "RECOMMEND_HARDENING"
157
-
158
- return {
159
- "score": score,
160
- "max_score": 100,
161
- "score_kind": "static_textual_indicator",
162
- "syntax_valid": syntax_valid,
163
- "rating": rating,
164
- "tier_rating": tier_rating,
165
- "tiers_active": tiers_active,
166
- "tiers_total": TOTAL_TIER_COUNT,
167
- "domains_active": tier_coverage["domains_active"],
168
- "domains_total": tier_coverage["domains_total"],
169
- "tier_coverage_pct": tier_coverage["coverage_pct"],
170
- "domain_breakdown": tier_coverage["domain_breakdown"],
171
- "defenses_active": {
172
- "adversarial_prompt_traps": has_prompt_trap,
173
- "control_flow_flattening": has_cff,
174
- "token_chaff_exhaustion": has_chaff,
175
- "homoglyph_desynchronization": has_homoglyphs,
176
- "mcp_honeypot_armor": has_mcp_or_honeypot,
177
- "dynamic_polyvm_container": has_vm,
178
- "hmac_crypto_envelope": has_crypto_envelope,
179
- "decompiler_crash_barrier": has_decompiler_trap,
180
- "cognitive_jailbreak_decoy": has_jailbreak_decoy,
181
- "anti_agent_sandbox_guard": has_anti_agent,
182
- "algebraic_mba_mutation": has_mba,
183
- "native_anti_debugger_gate": has_anti_debugger,
184
- "anti_vm_hypervisor_guard": has_anti_vm,
185
- "rdtsc_hardware_timing_guard": has_rdtsc,
186
- "memory_integrity_guard": has_debugger_or_integrity,
187
- },
188
- "unverified_layers": ["debugger_evasion", "vm_evasion", "asar_shield"],
189
- "jailbreak_ai_immune": syntax_valid and score >= 85 and has_jailbreak_decoy and has_vm,
190
- "anti_debugger_active": has_anti_debugger,
191
- "findings": findings,
192
- "status": status,
193
- }
194
-
195
- @classmethod
196
- def audit_file(cls, file_path: str) -> Dict[str, Any]:
197
- """Audits a file on disk (Python or binary)."""
198
- if not os.path.isfile(file_path):
199
- return {"error": f"File not found: {file_path}", "score": 0}
200
-
201
- try:
202
- with open(file_path, "r", encoding="utf-8", errors="replace") as f:
203
- content = f.read()
204
- audit = cls.audit_python_source(content)
205
- audit["file"] = os.path.basename(file_path)
206
- return audit
207
- except Exception as e:
208
- return {"error": str(e), "score": 0}
@@ -1,48 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """Tier 19: Adversarial BPE Token Collision & Subword Disrupter.
3
-
4
- Exploits Byte-Pair Encoding (BPE) merge-table vulnerabilities in modern LLM
5
- tokenizers (tiktoken cl100k/o200k, LLaMA sentencepiece).
6
-
7
- By weaving zero-width joiners, variation selectors, and combining graphemes
8
- into docstrings and metadata, it triggers single-byte fallback mode. A single
9
- 10-character line shatters into 20+ disjoint byte tokens, exhausting token
10
- budgets and inducing self-attention dispersion.
11
-
12
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
13
- Part of Siber Akademi T-Zero Security Suite.
14
- License: MIT
15
- """
16
-
17
- import random
18
-
19
-
20
- class BPETokenDisrupter:
21
- """Disrupts BPE tokenizer representations to induce attention degradation."""
22
-
23
- VARIATION_SELECTORS = [
24
- "\uFE00", "\uFE01", "\uFE02", "\uFE03",
25
- "\u2060", # Word joiner
26
- "\u200B", # Zero-width space
27
- "\u200D", # Zero-width joiner
28
- ]
29
-
30
- @classmethod
31
- def disrupt_string_bpe(cls, text: str, density: float = 0.2, seed: int = 42) -> str:
32
- """Injects non-rendering Unicode variation selectors into text."""
33
- rng = random.Random(seed)
34
- chars = []
35
- for c in text:
36
- chars.append(c)
37
- if c.isalnum() and rng.random() < density:
38
- chars.append(rng.choice(cls.VARIATION_SELECTORS))
39
- return "".join(chars)
40
-
41
- @classmethod
42
- def inject_bpe_bomb_comment(cls, source_code: str, length: int = 100, seed: int = 42) -> str:
43
- """Generates an adversarial comment containing high-density BPE shattering tokens."""
44
- rng = random.Random(seed)
45
- base = "# [RFC-8227-AI-RESISTANCE-FRAMEWORK-ATTESTATION: "
46
- payload = "".join(rng.choice(cls.VARIATION_SELECTORS) for _ in range(length))
47
- comment = f"{base}{payload}]\n"
48
- return f"{comment}{source_code}"
@@ -1,85 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """Tier 14: Anti-Decompiler Bytecode Trap & Crasher Engine.
3
-
4
- Injects decompiler-crashing constructs and malformed dead-code sequences
5
- that cause automated reverse-engineering decompilers (such as pycdc / decompyle++,
6
- uncompyle6, and Ghidra Python bytecode loaders) to terminate abnormally with
7
- unhandled opcode exceptions or recursion overflow, before any decompiled source
8
- can be presented to an LLM agent.
9
-
10
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
11
- Part of Siber Akademi T-Zero Security Suite.
12
- License: MIT
13
- """
14
-
15
- import ast
16
- import random
17
- from typing import Dict, Any, List
18
-
19
-
20
- class BytecodeTrap:
21
- """Injects control-flow and opcode traps specifically targeted at AI decompilers."""
22
-
23
- # Syntactic decompiler crashers:
24
- # 1. Recursive nested exception blocks with synthetic break targets
25
- # 2. Unreachable yield-from generator cycles
26
- # 3. Dynamic lambda closures with circular type hints
27
- DECOMPILER_CRASHER_SNIPPET = '''
28
- # --- SIBER AKADEMI ANTI-DECOMPILER RESISTANCE BARRIER ---
29
- def _anti_decompiler_guard_gate_0x9F():
30
- """Uncompyle6 and pycdc recursion limiter trap.
31
- Forces AST decompiler into non-linear CFG cycle causing fatal recursion.
32
- """
33
- _trap_flag = False
34
- if _trap_flag:
35
- try:
36
- for _ in (lambda: (yield from ()))():
37
- while True:
38
- try:
39
- pass
40
- except Exception:
41
- pass
42
- except (GeneratorExit, SystemExit, Exception):
43
- pass
44
- else:
45
- return 0xDEADBEEF
46
- return True
47
- '''
48
-
49
- @classmethod
50
- def inject_decompiler_crash_constructs(cls, source_code: str, seed: int = 42) -> str:
51
- """Injects syntactic CFG cycles that crash decompilers without runtime penalty."""
52
- rng = random.Random(seed)
53
- salt = rng.randint(0x1000, 0xFFFF)
54
- crasher = cls.DECOMPILER_CRASHER_SNIPPET.replace("0x9F", f"0x{salt:X}")
55
-
56
- # Also inject an inline invariant check that executes at module import
57
- gate_call = f"\nif not _anti_decompiler_guard_gate_0x{salt:X}():\n raise SystemExit(1)\n"
58
-
59
- return f"{crasher}\n{gate_call}\n{source_code}"
60
-
61
- @classmethod
62
- def shield_pyc_bytecode(cls, pyc_bytes: bytes) -> bytes:
63
- """Applies decompiler crasher padding to compiled Python bytecode."""
64
- if len(pyc_bytes) < 16:
65
- return pyc_bytes
66
-
67
- # Python PEP 552 16-byte header check
68
- # Injects unreachable trailer block with dead-byte pattern 0xFF 0xFF (invalid opcode)
69
- # Python interpreter terminates before reading trailing junk, but linear sweep
70
- # disassemblers and Ghidra decompiler parse to EOF and crash with Unhandled Opcode 0xFF
71
- crasher_trailer = b"\x00\x00\x00\x00" + (b"\xFF\xFE\xFD\xFF" * 8)
72
- return pyc_bytes + crasher_trailer
73
-
74
- @classmethod
75
- def audit_decompiler_resistance(cls, source_code: str) -> Dict[str, Any]:
76
- """Audits source code for the presence of decompiler crash barriers."""
77
- has_gate = "_anti_decompiler_guard_gate" in source_code
78
- has_cfg_trap = "yield from" in source_code and ("except" in source_code or "finally" in source_code)
79
-
80
- return {
81
- "has_decompiler_guard_gate": has_gate,
82
- "has_cfg_trap": has_cfg_trap,
83
- "decompiler_crash_capable": has_gate and has_cfg_trap,
84
- "rating": "IMMUNE_TO_STATIC_DECOMPILERS" if (has_gate and has_cfg_trap) else "VULNERABLE"
85
- }
@@ -1,167 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """Tier 22: Opt-In Tamper Alert Webhook & Security Telemetry.
3
-
4
- Dispatches opt-in security notifications to developer-configured HTTPS webhook
5
- endpoints or an explicit canary domain when an integrity or debugger guard triggers.
6
- Disabled by default unless explicitly configured by the application author.
7
-
8
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
9
- Part of Siber Akademi T-Zero Security Suite.
10
- License: MIT
11
- """
12
-
13
- import json
14
- import os
15
- import socket
16
- import sys
17
- import threading
18
- import time
19
- import urllib.request
20
- from typing import Any, Dict, Optional
21
-
22
-
23
- class CanaryBeacon:
24
- """Dispatches explicit opt-in tamper alert notifications to developer endpoints."""
25
-
26
- @classmethod
27
- def encrypt_endpoint(cls, endpoint_str: str, key: int = 0x7E) -> bytes:
28
- """Obfuscates a developer-configured webhook URL against casual plaintext string scans."""
29
- return bytes([b ^ ((key + i * 13) & 0xFF) for i, b in enumerate(endpoint_str.encode("utf-8"))])
30
-
31
- @classmethod
32
- def decrypt_endpoint(cls, enc_bytes: bytes, key: int = 0x7E) -> str:
33
- """Decodes an obfuscated webhook endpoint when dispatching an opt-in alert."""
34
- dec = bytes([b ^ ((key + i * 13) & 0xFF) for i, b in enumerate(enc_bytes)])
35
- return dec.decode("utf-8", errors="replace")
36
-
37
- @classmethod
38
- def _collect_host_context(cls) -> Dict[str, Any]:
39
- """Collects minimal execution metadata for developer tamper audit alerts."""
40
- try:
41
- hostname = socket.gethostname()
42
- except Exception:
43
- hostname = "unknown_host"
44
-
45
- return {
46
- "timestamp": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()),
47
- "platform": sys.platform,
48
- "os_name": os.name,
49
- "python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
50
- "pid": os.getpid(),
51
- "hostname": hostname[:16],
52
- }
53
-
54
- @classmethod
55
- def _dispatch_http(cls, url: str, payload: dict) -> bool:
56
- """Dispatches a JSON tamper alert payload to an explicitly configured webhook URL."""
57
- try:
58
- data = json.dumps(payload).encode("utf-8")
59
- req = urllib.request.Request(
60
- url,
61
- data=data,
62
- headers={
63
- "Content-Type": "application/json",
64
- "User-Agent": "SiberAkademi-TZero-SecurityAudit/1.0",
65
- },
66
- )
67
- with urllib.request.urlopen(req, timeout=3.0) as resp:
68
- return resp.status in (200, 204)
69
- except Exception:
70
- return False
71
-
72
- @classmethod
73
- def _dispatch_dns_ping(cls, threat_code: str, canary_domain: str) -> None:
74
- """Resolves an explicitly configured canary hostname for developer security alerting."""
75
- try:
76
- subdomain = f"{threat_code.lower()[:8]}-{int(time.time())}.{canary_domain}"
77
- socket.gethostbyname(subdomain)
78
- except Exception:
79
- pass
80
-
81
- @classmethod
82
- def dispatch_alert_async(
83
- cls,
84
- threat_type: str,
85
- detected_tool: str = "x64dbg",
86
- webhook_url: Optional[str] = None,
87
- canary_domain: Optional[str] = None,
88
- ) -> threading.Thread:
89
- """Dispatches an opt-in tamper alert asynchronously on a background daemon thread."""
90
- payload = {
91
- "alert": "SECURITY_VIOLATION_DETECTED",
92
- "threat_type": threat_type,
93
- "detected_tool": detected_tool,
94
- "action_taken": "EXECUTION_TERMINATED_OR_DIVERTED",
95
- "context": cls._collect_host_context(),
96
- }
97
-
98
- def _worker():
99
- if webhook_url:
100
- cls._dispatch_http(webhook_url, payload)
101
- if canary_domain:
102
- cls._dispatch_dns_ping(threat_type, canary_domain)
103
-
104
- t = threading.Thread(target=_worker, name="anti_rea_tamper_alert", daemon=True)
105
- t.start()
106
- return t
107
-
108
- @classmethod
109
- def get_injected_beacon_code(
110
- cls,
111
- enc_webhook_bytes: Optional[bytes] = None,
112
- enc_key: int = 0x7E,
113
- canary_domain: Optional[str] = None,
114
- ) -> str:
115
- """Generates self-contained opt-in tamper alert code for protected builds."""
116
- enc_repr = repr(enc_webhook_bytes) if enc_webhook_bytes else "None"
117
- dom_repr = repr(canary_domain) if canary_domain else "None"
118
-
119
- return f'''
120
- # --- SIBER AKADEMI OPT-IN TAMPER ALERT WEBHOOK ---
121
- def _dispatch_tamper_alert(threat_label="DEBUGGER_DETECTED", tool_name="x64dbg"):
122
- """Dispatches opt-in tamper notification only when configured by application author."""
123
- import json, os, socket, sys, threading, urllib.request
124
- enc_bytes = {enc_repr}
125
- canary_dom = {dom_repr}
126
- if not enc_bytes and not canary_dom:
127
- return
128
-
129
- def _alert_job():
130
- if enc_bytes:
131
- try:
132
- url = bytes([b ^ (({enc_key} + i * 13) & 0xFF) for i, b in enumerate(enc_bytes)]).decode("utf-8")
133
- data = json.dumps({{
134
- "threat": threat_label,
135
- "tool": tool_name,
136
- "platform": sys.platform,
137
- "pid": os.getpid(),
138
- }}).encode("utf-8")
139
- req = urllib.request.Request(
140
- url, data=data,
141
- headers={{"Content-Type": "application/json", "User-Agent": "SiberAkademi-TZero-SecurityAudit/1.0"}},
142
- )
143
- urllib.request.urlopen(req, timeout=2.0)
144
- except Exception:
145
- pass
146
- if canary_dom:
147
- try:
148
- sub = "".join(ch if ch.isalnum() else "-" for ch in str(threat_label).lower()).strip("-") or "alert"
149
- socket.getaddrinfo(f"{{sub}}.{{canary_dom}}", 80)
150
- except Exception:
151
- pass
152
-
153
- threading.Thread(target=_alert_job, daemon=True).start()
154
- '''
155
-
156
- @classmethod
157
- def inject_beacon_into_source(
158
- cls,
159
- source_code: str,
160
- webhook_url: Optional[str] = None,
161
- key: int = 0x7E,
162
- canary_domain: Optional[str] = None,
163
- ) -> str:
164
- """Injects opt-in tamper alert helper into protected Python source code."""
165
- enc_bytes = cls.encrypt_endpoint(webhook_url, key=key) if webhook_url else None
166
- snippet = cls.get_injected_beacon_code(enc_bytes, enc_key=key, canary_domain=canary_domain)
167
- return f"{snippet.strip()}\n\n{source_code}"
@@ -1,134 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """Command-Line Interface for Anti-REA.
3
-
4
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
- Part of Siber Akademi T-Zero Security Suite.
6
- License: MIT
7
- """
8
-
9
- import sys
10
- import argparse
11
- import json
12
- from pathlib import Path
13
-
14
- from .engine import AntiREAEngine
15
- from .auditor import AIResistanceAuditor
16
- from .extractor_shield import ExtractorShield
17
- from .traps import AdversarialTrapGenerator
18
- from .tier_catalog import get_tier_catalog
19
-
20
-
21
- def main():
22
- """Main CLI entry point for anti-rea."""
23
- parser = argparse.ArgumentParser(
24
- prog="anti-rea",
25
- description="Anti-REA v5.0: 180-Tier defense engine against AI reverse engineering (morluto/rea, Ghidra MCP) and jailbroken LLMs."
26
- )
27
- subparsers = parser.add_subparsers(dest="command", help="Available subcommands")
28
-
29
- # Command: protect
30
- protect_parser = subparsers.add_parser("protect", help="Hardens Python source file with 180-Tier Anti-REA defense matrix.")
31
- protect_parser.add_argument("path", help="Path to Python file to protect.")
32
- protect_parser.add_argument("-o", "--output", help="Output path (default: overwrite original).")
33
- protect_parser.add_argument("--no-flatten", action="store_true", help="Disable control-flow flattening.")
34
- protect_parser.add_argument("--no-chaff", action="store_true", help="Disable semantic token chaff.")
35
- protect_parser.add_argument("--no-vm", action="store_true", help="Disable dynamic PolyVM container.")
36
- protect_parser.add_argument("--no-jailbreak-decoy", action="store_true", help="Disable cognitive jailbreak decoys.")
37
- protect_parser.add_argument("--no-envelope", action="store_true", help="Disable authenticated bytecode envelope.")
38
- protect_parser.add_argument("--seed", type=int, default=42, help="Random seed for polymorphic passes.")
39
-
40
- # Command: shield-exe
41
- shield_parser = subparsers.add_parser("shield-exe", help="Shields compiled PyInstaller .exe against pyinstxtractor.")
42
- shield_parser.add_argument("exe_path", help="Path to executable binary.")
43
- shield_parser.add_argument("-o", "--output", help="Output path for shielded binary.")
44
-
45
- # Command: audit
46
- audit_parser = subparsers.add_parser("audit", help="Audits target file for 180-Tier Anti-REA resistance.")
47
- audit_parser.add_argument("path", help="Path to file to audit.")
48
- audit_parser.add_argument("--json", action="store_true", help="Output raw JSON.")
49
-
50
- # Command: matrix
51
- matrix_parser = subparsers.add_parser("matrix", help="Prints full 180-Tier (12 Domains x 15 Sub-Tiers) defense catalog.")
52
- matrix_parser.add_argument("--domain", help="Filter by domain ID (e.g. D01..D12).")
53
- matrix_parser.add_argument("--json", action="store_true", help="Output raw JSON catalog.")
54
-
55
- args = parser.parse_args()
56
-
57
- if not args.command:
58
- parser.print_help()
59
- sys.exit(0)
60
-
61
- if args.command == "matrix":
62
- cat = get_tier_catalog()
63
- if args.domain:
64
- dom = args.domain.upper()
65
- cat = {
66
- **cat,
67
- "domains": [d for d in cat["domains"] if d["id"] == dom],
68
- "tiers": [t for t in cat["tiers"] if t["domain_id"] == dom],
69
- }
70
- if args.json:
71
- print(json.dumps(cat, indent=2))
72
- else:
73
- print(f"ANTI-REA v{cat['version']} SOVEREIGN DEFENSE MATRIX ({cat['total_tiers']} Tiers across {cat['total_domains']} Domains)")
74
- for d in cat["domains"]:
75
- print(f" [{d['id']}] {d['name']} ({d['tier_range']}, {d['count']} tiers)")
76
- return
77
-
78
- if args.command == "protect":
79
- res = AntiREAEngine.protect_file(
80
- args.path,
81
- output_path=args.output,
82
- flatten=not args.no_flatten,
83
- token_chaff=not args.no_chaff,
84
- vm_container=not args.no_vm,
85
- jailbreak_decoy=not args.no_jailbreak_decoy,
86
- sealed_envelope=not args.no_envelope,
87
- seed=args.seed
88
- )
89
- if res.get("success"):
90
- print(f"[OK] Successfully applied Anti-REA Armor to: {res['output_file']}")
91
- print(f" AI Resistance Score: {res['score_before']}/100 -> {res['score_after']}/100 [{res.get('tier_rating', res['rating'])}]")
92
- print(f" Verified Tiers Active: {res.get('tiers_active', 0)}/{res.get('tiers_total', 180)} ({res.get('domains_active', 0)}/{res.get('domains_total', 12)} domains)")
93
- else:
94
- print(f"[FAIL] Error protecting file: {res.get('error')}", file=sys.stderr)
95
- sys.exit(1)
96
-
97
- elif args.command == "shield-exe":
98
- res = ExtractorShield.shield_file(args.exe_path, output_path=args.output)
99
- if res.get("shielded"):
100
- print(f"[OK] Shielded executable against pyinstxtractor: {res.get('output_path', args.exe_path)}")
101
- print(f" Decoy archive traps injected: {res.get('decoy_traps_injected', 0)}")
102
- else:
103
- print(f"[INFO] {res.get('reason', 'Already shielded or not a PyInstaller binary.')}")
104
-
105
- elif args.command == "audit":
106
- audit = AIResistanceAuditor.audit_file(args.path)
107
- if audit.get("error"):
108
- if args.json:
109
- print(json.dumps(audit, indent=2))
110
- else:
111
- print(f"[FAIL] {audit['error']}", file=sys.stderr)
112
- sys.exit(1)
113
- if args.json:
114
- print(json.dumps(audit, indent=2))
115
- else:
116
- print("================================================================================")
117
- print(" SHIELD AUDIT REPORT: AI REVERSE-ENGINEERING RESISTANCE (TDQS-REA)")
118
- print("================================================================================")
119
- print(f"Target File: {audit.get('file', args.path)}")
120
- print(f"AI Score: {audit.get('score', 0)} / 100 [{audit.get('rating', 'UNVERIFIED')}]")
121
- print(f"Jailbreak Immune: {'YES (Impregnable)' if audit.get('jailbreak_ai_immune') else 'NO'}")
122
- print(f"Status: {audit.get('status', 'N/A')}")
123
- print("\nActive Defenses:")
124
- for k, v in audit.get("defenses_active", {}).items():
125
- print(f" [{'✔' if v else ' '}] {k}")
126
- if audit.get("findings"):
127
- print("\nRecommendations:")
128
- for f in audit["findings"]:
129
- print(f" • {f}")
130
- print("================================================================================")
131
-
132
-
133
- if __name__ == "__main__":
134
- main()