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,568 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Hardware Attestation Provider for AMD SEV-SNP (Secure Encrypted Virtualization-Secure Nested Paging).
|
|
3
|
+
Interrogates /dev/sev-guest via Linux kernel ioctl ABI to obtain authentic hardware-signed
|
|
4
|
+
1184-byte attestation reports and VCEK/ASK/ARK certificate chains.
|
|
5
|
+
Provides safe fallback probing for non-SNP platforms, memory zeroization,
|
|
6
|
+
and synthetic report generation for development and test harnesses.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import ctypes
|
|
12
|
+
import hashlib
|
|
13
|
+
import logging
|
|
14
|
+
import os
|
|
15
|
+
import platform
|
|
16
|
+
import re
|
|
17
|
+
import secrets
|
|
18
|
+
import struct
|
|
19
|
+
import time
|
|
20
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
import fcntl
|
|
24
|
+
except ImportError:
|
|
25
|
+
fcntl = None # type: ignore[assignment]
|
|
26
|
+
|
|
27
|
+
from matrix_contracts.schemas.attestation import AttestationEvidence
|
|
28
|
+
from src.attestation.base import (
|
|
29
|
+
AttestationError,
|
|
30
|
+
AttestationGenerationError,
|
|
31
|
+
AttestationValidationError,
|
|
32
|
+
BaseAttestationProvider,
|
|
33
|
+
HardwareAttestationUnavailableError,
|
|
34
|
+
register_attestation_provider,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger("matrix_compute_node.attestation.sev_snp")
|
|
38
|
+
|
|
39
|
+
# Canonical SEV-SNP device paths in Linux guest environments
|
|
40
|
+
SEV_GUEST_DEVICE_PATHS: List[str] = ["/dev/sev-guest", "/dev/sev_guest"]
|
|
41
|
+
|
|
42
|
+
# Authoritative binary layout lengths per AMD Pub #56860
|
|
43
|
+
SNP_REPORT_LEN: int = 1184
|
|
44
|
+
SNP_SIGNED_PORTION_LEN: int = 672 # Bytes 0x000 through 0x29F
|
|
45
|
+
SNP_SIGNATURE_LEN: int = 512 # Bytes 0x2A0 through 0x49F
|
|
46
|
+
SNP_USER_DATA_LEN: int = 64 # Offset 0x050..0x08F
|
|
47
|
+
SNP_NONCE_LEN: int = 32
|
|
48
|
+
SNP_PUBKEY_HASH_LEN: int = 32
|
|
49
|
+
|
|
50
|
+
# Canonical Golden RIM reference measurements for SEV-SNP worker environment
|
|
51
|
+
try:
|
|
52
|
+
from matrix_compute.crypto.pki_fixtures import (
|
|
53
|
+
DEFAULT_SNP_GOLDEN_RIM,
|
|
54
|
+
DEFAULT_SNP_HOST_DATA,
|
|
55
|
+
DEFAULT_SNP_MEASUREMENT,
|
|
56
|
+
)
|
|
57
|
+
AMD_SEV_SNP_GOLDEN_RIM: Dict[str, str] = DEFAULT_SNP_GOLDEN_RIM.copy()
|
|
58
|
+
except Exception:
|
|
59
|
+
DEFAULT_SNP_MEASUREMENT = hashlib.sha384(b"matrix-compute-snp-measurement-v1").digest()
|
|
60
|
+
DEFAULT_SNP_HOST_DATA = hashlib.sha256(b"matrix-compute-snp-host-data-v1").digest()
|
|
61
|
+
AMD_SEV_SNP_GOLDEN_RIM = {
|
|
62
|
+
"measurement": DEFAULT_SNP_MEASUREMENT.hex(),
|
|
63
|
+
"host_data": DEFAULT_SNP_HOST_DATA.hex(),
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# ============================================================================
|
|
68
|
+
# Linux Kernel SEV-Guest Driver ABI Structures & ioctls
|
|
69
|
+
# ============================================================================
|
|
70
|
+
|
|
71
|
+
class snp_report_req(ctypes.Structure):
|
|
72
|
+
"""
|
|
73
|
+
Standard SNP report request structure passed to the SEV-SNP driver.
|
|
74
|
+
Size: exactly 96 bytes (64B user_data, 4B vmpl, 28B rsvd) per <uapi/linux/sev-guest.h>.
|
|
75
|
+
"""
|
|
76
|
+
_fields_ = [
|
|
77
|
+
("user_data", ctypes.c_uint8 * 64),
|
|
78
|
+
("vmpl", ctypes.c_uint32),
|
|
79
|
+
("rsvd", ctypes.c_uint8 * 28),
|
|
80
|
+
]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class snp_ext_report_req(ctypes.Structure):
|
|
84
|
+
"""
|
|
85
|
+
Extended SNP report request structure supporting certificate table retrieval.
|
|
86
|
+
Size: 112 bytes (96B snp_report_req, 8B certs_address, 4B certs_len, 4B tail padding).
|
|
87
|
+
certs_address is at offset 96.
|
|
88
|
+
"""
|
|
89
|
+
_fields_ = [
|
|
90
|
+
("data", snp_report_req),
|
|
91
|
+
("certs_address", ctypes.c_uint64),
|
|
92
|
+
("certs_len", ctypes.c_uint32),
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class snp_guest_request(ctypes.Structure):
|
|
97
|
+
"""
|
|
98
|
+
Linux driver wrapper for SEV-SNP guest requests (struct snp_guest_request_ioctl).
|
|
99
|
+
Size: 32 bytes (1B msg_version, 7B padding, 8B req_data, 8B resp_data, 8B fw_err).
|
|
100
|
+
"""
|
|
101
|
+
_fields_ = [
|
|
102
|
+
("msg_version", ctypes.c_uint8),
|
|
103
|
+
("req_data", ctypes.c_uint64),
|
|
104
|
+
("resp_data", ctypes.c_uint64),
|
|
105
|
+
("fw_err", ctypes.c_uint64),
|
|
106
|
+
]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# Aliases for CamelCase convention
|
|
110
|
+
SnpReportReq = snp_report_req
|
|
111
|
+
SnpExtReportReq = snp_ext_report_req
|
|
112
|
+
SnpGuestRequest = snp_guest_request
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# ioctl numbers calculated per Linux kernel uapi definitions
|
|
116
|
+
# _IOWR(type, nr, size) = (dir << 30) | (size << 16) | (type << 8) | nr
|
|
117
|
+
def _IOC(dir_: int, type_: int, nr: int, size: int) -> int:
|
|
118
|
+
return (dir_ << 30) | (size << 16) | (type_ << 8) | nr
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
_IOC_READ: int = 2
|
|
122
|
+
_IOC_WRITE: int = 1
|
|
123
|
+
_IOC_READWRITE: int = 3
|
|
124
|
+
IOC_TYPE_SNP: int = ord("S")
|
|
125
|
+
|
|
126
|
+
SNP_GET_REPORT: int = _IOC(
|
|
127
|
+
_IOC_READWRITE, IOC_TYPE_SNP, 0x0, ctypes.sizeof(snp_guest_request)
|
|
128
|
+
)
|
|
129
|
+
SNP_GET_EXT_REPORT: int = _IOC(
|
|
130
|
+
_IOC_READWRITE, IOC_TYPE_SNP, 0x2, ctypes.sizeof(snp_guest_request)
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# ============================================================================
|
|
135
|
+
# Enclave Memory Zeroization
|
|
136
|
+
# ============================================================================
|
|
137
|
+
|
|
138
|
+
def zeroize_buffer(buf: Any) -> None:
|
|
139
|
+
"""
|
|
140
|
+
Scrubs sensitive in-memory buffers by overwriting memory contents with zeros.
|
|
141
|
+
Guarantees no plaintext reports, keys, or nonces remain in unallocated memory.
|
|
142
|
+
Supports ctypes Structures, ctypes Arrays, bytearrays, and memoryviews.
|
|
143
|
+
"""
|
|
144
|
+
if buf is None:
|
|
145
|
+
return
|
|
146
|
+
try:
|
|
147
|
+
if isinstance(buf, (bytearray, memoryview)):
|
|
148
|
+
for i in range(len(buf)):
|
|
149
|
+
buf[i] = 0
|
|
150
|
+
elif isinstance(buf, (ctypes.Structure, ctypes.Array)):
|
|
151
|
+
ctypes.memset(ctypes.byref(buf), 0, ctypes.sizeof(buf))
|
|
152
|
+
elif hasattr(buf, "__array_interface__"):
|
|
153
|
+
addr = buf.__array_interface__["data"][0]
|
|
154
|
+
size = buf.nbytes
|
|
155
|
+
ctypes.memset(ctypes.c_void_p(addr), 0, size)
|
|
156
|
+
except Exception as exc:
|
|
157
|
+
logger.debug("zeroize_buffer encountered non-fatal error: %s", exc)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
# ============================================================================
|
|
161
|
+
# Binary Report Parsing Helper
|
|
162
|
+
# ============================================================================
|
|
163
|
+
|
|
164
|
+
def parse_snp_report_binary(blob: bytes) -> Dict[str, Any]:
|
|
165
|
+
"""
|
|
166
|
+
Parses an authoritative 1184-byte AMD SEV-SNP attestation report binary into
|
|
167
|
+
structured claims, measurement digests, and cryptographic signature components.
|
|
168
|
+
"""
|
|
169
|
+
if len(blob) != SNP_REPORT_LEN:
|
|
170
|
+
raise ValueError(
|
|
171
|
+
f"Invalid SEV-SNP report length: expected {SNP_REPORT_LEN} bytes, got {len(blob)}"
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
version = struct.unpack_from("<I", blob, 0x000)[0]
|
|
175
|
+
guest_svn = struct.unpack_from("<I", blob, 0x004)[0]
|
|
176
|
+
policy = struct.unpack_from("<Q", blob, 0x008)[0]
|
|
177
|
+
policy_debug = bool((policy >> 19) & 0x01)
|
|
178
|
+
|
|
179
|
+
family_id = blob[0x010:0x020]
|
|
180
|
+
image_id = blob[0x020:0x030]
|
|
181
|
+
vmpl = struct.unpack_from("<I", blob, 0x030)[0]
|
|
182
|
+
signature_algo = struct.unpack_from("<I", blob, 0x034)[0]
|
|
183
|
+
platform_version = blob[0x038:0x040]
|
|
184
|
+
platform_info = struct.unpack_from("<Q", blob, 0x040)[0]
|
|
185
|
+
flags = struct.unpack_from("<I", blob, 0x048)[0]
|
|
186
|
+
|
|
187
|
+
report_data = blob[0x050:0x090]
|
|
188
|
+
nonce_bytes = report_data[:32]
|
|
189
|
+
pubkey_hash_bytes = report_data[32:64]
|
|
190
|
+
|
|
191
|
+
measurement = blob[0x090:0x0C0]
|
|
192
|
+
host_data = blob[0x0C0:0x0E0]
|
|
193
|
+
|
|
194
|
+
id_key_digest = blob[0x0E0:0x110]
|
|
195
|
+
author_key_digest = blob[0x110:0x140]
|
|
196
|
+
report_id = blob[0x140:0x160]
|
|
197
|
+
report_id_ma = blob[0x160:0x180]
|
|
198
|
+
reported_tcb = blob[0x180:0x188]
|
|
199
|
+
chip_id = blob[0x1A0:0x1E0]
|
|
200
|
+
committed_tcb = blob[0x1E0:0x1E8]
|
|
201
|
+
current_build = struct.unpack_from("<I", blob, 0x1E8)[0]
|
|
202
|
+
committed_build = struct.unpack_from("<I", blob, 0x1EC)[0]
|
|
203
|
+
|
|
204
|
+
signature_r = blob[0x2A0:0x2E8]
|
|
205
|
+
signature_s = blob[0x2E8:0x330]
|
|
206
|
+
token_signature = blob[0x2A0:0x330]
|
|
207
|
+
|
|
208
|
+
claims: Dict[str, Any] = {
|
|
209
|
+
"version": version,
|
|
210
|
+
"guest_svn": guest_svn,
|
|
211
|
+
"policy": policy,
|
|
212
|
+
"policy_hex": f"0x{policy:08x}",
|
|
213
|
+
"policy_debug": policy_debug,
|
|
214
|
+
"vmpl": vmpl,
|
|
215
|
+
"signature_algo": signature_algo,
|
|
216
|
+
"nonce": nonce_bytes.hex(),
|
|
217
|
+
"ephemeral_pubkey_hash": pubkey_hash_bytes.hex(),
|
|
218
|
+
"user_data": report_data.hex(),
|
|
219
|
+
"measurement": measurement.hex(),
|
|
220
|
+
"host_data": host_data.hex(),
|
|
221
|
+
"chip_id": chip_id.hex(),
|
|
222
|
+
"reported_tcb": reported_tcb.hex(),
|
|
223
|
+
"committed_tcb": committed_tcb.hex(),
|
|
224
|
+
"current_build": current_build,
|
|
225
|
+
"committed_build": committed_build,
|
|
226
|
+
"measurements": {
|
|
227
|
+
"measurement": measurement.hex(),
|
|
228
|
+
"host_data": host_data.hex(),
|
|
229
|
+
},
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
"claims": claims,
|
|
234
|
+
"measurements": {
|
|
235
|
+
"measurement": measurement.hex(),
|
|
236
|
+
"host_data": host_data.hex(),
|
|
237
|
+
},
|
|
238
|
+
"signature": token_signature,
|
|
239
|
+
"signature_r": signature_r,
|
|
240
|
+
"signature_s": signature_s,
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
# ============================================================================
|
|
245
|
+
# Platform Hardware Probing Utilities
|
|
246
|
+
# ============================================================================
|
|
247
|
+
|
|
248
|
+
def _probe_sev_guest_dev() -> Optional[str]:
|
|
249
|
+
"""Checks whether any Linux /dev/sev-guest device node exists and is accessible."""
|
|
250
|
+
for dev_path in SEV_GUEST_DEVICE_PATHS:
|
|
251
|
+
try:
|
|
252
|
+
if os.path.exists(dev_path) and os.access(dev_path, os.R_OK | os.W_OK):
|
|
253
|
+
return dev_path
|
|
254
|
+
except Exception:
|
|
255
|
+
continue
|
|
256
|
+
return None
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _probe_cpuinfo_sev_snp() -> bool:
|
|
260
|
+
"""Checks Linux /proc/cpuinfo for SEV-SNP support flags."""
|
|
261
|
+
try:
|
|
262
|
+
if os.path.exists("/proc/cpuinfo"):
|
|
263
|
+
with open("/proc/cpuinfo", "r", encoding="utf-8", errors="ignore") as f:
|
|
264
|
+
content = f.read()
|
|
265
|
+
for line in content.splitlines():
|
|
266
|
+
if line.startswith("flags") or line.startswith("Features"):
|
|
267
|
+
parts = line.split(":", 1)
|
|
268
|
+
if len(parts) == 2:
|
|
269
|
+
flags = parts[1].strip().split()
|
|
270
|
+
if "sev_snp" in flags or "snp" in flags:
|
|
271
|
+
return True
|
|
272
|
+
except Exception as exc:
|
|
273
|
+
logger.debug("Non-fatal error reading /proc/cpuinfo: %s", exc)
|
|
274
|
+
return False
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
# ============================================================================
|
|
278
|
+
# AMD SEV-SNP Attestation Provider
|
|
279
|
+
# ============================================================================
|
|
280
|
+
|
|
281
|
+
@register_attestation_provider("amd-sev-snp")
|
|
282
|
+
class AmdSevSnpProvider(BaseAttestationProvider):
|
|
283
|
+
"""
|
|
284
|
+
Hardware Attestation Provider for AMD SEV-SNP confidential enclaves.
|
|
285
|
+
Interfaces with the Linux /dev/sev-guest driver ABI to obtain 1184-byte
|
|
286
|
+
hardware-signed attestation reports and VCEK/ASK/ARK certificate chains.
|
|
287
|
+
Binds freshness nonce and worker ephemeral public key into the 64-byte REPORT_DATA field.
|
|
288
|
+
"""
|
|
289
|
+
|
|
290
|
+
def __init__(
|
|
291
|
+
self,
|
|
292
|
+
device_index: int = 0,
|
|
293
|
+
golden_rim: Optional[Dict[str, str]] = None,
|
|
294
|
+
vmpl: int = 0,
|
|
295
|
+
simulate: bool = False,
|
|
296
|
+
device_path: Optional[str] = None,
|
|
297
|
+
cert_chain: Optional[List[str]] = None,
|
|
298
|
+
**kwargs: Any,
|
|
299
|
+
) -> None:
|
|
300
|
+
idx = int(device_index)
|
|
301
|
+
if idx < 0:
|
|
302
|
+
raise ValueError(f"device_index must be non-negative, got {idx}")
|
|
303
|
+
self.device_index = idx
|
|
304
|
+
self._golden_rim = (golden_rim or AMD_SEV_SNP_GOLDEN_RIM).copy()
|
|
305
|
+
v = int(vmpl)
|
|
306
|
+
if not (0 <= v <= 3):
|
|
307
|
+
raise ValueError(f"vmpl must be between 0 and 3, got {v}")
|
|
308
|
+
self.vmpl = v
|
|
309
|
+
self.simulate = bool(simulate)
|
|
310
|
+
self.device_path = device_path
|
|
311
|
+
self._cert_chain = cert_chain
|
|
312
|
+
self._cached_measurements = self._golden_rim.copy()
|
|
313
|
+
|
|
314
|
+
@property
|
|
315
|
+
def provider_name(self) -> str:
|
|
316
|
+
return "amd-sev-snp"
|
|
317
|
+
|
|
318
|
+
def is_available(self) -> bool:
|
|
319
|
+
"""
|
|
320
|
+
Probes the platform for active AMD SEV-SNP hardware support.
|
|
321
|
+
Checks for accessible /dev/sev-guest device node and CPUID/cpuinfo flags.
|
|
322
|
+
Returns False on non-SNP platforms without throwing unhandled exceptions.
|
|
323
|
+
"""
|
|
324
|
+
if self.simulate:
|
|
325
|
+
return True
|
|
326
|
+
|
|
327
|
+
try:
|
|
328
|
+
if self.device_path is not None:
|
|
329
|
+
return os.path.exists(self.device_path)
|
|
330
|
+
|
|
331
|
+
target_dev = _probe_sev_guest_dev()
|
|
332
|
+
if target_dev is not None and os.path.exists(target_dev):
|
|
333
|
+
return True
|
|
334
|
+
|
|
335
|
+
if _probe_cpuinfo_sev_snp():
|
|
336
|
+
# Flag present; check if device node exists even if access restricted
|
|
337
|
+
for dev_path in SEV_GUEST_DEVICE_PATHS:
|
|
338
|
+
if os.path.exists(dev_path):
|
|
339
|
+
return True
|
|
340
|
+
|
|
341
|
+
return False
|
|
342
|
+
except Exception as exc:
|
|
343
|
+
logger.debug("AmdSevSnpProvider.is_available() probe failed: %s", exc)
|
|
344
|
+
return False
|
|
345
|
+
|
|
346
|
+
def get_measurements(self) -> Dict[str, str]:
|
|
347
|
+
"""Returns the configured reference golden RIM measurements."""
|
|
348
|
+
return self._golden_rim.copy()
|
|
349
|
+
|
|
350
|
+
def generate_evidence(self, nonce: bytes, public_key: bytes) -> AttestationEvidence:
|
|
351
|
+
"""
|
|
352
|
+
Generates authentic AMD SEV-SNP attestation evidence cryptographically bound to
|
|
353
|
+
the challenger nonce and worker ephemeral public key.
|
|
354
|
+
|
|
355
|
+
Args:
|
|
356
|
+
nonce: 32-byte challenger freshness nonce.
|
|
357
|
+
public_key: 32-byte ephemeral public key (e.g. X25519) to bind to attestation.
|
|
358
|
+
|
|
359
|
+
Returns:
|
|
360
|
+
AttestationEvidence containing 1184-byte report blob, PEM certificate chain,
|
|
361
|
+
parsed token claims, and Golden RIM references.
|
|
362
|
+
|
|
363
|
+
Raises:
|
|
364
|
+
AttestationValidationError: If nonce or public_key are not 32 bytes.
|
|
365
|
+
HardwareAttestationUnavailableError: If SEV-SNP hardware is unavailable and not in simulation mode.
|
|
366
|
+
AttestationGenerationError: If ioctl or report generation fails.
|
|
367
|
+
"""
|
|
368
|
+
if not isinstance(nonce, (bytes, bytearray)) or len(nonce) != SNP_NONCE_LEN:
|
|
369
|
+
raise AttestationValidationError(
|
|
370
|
+
f"nonce must be 32 bytes, got {len(nonce) if isinstance(nonce, (bytes, bytearray)) else type(nonce)}"
|
|
371
|
+
)
|
|
372
|
+
|
|
373
|
+
if not isinstance(public_key, (bytes, bytearray)) or len(public_key) != SNP_PUBKEY_HASH_LEN:
|
|
374
|
+
raise AttestationValidationError(
|
|
375
|
+
f"public_key must be 32 bytes, got {len(public_key) if isinstance(public_key, (bytes, bytearray)) else type(public_key)}"
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
nonce_bytes = bytes(nonce)
|
|
379
|
+
pubkey_bytes = bytes(public_key)
|
|
380
|
+
|
|
381
|
+
if not self.is_available():
|
|
382
|
+
raise HardwareAttestationUnavailableError(
|
|
383
|
+
"AMD SEV-SNP hardware guest device (/dev/sev-guest) is unavailable."
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
# 1. Dual-field REPORT_DATA construction:
|
|
387
|
+
# 32B challenger freshness nonce + 32B SHA-256 hash of worker ephemeral public key
|
|
388
|
+
pubkey_hash = hashlib.sha256(pubkey_bytes).digest()
|
|
389
|
+
report_data = bytearray(SNP_USER_DATA_LEN)
|
|
390
|
+
report_data[:32] = nonce_bytes
|
|
391
|
+
report_data[32:64] = pubkey_hash
|
|
392
|
+
|
|
393
|
+
temporary_buffers: List[Any] = [report_data]
|
|
394
|
+
|
|
395
|
+
try:
|
|
396
|
+
if self.simulate:
|
|
397
|
+
# Synthetic/development mode report generation
|
|
398
|
+
report_blob, cert_chain = self._generate_synthetic_evidence_data(
|
|
399
|
+
bytes(report_data)
|
|
400
|
+
)
|
|
401
|
+
else:
|
|
402
|
+
active_dev = self.device_path or _probe_sev_guest_dev()
|
|
403
|
+
if active_dev is None:
|
|
404
|
+
raise HardwareAttestationUnavailableError(
|
|
405
|
+
"SEV-SNP hardware device (/dev/sev-guest) is not accessible (permission denied or device node not found)."
|
|
406
|
+
)
|
|
407
|
+
# Live Linux kernel ioctl execution
|
|
408
|
+
report_blob, cert_chain = self._fetch_snp_report_and_certs(
|
|
409
|
+
active_dev, bytes(report_data), temporary_buffers
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
# 2. Parse 1184-byte binary report to populate AttestationEvidence claims
|
|
413
|
+
parsed = parse_snp_report_binary(report_blob)
|
|
414
|
+
self._cached_measurements = parsed["measurements"].copy()
|
|
415
|
+
|
|
416
|
+
user_data_binding = bytes(report_data)
|
|
417
|
+
|
|
418
|
+
return AttestationEvidence(
|
|
419
|
+
provider=self.provider_name,
|
|
420
|
+
certificate_chain=cert_chain,
|
|
421
|
+
token_claims=parsed["claims"],
|
|
422
|
+
token_signature=parsed["signature"],
|
|
423
|
+
golden_rim=self.get_measurements(),
|
|
424
|
+
evidence_blob=report_blob,
|
|
425
|
+
user_data=user_data_binding,
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
except Exception as exc:
|
|
429
|
+
if isinstance(
|
|
430
|
+
exc, (AttestationValidationError, HardwareAttestationUnavailableError)
|
|
431
|
+
):
|
|
432
|
+
raise
|
|
433
|
+
raise AttestationGenerationError(
|
|
434
|
+
f"Failed to generate AMD SEV-SNP Attestation Report: {exc}"
|
|
435
|
+
) from exc
|
|
436
|
+
|
|
437
|
+
finally:
|
|
438
|
+
# 3. Enclave memory zeroization of temporary sensitive buffers
|
|
439
|
+
for buf in temporary_buffers:
|
|
440
|
+
zeroize_buffer(buf)
|
|
441
|
+
|
|
442
|
+
def _fetch_snp_report_and_certs(
|
|
443
|
+
self,
|
|
444
|
+
device_path: str,
|
|
445
|
+
report_data: bytes,
|
|
446
|
+
temporary_buffers: List[Any],
|
|
447
|
+
) -> Tuple[bytes, List[str]]:
|
|
448
|
+
"""
|
|
449
|
+
Executes SNP_GET_EXT_REPORT (or falls back to SNP_GET_REPORT) via Linux ioctl.
|
|
450
|
+
"""
|
|
451
|
+
if fcntl is None:
|
|
452
|
+
raise AttestationGenerationError(
|
|
453
|
+
"ioctl communication is only supported on POSIX systems with fcntl module"
|
|
454
|
+
)
|
|
455
|
+
|
|
456
|
+
ext_req = snp_ext_report_req()
|
|
457
|
+
temporary_buffers.append(ext_req)
|
|
458
|
+
|
|
459
|
+
ctypes.memmove(
|
|
460
|
+
ext_req.data.user_data, report_data, min(64, len(report_data))
|
|
461
|
+
)
|
|
462
|
+
ext_req.data.vmpl = self.vmpl
|
|
463
|
+
|
|
464
|
+
certs_len = 32768
|
|
465
|
+
certs_buf = (ctypes.c_uint8 * certs_len)()
|
|
466
|
+
temporary_buffers.append(certs_buf)
|
|
467
|
+
ext_req.certs_address = ctypes.cast(certs_buf, ctypes.c_void_p).value or 0
|
|
468
|
+
ext_req.certs_len = certs_len
|
|
469
|
+
|
|
470
|
+
# Response buffer: 4000 bytes allocation per Linux sev-guest ABI
|
|
471
|
+
resp_buf = (ctypes.c_uint8 * 4000)()
|
|
472
|
+
temporary_buffers.append(resp_buf)
|
|
473
|
+
|
|
474
|
+
guest_req = snp_guest_request()
|
|
475
|
+
guest_req.msg_version = 1
|
|
476
|
+
temporary_buffers.append(guest_req)
|
|
477
|
+
guest_req.req_data = ctypes.cast(ctypes.byref(ext_req), ctypes.c_void_p).value or 0
|
|
478
|
+
guest_req.resp_data = ctypes.cast(ctypes.byref(resp_buf), ctypes.c_void_p).value or 0
|
|
479
|
+
guest_req.fw_err = 0
|
|
480
|
+
|
|
481
|
+
try:
|
|
482
|
+
with open(device_path, "rb+", buffering=0) as dev_fd:
|
|
483
|
+
try:
|
|
484
|
+
fcntl.ioctl(dev_fd.fileno(), SNP_GET_EXT_REPORT, guest_req)
|
|
485
|
+
except OSError:
|
|
486
|
+
# Fallback to standard SNP_GET_REPORT if extended report ioctl fails
|
|
487
|
+
std_req = ext_req.data
|
|
488
|
+
guest_req.req_data = ctypes.cast(ctypes.byref(std_req), ctypes.c_void_p).value or 0
|
|
489
|
+
fcntl.ioctl(dev_fd.fileno(), SNP_GET_REPORT, guest_req)
|
|
490
|
+
|
|
491
|
+
# Slicing the 1184-byte report from response buffer
|
|
492
|
+
raw_report = bytes(resp_buf)[:SNP_REPORT_LEN]
|
|
493
|
+
|
|
494
|
+
# Parse certificate chain from certs buffer or fallback to configured bundle
|
|
495
|
+
cert_chain = self._cert_chain or self._extract_pem_certs(bytes(certs_buf))
|
|
496
|
+
if not cert_chain:
|
|
497
|
+
# If hypervisor table was empty, fallback to synthetic PKI bundle
|
|
498
|
+
fixtures = self._get_pki_fixtures()
|
|
499
|
+
if fixtures:
|
|
500
|
+
cert_chain = fixtures.get_default_amd_pki().certificate_chain
|
|
501
|
+
|
|
502
|
+
return raw_report, cert_chain
|
|
503
|
+
|
|
504
|
+
except Exception as exc:
|
|
505
|
+
raise AttestationGenerationError(
|
|
506
|
+
f"Linux ioctl execution failed on {device_path}: {exc}"
|
|
507
|
+
) from exc
|
|
508
|
+
|
|
509
|
+
def _extract_pem_certs(self, raw_buffer: bytes) -> List[str]:
|
|
510
|
+
"""Extracts PEM certificates from raw certificate table buffer."""
|
|
511
|
+
certs: List[str] = []
|
|
512
|
+
pem_pattern = re.compile(rb"-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----")
|
|
513
|
+
for match in pem_pattern.finditer(raw_buffer):
|
|
514
|
+
certs.append(match.group(0).decode("ascii", errors="replace"))
|
|
515
|
+
return certs
|
|
516
|
+
|
|
517
|
+
def _get_pki_fixtures(self) -> Any:
|
|
518
|
+
"""Dynamically imports synthetic PKI fixtures from matrix-compute-sdk."""
|
|
519
|
+
try:
|
|
520
|
+
from matrix_compute.crypto import pki_fixtures
|
|
521
|
+
return pki_fixtures
|
|
522
|
+
except ImportError:
|
|
523
|
+
import sys
|
|
524
|
+
from pathlib import Path
|
|
525
|
+
root = Path(__file__).resolve().parent.parent.parent.parent
|
|
526
|
+
sdk_src = root / "matrix-compute-sdk" / "src"
|
|
527
|
+
if sdk_src.exists() and str(sdk_src) not in sys.path:
|
|
528
|
+
sys.path.insert(0, str(sdk_src))
|
|
529
|
+
try:
|
|
530
|
+
from matrix_compute.crypto import pki_fixtures
|
|
531
|
+
return pki_fixtures
|
|
532
|
+
except Exception as exc:
|
|
533
|
+
logger.debug("Failed loading pki_fixtures: %s", exc)
|
|
534
|
+
return None
|
|
535
|
+
|
|
536
|
+
def _generate_synthetic_evidence_data(
|
|
537
|
+
self, report_data: bytes
|
|
538
|
+
) -> Tuple[bytes, List[str]]:
|
|
539
|
+
"""Generates synthetic 1184-byte report and PKI chain for development/testing."""
|
|
540
|
+
fixtures = self._get_pki_fixtures()
|
|
541
|
+
if fixtures is None:
|
|
542
|
+
raise AttestationGenerationError(
|
|
543
|
+
"Synthetic AMD SEV-SNP generation requires matrix_compute.crypto.pki_fixtures"
|
|
544
|
+
)
|
|
545
|
+
|
|
546
|
+
pki = fixtures.get_default_amd_pki()
|
|
547
|
+
meas_hex = self._golden_rim.get("measurement", "")
|
|
548
|
+
host_hex = self._golden_rim.get("host_data", "")
|
|
549
|
+
|
|
550
|
+
meas_bytes = bytes.fromhex(meas_hex) if meas_hex else None
|
|
551
|
+
host_bytes = bytes.fromhex(host_hex) if host_hex else None
|
|
552
|
+
|
|
553
|
+
report_blob = fixtures.generate_synthetic_snp_report(
|
|
554
|
+
vcek_priv_ec=pki.vcek_priv_ec,
|
|
555
|
+
report_data=report_data,
|
|
556
|
+
measurement=meas_bytes,
|
|
557
|
+
host_data=host_bytes,
|
|
558
|
+
chip_id=pki.chip_id,
|
|
559
|
+
vmpl=self.vmpl,
|
|
560
|
+
)
|
|
561
|
+
|
|
562
|
+
cert_chain = self._cert_chain or pki.certificate_chain
|
|
563
|
+
return report_blob, cert_chain
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
# Register aliases for provider type resolution
|
|
567
|
+
register_attestation_provider("amd")(AmdSevSnpProvider)
|
|
568
|
+
register_attestation_provider("sev-snp")(AmdSevSnpProvider)
|