gamai-plugins 0.2.2__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.
- gamai_plugins/__init__.py +2 -0
- gamai_plugins/cli.py +134 -0
- gamai_plugins/mcp.py +89 -0
- gamai_plugins/plugins/protean/plugin.json +64 -0
- gamai_plugins/plugins/protean/run.py +788 -0
- gamai_plugins/plugins/protean/seccomp.json +134 -0
- gamai_plugins/plugins/team/plugin.json +105 -0
- gamai_plugins/plugins/team/run.py +59 -0
- gamai_plugins/plugins/team/team_core.py +642 -0
- gamai_plugins/plugins/trust/plugin.json +76 -0
- gamai_plugins/plugins/trust/run.py +680 -0
- gamai_plugins-0.2.2.dist-info/METADATA +220 -0
- gamai_plugins-0.2.2.dist-info/RECORD +17 -0
- gamai_plugins-0.2.2.dist-info/WHEEL +5 -0
- gamai_plugins-0.2.2.dist-info/entry_points.txt +6 -0
- gamai_plugins-0.2.2.dist-info/licenses/LICENSE +21 -0
- gamai_plugins-0.2.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,788 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""PROTEAN sandbox runner (stdin=args JSON, stdout=JSON).
|
|
3
|
+
|
|
4
|
+
Chain: genome -> signed lease (HMAC-SHA256, TTL, genome+cmd binding) -> policy
|
|
5
|
+
gate -> substrate -> evidence. Fail-closed on unknown risk/substrate, invalid
|
|
6
|
+
or expired lease, TTL overflow, unsupported network request, and executables
|
|
7
|
+
outside the genome allowlist.
|
|
8
|
+
|
|
9
|
+
Substrates:
|
|
10
|
+
low bwrap (user/pid/net/uts/ipc/cgroup namespaces, ro-root, tmpfs /tmp)
|
|
11
|
+
medium Docker runc (--network=none, cap-drop ALL, no-new-privileges,
|
|
12
|
+
read-only root, tmpfs /tmp, pids/mem/cpu limits, uid 65534)
|
|
13
|
+
high Docker runc + default-deny seccomp allowlist
|
|
14
|
+
critical denied locally (no /dev/kvm); remote=true -> SSH to a configured
|
|
15
|
+
remote host and run under gVisor (runsc) if it is reachable and ready
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import hashlib
|
|
19
|
+
import hmac
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import secrets
|
|
24
|
+
import shlex
|
|
25
|
+
import shutil
|
|
26
|
+
import subprocess
|
|
27
|
+
import sys
|
|
28
|
+
import threading
|
|
29
|
+
import time
|
|
30
|
+
from datetime import datetime, timezone
|
|
31
|
+
|
|
32
|
+
BASE = os.path.expanduser(os.environ.get("PROTEAN_HOME", "~/.config/gamai/protean"))
|
|
33
|
+
os.makedirs(BASE, mode=0o700, exist_ok=True)
|
|
34
|
+
try:
|
|
35
|
+
os.chmod(BASE, 0o700)
|
|
36
|
+
except OSError:
|
|
37
|
+
pass
|
|
38
|
+
LEASE_KEY_PATH = os.path.join(BASE, "lease.key")
|
|
39
|
+
SECCOMP_PATH = os.path.join(BASE, "seccomp.json")
|
|
40
|
+
if not os.path.isfile(SECCOMP_PATH):
|
|
41
|
+
bundled = os.path.join(os.path.dirname(os.path.abspath(__file__)), "seccomp.json")
|
|
42
|
+
if os.path.isfile(bundled):
|
|
43
|
+
shutil.copyfile(bundled, SECCOMP_PATH)
|
|
44
|
+
RUNS_DIR = os.path.join(BASE, "runs")
|
|
45
|
+
|
|
46
|
+
# Putanje s tajnama koje sandboxirana komanda NE smije citati.
|
|
47
|
+
# Maskiraju se unutar bwrap sandboxa (protean sam ih i dalje vidi na hostu).
|
|
48
|
+
SECRET_MASKS = (
|
|
49
|
+
"/etc/shadow",
|
|
50
|
+
"/etc/shadow-",
|
|
51
|
+
"/etc/gshadow",
|
|
52
|
+
"/etc/gshadow-",
|
|
53
|
+
"/etc/sudoers",
|
|
54
|
+
"/etc/sudoers.d",
|
|
55
|
+
"/etc/ssh",
|
|
56
|
+
"/etc/ssl/private",
|
|
57
|
+
"/etc/pki/private",
|
|
58
|
+
"/etc/security/opasswd",
|
|
59
|
+
os.path.expanduser("~/.ssh"),
|
|
60
|
+
os.path.expanduser("~/.aws"),
|
|
61
|
+
os.path.expanduser("~/.config/gamai"),
|
|
62
|
+
os.path.join(BASE, "lease.key"),
|
|
63
|
+
)
|
|
64
|
+
BWRAP_ROOTS = ("/usr/bin", "/usr/sbin", "/usr/lib", "/usr/lib64", "/usr/share",
|
|
65
|
+
"/bin", "/sbin", "/lib", "/lib64")
|
|
66
|
+
BWRAP_ETC_ALLOW = (
|
|
67
|
+
"/etc/passwd", "/etc/group", "/etc/nsswitch.conf", "/etc/hosts",
|
|
68
|
+
"/etc/hostname", "/etc/localtime", "/etc/timezone", "/etc/services",
|
|
69
|
+
"/etc/protocols", "/etc/ssl/certs", "/etc/ssl/openssl.cnf",
|
|
70
|
+
"/etc/ca-certificates", "/etc/ca-certificates.conf", "/etc/ld.so.cache",
|
|
71
|
+
"/etc/ld.so.conf", "/etc/ld.so.conf.d", "/etc/alternatives",
|
|
72
|
+
"/etc/mime.types", "/etc/gitconfig",
|
|
73
|
+
)
|
|
74
|
+
BWRAP_TMPFS_SIZE = 32 * 1024 * 1024
|
|
75
|
+
TOTAL_BUDGET_S = 56.0 # manifest timeout_s=60; ostatak je rezerva za evidenciju
|
|
76
|
+
EMPTY_MASK_FILE = os.path.join(BASE, ".empty_mask")
|
|
77
|
+
|
|
78
|
+
IMAGE = os.environ.get("PROTEAN_IMAGE", "python:3.12-alpine")
|
|
79
|
+
REMOTE_HOST = os.environ.get("PROTEAN_REMOTE_HOST", "")
|
|
80
|
+
REMOTE_PORT = os.environ.get("PROTEAN_REMOTE_PORT", "22")
|
|
81
|
+
REMOTE_KEY = os.environ.get("PROTEAN_REMOTE_KEY", "")
|
|
82
|
+
REMOTE_USER = os.environ.get("PROTEAN_REMOTE_USER", "root")
|
|
83
|
+
KNOWN_HOSTS = os.path.expanduser(os.environ.get("PROTEAN_KNOWN_HOSTS", "~/.ssh/known_hosts"))
|
|
84
|
+
SSH_STRICT = os.environ.get("PROTEAN_SSH_STRICT", "accept-new")
|
|
85
|
+
if SSH_STRICT not in ("yes", "accept-new", "no"):
|
|
86
|
+
SSH_STRICT = "accept-new"
|
|
87
|
+
HIGH_REMOTE = os.environ.get("PROTEAN_HIGH_REMOTE", "0") == "1"
|
|
88
|
+
PATH_ENV = os.environ.get(
|
|
89
|
+
"PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
|
90
|
+
)
|
|
91
|
+
CLEAN_ENV = {"PATH": PATH_ENV, "LANG": "C.UTF-8", "LC_ALL": "C.UTF-8", "HOME": "/tmp"}
|
|
92
|
+
|
|
93
|
+
ALLOWED_RISKS = ("low", "medium", "high", "critical")
|
|
94
|
+
TTL_MAX = 50
|
|
95
|
+
TIMEOUT_MAX = 45
|
|
96
|
+
CMD_MAX = 4096
|
|
97
|
+
OUT_CLIP = 8000
|
|
98
|
+
CAPTURE_LIMIT = 64 * 1024
|
|
99
|
+
|
|
100
|
+
TOOLS = {
|
|
101
|
+
"sh", "dash", "bash", "cat", "echo", "printf", "ls", "id", "uname",
|
|
102
|
+
"head", "tail", "wc", "sleep", "true", "false", "date", "whoami",
|
|
103
|
+
"pwd", "grep", "sed", "awk", "cut", "tr", "sort", "uniq", "find",
|
|
104
|
+
"test", "[", "stat", "readlink", "realpath", "dirname", "basename",
|
|
105
|
+
"seq", "hostname", "mktemp", "touch", "df", "du", "ps", "timeout",
|
|
106
|
+
"base64", "sha256sum", "md5sum", "tar", "gzip", "gunzip", "node",
|
|
107
|
+
"python3", "python", "git",
|
|
108
|
+
}
|
|
109
|
+
SHELL_KEYWORDS = {
|
|
110
|
+
"if", "then", "else", "elif", "fi", "for", "while", "until", "do",
|
|
111
|
+
"done", "case", "esac", "function", "select", "time", "!", "{", "(",
|
|
112
|
+
}
|
|
113
|
+
FIRST_TOKEN_RE = re.compile(
|
|
114
|
+
r"^\s*((?:[A-Za-z_][A-Za-z0-9_]*=(?:'[^']*'|\"[^\"]*\"|\S*)\s+)*)"
|
|
115
|
+
r"([^\s;|&<>`]+)"
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def emit(obj):
|
|
120
|
+
sys.stdout.write(json.dumps(obj, ensure_ascii=False, sort_keys=True))
|
|
121
|
+
sys.stdout.write("\n")
|
|
122
|
+
return 0
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _read_capped(stream, sink):
|
|
126
|
+
total = 0
|
|
127
|
+
while True:
|
|
128
|
+
chunk = stream.read(65536)
|
|
129
|
+
if not chunk:
|
|
130
|
+
break
|
|
131
|
+
if total < CAPTURE_LIMIT:
|
|
132
|
+
take = chunk[:CAPTURE_LIMIT - total]
|
|
133
|
+
sink.append(take)
|
|
134
|
+
total += len(take)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def run_limited(argv, timeout, env=None, cwd=None):
|
|
138
|
+
"""Run a process with bounded stdout/stderr capture (memory-safe)."""
|
|
139
|
+
proc = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
140
|
+
env=env, cwd=cwd)
|
|
141
|
+
out_chunks, err_chunks = [], []
|
|
142
|
+
readers = [
|
|
143
|
+
threading.Thread(target=_read_capped, args=(proc.stdout, out_chunks), daemon=True),
|
|
144
|
+
threading.Thread(target=_read_capped, args=(proc.stderr, err_chunks), daemon=True),
|
|
145
|
+
]
|
|
146
|
+
for reader in readers:
|
|
147
|
+
reader.start()
|
|
148
|
+
timed_out = False
|
|
149
|
+
try:
|
|
150
|
+
rc = proc.wait(timeout=timeout)
|
|
151
|
+
except subprocess.TimeoutExpired:
|
|
152
|
+
timed_out = True
|
|
153
|
+
proc.kill()
|
|
154
|
+
try:
|
|
155
|
+
rc = proc.wait(timeout=5)
|
|
156
|
+
except subprocess.TimeoutExpired:
|
|
157
|
+
rc = None
|
|
158
|
+
for reader in readers:
|
|
159
|
+
reader.join(timeout=2)
|
|
160
|
+
for stream in (proc.stdout, proc.stderr):
|
|
161
|
+
try:
|
|
162
|
+
stream.close()
|
|
163
|
+
except Exception:
|
|
164
|
+
pass
|
|
165
|
+
return rc, b"".join(out_chunks), b"".join(err_chunks), timed_out
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def clip(text, limit=OUT_CLIP):
|
|
169
|
+
if not isinstance(text, str):
|
|
170
|
+
text = str(text)
|
|
171
|
+
if len(text) <= limit:
|
|
172
|
+
return text
|
|
173
|
+
return text[:limit] + "\n...[skraceno %d znakova]" % (len(text) - limit)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def canon(obj):
|
|
177
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def sha256_hex(data):
|
|
181
|
+
if isinstance(data, str):
|
|
182
|
+
data = data.encode("utf-8")
|
|
183
|
+
return hashlib.sha256(data).hexdigest()
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def load_lease_key():
|
|
187
|
+
try:
|
|
188
|
+
with open(LEASE_KEY_PATH, "rb") as fh:
|
|
189
|
+
key = fh.read()
|
|
190
|
+
except FileNotFoundError:
|
|
191
|
+
key = secrets.token_bytes(32)
|
|
192
|
+
try:
|
|
193
|
+
fd = os.open(LEASE_KEY_PATH, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
194
|
+
with os.fdopen(fd, "wb") as fh:
|
|
195
|
+
fh.write(key)
|
|
196
|
+
except FileExistsError:
|
|
197
|
+
with open(LEASE_KEY_PATH, "rb") as fh:
|
|
198
|
+
key = fh.read()
|
|
199
|
+
if len(key) < 32:
|
|
200
|
+
raise RuntimeError("lease.key je prekratak")
|
|
201
|
+
try:
|
|
202
|
+
os.chmod(LEASE_KEY_PATH, 0o600)
|
|
203
|
+
except OSError:
|
|
204
|
+
pass
|
|
205
|
+
return key
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def genome_for(risk, net, timeout_s, substrate):
|
|
209
|
+
ttl = min(max(int(timeout_s) + 5, 10), TTL_MAX)
|
|
210
|
+
if risk == "low":
|
|
211
|
+
fs_read, fs_write = list(BWRAP_ROOTS), ["/tmp"]
|
|
212
|
+
cpu, mem_mb, pids = 0, 0, 0
|
|
213
|
+
elif risk in ("medium", "high"):
|
|
214
|
+
fs_read, fs_write = ["/"], ["/tmp"]
|
|
215
|
+
cpu, mem_mb, pids = 1, 256, 128
|
|
216
|
+
else:
|
|
217
|
+
fs_read, fs_write = ["/"], ["/tmp"]
|
|
218
|
+
cpu, mem_mb, pids = 1, 256, 128
|
|
219
|
+
return {
|
|
220
|
+
"version": 1,
|
|
221
|
+
"risk": risk,
|
|
222
|
+
"substrate": substrate,
|
|
223
|
+
"fs_read": fs_read,
|
|
224
|
+
"fs_write": fs_write,
|
|
225
|
+
"net": bool(net),
|
|
226
|
+
"tools": sorted(TOOLS),
|
|
227
|
+
"cpu": cpu,
|
|
228
|
+
"mem_mb": mem_mb,
|
|
229
|
+
"pids": pids,
|
|
230
|
+
"ttl": ttl,
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def cmd_hash(cmd):
|
|
235
|
+
return sha256_hex(cmd.encode("utf-8"))
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def mint_lease(genome, risk, cmd, now=None):
|
|
239
|
+
now = int(time.time() if now is None else now)
|
|
240
|
+
payload = {
|
|
241
|
+
"v": 1,
|
|
242
|
+
"lease_id": "pl_" + secrets.token_hex(12),
|
|
243
|
+
"risk": risk,
|
|
244
|
+
"genome": genome,
|
|
245
|
+
"genome_hash": sha256_hex(canon(genome)),
|
|
246
|
+
"cmd_hash": cmd_hash(cmd),
|
|
247
|
+
"issued_at": now,
|
|
248
|
+
"expires_at": now + int(genome["ttl"]),
|
|
249
|
+
"nonce": secrets.token_hex(16),
|
|
250
|
+
}
|
|
251
|
+
key = load_lease_key()
|
|
252
|
+
payload["hmac"] = hmac.new(
|
|
253
|
+
key, canon(payload).encode("utf-8"), hashlib.sha256
|
|
254
|
+
).hexdigest()
|
|
255
|
+
return payload
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def verify_lease(lease, genome, risk, cmd, now=None):
|
|
259
|
+
now = int(time.time() if now is None else now)
|
|
260
|
+
if not isinstance(lease, dict):
|
|
261
|
+
return False, "lease nije objekat"
|
|
262
|
+
required = (
|
|
263
|
+
"v", "lease_id", "risk", "genome", "genome_hash", "cmd_hash",
|
|
264
|
+
"issued_at", "expires_at", "nonce", "hmac",
|
|
265
|
+
)
|
|
266
|
+
for field in required:
|
|
267
|
+
if field not in lease:
|
|
268
|
+
return False, "lease nema polje %s" % field
|
|
269
|
+
if lease.get("v") != 1:
|
|
270
|
+
return False, "nepoznata verzija lease-a"
|
|
271
|
+
if not re.match(r"^pl_[0-9a-f]{24}$", str(lease.get("lease_id"))):
|
|
272
|
+
return False, "nevalidan lease_id"
|
|
273
|
+
if lease.get("risk") != risk:
|
|
274
|
+
return False, "lease risk se ne poklapa"
|
|
275
|
+
if lease.get("genome") != genome:
|
|
276
|
+
return False, "lease genom se ne poklapa"
|
|
277
|
+
expected_genome = sha256_hex(canon(genome))
|
|
278
|
+
if not hmac.compare_digest(str(lease.get("genome_hash")), expected_genome):
|
|
279
|
+
return False, "genome_hash se ne poklapa"
|
|
280
|
+
if not hmac.compare_digest(str(lease.get("cmd_hash")), cmd_hash(cmd)):
|
|
281
|
+
return False, "cmd_hash se ne poklapa"
|
|
282
|
+
try:
|
|
283
|
+
issued = int(lease.get("issued_at"))
|
|
284
|
+
expires = int(lease.get("expires_at"))
|
|
285
|
+
ttl = int(genome.get("ttl"))
|
|
286
|
+
except (TypeError, ValueError):
|
|
287
|
+
return False, "nevalidan TTL"
|
|
288
|
+
if expires - issued != ttl or ttl < 1 or ttl > TTL_MAX:
|
|
289
|
+
return False, "nevalidan TTL u lease-u"
|
|
290
|
+
if now < issued - 5:
|
|
291
|
+
return False, "lease jos nije vazeci"
|
|
292
|
+
if now >= expires:
|
|
293
|
+
return False, "lease je istekao (TTL %ds)" % ttl
|
|
294
|
+
signature = str(lease.get("hmac"))
|
|
295
|
+
if not re.match(r"^[0-9a-f]{64}$", signature):
|
|
296
|
+
return False, "nevalidan potpis"
|
|
297
|
+
payload = {k: v for k, v in lease.items() if k != "hmac"}
|
|
298
|
+
expected = hmac.new(
|
|
299
|
+
load_lease_key(), canon(payload).encode("utf-8"), hashlib.sha256
|
|
300
|
+
).hexdigest()
|
|
301
|
+
if not hmac.compare_digest(signature, expected):
|
|
302
|
+
return False, "HMAC potpis nije validan"
|
|
303
|
+
return True, ""
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def parse_args(raw):
|
|
307
|
+
if not isinstance(raw, dict):
|
|
308
|
+
return None, "args moraju biti JSON objekat"
|
|
309
|
+
cmd = raw.get("cmd")
|
|
310
|
+
risk = raw.get("risk")
|
|
311
|
+
if not isinstance(cmd, str) or not cmd.strip():
|
|
312
|
+
return None, "cmd mora biti neprazan string"
|
|
313
|
+
if len(cmd) > CMD_MAX:
|
|
314
|
+
return None, "cmd je predug (max %d)" % CMD_MAX
|
|
315
|
+
if "\x00" in cmd:
|
|
316
|
+
return None, "cmd sadrzi NUL"
|
|
317
|
+
if risk not in ALLOWED_RISKS:
|
|
318
|
+
return None, "nepoznat risk (dozvoljeno: %s)" % ", ".join(ALLOWED_RISKS)
|
|
319
|
+
net = raw.get("net", False)
|
|
320
|
+
if not isinstance(net, bool):
|
|
321
|
+
return None, "net mora biti boolean"
|
|
322
|
+
remote = raw.get("remote", False)
|
|
323
|
+
if not isinstance(remote, bool):
|
|
324
|
+
return None, "remote mora biti boolean"
|
|
325
|
+
timeout_s = raw.get("timeout_s", 20)
|
|
326
|
+
if isinstance(timeout_s, bool) or not isinstance(timeout_s, int):
|
|
327
|
+
return None, "timeout_s mora biti cijeli broj"
|
|
328
|
+
if not 1 <= timeout_s <= TIMEOUT_MAX:
|
|
329
|
+
return None, "timeout_s mora biti 1..%d" % TIMEOUT_MAX
|
|
330
|
+
workdir = raw.get("workdir")
|
|
331
|
+
if workdir is not None:
|
|
332
|
+
if not isinstance(workdir, str) or not workdir.startswith("/"):
|
|
333
|
+
return None, "workdir mora biti apsolutna putanja ili null"
|
|
334
|
+
if ".." in workdir.split("/") or len(workdir) > 256:
|
|
335
|
+
return None, "nevalidan workdir"
|
|
336
|
+
if net and risk != "low":
|
|
337
|
+
return None, "net=true nije dozvoljen za risk=%s (mreza je iskljucena)" % risk
|
|
338
|
+
if remote and risk != "critical":
|
|
339
|
+
return None, "remote=true je dozvoljen samo za risk=critical"
|
|
340
|
+
ok, err = check_tool(cmd)
|
|
341
|
+
if not ok:
|
|
342
|
+
return None, err
|
|
343
|
+
return {
|
|
344
|
+
"cmd": cmd,
|
|
345
|
+
"risk": risk,
|
|
346
|
+
"net": net,
|
|
347
|
+
"remote": remote,
|
|
348
|
+
"timeout_s": timeout_s,
|
|
349
|
+
"workdir": workdir or "/tmp",
|
|
350
|
+
}, ""
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def check_tool(cmd):
|
|
354
|
+
stripped = cmd.lstrip()
|
|
355
|
+
if not stripped:
|
|
356
|
+
return False, "prazna komanda"
|
|
357
|
+
first_char = stripped[0]
|
|
358
|
+
if first_char == "$":
|
|
359
|
+
return False, "komanda ne smije pocinjati promjenljivom"
|
|
360
|
+
match = FIRST_TOKEN_RE.match(cmd)
|
|
361
|
+
if not match:
|
|
362
|
+
if first_char in "({!":
|
|
363
|
+
return True, ""
|
|
364
|
+
return False, "ne mogu odrediti izvrsni program"
|
|
365
|
+
token = match.group(2)
|
|
366
|
+
if token in SHELL_KEYWORDS:
|
|
367
|
+
return True, ""
|
|
368
|
+
base = os.path.basename(token)
|
|
369
|
+
if base not in TOOLS:
|
|
370
|
+
return False, "izvrsni program nije u genome allowlisti: %s" % base[:64]
|
|
371
|
+
return True, ""
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def docker_available():
|
|
375
|
+
return bool(shutil.which("docker")) and os.path.exists("/var/run/docker.sock")
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def resolve_substrate(risk, remote):
|
|
379
|
+
if risk == "low":
|
|
380
|
+
if not shutil.which("bwrap"):
|
|
381
|
+
return None, "bwrap nije instaliran"
|
|
382
|
+
return "bwrap", ""
|
|
383
|
+
if risk == "medium":
|
|
384
|
+
if not docker_available():
|
|
385
|
+
return None, "Docker nije dostupan"
|
|
386
|
+
return "docker-runc", ""
|
|
387
|
+
if risk == "high":
|
|
388
|
+
if shutil.which("runsc") and docker_available():
|
|
389
|
+
return "docker-gvisor", ""
|
|
390
|
+
if HIGH_REMOTE:
|
|
391
|
+
ready, reason = remote_ready()
|
|
392
|
+
if ready:
|
|
393
|
+
return "remote-gvisor", ""
|
|
394
|
+
return None, "remote gVisor nije spreman: %s" % reason
|
|
395
|
+
if not docker_available():
|
|
396
|
+
return None, "Docker nije dostupan"
|
|
397
|
+
if not os.path.isfile(SECCOMP_PATH):
|
|
398
|
+
return None, "seccomp profil nedostaje"
|
|
399
|
+
return "docker-seccomp", ""
|
|
400
|
+
if not remote:
|
|
401
|
+
return None, (
|
|
402
|
+
"critical se odbija lokalno: potreban je remote gVisor; "
|
|
403
|
+
"postavi remote=true uz PROTEAN_REMOTE_HOST (SSH %s:%s)" % (REMOTE_HOST or "?", REMOTE_PORT)
|
|
404
|
+
)
|
|
405
|
+
ready, reason = remote_ready()
|
|
406
|
+
if not ready:
|
|
407
|
+
return None, "remote sandbox nije spreman: %s" % reason
|
|
408
|
+
return "remote-gvisor", ""
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def ssh_base():
|
|
412
|
+
try:
|
|
413
|
+
parent = os.path.dirname(KNOWN_HOSTS)
|
|
414
|
+
if parent:
|
|
415
|
+
os.makedirs(parent, mode=0o700, exist_ok=True)
|
|
416
|
+
except OSError:
|
|
417
|
+
pass
|
|
418
|
+
return [
|
|
419
|
+
"ssh", "-i", REMOTE_KEY, "-p", REMOTE_PORT, "-o", "BatchMode=yes",
|
|
420
|
+
"-o", "ConnectTimeout=6", "-o", "StrictHostKeyChecking=" + SSH_STRICT,
|
|
421
|
+
"-o", "UserKnownHostsFile=" + KNOWN_HOSTS,
|
|
422
|
+
"%s@%s" % (REMOTE_USER, REMOTE_HOST), "--",
|
|
423
|
+
]
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def remote_ready():
|
|
427
|
+
if not REMOTE_HOST:
|
|
428
|
+
return False, "remote host nije konfigurisan (PROTEAN_REMOTE_HOST)"
|
|
429
|
+
if not shutil.which("ssh"):
|
|
430
|
+
return False, "ssh klijent nedostaje"
|
|
431
|
+
if not REMOTE_KEY or not os.path.isfile(REMOTE_KEY):
|
|
432
|
+
return False, "SSH kljuc nedostaje"
|
|
433
|
+
script = (
|
|
434
|
+
"test -e /dev/kvm && command -v runsc >/dev/null 2>&1 && "
|
|
435
|
+
"command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1 && "
|
|
436
|
+
"echo PROTEAN_READY"
|
|
437
|
+
)
|
|
438
|
+
try:
|
|
439
|
+
proc = subprocess.run(
|
|
440
|
+
ssh_base() + [script], capture_output=True, timeout=9, env=CLEAN_ENV
|
|
441
|
+
)
|
|
442
|
+
except subprocess.TimeoutExpired:
|
|
443
|
+
return False, "SSH timeout"
|
|
444
|
+
except OSError as exc:
|
|
445
|
+
return False, "SSH greska: %s" % exc
|
|
446
|
+
out = (proc.stdout or b"").decode("utf-8", "replace")
|
|
447
|
+
if proc.returncode == 0 and "PROTEAN_READY" in out:
|
|
448
|
+
return True, ""
|
|
449
|
+
err = (proc.stderr or b"").decode("utf-8", "replace").strip().splitlines()
|
|
450
|
+
return False, (err[-1] if err else "runsc/KVM nije dostupan")[:160]
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def docker_argv(substrate, workdir, cmd):
|
|
454
|
+
name = "protean-" + secrets.token_hex(12)
|
|
455
|
+
argv = [
|
|
456
|
+
"docker", "run", "--rm", "--name", name, "--network=none",
|
|
457
|
+
"--cap-drop=ALL", "--security-opt=no-new-privileges", "--read-only",
|
|
458
|
+
"--tmpfs", "/tmp:rw,nosuid,nodev,size=32m",
|
|
459
|
+
"--pids-limit", "128", "--memory", "256m", "--memory-swap", "256m",
|
|
460
|
+
"--cpus", "1", "--user", "65534:65534", "-w", workdir,
|
|
461
|
+
]
|
|
462
|
+
if substrate == "docker-gvisor":
|
|
463
|
+
argv.append("--runtime=runsc")
|
|
464
|
+
if substrate == "docker-seccomp":
|
|
465
|
+
argv += ["--security-opt", "seccomp=" + SECCOMP_PATH]
|
|
466
|
+
argv += [IMAGE, "sh", "-c", cmd]
|
|
467
|
+
return name, argv
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def _empty_mask_file():
|
|
471
|
+
"""Prazan regularni fajl za maskiranje (cita se kao ""), lazy + fail-open."""
|
|
472
|
+
try:
|
|
473
|
+
if not os.path.exists(EMPTY_MASK_FILE):
|
|
474
|
+
fd = os.open(EMPTY_MASK_FILE, os.O_WRONLY | os.O_CREAT, 0o644)
|
|
475
|
+
os.close(fd)
|
|
476
|
+
return EMPTY_MASK_FILE
|
|
477
|
+
except OSError:
|
|
478
|
+
return ""
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _in_sandbox(path):
|
|
482
|
+
roots = BWRAP_ROOTS + ("/etc",)
|
|
483
|
+
return any(path == root or path.startswith(root + os.sep) for root in roots)
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def secret_mask_args():
|
|
487
|
+
"""Mask known secrets inside bwrap; fail closed if a mask file is unavailable."""
|
|
488
|
+
out = []
|
|
489
|
+
empty = ""
|
|
490
|
+
for path in SECRET_MASKS:
|
|
491
|
+
if not _in_sandbox(path):
|
|
492
|
+
continue
|
|
493
|
+
try:
|
|
494
|
+
if os.path.isdir(path):
|
|
495
|
+
out += ["--tmpfs", path]
|
|
496
|
+
elif os.path.isfile(path):
|
|
497
|
+
if not empty:
|
|
498
|
+
empty = _empty_mask_file()
|
|
499
|
+
if not empty:
|
|
500
|
+
return None, "mask_unavailable: %s" % path
|
|
501
|
+
out += ["--ro-bind", empty, path]
|
|
502
|
+
except OSError as exc:
|
|
503
|
+
return None, "mask_error: %s" % exc
|
|
504
|
+
return out, None
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def run_local_bwrap(args, timeout_s):
|
|
508
|
+
wd = args["workdir"]
|
|
509
|
+
if not os.path.isdir(wd):
|
|
510
|
+
return {
|
|
511
|
+
"ok": False, "rc": None, "out": "", "err": "workdir ne postoji: %s" % wd,
|
|
512
|
+
"timed_out": False,
|
|
513
|
+
}
|
|
514
|
+
argv = [
|
|
515
|
+
"bwrap", "--die-with-parent", "--new-session",
|
|
516
|
+
"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts",
|
|
517
|
+
"--unshare-cgroup",
|
|
518
|
+
]
|
|
519
|
+
if not args["net"]:
|
|
520
|
+
argv.append("--unshare-net")
|
|
521
|
+
argv += ["--cap-drop", "ALL"]
|
|
522
|
+
for root in BWRAP_ROOTS:
|
|
523
|
+
if os.path.exists(root):
|
|
524
|
+
argv += ["--ro-bind", root, root]
|
|
525
|
+
argv += ["--tmpfs", "/etc"]
|
|
526
|
+
for path in BWRAP_ETC_ALLOW:
|
|
527
|
+
if not os.path.exists(path):
|
|
528
|
+
continue
|
|
529
|
+
parent = os.path.dirname(path)
|
|
530
|
+
while parent and parent != "/etc":
|
|
531
|
+
argv += ["--dir", parent]
|
|
532
|
+
parent = os.path.dirname(parent)
|
|
533
|
+
argv += ["--ro-bind", path, path]
|
|
534
|
+
# Bind only the resolv.conf file (never its parent directory: /run may
|
|
535
|
+
# contain sockets such as docker.sock).
|
|
536
|
+
resolv = "/etc/resolv.conf"
|
|
537
|
+
if os.path.exists(resolv):
|
|
538
|
+
target = os.path.realpath(resolv)
|
|
539
|
+
if os.path.isfile(target):
|
|
540
|
+
argv += ["--ro-bind", target, resolv]
|
|
541
|
+
argv += ["--dev", "/dev", "--proc", "/proc"]
|
|
542
|
+
masks, mask_err = secret_mask_args()
|
|
543
|
+
if mask_err:
|
|
544
|
+
return {
|
|
545
|
+
"ok": False, "rc": None, "out": "", "err": mask_err,
|
|
546
|
+
"timed_out": False,
|
|
547
|
+
}
|
|
548
|
+
argv += masks
|
|
549
|
+
exec_cmd = ["sh", "-c", args["cmd"]]
|
|
550
|
+
prlimit = shutil.which("prlimit")
|
|
551
|
+
if prlimit and any(prlimit.startswith(r + os.sep) for r in BWRAP_ROOTS):
|
|
552
|
+
exec_cmd = [prlimit, "--as=536870912", "--nproc=1024",
|
|
553
|
+
"--core=0", "--"] + exec_cmd
|
|
554
|
+
else:
|
|
555
|
+
exec_cmd = ["sh", "-c",
|
|
556
|
+
'ulimit -v 524288 2>/dev/null; ulimit -c 0 2>/dev/null; exec sh -c "$1"',
|
|
557
|
+
"sh", args["cmd"]]
|
|
558
|
+
argv += [
|
|
559
|
+
"--size", str(BWRAP_TMPFS_SIZE), "--tmpfs", "/tmp", "--clearenv",
|
|
560
|
+
"--setenv", "PATH", PATH_ENV, "--setenv", "HOME", "/tmp",
|
|
561
|
+
"--setenv", "LANG", "C.UTF-8", "--chdir", wd, "--",
|
|
562
|
+
] + exec_cmd
|
|
563
|
+
try:
|
|
564
|
+
rc, raw_out, raw_err, timed_out = run_limited(
|
|
565
|
+
argv, timeout_s, env=CLEAN_ENV
|
|
566
|
+
)
|
|
567
|
+
except OSError as exc:
|
|
568
|
+
return {"ok": False, "rc": None, "out": "", "err": str(exc), "timed_out": False}
|
|
569
|
+
out = raw_out.decode("utf-8", "replace")
|
|
570
|
+
err = raw_err.decode("utf-8", "replace")
|
|
571
|
+
if timed_out:
|
|
572
|
+
err = (err + "\ntimeout (%ds)" % timeout_s).strip()
|
|
573
|
+
return {
|
|
574
|
+
"ok": (not timed_out) and rc == 0, "rc": rc, "out": out,
|
|
575
|
+
"err": err, "timed_out": timed_out,
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def run_local_docker(substrate, args, timeout_s):
|
|
580
|
+
name, argv = docker_argv(substrate, args["workdir"], args["cmd"])
|
|
581
|
+
timed_out = False
|
|
582
|
+
try:
|
|
583
|
+
rc, raw_out, raw_err, timed_out = run_limited(
|
|
584
|
+
argv, timeout_s + 4, env=CLEAN_ENV
|
|
585
|
+
)
|
|
586
|
+
if timed_out:
|
|
587
|
+
subprocess.run(
|
|
588
|
+
["docker", "kill", name], capture_output=True, timeout=8,
|
|
589
|
+
env=CLEAN_ENV,
|
|
590
|
+
)
|
|
591
|
+
except OSError as exc:
|
|
592
|
+
return {"ok": False, "rc": None, "out": "", "err": str(exc), "timed_out": False}
|
|
593
|
+
finally:
|
|
594
|
+
subprocess.run(
|
|
595
|
+
["docker", "rm", "-f", name], capture_output=True, timeout=8,
|
|
596
|
+
env=CLEAN_ENV,
|
|
597
|
+
)
|
|
598
|
+
out = raw_out.decode("utf-8", "replace")
|
|
599
|
+
err = raw_err.decode("utf-8", "replace")
|
|
600
|
+
if timed_out:
|
|
601
|
+
err = (err + "\ntimeout (%ds)" % timeout_s).strip()
|
|
602
|
+
return {
|
|
603
|
+
"ok": (not timed_out) and rc == 0, "rc": rc, "out": out,
|
|
604
|
+
"err": err, "timed_out": timed_out,
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def run_remote_gvisor(args, timeout_s):
|
|
609
|
+
name = "protean-" + secrets.token_hex(12)
|
|
610
|
+
docker_cmd = [
|
|
611
|
+
"docker", "run", "--rm", "--name", name, "--runtime=runsc",
|
|
612
|
+
"--network=none", "--cap-drop=ALL",
|
|
613
|
+
"--security-opt=no-new-privileges", "--read-only",
|
|
614
|
+
"--tmpfs", "/tmp:rw,nosuid,nodev,size=32m", "--pids-limit", "128",
|
|
615
|
+
"--memory", "256m", "--cpus", "1", "--user", "65534:65534",
|
|
616
|
+
"-w", args["workdir"], IMAGE, "sh", "-c", args["cmd"],
|
|
617
|
+
]
|
|
618
|
+
remote_cmd = " ".join(shlex.quote(part) for part in docker_cmd)
|
|
619
|
+
remote_cmd = "timeout -k 2 %d %s" % (timeout_s, remote_cmd)
|
|
620
|
+
timed_out = False
|
|
621
|
+
try:
|
|
622
|
+
rc, raw_out, raw_err, timed_out = run_limited(
|
|
623
|
+
ssh_base() + [remote_cmd], timeout_s + 10, env=CLEAN_ENV
|
|
624
|
+
)
|
|
625
|
+
if timed_out:
|
|
626
|
+
subprocess.run(
|
|
627
|
+
ssh_base() + ["docker kill %s >/dev/null 2>&1 || true" % shlex.quote(name)],
|
|
628
|
+
capture_output=True, timeout=8, env=CLEAN_ENV,
|
|
629
|
+
)
|
|
630
|
+
except OSError as exc:
|
|
631
|
+
return {"ok": False, "rc": None, "out": "", "err": str(exc), "timed_out": False}
|
|
632
|
+
out = raw_out.decode("utf-8", "replace")
|
|
633
|
+
err = raw_err.decode("utf-8", "replace")
|
|
634
|
+
if timed_out:
|
|
635
|
+
err = (err + "\nremote timeout (%ds)" % timeout_s).strip()
|
|
636
|
+
return {
|
|
637
|
+
"ok": (not timed_out) and rc == 0, "rc": rc, "out": out,
|
|
638
|
+
"err": err, "timed_out": timed_out,
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def execute(substrate, args, timeout_s):
|
|
643
|
+
if substrate == "bwrap":
|
|
644
|
+
return run_local_bwrap(args, timeout_s)
|
|
645
|
+
if substrate in ("docker-runc", "docker-seccomp", "docker-gvisor"):
|
|
646
|
+
return run_local_docker(substrate, args, timeout_s)
|
|
647
|
+
if substrate == "remote-gvisor":
|
|
648
|
+
return run_remote_gvisor(args, timeout_s)
|
|
649
|
+
return {"ok": False, "rc": None, "out": "", "err": "nepoznat substrat",
|
|
650
|
+
"timed_out": False}
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
MAX_EVIDENCE_RUNS = 200
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def _prune_evidence():
|
|
657
|
+
try:
|
|
658
|
+
entries = sorted(os.listdir(RUNS_DIR))
|
|
659
|
+
except OSError:
|
|
660
|
+
return
|
|
661
|
+
for name in entries[:-MAX_EVIDENCE_RUNS]:
|
|
662
|
+
shutil.rmtree(os.path.join(RUNS_DIR, name), ignore_errors=True)
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def write_evidence(record):
|
|
666
|
+
os.makedirs(RUNS_DIR, mode=0o700, exist_ok=True)
|
|
667
|
+
_prune_evidence()
|
|
668
|
+
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S.%fZ")
|
|
669
|
+
lease = record.get("lease_id") or "nolease"
|
|
670
|
+
subdir = os.path.join(RUNS_DIR, "%s-%s" % (stamp, lease[-6:]))
|
|
671
|
+
os.makedirs(subdir, mode=0o700, exist_ok=True)
|
|
672
|
+
path = os.path.join(subdir, "evidence.jsonl")
|
|
673
|
+
line = json.dumps(record, ensure_ascii=False, sort_keys=True) + "\n"
|
|
674
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
|
675
|
+
try:
|
|
676
|
+
os.write(fd, line.encode("utf-8"))
|
|
677
|
+
finally:
|
|
678
|
+
os.close(fd)
|
|
679
|
+
return path
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
def denied(reason, **extra):
|
|
683
|
+
payload = {"ok": False, "denied": True, "err": reason}
|
|
684
|
+
payload.update(extra)
|
|
685
|
+
return payload
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
def handle_run(raw):
|
|
689
|
+
started = time.time()
|
|
690
|
+
args, err = parse_args(raw)
|
|
691
|
+
if err:
|
|
692
|
+
return denied(err, stage="args")
|
|
693
|
+
|
|
694
|
+
substrate, reason = resolve_substrate(args["risk"], args["remote"])
|
|
695
|
+
if substrate is None:
|
|
696
|
+
genome = genome_for(args["risk"], args["net"], args["timeout_s"], "deny")
|
|
697
|
+
lease = mint_lease(genome, args["risk"], args["cmd"])
|
|
698
|
+
valid, verr = verify_lease(lease, genome, args["risk"], args["cmd"])
|
|
699
|
+
rec = {
|
|
700
|
+
"ts": datetime.now(timezone.utc).isoformat(),
|
|
701
|
+
"tool": "run", "risk": args["risk"], "remote": args["remote"],
|
|
702
|
+
"net": args["net"], "cmd_sha": cmd_hash(args["cmd"]),
|
|
703
|
+
"genome_hash": lease["genome_hash"], "lease_id": lease["lease_id"],
|
|
704
|
+
"lease_expires_at": lease["expires_at"], "substrate": "deny",
|
|
705
|
+
"ok": False, "ms": round((time.time() - started) * 1000, 3),
|
|
706
|
+
"out_sha": sha256_hex(b""), "rc": None, "timed_out": False,
|
|
707
|
+
"err": (reason if valid else verr)[:300],
|
|
708
|
+
}
|
|
709
|
+
rec["evidence"] = write_evidence(rec)
|
|
710
|
+
return denied(rec["err"], stage="policy", substrate="deny",
|
|
711
|
+
lease_id=lease["lease_id"],
|
|
712
|
+
genome_hash=lease["genome_hash"], evidence=rec["evidence"])
|
|
713
|
+
|
|
714
|
+
genome = genome_for(args["risk"], args["net"], args["timeout_s"], substrate)
|
|
715
|
+
lease = mint_lease(genome, args["risk"], args["cmd"])
|
|
716
|
+
valid, verr = verify_lease(lease, genome, args["risk"], args["cmd"])
|
|
717
|
+
if not valid:
|
|
718
|
+
return denied("lease odbijen prije izvrsenja: %s" % verr, stage="lease",
|
|
719
|
+
substrate=substrate)
|
|
720
|
+
if args["timeout_s"] + 2 > int(genome["ttl"]):
|
|
721
|
+
return denied("timeout_s prelazi TTL lease-a", stage="ttl",
|
|
722
|
+
substrate=substrate)
|
|
723
|
+
|
|
724
|
+
remaining = TOTAL_BUDGET_S - (time.time() - started)
|
|
725
|
+
if remaining < 12.0:
|
|
726
|
+
return denied("vremenski budzet iscrpljen prije izvrsenja",
|
|
727
|
+
stage="budget", substrate=substrate)
|
|
728
|
+
exec_timeout = int(min(args["timeout_s"], max(1.0, remaining - 10.0)))
|
|
729
|
+
result = execute(substrate, args, exec_timeout)
|
|
730
|
+
elapsed_ms = round((time.time() - started) * 1000, 3)
|
|
731
|
+
out_sha = sha256_hex(
|
|
732
|
+
(result["out"] + result["err"]).encode("utf-8", "replace")
|
|
733
|
+
)
|
|
734
|
+
rec = {
|
|
735
|
+
"ts": datetime.now(timezone.utc).isoformat(),
|
|
736
|
+
"tool": "run", "risk": args["risk"], "remote": args["remote"],
|
|
737
|
+
"net": args["net"], "cmd_sha": cmd_hash(args["cmd"]),
|
|
738
|
+
"genome_hash": lease["genome_hash"], "lease_id": lease["lease_id"],
|
|
739
|
+
"lease_expires_at": lease["expires_at"], "substrate": substrate,
|
|
740
|
+
"exec_timeout_s": exec_timeout,
|
|
741
|
+
"ok": bool(result["ok"]), "ms": elapsed_ms, "out_sha": out_sha,
|
|
742
|
+
"rc": result["rc"], "timed_out": bool(result["timed_out"]),
|
|
743
|
+
"err": clip(result["err"], 300),
|
|
744
|
+
}
|
|
745
|
+
rec["evidence"] = write_evidence(rec)
|
|
746
|
+
|
|
747
|
+
payload = {
|
|
748
|
+
"ok": bool(result["ok"]),
|
|
749
|
+
"risk": args["risk"],
|
|
750
|
+
"substrate": substrate,
|
|
751
|
+
"net": args["net"],
|
|
752
|
+
"remote": args["remote"],
|
|
753
|
+
"genome_hash": lease["genome_hash"],
|
|
754
|
+
"lease_id": lease["lease_id"],
|
|
755
|
+
"lease_ttl_s": genome["ttl"],
|
|
756
|
+
"exec_timeout_s": exec_timeout,
|
|
757
|
+
"ms": elapsed_ms,
|
|
758
|
+
"rc": result["rc"],
|
|
759
|
+
"timed_out": bool(result["timed_out"]),
|
|
760
|
+
"out": clip(result["out"]),
|
|
761
|
+
"err": clip(result["err"]),
|
|
762
|
+
"out_sha": out_sha,
|
|
763
|
+
"evidence": rec["evidence"],
|
|
764
|
+
}
|
|
765
|
+
return payload
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
def main(argv):
|
|
769
|
+
tool = argv[1] if len(argv) > 1 else ""
|
|
770
|
+
if tool != "run":
|
|
771
|
+
return emit({"ok": False, "err": "nepoznat alat (ocekivano: run)"})
|
|
772
|
+
try:
|
|
773
|
+
body = sys.stdin.buffer.read(131072).decode("utf-8", "replace")
|
|
774
|
+
raw = json.loads(body or "{}")
|
|
775
|
+
except (ValueError, UnicodeDecodeError) as exc:
|
|
776
|
+
return emit({"ok": False, "err": "nevalidan JSON na stdin: %s" % str(exc)[:120]})
|
|
777
|
+
try:
|
|
778
|
+
return emit(handle_run(raw))
|
|
779
|
+
except Exception as exc: # fail-closed, no traceback on stdout
|
|
780
|
+
sys.stderr.write("protean internal: %s: %s\n" % (type(exc).__name__, exc))
|
|
781
|
+
return emit({
|
|
782
|
+
"ok": False, "denied": True,
|
|
783
|
+
"err": "internal greska: %s" % type(exc).__name__,
|
|
784
|
+
})
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
if __name__ == "__main__":
|
|
788
|
+
sys.exit(main(sys.argv))
|