tzero-mcp 12.3.3 → 12.3.6

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 +4 -4
  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 +47 -215
  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 +322 -556
  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,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()
@@ -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
- '''