samarth-runtime 1.0.0__py3-none-any.whl
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.
- samarth_runtime/__init__.py +10 -0
- samarth_runtime/ast_codec.py +106 -0
- samarth_runtime/hardened_codec.py +316 -0
- samarth_runtime/literal_engine.py +156 -0
- samarth_runtime/runtime.py +67 -0
- samarth_runtime/vm_engine.py +834 -0
- samarth_runtime-1.0.0.dist-info/METADATA +6 -0
- samarth_runtime-1.0.0.dist-info/RECORD +10 -0
- samarth_runtime-1.0.0.dist-info/WHEEL +5 -0
- samarth_runtime-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""SAMARTH runtime: executes protected (.sme) Python modules.
|
|
2
|
+
|
|
3
|
+
This package intentionally contains no identifier-renaming, string
|
|
4
|
+
obfuscation, or `protect`/encode tooling -- only what is needed to run an
|
|
5
|
+
already-produced .sme file. See docs/AUDIT.md in the full project for why
|
|
6
|
+
this split exists and what it does and does not protect against.
|
|
7
|
+
"""
|
|
8
|
+
__version__ = "1.0.0"
|
|
9
|
+
|
|
10
|
+
from .runtime import execute_payload, build_payload
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Generic AST <-> plain-data codec, with literal pooling folded in.
|
|
3
|
+
|
|
4
|
+
Converts an ast.AST tree into nested plain Python data (str/int/float/bool/
|
|
5
|
+
None/list/tuple only) so it can be serialized with `marshal` safely.
|
|
6
|
+
|
|
7
|
+
IMPORTANT, and the whole reason this module exists instead of just using
|
|
8
|
+
`marshal.dumps(compile(source, ...))`: marshal'd *code objects* embed
|
|
9
|
+
CPython-version/ABI-specific internals and are not safe to carry across
|
|
10
|
+
Python versions or interpreters -- exactly the portability problem this
|
|
11
|
+
project exists to avoid on Termux/Pydroid, where the installed Python minor
|
|
12
|
+
version varies. marshal of *plain data* (what this module produces) has
|
|
13
|
+
been a stable, documented format for ordinary values across Python versions
|
|
14
|
+
for a very long time, so it is the safe choice here.
|
|
15
|
+
|
|
16
|
+
Every ast.Constant leaf is replaced with a `("$L", pool_index)` marker during
|
|
17
|
+
encoding; the actual values are pulled out into a separate literal pool
|
|
18
|
+
(samarth_runtime.literal_engine) so they are not sitting in the AST data
|
|
19
|
+
as a flat, trivially "strings"-scannable sequence.
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import ast
|
|
24
|
+
|
|
25
|
+
from . import literal_engine
|
|
26
|
+
|
|
27
|
+
_POOL_MARKER = "$L"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _collect_and_replace_constants(node, pool: list):
|
|
31
|
+
"""Mutates `node` in place: every ast.Constant becomes a pool reference."""
|
|
32
|
+
class _Pooler(ast.NodeTransformer):
|
|
33
|
+
def visit_Constant(self, n):
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
if n.value is None or n.value is True or n.value is False or n.value is Ellipsis:
|
|
37
|
+
return n
|
|
38
|
+
idx = len(pool)
|
|
39
|
+
pool.append(n.value)
|
|
40
|
+
marker = ast.Constant(value=(_POOL_MARKER, idx))
|
|
41
|
+
return ast.copy_location(marker, n)
|
|
42
|
+
return _Pooler().visit(node)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _restore_constants(node, pool: tuple):
|
|
46
|
+
class _Unpooler(ast.NodeTransformer):
|
|
47
|
+
def visit_Constant(self, n):
|
|
48
|
+
if (isinstance(n.value, tuple) and len(n.value) == 2
|
|
49
|
+
and n.value[0] == _POOL_MARKER and isinstance(n.value[1], int)):
|
|
50
|
+
return ast.copy_location(ast.Constant(value=pool[n.value[1]]), n)
|
|
51
|
+
return n
|
|
52
|
+
return _Unpooler().visit(node)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _node_to_data(node):
|
|
56
|
+
if isinstance(node, ast.AST):
|
|
57
|
+
fields = []
|
|
58
|
+
for name in node._fields:
|
|
59
|
+
fields.append(_node_to_data(getattr(node, name, None)))
|
|
60
|
+
return (type(node).__name__, fields)
|
|
61
|
+
if isinstance(node, list):
|
|
62
|
+
return [_node_to_data(n) for n in node]
|
|
63
|
+
if isinstance(node, tuple):
|
|
64
|
+
|
|
65
|
+
return ("$T", list(node))
|
|
66
|
+
return node
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
_NODE_TYPES = {name: cls for name, cls in vars(ast).items() if isinstance(cls, type) and issubclass(cls, ast.AST)}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _data_to_node(data):
|
|
73
|
+
if isinstance(data, list):
|
|
74
|
+
return [_data_to_node(d) for d in data]
|
|
75
|
+
if isinstance(data, tuple) and len(data) == 2 and data[0] == "$T":
|
|
76
|
+
return tuple(_data_to_node(d) for d in data[1])
|
|
77
|
+
if isinstance(data, tuple) and len(data) == 2 and isinstance(data[0], str) and data[0] in _NODE_TYPES:
|
|
78
|
+
type_name, field_values = data
|
|
79
|
+
cls = _NODE_TYPES[type_name]
|
|
80
|
+
node = cls()
|
|
81
|
+
for name, value in zip(cls._fields, field_values):
|
|
82
|
+
setattr(node, name, _data_to_node(value))
|
|
83
|
+
return node
|
|
84
|
+
return data
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def encode_module(tree: ast.Module) -> tuple[bytes, bytes, bytes]:
|
|
88
|
+
"""Returns (salt, literal_pool_blob, ast_data_marshalled_bytes)."""
|
|
89
|
+
import secrets
|
|
90
|
+
import marshal
|
|
91
|
+
pool: list = []
|
|
92
|
+
_collect_and_replace_constants(tree, pool)
|
|
93
|
+
salt = secrets.token_bytes(16)
|
|
94
|
+
pool_blob = literal_engine.pack_pool(pool, salt)
|
|
95
|
+
data = _node_to_data(tree)
|
|
96
|
+
ast_bytes = marshal.dumps(data, 4)
|
|
97
|
+
return salt, pool_blob, ast_bytes
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def decode_module(salt: bytes, pool_blob: bytes, ast_bytes: bytes) -> ast.Module:
|
|
101
|
+
import marshal
|
|
102
|
+
data = marshal.loads(ast_bytes)
|
|
103
|
+
tree = _data_to_node(data)
|
|
104
|
+
pool = literal_engine.unpack_pool(pool_blob, salt)
|
|
105
|
+
tree = _restore_constants(tree, pool)
|
|
106
|
+
return ast.fix_missing_locations(tree)
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Hardened, keyless, reversible obfuscation container.
|
|
3
|
+
|
|
4
|
+
Pipeline (encode order): compress -> GF(256) polynomial substitution (2
|
|
5
|
+
rounds) -> Feistel diffusion (4 rounds) -> split into real+parity+chaff
|
|
6
|
+
fragments -> binary container with a compact (non-JSON, non-"here is the
|
|
7
|
+
answer") header.
|
|
8
|
+
|
|
9
|
+
Design note -- read this before assuming any particular strength claim:
|
|
10
|
+
every parameter here (salt, round counts, fragment layout) ships inside the
|
|
11
|
+
file or inside this module, because the file must be decodable standalone,
|
|
12
|
+
keylessly, on a plain Termux/Pydroid install with no network and no secret.
|
|
13
|
+
That means: anyone who has *this module* can invert anything produced by
|
|
14
|
+
it, deterministically, in one Python session -- this is fundamentally no
|
|
15
|
+
different from any other keyless scheme (see docs/AUDIT.md for the full,
|
|
16
|
+
honest threat model). What this design *does* improve over an earlier
|
|
17
|
+
iteration of this project is the no-package attacker's tier: there is no
|
|
18
|
+
single cleartext JSON block listing the real-shard checksums, the algorithm
|
|
19
|
+
name, or the round counts in human-readable form -- so someone with only the
|
|
20
|
+
.sme file and a hex editor has to do real reverse-engineering work to even
|
|
21
|
+
identify the container's shape, instead of reading the answer out of the
|
|
22
|
+
metadata. That is a cost increase, not a confidentiality guarantee.
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import bz2
|
|
27
|
+
import hashlib
|
|
28
|
+
import secrets
|
|
29
|
+
import struct
|
|
30
|
+
import zlib
|
|
31
|
+
|
|
32
|
+
try:
|
|
33
|
+
from . import _native_scramble as _native
|
|
34
|
+
except ImportError:
|
|
35
|
+
_native = None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
MAGIC = b"SMRH01"
|
|
43
|
+
HEADER_STRUCT = ">6sBB16sIIBB"
|
|
44
|
+
HEADER_SIZE = struct.calcsize(HEADER_STRUCT)
|
|
45
|
+
|
|
46
|
+
FLAG_BZ2 = 0x01
|
|
47
|
+
FEISTEL_ROUNDS = 4
|
|
48
|
+
POLY_ROUNDS = 2
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _compress(data: bytes) -> tuple[bytes, int]:
|
|
55
|
+
z = zlib.compress(data, 9)
|
|
56
|
+
b = bz2.compress(data, 9)
|
|
57
|
+
if len(b) < len(z):
|
|
58
|
+
return b, FLAG_BZ2
|
|
59
|
+
return z, 0
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _decompress(data: bytes, flags: int) -> bytes:
|
|
63
|
+
if flags & FLAG_BZ2:
|
|
64
|
+
return bz2.decompress(data)
|
|
65
|
+
return zlib.decompress(data)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _round_keys(salt: bytes, round_no: int) -> tuple[int, int]:
|
|
72
|
+
digest = hashlib.shake_256(salt + b"poly" + bytes([round_no])).digest(2)
|
|
73
|
+
multiplier = digest[0] | 1
|
|
74
|
+
offset = digest[1]
|
|
75
|
+
return multiplier, offset
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _modinv(a: int, m: int = 256) -> int:
|
|
79
|
+
|
|
80
|
+
g, x, _ = _egcd(a, m)
|
|
81
|
+
if g != 1:
|
|
82
|
+
raise ValueError("not invertible")
|
|
83
|
+
return x % m
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _egcd(a: int, b: int) -> tuple[int, int, int]:
|
|
87
|
+
if a == 0:
|
|
88
|
+
return b, 0, 1
|
|
89
|
+
g, x1, y1 = _egcd(b % a, a)
|
|
90
|
+
return g, y1 - (b // a) * x1, x1
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _poly_substitute(data: bytes, salt: bytes, rounds: int, forward: bool) -> bytes:
|
|
94
|
+
if _native is not None:
|
|
95
|
+
return _native.poly_substitute(data, salt, rounds, forward)
|
|
96
|
+
out = bytearray(data)
|
|
97
|
+
order = range(rounds) if forward else range(rounds - 1, -1, -1)
|
|
98
|
+
for r in order:
|
|
99
|
+
mult, off = _round_keys(salt, r)
|
|
100
|
+
if forward:
|
|
101
|
+
out = bytearray((mult * b + off) & 0xFF for b in out)
|
|
102
|
+
else:
|
|
103
|
+
inv = _modinv(mult)
|
|
104
|
+
out = bytearray((inv * ((b - off) & 0xFF)) & 0xFF for b in out)
|
|
105
|
+
return bytes(out)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _feistel_round_function(half: bytes, salt: bytes, round_no: int, out_len: int) -> bytes:
|
|
112
|
+
ks = hashlib.shake_256(salt + b"feistel" + bytes([round_no]) + half).digest(out_len)
|
|
113
|
+
return ks
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _feistel_encrypt(data: bytes, salt: bytes, rounds: int) -> bytes:
|
|
117
|
+
if _native is not None:
|
|
118
|
+
return _native.feistel_crypt(data, salt, rounds, True)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
pad = (-len(data)) % 2
|
|
123
|
+
padded = data + bytes(pad)
|
|
124
|
+
half_len = len(padded) // 2
|
|
125
|
+
left, right = bytearray(padded[:half_len]), bytearray(padded[half_len:])
|
|
126
|
+
for r in range(rounds):
|
|
127
|
+
f = _feistel_round_function(bytes(right), salt, r, half_len)
|
|
128
|
+
new_left = bytes(a ^ b for a, b in zip(left, f))
|
|
129
|
+
left, right = right, bytearray(new_left)
|
|
130
|
+
return bytes([pad]) + bytes(left) + bytes(right)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _feistel_decrypt(blob: bytes, salt: bytes, rounds: int) -> bytes:
|
|
134
|
+
if _native is not None:
|
|
135
|
+
return _native.feistel_crypt(blob, salt, rounds, False)
|
|
136
|
+
pad = blob[0]
|
|
137
|
+
body = blob[1:]
|
|
138
|
+
half_len = len(body) // 2
|
|
139
|
+
left, right = bytearray(body[:half_len]), bytearray(body[half_len:])
|
|
140
|
+
for r in range(rounds - 1, -1, -1):
|
|
141
|
+
f = _feistel_round_function(bytes(left), salt, r, half_len)
|
|
142
|
+
new_right = bytes(a ^ b for a, b in zip(right, f))
|
|
143
|
+
right, left = left, bytearray(new_right)
|
|
144
|
+
result = bytes(left) + bytes(right)
|
|
145
|
+
return result[:len(result) - pad] if pad else result
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _lehmer_permutation(n: int, salt: bytes) -> list[int]:
|
|
153
|
+
"""Deterministic, salt-seeded permutation of range(n), decodable without
|
|
154
|
+
storing the permutation itself -- only `n` and `salt` are needed."""
|
|
155
|
+
pool = list(range(n))
|
|
156
|
+
out = []
|
|
157
|
+
digest = hashlib.shake_256(salt + b"lehmer").digest(max(n * 2, 2))
|
|
158
|
+
di = 0
|
|
159
|
+
for remaining in range(n, 0, -1):
|
|
160
|
+
idx = int.from_bytes(digest[di:di + 2], "big") % remaining
|
|
161
|
+
di = (di + 2) % len(digest)
|
|
162
|
+
out.append(pool.pop(idx))
|
|
163
|
+
return out
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _shard_tag(salt: bytes, index: int, payload: bytes) -> bytes:
|
|
167
|
+
"""A salt-keyed authenticity tag for one real/parity shard. Deliberately
|
|
168
|
+
NOT a plain content hash of a value that is also published anywhere in
|
|
169
|
+
cleartext -- it binds the shard's own content to its logical position,
|
|
170
|
+
so identifying genuine shards among chaff requires recomputing this
|
|
171
|
+
function (i.e. having this module), not reading a list out of the file.
|
|
172
|
+
"""
|
|
173
|
+
return hashlib.shake_256(salt + b"shard" + struct.pack(">I", index) + payload).digest(16)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _fragment(data: bytes, salt: bytes, k: int, chaff: int) -> list[bytes]:
|
|
177
|
+
"""Systematic split into k nearly-equal data shards + 1 XOR parity shard
|
|
178
|
+
(tolerates the loss of any single real/parity shard) + `chaff` decoy
|
|
179
|
+
shards of identical size and shape, all placed in salt-derived order."""
|
|
180
|
+
shard_size = -(-len(data) // k)
|
|
181
|
+
padded = data + bytes(shard_size * k - len(data))
|
|
182
|
+
data_shards = [padded[i * shard_size:(i + 1) * shard_size] for i in range(k)]
|
|
183
|
+
parity = bytearray(shard_size)
|
|
184
|
+
for s in data_shards:
|
|
185
|
+
for i, b in enumerate(s):
|
|
186
|
+
parity[i] ^= b
|
|
187
|
+
real_shards = data_shards + [bytes(parity)]
|
|
188
|
+
|
|
189
|
+
records = []
|
|
190
|
+
for idx, payload in enumerate(real_shards):
|
|
191
|
+
tag = _shard_tag(salt, idx, payload)
|
|
192
|
+
records.append((idx, True, tag, payload))
|
|
193
|
+
for c in range(chaff):
|
|
194
|
+
decoy = secrets.token_bytes(shard_size)
|
|
195
|
+
fake_tag = secrets.token_bytes(16)
|
|
196
|
+
records.append((-(c + 1), False, fake_tag, decoy))
|
|
197
|
+
|
|
198
|
+
order = _lehmer_permutation(len(records), salt)
|
|
199
|
+
ordered = [records[i] for i in order]
|
|
200
|
+
|
|
201
|
+
out = []
|
|
202
|
+
for _, _, tag, payload in ordered:
|
|
203
|
+
rec = struct.pack(">I", len(payload)) + tag + payload
|
|
204
|
+
out.append(rec)
|
|
205
|
+
return out
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _defragment(fragments: list[bytes], salt: bytes, k: int, orig_len: int) -> bytes:
|
|
209
|
+
total = len(fragments)
|
|
210
|
+
order = _lehmer_permutation(total, salt)
|
|
211
|
+
|
|
212
|
+
logical_of_physical = [0] * total
|
|
213
|
+
for physical_pos, logical_idx in enumerate(order):
|
|
214
|
+
logical_of_physical[physical_pos] = logical_idx
|
|
215
|
+
|
|
216
|
+
parsed = []
|
|
217
|
+
for physical_pos, rec in enumerate(fragments):
|
|
218
|
+
(length,) = struct.unpack(">I", rec[:4])
|
|
219
|
+
tag = rec[4:20]
|
|
220
|
+
payload = rec[20:20 + length]
|
|
221
|
+
parsed.append((logical_of_physical[physical_pos], tag, payload))
|
|
222
|
+
|
|
223
|
+
real = {}
|
|
224
|
+
for logical_idx, tag, payload in parsed:
|
|
225
|
+
if 0 <= logical_idx <= k:
|
|
226
|
+
expected = _shard_tag(salt, logical_idx, payload)
|
|
227
|
+
if secrets.compare_digest(expected, tag):
|
|
228
|
+
real[logical_idx] = payload
|
|
229
|
+
|
|
230
|
+
missing = [i for i in range(k) if i not in real]
|
|
231
|
+
if len(missing) > 1:
|
|
232
|
+
raise ValueError("SAMARTH: too many missing/corrupted shards to recover payload")
|
|
233
|
+
if len(missing) == 1 and k in real:
|
|
234
|
+
|
|
235
|
+
shard_size = len(real[k])
|
|
236
|
+
rebuilt = bytearray(real[k])
|
|
237
|
+
for i in range(k):
|
|
238
|
+
if i == missing[0]:
|
|
239
|
+
continue
|
|
240
|
+
for b_i, b in enumerate(real[i]):
|
|
241
|
+
rebuilt[b_i] ^= b
|
|
242
|
+
real[missing[0]] = bytes(rebuilt)
|
|
243
|
+
elif missing:
|
|
244
|
+
raise ValueError("SAMARTH: missing data shard and no parity shard available")
|
|
245
|
+
|
|
246
|
+
data = b"".join(real[i] for i in range(k))
|
|
247
|
+
return data[:orig_len]
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def pack(source_bytes: bytes, *, k: int = 4, chaff: int = 2) -> bytes:
|
|
254
|
+
"""Encode `source_bytes` (already produced by the VM/literal layers, i.e.
|
|
255
|
+
whatever opaque blob is being protected) into a complete .sme container.
|
|
256
|
+
|
|
257
|
+
Integrity design note: there is deliberately NO single hash computed over
|
|
258
|
+
the whole container. A single whole-file hash would reject any
|
|
259
|
+
corruption outright and the shard-level erasure recovery below would
|
|
260
|
+
never get a chance to run -- the two goals (hard tamper rejection vs.
|
|
261
|
+
tolerating/healing partial corruption) are in direct tension, and this
|
|
262
|
+
format picks the second one for the body. The small, fixed-size header
|
|
263
|
+
(salt/lengths/counts) is still integrity-checked on its own, since if
|
|
264
|
+
*those* fields are corrupted nothing downstream can be trusted; the body
|
|
265
|
+
is protected and healed instead via the per-shard authenticity tags and
|
|
266
|
+
the XOR-parity shard in `_fragment`/`_defragment`.
|
|
267
|
+
"""
|
|
268
|
+
salt = secrets.token_bytes(16)
|
|
269
|
+
compressed, flags = _compress(source_bytes)
|
|
270
|
+
stage = _poly_substitute(compressed, salt, POLY_ROUNDS, forward=True)
|
|
271
|
+
stage = _feistel_encrypt(stage, salt, FEISTEL_ROUNDS)
|
|
272
|
+
|
|
273
|
+
fragments = _fragment(stage, salt, k, chaff)
|
|
274
|
+
body = bytearray()
|
|
275
|
+
body.append(len(fragments))
|
|
276
|
+
for frag in fragments:
|
|
277
|
+
body.extend(frag)
|
|
278
|
+
|
|
279
|
+
header_fields = struct.pack(
|
|
280
|
+
HEADER_STRUCT, MAGIC, 1, flags, salt, len(source_bytes), len(stage), k, chaff
|
|
281
|
+
)
|
|
282
|
+
header_checksum = hashlib.sha256(header_fields).digest()[:8]
|
|
283
|
+
return header_fields + header_checksum + bytes(body)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def unpack(container: bytes) -> bytes:
|
|
287
|
+
if len(container) < HEADER_SIZE + 8:
|
|
288
|
+
raise ValueError("SAMARTH: payload too short to be a valid container")
|
|
289
|
+
header_fields = container[:HEADER_SIZE]
|
|
290
|
+
header_checksum = container[HEADER_SIZE:HEADER_SIZE + 8]
|
|
291
|
+
if not secrets.compare_digest(hashlib.sha256(header_fields).digest()[:8], header_checksum):
|
|
292
|
+
raise ValueError("SAMARTH integrity check failed: header corrupted")
|
|
293
|
+
|
|
294
|
+
magic, version, flags, salt, orig_len, stage_len, k, chaff = struct.unpack(
|
|
295
|
+
HEADER_STRUCT, header_fields
|
|
296
|
+
)
|
|
297
|
+
if magic != MAGIC:
|
|
298
|
+
raise ValueError("SAMARTH: not a recognized container")
|
|
299
|
+
if version != 1:
|
|
300
|
+
raise ValueError(f"SAMARTH: unsupported container version {version}")
|
|
301
|
+
|
|
302
|
+
rest = container[HEADER_SIZE + 8:]
|
|
303
|
+
frag_count = rest[0]
|
|
304
|
+
pos = 1
|
|
305
|
+
fragments = []
|
|
306
|
+
for _ in range(frag_count):
|
|
307
|
+
(length,) = struct.unpack(">I", rest[pos:pos + 4])
|
|
308
|
+
rec_len = 4 + 16 + length
|
|
309
|
+
fragments.append(rest[pos:pos + rec_len])
|
|
310
|
+
pos += rec_len
|
|
311
|
+
|
|
312
|
+
stage = _defragment(fragments, salt, k, stage_len)
|
|
313
|
+
compressed = _feistel_decrypt(stage, salt, FEISTEL_ROUNDS)
|
|
314
|
+
compressed = _poly_substitute(compressed, salt, POLY_ROUNDS, forward=False)
|
|
315
|
+
source_bytes = _decompress(compressed, flags)
|
|
316
|
+
return source_bytes[:orig_len]
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Literal pool engine.
|
|
3
|
+
|
|
4
|
+
Collects every string/bytes/int/float/complex constant used by a protected
|
|
5
|
+
module into a single pool, encodes the pool as one opaque blob, and lets the
|
|
6
|
+
VM/encoder refer to each value by index instead of embedding it directly in
|
|
7
|
+
the AST. This is reversible, keyless obfuscation: it hides literal values
|
|
8
|
+
from a casual "strings" scan of the .sme file, it does NOT provide
|
|
9
|
+
confidentiality against anyone holding this module (see docs/AUDIT.md).
|
|
10
|
+
|
|
11
|
+
Encoding, per value:
|
|
12
|
+
tag(1 byte) + length(varint) + payload
|
|
13
|
+
where tag identifies the Python type (str/bytes/int/float/complex/bool/None)
|
|
14
|
+
so decoding never depends on marshal or pickle (keeps this safe across
|
|
15
|
+
Python versions/ABIs -- important for the Termux/Pydroid portability goal).
|
|
16
|
+
|
|
17
|
+
The whole encoded stream is then XORed with a SHAKE-256(salt) keystream
|
|
18
|
+
(reversible, keyless -- the salt ships in the same file, this is NOT a
|
|
19
|
+
secret, see docs/AUDIT.md) to avoid leaving literal values as a trivially
|
|
20
|
+
readable flat byte stream even before the outer compression/scramble layers
|
|
21
|
+
run.
|
|
22
|
+
"""
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import hashlib
|
|
26
|
+
import struct
|
|
27
|
+
|
|
28
|
+
_TAG_NONE = 0
|
|
29
|
+
_TAG_TRUE = 1
|
|
30
|
+
_TAG_FALSE = 2
|
|
31
|
+
_TAG_INT = 3
|
|
32
|
+
_TAG_FLOAT = 4
|
|
33
|
+
_TAG_COMPLEX = 5
|
|
34
|
+
_TAG_STR = 6
|
|
35
|
+
_TAG_BYTES = 7
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _write_varint(buf: bytearray, n: int) -> None:
|
|
39
|
+
if n < 0:
|
|
40
|
+
raise ValueError("varint length must be non-negative")
|
|
41
|
+
while True:
|
|
42
|
+
b = n & 0x7F
|
|
43
|
+
n >>= 7
|
|
44
|
+
if n:
|
|
45
|
+
buf.append(b | 0x80)
|
|
46
|
+
else:
|
|
47
|
+
buf.append(b)
|
|
48
|
+
return
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _read_varint(data: bytes, pos: int) -> tuple[int, int]:
|
|
52
|
+
result = 0
|
|
53
|
+
shift = 0
|
|
54
|
+
while True:
|
|
55
|
+
b = data[pos]
|
|
56
|
+
pos += 1
|
|
57
|
+
result |= (b & 0x7F) << shift
|
|
58
|
+
if not (b & 0x80):
|
|
59
|
+
return result, pos
|
|
60
|
+
shift += 7
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _keystream(salt: bytes, length: int, *, label: bytes = b"samarth-literal-pool") -> bytes:
|
|
64
|
+
return hashlib.shake_256(label + salt).digest(max(length, 1))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _xor(data: bytes, salt: bytes, label: bytes = b"samarth-literal-pool") -> bytes:
|
|
68
|
+
ks = _keystream(salt, len(data), label=label)
|
|
69
|
+
return bytes(a ^ b for a, b in zip(data, ks))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _encode_one(value) -> bytes:
|
|
73
|
+
buf = bytearray()
|
|
74
|
+
if value is None:
|
|
75
|
+
buf.append(_TAG_NONE)
|
|
76
|
+
elif value is True:
|
|
77
|
+
buf.append(_TAG_TRUE)
|
|
78
|
+
elif value is False:
|
|
79
|
+
buf.append(_TAG_FALSE)
|
|
80
|
+
elif isinstance(value, int):
|
|
81
|
+
raw = value.to_bytes((value.bit_length() + 8) // 8 or 1, "big", signed=True)
|
|
82
|
+
buf.append(_TAG_INT)
|
|
83
|
+
_write_varint(buf, len(raw))
|
|
84
|
+
buf.extend(raw)
|
|
85
|
+
elif isinstance(value, float):
|
|
86
|
+
buf.append(_TAG_FLOAT)
|
|
87
|
+
buf.extend(struct.pack(">d", value))
|
|
88
|
+
elif isinstance(value, complex):
|
|
89
|
+
buf.append(_TAG_COMPLEX)
|
|
90
|
+
buf.extend(struct.pack(">dd", value.real, value.imag))
|
|
91
|
+
elif isinstance(value, str):
|
|
92
|
+
raw = value.encode("utf-8")
|
|
93
|
+
buf.append(_TAG_STR)
|
|
94
|
+
_write_varint(buf, len(raw))
|
|
95
|
+
buf.extend(raw)
|
|
96
|
+
elif isinstance(value, (bytes, bytearray)):
|
|
97
|
+
raw = bytes(value)
|
|
98
|
+
buf.append(_TAG_BYTES)
|
|
99
|
+
_write_varint(buf, len(raw))
|
|
100
|
+
buf.extend(raw)
|
|
101
|
+
else:
|
|
102
|
+
raise TypeError(f"literal pool cannot encode type {type(value)!r}")
|
|
103
|
+
return bytes(buf)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _decode_one(data: bytes, pos: int):
|
|
107
|
+
tag = data[pos]
|
|
108
|
+
pos += 1
|
|
109
|
+
if tag == _TAG_NONE:
|
|
110
|
+
return None, pos
|
|
111
|
+
if tag == _TAG_TRUE:
|
|
112
|
+
return True, pos
|
|
113
|
+
if tag == _TAG_FALSE:
|
|
114
|
+
return False, pos
|
|
115
|
+
if tag == _TAG_INT:
|
|
116
|
+
n, pos = _read_varint(data, pos)
|
|
117
|
+
raw = data[pos:pos + n]
|
|
118
|
+
pos += n
|
|
119
|
+
return int.from_bytes(raw, "big", signed=True), pos
|
|
120
|
+
if tag == _TAG_FLOAT:
|
|
121
|
+
(v,) = struct.unpack(">d", data[pos:pos + 8])
|
|
122
|
+
return v, pos + 8
|
|
123
|
+
if tag == _TAG_COMPLEX:
|
|
124
|
+
re, im = struct.unpack(">dd", data[pos:pos + 16])
|
|
125
|
+
return complex(re, im), pos + 16
|
|
126
|
+
if tag == _TAG_STR:
|
|
127
|
+
n, pos = _read_varint(data, pos)
|
|
128
|
+
raw = data[pos:pos + n]
|
|
129
|
+
pos += n
|
|
130
|
+
return raw.decode("utf-8"), pos
|
|
131
|
+
if tag == _TAG_BYTES:
|
|
132
|
+
n, pos = _read_varint(data, pos)
|
|
133
|
+
raw = data[pos:pos + n]
|
|
134
|
+
pos += n
|
|
135
|
+
return bytes(raw), pos
|
|
136
|
+
raise ValueError(f"corrupt literal pool: unknown tag {tag}")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def pack_pool(values: list, salt: bytes) -> bytes:
|
|
140
|
+
"""Encode a list of literal values into one opaque, salt-obfuscated blob."""
|
|
141
|
+
buf = bytearray()
|
|
142
|
+
_write_varint(buf, len(values))
|
|
143
|
+
for v in values:
|
|
144
|
+
buf.extend(_encode_one(v))
|
|
145
|
+
return _xor(bytes(buf), salt)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def unpack_pool(payload: bytes, salt: bytes) -> tuple:
|
|
149
|
+
"""Inverse of pack_pool. Returns a tuple of the original literal values."""
|
|
150
|
+
data = _xor(payload, salt)
|
|
151
|
+
count, pos = _read_varint(data, 0)
|
|
152
|
+
out = []
|
|
153
|
+
for _ in range(count):
|
|
154
|
+
v, pos = _decode_one(data, pos)
|
|
155
|
+
out.append(v)
|
|
156
|
+
return tuple(out)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Top-level runtime entry point. This is the ONLY module `loader.py` needs to
|
|
3
|
+
import. Everything else in this package is an implementation detail reached
|
|
4
|
+
through here.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import ast
|
|
9
|
+
import struct
|
|
10
|
+
|
|
11
|
+
from . import hardened_codec
|
|
12
|
+
from .ast_codec import decode_module
|
|
13
|
+
from .vm_engine import VMRuntime
|
|
14
|
+
|
|
15
|
+
CAPSULE_MAGIC = b"SMCP"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _build_capsule(salt: bytes, pool_blob: bytes, ast_bytes: bytes) -> bytes:
|
|
19
|
+
return (
|
|
20
|
+
CAPSULE_MAGIC
|
|
21
|
+
+ struct.pack(">I", len(salt)) + salt
|
|
22
|
+
+ struct.pack(">I", len(pool_blob)) + pool_blob
|
|
23
|
+
+ ast_bytes
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _parse_capsule(capsule: bytes) -> tuple[bytes, bytes, bytes]:
|
|
28
|
+
if capsule[:4] != CAPSULE_MAGIC:
|
|
29
|
+
raise ValueError("SAMARTH: not a recognized module capsule")
|
|
30
|
+
pos = 4
|
|
31
|
+
(salt_len,) = struct.unpack(">I", capsule[pos:pos + 4]); pos += 4
|
|
32
|
+
salt = capsule[pos:pos + salt_len]; pos += salt_len
|
|
33
|
+
(pool_len,) = struct.unpack(">I", capsule[pos:pos + 4]); pos += 4
|
|
34
|
+
pool_blob = capsule[pos:pos + pool_len]; pos += pool_len
|
|
35
|
+
ast_bytes = capsule[pos:]
|
|
36
|
+
return salt, pool_blob, ast_bytes
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def build_payload(tree: ast.Module, *, k: int = 4, chaff: int = 2) -> bytes:
|
|
40
|
+
"""Encoder-side helper: turn a transformed AST into a complete .sme
|
|
41
|
+
payload. Exposed here (not only in samarth_encoder) because it has no
|
|
42
|
+
identifier-renaming/obfuscation logic of its own -- it is pure, harmless
|
|
43
|
+
plumbing, same as zlib.compress being safe to expose alongside
|
|
44
|
+
zlib.decompress. The actual protection logic (renaming, eligibility
|
|
45
|
+
analysis, CLI) lives in the separate, non-redistributed samarth_encoder
|
|
46
|
+
package.
|
|
47
|
+
"""
|
|
48
|
+
from .ast_codec import encode_module
|
|
49
|
+
salt, pool_blob, ast_bytes = encode_module(tree)
|
|
50
|
+
capsule = _build_capsule(salt, pool_blob, ast_bytes)
|
|
51
|
+
return hardened_codec.pack(capsule, k=k, chaff=chaff)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def execute_payload(payload: bytes, globals_dict: dict | None = None, filename: str = "<samarth>") -> dict:
|
|
55
|
+
"""Decode and run a .sme payload. Returns a small metadata dict."""
|
|
56
|
+
capsule = hardened_codec.unpack(payload)
|
|
57
|
+
salt, pool_blob, ast_bytes = _parse_capsule(capsule)
|
|
58
|
+
tree = decode_module(salt, pool_blob, ast_bytes)
|
|
59
|
+
|
|
60
|
+
ns = globals_dict if globals_dict is not None else {"__name__": "__main__"}
|
|
61
|
+
ns.setdefault("__file__", filename)
|
|
62
|
+
doc = ast.get_docstring(tree, clean=False)
|
|
63
|
+
if doc is not None:
|
|
64
|
+
ns.setdefault("__doc__", doc)
|
|
65
|
+
|
|
66
|
+
VMRuntime(tree, ns).run()
|
|
67
|
+
return {"format": "samarth-runtime-v1", "filename": filename}
|