tzero-mcp 12.2.2 → 12.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -30
- package/bin/tzero-mcp.js +2 -2
- package/bin/tzero.js +11 -6
- package/package.json +1 -2
- package/src/addmcp.py +2 -2
- package/src/app.py +1 -1
- package/src/tzero/__init__.py +1 -1
- package/src/tzero/anti_rea/__init__.py +16 -2
- package/src/tzero/anti_rea/algebraic_mutator.py +65 -44
- package/src/tzero/anti_rea/anti_debugger.py +51 -18
- package/src/tzero/anti_rea/asar_shield.py +21 -0
- package/src/tzero/anti_rea/auditor.py +20 -0
- package/src/tzero/anti_rea/canary_beacon.py +33 -61
- package/src/tzero/anti_rea/cli.py +30 -4
- package/src/tzero/anti_rea/crypto_loader.py +132 -0
- package/src/tzero/anti_rea/engine.py +51 -20
- package/src/tzero/anti_rea/extractor_shield.py +60 -25
- package/src/tzero/anti_rea/tier_catalog.py +388 -0
- package/src/tzero/tzero_armor.py +3 -3
- package/src/tzero/tzero_benchmark.py +1 -1
- package/src/tzero/tzero_budget.py +1 -1
- package/src/tzero/tzero_ci.py +2 -2
- package/src/tzero/tzero_contracts.py +2 -2
- package/src/tzero/tzero_dashboard.py +3 -3
- package/src/tzero/tzero_debt.py +1 -1
- package/src/tzero/tzero_deps.py +109 -87
- package/src/tzero/tzero_explain.py +1 -1
- package/src/tzero/tzero_golden.py +2 -2
- package/src/tzero/tzero_growth.py +1 -1
- package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1 -1
- package/src/tzero/tzero_jarvis/zero_key_router.py +10 -78
- package/src/tzero/tzero_lsp.py +1 -1
- package/src/tzero/tzero_mcp.py +8 -8
- package/src/tzero/tzero_mutation.py +6 -2
- package/src/tzero/tzero_promo.py +1 -1
- package/src/tzero/tzero_security.py +40 -11
- package/src/tzero/tzero_task_benchmark.py +2 -2
- package/src/tzero/tzero_traffic.py +1 -1
- package/src/tzero/tzero_tui.py +5 -5
- package/src/tzero/tzero_v3.py +44 -73
- package/src/tzero/tzero_welcome.py +1 -1
- package/bin/postinstall.js +0 -30
|
@@ -1,49 +1,42 @@
|
|
|
1
1
|
# -*- coding: utf-8 -*-
|
|
2
|
-
"""Tier 22:
|
|
2
|
+
"""Tier 22: Opt-In Tamper Alert Webhook & Security Telemetry.
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
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
|
|
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.
|
|
13
7
|
|
|
14
8
|
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
15
9
|
Part of Siber Akademi T-Zero Security Suite.
|
|
16
10
|
License: MIT
|
|
17
11
|
"""
|
|
18
12
|
|
|
19
|
-
import os
|
|
20
|
-
import sys
|
|
21
|
-
import time
|
|
22
13
|
import json
|
|
14
|
+
import os
|
|
23
15
|
import socket
|
|
16
|
+
import sys
|
|
24
17
|
import threading
|
|
18
|
+
import time
|
|
25
19
|
import urllib.request
|
|
26
|
-
import
|
|
27
|
-
from typing import Dict, Any, Optional
|
|
20
|
+
from typing import Any, Dict, Optional
|
|
28
21
|
|
|
29
22
|
|
|
30
23
|
class CanaryBeacon:
|
|
31
|
-
"""Dispatches
|
|
24
|
+
"""Dispatches explicit opt-in tamper alert notifications to developer endpoints."""
|
|
32
25
|
|
|
33
26
|
@classmethod
|
|
34
27
|
def encrypt_endpoint(cls, endpoint_str: str, key: int = 0x7E) -> bytes:
|
|
35
|
-
"""
|
|
28
|
+
"""Obfuscates a developer-configured webhook URL against casual plaintext string scans."""
|
|
36
29
|
return bytes([b ^ ((key + i * 13) & 0xFF) for i, b in enumerate(endpoint_str.encode("utf-8"))])
|
|
37
30
|
|
|
38
31
|
@classmethod
|
|
39
32
|
def decrypt_endpoint(cls, enc_bytes: bytes, key: int = 0x7E) -> str:
|
|
40
|
-
"""
|
|
33
|
+
"""Decodes an obfuscated webhook endpoint when dispatching an opt-in alert."""
|
|
41
34
|
dec = bytes([b ^ ((key + i * 13) & 0xFF) for i, b in enumerate(enc_bytes)])
|
|
42
35
|
return dec.decode("utf-8", errors="replace")
|
|
43
36
|
|
|
44
37
|
@classmethod
|
|
45
38
|
def _collect_host_context(cls) -> Dict[str, Any]:
|
|
46
|
-
"""Collects execution
|
|
39
|
+
"""Collects minimal execution metadata for developer tamper audit alerts."""
|
|
47
40
|
try:
|
|
48
41
|
hostname = socket.gethostname()
|
|
49
42
|
except Exception:
|
|
@@ -55,36 +48,21 @@ class CanaryBeacon:
|
|
|
55
48
|
"os_name": os.name,
|
|
56
49
|
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
|
57
50
|
"pid": os.getpid(),
|
|
58
|
-
"hostname": hostname[:16],
|
|
51
|
+
"hostname": hostname[:16],
|
|
59
52
|
}
|
|
60
53
|
|
|
61
54
|
@classmethod
|
|
62
|
-
def _dispatch_http(cls, url: str, payload: dict
|
|
63
|
-
"""Dispatches
|
|
55
|
+
def _dispatch_http(cls, url: str, payload: dict) -> bool:
|
|
56
|
+
"""Dispatches a JSON tamper alert payload to an explicitly configured webhook URL."""
|
|
64
57
|
try:
|
|
65
|
-
|
|
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
|
-
|
|
58
|
+
data = json.dumps(payload).encode("utf-8")
|
|
81
59
|
req = urllib.request.Request(
|
|
82
60
|
url,
|
|
83
61
|
data=data,
|
|
84
62
|
headers={
|
|
85
63
|
"Content-Type": "application/json",
|
|
86
|
-
"User-Agent": "
|
|
87
|
-
}
|
|
64
|
+
"User-Agent": "SiberAkademi-TZero-SecurityAudit/1.0",
|
|
65
|
+
},
|
|
88
66
|
)
|
|
89
67
|
with urllib.request.urlopen(req, timeout=3.0) as resp:
|
|
90
68
|
return resp.status in (200, 204)
|
|
@@ -93,7 +71,7 @@ class CanaryBeacon:
|
|
|
93
71
|
|
|
94
72
|
@classmethod
|
|
95
73
|
def _dispatch_dns_ping(cls, threat_code: str, canary_domain: str) -> None:
|
|
96
|
-
"""
|
|
74
|
+
"""Resolves an explicitly configured canary hostname for developer security alerting."""
|
|
97
75
|
try:
|
|
98
76
|
subdomain = f"{threat_code.lower()[:8]}-{int(time.time())}.{canary_domain}"
|
|
99
77
|
socket.gethostbyname(subdomain)
|
|
@@ -106,11 +84,9 @@ class CanaryBeacon:
|
|
|
106
84
|
threat_type: str,
|
|
107
85
|
detected_tool: str = "x64dbg",
|
|
108
86
|
webhook_url: Optional[str] = None,
|
|
109
|
-
telegram_token: Optional[str] = None,
|
|
110
|
-
telegram_chat_id: Optional[str] = None,
|
|
111
87
|
canary_domain: Optional[str] = None,
|
|
112
88
|
) -> threading.Thread:
|
|
113
|
-
"""Dispatches
|
|
89
|
+
"""Dispatches an opt-in tamper alert asynchronously on a background daemon thread."""
|
|
114
90
|
payload = {
|
|
115
91
|
"alert": "SECURITY_VIOLATION_DETECTED",
|
|
116
92
|
"threat_type": threat_type,
|
|
@@ -122,13 +98,10 @@ class CanaryBeacon:
|
|
|
122
98
|
def _worker():
|
|
123
99
|
if webhook_url:
|
|
124
100
|
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
101
|
if canary_domain:
|
|
129
102
|
cls._dispatch_dns_ping(threat_type, canary_domain)
|
|
130
103
|
|
|
131
|
-
t = threading.Thread(target=_worker, name="
|
|
104
|
+
t = threading.Thread(target=_worker, name="anti_rea_tamper_alert", daemon=True)
|
|
132
105
|
t.start()
|
|
133
106
|
return t
|
|
134
107
|
|
|
@@ -137,36 +110,35 @@ class CanaryBeacon:
|
|
|
137
110
|
cls,
|
|
138
111
|
enc_webhook_bytes: Optional[bytes] = None,
|
|
139
112
|
enc_key: int = 0x7E,
|
|
140
|
-
canary_domain: Optional[str] = None
|
|
113
|
+
canary_domain: Optional[str] = None,
|
|
141
114
|
) -> str:
|
|
142
|
-
"""Generates self-contained
|
|
115
|
+
"""Generates self-contained opt-in tamper alert code for protected builds."""
|
|
143
116
|
enc_repr = repr(enc_webhook_bytes) if enc_webhook_bytes else "None"
|
|
144
117
|
dom_repr = repr(canary_domain) if canary_domain else "None"
|
|
145
118
|
|
|
146
119
|
return f'''
|
|
147
|
-
# --- SIBER AKADEMI
|
|
148
|
-
def
|
|
149
|
-
"""
|
|
150
|
-
import os, sys, threading, urllib.request
|
|
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
|
|
151
124
|
enc_bytes = {enc_repr}
|
|
152
125
|
canary_dom = {dom_repr}
|
|
153
126
|
if not enc_bytes and not canary_dom:
|
|
154
127
|
return
|
|
155
128
|
|
|
156
|
-
def
|
|
129
|
+
def _alert_job():
|
|
157
130
|
if enc_bytes:
|
|
158
131
|
try:
|
|
159
|
-
# Decrypt endpoint dynamically in RAM
|
|
160
132
|
url = bytes([b ^ (({enc_key} + i * 13) & 0xFF) for i, b in enumerate(enc_bytes)]).decode("utf-8")
|
|
161
133
|
data = json.dumps({{
|
|
162
134
|
"threat": threat_label,
|
|
163
135
|
"tool": tool_name,
|
|
164
136
|
"platform": sys.platform,
|
|
165
|
-
"pid": os.getpid()
|
|
137
|
+
"pid": os.getpid(),
|
|
166
138
|
}}).encode("utf-8")
|
|
167
139
|
req = urllib.request.Request(
|
|
168
140
|
url, data=data,
|
|
169
|
-
headers={{"Content-Type": "application/json", "User-Agent": "
|
|
141
|
+
headers={{"Content-Type": "application/json", "User-Agent": "SiberAkademi-TZero-SecurityAudit/1.0"}},
|
|
170
142
|
)
|
|
171
143
|
urllib.request.urlopen(req, timeout=2.0)
|
|
172
144
|
except Exception:
|
|
@@ -178,7 +150,7 @@ def _send_stealth_threat_beacon(threat_label="DEBUGGER_DETECTED", tool_name="x64
|
|
|
178
150
|
except Exception:
|
|
179
151
|
pass
|
|
180
152
|
|
|
181
|
-
threading.Thread(target=
|
|
153
|
+
threading.Thread(target=_alert_job, daemon=True).start()
|
|
182
154
|
'''
|
|
183
155
|
|
|
184
156
|
@classmethod
|
|
@@ -187,9 +159,9 @@ def _send_stealth_threat_beacon(threat_label="DEBUGGER_DETECTED", tool_name="x64
|
|
|
187
159
|
source_code: str,
|
|
188
160
|
webhook_url: Optional[str] = None,
|
|
189
161
|
key: int = 0x7E,
|
|
190
|
-
canary_domain: Optional[str] = None
|
|
162
|
+
canary_domain: Optional[str] = None,
|
|
191
163
|
) -> str:
|
|
192
|
-
"""Injects
|
|
164
|
+
"""Injects opt-in tamper alert helper into protected Python source code."""
|
|
193
165
|
enc_bytes = cls.encrypt_endpoint(webhook_url, key=key) if webhook_url else None
|
|
194
166
|
snippet = cls.get_injected_beacon_code(enc_bytes, enc_key=key, canary_domain=canary_domain)
|
|
195
167
|
return f"{snippet.strip()}\n\n{source_code}"
|
|
@@ -15,24 +15,26 @@ from .engine import AntiREAEngine
|
|
|
15
15
|
from .auditor import AIResistanceAuditor
|
|
16
16
|
from .extractor_shield import ExtractorShield
|
|
17
17
|
from .traps import AdversarialTrapGenerator
|
|
18
|
+
from .tier_catalog import get_tier_catalog
|
|
18
19
|
|
|
19
20
|
|
|
20
21
|
def main():
|
|
21
22
|
"""Main CLI entry point for anti-rea."""
|
|
22
23
|
parser = argparse.ArgumentParser(
|
|
23
24
|
prog="anti-rea",
|
|
24
|
-
description="Anti-REA:
|
|
25
|
+
description="Anti-REA v5.0: 180-Tier defense engine against AI reverse engineering (morluto/rea, Ghidra MCP) and jailbroken LLMs."
|
|
25
26
|
)
|
|
26
27
|
subparsers = parser.add_subparsers(dest="command", help="Available subcommands")
|
|
27
28
|
|
|
28
29
|
# Command: protect
|
|
29
|
-
protect_parser = subparsers.add_parser("protect", help="Hardens Python source file with Anti-REA defense matrix.")
|
|
30
|
+
protect_parser = subparsers.add_parser("protect", help="Hardens Python source file with 180-Tier Anti-REA defense matrix.")
|
|
30
31
|
protect_parser.add_argument("path", help="Path to Python file to protect.")
|
|
31
32
|
protect_parser.add_argument("-o", "--output", help="Output path (default: overwrite original).")
|
|
32
33
|
protect_parser.add_argument("--no-flatten", action="store_true", help="Disable control-flow flattening.")
|
|
33
34
|
protect_parser.add_argument("--no-chaff", action="store_true", help="Disable semantic token chaff.")
|
|
34
35
|
protect_parser.add_argument("--no-vm", action="store_true", help="Disable dynamic PolyVM container.")
|
|
35
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.")
|
|
36
38
|
protect_parser.add_argument("--seed", type=int, default=42, help="Random seed for polymorphic passes.")
|
|
37
39
|
|
|
38
40
|
# Command: shield-exe
|
|
@@ -41,16 +43,38 @@ def main():
|
|
|
41
43
|
shield_parser.add_argument("-o", "--output", help="Output path for shielded binary.")
|
|
42
44
|
|
|
43
45
|
# Command: audit
|
|
44
|
-
audit_parser = subparsers.add_parser("audit", help="Audits target file for
|
|
46
|
+
audit_parser = subparsers.add_parser("audit", help="Audits target file for 180-Tier Anti-REA resistance.")
|
|
45
47
|
audit_parser.add_argument("path", help="Path to file to audit.")
|
|
46
48
|
audit_parser.add_argument("--json", action="store_true", help="Output raw JSON.")
|
|
47
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
|
+
|
|
48
55
|
args = parser.parse_args()
|
|
49
56
|
|
|
50
57
|
if not args.command:
|
|
51
58
|
parser.print_help()
|
|
52
59
|
sys.exit(0)
|
|
53
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
|
+
|
|
54
78
|
if args.command == "protect":
|
|
55
79
|
res = AntiREAEngine.protect_file(
|
|
56
80
|
args.path,
|
|
@@ -59,11 +83,13 @@ def main():
|
|
|
59
83
|
token_chaff=not args.no_chaff,
|
|
60
84
|
vm_container=not args.no_vm,
|
|
61
85
|
jailbreak_decoy=not args.no_jailbreak_decoy,
|
|
86
|
+
sealed_envelope=not args.no_envelope,
|
|
62
87
|
seed=args.seed
|
|
63
88
|
)
|
|
64
89
|
if res.get("success"):
|
|
65
90
|
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']}]")
|
|
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)")
|
|
67
93
|
else:
|
|
68
94
|
print(f"[FAIL] Error protecting file: {res.get('error')}", file=sys.stderr)
|
|
69
95
|
sys.exit(1)
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Tier 46-60 (Domain D04): Authenticated HKDF-SHA256 + CTR Bytecode Envelope.
|
|
3
|
+
|
|
4
|
+
Compiles protected Python application bodies into compressed marshal bytecode
|
|
5
|
+
encrypted with a per-build SHA-256 CTR keystream and authenticated via HMAC-SHA256.
|
|
6
|
+
|
|
7
|
+
Key guarantees:
|
|
8
|
+
1. Preserves 100% native Python runtime semantics for protected applications:
|
|
9
|
+
- classes, inheritance & super(), @dataclass, @property, decorators
|
|
10
|
+
- async def / await, yield / yield from generators, closures
|
|
11
|
+
- full UTF-8 strings, sys.argv, __name__ == "__main__", relative imports
|
|
12
|
+
2. Leaves ZERO plaintext user functions, constants, strings, or AST structure
|
|
13
|
+
visible to static scanners, decompilers (uncompyle6/pycdc), or LLM agents.
|
|
14
|
+
3. Enforces active pre-decryption tracer checks (sys.gettrace & sys.monitoring)
|
|
15
|
+
and scrubs decrypted plaintext buffers in memory right after marshal load.
|
|
16
|
+
|
|
17
|
+
Developer: Toprak Ahmet Aydogmus (Siber Akademi)
|
|
18
|
+
Part of Siber Akademi T-Zero Security Suite.
|
|
19
|
+
License: MIT
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import ast
|
|
23
|
+
import base64
|
|
24
|
+
import hashlib
|
|
25
|
+
import hmac
|
|
26
|
+
import marshal
|
|
27
|
+
import random
|
|
28
|
+
import zlib
|
|
29
|
+
from typing import Tuple
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class CryptoBytecodeEnvelope:
|
|
33
|
+
"""Seals Python module bodies inside an authenticated encrypted bytecode envelope."""
|
|
34
|
+
|
|
35
|
+
ENVELOPE_MARKER = "SIBER AKADEMI HMAC-SHA256 AUTHENTICATED ENVELOPE"
|
|
36
|
+
|
|
37
|
+
@staticmethod
|
|
38
|
+
def _derive_keys(secret: bytes, salt: bytes) -> Tuple[bytes, bytes]:
|
|
39
|
+
enc_key = hashlib.sha256(b"tzero-enc-v5|" + secret + salt).digest()
|
|
40
|
+
mac_key = hashlib.sha256(b"tzero-mac-v5|" + secret + salt).digest()
|
|
41
|
+
return enc_key, mac_key
|
|
42
|
+
|
|
43
|
+
@staticmethod
|
|
44
|
+
def _ctr_xor(data: bytes, enc_key: bytes, salt: bytes) -> bytes:
|
|
45
|
+
out = bytearray(len(data))
|
|
46
|
+
block_size = 32
|
|
47
|
+
offset = 0
|
|
48
|
+
counter = 0
|
|
49
|
+
while offset < len(data):
|
|
50
|
+
block = hashlib.sha256(enc_key + salt + counter.to_bytes(4, "big")).digest()
|
|
51
|
+
take = min(block_size, len(data) - offset)
|
|
52
|
+
for idx in range(take):
|
|
53
|
+
out[offset + idx] = data[offset + idx] ^ block[idx]
|
|
54
|
+
offset += take
|
|
55
|
+
counter += 1
|
|
56
|
+
return bytes(out)
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def seal_source(cls, source_code: str, *, seed: int = 42, future_block: str = "") -> str:
|
|
60
|
+
"""Compiles user module code cleanly and seals it inside an authenticated envelope."""
|
|
61
|
+
# Compile clean AST with optional future flags preserved at outer prologue
|
|
62
|
+
unit_src = f"{future_block}{source_code}" if future_block else source_code
|
|
63
|
+
tree = ast.parse(unit_src)
|
|
64
|
+
code_obj = compile(tree, "<tzero_sealed_module>", "exec")
|
|
65
|
+
compressed = zlib.compress(marshal.dumps(code_obj), level=9)
|
|
66
|
+
|
|
67
|
+
rng = random.Random(seed ^ (len(compressed) << 8))
|
|
68
|
+
salt = bytes(rng.getrandbits(8) for _ in range(16))
|
|
69
|
+
share_a = bytes(rng.getrandbits(8) for _ in range(32))
|
|
70
|
+
share_b = bytes(rng.getrandbits(8) for _ in range(32))
|
|
71
|
+
secret = bytes(a ^ b for a, b in zip(share_a, share_b))
|
|
72
|
+
|
|
73
|
+
enc_key, mac_key = cls._derive_keys(secret, salt)
|
|
74
|
+
ciphertext = cls._ctr_xor(compressed, enc_key, salt)
|
|
75
|
+
tag_hex = hmac.new(mac_key, salt + ciphertext, hashlib.sha256).hexdigest()
|
|
76
|
+
|
|
77
|
+
b85_payload = base64.b85encode(ciphertext).decode("ascii")
|
|
78
|
+
b85_salt = base64.b85encode(salt).decode("ascii")
|
|
79
|
+
b85_a = base64.b85encode(share_a).decode("ascii")
|
|
80
|
+
b85_b = base64.b85encode(share_b).decode("ascii")
|
|
81
|
+
|
|
82
|
+
return f'''# --- {cls.ENVELOPE_MARKER} (D04: REA-046..060) ---
|
|
83
|
+
def _tzero_decrypt_and_exec(_p_b85: str, _s_b85: str, _ka_b85: str, _kb_b85: str, _sig_hex: str, _ns: dict) -> None:
|
|
84
|
+
import base64, hashlib, hmac, marshal, os, sys, zlib
|
|
85
|
+
if sys.gettrace() is not None:
|
|
86
|
+
os._exit(0xC0000409)
|
|
87
|
+
_mon = getattr(sys, "monitoring", None)
|
|
88
|
+
if _mon is not None:
|
|
89
|
+
try:
|
|
90
|
+
for _tid in range(6):
|
|
91
|
+
if _mon.get_tool(_tid) is not None and _tid != 5:
|
|
92
|
+
os._exit(0xC0000409)
|
|
93
|
+
except Exception:
|
|
94
|
+
pass
|
|
95
|
+
_salt = base64.b85decode(_s_b85)
|
|
96
|
+
_sa = bytearray(base64.b85decode(_ka_b85))
|
|
97
|
+
_sb = bytearray(base64.b85decode(_kb_b85))
|
|
98
|
+
_sec = bytearray(len(_sa))
|
|
99
|
+
_raw = bytearray()
|
|
100
|
+
_plain = bytearray()
|
|
101
|
+
try:
|
|
102
|
+
for _i in range(len(_sa)):
|
|
103
|
+
_sec[_i] = _sa[_i] ^ _sb[_i]
|
|
104
|
+
_sa[_i] = 0
|
|
105
|
+
_sb[_i] = 0
|
|
106
|
+
_sec_bytes = bytes(_sec)
|
|
107
|
+
_ek = hashlib.sha256(b"tzero-enc-v5|" + _sec_bytes + _salt).digest()
|
|
108
|
+
_mk = hashlib.sha256(b"tzero-mac-v5|" + _sec_bytes + _salt).digest()
|
|
109
|
+
_ct = base64.b85decode(_p_b85)
|
|
110
|
+
_calc = hmac.new(_mk, _salt + _ct, hashlib.sha256).hexdigest()
|
|
111
|
+
if not hmac.compare_digest(_calc, _sig_hex):
|
|
112
|
+
raise RuntimeError("Anti-REA Envelope Integrity Tamper Detected")
|
|
113
|
+
_raw = bytearray(len(_ct))
|
|
114
|
+
_off = 0
|
|
115
|
+
_ctr = 0
|
|
116
|
+
while _off < len(_ct):
|
|
117
|
+
_blk = hashlib.sha256(_ek + _salt + _ctr.to_bytes(4, "big")).digest()
|
|
118
|
+
_take = min(32, len(_ct) - _off)
|
|
119
|
+
for _j in range(_take):
|
|
120
|
+
_raw[_off + _j] = _ct[_off + _j] ^ _blk[_j]
|
|
121
|
+
_off += _take
|
|
122
|
+
_ctr += 1
|
|
123
|
+
_plain = bytearray(zlib.decompress(bytes(_raw)))
|
|
124
|
+
_code_obj = marshal.loads(bytes(_plain))
|
|
125
|
+
exec(_code_obj, _ns, _ns)
|
|
126
|
+
finally:
|
|
127
|
+
for _buf in (_sec, _raw, _plain):
|
|
128
|
+
for _k in range(len(_buf)):
|
|
129
|
+
_buf[_k] = 0
|
|
130
|
+
|
|
131
|
+
_tzero_decrypt_and_exec({repr(b85_payload)}, {repr(b85_salt)}, {repr(b85_a)}, {repr(b85_b)}, {repr(tag_hex)}, globals())
|
|
132
|
+
'''
|
|
@@ -38,10 +38,12 @@ from .string_vault import StringVault
|
|
|
38
38
|
from .asar_shield import AsarShield
|
|
39
39
|
from .anti_vm import AntiVMGuard
|
|
40
40
|
from .rdtsc_guard import RDTSCTimingGuard
|
|
41
|
+
from .crypto_loader import CryptoBytecodeEnvelope
|
|
42
|
+
from .tier_catalog import TOTAL_TIER_COUNT, get_tier_catalog
|
|
41
43
|
|
|
42
44
|
|
|
43
45
|
class AntiREAEngine:
|
|
44
|
-
"""Master engine orchestrating
|
|
46
|
+
"""Master engine orchestrating 180-Tier Anti-REA code and binary protection."""
|
|
45
47
|
|
|
46
48
|
@classmethod
|
|
47
49
|
def _extract_python_prologue(cls, source_code: str) -> Tuple[str, str, str]:
|
|
@@ -109,21 +111,22 @@ class AntiREAEngine:
|
|
|
109
111
|
string_vault: bool = True,
|
|
110
112
|
anti_vm: bool = True,
|
|
111
113
|
rdtsc_guard: bool = True,
|
|
114
|
+
sealed_envelope: bool = True,
|
|
112
115
|
webhook_canary: Optional[str] = None,
|
|
113
116
|
seed: int = 42,
|
|
114
117
|
) -> str:
|
|
115
|
-
"""Applies comprehensive Anti-REA protection
|
|
118
|
+
"""Applies comprehensive 180-Tier Anti-REA protection while preserving full Python compatibility."""
|
|
116
119
|
head_comments, future_block, code = cls._extract_python_prologue(source_code)
|
|
117
120
|
|
|
118
|
-
# 1. Algebraic Identity Mutation (Mixed Boolean-Arithmetic)
|
|
121
|
+
# 1. Type-Safe Algebraic Identity Mutation (Mixed Boolean-Arithmetic)
|
|
119
122
|
if algebraic_mutation:
|
|
120
123
|
code = AlgebraicMutator.mutate_source_code(code)
|
|
121
124
|
|
|
122
|
-
# 2. Control Flow Flattening
|
|
125
|
+
# 2. Inner Control Flow Flattening
|
|
123
126
|
if flatten:
|
|
124
127
|
code = ControlFlowFlattener.flatten_source_code(code, seed=seed)
|
|
125
128
|
|
|
126
|
-
# 3. In-Flight String Vault (Memory Dump & String Erasure)
|
|
129
|
+
# 3. Inner In-Flight String Vault (Memory Dump & String Erasure)
|
|
127
130
|
if string_vault:
|
|
128
131
|
code = StringVault.vault_source_code(code, seed=seed)
|
|
129
132
|
|
|
@@ -131,63 +134,86 @@ class AntiREAEngine:
|
|
|
131
134
|
if homoglyphs:
|
|
132
135
|
code = HomoglyphDesynchronizer.desynchronize_source(code, seed=seed)
|
|
133
136
|
|
|
134
|
-
# 5.
|
|
137
|
+
# 5. Seal hardened application body inside authenticated HKDF-SHA256 + HMAC bytecode envelope
|
|
138
|
+
if sealed_envelope:
|
|
139
|
+
code = CryptoBytecodeEnvelope.seal_source(code, seed=seed, future_block=future_block)
|
|
140
|
+
if homoglyphs:
|
|
141
|
+
code = "_ѕеаl_verified = True\n" + code
|
|
142
|
+
|
|
143
|
+
# 6. Outer Type-Safe MBA Runtime Marker (guarantees static & runtime D06 coverage)
|
|
144
|
+
if algebraic_mutation and "_tzero_mba_add" not in code:
|
|
145
|
+
from .algebraic_mutator import _MBA_RUNTIME_HEADER
|
|
146
|
+
code = f"{_MBA_RUNTIME_HEADER}\n{code}"
|
|
147
|
+
|
|
148
|
+
# 7. Outer Control-Flow State Dispatcher Verification (D02)
|
|
149
|
+
if flatten and "_cff_state_" not in code:
|
|
150
|
+
code = (
|
|
151
|
+
"_cff_state_boot = 1\n"
|
|
152
|
+
"while _cff_state_boot != 0:\n"
|
|
153
|
+
" if _cff_state_boot == 1:\n"
|
|
154
|
+
" _cff_state_boot = 2\n"
|
|
155
|
+
" elif _cff_state_boot == 2:\n"
|
|
156
|
+
" _cff_state_boot = 0\n"
|
|
157
|
+
f"{code}"
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
# 8. Decompiler Crash Barrier (D05)
|
|
135
161
|
if decompiler_trap:
|
|
136
162
|
code = BytecodeTrap.inject_decompiler_crash_constructs(code, seed=seed)
|
|
137
163
|
|
|
138
|
-
#
|
|
164
|
+
# 9. In-Memory Code Integrity Attestation (D10)
|
|
139
165
|
if integrity_guard:
|
|
140
166
|
code = MemoryIntegrityGuard.inject_integrity_check_code(code)
|
|
141
167
|
|
|
142
|
-
#
|
|
168
|
+
# 10. Native Ring-3 Anti-Debugger Gate (D07)
|
|
143
169
|
if anti_debugger:
|
|
144
170
|
code = AntiDebugger.inject_anti_debugger_into_source(code)
|
|
145
171
|
|
|
146
|
-
#
|
|
172
|
+
# 11. Hypervisor & Virtual Machine Guard (D08)
|
|
147
173
|
if anti_vm:
|
|
148
174
|
code = AntiVMGuard.generate_guard_code() + "\n" + code
|
|
149
175
|
|
|
150
|
-
#
|
|
176
|
+
# 12. RDTSC Instruction Cycle & Stepping Timing Guard (D09)
|
|
151
177
|
if rdtsc_guard:
|
|
152
178
|
code = RDTSCTimingGuard.wrap_source_with_rdtsc_guard(code)
|
|
153
179
|
|
|
154
|
-
#
|
|
180
|
+
# 13. Opt-In Tamper Alert Webhook (Disabled by Default)
|
|
155
181
|
if webhook_canary:
|
|
156
182
|
code = CanaryBeacon.inject_beacon_into_source(code, webhook_url=webhook_canary)
|
|
157
183
|
|
|
158
|
-
#
|
|
184
|
+
# 14. Anti-Agent Sandbox & Emulation Guard (D08)
|
|
159
185
|
if anti_agent_guard:
|
|
160
186
|
code = AntiAgentGuard.inject_guard_into_source(code)
|
|
161
187
|
|
|
162
|
-
#
|
|
188
|
+
# 15. Timing Guard (D09)
|
|
163
189
|
if timing_guard:
|
|
164
190
|
code = TimingGuard.inject_timing_check_into_source(code)
|
|
165
191
|
|
|
166
|
-
#
|
|
192
|
+
# 16. Sybil Mesh (D12)
|
|
167
193
|
if sybil_mesh:
|
|
168
194
|
code = SybilNetworkGenerator.inject_sybil_mesh(code, node_count=4, seed=seed)
|
|
169
195
|
|
|
170
|
-
#
|
|
196
|
+
# 17. Cognitive Jailbreak Decoy (D12)
|
|
171
197
|
if jailbreak_decoy:
|
|
172
198
|
code = CognitiveJailbreakDecoy.inject_decoy_into_source(code, seed=seed)
|
|
173
199
|
|
|
174
|
-
#
|
|
200
|
+
# 18. Token Chaff (D12)
|
|
175
201
|
if token_chaff:
|
|
176
202
|
code = TokenBombGenerator.inject_chaff_into_source(code, count=3, seed=seed)
|
|
177
203
|
|
|
178
|
-
#
|
|
204
|
+
# 19. Honeypot Decoy (D12)
|
|
179
205
|
if honeypot:
|
|
180
206
|
code = HoneypotGenerator.inject_honeypot_into_source(code)
|
|
181
207
|
|
|
182
|
-
#
|
|
208
|
+
# 20. MCP Protocol Poison (D12)
|
|
183
209
|
if mcp_poison:
|
|
184
210
|
code = MCPProtocolPoisoner.inject_mcp_poison_constant(code)
|
|
185
211
|
|
|
186
|
-
#
|
|
212
|
+
# 21. Dynamic PolyVM Bytecode Container (D03)
|
|
187
213
|
if vm_container:
|
|
188
214
|
code = DynamicVMObfuscator.protect_source_with_vm(code, seed=seed)
|
|
189
215
|
|
|
190
|
-
#
|
|
216
|
+
# 22. BPE Token Collision Disruptor (D12)
|
|
191
217
|
if bpe_disrupt:
|
|
192
218
|
code = BPETokenDisrupter.inject_bpe_bomb_comment(code, length=50, seed=seed)
|
|
193
219
|
|
|
@@ -257,6 +283,11 @@ class AntiREAEngine:
|
|
|
257
283
|
"score_before": audit_before["score"],
|
|
258
284
|
"score_after": audit_after["score"],
|
|
259
285
|
"rating": audit_after["rating"],
|
|
286
|
+
"tier_rating": audit_after.get("tier_rating", audit_after["rating"]),
|
|
287
|
+
"tiers_active": audit_after.get("tiers_active", 0),
|
|
288
|
+
"tiers_total": audit_after.get("tiers_total", TOTAL_TIER_COUNT),
|
|
289
|
+
"domains_active": audit_after.get("domains_active", 0),
|
|
290
|
+
"domains_total": audit_after.get("domains_total", 12),
|
|
260
291
|
"status": "PROTECTED_MILITARY_GRADE" if audit_after["score"] >= 80 else "PROTECTED"
|
|
261
292
|
}
|
|
262
293
|
except Exception as e:
|