sitrtech 1.2.0__tar.gz → 1.2.3__tar.gz
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.
- {sitrtech-1.2.0 → sitrtech-1.2.3}/PKG-INFO +1 -1
- {sitrtech-1.2.0 → sitrtech-1.2.3}/pyproject.toml +1 -1
- {sitrtech-1.2.0 → sitrtech-1.2.3}/src/sitrtech/__init__.py +1 -1
- {sitrtech-1.2.0 → sitrtech-1.2.3}/src/sitrtech/cli.py +105 -13
- {sitrtech-1.2.0 → sitrtech-1.2.3}/src/sitrtech/engine.py +33 -4
- {sitrtech-1.2.0 → sitrtech-1.2.3}/src/sitrtech/local.py +171 -10
- sitrtech-1.2.3/src/sitrtech/php.py +277 -0
- {sitrtech-1.2.0 → sitrtech-1.2.3}/src/sitrtech.egg-info/PKG-INFO +1 -1
- {sitrtech-1.2.0 → sitrtech-1.2.3}/src/sitrtech.egg-info/SOURCES.txt +1 -0
- {sitrtech-1.2.0 → sitrtech-1.2.3}/README.md +0 -0
- {sitrtech-1.2.0 → sitrtech-1.2.3}/setup.cfg +0 -0
- {sitrtech-1.2.0 → sitrtech-1.2.3}/src/sitrtech/runtime.py +0 -0
- {sitrtech-1.2.0 → sitrtech-1.2.3}/src/sitrtech.egg-info/dependency_links.txt +0 -0
- {sitrtech-1.2.0 → sitrtech-1.2.3}/src/sitrtech.egg-info/entry_points.txt +0 -0
- {sitrtech-1.2.0 → sitrtech-1.2.3}/src/sitrtech.egg-info/requires.txt +0 -0
- {sitrtech-1.2.0 → sitrtech-1.2.3}/src/sitrtech.egg-info/top_level.txt +0 -0
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "sitrtech"
|
|
7
|
-
version = "1.2.
|
|
7
|
+
version = "1.2.3"
|
|
8
8
|
description = "SitrTech Python code encryption CLI — protect Odoo, Django, Flask, FastAPI and Tornado projects"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = { text = "Proprietary" }
|
|
@@ -44,7 +44,7 @@ from rich.table import Table
|
|
|
44
44
|
# Constants
|
|
45
45
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
46
46
|
|
|
47
|
-
__version__ = "1.
|
|
47
|
+
__version__ = "1.2.3"
|
|
48
48
|
API_BASE_DEFAULT = "https://sitrtech.com"
|
|
49
49
|
MANIFEST_SUFFIX = ".sitr_manifest.json"
|
|
50
50
|
|
|
@@ -52,14 +52,20 @@ console = Console()
|
|
|
52
52
|
err_console = Console(stderr=True)
|
|
53
53
|
|
|
54
54
|
FRAMEWORKS = {
|
|
55
|
-
"odoo":
|
|
56
|
-
"frappe":
|
|
57
|
-
"django":
|
|
58
|
-
"flask":
|
|
59
|
-
"fastapi":
|
|
60
|
-
"tornado":
|
|
55
|
+
"odoo": "__manifest__.py",
|
|
56
|
+
"frappe": "hooks.py",
|
|
57
|
+
"django": "manage.py",
|
|
58
|
+
"flask": "app.py / wsgi.py / application.py",
|
|
59
|
+
"fastapi": "main.py / asgi.py",
|
|
60
|
+
"tornado": "main.py / server.py",
|
|
61
|
+
"wordpress": "wp-config.php / style.css",
|
|
62
|
+
"laravel": "artisan / composer.json",
|
|
63
|
+
"php": "index.php / composer.json",
|
|
61
64
|
}
|
|
62
65
|
|
|
66
|
+
# PHP frameworks are protected by the PHP-side loader (not the Python engine).
|
|
67
|
+
PHP_FRAMEWORKS = {"wordpress", "laravel", "php"}
|
|
68
|
+
|
|
63
69
|
_STRUCTURAL = {
|
|
64
70
|
"__manifest__.py", "__openerp__.py", "__init__.py",
|
|
65
71
|
"manage.py", "app.py", "application.py", "wsgi.py",
|
|
@@ -227,8 +233,87 @@ def main(ctx: click.Context, secret: Optional[str], base: Optional[str]) -> None
|
|
|
227
233
|
# encrypt
|
|
228
234
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
229
235
|
|
|
236
|
+
def _php_binding(protection: dict, expiry, start, domain, network) -> dict:
|
|
237
|
+
"""Map the shared protection options to PHP-loader binding keys."""
|
|
238
|
+
import datetime
|
|
239
|
+
def _epoch(d):
|
|
240
|
+
if not d:
|
|
241
|
+
return None
|
|
242
|
+
try:
|
|
243
|
+
return int(datetime.datetime.fromisoformat(str(d)).timestamp())
|
|
244
|
+
except Exception:
|
|
245
|
+
return None
|
|
246
|
+
b: dict = {}
|
|
247
|
+
if _epoch(expiry):
|
|
248
|
+
b["expires"] = _epoch(expiry)
|
|
249
|
+
if _epoch(start):
|
|
250
|
+
b["start"] = _epoch(start)
|
|
251
|
+
if domain:
|
|
252
|
+
b["domains"] = list(domain)
|
|
253
|
+
if network:
|
|
254
|
+
b["ips"] = list(network)
|
|
255
|
+
return b
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _encrypt_php(ctx, source, fw, version, protection, output,
|
|
259
|
+
base, secret, expiry, start, domain, network) -> None:
|
|
260
|
+
"""Encrypt a PHP project directory with the PHP-side loader."""
|
|
261
|
+
try:
|
|
262
|
+
from . import local as _local
|
|
263
|
+
except Exception as e: # pragma: no cover
|
|
264
|
+
err_console.print(f"[red]Error:[/] {e}")
|
|
265
|
+
sys.exit(1)
|
|
266
|
+
|
|
267
|
+
src = Path(source)
|
|
268
|
+
if not src.is_dir():
|
|
269
|
+
err_console.print(
|
|
270
|
+
f"[red]Error:[/] For [bold]{fw}[/] the input must be a project "
|
|
271
|
+
f"DIRECTORY (got [bold]{src.name}[/bold]).")
|
|
272
|
+
sys.exit(1)
|
|
273
|
+
out_dir: Path = Path(output) if output else src.with_name(src.name + "_encrypted")
|
|
274
|
+
|
|
275
|
+
console.print()
|
|
276
|
+
console.print(Panel.fit(
|
|
277
|
+
f"[bold]SitrTech Encrypt[/] · [cyan]{fw}[/] [magenta]PHP[/]"
|
|
278
|
+
f"\n[dim]{src} → {out_dir}[/]",
|
|
279
|
+
border_style="bright_black",
|
|
280
|
+
))
|
|
281
|
+
console.print("[dim]PHP mode — source is encrypted on this machine; the "
|
|
282
|
+
"platform is contacted only to authorize + meter.[/]")
|
|
283
|
+
|
|
284
|
+
binding = _php_binding(protection, expiry, start, domain, network)
|
|
285
|
+
with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"),
|
|
286
|
+
BarColumn(bar_width=30), TimeElapsedColumn(),
|
|
287
|
+
console=console, transient=True) as prog:
|
|
288
|
+
task = prog.add_task("Authorizing…", total=None)
|
|
289
|
+
def _status(stage):
|
|
290
|
+
prog.update(task, description={
|
|
291
|
+
"authorize": "Authorizing…", "encrypt": "Encrypting locally…",
|
|
292
|
+
"commit": "Finalizing…", "offline": "Offline grant…"}.get(stage, stage))
|
|
293
|
+
try:
|
|
294
|
+
res = _local.encrypt_php_local(
|
|
295
|
+
str(src), str(out_dir), fw, base, secret,
|
|
296
|
+
protection=binding, version=version, on_status=_status,
|
|
297
|
+
)
|
|
298
|
+
except _local.LocalError as e:
|
|
299
|
+
err_console.print(f"[red]Error:[/] {e}")
|
|
300
|
+
sys.exit(1)
|
|
301
|
+
|
|
302
|
+
console.print(
|
|
303
|
+
f"\n[bold green]✓ Encrypted[/] [bold]{out_dir}[/] "
|
|
304
|
+
f"({res['files']} file(s), {res['lines']:,} lines)")
|
|
305
|
+
console.print(f"[dim]Runtime loader: {Path(res['loader']).name} "
|
|
306
|
+
"(ships inside the output — deploy the whole folder).[/]")
|
|
307
|
+
if res.get("charged") is not None:
|
|
308
|
+
console.print(f"[dim]Charged {res['charged']:,} tokens · "
|
|
309
|
+
f"{res.get('tokens_left', '?'):,} left[/]")
|
|
310
|
+
if res.get("protection"):
|
|
311
|
+
console.print("[dim]License binding embedded (enforced at runtime).[/]")
|
|
312
|
+
console.print()
|
|
313
|
+
|
|
314
|
+
|
|
230
315
|
@main.command()
|
|
231
|
-
@click.argument("file", type=click.Path(exists=True, dir_okay=
|
|
316
|
+
@click.argument("file", type=click.Path(exists=True, dir_okay=True, path_type=Path))
|
|
232
317
|
@click.option("--framework", "-f",
|
|
233
318
|
type=click.Choice(list(FRAMEWORKS.keys()), case_sensitive=False),
|
|
234
319
|
default="odoo", show_default=True,
|
|
@@ -303,11 +388,6 @@ def encrypt(
|
|
|
303
388
|
resolved_secret = _resolve_secret(ctx.obj, secret)
|
|
304
389
|
base = _resolve_base(ctx.obj)
|
|
305
390
|
fw = framework.lower()
|
|
306
|
-
output_path: Path = output or file.with_name(file.stem + "_encrypted.zip")
|
|
307
|
-
|
|
308
|
-
if not file.name.endswith(".zip"):
|
|
309
|
-
err_console.print(f"[red]Error:[/] FILE must be a .zip archive (got [bold]{file.name}[/bold])")
|
|
310
|
-
sys.exit(1)
|
|
311
391
|
|
|
312
392
|
# Collect binding / protection options shared by both modes.
|
|
313
393
|
protection = {
|
|
@@ -322,6 +402,18 @@ def encrypt(
|
|
|
322
402
|
"domain": list(domain),
|
|
323
403
|
}
|
|
324
404
|
|
|
405
|
+
# ── PHP frameworks: encrypt a project DIRECTORY with the PHP-side loader.
|
|
406
|
+
if fw in PHP_FRAMEWORKS:
|
|
407
|
+
_encrypt_php(ctx, file, fw, version, protection, output,
|
|
408
|
+
base, resolved_secret, expiry, start, domain, network)
|
|
409
|
+
return
|
|
410
|
+
|
|
411
|
+
output_path: Path = output or file.with_name(file.stem + "_encrypted.zip")
|
|
412
|
+
|
|
413
|
+
if not file.name.endswith(".zip"):
|
|
414
|
+
err_console.print(f"[red]Error:[/] FILE must be a .zip archive (got [bold]{file.name}[/bold])")
|
|
415
|
+
sys.exit(1)
|
|
416
|
+
|
|
325
417
|
console.print()
|
|
326
418
|
console.print(Panel.fit(
|
|
327
419
|
f"[bold]SitrTech Encrypt[/] · [cyan]{fw}[/]"
|
|
@@ -14,10 +14,13 @@ from __future__ import annotations
|
|
|
14
14
|
|
|
15
15
|
import os
|
|
16
16
|
import re
|
|
17
|
+
import io
|
|
18
|
+
import ast
|
|
17
19
|
import json
|
|
18
20
|
import base64
|
|
19
|
-
import secrets
|
|
20
21
|
import shutil
|
|
22
|
+
import secrets
|
|
23
|
+
import tokenize
|
|
21
24
|
import datetime
|
|
22
25
|
from typing import Optional, Callable, List, Dict, Any
|
|
23
26
|
|
|
@@ -32,7 +35,7 @@ from cryptography.hazmat.primitives.asymmetric.x25519 import (
|
|
|
32
35
|
)
|
|
33
36
|
|
|
34
37
|
# Injected at build time (build_engine.py replaces this placeholder with the real key).
|
|
35
|
-
EMBEDDED_GRANT_PUBKEY_B64 = os.environ.get("SITR_GRANT_PK_B64", "")
|
|
38
|
+
EMBEDDED_GRANT_PUBKEY_B64 = os.environ.get("SITR_GRANT_PK_B64", "") or "nLFEnli4G4ELB2NraUif5spkal2IIZBYl00avjLVzJ4"
|
|
36
39
|
|
|
37
40
|
FRAMEWORK_MARKERS: Dict[str, list] = {
|
|
38
41
|
"odoo": ["__manifest__.py", "__openerp__.py"],
|
|
@@ -121,6 +124,12 @@ def _to_ts(v) -> Optional[int]:
|
|
|
121
124
|
return int(dt.timestamp())
|
|
122
125
|
|
|
123
126
|
|
|
127
|
+
def _norm_mac(s: str) -> str:
|
|
128
|
+
"""Normalize a MAC to 12 lowercase hex chars, matching the loader's format."""
|
|
129
|
+
h = "".join(c for c in str(s).lower() if c in "0123456789abcdef")
|
|
130
|
+
return h if len(h) == 12 else str(s).strip().lower()
|
|
131
|
+
|
|
132
|
+
|
|
124
133
|
def build_license_meta(options: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
125
134
|
"""Turn CLI/API options into the compact license metadata the loader enforces."""
|
|
126
135
|
meta: Dict[str, Any] = {}
|
|
@@ -131,7 +140,7 @@ def build_license_meta(options: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
|
131
140
|
if options.get("network"):
|
|
132
141
|
meta["net_scopes"] = _split(options["network"])
|
|
133
142
|
if options.get("mac"):
|
|
134
|
-
meta["macs"] = [m
|
|
143
|
+
meta["macs"] = [_norm_mac(m) for m in _split(options["mac"])]
|
|
135
144
|
if options.get("machine_id"):
|
|
136
145
|
meta["machine_ids"] = [m.lower() for m in _split(options["machine_id"])]
|
|
137
146
|
if options.get("hostname"):
|
|
@@ -146,10 +155,30 @@ def build_license_meta(options: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
|
146
155
|
|
|
147
156
|
|
|
148
157
|
# ── file encryption (v6: file key wrapped under jobKEK) ─────────────────────
|
|
158
|
+
def _strip_comments(source: str) -> str:
|
|
159
|
+
"""Remove comments before encryption so the protected payload carries no
|
|
160
|
+
human-readable annotations — even in memory once decrypted at runtime.
|
|
161
|
+
|
|
162
|
+
Docstrings are preserved (some frameworks read them, e.g. FastAPI/OpenAPI).
|
|
163
|
+
The transform is verified to be semantics-preserving: the comment-free source
|
|
164
|
+
must parse to an identical AST, otherwise the original source is kept.
|
|
165
|
+
"""
|
|
166
|
+
try:
|
|
167
|
+
stripped = tokenize.untokenize(
|
|
168
|
+
tok for tok in tokenize.generate_tokens(io.StringIO(source).readline)
|
|
169
|
+
if tok.type != tokenize.COMMENT
|
|
170
|
+
)
|
|
171
|
+
if ast.dump(ast.parse(stripped)) == ast.dump(ast.parse(source)):
|
|
172
|
+
return stripped
|
|
173
|
+
except Exception:
|
|
174
|
+
pass
|
|
175
|
+
return source
|
|
176
|
+
|
|
177
|
+
|
|
149
178
|
def encrypt_file_v6(src_path: str, out_path: str, job_kek: bytes,
|
|
150
179
|
license_meta: Optional[Dict[str, Any]] = None) -> None:
|
|
151
180
|
with open(src_path, "r", encoding="utf-8") as f:
|
|
152
|
-
payload = f.read().encode("utf-8")
|
|
181
|
+
payload = _strip_comments(f.read()).encode("utf-8")
|
|
153
182
|
|
|
154
183
|
file_key = secrets.token_bytes(32)
|
|
155
184
|
file_nonce = secrets.token_bytes(12)
|
|
@@ -30,8 +30,11 @@ from typing import Optional, Dict, Any, List
|
|
|
30
30
|
import requests
|
|
31
31
|
|
|
32
32
|
from . import engine
|
|
33
|
+
from . import php as phpmod
|
|
33
34
|
from .runtime import native_injector
|
|
34
35
|
|
|
36
|
+
PHP_FRAMEWORKS = {"wordpress", "laravel", "php"}
|
|
37
|
+
|
|
35
38
|
|
|
36
39
|
# ── secure transport: HMAC-signed requests (integrity + anti-replay) ─────────
|
|
37
40
|
def _sig_headers(secret: str, method: str, path: str, body_str: str) -> Dict[str, str]:
|
|
@@ -193,34 +196,98 @@ def _bundled_has_loaders() -> Optional[str]:
|
|
|
193
196
|
return None
|
|
194
197
|
|
|
195
198
|
|
|
196
|
-
|
|
197
|
-
|
|
199
|
+
_LOADER_CACHE = os.path.join(os.path.expanduser("~"), ".cache", "sitrtech", "loaders")
|
|
200
|
+
_VERSION_FILE = ".loader_version"
|
|
198
201
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
+
|
|
203
|
+
def _cached_loader_version(cache: str) -> Optional[int]:
|
|
204
|
+
try:
|
|
205
|
+
with open(os.path.join(cache, _VERSION_FILE)) as f:
|
|
206
|
+
return int(f.read().strip())
|
|
207
|
+
except Exception:
|
|
208
|
+
return None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _download_loaders(base_url: str, secret: str, cache: str) -> int:
|
|
212
|
+
"""Fetch the loader set + its version; returns the downloaded version."""
|
|
202
213
|
import glob
|
|
203
|
-
cache = os.path.join(os.path.expanduser("~"), ".cache", "sitrtech", "loaders")
|
|
204
|
-
os.makedirs(cache, exist_ok=True)
|
|
205
|
-
if glob.glob(os.path.join(cache, "sitry-*.*")):
|
|
206
|
-
return cache
|
|
207
214
|
r = _get_signed(base_url, "/api/loaders", secret)
|
|
208
215
|
if not r.ok:
|
|
209
216
|
raise LocalError(f"Cannot fetch runtime loaders ({r.status_code}).")
|
|
210
|
-
|
|
217
|
+
body = r.json()
|
|
218
|
+
files = body.get("files", [])
|
|
219
|
+
version = int(body.get("version", 0) or 0)
|
|
211
220
|
if not files:
|
|
212
221
|
raise LocalError("Platform has no runtime loaders available.")
|
|
222
|
+
# clear stale loaders so a rotated set fully replaces the old one
|
|
223
|
+
for old in glob.glob(os.path.join(cache, "sitry-*.*")):
|
|
224
|
+
try:
|
|
225
|
+
os.remove(old)
|
|
226
|
+
except Exception:
|
|
227
|
+
pass
|
|
213
228
|
for name in files:
|
|
214
229
|
fr = _get_signed(base_url, f"/api/loaders/{name}", secret, 120)
|
|
215
230
|
if fr.ok:
|
|
216
231
|
with open(os.path.join(cache, name), "wb") as f:
|
|
217
232
|
f.write(fr.content)
|
|
233
|
+
with open(os.path.join(cache, _VERSION_FILE), "w") as f:
|
|
234
|
+
f.write(str(version))
|
|
235
|
+
return version
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _ensure_loaders(base_url: str, secret: str) -> str:
|
|
239
|
+
"""Download / auto-update runtime loaders into the local cache.
|
|
240
|
+
|
|
241
|
+
The master-secret loaders are kept out of the public wheel — served only to
|
|
242
|
+
authenticated customers. Each run checks the platform's loader *version*: if
|
|
243
|
+
it changed, the newest loaders are fetched automatically so a customer never
|
|
244
|
+
encrypts with a stale/unsupported loader. `min_supported` forces an update
|
|
245
|
+
(and lets the platform revoke a compromised loader).
|
|
246
|
+
"""
|
|
247
|
+
import glob
|
|
248
|
+
cache = _LOADER_CACHE
|
|
249
|
+
os.makedirs(cache, exist_ok=True)
|
|
250
|
+
have = bool(glob.glob(os.path.join(cache, "sitry-*.*")))
|
|
251
|
+
cached_ver = _cached_loader_version(cache)
|
|
252
|
+
|
|
253
|
+
# Lightweight version probe (best-effort; never blocks when offline).
|
|
254
|
+
server_ver = None
|
|
255
|
+
min_supported = None
|
|
256
|
+
try:
|
|
257
|
+
vr = _get_signed(base_url, "/api/loaders/version", secret, 15)
|
|
258
|
+
if vr.ok:
|
|
259
|
+
vj = vr.json()
|
|
260
|
+
server_ver = int(vj.get("version", 0) or 0)
|
|
261
|
+
min_supported = int(vj.get("min_supported", 0) or 0)
|
|
262
|
+
except _NET_ERRORS:
|
|
263
|
+
pass
|
|
264
|
+
|
|
265
|
+
if not have:
|
|
266
|
+
_download_loaders(base_url, secret, cache)
|
|
267
|
+
elif server_ver is not None and server_ver != cached_ver:
|
|
268
|
+
# loaders rotated on the platform → pull the newest set
|
|
269
|
+
try:
|
|
270
|
+
_download_loaders(base_url, secret, cache)
|
|
271
|
+
except LocalError:
|
|
272
|
+
if min_supported and (cached_ver or 0) < min_supported:
|
|
273
|
+
raise LocalError(
|
|
274
|
+
"Your runtime loaders are outdated and no longer supported, "
|
|
275
|
+
"and the newest set could not be downloaded. Reconnect and retry.")
|
|
276
|
+
|
|
277
|
+
# Hard floor: refuse to run on a loader below the platform's min_supported.
|
|
278
|
+
if min_supported:
|
|
279
|
+
cur = _cached_loader_version(cache) or 0
|
|
280
|
+
if cur and cur < min_supported:
|
|
281
|
+
raise LocalError(
|
|
282
|
+
f"Loader version {cur} is below the minimum supported "
|
|
283
|
+
f"({min_supported}). Update failed — reconnect to the platform.")
|
|
218
284
|
return cache
|
|
219
285
|
|
|
220
286
|
|
|
221
287
|
def _resolve_loaders(base_url: str, secret: str, explicit: Optional[str]) -> str:
|
|
222
288
|
if explicit:
|
|
223
289
|
return explicit
|
|
290
|
+
# A bundled loader dir (dev) skips the fetch; otherwise ensure/auto-update.
|
|
224
291
|
return _bundled_has_loaders() or _ensure_loaders(base_url, secret)
|
|
225
292
|
|
|
226
293
|
|
|
@@ -342,6 +409,100 @@ def encrypt_local(
|
|
|
342
409
|
}
|
|
343
410
|
|
|
344
411
|
|
|
412
|
+
def encrypt_php_local(
|
|
413
|
+
source_dir: str,
|
|
414
|
+
output_dir: str,
|
|
415
|
+
framework: str,
|
|
416
|
+
base_url: str,
|
|
417
|
+
secret: str,
|
|
418
|
+
protection: Optional[Dict[str, Any]] = None,
|
|
419
|
+
version: str = "",
|
|
420
|
+
on_status=None,
|
|
421
|
+
) -> Dict[str, Any]:
|
|
422
|
+
"""Encrypt a PHP project (WordPress/Laravel/PHP) locally.
|
|
423
|
+
|
|
424
|
+
Same billing contract as `encrypt_local`: the platform is contacted only to
|
|
425
|
+
authorize (reserve tokens) and commit (charge real lines). Encryption and
|
|
426
|
+
the runtime PHP loader are produced entirely on this machine.
|
|
427
|
+
"""
|
|
428
|
+
framework = (framework or "php").lower()
|
|
429
|
+
protection = protection or {}
|
|
430
|
+
say = on_status or (lambda *_: None)
|
|
431
|
+
|
|
432
|
+
if not os.path.isdir(source_dir):
|
|
433
|
+
raise LocalError(f"Source directory not found: {source_dir}")
|
|
434
|
+
|
|
435
|
+
files = phpmod.discover_php_files(source_dir)
|
|
436
|
+
if not files:
|
|
437
|
+
raise LocalError("No .php files found to encrypt.")
|
|
438
|
+
est_lines = phpmod.count_php_lines(files)
|
|
439
|
+
|
|
440
|
+
say("authorize")
|
|
441
|
+
client_priv, client_pub = engine.new_client_keypair()
|
|
442
|
+
offline = False
|
|
443
|
+
job_id = None
|
|
444
|
+
try:
|
|
445
|
+
r = _post_signed(
|
|
446
|
+
base_url, "/api/authorize", secret,
|
|
447
|
+
{"framework": framework, "version": version, "est_lines": est_lines,
|
|
448
|
+
"client_pub": client_pub},
|
|
449
|
+
)
|
|
450
|
+
if r.status_code == 401:
|
|
451
|
+
raise LocalError("Invalid API secret.")
|
|
452
|
+
if r.status_code == 402:
|
|
453
|
+
d = r.json()
|
|
454
|
+
raise LocalError(f"Insufficient tokens: need {d.get('needed')}, have {d.get('available')}.")
|
|
455
|
+
if not r.ok:
|
|
456
|
+
raise LocalError(f"Authorize failed ({r.status_code}): {r.text[:200]}")
|
|
457
|
+
job_id = r.json().get("job_id")
|
|
458
|
+
except _NET_ERRORS:
|
|
459
|
+
cache = _offline_load()
|
|
460
|
+
if not cache:
|
|
461
|
+
raise LocalError(
|
|
462
|
+
"Platform unreachable and no offline grant cached. "
|
|
463
|
+
"While online run: sitr offline fetch")
|
|
464
|
+
say("offline")
|
|
465
|
+
_offline_acquire(cache, est_lines) # meter locally against the grant
|
|
466
|
+
offline = True
|
|
467
|
+
|
|
468
|
+
try:
|
|
469
|
+
say("encrypt")
|
|
470
|
+
summary = phpmod.encrypt_php_project(source_dir, output_dir, protection, say)
|
|
471
|
+
except Exception as e:
|
|
472
|
+
if not offline and job_id:
|
|
473
|
+
try:
|
|
474
|
+
_post_signed(base_url, "/api/cancel", secret, {"job_id": job_id}, 15)
|
|
475
|
+
except Exception:
|
|
476
|
+
pass
|
|
477
|
+
raise LocalError(f"PHP encryption failed: {e}")
|
|
478
|
+
|
|
479
|
+
charged = None
|
|
480
|
+
tokens_left = None
|
|
481
|
+
if not offline and job_id:
|
|
482
|
+
say("commit")
|
|
483
|
+
c = _post_signed(
|
|
484
|
+
base_url, "/api/commit", secret,
|
|
485
|
+
{"job_id": job_id, "actual_lines": summary["lines"],
|
|
486
|
+
"module_name": os.path.basename(os.path.abspath(source_dir)),
|
|
487
|
+
"framework": framework, "version": version, "modules": summary["files"]},
|
|
488
|
+
)
|
|
489
|
+
if c.ok:
|
|
490
|
+
cj = c.json()
|
|
491
|
+
charged = cj.get("charged")
|
|
492
|
+
tokens_left = cj.get("tokens")
|
|
493
|
+
|
|
494
|
+
return {
|
|
495
|
+
"output": output_dir,
|
|
496
|
+
"offline": offline,
|
|
497
|
+
"lines": summary["lines"],
|
|
498
|
+
"files": summary["files"],
|
|
499
|
+
"loader": summary["loader"],
|
|
500
|
+
"charged": charged,
|
|
501
|
+
"tokens_left": tokens_left,
|
|
502
|
+
"protection": bool(phpmod.build_php_license(protection)),
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
|
|
345
506
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
346
507
|
# Batch / directory mode — for CI/CD (many modules, incremental, parallel)
|
|
347
508
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"""SitrTech PHP encoder — protect WordPress / Laravel / generic PHP projects.
|
|
2
|
+
|
|
3
|
+
The platform's primary engine protects Python with a compiled native loader
|
|
4
|
+
(``sitry-*.so``) that holds a whitebox secret. PHP runs a different runtime, so
|
|
5
|
+
PHP code is protected by a *PHP-side loader* instead:
|
|
6
|
+
|
|
7
|
+
• every ``.php`` file's source is encrypted with AES-256-GCM (a fresh IV per
|
|
8
|
+
file) under a random 256-bit project key;
|
|
9
|
+
• the original file is replaced by a tiny stub that hands its encrypted blob
|
|
10
|
+
to ``\\SitrTech\\SitrLoader``;
|
|
11
|
+
• ``sitrtech-loader.php`` (dropped at the project root) decrypts the blob,
|
|
12
|
+
enforces the license (expiry / domain / IP binding) and executes it.
|
|
13
|
+
|
|
14
|
+
Billing is identical to the Python path: the platform is contacted only to
|
|
15
|
+
``authorize`` (reserve tokens) and ``commit`` (charge the real line count).
|
|
16
|
+
|
|
17
|
+
Protection tiers
|
|
18
|
+
----------------
|
|
19
|
+
The bundled ``sitrtech-loader.php`` is a **pure-PHP** loader: it needs the
|
|
20
|
+
decryption key at runtime, so the key lives (obfuscated) inside it. That is
|
|
21
|
+
obfuscation-grade protection — equivalent to non-extension PHP encoders — and
|
|
22
|
+
it is honestly documented as such. A hardened **native PHP (Zend) extension**
|
|
23
|
+
(``sitrtech.so``), built like the Python loader matrix, is the production-grade
|
|
24
|
+
tier and slots in without re-encrypting: the blob format is identical.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import os
|
|
30
|
+
import base64
|
|
31
|
+
import json
|
|
32
|
+
import secrets
|
|
33
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
34
|
+
|
|
35
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
36
|
+
|
|
37
|
+
# ── framework detection ──────────────────────────────────────────────────────
|
|
38
|
+
# Marker files that identify a PHP project kind. `php` is the generic fallback.
|
|
39
|
+
PHP_MARKERS: Dict[str, list] = {
|
|
40
|
+
"wordpress": ["wp-config.php", "wp-load.php", "wp-settings.php", "style.css"],
|
|
41
|
+
"laravel": ["artisan"],
|
|
42
|
+
"php": ["composer.json", "index.php"],
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
# Directories never encrypted (dependencies, build output, runtime caches).
|
|
46
|
+
PHP_SKIP_DIRS = {
|
|
47
|
+
"vendor", "node_modules", ".git", ".github", "storage", "bootstrap",
|
|
48
|
+
"cache", "tests", "test", "dist", "build", ".idea", ".vscode",
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
# Files never encrypted — bootstrap/config PHP that frameworks read directly.
|
|
52
|
+
PHP_SKIP_FILES = {
|
|
53
|
+
"wp-config.php", "wp-load.php", "wp-settings.php", "wp-blog-header.php",
|
|
54
|
+
"index.php", "artisan", "sitrtech-loader.php",
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
LOADER_NAME = "sitrtech-loader.php"
|
|
58
|
+
MAGIC = "SITRPHP1"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class PhpError(RuntimeError):
|
|
62
|
+
pass
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# ── discovery / metering ─────────────────────────────────────────────────────
|
|
66
|
+
def discover_php_files(root: str) -> List[str]:
|
|
67
|
+
"""Every encryptable ``.php`` file under *root* (skip deps/config/loader)."""
|
|
68
|
+
out: List[str] = []
|
|
69
|
+
for r, dirs, files in os.walk(root):
|
|
70
|
+
dirs[:] = [d for d in dirs if d.lower() not in PHP_SKIP_DIRS]
|
|
71
|
+
for fn in files:
|
|
72
|
+
if not fn.endswith(".php"):
|
|
73
|
+
continue
|
|
74
|
+
if fn in PHP_SKIP_FILES:
|
|
75
|
+
continue
|
|
76
|
+
out.append(os.path.join(r, fn))
|
|
77
|
+
return out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def count_php_lines(files: List[str]) -> int:
|
|
81
|
+
total = 0
|
|
82
|
+
for fp in files:
|
|
83
|
+
try:
|
|
84
|
+
with open(fp, "r", encoding="utf-8", errors="ignore") as f:
|
|
85
|
+
total += sum(1 for _ in f)
|
|
86
|
+
except Exception:
|
|
87
|
+
pass
|
|
88
|
+
return max(1, total)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def detect_php_framework(root: str) -> Optional[str]:
|
|
92
|
+
"""Return 'wordpress' | 'laravel' | 'php' if *root* looks like a PHP app."""
|
|
93
|
+
names = set()
|
|
94
|
+
for r, _d, files in os.walk(root):
|
|
95
|
+
names.update(files)
|
|
96
|
+
# only need the top couple of levels for markers
|
|
97
|
+
if r.count(os.sep) - root.count(os.sep) > 2:
|
|
98
|
+
break
|
|
99
|
+
for kind in ("wordpress", "laravel"):
|
|
100
|
+
if any(m in names for m in PHP_MARKERS[kind]):
|
|
101
|
+
return kind
|
|
102
|
+
if any(m in names for m in PHP_MARKERS["php"]):
|
|
103
|
+
return "php"
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# ── crypto ───────────────────────────────────────────────────────────────────
|
|
108
|
+
def _encrypt_source(src: bytes, key: bytes) -> str:
|
|
109
|
+
"""AES-256-GCM one file → base64(MAGIC-less payload: iv || ct || tag)."""
|
|
110
|
+
iv = secrets.token_bytes(12)
|
|
111
|
+
ct = AESGCM(key).encrypt(iv, src, None) # ct = ciphertext || 16-byte tag
|
|
112
|
+
return base64.b64encode(iv + ct).decode("ascii")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _obfuscate_key(key: bytes) -> Tuple[str, str]:
|
|
116
|
+
"""Split the key into two XOR-masked halves for the loader (obfuscation)."""
|
|
117
|
+
pad = secrets.token_bytes(len(key))
|
|
118
|
+
masked = bytes(a ^ b for a, b in zip(key, pad))
|
|
119
|
+
return base64.b64encode(masked).decode(), base64.b64encode(pad).decode()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _stub(rel_blob: str) -> str:
|
|
123
|
+
"""The tiny PHP file that replaces an encrypted source file."""
|
|
124
|
+
return (
|
|
125
|
+
"<?php\n"
|
|
126
|
+
"/* Protected by SitrTech — https://sitrtech.com */\n"
|
|
127
|
+
"if(!class_exists('SitrTech\\\\SitrLoader')){$d=__DIR__;"
|
|
128
|
+
"while($d!==dirname($d)){if(is_file($d.'/" + LOADER_NAME + "')){"
|
|
129
|
+
"require_once $d.'/" + LOADER_NAME + "';break;}$d=dirname($d);}}\n"
|
|
130
|
+
"\\SitrTech\\SitrLoader::exec(__FILE__,'" + rel_blob + "');\n"
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# ── license meta ─────────────────────────────────────────────────────────────
|
|
135
|
+
def build_php_license(binding: Optional[Dict[str, Any]]) -> Dict[str, Any]:
|
|
136
|
+
b = binding or {}
|
|
137
|
+
meta: Dict[str, Any] = {}
|
|
138
|
+
if b.get("expires"):
|
|
139
|
+
meta["exp"] = int(b["expires"])
|
|
140
|
+
if b.get("start"):
|
|
141
|
+
meta["nbf"] = int(b["start"])
|
|
142
|
+
for k_in, k_out in (
|
|
143
|
+
("domains", "domains"), ("ips", "ips"), ("hostnames", "hostnames"),
|
|
144
|
+
):
|
|
145
|
+
v = b.get(k_in)
|
|
146
|
+
if v:
|
|
147
|
+
meta[k_out] = list(v)
|
|
148
|
+
return meta
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
# ── PHP loader template ──────────────────────────────────────────────────────
|
|
152
|
+
def render_loader(key: bytes, meta: Dict[str, Any]) -> str:
|
|
153
|
+
masked_b64, pad_b64 = _obfuscate_key(key)
|
|
154
|
+
meta_json = json.dumps(meta, separators=(",", ":"))
|
|
155
|
+
# The loader is intentionally compact. It reconstitutes the key from two
|
|
156
|
+
# XOR halves, enforces the license, then decrypts + executes each blob.
|
|
157
|
+
return f"""<?php
|
|
158
|
+
/* SitrTech PHP loader — protected runtime. https://sitrtech.com
|
|
159
|
+
* Pure-PHP tier: obfuscation-grade. Replace with the native sitrtech.so
|
|
160
|
+
* Zend extension for hardened protection (same blob format). */
|
|
161
|
+
namespace SitrTech;
|
|
162
|
+
|
|
163
|
+
final class SitrLoader {{
|
|
164
|
+
const MAGIC = '{MAGIC}';
|
|
165
|
+
private static $key = null;
|
|
166
|
+
|
|
167
|
+
private static function key() {{
|
|
168
|
+
if (self::$key !== null) return self::$key;
|
|
169
|
+
$m = base64_decode('{masked_b64}');
|
|
170
|
+
$p = base64_decode('{pad_b64}');
|
|
171
|
+
$k = '';
|
|
172
|
+
for ($i = 0; $i < strlen($m); $i++) $k .= chr(ord($m[$i]) ^ ord($p[$i]));
|
|
173
|
+
return self::$key = $k;
|
|
174
|
+
}}
|
|
175
|
+
|
|
176
|
+
private static function deny($why) {{
|
|
177
|
+
http_response_code(403);
|
|
178
|
+
die('SitrTech: license check failed (' . $why . ')');
|
|
179
|
+
}}
|
|
180
|
+
|
|
181
|
+
private static function checkLicense() {{
|
|
182
|
+
$meta = json_decode('{meta_json}', true);
|
|
183
|
+
if (!$meta) return;
|
|
184
|
+
$now = time();
|
|
185
|
+
if (isset($meta['nbf']) && $now < $meta['nbf']) self::deny('not-yet-valid');
|
|
186
|
+
if (isset($meta['exp']) && $now > $meta['exp']) self::deny('expired');
|
|
187
|
+
if (!empty($meta['domains'])) {{
|
|
188
|
+
$host = strtolower($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '');
|
|
189
|
+
$host = preg_replace('/:\\d+$/', '', $host);
|
|
190
|
+
$ok = false;
|
|
191
|
+
foreach ($meta['domains'] as $d) {{
|
|
192
|
+
$d = strtolower(trim($d));
|
|
193
|
+
if ($host === $d || ($d[0] === '.' && substr($host, -strlen($d)) === $d)
|
|
194
|
+
|| substr($host, -strlen('.' . $d)) === '.' . $d || $host === ltrim($d, '.')) {{
|
|
195
|
+
$ok = true; break;
|
|
196
|
+
}}
|
|
197
|
+
}}
|
|
198
|
+
if (!$ok) self::deny('domain');
|
|
199
|
+
}}
|
|
200
|
+
if (!empty($meta['ips'])) {{
|
|
201
|
+
$ip = $_SERVER['SERVER_ADDR'] ?? '';
|
|
202
|
+
if (!in_array($ip, $meta['ips'], true)) self::deny('ip');
|
|
203
|
+
}}
|
|
204
|
+
}}
|
|
205
|
+
|
|
206
|
+
public static function exec($file, $blob) {{
|
|
207
|
+
self::checkLicense();
|
|
208
|
+
$raw = base64_decode($blob, true);
|
|
209
|
+
if ($raw === false || strlen($raw) < 28) self::deny('corrupt');
|
|
210
|
+
$iv = substr($raw, 0, 12);
|
|
211
|
+
$rest = substr($raw, 12);
|
|
212
|
+
$tag = substr($rest, -16);
|
|
213
|
+
$ct = substr($rest, 0, -16);
|
|
214
|
+
$src = openssl_decrypt($ct, 'aes-256-gcm', self::key(), OPENSSL_RAW_DATA, $iv, $tag);
|
|
215
|
+
if ($src === false) self::deny('decrypt');
|
|
216
|
+
// Prepend a close-tag so eval() runs a complete PHP file (with inline HTML).
|
|
217
|
+
eval('?>' . $src);
|
|
218
|
+
}}
|
|
219
|
+
}}
|
|
220
|
+
"""
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
# ── project encryption ───────────────────────────────────────────────────────
|
|
224
|
+
def encrypt_php_project(
|
|
225
|
+
source_dir: str,
|
|
226
|
+
out_dir: str,
|
|
227
|
+
binding: Optional[Dict[str, Any]] = None,
|
|
228
|
+
say=lambda *_a: None,
|
|
229
|
+
) -> Dict[str, Any]:
|
|
230
|
+
"""Encrypt every ``.php`` file under *source_dir* into *out_dir*.
|
|
231
|
+
|
|
232
|
+
Returns a summary dict: {files, lines, loader}. Caller handles billing
|
|
233
|
+
(authorize/commit) around this call so metering matches the Python path.
|
|
234
|
+
"""
|
|
235
|
+
if not os.path.isdir(source_dir):
|
|
236
|
+
raise PhpError(f"source not found: {source_dir}")
|
|
237
|
+
|
|
238
|
+
files = discover_php_files(source_dir)
|
|
239
|
+
if not files:
|
|
240
|
+
raise PhpError("no .php files to encrypt")
|
|
241
|
+
|
|
242
|
+
key = secrets.token_bytes(32)
|
|
243
|
+
meta = build_php_license(binding)
|
|
244
|
+
|
|
245
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
246
|
+
n = 0
|
|
247
|
+
for r, dirs, fnames in os.walk(source_dir):
|
|
248
|
+
dirs[:] = [d for d in dirs if d.lower() not in PHP_SKIP_DIRS]
|
|
249
|
+
rel_dir = os.path.relpath(r, source_dir)
|
|
250
|
+
dst_dir = out_dir if rel_dir == "." else os.path.join(out_dir, rel_dir)
|
|
251
|
+
os.makedirs(dst_dir, exist_ok=True)
|
|
252
|
+
for fn in fnames:
|
|
253
|
+
src_fp = os.path.join(r, fn)
|
|
254
|
+
dst_fp = os.path.join(dst_dir, fn)
|
|
255
|
+
if fn.endswith(".php") and fn not in PHP_SKIP_FILES:
|
|
256
|
+
with open(src_fp, "rb") as f:
|
|
257
|
+
blob = _encrypt_source(f.read(), key)
|
|
258
|
+
with open(dst_fp, "w", encoding="utf-8") as f:
|
|
259
|
+
f.write(_stub(blob))
|
|
260
|
+
n += 1
|
|
261
|
+
else:
|
|
262
|
+
# copy assets / skipped files verbatim
|
|
263
|
+
with open(src_fp, "rb") as f:
|
|
264
|
+
data = f.read()
|
|
265
|
+
with open(dst_fp, "wb") as f:
|
|
266
|
+
f.write(data)
|
|
267
|
+
|
|
268
|
+
loader_path = os.path.join(out_dir, LOADER_NAME)
|
|
269
|
+
with open(loader_path, "w", encoding="utf-8") as f:
|
|
270
|
+
f.write(render_loader(key, meta))
|
|
271
|
+
say(f"encrypted {n} php file(s)")
|
|
272
|
+
|
|
273
|
+
return {
|
|
274
|
+
"files": n,
|
|
275
|
+
"lines": count_php_lines(files),
|
|
276
|
+
"loader": loader_path,
|
|
277
|
+
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|