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.
@@ -0,0 +1,325 @@
1
+ """
2
+ Simulated Attestation Provider and Synthetic PKI Generator.
3
+ Produces authentic X.509 certificate chains, nonce/pubkey token claims,
4
+ and Golden RIM reference digests for hermetic 100% offline environments.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from datetime import datetime, timedelta, timezone
10
+ import hashlib
11
+ import json
12
+ import logging
13
+ import secrets
14
+ import time
15
+ from typing import Any, Dict, List, Optional, Tuple
16
+
17
+ from cryptography import x509
18
+ from cryptography.hazmat.primitives import hashes, serialization
19
+ from cryptography.hazmat.primitives.asymmetric import ec
20
+ from cryptography.x509.oid import NameOID
21
+
22
+ from matrix_contracts.schemas.attestation import AttestationEvidence
23
+ from src.attestation.base import (
24
+ BaseAttestationProvider,
25
+ AttestationValidationError,
26
+ register_attestation_provider,
27
+ )
28
+
29
+ logger = logging.getLogger("matrix_compute_node.attestation.simulated")
30
+
31
+ DEFAULT_SIMULATED_MEASUREMENTS: Dict[str, str] = {
32
+ "vbios_digest": "4a7d1ed414474e4033ac29ccb8653d9b12c6a0c5c3d2ec3b6a07e2c9497e5d2f",
33
+ "driver_digest": "782356c891048efd429a1b327b87561f95c028a213e8b4e74982a0349ef821cd",
34
+ "runtime_digest": "d348b64e5264b4c798e3b2e95a98762f0123456789abcdef0123456789abcdef",
35
+ }
36
+
37
+
38
+ class SyntheticPKICertificateBundle:
39
+ """Holds a generated 3-tier X.509 certificate chain and private keys."""
40
+
41
+ def __init__(
42
+ self,
43
+ root_cert_pem: str,
44
+ intermediate_cert_pem: str,
45
+ leaf_cert_pem: str,
46
+ leaf_private_key: ec.EllipticCurvePrivateKey,
47
+ ) -> None:
48
+ self.root_cert_pem = root_cert_pem
49
+ self.intermediate_cert_pem = intermediate_cert_pem
50
+ self.leaf_cert_pem = leaf_cert_pem
51
+ self.leaf_private_key = leaf_private_key
52
+
53
+ @property
54
+ def certificate_chain(self) -> List[str]:
55
+ return [self.leaf_cert_pem, self.intermediate_cert_pem, self.root_cert_pem]
56
+
57
+
58
+ def generate_synthetic_pki(
59
+ expired: bool = False,
60
+ untrusted: bool = False,
61
+ ) -> SyntheticPKICertificateBundle:
62
+ """
63
+ Generates a 3-tier X.509 certificate chain using ECDSA SECP256R1:
64
+ Root CA -> Intermediate CA -> Leaf Attestation Certificate.
65
+ """
66
+ now = datetime.now(timezone.utc)
67
+ if expired:
68
+ valid_from = now - timedelta(days=60)
69
+ valid_to = now - timedelta(days=1)
70
+ else:
71
+ valid_from = now - timedelta(days=1)
72
+ valid_to = now + timedelta(days=365)
73
+
74
+ # 1. Root CA
75
+ root_key = ec.generate_private_key(ec.SECP256R1())
76
+ root_org = "Untrusted Rogue CA" if untrusted else "DistributedMatrixMultiply Root Authority"
77
+ root_name = x509.Name([
78
+ x509.NameAttribute(NameOID.COUNTRY_NAME, "US"),
79
+ x509.NameAttribute(NameOID.ORGANIZATION_NAME, root_org),
80
+ x509.NameAttribute(NameOID.COMMON_NAME, "Simulated Hardware Root CA"),
81
+ ])
82
+ root_cert = (
83
+ x509.CertificateBuilder()
84
+ .subject_name(root_name)
85
+ .issuer_name(root_name)
86
+ .public_key(root_key.public_key())
87
+ .serial_number(x509.random_serial_number())
88
+ .not_valid_before(valid_from)
89
+ .not_valid_after(valid_to)
90
+ .add_extension(
91
+ x509.BasicConstraints(ca=True, path_length=None),
92
+ critical=True,
93
+ )
94
+ .add_extension(
95
+ x509.KeyUsage(
96
+ digital_signature=True,
97
+ content_commitment=False,
98
+ key_encipherment=False,
99
+ data_encipherment=False,
100
+ key_agreement=False,
101
+ key_cert_sign=True,
102
+ crl_sign=True,
103
+ encipher_only=False,
104
+ decipher_only=False,
105
+ ),
106
+ critical=True,
107
+ )
108
+ .add_extension(
109
+ x509.SubjectKeyIdentifier.from_public_key(root_key.public_key()),
110
+ critical=False,
111
+ )
112
+ .sign(root_key, hashes.SHA256())
113
+ )
114
+
115
+ # 2. Intermediate CA
116
+ inter_key = ec.generate_private_key(ec.SECP256R1())
117
+ inter_name = x509.Name([
118
+ x509.NameAttribute(NameOID.COUNTRY_NAME, "US"),
119
+ x509.NameAttribute(NameOID.ORGANIZATION_NAME, "DistributedMatrixMultiply TEE"),
120
+ x509.NameAttribute(NameOID.COMMON_NAME, "Simulated NVIDIA Hopper Attestation Intermediate CA"),
121
+ ])
122
+ inter_cert = (
123
+ x509.CertificateBuilder()
124
+ .subject_name(inter_name)
125
+ .issuer_name(root_name)
126
+ .public_key(inter_key.public_key())
127
+ .serial_number(x509.random_serial_number())
128
+ .not_valid_before(valid_from)
129
+ .not_valid_after(valid_to)
130
+ .add_extension(
131
+ x509.BasicConstraints(ca=True, path_length=0),
132
+ critical=True,
133
+ )
134
+ .add_extension(
135
+ x509.KeyUsage(
136
+ digital_signature=True,
137
+ content_commitment=False,
138
+ key_encipherment=False,
139
+ data_encipherment=False,
140
+ key_agreement=False,
141
+ key_cert_sign=True,
142
+ crl_sign=True,
143
+ encipher_only=False,
144
+ decipher_only=False,
145
+ ),
146
+ critical=True,
147
+ )
148
+ .add_extension(
149
+ x509.SubjectKeyIdentifier.from_public_key(inter_key.public_key()),
150
+ critical=False,
151
+ )
152
+ .add_extension(
153
+ x509.AuthorityKeyIdentifier.from_issuer_public_key(root_key.public_key()),
154
+ critical=False,
155
+ )
156
+ .sign(root_key, hashes.SHA256())
157
+ )
158
+
159
+ # 3. Leaf Attestation Certificate
160
+ leaf_key = ec.generate_private_key(ec.SECP256R1())
161
+ leaf_name = x509.Name([
162
+ x509.NameAttribute(NameOID.COUNTRY_NAME, "US"),
163
+ x509.NameAttribute(NameOID.ORGANIZATION_NAME, "DistributedMatrixMultiply Enclave"),
164
+ x509.NameAttribute(NameOID.COMMON_NAME, "Simulated H100 Attestation Leaf"),
165
+ x509.NameAttribute(NameOID.SERIAL_NUMBER, "SIM-H100-ENCLAVE-001"),
166
+ ])
167
+ leaf_cert = (
168
+ x509.CertificateBuilder()
169
+ .subject_name(leaf_name)
170
+ .issuer_name(inter_name)
171
+ .public_key(leaf_key.public_key())
172
+ .serial_number(x509.random_serial_number())
173
+ .not_valid_before(valid_from)
174
+ .not_valid_after(valid_to)
175
+ .add_extension(
176
+ x509.BasicConstraints(ca=False, path_length=None),
177
+ critical=True,
178
+ )
179
+ .add_extension(
180
+ x509.KeyUsage(
181
+ digital_signature=True,
182
+ content_commitment=False,
183
+ key_encipherment=False,
184
+ data_encipherment=False,
185
+ key_agreement=True,
186
+ key_cert_sign=False,
187
+ crl_sign=False,
188
+ encipher_only=False,
189
+ decipher_only=False,
190
+ ),
191
+ critical=True,
192
+ )
193
+ .add_extension(
194
+ x509.SubjectKeyIdentifier.from_public_key(leaf_key.public_key()),
195
+ critical=False,
196
+ )
197
+ .add_extension(
198
+ x509.AuthorityKeyIdentifier.from_issuer_public_key(inter_key.public_key()),
199
+ critical=False,
200
+ )
201
+ .sign(inter_key, hashes.SHA256())
202
+ )
203
+
204
+ root_pem = root_cert.public_bytes(serialization.Encoding.PEM).decode("utf-8")
205
+ inter_pem = inter_cert.public_bytes(serialization.Encoding.PEM).decode("utf-8")
206
+ leaf_pem = leaf_cert.public_bytes(serialization.Encoding.PEM).decode("utf-8")
207
+
208
+ return SyntheticPKICertificateBundle(
209
+ root_cert_pem=root_pem,
210
+ intermediate_cert_pem=inter_pem,
211
+ leaf_cert_pem=leaf_pem,
212
+ leaf_private_key=leaf_key,
213
+ )
214
+
215
+
216
+ @register_attestation_provider("simulated-cca")
217
+ @register_attestation_provider("simulated")
218
+ class SimulatedAttestationProvider(BaseAttestationProvider):
219
+ """
220
+ Simulated Hardware Attestation Provider for offline development and hermetic testing.
221
+ Generates authentic synthetic X.509 cert chains, nonce/pubkey bindings, and Golden RIM.
222
+ Supports fault-injection parameters for testing adversarial scenarios.
223
+ """
224
+
225
+ def __init__(
226
+ self,
227
+ golden_rim: Optional[Dict[str, str]] = None,
228
+ measurements: Optional[Dict[str, str]] = None,
229
+ tamper_signature: bool = False,
230
+ tamper_measurements: bool = False,
231
+ tamper_nonce: bool = False,
232
+ expired_cert: bool = False,
233
+ untrusted_ca: bool = False,
234
+ fixed_timestamp: Optional[int] = None,
235
+ pki_bundle: Optional[SyntheticPKICertificateBundle] = None,
236
+ **kwargs: Any,
237
+ ) -> None:
238
+ self._golden_rim = (golden_rim or DEFAULT_SIMULATED_MEASUREMENTS).copy()
239
+ self._measurements = (measurements or self._golden_rim).copy()
240
+ self.tamper_signature = tamper_signature
241
+ self.tamper_measurements = tamper_measurements
242
+ self.tamper_nonce = tamper_nonce
243
+ self.expired_cert = expired_cert
244
+ self.untrusted_ca = untrusted_ca
245
+ self.fixed_timestamp = fixed_timestamp
246
+
247
+ # Generate or use injected PKI bundle
248
+ self.pki_bundle = pki_bundle or generate_synthetic_pki(
249
+ expired=self.expired_cert,
250
+ untrusted=self.untrusted_ca,
251
+ )
252
+
253
+ @property
254
+ def provider_name(self) -> str:
255
+ return "simulated-cca"
256
+
257
+ def is_available(self) -> bool:
258
+ """Simulated provider is always operational offline."""
259
+ return True
260
+
261
+ def get_measurements(self) -> Dict[str, str]:
262
+ return self._measurements.copy()
263
+
264
+ def generate_evidence(self, nonce: bytes, public_key: bytes) -> AttestationEvidence:
265
+ """
266
+ Generates authentic synthetic attestation evidence.
267
+ Binds challenger nonce and ephemeral public key.
268
+ """
269
+ if not isinstance(nonce, (bytes, bytearray)) or len(nonce) != 32:
270
+ raise AttestationValidationError(
271
+ f"nonce must be 32 bytes, got {len(nonce) if isinstance(nonce, (bytes, bytearray)) else type(nonce)}"
272
+ )
273
+
274
+ if not isinstance(public_key, (bytes, bytearray)) or len(public_key) != 32:
275
+ raise AttestationValidationError(
276
+ f"public_key must be 32 bytes, got {len(public_key) if isinstance(public_key, (bytes, bytearray)) else type(public_key)}"
277
+ )
278
+
279
+ nonce_bytes = bytes(nonce)
280
+ pubkey_bytes = bytes(public_key)
281
+
282
+ # Apply fault injection if requested
283
+ if self.tamper_nonce:
284
+ nonce_bytes = bytes([(b ^ 0xFF) for b in nonce_bytes])
285
+
286
+ measurements = self._measurements.copy()
287
+ if self.tamper_measurements:
288
+ measurements["runtime_digest"] = "bad0" * 16
289
+
290
+ pubkey_hash = hashlib.sha256(pubkey_bytes).hexdigest()
291
+ user_data = hashlib.sha256(nonce_bytes + pubkey_bytes).digest()
292
+
293
+ ts = self.fixed_timestamp if self.fixed_timestamp is not None else int(time.time())
294
+
295
+ token_claims = {
296
+ "provider": self.provider_name,
297
+ "nonce": nonce_bytes.hex(),
298
+ "ephemeral_pubkey_hash": pubkey_hash,
299
+ "public_key": pubkey_bytes.hex(),
300
+ "timestamp": ts,
301
+ "security_version": 1,
302
+ "measurements": measurements,
303
+ "gpu_model": "NVIDIA H100 80GB HBM3 (Simulated CC)",
304
+ "cc_mode": True,
305
+ }
306
+
307
+ # Canonical claims serialization for signing
308
+ claims_bytes = json.dumps(token_claims, sort_keys=True, separators=(",", ":")).encode("utf-8")
309
+
310
+ # Sign using Leaf certificate private key
311
+ sig = self.pki_bundle.leaf_private_key.sign(claims_bytes, ec.ECDSA(hashes.SHA256()))
312
+ if self.tamper_signature:
313
+ sig = bytes([(b ^ 0xAA) for b in sig])
314
+
315
+ evidence_blob = b"SIMULATED_NVIDIA_CCA_QUOTE_V1:" + user_data
316
+
317
+ return AttestationEvidence(
318
+ provider=self.provider_name,
319
+ certificate_chain=self.pki_bundle.certificate_chain,
320
+ token_claims=token_claims,
321
+ token_signature=sig,
322
+ golden_rim=self._golden_rim.copy(),
323
+ evidence_blob=evidence_blob,
324
+ user_data=user_data,
325
+ )