matrix-compute-node 0.1.0__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.
- matrix_compute_node-0.1.0.dist-info/LICENSE +190 -0
- matrix_compute_node-0.1.0.dist-info/METADATA +71 -0
- matrix_compute_node-0.1.0.dist-info/RECORD +35 -0
- matrix_compute_node-0.1.0.dist-info/WHEEL +5 -0
- matrix_compute_node-0.1.0.dist-info/entry_points.txt +2 -0
- matrix_compute_node-0.1.0.dist-info/top_level.txt +1 -0
- src/__init__.py +52 -0
- src/attestation/__init__.py +114 -0
- src/attestation/base.py +226 -0
- src/attestation/nvml_attest.py +1000 -0
- src/attestation/sev_snp_attest.py +568 -0
- src/attestation/simulated.py +325 -0
- src/attestation/tdx_attest.py +596 -0
- src/auth/__init__.py +19 -0
- src/auth/hashcash.py +245 -0
- src/auth/l402_gate.py +553 -0
- src/config/__init__.py +4 -0
- src/config/settings.py +730 -0
- src/crypto/__init__.py +4 -0
- src/crypto/signer.py +257 -0
- src/engine/__init__.py +46 -0
- src/engine/compute_core.py +409 -0
- src/engine/enclave_compute.py +587 -0
- src/engine/scheduler.py +213 -0
- src/engine/session_manager.py +563 -0
- src/main.py +224 -0
- src/p2p/__init__.py +5 -0
- src/p2p/servicer.py +893 -0
- src/p2p/tunnel_client.py +604 -0
- src/relay/__init__.py +5 -0
- src/relay/nostr_client.py +266 -0
- src/settings.py +8 -0
- src/test_doubles/__init__.py +5 -0
- src/test_doubles/mock_nostr_relay.py +332 -0
- src/test_doubles/mock_settlement.py +410 -0
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Hardware Attestation Provider for Intel Trust Domain Extensions (TDX).
|
|
3
|
+
Interfaces with the Linux /dev/tdx_guest driver ABI and host QGS daemon via AF_VSOCK
|
|
4
|
+
to obtain authentic, hardware-signed Intel DCAP Quotes (Format v4/v5).
|
|
5
|
+
Provides safe fallback probing for non-TDX platforms, memory zeroization,
|
|
6
|
+
and synthetic quote generation for offline hermetic testing.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import ctypes
|
|
12
|
+
import hashlib
|
|
13
|
+
import logging
|
|
14
|
+
import os
|
|
15
|
+
import secrets
|
|
16
|
+
import socket
|
|
17
|
+
import struct
|
|
18
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
import fcntl
|
|
22
|
+
except ImportError:
|
|
23
|
+
fcntl = None # type: ignore[assignment]
|
|
24
|
+
|
|
25
|
+
from matrix_contracts.schemas.attestation import AttestationEvidence
|
|
26
|
+
from src.attestation.base import (
|
|
27
|
+
AttestationError,
|
|
28
|
+
AttestationGenerationError,
|
|
29
|
+
AttestationValidationError,
|
|
30
|
+
BaseAttestationProvider,
|
|
31
|
+
HardwareAttestationUnavailableError,
|
|
32
|
+
register_attestation_provider,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger("matrix_compute_node.attestation.tdx")
|
|
36
|
+
|
|
37
|
+
# Canonical device nodes and networking constants
|
|
38
|
+
TDX_GUEST_DEV_NODES: List[str] = ["/dev/tdx_guest", "/dev/tdx-guest"]
|
|
39
|
+
TDX_REPORTDATA_LEN: int = 64
|
|
40
|
+
TDREPORT_STRUCT_LEN: int = 1024
|
|
41
|
+
VSOCK_HOST_CID: int = 2
|
|
42
|
+
VSOCK_QGS_PORT: int = 4050
|
|
43
|
+
INTEL_TDX_TEE_TYPE: int = 0x00000081
|
|
44
|
+
|
|
45
|
+
# Linux Kernel TDX guest driver ioctl numbers
|
|
46
|
+
# TDX_CMD_GET_REPORT0 = _IOWR('T', 1, struct tdx_report_req) = 0xC4405401
|
|
47
|
+
TDX_CMD_GET_REPORT0: int = 0xC4405401
|
|
48
|
+
# TDX_CMD_GET_QUOTE = _IOWR('T', 2, struct tdx_quote_req) = 0xC0105402
|
|
49
|
+
TDX_CMD_GET_QUOTE: int = 0xC0105402
|
|
50
|
+
|
|
51
|
+
# Default Golden RIM measurements for Intel TDX worker environment
|
|
52
|
+
DEFAULT_TDX_GOLDEN_RIM: Dict[str, str] = {
|
|
53
|
+
"mrtd": hashlib.sha384(b"matrix-compute-tdx-mrtd-synthetic-v1").hexdigest(),
|
|
54
|
+
"rtmr0": "11223344556677889900aabbccddeeff11223344556677889900aabbccddeeff11223344556677889900aabbccddeeff",
|
|
55
|
+
"rtmr1": "aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899",
|
|
56
|
+
"rtmr2": "99887766554433221100ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100ffeeddccbbaa",
|
|
57
|
+
"rtmr3": "f1e2d3c4b5a60718293a4b5c6d7e8f90f1e2d3c4b5a60718293a4b5c6d7e8f90f1e2d3c4b5a60718293a4b5c6d7e8f90",
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
from matrix_compute.crypto.pki_fixtures import DEFAULT_TDX_GOLDEN_RIM as _SDK_RIM
|
|
62
|
+
DEFAULT_TDX_GOLDEN_RIM = _SDK_RIM.copy()
|
|
63
|
+
except Exception:
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
INTEL_TDX_GOLDEN_RIM: Dict[str, str] = DEFAULT_TDX_GOLDEN_RIM.copy()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# ============================================================================
|
|
70
|
+
# Linux Kernel TDX Guest Driver ABI Structures
|
|
71
|
+
# ============================================================================
|
|
72
|
+
|
|
73
|
+
class tdx_report_req(ctypes.Structure):
|
|
74
|
+
"""
|
|
75
|
+
Standard TDX report request structure per <uapi/linux/tdx-guest.h>.
|
|
76
|
+
Size: exactly 1088 bytes (64 bytes reportdata, 1024 bytes tdreport).
|
|
77
|
+
"""
|
|
78
|
+
_fields_ = [
|
|
79
|
+
("reportdata", ctypes.c_uint8 * 64),
|
|
80
|
+
("tdreport", ctypes.c_uint8 * 1024),
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class tdx_quote_req(ctypes.Structure):
|
|
85
|
+
"""
|
|
86
|
+
Standard TDX quote request structure.
|
|
87
|
+
Size: exactly 16 bytes (8 bytes user buffer pointer, 8 bytes buffer length).
|
|
88
|
+
"""
|
|
89
|
+
_fields_ = [
|
|
90
|
+
("buf", ctypes.c_uint64),
|
|
91
|
+
("len", ctypes.c_uint64),
|
|
92
|
+
]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
TdxReportReq = tdx_report_req
|
|
96
|
+
TdxQuoteReq = tdx_quote_req
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ============================================================================
|
|
100
|
+
# Memory Zeroization
|
|
101
|
+
# ============================================================================
|
|
102
|
+
|
|
103
|
+
def zeroize_buffer(buf: Any) -> None:
|
|
104
|
+
"""Scrubs sensitive in-memory buffers by overwriting memory contents with zeros."""
|
|
105
|
+
if buf is None:
|
|
106
|
+
return
|
|
107
|
+
try:
|
|
108
|
+
if isinstance(buf, (bytearray, memoryview)):
|
|
109
|
+
for i in range(len(buf)):
|
|
110
|
+
buf[i] = 0
|
|
111
|
+
elif isinstance(buf, (ctypes.Structure, ctypes.Array)):
|
|
112
|
+
ctypes.memset(ctypes.byref(buf), 0, ctypes.sizeof(buf))
|
|
113
|
+
elif hasattr(buf, "__array_interface__"):
|
|
114
|
+
addr = buf.__array_interface__["data"][0]
|
|
115
|
+
size = buf.nbytes
|
|
116
|
+
ctypes.memset(ctypes.c_void_p(addr), 0, size)
|
|
117
|
+
except Exception as exc:
|
|
118
|
+
logger.debug("zeroize_buffer encountered non-fatal error: %s", exc)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
# ============================================================================
|
|
122
|
+
# Hardware Probing Utilities
|
|
123
|
+
# ============================================================================
|
|
124
|
+
|
|
125
|
+
def _probe_tdx_guest_dev() -> Optional[str]:
|
|
126
|
+
"""Checks whether any Linux /dev/tdx_guest device node exists and is accessible."""
|
|
127
|
+
for dev_path in TDX_GUEST_DEV_NODES:
|
|
128
|
+
try:
|
|
129
|
+
if os.path.exists(dev_path) and os.access(dev_path, os.R_OK | os.W_OK):
|
|
130
|
+
return dev_path
|
|
131
|
+
except Exception:
|
|
132
|
+
continue
|
|
133
|
+
return None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _probe_cpuinfo_tdx() -> bool:
|
|
137
|
+
"""Checks Linux /proc/cpuinfo for Intel TDX guest support flags."""
|
|
138
|
+
try:
|
|
139
|
+
if os.path.exists("/proc/cpuinfo"):
|
|
140
|
+
with open("/proc/cpuinfo", "r", encoding="utf-8", errors="ignore") as f:
|
|
141
|
+
for line in f:
|
|
142
|
+
if line.startswith("flags") or line.startswith("Features"):
|
|
143
|
+
parts = line.split(":", 1)
|
|
144
|
+
if len(parts) == 2:
|
|
145
|
+
flags = parts[1].strip().split()
|
|
146
|
+
if any(flag in flags for flag in ("tdx_guest", "intel_tdx", "tdx")):
|
|
147
|
+
return True
|
|
148
|
+
except Exception as exc:
|
|
149
|
+
logger.debug("Non-fatal error reading /proc/cpuinfo: %s", exc)
|
|
150
|
+
return False
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _probe_vsock_qgs(timeout: float = 0.2) -> bool:
|
|
154
|
+
"""Probes host Quote Generation Service (QGS) via AF_VSOCK on Host CID 2, Port 4050."""
|
|
155
|
+
if not hasattr(socket, "AF_VSOCK"):
|
|
156
|
+
return False
|
|
157
|
+
try:
|
|
158
|
+
with socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM) as sock:
|
|
159
|
+
sock.settimeout(timeout)
|
|
160
|
+
sock.connect((VSOCK_HOST_CID, VSOCK_QGS_PORT))
|
|
161
|
+
return True
|
|
162
|
+
except Exception:
|
|
163
|
+
return False
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _recv_exact(sock: socket.socket, num_bytes: int) -> bytes:
|
|
167
|
+
"""Reads exactly num_bytes from stream socket, guarding against packet fragmentation."""
|
|
168
|
+
buf = bytearray()
|
|
169
|
+
while len(buf) < num_bytes:
|
|
170
|
+
chunk = sock.recv(min(4096, num_bytes - len(buf)))
|
|
171
|
+
if not chunk:
|
|
172
|
+
raise AttestationGenerationError(
|
|
173
|
+
f"VSOCK connection closed prematurely by QGS: received {len(buf)} of {num_bytes} expected bytes"
|
|
174
|
+
)
|
|
175
|
+
buf.extend(chunk)
|
|
176
|
+
return bytes(buf)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def fetch_quote_vsock(td_report: bytes, timeout: float = 10.0) -> bytes:
|
|
180
|
+
"""
|
|
181
|
+
Transmits TDREPORT to host Quote Generation Service (QGS) daemon via AF_VSOCK.
|
|
182
|
+
Returns the raw binary DCAP Quote.
|
|
183
|
+
"""
|
|
184
|
+
if not hasattr(socket, "AF_VSOCK"):
|
|
185
|
+
raise HardwareAttestationUnavailableError("AF_VSOCK is not supported on this platform")
|
|
186
|
+
|
|
187
|
+
if len(td_report) != TDREPORT_STRUCT_LEN:
|
|
188
|
+
raise AttestationValidationError(
|
|
189
|
+
f"td_report must be exactly {TDREPORT_STRUCT_LEN} bytes, got {len(td_report)}"
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
req_type = 1 # GET_QUOTE_REQ
|
|
193
|
+
req_payload = struct.pack(">I", req_type) + td_report
|
|
194
|
+
req_frame = struct.pack(">I", len(req_payload)) + req_payload
|
|
195
|
+
|
|
196
|
+
try:
|
|
197
|
+
with socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM) as sock:
|
|
198
|
+
sock.settimeout(timeout)
|
|
199
|
+
sock.connect((VSOCK_HOST_CID, VSOCK_QGS_PORT))
|
|
200
|
+
sock.sendall(req_frame)
|
|
201
|
+
|
|
202
|
+
hdr_bytes = _recv_exact(sock, 4)
|
|
203
|
+
resp_len = struct.unpack(">I", hdr_bytes)[0]
|
|
204
|
+
if resp_len < 4:
|
|
205
|
+
raise AttestationGenerationError(f"Malformed QGS response length header: {resp_len}")
|
|
206
|
+
|
|
207
|
+
body_bytes = _recv_exact(sock, resp_len)
|
|
208
|
+
error_code = struct.unpack(">I", body_bytes[:4])[0]
|
|
209
|
+
if error_code != 0:
|
|
210
|
+
raise AttestationGenerationError(
|
|
211
|
+
f"Host QGS daemon returned error status code: 0x{error_code:08X}"
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
quote_bytes = body_bytes[4:]
|
|
215
|
+
if len(quote_bytes) < 636:
|
|
216
|
+
raise AttestationGenerationError(
|
|
217
|
+
f"QGS returned truncated Quote binary ({len(quote_bytes)} bytes; expected >= 636)"
|
|
218
|
+
)
|
|
219
|
+
return quote_bytes
|
|
220
|
+
|
|
221
|
+
except (socket.error, OSError) as exc:
|
|
222
|
+
raise AttestationGenerationError(f"AF_VSOCK communication with host QGS failed: {exc}") from exc
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def parse_tdx_quote_binary(quote_blob: bytes) -> Dict[str, Any]:
|
|
226
|
+
"""Parses raw binary DCAP Quote to extract claims, measurements, and PCK certificate chain."""
|
|
227
|
+
if len(quote_blob) < 636:
|
|
228
|
+
raise AttestationValidationError(
|
|
229
|
+
f"Quote binary too short ({len(quote_blob)} bytes; expected >= 636 bytes)"
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
version, att_key_type, tee_type = struct.unpack_from("<HHI", quote_blob, 0)
|
|
233
|
+
if version not in (4, 5):
|
|
234
|
+
raise AttestationValidationError(f"Unsupported Quote version: {version}")
|
|
235
|
+
|
|
236
|
+
if version == 4:
|
|
237
|
+
body_offset = 48
|
|
238
|
+
body_size = 584
|
|
239
|
+
else:
|
|
240
|
+
if len(quote_blob) < 54:
|
|
241
|
+
raise AttestationValidationError("Truncated Quote v5 body descriptor")
|
|
242
|
+
body_type, body_size = struct.unpack_from("<HI", quote_blob, 48)
|
|
243
|
+
body_offset = 54
|
|
244
|
+
|
|
245
|
+
if len(quote_blob) < body_offset + 584:
|
|
246
|
+
raise AttestationValidationError("Truncated TD Report Body in quote")
|
|
247
|
+
|
|
248
|
+
tdattributes = struct.unpack_from("<Q", quote_blob, body_offset + 120)[0]
|
|
249
|
+
mrtd = quote_blob[body_offset + 136 : body_offset + 184].hex()
|
|
250
|
+
rtmr0 = quote_blob[body_offset + 328 : body_offset + 376].hex()
|
|
251
|
+
rtmr1 = quote_blob[body_offset + 376 : body_offset + 424].hex()
|
|
252
|
+
rtmr2 = quote_blob[body_offset + 424 : body_offset + 472].hex()
|
|
253
|
+
rtmr3 = quote_blob[body_offset + 472 : body_offset + 520].hex()
|
|
254
|
+
reportdata = quote_blob[body_offset + 520 : body_offset + 584]
|
|
255
|
+
|
|
256
|
+
signed_body_len = body_offset + body_size
|
|
257
|
+
sig_offset = signed_body_len + 4
|
|
258
|
+
key_len = 64 if att_key_type == 2 else 96
|
|
259
|
+
quote_sig = quote_blob[sig_offset : sig_offset + key_len]
|
|
260
|
+
|
|
261
|
+
# Extract PEM Certificate Chain from Quote Certification Data
|
|
262
|
+
cert_chain: List[str] = []
|
|
263
|
+
pem_pattern = b"-----BEGIN CERTIFICATE-----"
|
|
264
|
+
if pem_pattern in quote_blob:
|
|
265
|
+
try:
|
|
266
|
+
raw_text = quote_blob.decode("latin1", errors="ignore")
|
|
267
|
+
parts = raw_text.split("-----BEGIN CERTIFICATE-----")
|
|
268
|
+
for p in parts[1:]:
|
|
269
|
+
clean = p.split("-----END CERTIFICATE-----")[0].strip()
|
|
270
|
+
if clean:
|
|
271
|
+
cert_chain.append(f"-----BEGIN CERTIFICATE-----\n{clean}\n-----END CERTIFICATE-----")
|
|
272
|
+
except Exception:
|
|
273
|
+
pass
|
|
274
|
+
|
|
275
|
+
measurements = {
|
|
276
|
+
"mrtd": mrtd,
|
|
277
|
+
"rtmr0": rtmr0,
|
|
278
|
+
"rtmr1": rtmr1,
|
|
279
|
+
"rtmr2": rtmr2,
|
|
280
|
+
"rtmr3": rtmr3,
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
claims = {
|
|
284
|
+
"provider": "intel-tdx",
|
|
285
|
+
"quote_version": version,
|
|
286
|
+
"tee_type": hex(tee_type),
|
|
287
|
+
"nonce": reportdata[:32].hex(),
|
|
288
|
+
"ephemeral_pubkey_hash": reportdata[32:64].hex(),
|
|
289
|
+
"client_pubkey_hash": reportdata[32:64].hex(),
|
|
290
|
+
"user_data": reportdata.hex(),
|
|
291
|
+
"measurements": measurements,
|
|
292
|
+
"tdattributes": tdattributes,
|
|
293
|
+
"debug": bool((tdattributes & 0x01) != 0),
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
return {
|
|
297
|
+
"claims": claims,
|
|
298
|
+
"measurements": measurements,
|
|
299
|
+
"quote_signature": quote_sig,
|
|
300
|
+
"certificate_chain": cert_chain,
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
# ============================================================================
|
|
305
|
+
# Intel TDX Attestation Provider
|
|
306
|
+
# ============================================================================
|
|
307
|
+
|
|
308
|
+
@register_attestation_provider("intel-tdx")
|
|
309
|
+
class IntelTdxProvider(BaseAttestationProvider):
|
|
310
|
+
"""
|
|
311
|
+
Hardware Attestation Provider for Intel Trust Domain Extensions (TDX).
|
|
312
|
+
Interfaces with /dev/tdx_guest and host QGS to produce authentic DCAP Quotes.
|
|
313
|
+
Binds challenger freshness nonce and worker ephemeral public key into the 64-byte REPORTDATA.
|
|
314
|
+
"""
|
|
315
|
+
|
|
316
|
+
def __init__(
|
|
317
|
+
self,
|
|
318
|
+
device_index: int = 0,
|
|
319
|
+
golden_rim: Optional[Dict[str, str]] = None,
|
|
320
|
+
simulate: bool = False,
|
|
321
|
+
device_path: Optional[str] = None,
|
|
322
|
+
cert_chain: Optional[List[str]] = None,
|
|
323
|
+
quote_strategy: str = "auto", # 'auto', 'ioctl', 'vsock'
|
|
324
|
+
quote_version: int = 4,
|
|
325
|
+
binding_mode: str = "dual", # 'dual' or 'sha256_dual'
|
|
326
|
+
**kwargs: Any,
|
|
327
|
+
) -> None:
|
|
328
|
+
idx = int(device_index)
|
|
329
|
+
if idx < 0:
|
|
330
|
+
raise ValueError(f"device_index must be non-negative, got {idx}")
|
|
331
|
+
self.device_index = idx
|
|
332
|
+
self._golden_rim = (golden_rim or INTEL_TDX_GOLDEN_RIM).copy()
|
|
333
|
+
self.simulate = bool(simulate)
|
|
334
|
+
self.device_path = device_path
|
|
335
|
+
self._cert_chain = cert_chain
|
|
336
|
+
self.quote_strategy = quote_strategy.lower().strip()
|
|
337
|
+
self.quote_version = quote_version
|
|
338
|
+
self.binding_mode = binding_mode.lower().strip()
|
|
339
|
+
self._cached_measurements = self._golden_rim.copy()
|
|
340
|
+
|
|
341
|
+
@property
|
|
342
|
+
def provider_name(self) -> str:
|
|
343
|
+
return "intel-tdx"
|
|
344
|
+
|
|
345
|
+
def is_available(self) -> bool:
|
|
346
|
+
"""
|
|
347
|
+
Probes platform for active Intel TDX guest environment.
|
|
348
|
+
Safe on non-TDX hosts (returns False without raising exceptions).
|
|
349
|
+
"""
|
|
350
|
+
if self.simulate:
|
|
351
|
+
return True
|
|
352
|
+
|
|
353
|
+
try:
|
|
354
|
+
if self.device_path is not None:
|
|
355
|
+
return os.path.exists(self.device_path)
|
|
356
|
+
|
|
357
|
+
target_dev = _probe_tdx_guest_dev()
|
|
358
|
+
if target_dev is not None and os.path.exists(target_dev):
|
|
359
|
+
return True
|
|
360
|
+
|
|
361
|
+
if _probe_cpuinfo_tdx():
|
|
362
|
+
for dev_path in TDX_GUEST_DEV_NODES:
|
|
363
|
+
if os.path.exists(dev_path):
|
|
364
|
+
return True
|
|
365
|
+
|
|
366
|
+
if _probe_vsock_qgs(timeout=0.2):
|
|
367
|
+
return True
|
|
368
|
+
|
|
369
|
+
return False
|
|
370
|
+
except Exception as exc:
|
|
371
|
+
logger.debug("IntelTdxProvider.is_available() probe failed: %s", exc)
|
|
372
|
+
return False
|
|
373
|
+
|
|
374
|
+
def get_measurements(self) -> Dict[str, str]:
|
|
375
|
+
"""Returns current MRTD and RTMR0-3 measurements."""
|
|
376
|
+
if self._cached_measurements:
|
|
377
|
+
return self._cached_measurements.copy()
|
|
378
|
+
return self._golden_rim.copy()
|
|
379
|
+
|
|
380
|
+
def generate_evidence(self, nonce: bytes, public_key: bytes) -> AttestationEvidence:
|
|
381
|
+
"""
|
|
382
|
+
Generates authentic Intel TDX Quote bound to challenger nonce and ephemeral public key.
|
|
383
|
+
|
|
384
|
+
Args:
|
|
385
|
+
nonce: 32-byte challenger freshness nonce.
|
|
386
|
+
public_key: 32-byte ephemeral public key (e.g. X25519) to bind to attestation.
|
|
387
|
+
|
|
388
|
+
Returns:
|
|
389
|
+
AttestationEvidence containing DCAP Quote binary, PCK PEM chain, claims, and measurements.
|
|
390
|
+
|
|
391
|
+
Raises:
|
|
392
|
+
AttestationValidationError: If nonce or public_key are not 32 bytes.
|
|
393
|
+
HardwareAttestationUnavailableError: If TDX hardware is unavailable and not in simulation mode.
|
|
394
|
+
AttestationGenerationError: If quote generation fails.
|
|
395
|
+
"""
|
|
396
|
+
if not isinstance(nonce, (bytes, bytearray)) or len(nonce) != 32:
|
|
397
|
+
raise AttestationValidationError(
|
|
398
|
+
f"nonce must be 32 bytes, got {len(nonce) if isinstance(nonce, (bytes, bytearray)) else type(nonce)}"
|
|
399
|
+
)
|
|
400
|
+
|
|
401
|
+
if not isinstance(public_key, (bytes, bytearray)) or len(public_key) != 32:
|
|
402
|
+
raise AttestationValidationError(
|
|
403
|
+
f"public_key must be 32 bytes, got {len(public_key) if isinstance(public_key, (bytes, bytearray)) else type(public_key)}"
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
nonce_bytes = bytes(nonce)
|
|
407
|
+
pubkey_bytes = bytes(public_key)
|
|
408
|
+
|
|
409
|
+
if not self.is_available():
|
|
410
|
+
raise HardwareAttestationUnavailableError(
|
|
411
|
+
"Intel TDX hardware guest environment is unavailable."
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
# 1. 64-byte REPORTDATA construction: 32B nonce + 32B SHA-256(public_key)
|
|
415
|
+
pubkey_hash = hashlib.sha256(pubkey_bytes).digest()
|
|
416
|
+
report_data = bytearray(TDX_REPORTDATA_LEN)
|
|
417
|
+
if self.binding_mode == "sha256_dual":
|
|
418
|
+
report_data[:32] = hashlib.sha256(nonce_bytes).digest()
|
|
419
|
+
else:
|
|
420
|
+
report_data[:32] = nonce_bytes
|
|
421
|
+
report_data[32:64] = pubkey_hash
|
|
422
|
+
|
|
423
|
+
temporary_buffers: List[Any] = [report_data]
|
|
424
|
+
|
|
425
|
+
try:
|
|
426
|
+
if self.simulate:
|
|
427
|
+
quote_blob, cert_chain = self._generate_synthetic_evidence_data(
|
|
428
|
+
bytes(report_data), nonce_bytes, pubkey_bytes
|
|
429
|
+
)
|
|
430
|
+
else:
|
|
431
|
+
quote_blob, cert_chain = self._fetch_td_quote(
|
|
432
|
+
bytes(report_data), temporary_buffers
|
|
433
|
+
)
|
|
434
|
+
|
|
435
|
+
# 2. Parse binary Quote to extract claims and measurements
|
|
436
|
+
parsed = parse_tdx_quote_binary(quote_blob)
|
|
437
|
+
self._cached_measurements = parsed["measurements"].copy()
|
|
438
|
+
if cert_chain:
|
|
439
|
+
parsed["certificate_chain"] = cert_chain
|
|
440
|
+
|
|
441
|
+
# Ensure client/worker pubkey hash alignment in claims
|
|
442
|
+
parsed["claims"]["client_pubkey_hash"] = pubkey_hash.hex()
|
|
443
|
+
parsed["claims"]["ephemeral_pubkey_hash"] = pubkey_hash.hex()
|
|
444
|
+
parsed["claims"]["nonce"] = nonce_bytes.hex()
|
|
445
|
+
|
|
446
|
+
return AttestationEvidence(
|
|
447
|
+
provider=self.provider_name,
|
|
448
|
+
certificate_chain=parsed["certificate_chain"],
|
|
449
|
+
token_claims=parsed["claims"],
|
|
450
|
+
token_signature=parsed["quote_signature"],
|
|
451
|
+
golden_rim=self.get_measurements(),
|
|
452
|
+
evidence_blob=quote_blob,
|
|
453
|
+
user_data=bytes(report_data),
|
|
454
|
+
)
|
|
455
|
+
|
|
456
|
+
except Exception as exc:
|
|
457
|
+
if isinstance(exc, (AttestationValidationError, HardwareAttestationUnavailableError)):
|
|
458
|
+
raise
|
|
459
|
+
raise AttestationGenerationError(f"Failed to generate Intel TDX Quote: {exc}") from exc
|
|
460
|
+
|
|
461
|
+
finally:
|
|
462
|
+
for buf in temporary_buffers:
|
|
463
|
+
zeroize_buffer(buf)
|
|
464
|
+
|
|
465
|
+
def _fetch_td_quote(self, report_data: bytes, temporary_buffers: List[Any]) -> Tuple[bytes, List[str]]:
|
|
466
|
+
"""Dispatches quote generation to ioctl or AF_VSOCK according to quote_strategy."""
|
|
467
|
+
active_dev = self.device_path or _probe_tdx_guest_dev()
|
|
468
|
+
if active_dev is None and self.quote_strategy in ("auto", "ioctl"):
|
|
469
|
+
raise HardwareAttestationUnavailableError(
|
|
470
|
+
f"No accessible TDX guest device node found among {TDX_GUEST_DEV_NODES}"
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
# Strategy: ioctl
|
|
474
|
+
if self.quote_strategy in ("auto", "ioctl") and active_dev is not None:
|
|
475
|
+
try:
|
|
476
|
+
quote_blob = self._get_quote_ioctl(active_dev, report_data, temporary_buffers)
|
|
477
|
+
return quote_blob, self._cert_chain or []
|
|
478
|
+
except Exception as exc:
|
|
479
|
+
if self.quote_strategy == "ioctl":
|
|
480
|
+
raise AttestationGenerationError(f"ioctl quote generation failed: {exc}") from exc
|
|
481
|
+
logger.debug("TDX_CMD_GET_QUOTE failed, falling back to AF_VSOCK QGS: %s", exc)
|
|
482
|
+
|
|
483
|
+
# Strategy: vsock
|
|
484
|
+
if self.quote_strategy in ("auto", "vsock"):
|
|
485
|
+
if active_dev is None:
|
|
486
|
+
raise HardwareAttestationUnavailableError("TDX device node missing for TDREPORT0 generation")
|
|
487
|
+
td_report = self._get_td_report0_ioctl(active_dev, report_data, temporary_buffers)
|
|
488
|
+
quote_blob = self._get_quote_vsock(td_report)
|
|
489
|
+
return quote_blob, self._cert_chain or []
|
|
490
|
+
|
|
491
|
+
raise AttestationGenerationError(f"Unsupported quote strategy: {self.quote_strategy}")
|
|
492
|
+
|
|
493
|
+
def _get_td_report0_ioctl(self, dev_path: str, report_data: bytes, temporary_buffers: List[Any]) -> bytes:
|
|
494
|
+
"""Invokes TDX_CMD_GET_REPORT0 ioctl on dev_path to retrieve the 1024-byte TDREPORT0."""
|
|
495
|
+
if fcntl is None:
|
|
496
|
+
raise AttestationGenerationError("fcntl module is only available on POSIX systems")
|
|
497
|
+
|
|
498
|
+
req = tdx_report_req()
|
|
499
|
+
temporary_buffers.append(req)
|
|
500
|
+
ctypes.memmove(req.reportdata, report_data, min(64, len(report_data)))
|
|
501
|
+
|
|
502
|
+
try:
|
|
503
|
+
with open(dev_path, "r+b", buffering=0) as fd:
|
|
504
|
+
fcntl.ioctl(fd.fileno(), TDX_CMD_GET_REPORT0, req)
|
|
505
|
+
except OSError as exc:
|
|
506
|
+
raise AttestationGenerationError(f"TDX_CMD_GET_REPORT0 ioctl failed on {dev_path}: {exc}") from exc
|
|
507
|
+
|
|
508
|
+
return bytes(req.tdreport)
|
|
509
|
+
|
|
510
|
+
def _get_quote_ioctl(self, dev_path: str, report_data: bytes, temporary_buffers: List[Any]) -> bytes:
|
|
511
|
+
"""Invokes TDX_CMD_GET_QUOTE ioctl when supported by driver."""
|
|
512
|
+
if fcntl is None:
|
|
513
|
+
raise AttestationGenerationError("fcntl module is only available on POSIX systems")
|
|
514
|
+
|
|
515
|
+
td_report = self._get_td_report0_ioctl(dev_path, report_data, temporary_buffers)
|
|
516
|
+
|
|
517
|
+
quote_buf_len = 8192
|
|
518
|
+
out_buf = (ctypes.c_uint8 * quote_buf_len)()
|
|
519
|
+
temporary_buffers.append(out_buf)
|
|
520
|
+
|
|
521
|
+
ctypes.memmove(out_buf, td_report, len(td_report))
|
|
522
|
+
|
|
523
|
+
req = tdx_quote_req()
|
|
524
|
+
temporary_buffers.append(req)
|
|
525
|
+
req.buf = ctypes.cast(out_buf, ctypes.c_void_p).value or 0
|
|
526
|
+
req.len = quote_buf_len
|
|
527
|
+
|
|
528
|
+
try:
|
|
529
|
+
with open(dev_path, "r+b", buffering=0) as fd:
|
|
530
|
+
fcntl.ioctl(fd.fileno(), TDX_CMD_GET_QUOTE, req)
|
|
531
|
+
return bytes(out_buf)[:req.len]
|
|
532
|
+
except OSError as exc:
|
|
533
|
+
raise AttestationGenerationError(f"TDX_CMD_GET_QUOTE ioctl failed: {exc}") from exc
|
|
534
|
+
|
|
535
|
+
def _get_quote_vsock(self, td_report: bytes) -> bytes:
|
|
536
|
+
"""Transmits TDREPORT to host Quote Generation Service (QGS) daemon via AF_VSOCK."""
|
|
537
|
+
return fetch_quote_vsock(td_report)
|
|
538
|
+
|
|
539
|
+
def _get_pki_fixtures(self) -> Any:
|
|
540
|
+
"""Dynamically imports synthetic PKI fixtures from matrix-compute-sdk."""
|
|
541
|
+
try:
|
|
542
|
+
from matrix_compute.crypto import pki_fixtures
|
|
543
|
+
return pki_fixtures
|
|
544
|
+
except ImportError:
|
|
545
|
+
import sys
|
|
546
|
+
from pathlib import Path
|
|
547
|
+
root = Path(__file__).resolve().parent.parent.parent.parent
|
|
548
|
+
sdk_src = root / "matrix-compute-sdk" / "src"
|
|
549
|
+
if sdk_src.exists() and str(sdk_src) not in sys.path:
|
|
550
|
+
sys.path.insert(0, str(sdk_src))
|
|
551
|
+
try:
|
|
552
|
+
from matrix_compute.crypto import pki_fixtures
|
|
553
|
+
return pki_fixtures
|
|
554
|
+
except Exception as exc:
|
|
555
|
+
logger.debug("Failed loading pki_fixtures: %s", exc)
|
|
556
|
+
return None
|
|
557
|
+
|
|
558
|
+
def _generate_synthetic_evidence_data(
|
|
559
|
+
self, report_data: bytes, nonce: bytes, public_key: bytes
|
|
560
|
+
) -> Tuple[bytes, List[str]]:
|
|
561
|
+
"""Generates authentic synthetic Quote and PKI chain for offline hermetic testing."""
|
|
562
|
+
fixtures = self._get_pki_fixtures()
|
|
563
|
+
if fixtures is None:
|
|
564
|
+
raise AttestationGenerationError(
|
|
565
|
+
"Synthetic Intel TDX generation requires matrix_compute.crypto.pki_fixtures"
|
|
566
|
+
)
|
|
567
|
+
|
|
568
|
+
pki = fixtures.get_default_intel_pki()
|
|
569
|
+
|
|
570
|
+
mrtd_bytes = bytes.fromhex(self._golden_rim.get("mrtd", "")) if "mrtd" in self._golden_rim else None
|
|
571
|
+
rtmr0_bytes = bytes.fromhex(self._golden_rim.get("rtmr0", "")) if "rtmr0" in self._golden_rim else None
|
|
572
|
+
rtmr1_bytes = bytes.fromhex(self._golden_rim.get("rtmr1", "")) if "rtmr1" in self._golden_rim else None
|
|
573
|
+
rtmr2_bytes = bytes.fromhex(self._golden_rim.get("rtmr2", "")) if "rtmr2" in self._golden_rim else None
|
|
574
|
+
rtmr3_bytes = bytes.fromhex(self._golden_rim.get("rtmr3", "")) if "rtmr3" in self._golden_rim else None
|
|
575
|
+
|
|
576
|
+
quote_blob = fixtures.generate_synthetic_tdx_quote(
|
|
577
|
+
pki=pki,
|
|
578
|
+
quote_version=self.quote_version,
|
|
579
|
+
nonce=nonce,
|
|
580
|
+
worker_ephemeral_pubkey=public_key,
|
|
581
|
+
report_data=report_data,
|
|
582
|
+
debug=False,
|
|
583
|
+
mrtd=mrtd_bytes,
|
|
584
|
+
rtmr0=rtmr0_bytes,
|
|
585
|
+
rtmr1=rtmr1_bytes,
|
|
586
|
+
rtmr2=rtmr2_bytes,
|
|
587
|
+
rtmr3=rtmr3_bytes,
|
|
588
|
+
)
|
|
589
|
+
|
|
590
|
+
cert_chain = self._cert_chain or pki.certificate_chain
|
|
591
|
+
return quote_blob, cert_chain
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
# Register aliases for provider type resolution
|
|
595
|
+
register_attestation_provider("tdx")(IntelTdxProvider)
|
|
596
|
+
register_attestation_provider("intel")(IntelTdxProvider)
|
src/auth/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""L402 Authentication, Hashcash PoW, and Pre-Allocation Gate subsystem."""
|
|
2
|
+
|
|
3
|
+
from src.auth.hashcash import (
|
|
4
|
+
HashcashVerifier,
|
|
5
|
+
count_leading_zero_bits,
|
|
6
|
+
solve_hashcash,
|
|
7
|
+
verify_hashcash,
|
|
8
|
+
verify_hashcash_with_reason,
|
|
9
|
+
)
|
|
10
|
+
from src.auth.l402_gate import L402PreAllocationGate
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"L402PreAllocationGate",
|
|
14
|
+
"HashcashVerifier",
|
|
15
|
+
"count_leading_zero_bits",
|
|
16
|
+
"solve_hashcash",
|
|
17
|
+
"verify_hashcash",
|
|
18
|
+
"verify_hashcash_with_reason",
|
|
19
|
+
]
|