Files
iishko-sandbox/broker.py
T

462 lines
18 KiB
Python

#!/usr/bin/env python3
"""iishko sandbox broker.
Routes iishko user jobs into disposable Offense sandboxes (offense.sh hosted infra).
Nothing runs on the iishko VPS: the broker only makes outbound HTTPS calls to
https://app.offense.sh and never executes user code itself.
Guarantees:
* no local execution - only JSON goes out, findings come back
* no repo/file upload - /api/v1/scans (gzip upload) is never called
* target deny-list - our own hosts and private IPs are refused
* instruction screening - credentials-looking strings are refused
* hard budget caps - per job and per key per day
* balance floor - refuses work when workspace credit is low
* response sanitisation - cookies/tokens/passwords are redacted
* audit log without payloads - sha256 of instruction, never the text
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
HERE = os.path.dirname(os.path.abspath(__file__))
CFG_PATH = os.path.join(HERE, "config.json")
STATE_DIR = os.path.join(HERE, "state")
os.makedirs(STATE_DIR, exist_ok=True)
CFG = json.load(open(CFG_PATH, encoding="utf-8"))
REDACT = [
(re.compile(r"(?i)(set-cookie\s*:\s*)[^\r\n]+"), r"\1<redacted>"),
(re.compile(r"(?i)\b(password|passwd|secret|token|api[_-]?key)\b(\s*[:=]\s*)[^\s,;\"'}]+"), r"\1\2<redacted>"),
(re.compile(r"(offense_sk_[A-Za-z0-9]+)"), "<offense-key>"),
(re.compile(r"\b(sk-[A-Za-z0-9._-]{16,}|ck_[A-Za-z0-9]{10,}|nfp_[A-Za-z0-9]+)\b"), "<key>"),
]
PRIVATE_HOST = re.compile(
r"^(localhost|127\.|0\.0\.0\.0|10\.|192\.168\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.|\[?::1\]?$)"
)
class Offense:
def __init__(self, base_url: str, key: str):
self.base = base_url.rstrip("/")
self.key = key
def call(self, path: str, method: str = "GET", body=None, headers=None, timeout=90):
hdrs = {
"authorization": "Bearer " + self.key,
"accept": "application/json",
"user-agent": "iishko-sandbox-broker/1.0",
}
data = None
if body is not None:
data = json.dumps(body).encode()
hdrs["content-type"] = "application/json"
if headers:
hdrs.update(headers)
req = urllib.request.Request(self.base + path, data=data, headers=hdrs, method=method)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
raw = r.read().decode("utf-8", "replace")
return r.status, (json.loads(raw) if raw.strip() else {})
except urllib.error.HTTPError as e:
raw = e.read().decode("utf-8", "replace")
try:
parsed = json.loads(raw) if raw.strip() else {}
except Exception:
parsed = {"raw": raw[:400]}
return e.code, parsed
except Exception as e: # network
return 0, {"error": "network", "message": type(e).__name__}
# --- workspace state -------------------------------------------------
def whoami(self):
return self.call("/api/v1/whoami", timeout=30)
def target(self):
return self.call("/api/v1/targets", timeout=30)
def register_target(self, target_url: str, project: str):
return self.call("/api/v1/targets", "POST", {"target": target_url, "project": project})
def verify_target(self, target_id: str):
return self.call("/api/v1/targets/%s/verify" % urllib.parse.quote(target_id), "POST", {}, timeout=120)
def launch(self, budget: int, instruction: str, model: str, idem: str):
return self.call(
"/api/v1/assessments",
"POST",
{"budgetMicros": int(budget), "instruction": instruction[:2000], "model": model},
headers={"idempotency-key": idem},
)
def assessment(self, aid: str):
return self.call("/api/v1/assessments/" + urllib.parse.quote(aid), timeout=40)
def findings(self, aid: str):
return self.call("/api/v1/assessments/%s/findings" % urllib.parse.quote(aid), timeout=60)
def usage(self, aid: str):
return self.call("/api/v1/assessments/%s/usage" % urllib.parse.quote(aid), timeout=60)
def cancel(self, aid: str):
return self.call("/api/v1/assessments/%s/cancel" % urllib.parse.quote(aid), "POST", {}, timeout=60)
def load_pools():
"""Workspace pool. One Offense workspace holds one target, so per-user isolation
means one workspace (key) per user/slot; jobs are serialised inside a slot."""
path = os.path.join(HERE, "pools.json")
if os.path.exists(path):
pools = json.load(open(path, encoding="utf-8"))
out = []
for i, p in enumerate(pools):
key = p.get("key") or ""
if not key and p.get("key_file"):
kf = p["key_file"]
if not os.path.isabs(kf):
kf = os.path.join(HERE, kf)
key = open(kf, encoding="utf-8").read().strip()
if key:
out.append({"name": p.get("name") or "pool%d" % i, "key": key, "lock": threading.Lock()})
return out
kf = CFG.get("key_file", "offense_key.txt")
if not os.path.isabs(kf):
kf = os.path.join(HERE, kf)
return [{"name": "default", "key": open(kf, encoding="utf-8").read().strip(), "lock": threading.Lock()}]
def load_user_keys():
path = os.path.join(HERE, "keys.json")
if not os.path.exists(path):
return {}
data = json.load(open(path, encoding="utf-8"))
keys = {}
for item in data if isinstance(data, list) else data.get("keys", []):
tok = item.get("token") or ""
if tok:
keys[hashlib.sha256(tok.encode()).hexdigest()] = {
"name": item.get("name") or "user",
"daily_micros": int(item.get("daily_micros") or CFG["default_budget_micros"] * 10),
"pool": item.get("pool") or "default",
"enabled": bool(item.get("enabled", True)),
}
return keys
POOLS = load_pools()
POOL_BY_NAME = {p["name"]: p for p in POOLS}
USER_KEYS = load_user_keys()
JOBS = {} # id -> job dict
JOBS_LOCK = threading.Lock()
AUDIT = os.path.join(STATE_DIR, "audit.jsonl")
def audit(rec: dict):
rec["ts"] = int(time.time())
with open(AUDIT, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
def today_spend(key_id: str) -> int:
day = time.strftime("%Y-%m-%d")
total = 0
with JOBS_LOCK:
for j in JOBS.values():
if j["key_id"] == key_id and j["day"] == day:
total += int(j.get("spent_micros") or 0)
return total
def sanitize(obj):
if isinstance(obj, str):
s = obj
for rx, repl in REDACT:
s = rx.sub(repl, s)
return s
if isinstance(obj, list):
return [sanitize(x) for x in obj]
if isinstance(obj, dict):
out = {}
for k, v in obj.items():
if k.lower() in ("password", "passwd", "secret", "cookie", "authorization", "set-cookie", "session"):
out[k] = "<redacted>"
else:
out[k] = sanitize(v)
return out
return obj
def target_reject_reason(url: str):
try:
u = urllib.parse.urlparse(url)
except Exception:
return "bad_url"
if u.scheme != "https":
return "https_only"
host = (u.hostname or "").lower()
if not host or PRIVATE_HOST.match(host) or "." not in host:
return "private_or_local_host"
for d in CFG.get("deny_target_hosts", []):
if host == d or host.endswith("." + d):
return "denied_host"
return None
def instruction_reject_reason(text: str):
for pat in CFG.get("forbidden_instruction_patterns", []):
if re.search(pat, text, re.I):
return "credential_material_in_instruction"
return None
class Handler(BaseHTTPRequestHandler):
server_version = "iishko-sandbox/1.0"
def log_message(self, fmt, *args):
pass
# -- helpers ----------------------------------------------------------
def send_json(self, code: int, payload: dict):
body = json.dumps(payload, ensure_ascii=False).encode()
self.send_response(code)
self.send_header("content-type", "application/json; charset=utf-8")
self.send_header("content-length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def auth(self):
tok = (self.headers.get("x-sandbox-key") or "").strip()
if not tok:
h = self.headers.get("authorization") or ""
if h.lower().startswith("bearer "):
tok = h[7:].strip()
if not tok:
return None, "missing_key"
rec = USER_KEYS.get(hashlib.sha256(tok.encode()).hexdigest())
if not rec:
return None, "invalid_key"
if not rec["enabled"]:
return None, "disabled"
return (hashlib.sha256(tok.encode()).hexdigest(), rec), None
def body(self):
n = int(self.headers.get("content-length") or 0)
if n <= 0 or n > 64 * 1024:
return None
try:
return json.loads(self.rfile.read(n).decode("utf-8"))
except Exception:
return None
# -- routes -----------------------------------------------------------
def do_GET(self):
p = urllib.parse.urlparse(self.path).path
if p == "/healthz":
info = []
for pool in POOLS:
st, js = Offense(CFG["base_url"], pool["key"]).whoami()
bal = (js.get("workspace") or {}).get("balanceMicros")
info.append({"pool": pool["name"], "http": st, "balance_micros": bal})
return self.send_json(200, {"ok": True, "pools": info, "jobs": len(JOBS)})
key_id, why = self.auth()
if not key_id:
return self.send_json(401, {"error": why})
uid, urec = key_id
if p.startswith("/v1/jobs/"):
jid = p.rsplit("/", 1)[-1]
with JOBS_LOCK:
job = JOBS.get(jid)
if not job or job["key_id"] != uid:
return self.send_json(404, {"error": "not_found"})
return self.send_json(200, public_job(job))
if p == "/v1/jobs":
with JOBS_LOCK:
mine = [public_job(j) for j in JOBS.values() if j["key_id"] == uid]
return self.send_json(200, {"jobs": mine[-50:]})
if p == "/v1/limits":
return self.send_json(
200,
{
"name": urec["name"],
"daily_micros": urec["daily_micros"],
"used_today_micros": today_spend(uid),
"pool": urec["pool"],
},
)
return self.send_json(404, {"error": "not_found"})
def do_POST(self):
p = urllib.parse.urlparse(self.path).path
key_id, why = self.auth()
if not key_id:
return self.send_json(401, {"error": why})
uid, urec = key_id
if p == "/v1/jobs":
return self.create_job(uid, urec)
if p.startswith("/v1/jobs/") and p.endswith("/cancel"):
jid = p.split("/")[3]
with JOBS_LOCK:
job = JOBS.get(jid)
if not job or job["key_id"] != uid:
return self.send_json(404, {"error": "not_found"})
pool = POOL_BY_NAME.get(job["pool"]) or POOLS[0]
st, js = Offense(CFG["base_url"], pool["key"]).cancel(job["offense_id"])
job["status"] = "cancelled"
audit({"ev": "cancel", "job": jid, "http": st})
return self.send_json(200, public_job(job))
return self.send_json(404, {"error": "not_found"})
def create_job(self, uid, urec):
body = self.body()
if not body:
return self.send_json(400, {"error": "bad_json"})
target = (body.get("target") or "").strip()
instruction = (body.get("instruction") or "").strip()
if not target or not instruction:
return self.send_json(400, {"error": "target_and_instruction_required"})
if len(instruction) > 1800:
return self.send_json(400, {"error": "instruction_too_long", "max": 1800})
reason = target_reject_reason(target)
if reason:
audit({"ev": "deny_target", "reason": reason, "host": urllib.parse.urlparse(target).hostname})
return self.send_json(403, {"error": "target_refused", "reason": reason})
reason = instruction_reject_reason(instruction)
if reason:
audit({"ev": "deny_instruction", "reason": reason})
return self.send_json(403, {"error": "instruction_refused", "reason": reason})
budget = int(body.get("budget_micros") or CFG["default_budget_micros"])
budget = max(50_000, min(budget, CFG["max_budget_micros"]))
used = today_spend(uid)
if used + budget > urec["daily_micros"]:
return self.send_json(429, {"error": "daily_quota", "used": used, "limit": urec["daily_micros"]})
with JOBS_LOCK:
running = [j for j in JOBS.values() if j["key_id"] == uid and j["status"] in ("queued", "running")]
if len(running) >= CFG["max_concurrent_per_key"]:
return self.send_json(429, {"error": "busy", "running": len(running)})
pool = POOL_BY_NAME.get(urec["pool"]) or POOLS[0]
api = Offense(CFG["base_url"], pool["key"])
st, js = api.whoami()
bal = (js.get("workspace") or {}).get("balanceMicros")
if st != 200 or bal is None:
return self.send_json(503, {"error": "pool_unavailable", "http": st})
floor = int(CFG["min_balance_micros"])
if int(bal) < max(floor, budget):
return self.send_json(503, {"error": "credit_low", "balance_micros": bal, "need": max(floor, budget)})
with pool["lock"]: # one target per workspace
st, js = api.target()
tgt = ((js.get("targets") or [{}])[0] or {})
cur = (tgt.get("target") or "").rstrip("/")
if cur != target.rstrip("/") or not tgt.get("verified"):
st, js = api.register_target(target, "iishko-user")
if st not in (200, 201):
return self.send_json(502, {"error": "target_register_failed", "http": st,
"detail": sanitize(js).get("message")})
tid = ((js.get("target") or {}).get("id")) or ""
if not tid:
return self.send_json(502, {"error": "target_register_empty"})
st, js = api.verify_target(tid)
if st != 200 or not (js.get("target") or {}).get("verified"):
return self.send_json(409, {
"error": "target_not_verified",
"reason": (js.get("reason") or js.get("error") or "verification_failed"),
"how": "Serve the token at <target>/.well-known/offense-verify.txt, then retry.",
"token": ((tgt.get("verification") or {}).get("token")),
})
idem = "iishko-" + hashlib.sha256((uid + target + instruction + str(time.time())).encode()).hexdigest()[:40]
st, js = api.launch(budget, instruction, (body.get("model") or "").strip(), idem)
if st not in (200, 201):
audit({"ev": "launch_fail", "http": st, "err": (sanitize(js).get("error") or "")[:80]})
return self.send_json(502, {"error": "launch_failed", "http": st,
"detail": sanitize(js).get("message") or sanitize(js).get("error")})
a = js.get("assessment") or js
jid = "job_" + hashlib.sha256(idem.encode()).hexdigest()[:16]
job = {
"id": jid,
"key_id": uid,
"user": urec["name"],
"pool": pool["name"],
"offense_id": a.get("id"),
"target": target,
"instruction_sha256": hashlib.sha256(instruction.encode()).hexdigest(),
"budget_micros": budget,
"spent_micros": 0,
"status": a.get("status") or "queued",
"created": int(time.time()),
"day": time.strftime("%Y-%m-%d"),
"error": None,
}
with JOBS_LOCK:
JOBS[jid] = job
audit({"ev": "launch", "job": jid, "user": urec["name"], "budget": budget,
"target_host": urllib.parse.urlparse(target).hostname,
"instruction_sha256": job["instruction_sha256"]})
threading.Thread(target=poll_job, args=(jid,), daemon=True).start()
return self.send_json(202, public_job(job))
TERMINAL = ("completed", "failed", "cancelled", "canceled", "error")
def poll_job(jid: str):
job = JOBS.get(jid)
if not job:
return
pool = POOL_BY_NAME.get(job["pool"]) or POOLS[0]
api = Offense(CFG["base_url"], pool["key"])
deadline = time.time() + 45 * 60
while time.time() < deadline:
time.sleep(10)
st, js = api.assessment(job["offense_id"])
if st != 200:
continue
a = js.get("assessment") or js
job["status"] = a.get("status") or job["status"]
job["spent_micros"] = int(a.get("spentMicros") or 0)
if str(job["status"]).lower() in TERMINAL:
break
try:
st, f = api.findings(job["offense_id"])
job["findings"] = sanitize(f) if st == 200 else {"error": "findings_unavailable", "http": st}
st, u = api.usage(job["offense_id"])
job["usage"] = sanitize(u) if st == 200 else None
except Exception:
pass
job["finished"] = int(time.time())
audit({"ev": "finish", "job": jid, "status": job["status"], "spent": job["spent_micros"]})
def public_job(job: dict) -> dict:
out = {k: job.get(k) for k in ("id", "user", "status", "target", "budget_micros",
"spent_micros", "created", "finished", "error")}
if job.get("findings"):
out["findings"] = job["findings"]
if job.get("usage"):
out["usage"] = job["usage"]
return out
def main():
if not USER_KEYS:
print("WARNING: keys.json missing/empty - every request will get 401", flush=True)
srv = ThreadingHTTPServer((CFG["listen"], int(CFG["port"])), Handler)
print("broker on http://%s:%s pools=%d keys=%d" % (CFG["listen"], CFG["port"], len(POOLS), len(USER_KEYS)), flush=True)
srv.serve_forever()
if __name__ == "__main__":
main()