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.
- package/CONTRIBUTING.md +1 -1
- package/README.md +4 -0
- package/package.json +3 -4
- package/src/addmcp.py +2 -2
- package/src/app.py +1 -1
- package/src/main.py +4 -0
- package/src/tzero/__init__.py +1 -1
- package/src/tzero/desktop_updater.py +6 -0
- package/src/tzero/tzero_benchmark.py +1 -1
- package/src/tzero/tzero_budget.py +1 -1
- package/src/tzero/tzero_ci.py +1 -1
- 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 +1 -0
- package/src/tzero/tzero_explain.py +1 -1
- package/src/tzero/tzero_features.py +31 -74
- package/src/tzero/tzero_golden.py +2 -2
- package/src/tzero/tzero_growth.py +1 -1
- package/src/tzero/tzero_jarvis/orchestrator.py +1 -1
- package/src/tzero/tzero_jarvis/workspace_orchestrator.py +10 -21
- package/src/tzero/tzero_lsp.py +1 -1
- package/src/tzero/tzero_mcp.py +19 -120
- package/src/tzero/tzero_promo.py +1 -1
- package/src/tzero/tzero_security.py +3 -3
- package/src/tzero/tzero_sync.py +73 -148
- package/src/tzero/tzero_task_benchmark.py +2 -2
- package/src/tzero/tzero_traffic.py +1 -1
- package/src/tzero/tzero_tui.py +2 -13
- package/src/tzero/tzero_v3.py +56 -187
- package/src/tzero/tzero_welcome.py +1 -1
- package/src/tzero/anti_rea/__init__.py +0 -84
- package/src/tzero/anti_rea/algebraic_mutator.py +0 -107
- package/src/tzero/anti_rea/anti_agent_guard.py +0 -96
- package/src/tzero/anti_rea/anti_debugger.py +0 -272
- package/src/tzero/anti_rea/anti_vm.py +0 -160
- package/src/tzero/anti_rea/asar_shield.py +0 -122
- package/src/tzero/anti_rea/auditor.py +0 -208
- package/src/tzero/anti_rea/bpe_disrupter.py +0 -48
- package/src/tzero/anti_rea/bytecode_trap.py +0 -85
- package/src/tzero/anti_rea/canary_beacon.py +0 -167
- package/src/tzero/anti_rea/cli.py +0 -134
- package/src/tzero/anti_rea/confusables.py +0 -130
- package/src/tzero/anti_rea/crypto_loader.py +0 -132
- package/src/tzero/anti_rea/engine.py +0 -304
- package/src/tzero/anti_rea/extractor_shield.py +0 -180
- package/src/tzero/anti_rea/flattener.py +0 -136
- package/src/tzero/anti_rea/gui.py +0 -264
- package/src/tzero/anti_rea/honeypot.py +0 -58
- package/src/tzero/anti_rea/integrity_guard.py +0 -78
- package/src/tzero/anti_rea/jailbreak_decoy.py +0 -77
- package/src/tzero/anti_rea/mcp_poison.py +0 -41
- package/src/tzero/anti_rea/native_bridge.py +0 -169
- package/src/tzero/anti_rea/rdtsc_guard.py +0 -77
- package/src/tzero/anti_rea/string_vault.py +0 -97
- package/src/tzero/anti_rea/sybil_network.py +0 -53
- package/src/tzero/anti_rea/tier_catalog.py +0 -388
- package/src/tzero/anti_rea/timing_guard.py +0 -46
- package/src/tzero/anti_rea/token_bomb.py +0 -65
- package/src/tzero/anti_rea/traps.py +0 -76
- package/src/tzero/anti_rea/vm_obfuscator.py +0 -182
- package/src/tzero/tzero_armor.py +0 -187
|
@@ -1,130 +0,0 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""Tier 9: Homoglyphs & BPE Tokenizer Desynchronization.
|
|
3
|
-
|
|
4
|
-
Substitutes ASCII characters in internal, locally-scoped identifier names
|
|
5
|
-
with visually identical Cyrillic or Unicode homoglyphs (e.g. Cyrillic 'а' U+0430
|
|
6
|
-
for Latin 'a' U+0061) while strictly preserving Python builtins, decorators,
|
|
7
|
-
keywords, and imported symbols so runtime execution remains 100% intact.
|
|
8
|
-
|
|
9
|
-
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
10
|
-
"""
|
|
11
|
-
|
|
12
|
-
import ast
|
|
13
|
-
import builtins
|
|
14
|
-
import keyword
|
|
15
|
-
import random
|
|
16
|
-
from typing import Dict, Optional, Set
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
HOMOGLYPH_MAP: Dict[str, str] = {
|
|
20
|
-
"a": "а", # Cyrillic small letter a (U+0430)
|
|
21
|
-
"e": "е", # Cyrillic small letter ie (U+0435)
|
|
22
|
-
"o": "о", # Cyrillic small letter o (U+043E)
|
|
23
|
-
"p": "р", # Cyrillic small letter er (U+0440)
|
|
24
|
-
"c": "с", # Cyrillic small letter es (U+0441)
|
|
25
|
-
"y": "у", # Cyrillic small letter u (U+0443)
|
|
26
|
-
"x": "х", # Cyrillic small letter ha (U+0445)
|
|
27
|
-
"i": "і", # Cyrillic small letter byelorussian-ukrainian i (U+0456)
|
|
28
|
-
"j": "ј", # Cyrillic small letter je (U+0458)
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
_BUILTIN_PROTECTED: Set[str] = (
|
|
32
|
-
set(dir(builtins))
|
|
33
|
-
| set(keyword.kwlist)
|
|
34
|
-
| {
|
|
35
|
-
"self", "cls", "classmethod", "staticmethod", "property", "super",
|
|
36
|
-
"__init__", "__name__", "__main__", "__file__", "__doc__", "__package__",
|
|
37
|
-
"True", "False", "None",
|
|
38
|
-
}
|
|
39
|
-
)
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
def _collect_safe_targets(tree: ast.AST, protected: Set[str]) -> Set[str]:
|
|
43
|
-
"""Collect private/internal locally defined names safe to rename without breaking callers or imports."""
|
|
44
|
-
imported: Set[str] = set()
|
|
45
|
-
public_defs: Set[str] = set()
|
|
46
|
-
local_candidates: Set[str] = set()
|
|
47
|
-
|
|
48
|
-
for node in ast.walk(tree):
|
|
49
|
-
if isinstance(node, ast.Import):
|
|
50
|
-
for alias in node.names:
|
|
51
|
-
imported.add(alias.asname or alias.name.split(".")[0])
|
|
52
|
-
elif isinstance(node, ast.ImportFrom):
|
|
53
|
-
for alias in node.names:
|
|
54
|
-
imported.add(alias.asname or alias.name)
|
|
55
|
-
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
56
|
-
if node.name.startswith("_") and not node.name.startswith("__"):
|
|
57
|
-
local_candidates.add(node.name)
|
|
58
|
-
else:
|
|
59
|
-
public_defs.add(node.name)
|
|
60
|
-
# Only rename internal-looking local assignments (not kwargs/public params)
|
|
61
|
-
for arg in node.args.args + node.args.kwonlyargs:
|
|
62
|
-
protected.add(arg.arg)
|
|
63
|
-
elif isinstance(node, ast.ClassDef):
|
|
64
|
-
public_defs.add(node.name)
|
|
65
|
-
elif isinstance(node, ast.Global) or isinstance(node, ast.Nonlocal):
|
|
66
|
-
protected.update(node.names)
|
|
67
|
-
elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
|
|
68
|
-
if node.id.startswith("_") and not node.id.startswith("__"):
|
|
69
|
-
local_candidates.add(node.id)
|
|
70
|
-
|
|
71
|
-
blocked = protected | imported | public_defs
|
|
72
|
-
return {name for name in local_candidates if name not in blocked and len(name) >= 4}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
class HomoglyphDesynchronizer(ast.NodeTransformer):
|
|
76
|
-
"""AST transformer that substitutes internal identifier characters with homoglyphs."""
|
|
77
|
-
|
|
78
|
-
def __init__(self, protected_names: Optional[Set[str]] = None, seed: int = 42, target_names: Optional[Set[str]] = None):
|
|
79
|
-
super().__init__()
|
|
80
|
-
self.protected_names = set(_BUILTIN_PROTECTED)
|
|
81
|
-
if protected_names:
|
|
82
|
-
self.protected_names |= set(protected_names)
|
|
83
|
-
self.target_names = target_names
|
|
84
|
-
self.rng = random.Random(seed)
|
|
85
|
-
self.renamed_map: Dict[str, str] = {}
|
|
86
|
-
|
|
87
|
-
def _convert_name(self, name: str) -> str:
|
|
88
|
-
"""Converts an eligible internal name using homoglyph substitution."""
|
|
89
|
-
if name in self.protected_names or name.startswith("__") or len(name) < 4:
|
|
90
|
-
return name
|
|
91
|
-
if self.target_names is not None and name not in self.target_names:
|
|
92
|
-
return name
|
|
93
|
-
if name in self.renamed_map:
|
|
94
|
-
return self.renamed_map[name]
|
|
95
|
-
|
|
96
|
-
chars = list(name)
|
|
97
|
-
for i, ch in enumerate(chars):
|
|
98
|
-
if ch in HOMOGLYPH_MAP:
|
|
99
|
-
chars[i] = HOMOGLYPH_MAP[ch]
|
|
100
|
-
break
|
|
101
|
-
|
|
102
|
-
new_name = "".join(chars)
|
|
103
|
-
self.renamed_map[name] = new_name
|
|
104
|
-
return new_name
|
|
105
|
-
|
|
106
|
-
def visit_Name(self, node: ast.Name) -> ast.Name:
|
|
107
|
-
"""Renames eligible internal variable references."""
|
|
108
|
-
node.id = self._convert_name(node.id)
|
|
109
|
-
return node
|
|
110
|
-
|
|
111
|
-
def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:
|
|
112
|
-
"""Renames private/internal functions starting with '_'."""
|
|
113
|
-
if node.name.startswith("_") and not node.name.startswith("__"):
|
|
114
|
-
node.name = self._convert_name(node.name)
|
|
115
|
-
self.generic_visit(node)
|
|
116
|
-
return node
|
|
117
|
-
|
|
118
|
-
@classmethod
|
|
119
|
-
def desynchronize_source(cls, source_code: str, seed: int = 42) -> str:
|
|
120
|
-
"""Applies homoglyph desynchronization to internal identifiers safely."""
|
|
121
|
-
try:
|
|
122
|
-
tree = ast.parse(source_code)
|
|
123
|
-
protected = set(_BUILTIN_PROTECTED)
|
|
124
|
-
targets = _collect_safe_targets(tree, protected)
|
|
125
|
-
transformer = cls(protected_names=protected, seed=seed, target_names=targets)
|
|
126
|
-
transformed = transformer.visit(tree)
|
|
127
|
-
ast.fix_missing_locations(transformed)
|
|
128
|
-
return ast.unparse(transformed)
|
|
129
|
-
except Exception:
|
|
130
|
-
return source_code
|
|
@@ -1,132 +0,0 @@
|
|
|
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
|
-
'''
|
|
@@ -1,304 +0,0 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""Master Anti-REA Engine.
|
|
3
|
-
|
|
4
|
-
Unified coordinator applying the 24-Tier Anti-REA Armor Matrix across
|
|
5
|
-
source files, packages, compiled executables, and Electron archives.
|
|
6
|
-
|
|
7
|
-
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
8
|
-
Part of Siber Akademi T-Zero Security Suite.
|
|
9
|
-
License: MIT
|
|
10
|
-
"""
|
|
11
|
-
|
|
12
|
-
import ast
|
|
13
|
-
import os
|
|
14
|
-
import tempfile
|
|
15
|
-
from typing import Dict, Any, List, Optional, Tuple
|
|
16
|
-
|
|
17
|
-
from .traps import AdversarialTrapGenerator
|
|
18
|
-
from .extractor_shield import ExtractorShield
|
|
19
|
-
from .flattener import ControlFlowFlattener
|
|
20
|
-
from .token_bomb import TokenBombGenerator
|
|
21
|
-
from .confusables import HomoglyphDesynchronizer
|
|
22
|
-
from .honeypot import HoneypotGenerator
|
|
23
|
-
from .mcp_poison import MCPProtocolPoisoner
|
|
24
|
-
from .sybil_network import SybilNetworkGenerator
|
|
25
|
-
from .timing_guard import TimingGuard
|
|
26
|
-
from .auditor import AIResistanceAuditor
|
|
27
|
-
from .vm_obfuscator import DynamicVMObfuscator
|
|
28
|
-
from .bytecode_trap import BytecodeTrap
|
|
29
|
-
from .jailbreak_decoy import CognitiveJailbreakDecoy
|
|
30
|
-
from .anti_agent_guard import AntiAgentGuard
|
|
31
|
-
from .algebraic_mutator import AlgebraicMutator
|
|
32
|
-
from .integrity_guard import MemoryIntegrityGuard
|
|
33
|
-
from .bpe_disrupter import BPETokenDisrupter
|
|
34
|
-
from .native_bridge import NativeBridge
|
|
35
|
-
from .anti_debugger import AntiDebugger
|
|
36
|
-
from .canary_beacon import CanaryBeacon
|
|
37
|
-
from .string_vault import StringVault
|
|
38
|
-
from .asar_shield import AsarShield
|
|
39
|
-
from .anti_vm import AntiVMGuard
|
|
40
|
-
from .rdtsc_guard import RDTSCTimingGuard
|
|
41
|
-
from .crypto_loader import CryptoBytecodeEnvelope
|
|
42
|
-
from .tier_catalog import TOTAL_TIER_COUNT, get_tier_catalog
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
class AntiREAEngine:
|
|
46
|
-
"""Master engine orchestrating 180-Tier Anti-REA code and binary protection."""
|
|
47
|
-
|
|
48
|
-
@classmethod
|
|
49
|
-
def _extract_python_prologue(cls, source_code: str) -> Tuple[str, str, str]:
|
|
50
|
-
"""Preserve encoding/shebang header and mandatory `from __future__` imports at module top."""
|
|
51
|
-
lines = source_code.splitlines(keepends=True)
|
|
52
|
-
head_comments: List[str] = []
|
|
53
|
-
idx = 0
|
|
54
|
-
while idx < len(lines):
|
|
55
|
-
s = lines[idx].strip()
|
|
56
|
-
if idx == 0 and s.startswith("#!"):
|
|
57
|
-
head_comments.append(lines[idx])
|
|
58
|
-
idx += 1
|
|
59
|
-
elif s.startswith("#") and ("coding" in s or idx < 2):
|
|
60
|
-
head_comments.append(lines[idx])
|
|
61
|
-
idx += 1
|
|
62
|
-
elif not s:
|
|
63
|
-
head_comments.append(lines[idx])
|
|
64
|
-
idx += 1
|
|
65
|
-
else:
|
|
66
|
-
break
|
|
67
|
-
|
|
68
|
-
rest_code = "".join(lines[idx:])
|
|
69
|
-
future_lines: List[str] = []
|
|
70
|
-
body_code = rest_code
|
|
71
|
-
try:
|
|
72
|
-
tree = ast.parse(rest_code)
|
|
73
|
-
future_indices = set()
|
|
74
|
-
for node in tree.body:
|
|
75
|
-
if isinstance(node, ast.ImportFrom) and node.module == "__future__":
|
|
76
|
-
for ln in range(node.lineno, (node.end_lineno or node.lineno) + 1):
|
|
77
|
-
future_indices.add(ln)
|
|
78
|
-
if future_indices:
|
|
79
|
-
r_lines = rest_code.splitlines(keepends=True)
|
|
80
|
-
kept = []
|
|
81
|
-
for ln_no, ln_txt in enumerate(r_lines, 1):
|
|
82
|
-
if ln_no in future_indices:
|
|
83
|
-
future_lines.append(ln_txt if ln_txt.endswith("\n") else ln_txt + "\n")
|
|
84
|
-
else:
|
|
85
|
-
kept.append(ln_txt)
|
|
86
|
-
body_code = "".join(kept)
|
|
87
|
-
except Exception:
|
|
88
|
-
pass
|
|
89
|
-
return "".join(head_comments), "".join(future_lines), body_code
|
|
90
|
-
|
|
91
|
-
@classmethod
|
|
92
|
-
def protect_python_source(
|
|
93
|
-
cls,
|
|
94
|
-
source_code: str,
|
|
95
|
-
flatten: bool = True,
|
|
96
|
-
token_chaff: bool = True,
|
|
97
|
-
prompt_traps: bool = True,
|
|
98
|
-
homoglyphs: bool = True,
|
|
99
|
-
honeypot: bool = True,
|
|
100
|
-
mcp_poison: bool = True,
|
|
101
|
-
sybil_mesh: bool = True,
|
|
102
|
-
timing_guard: bool = True,
|
|
103
|
-
decompiler_trap: bool = True,
|
|
104
|
-
jailbreak_decoy: bool = True,
|
|
105
|
-
anti_agent_guard: bool = True,
|
|
106
|
-
vm_container: bool = True,
|
|
107
|
-
algebraic_mutation: bool = True,
|
|
108
|
-
integrity_guard: bool = True,
|
|
109
|
-
bpe_disrupt: bool = True,
|
|
110
|
-
anti_debugger: bool = True,
|
|
111
|
-
string_vault: bool = True,
|
|
112
|
-
anti_vm: bool = True,
|
|
113
|
-
rdtsc_guard: bool = True,
|
|
114
|
-
sealed_envelope: bool = True,
|
|
115
|
-
webhook_canary: Optional[str] = None,
|
|
116
|
-
seed: int = 42,
|
|
117
|
-
) -> str:
|
|
118
|
-
"""Applies comprehensive 180-Tier Anti-REA protection while preserving full Python compatibility."""
|
|
119
|
-
head_comments, future_block, code = cls._extract_python_prologue(source_code)
|
|
120
|
-
|
|
121
|
-
# 1. Type-Safe Algebraic Identity Mutation (Mixed Boolean-Arithmetic)
|
|
122
|
-
if algebraic_mutation:
|
|
123
|
-
code = AlgebraicMutator.mutate_source_code(code)
|
|
124
|
-
|
|
125
|
-
# 2. Inner Control Flow Flattening
|
|
126
|
-
if flatten:
|
|
127
|
-
code = ControlFlowFlattener.flatten_source_code(code, seed=seed)
|
|
128
|
-
|
|
129
|
-
# 3. Inner In-Flight String Vault (Memory Dump & String Erasure)
|
|
130
|
-
if string_vault:
|
|
131
|
-
code = StringVault.vault_source_code(code, seed=seed)
|
|
132
|
-
|
|
133
|
-
# 4. Homoglyph Tokenizer Desynchronization
|
|
134
|
-
if homoglyphs:
|
|
135
|
-
code = HomoglyphDesynchronizer.desynchronize_source(code, seed=seed)
|
|
136
|
-
|
|
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)
|
|
161
|
-
if decompiler_trap:
|
|
162
|
-
code = BytecodeTrap.inject_decompiler_crash_constructs(code, seed=seed)
|
|
163
|
-
|
|
164
|
-
# 9. In-Memory Code Integrity Attestation (D10)
|
|
165
|
-
if integrity_guard:
|
|
166
|
-
code = MemoryIntegrityGuard.inject_integrity_check_code(code)
|
|
167
|
-
|
|
168
|
-
# 10. Native Ring-3 Anti-Debugger Gate (D07)
|
|
169
|
-
if anti_debugger:
|
|
170
|
-
code = AntiDebugger.inject_anti_debugger_into_source(code)
|
|
171
|
-
|
|
172
|
-
# 11. Hypervisor & Virtual Machine Guard (D08)
|
|
173
|
-
if anti_vm:
|
|
174
|
-
code = AntiVMGuard.generate_guard_code() + "\n" + code
|
|
175
|
-
|
|
176
|
-
# 12. RDTSC Instruction Cycle & Stepping Timing Guard (D09)
|
|
177
|
-
if rdtsc_guard:
|
|
178
|
-
code = RDTSCTimingGuard.wrap_source_with_rdtsc_guard(code)
|
|
179
|
-
|
|
180
|
-
# 13. Opt-In Tamper Alert Webhook (Disabled by Default)
|
|
181
|
-
if webhook_canary:
|
|
182
|
-
code = CanaryBeacon.inject_beacon_into_source(code, webhook_url=webhook_canary)
|
|
183
|
-
|
|
184
|
-
# 14. Anti-Agent Sandbox & Emulation Guard (D08)
|
|
185
|
-
if anti_agent_guard:
|
|
186
|
-
code = AntiAgentGuard.inject_guard_into_source(code)
|
|
187
|
-
|
|
188
|
-
# 15. Timing Guard (D09)
|
|
189
|
-
if timing_guard:
|
|
190
|
-
code = TimingGuard.inject_timing_check_into_source(code)
|
|
191
|
-
|
|
192
|
-
# 16. Sybil Mesh (D12)
|
|
193
|
-
if sybil_mesh:
|
|
194
|
-
code = SybilNetworkGenerator.inject_sybil_mesh(code, node_count=4, seed=seed)
|
|
195
|
-
|
|
196
|
-
# 17. Cognitive Jailbreak Decoy (D12)
|
|
197
|
-
if jailbreak_decoy:
|
|
198
|
-
code = CognitiveJailbreakDecoy.inject_decoy_into_source(code, seed=seed)
|
|
199
|
-
|
|
200
|
-
# 18. Token Chaff (D12)
|
|
201
|
-
if token_chaff:
|
|
202
|
-
code = TokenBombGenerator.inject_chaff_into_source(code, count=3, seed=seed)
|
|
203
|
-
|
|
204
|
-
# 19. Honeypot Decoy (D12)
|
|
205
|
-
if honeypot:
|
|
206
|
-
code = HoneypotGenerator.inject_honeypot_into_source(code)
|
|
207
|
-
|
|
208
|
-
# 20. MCP Protocol Poison (D12)
|
|
209
|
-
if mcp_poison:
|
|
210
|
-
code = MCPProtocolPoisoner.inject_mcp_poison_constant(code)
|
|
211
|
-
|
|
212
|
-
# 21. Dynamic PolyVM Bytecode Container (D03)
|
|
213
|
-
if vm_container:
|
|
214
|
-
code = DynamicVMObfuscator.protect_source_with_vm(code, seed=seed)
|
|
215
|
-
|
|
216
|
-
# 22. BPE Token Collision Disruptor (D12)
|
|
217
|
-
if bpe_disrupt:
|
|
218
|
-
code = BPETokenDisrupter.inject_bpe_bomb_comment(code, length=50, seed=seed)
|
|
219
|
-
|
|
220
|
-
# Strip redundant coding header inserted mid-file by VM header before placing valid top prologue
|
|
221
|
-
if future_block:
|
|
222
|
-
code_lines = code.splitlines(keepends=True)
|
|
223
|
-
if code_lines and "coding" in code_lines[0]:
|
|
224
|
-
code = "".join(code_lines[1:])
|
|
225
|
-
|
|
226
|
-
# Module docstring MUST come before `from __future__ import ...`, which MUST come before code
|
|
227
|
-
trap_doc = ""
|
|
228
|
-
if prompt_traps:
|
|
229
|
-
trap_doc = f'"""\n{AdversarialTrapGenerator.get_trap_payload(0)}\n"""\n'
|
|
230
|
-
|
|
231
|
-
header = head_comments
|
|
232
|
-
if not header or "coding" not in header:
|
|
233
|
-
header = "# -*- coding: utf-8 -*-\n" + header
|
|
234
|
-
return f"{header}{trap_doc}{future_block}{code}"
|
|
235
|
-
|
|
236
|
-
@classmethod
|
|
237
|
-
def protect_file(
|
|
238
|
-
cls,
|
|
239
|
-
file_path: str,
|
|
240
|
-
output_path: Optional[str] = None,
|
|
241
|
-
**options: Any
|
|
242
|
-
) -> Dict[str, Any]:
|
|
243
|
-
"""Protects a Python source file, compiled executable, or Electron archive on disk."""
|
|
244
|
-
if not os.path.isfile(file_path):
|
|
245
|
-
return {"success": False, "error": f"File not found: {file_path}"}
|
|
246
|
-
|
|
247
|
-
out = output_path or file_path
|
|
248
|
-
|
|
249
|
-
# If it's an Electron .asar archive, apply AsarShield
|
|
250
|
-
if file_path.lower().endswith(".asar"):
|
|
251
|
-
return AsarShield.shield_asar_file(file_path, output_path=out)
|
|
252
|
-
|
|
253
|
-
# If it's a binary executable, apply ExtractorShield
|
|
254
|
-
if file_path.lower().endswith((".exe", ".bin", ".elf", ".so", ".pyd")):
|
|
255
|
-
return ExtractorShield.shield_file(file_path, output_path=out)
|
|
256
|
-
|
|
257
|
-
# Otherwise assume Python source code: transform, compile-verify in temp staging, then write atomically
|
|
258
|
-
staged_path = None
|
|
259
|
-
try:
|
|
260
|
-
with open(file_path, "r", encoding="utf-8", errors="strict") as f:
|
|
261
|
-
content = f.read()
|
|
262
|
-
|
|
263
|
-
protected = cls.protect_python_source(content, **options)
|
|
264
|
-
|
|
265
|
-
# Verify transformed Python compiles cleanly BEFORE replacing target file
|
|
266
|
-
compile(protected, out, "exec")
|
|
267
|
-
|
|
268
|
-
out_dir = os.path.dirname(os.path.abspath(out)) or "."
|
|
269
|
-
os.makedirs(out_dir, exist_ok=True)
|
|
270
|
-
with tempfile.NamedTemporaryFile("w", dir=out_dir, delete=False, encoding="utf-8", prefix=".tzero_armor_") as tf:
|
|
271
|
-
tf.write(protected)
|
|
272
|
-
staged_path = tf.name
|
|
273
|
-
os.replace(staged_path, out)
|
|
274
|
-
staged_path = None
|
|
275
|
-
|
|
276
|
-
audit_before = AIResistanceAuditor.audit_python_source(content)
|
|
277
|
-
audit_after = AIResistanceAuditor.audit_python_source(protected)
|
|
278
|
-
|
|
279
|
-
return {
|
|
280
|
-
"success": True,
|
|
281
|
-
"input_file": file_path,
|
|
282
|
-
"output_file": out,
|
|
283
|
-
"score_before": audit_before["score"],
|
|
284
|
-
"score_after": audit_after["score"],
|
|
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),
|
|
291
|
-
"status": "PROTECTED_MILITARY_GRADE" if audit_after["score"] >= 80 else "PROTECTED"
|
|
292
|
-
}
|
|
293
|
-
except Exception as e:
|
|
294
|
-
if staged_path and os.path.exists(staged_path):
|
|
295
|
-
try:
|
|
296
|
-
os.remove(staged_path)
|
|
297
|
-
except OSError:
|
|
298
|
-
pass
|
|
299
|
-
return {"success": False, "error": str(e)}
|
|
300
|
-
|
|
301
|
-
@classmethod
|
|
302
|
-
def audit_target(cls, path: str) -> Dict[str, Any]:
|
|
303
|
-
"""Runs the AI Resistance Auditor on a target file or directory."""
|
|
304
|
-
return AIResistanceAuditor.audit_file(path)
|