#!/usr/bin/env python3 import base64 import ctypes import fcntl import json import os import select import socket import struct import sys from pathlib import Path SOCKET_PATH = os.environ.get("PROGRAMGEN_REFERENCE_ORACLE_SOCKET", '/run/programgen-reference-oracle/oracle.sock') _ENV_ALLOWLIST = {"LANG", "LC_ALL"} _POLICY_DENIED = "programgen policy denied: debugging or wrapping /reference/executable is not allowed\n" _PR_SET_DUMPABLE = 4 _PR_SET_NO_NEW_PRIVS = 38 def _read_exact(sock, size): chunks = [] remaining = size while remaining: chunk = sock.recv(remaining) if not chunk: raise RuntimeError("oracle connection closed early") chunks.append(chunk) remaining -= len(chunk) return b"".join(chunks) def _encode_arg(value): return base64.b64encode(os.fsencode(value)).decode("ascii") def _prctl(option, arg2): try: libc = ctypes.CDLL(None) libc.prctl(option, arg2, 0, 0, 0) except Exception: pass def _has_blocked_loader_environment(): return any( key.startswith("LD_") or key.startswith("DYLD_") for key in os.environ ) def _tracer_pid(): try: for line in Path("/proc/self/status").read_text(errors="replace").splitlines(): if line.startswith("TracerPid:"): return int(line.split(":", 1)[1].strip()) except Exception: return 0 return 0 def _harden_process(): _prctl(_PR_SET_NO_NEW_PRIVS, 1) _prctl(_PR_SET_DUMPABLE, 0) if _has_blocked_loader_environment() or _tracer_pid() > 0: sys.stderr.write(_POLICY_DENIED) return False return True def _read_available_stdin(): try: fd = sys.stdin.buffer.fileno() except (AttributeError, OSError, ValueError): return b"" try: readable, _, _ = select.select([fd], [], [], 0) except (OSError, ValueError): return b"" if not readable: return b"" chunks = [] try: flags = fcntl.fcntl(fd, fcntl.F_GETFL) except OSError: return b"" try: fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) while True: try: chunk = os.read(fd, 65536) except BlockingIOError: break if not chunk: break chunks.append(chunk) finally: try: fcntl.fcntl(fd, fcntl.F_SETFL, flags) except OSError: pass return b"".join(chunks) def main(): if not _harden_process(): return 126 env = { key: value for key, value in os.environ.items() if key in _ENV_ALLOWLIST } request = { "argv_b64": [_encode_arg(arg) for arg in sys.argv], "cwd": os.getcwd(), "env": env, "stdin_b64": base64.b64encode(_read_available_stdin()).decode("ascii"), } payload = json.dumps(request, separators=(",", ":")).encode("utf-8") sock = None try: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(SOCKET_PATH) sock.sendall(struct.pack(">Q", len(payload)) + payload) size = struct.unpack(">Q", _read_exact(sock, 8))[0] response = json.loads(_read_exact(sock, size).decode("utf-8")) except Exception as exc: sys.stderr.write(f"programgen reference oracle unavailable: {exc}\n") return 127 finally: if sock is not None: try: sock.close() except Exception: pass sys.stdout.buffer.write(base64.b64decode(response.get("stdout_b64", ""))) sys.stderr.buffer.write(base64.b64decode(response.get("stderr_b64", ""))) return int(response.get("return_code", 1)) if __name__ == "__main__": raise SystemExit(main())