|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""dstack -> configfs-tsm shim. |
| 3 | +
|
| 4 | +Serves <dir>/inblob (write report_data, <=64 bytes) and <dir>/outblob (read the |
| 5 | +raw Intel DCAP TDX quote) by forwarding to the dstack guest-agent GetQuote RPC. |
| 6 | +inblob/outblob are FIFOs, so a read of outblob blocks until the quote is ready. |
| 7 | +report_data is forwarded byte-for-byte, so the quote is the genuine hardware |
| 8 | +quote. |
| 9 | +
|
| 10 | +Serves ONE request at a time and supports a SINGLE in-flight requester -- like a |
| 11 | +single configfs-tsm report entry, it cannot correlate concurrent callers. Run one |
| 12 | +shim per app. An empty outblob read means the quote failed. |
| 13 | +
|
| 14 | +Env: TSM_REPORT_DIR (default /run/tsm/report), DSTACK_SOCKET (default |
| 15 | +/var/run/dstack.sock). |
| 16 | +""" |
| 17 | +import errno |
| 18 | +import fcntl |
| 19 | +import http.client |
| 20 | +import json |
| 21 | +import os |
| 22 | +import socket |
| 23 | +import sys |
| 24 | +import time |
| 25 | + |
| 26 | +REPORT_DIR = os.environ.get("TSM_REPORT_DIR", "/run/tsm/report") |
| 27 | +SOCKET = os.environ.get("DSTACK_SOCKET", "/var/run/dstack.sock") |
| 28 | +# How long to wait for the app to open outblob for reading before giving up, so a |
| 29 | +# caller that writes inblob then dies can't wedge the daemon. |
| 30 | +OUTBLOB_DEADLINE = float(os.environ.get("TSM_OUTBLOB_DEADLINE", "30")) |
| 31 | + |
| 32 | + |
| 33 | +def log(msg): |
| 34 | + sys.stderr.write(f"[tsm-shim] {msg}\n") |
| 35 | + sys.stderr.flush() |
| 36 | + |
| 37 | + |
| 38 | +class _UDS(http.client.HTTPConnection): |
| 39 | + """HTTPConnection over an AF_UNIX socket.""" |
| 40 | + |
| 41 | + def __init__(self, path, timeout): |
| 42 | + super().__init__("localhost", timeout=timeout) |
| 43 | + self._path = path |
| 44 | + |
| 45 | + def connect(self): |
| 46 | + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 47 | + self.sock.settimeout(self.timeout) |
| 48 | + self.sock.connect(self._path) |
| 49 | + |
| 50 | + |
| 51 | +def get_quote(report_data, timeout=30): |
| 52 | + conn = _UDS(SOCKET, timeout) |
| 53 | + try: |
| 54 | + conn.request("POST", "/GetQuote", |
| 55 | + body=json.dumps({"report_data": report_data.hex()}), |
| 56 | + headers={"Host": "localhost", "Content-Type": "application/json"}) |
| 57 | + resp = conn.getresponse() |
| 58 | + data = resp.read() |
| 59 | + if resp.status != 200: |
| 60 | + raise RuntimeError(f"guest-agent returned http {resp.status}: {data[:200]!r}") |
| 61 | + quote = json.loads(data).get("quote") |
| 62 | + if not quote: |
| 63 | + raise RuntimeError(f"no quote in response: {data[:200]!r}") |
| 64 | + return bytes.fromhex(quote) |
| 65 | + finally: |
| 66 | + conn.close() |
| 67 | + |
| 68 | + |
| 69 | +def open_write_deadline(path, deadline=30.0): |
| 70 | + """open a FIFO for writing, waiting up to `deadline`s for a reader. |
| 71 | +
|
| 72 | + Returns a blocking fd, or None if no reader showed up -- so a caller that |
| 73 | + writes inblob then dies can't wedge the daemon forever. |
| 74 | + """ |
| 75 | + end = time.monotonic() + deadline |
| 76 | + while True: |
| 77 | + try: |
| 78 | + fd = os.open(path, os.O_WRONLY | os.O_NONBLOCK) |
| 79 | + except OSError as exc: |
| 80 | + if exc.errno == errno.ENXIO and time.monotonic() < end: |
| 81 | + time.sleep(0.05) |
| 82 | + continue |
| 83 | + return None |
| 84 | + fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) & ~os.O_NONBLOCK) |
| 85 | + return fd |
| 86 | + |
| 87 | + |
| 88 | +def make_fifo(path): |
| 89 | + if os.path.lexists(path): |
| 90 | + os.remove(path) |
| 91 | + os.mkfifo(path, 0o600) |
| 92 | + |
| 93 | + |
| 94 | +def main(): |
| 95 | + os.makedirs(REPORT_DIR, exist_ok=True) |
| 96 | + inblob = os.path.join(REPORT_DIR, "inblob") |
| 97 | + outblob = os.path.join(REPORT_DIR, "outblob") |
| 98 | + make_fifo(inblob) |
| 99 | + make_fifo(outblob) |
| 100 | + log(f"ready: {REPORT_DIR} -> {SOCKET}") |
| 101 | + |
| 102 | + while True: |
| 103 | + try: |
| 104 | + with open(inblob, "rb") as f: # blocks until the app writes |
| 105 | + report_data = f.read() |
| 106 | + if not report_data: |
| 107 | + continue |
| 108 | + if len(report_data) > 64: |
| 109 | + # >64 bytes means more than one writer raced on inblob -- fail |
| 110 | + # closed rather than hand back a quote bound to ambiguous data. |
| 111 | + log(f"rejecting inblob: {len(report_data)} bytes (>64); concurrent writers?") |
| 112 | + quote = b"" |
| 113 | + else: |
| 114 | + try: |
| 115 | + quote = get_quote(report_data.ljust(64, b"\0")) |
| 116 | + log(f"quote {len(quote)} bytes, header={quote[:2].hex()}") |
| 117 | + except Exception as exc: |
| 118 | + log(f"getquote failed: {exc}") # deliver empty == failure signal |
| 119 | + quote = b"" |
| 120 | + fd = open_write_deadline(outblob, OUTBLOB_DEADLINE) |
| 121 | + if fd is None: |
| 122 | + log("no reader for outblob within deadline; dropping") |
| 123 | + continue |
| 124 | + with os.fdopen(fd, "wb") as f: |
| 125 | + f.write(quote) |
| 126 | + except Exception as exc: |
| 127 | + log(f"serve loop error: {exc}") |
| 128 | + time.sleep(0.5) |
| 129 | + |
| 130 | + |
| 131 | +if __name__ == "__main__": |
| 132 | + main() |
0 commit comments