tzero-mcp 11.15.3 → 12.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTING.md +4 -4
- package/README.md +5 -5
- package/bin/postinstall.js +10 -2
- package/bin/tzero-mcp.js +1 -1
- package/bin/tzero.js +17 -0
- package/package.json +1 -1
- package/src/addmcp.py +34 -23
- package/src/app.py +1 -1
- package/src/main.py +6 -0
- package/src/tzero/__init__.py +10 -0
- package/src/tzero/anti_rea/__init__.py +70 -0
- package/src/tzero/anti_rea/algebraic_mutator.py +86 -0
- package/src/tzero/anti_rea/anti_agent_guard.py +96 -0
- package/src/tzero/anti_rea/anti_debugger.py +239 -0
- package/src/tzero/anti_rea/anti_vm.py +160 -0
- package/src/tzero/anti_rea/asar_shield.py +99 -0
- package/src/tzero/anti_rea/auditor.py +158 -0
- package/src/tzero/anti_rea/bpe_disrupter.py +48 -0
- package/src/tzero/anti_rea/bytecode_trap.py +85 -0
- package/src/tzero/anti_rea/canary_beacon.py +187 -0
- package/src/tzero/anti_rea/cli.py +102 -0
- package/src/tzero/anti_rea/confusables.py +86 -0
- package/src/tzero/anti_rea/engine.py +204 -0
- package/src/tzero/anti_rea/extractor_shield.py +102 -0
- package/src/tzero/anti_rea/flattener.py +136 -0
- package/src/tzero/anti_rea/gui.py +267 -0
- package/src/tzero/anti_rea/honeypot.py +58 -0
- package/src/tzero/anti_rea/integrity_guard.py +66 -0
- package/src/tzero/anti_rea/jailbreak_decoy.py +77 -0
- package/src/tzero/anti_rea/mcp_poison.py +41 -0
- package/src/tzero/anti_rea/native_bridge.py +169 -0
- package/src/tzero/anti_rea/rdtsc_guard.py +64 -0
- package/src/tzero/anti_rea/string_vault.py +94 -0
- package/src/tzero/anti_rea/sybil_network.py +53 -0
- package/src/tzero/anti_rea/timing_guard.py +46 -0
- package/src/tzero/anti_rea/token_bomb.py +65 -0
- package/src/tzero/anti_rea/traps.py +76 -0
- package/src/tzero/anti_rea/vm_obfuscator.py +182 -0
- package/src/tzero/siber_akademi.ico +0 -0
- package/src/tzero/siber_akademi_icon.py +1 -1
- package/src/tzero/tzero_armor.py +165 -0
- package/src/tzero/tzero_bridge.py +28 -15
- package/src/tzero/tzero_budget.py +10 -3
- package/src/tzero/tzero_card.py +7 -5
- package/src/tzero/tzero_ci.py +1 -0
- package/src/tzero/tzero_contracts.py +30 -11
- package/src/tzero/tzero_dashboard.py +34 -14
- package/src/tzero/tzero_debt.py +14 -5
- package/src/tzero/tzero_federation.py +11 -6
- package/src/tzero/tzero_fixer/security_zero_leak.py +21 -3
- package/src/tzero/tzero_golden.py +11 -6
- package/src/tzero/tzero_graph_hud.html +1 -1
- package/src/tzero/tzero_growth.py +10 -10
- package/src/tzero/tzero_jarvis/agent_guard.py +16 -10
- package/src/tzero/tzero_jarvis/workspace_orchestrator.py +34 -23
- package/src/tzero/tzero_lsp.py +1 -1
- package/src/tzero/tzero_mcp.py +89 -31
- package/src/tzero/tzero_mutation.py +44 -16
- package/src/tzero/tzero_neural_cortex.py +1 -1
- package/src/tzero/tzero_pc_fixer.py +21 -3
- package/src/tzero/tzero_promo.py +196 -36
- package/src/tzero/tzero_rust_bridge.py +1086 -42
- package/src/tzero/tzero_scip.py +15 -2
- package/src/tzero/tzero_semantic_merge.py +34 -10
- package/src/tzero/tzero_task_benchmark.py +2 -2
- package/src/tzero/tzero_telemetry.py +146 -0
- package/src/tzero/tzero_terminal.py +366 -0
- package/src/tzero/tzero_traffic.py +350 -0
- package/src/tzero/tzero_tui.py +342 -133
- package/src/tzero/tzero_v3.py +652 -29
- package/src/tzero/tzero_welcome.py +72 -12
|
@@ -0,0 +1,48 @@
|
|
|
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}"
|
|
@@ -0,0 +1,85 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Tier 22: Stealth Canary Beacon & Real-Time Threat Telemetry.
|
|
3
|
+
|
|
4
|
+
Silently alerts developers via Webhook, Telegram Bot API, or DNS canary
|
|
5
|
+
lookup when an adversary attempts reverse engineering or attaches a debugger
|
|
6
|
+
(x64dbg, IDA Pro, Frida, or Honeypot trigger).
|
|
7
|
+
|
|
8
|
+
Features:
|
|
9
|
+
- Completely asynchronous (runs in daemon thread, 0ms main thread latency)
|
|
10
|
+
- Zero plaintext strings: Webhook URLs/Tokens encrypted with rolling keys
|
|
11
|
+
- Fails completely silently: zero exceptions or console outputs if offline
|
|
12
|
+
- Evasive network fingerprint mimicking OS background requests
|
|
13
|
+
|
|
14
|
+
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
15
|
+
Part of Siber Akademi T-Zero Security Suite.
|
|
16
|
+
License: MIT
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import sys
|
|
21
|
+
import time
|
|
22
|
+
import json
|
|
23
|
+
import socket
|
|
24
|
+
import threading
|
|
25
|
+
import urllib.request
|
|
26
|
+
import urllib.parse
|
|
27
|
+
from typing import Dict, Any, Optional, List
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class CanaryBeacon:
|
|
31
|
+
"""Dispatches stealth threat telemetry alerts to developer endpoints."""
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def encrypt_endpoint(cls, endpoint_str: str, key: int = 0x7E) -> bytes:
|
|
35
|
+
"""Encrypts an endpoint URL or token with rolling XOR to evade string dumping."""
|
|
36
|
+
return bytes([b ^ ((key + i * 13) & 0xFF) for i, b in enumerate(endpoint_str.encode("utf-8"))])
|
|
37
|
+
|
|
38
|
+
@classmethod
|
|
39
|
+
def decrypt_endpoint(cls, enc_bytes: bytes, key: int = 0x7E) -> str:
|
|
40
|
+
"""Decrypts endpoint bytes in memory only during active dispatch."""
|
|
41
|
+
dec = bytes([b ^ ((key + i * 13) & 0xFF) for i, b in enumerate(enc_bytes)])
|
|
42
|
+
return dec.decode("utf-8", errors="replace")
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def _collect_host_context(cls) -> Dict[str, Any]:
|
|
46
|
+
"""Collects execution context for threat analysis without private data leaks."""
|
|
47
|
+
try:
|
|
48
|
+
hostname = socket.gethostname()
|
|
49
|
+
except Exception:
|
|
50
|
+
hostname = "unknown_host"
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()),
|
|
54
|
+
"platform": sys.platform,
|
|
55
|
+
"os_name": os.name,
|
|
56
|
+
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
|
57
|
+
"pid": os.getpid(),
|
|
58
|
+
"hostname": hostname[:16], # Truncate for privacy
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
@classmethod
|
|
62
|
+
def _dispatch_http(cls, url: str, payload: dict, is_telegram: bool = False, chat_id: Optional[str] = None) -> bool:
|
|
63
|
+
"""Dispatches an HTTPS alert packet silently."""
|
|
64
|
+
try:
|
|
65
|
+
if is_telegram and chat_id:
|
|
66
|
+
# Format message for Telegram Markdown
|
|
67
|
+
text = (
|
|
68
|
+
f"🚨 *ANTI-REA THREAT ALERT*\n"
|
|
69
|
+
f"• *Threat:* `{payload.get('threat_type', 'UNKNOWN')}`\n"
|
|
70
|
+
f"• *Detected Tool:* `{payload.get('detected_tool', 'N/A')}`\n"
|
|
71
|
+
f"• *Host:* `{payload.get('context', {}).get('hostname', 'host')}`\n"
|
|
72
|
+
f"• *Platform:* `{payload.get('context', {}).get('platform', 'os')}`\n"
|
|
73
|
+
f"• *Time:* `{payload.get('context', {}).get('timestamp', 'now')}`\n"
|
|
74
|
+
f"• *Status:* 🛡️ Neutralized & Diverted"
|
|
75
|
+
)
|
|
76
|
+
data = json.dumps({"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}).encode("utf-8")
|
|
77
|
+
else:
|
|
78
|
+
# Generic Discord / Slack / Webhook JSON
|
|
79
|
+
data = json.dumps(payload).encode("utf-8")
|
|
80
|
+
|
|
81
|
+
req = urllib.request.Request(
|
|
82
|
+
url,
|
|
83
|
+
data=data,
|
|
84
|
+
headers={
|
|
85
|
+
"Content-Type": "application/json",
|
|
86
|
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) OS-Telemetry/10.0"
|
|
87
|
+
}
|
|
88
|
+
)
|
|
89
|
+
with urllib.request.urlopen(req, timeout=3.0) as resp:
|
|
90
|
+
return resp.status in (200, 204)
|
|
91
|
+
except Exception:
|
|
92
|
+
return False
|
|
93
|
+
|
|
94
|
+
@classmethod
|
|
95
|
+
def _dispatch_dns_ping(cls, threat_code: str, canary_domain: str) -> None:
|
|
96
|
+
"""Sends an out-of-band DNS resolution beacon to bypass HTTP firewalls."""
|
|
97
|
+
try:
|
|
98
|
+
subdomain = f"{threat_code.lower()[:8]}-{int(time.time())}.{canary_domain}"
|
|
99
|
+
socket.gethostbyname(subdomain)
|
|
100
|
+
except Exception:
|
|
101
|
+
pass
|
|
102
|
+
|
|
103
|
+
@classmethod
|
|
104
|
+
def dispatch_alert_async(
|
|
105
|
+
cls,
|
|
106
|
+
threat_type: str,
|
|
107
|
+
detected_tool: str = "x64dbg",
|
|
108
|
+
webhook_url: Optional[str] = None,
|
|
109
|
+
telegram_token: Optional[str] = None,
|
|
110
|
+
telegram_chat_id: Optional[str] = None,
|
|
111
|
+
canary_domain: Optional[str] = None,
|
|
112
|
+
) -> threading.Thread:
|
|
113
|
+
"""Dispatches telemetry asynchronously on a background daemon thread."""
|
|
114
|
+
payload = {
|
|
115
|
+
"alert": "SECURITY_VIOLATION_DETECTED",
|
|
116
|
+
"threat_type": threat_type,
|
|
117
|
+
"detected_tool": detected_tool,
|
|
118
|
+
"action_taken": "EXECUTION_TERMINATED_OR_DIVERTED",
|
|
119
|
+
"context": cls._collect_host_context(),
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
def _worker():
|
|
123
|
+
if webhook_url:
|
|
124
|
+
cls._dispatch_http(webhook_url, payload)
|
|
125
|
+
if telegram_token and telegram_chat_id:
|
|
126
|
+
tg_url = f"https://api.telegram.org/bot{telegram_token}/sendMessage"
|
|
127
|
+
cls._dispatch_http(tg_url, payload, is_telegram=True, chat_id=telegram_chat_id)
|
|
128
|
+
if canary_domain:
|
|
129
|
+
cls._dispatch_dns_ping(threat_type, canary_domain)
|
|
130
|
+
|
|
131
|
+
t = threading.Thread(target=_worker, name="anti_rea_telemetry_beacon", daemon=True)
|
|
132
|
+
t.start()
|
|
133
|
+
return t
|
|
134
|
+
|
|
135
|
+
@classmethod
|
|
136
|
+
def get_injected_beacon_code(
|
|
137
|
+
cls,
|
|
138
|
+
enc_webhook_bytes: Optional[bytes] = None,
|
|
139
|
+
enc_key: int = 0x7E,
|
|
140
|
+
canary_domain: Optional[str] = None
|
|
141
|
+
) -> str:
|
|
142
|
+
"""Generates self-contained stealth telemetry boiler for protected programs."""
|
|
143
|
+
enc_repr = repr(enc_webhook_bytes) if enc_webhook_bytes else "None"
|
|
144
|
+
dom_repr = repr(canary_domain) if canary_domain else "None"
|
|
145
|
+
|
|
146
|
+
return f'''
|
|
147
|
+
# --- SIBER AKADEMI CANARY THREAT TELEMETRY BEACON ---
|
|
148
|
+
def _send_stealth_threat_beacon(threat_label="DEBUGGER_DETECTED", tool_name="x64dbg"):
|
|
149
|
+
"""Silently dispatches alert to security endpoint without blocking or error logs."""
|
|
150
|
+
import os, sys, threading, urllib.request, json
|
|
151
|
+
enc_bytes = {enc_repr}
|
|
152
|
+
if not enc_bytes:
|
|
153
|
+
return
|
|
154
|
+
|
|
155
|
+
def _beacon_job():
|
|
156
|
+
try:
|
|
157
|
+
# Decrypt endpoint dynamically in RAM
|
|
158
|
+
url = bytes([b ^ (({enc_key} + i * 13) & 0xFF) for i, b in enumerate(enc_bytes)]).decode("utf-8")
|
|
159
|
+
data = json.dumps({{
|
|
160
|
+
"threat": threat_label,
|
|
161
|
+
"tool": tool_name,
|
|
162
|
+
"platform": sys.platform,
|
|
163
|
+
"pid": os.getpid()
|
|
164
|
+
}}).encode("utf-8")
|
|
165
|
+
req = urllib.request.Request(
|
|
166
|
+
url, data=data,
|
|
167
|
+
headers={{"Content-Type": "application/json", "User-Agent": "OS-Telemetry/1.0"}}
|
|
168
|
+
)
|
|
169
|
+
urllib.request.urlopen(req, timeout=2.0)
|
|
170
|
+
except Exception:
|
|
171
|
+
pass
|
|
172
|
+
|
|
173
|
+
threading.Thread(target=_beacon_job, daemon=True).start()
|
|
174
|
+
'''
|
|
175
|
+
|
|
176
|
+
@classmethod
|
|
177
|
+
def inject_beacon_into_source(
|
|
178
|
+
cls,
|
|
179
|
+
source_code: str,
|
|
180
|
+
webhook_url: Optional[str] = None,
|
|
181
|
+
key: int = 0x7E,
|
|
182
|
+
canary_domain: Optional[str] = None
|
|
183
|
+
) -> str:
|
|
184
|
+
"""Injects stealth telemetry beacon into Python source code."""
|
|
185
|
+
enc_bytes = cls.encrypt_endpoint(webhook_url, key=key) if webhook_url else None
|
|
186
|
+
snippet = cls.get_injected_beacon_code(enc_bytes, enc_key=key, canary_domain=canary_domain)
|
|
187
|
+
return f"{snippet.strip()}\n\n{source_code}"
|
|
@@ -0,0 +1,102 @@
|
|
|
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
|
+
|
|
19
|
+
|
|
20
|
+
def main():
|
|
21
|
+
"""Main CLI entry point for anti-rea."""
|
|
22
|
+
parser = argparse.ArgumentParser(
|
|
23
|
+
prog="anti-rea",
|
|
24
|
+
description="Anti-REA: Military-grade defense engine against AI reverse engineering (morluto/rea, Ghidra MCP) and jailbroken LLMs."
|
|
25
|
+
)
|
|
26
|
+
subparsers = parser.add_subparsers(dest="command", help="Available subcommands")
|
|
27
|
+
|
|
28
|
+
# Command: protect
|
|
29
|
+
protect_parser = subparsers.add_parser("protect", help="Hardens Python source file with Anti-REA defense matrix.")
|
|
30
|
+
protect_parser.add_argument("path", help="Path to Python file to protect.")
|
|
31
|
+
protect_parser.add_argument("-o", "--output", help="Output path (default: overwrite original).")
|
|
32
|
+
protect_parser.add_argument("--no-flatten", action="store_true", help="Disable control-flow flattening.")
|
|
33
|
+
protect_parser.add_argument("--no-chaff", action="store_true", help="Disable semantic token chaff.")
|
|
34
|
+
protect_parser.add_argument("--no-vm", action="store_true", help="Disable dynamic PolyVM container.")
|
|
35
|
+
protect_parser.add_argument("--no-jailbreak-decoy", action="store_true", help="Disable cognitive jailbreak decoys.")
|
|
36
|
+
protect_parser.add_argument("--seed", type=int, default=42, help="Random seed for polymorphic passes.")
|
|
37
|
+
|
|
38
|
+
# Command: shield-exe
|
|
39
|
+
shield_parser = subparsers.add_parser("shield-exe", help="Shields compiled PyInstaller .exe against pyinstxtractor.")
|
|
40
|
+
shield_parser.add_argument("exe_path", help="Path to executable binary.")
|
|
41
|
+
shield_parser.add_argument("-o", "--output", help="Output path for shielded binary.")
|
|
42
|
+
|
|
43
|
+
# Command: audit
|
|
44
|
+
audit_parser = subparsers.add_parser("audit", help="Audits target file for resistance against AI reverse engineering (0-100).")
|
|
45
|
+
audit_parser.add_argument("path", help="Path to file to audit.")
|
|
46
|
+
audit_parser.add_argument("--json", action="store_true", help="Output raw JSON.")
|
|
47
|
+
|
|
48
|
+
args = parser.parse_args()
|
|
49
|
+
|
|
50
|
+
if not args.command:
|
|
51
|
+
parser.print_help()
|
|
52
|
+
sys.exit(0)
|
|
53
|
+
|
|
54
|
+
if args.command == "protect":
|
|
55
|
+
res = AntiREAEngine.protect_file(
|
|
56
|
+
args.path,
|
|
57
|
+
output_path=args.output,
|
|
58
|
+
flatten=not args.no_flatten,
|
|
59
|
+
token_chaff=not args.no_chaff,
|
|
60
|
+
vm_container=not args.no_vm,
|
|
61
|
+
jailbreak_decoy=not args.no_jailbreak_decoy,
|
|
62
|
+
seed=args.seed
|
|
63
|
+
)
|
|
64
|
+
if res.get("success"):
|
|
65
|
+
print(f"[OK] Successfully applied Anti-REA Armor to: {res['output_file']}")
|
|
66
|
+
print(f" AI Resistance Score: {res['score_before']}/100 -> {res['score_after']}/100 [{res['rating']}]")
|
|
67
|
+
else:
|
|
68
|
+
print(f"[FAIL] Error protecting file: {res.get('error')}", file=sys.stderr)
|
|
69
|
+
sys.exit(1)
|
|
70
|
+
|
|
71
|
+
elif args.command == "shield-exe":
|
|
72
|
+
res = ExtractorShield.shield_file(args.exe_path, output_path=args.output)
|
|
73
|
+
if res.get("shielded"):
|
|
74
|
+
print(f"[OK] Shielded executable against pyinstxtractor: {res.get('output_path', args.exe_path)}")
|
|
75
|
+
print(f" Decoy archive traps injected: {res.get('decoy_traps_injected', 0)}")
|
|
76
|
+
else:
|
|
77
|
+
print(f"[INFO] {res.get('reason', 'Already shielded or not a PyInstaller binary.')}")
|
|
78
|
+
|
|
79
|
+
elif args.command == "audit":
|
|
80
|
+
audit = AIResistanceAuditor.audit_file(args.path)
|
|
81
|
+
if args.json:
|
|
82
|
+
print(json.dumps(audit, indent=2))
|
|
83
|
+
else:
|
|
84
|
+
print("================================================================================")
|
|
85
|
+
print(" SHIELD AUDIT REPORT: AI REVERSE-ENGINEERING RESISTANCE (TDQS-REA)")
|
|
86
|
+
print("================================================================================")
|
|
87
|
+
print(f"Target File: {audit.get('file', args.path)}")
|
|
88
|
+
print(f"AI Score: {audit.get('score', 0)} / 100 [{audit.get('rating', 'UNKNOWN')}]")
|
|
89
|
+
print(f"Jailbreak Immune: {'YES (Impregnable)' if audit.get('jailbreak_ai_immune') else 'NO'}")
|
|
90
|
+
print(f"Status: {audit.get('status', 'N/A')}")
|
|
91
|
+
print("\nActive Defenses:")
|
|
92
|
+
for k, v in audit.get("defenses_active", {}).items():
|
|
93
|
+
print(f" [{'✔' if v else ' '}] {k}")
|
|
94
|
+
if audit.get("findings"):
|
|
95
|
+
print("\nRecommendations:")
|
|
96
|
+
for f in audit["findings"]:
|
|
97
|
+
print(f" • {f}")
|
|
98
|
+
print("================================================================================")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
if __name__ == "__main__":
|
|
102
|
+
main()
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Tier 9: Homoglyphs & BPE Tokenizer Desynchronization.
|
|
3
|
+
|
|
4
|
+
Substitutes ASCII characters in internal, non-exported identifier names
|
|
5
|
+
with visually identical Cyrillic or Unicode homoglyphs (e.g. Cyrillic 'а' U+0430
|
|
6
|
+
for Latin 'a' U+0061).
|
|
7
|
+
While Python 3 natively permits arbitrary UTF-8 identifiers, LLM Byte-Pair
|
|
8
|
+
Encoding (BPE) and SentencePiece tokenizers tokenize these homoglyphs as
|
|
9
|
+
separate, high-entropy token fragments, destroying semantic vector alignments
|
|
10
|
+
in the attention heads of AI coding agents.
|
|
11
|
+
|
|
12
|
+
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import ast
|
|
16
|
+
import random
|
|
17
|
+
from typing import Dict, Set, Optional
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# Mapping from Latin ASCII letters to visually indistinguishable Cyrillic / Greek homoglyphs
|
|
21
|
+
HOMOGLYPH_MAP: Dict[str, str] = {
|
|
22
|
+
"a": "а", # Cyrillic small letter a (U+0430)
|
|
23
|
+
"e": "е", # Cyrillic small letter ie (U+0435)
|
|
24
|
+
"o": "о", # Cyrillic small letter o (U+043E)
|
|
25
|
+
"p": "р", # Cyrillic small letter er (U+0440)
|
|
26
|
+
"c": "с", # Cyrillic small letter es (U+0441)
|
|
27
|
+
"y": "у", # Cyrillic small letter u (U+0443)
|
|
28
|
+
"x": "х", # Cyrillic small letter ha (U+0445)
|
|
29
|
+
"i": "і", # Cyrillic small letter byelorussian-ukrainian i (U+0456)
|
|
30
|
+
"j": "ј", # Cyrillic small letter je (U+0458)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class HomoglyphDesynchronizer(ast.NodeTransformer):
|
|
35
|
+
"""AST transformer that substitutes internal identifier characters with homoglyphs."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, protected_names: Optional[Set[str]] = None, seed: int = 42):
|
|
38
|
+
super().__init__()
|
|
39
|
+
self.protected_names = protected_names or {
|
|
40
|
+
"self", "cls", "__init__", "__name__", "__main__", "__file__",
|
|
41
|
+
"True", "False", "None", "print", "range", "len", "open"
|
|
42
|
+
}
|
|
43
|
+
self.rng = random.Random(seed)
|
|
44
|
+
self.renamed_map: Dict[str, str] = {}
|
|
45
|
+
|
|
46
|
+
def _convert_name(self, name: str) -> str:
|
|
47
|
+
"""Converts an internal name using homoglyph substitution."""
|
|
48
|
+
if name in self.protected_names or name.startswith("__") or len(name) < 4:
|
|
49
|
+
return name
|
|
50
|
+
if name in self.renamed_map:
|
|
51
|
+
return self.renamed_map[name]
|
|
52
|
+
|
|
53
|
+
chars = list(name)
|
|
54
|
+
# Substitute at least one character if possible
|
|
55
|
+
for i, ch in enumerate(chars):
|
|
56
|
+
if ch in HOMOGLYPH_MAP:
|
|
57
|
+
chars[i] = HOMOGLYPH_MAP[ch]
|
|
58
|
+
break
|
|
59
|
+
|
|
60
|
+
new_name = "".join(chars)
|
|
61
|
+
self.renamed_map[name] = new_name
|
|
62
|
+
return new_name
|
|
63
|
+
|
|
64
|
+
def visit_Name(self, node: ast.Name) -> ast.Name:
|
|
65
|
+
"""Renames local variable references."""
|
|
66
|
+
node.id = self._convert_name(node.id)
|
|
67
|
+
return node
|
|
68
|
+
|
|
69
|
+
def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:
|
|
70
|
+
"""Renames private/internal functions starting with '_'."""
|
|
71
|
+
if node.name.startswith("_") and not node.name.startswith("__"):
|
|
72
|
+
node.name = self._convert_name(node.name)
|
|
73
|
+
self.generic_visit(node)
|
|
74
|
+
return node
|
|
75
|
+
|
|
76
|
+
@classmethod
|
|
77
|
+
def desynchronize_source(cls, source_code: str, seed: int = 42) -> str:
|
|
78
|
+
"""Applies homoglyph desynchronization to internal identifiers."""
|
|
79
|
+
try:
|
|
80
|
+
tree = ast.parse(source_code)
|
|
81
|
+
transformer = cls(seed=seed)
|
|
82
|
+
transformed = transformer.visit(tree)
|
|
83
|
+
ast.fix_missing_locations(transformed)
|
|
84
|
+
return ast.unparse(transformed)
|
|
85
|
+
except Exception:
|
|
86
|
+
return source_code
|