entropy-protocol 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.
- entropy_protocol/__init__.py +11 -0
- entropy_protocol/_unicode14.py +120 -0
- entropy_protocol/attest.py +62 -0
- entropy_protocol/attested/__init__.py +6 -0
- entropy_protocol/attested/amd.py +221 -0
- entropy_protocol/attested/appraise.py +325 -0
- entropy_protocol/attested/attester.py +58 -0
- entropy_protocol/attested/authority.py +239 -0
- entropy_protocol/attested/azure_cgpu.py +186 -0
- entropy_protocol/attested/binding.py +71 -0
- entropy_protocol/attested/capture.py +109 -0
- entropy_protocol/attested/ear.py +94 -0
- entropy_protocol/attested/enroll.py +119 -0
- entropy_protocol/attested/evidence.py +106 -0
- entropy_protocol/attested/hcl.py +109 -0
- entropy_protocol/attested/nvidia.py +168 -0
- entropy_protocol/attested/ocsp.py +90 -0
- entropy_protocol/attested/pki.py +121 -0
- entropy_protocol/attested/rim.py +130 -0
- entropy_protocol/attested/service.py +242 -0
- entropy_protocol/attested/tpm.py +259 -0
- entropy_protocol/backend_hf.py +439 -0
- entropy_protocol/batch.py +537 -0
- entropy_protocol/calibrate.py +99 -0
- entropy_protocol/canon.py +321 -0
- entropy_protocol/canongen.py +325 -0
- entropy_protocol/cli.py +493 -0
- entropy_protocol/cose.py +260 -0
- entropy_protocol/crypto.py +140 -0
- entropy_protocol/delivery.py +31 -0
- entropy_protocol/detect.py +246 -0
- entropy_protocol/gateway.py +370 -0
- entropy_protocol/hpke.py +105 -0
- entropy_protocol/mcp.py +159 -0
- entropy_protocol/pack.py +217 -0
- entropy_protocol/plain.py +122 -0
- entropy_protocol/predicates.py +37 -0
- entropy_protocol/profiles.py +45 -0
- entropy_protocol/record.py +116 -0
- entropy_protocol/scrapi.py +203 -0
- entropy_protocol/seal.py +232 -0
- entropy_protocol/statements.py +148 -0
- entropy_protocol/stats.py +20 -0
- entropy_protocol/tlog.py +147 -0
- entropy_protocol/ts3161.py +205 -0
- entropy_protocol/typography.py +73 -0
- entropy_protocol/verify.py +232 -0
- entropy_protocol-0.1.0.dist-info/METADATA +255 -0
- entropy_protocol-0.1.0.dist-info/RECORD +54 -0
- entropy_protocol-0.1.0.dist-info/WHEEL +5 -0
- entropy_protocol-0.1.0.dist-info/entry_points.txt +2 -0
- entropy_protocol-0.1.0.dist-info/licenses/LICENSE +201 -0
- entropy_protocol-0.1.0.dist-info/licenses/NOTICE +4 -0
- entropy_protocol-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""The attestation part of an evidence package (`ep1-pack/v2`, ARCHITECTURE §7d) and its offline check.
|
|
2
|
+
|
|
3
|
+
`att` = {"root": the authority's root certificate (DER), "authority": {"rrp_id", "name"},
|
|
4
|
+
"gen" | "det": {"ear": the attestation result, "request": the enrollment request (evidence + CSR),
|
|
5
|
+
"collateral": what the authority fetched (CBOR), "policy": the policy it applied (JSON)}}
|
|
6
|
+
|
|
7
|
+
The check needs no secret and no network. Per attested statement it establishes: the result is signed by the root;
|
|
8
|
+
the statement carries that result's digest and a certificate of the root for the key it is signed under; the
|
|
9
|
+
result affirms exactly that key, for that kind of statement; the result's nonce is the request's handle; and the
|
|
10
|
+
evidence in the request, appraised again here with the same code, the same collateral and the same policy at the
|
|
11
|
+
result's issue time, affirms - from AMD's and NVIDIA's pinned roots, through the hardware reports and the binding
|
|
12
|
+
value, to the certified key. The reader still decides whether the root is the authority's (compare its fingerprint
|
|
13
|
+
with the one the authority publishes) - the package cannot vouch for itself.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import datetime as dt
|
|
18
|
+
import hashlib
|
|
19
|
+
import json
|
|
20
|
+
|
|
21
|
+
from cryptography import x509
|
|
22
|
+
|
|
23
|
+
from .. import cose
|
|
24
|
+
from . import appraise, ear, enroll, pki
|
|
25
|
+
|
|
26
|
+
EAR_REF = "ep1-ear"
|
|
27
|
+
X5CHAIN = 33
|
|
28
|
+
CREDENTIAL_OF = {"gen": enroll.CRED_STATEMENT, "det": enroll.CRED_DETECTION}
|
|
29
|
+
TITLE = {"gen": "generation", "det": "detection"}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def section(root_der: bytes, authority: dict, roles: dict) -> dict:
|
|
33
|
+
"""``roles``: {"gen" | "det": issued directory of the authority (request.cbor, collateral.cbor, ear.cose) +
|
|
34
|
+
the policy text}."""
|
|
35
|
+
out = {"root": root_der, "authority": {"rrp_id": authority["rrp_id"], "name": authority["name"]}}
|
|
36
|
+
for role, d in roles.items():
|
|
37
|
+
out[role] = {"ear": (d["dir"] / "ear.cose").read_bytes(), "request": (d["dir"] / "request.cbor").read_bytes(),
|
|
38
|
+
"collateral": (d["dir"] / "collateral.cbor").read_bytes(), "policy": d["policy"]}
|
|
39
|
+
return out
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def check(st: dict, att: dict, note) -> dict:
|
|
43
|
+
"""Run every attestation check, reporting through ``note(name, ok, detail)``. Returns {role: Ed25519 key} for the
|
|
44
|
+
statements whose key the attestation established, and the attested identities per role."""
|
|
45
|
+
keys, ids = {}, {}
|
|
46
|
+
try:
|
|
47
|
+
root = x509.load_der_x509_certificate(att["root"])
|
|
48
|
+
except (KeyError, *pki.UNREADABLE) as exc:
|
|
49
|
+
note("attestation: authority root", False, f"{type(exc).__name__}: {exc}")
|
|
50
|
+
return {"keys": keys, "identities": ids}
|
|
51
|
+
note("attestation: authority root", None, f"{att.get('authority', {}).get('name', '?')}, SHA-256 "
|
|
52
|
+
f"{hashlib.sha256(att['root']).hexdigest()} - compare with the fingerprint the authority publishes")
|
|
53
|
+
for role in ("gen", "det"):
|
|
54
|
+
if role not in st or role not in att:
|
|
55
|
+
continue
|
|
56
|
+
t = TITLE[role]
|
|
57
|
+
a = att[role]
|
|
58
|
+
try:
|
|
59
|
+
c = ear.read(a["ear"], root.public_key())
|
|
60
|
+
except Exception as exc: # noqa: BLE001 - a failed check is a result
|
|
61
|
+
note(f"attestation ({t}): result signed by the authority", False, f"{type(exc).__name__}: {exc}")
|
|
62
|
+
continue
|
|
63
|
+
iat = dt.datetime.fromtimestamp(c[ear.IAT], dt.timezone.utc)
|
|
64
|
+
ext = c.get(ear.EP1, {})
|
|
65
|
+
note(f"attestation ({t}): result signed by the authority", True,
|
|
66
|
+
f"issued {iat.isoformat()}, status {c.get(ear.STATUS)}, submods {sorted(c.get(ear.SUBMODS, {}))}")
|
|
67
|
+
note(f"attestation ({t}): result affirming", c.get(ear.STATUS) == ear.AFFIRMING and not ext.get("failed"),
|
|
68
|
+
f"failed checks: {ext.get('failed') or 'none'}")
|
|
69
|
+
note(f"attestation ({t}): result is for this kind of statement", ext.get("credential_type") ==
|
|
70
|
+
CREDENTIAL_OF[role], str(ext.get("credential_type")))
|
|
71
|
+
prot = cose.decode1(st[role])[0]
|
|
72
|
+
note(f"attestation ({t}): statement names this result", prot.get(EAR_REF) == hashlib.sha256(a["ear"]).digest(),
|
|
73
|
+
"protected header ep1-ear = SHA-256 of the result")
|
|
74
|
+
leaf = prot.get(X5CHAIN)
|
|
75
|
+
leaf = leaf[0] if isinstance(leaf, list) else leaf
|
|
76
|
+
try:
|
|
77
|
+
key = pki.check_leaf(leaf, root, iat, pki.STATEMENT_EKU)
|
|
78
|
+
note(f"attestation ({t}): certificate of the authority for the signing key", True,
|
|
79
|
+
x509.load_der_x509_certificate(leaf).subject.rfc4514_string())
|
|
80
|
+
except Exception as exc: # noqa: BLE001
|
|
81
|
+
note(f"attestation ({t}): certificate of the authority for the signing key", False,
|
|
82
|
+
f"{type(exc).__name__}: {exc}")
|
|
83
|
+
continue
|
|
84
|
+
note(f"attestation ({t}): result affirms this key", ext.get("key") == hashlib.sha256(pki.spki(key)).digest(),
|
|
85
|
+
"ep1 key = SHA-256 of the certified key")
|
|
86
|
+
try:
|
|
87
|
+
req = enroll.read_request(a["request"])
|
|
88
|
+
note(f"attestation ({t}): result's nonce is the request's handle", c.get(ear.NONCE) == req["handle"])
|
|
89
|
+
again = appraise.appraise(req, rrp_id=att["authority"]["rrp_id"], policy=json.loads(a["policy"]), at=iat,
|
|
90
|
+
collateral=cose._thaw(cose.loads(a["collateral"])))
|
|
91
|
+
failed = [f"{x.name}: {x.detail}" for x in again.failed()]
|
|
92
|
+
note(f"attestation ({t}): evidence appraised again offline", not failed and again.ok,
|
|
93
|
+
f"{len(again.checks)} checks, failed: {failed or 'none'}; not performed: "
|
|
94
|
+
f"{[x.name for x in again.checks if x.ok is None] or 'none'}")
|
|
95
|
+
same = all(ext.get(k) == v for k, v in again.identities.items())
|
|
96
|
+
note(f"attestation ({t}): the result's identities are the evidence's", same,
|
|
97
|
+
f"binding {again.identities.get('binding', b'').hex()[:16]}…, weights "
|
|
98
|
+
f"{again.identities.get('weights', b'').hex()[:16]}…, code {again.identities.get('code', b'').hex()[:16]}…")
|
|
99
|
+
note(f"attestation ({t}): the request's key is the certified key", again.statement_key is not None and
|
|
100
|
+
pki.spki(again.statement_key) == pki.spki(key))
|
|
101
|
+
except Exception as exc: # noqa: BLE001
|
|
102
|
+
note(f"attestation ({t}): evidence appraised again offline", False, f"{type(exc).__name__}: {exc}")
|
|
103
|
+
continue
|
|
104
|
+
keys[role] = key
|
|
105
|
+
ids[role] = ext
|
|
106
|
+
return {"keys": keys, "identities": ids}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""The Azure paravisor's report (vTPM NV 0x01400001): HCL header, SNP report, request data, runtime claims.
|
|
2
|
+
|
|
3
|
+
Layout (microsoft/openvmm `vm/devices/tpm/tpm_guest_tests/src/report.rs`, `openhcl_attestation_protocol/src/
|
|
4
|
+
igvm_attest/get.rs`): header {signature "HCLA" (0x414c4348), version 2, report_size, request_type, status, 3 reserved}
|
|
5
|
+
32 octets; the TEE report in a 0x4a0-octet slot; request data {data_size, version, report_type (2 = SNP),
|
|
6
|
+
report_data_hash_type (1 SHA-256, 2 SHA-384, 3 SHA-512), variable_data_size} 20 octets; then the runtime claims, a
|
|
7
|
+
JSON object {keys: [HCLAkPub, HCLEkPub as RSA JWKs], vm-configuration: {...}, user-data: hex}. The hash of the
|
|
8
|
+
runtime claims, in the stated type, is the start of REPORT_DATA; the rest of REPORT_DATA is zero.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import base64
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
|
|
18
|
+
from . import amd
|
|
19
|
+
|
|
20
|
+
SIGNATURE = 0x414C4348
|
|
21
|
+
HEADER = 32
|
|
22
|
+
SLOT = 0x4A0
|
|
23
|
+
REQUEST_DATA = 20
|
|
24
|
+
HASHES = {1: hashlib.sha256, 2: hashlib.sha384, 3: hashlib.sha512}
|
|
25
|
+
B64URL = re.compile(r"[A-Za-z0-9_-]+")
|
|
26
|
+
HEX = re.compile(r"[0-9A-Fa-f]*")
|
|
27
|
+
SNP_VM_REPORT = 2
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class HCLError(ValueError):
|
|
31
|
+
"""Not a paravisor report, or its parts do not hold together."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class HCLReport:
|
|
36
|
+
raw: bytes
|
|
37
|
+
version: int
|
|
38
|
+
report_size: int
|
|
39
|
+
request_type: int
|
|
40
|
+
status: int
|
|
41
|
+
snp: amd.Report
|
|
42
|
+
report_type: int
|
|
43
|
+
hash_type: int
|
|
44
|
+
claims_raw: bytes
|
|
45
|
+
claims: dict
|
|
46
|
+
|
|
47
|
+
def jwk(self, kid: str) -> dict | None:
|
|
48
|
+
keys = self.claims.get("keys")
|
|
49
|
+
return next((k for k in keys if isinstance(k, dict) and k.get("kid") == kid), None) if isinstance(keys, list) \
|
|
50
|
+
else None
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def user_data(self) -> bytes:
|
|
54
|
+
v = self.claims.get("user-data", "")
|
|
55
|
+
if not (isinstance(v, str) and HEX.fullmatch(v) and len(v) % 2 == 0):
|
|
56
|
+
raise HCLError("user-data is not an even run of hex digits")
|
|
57
|
+
return bytes.fromhex(v)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _u32(b: bytes, off: int) -> int:
|
|
61
|
+
return int.from_bytes(b[off:off + 4], "little")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def parse(raw: bytes) -> HCLReport:
|
|
65
|
+
if len(raw) < HEADER + SLOT + REQUEST_DATA or _u32(raw, 0) != SIGNATURE:
|
|
66
|
+
raise HCLError("not an HCL report")
|
|
67
|
+
version, size, rtype, status = (_u32(raw, o) for o in (4, 8, 12, 16))
|
|
68
|
+
rd = HEADER + SLOT
|
|
69
|
+
data_size, _rd_version, report_type, hash_type, var_size = (_u32(raw, rd + o) for o in (0, 4, 8, 12, 16))
|
|
70
|
+
start = rd + REQUEST_DATA
|
|
71
|
+
if data_size != REQUEST_DATA + var_size or start + var_size != size or size > len(raw):
|
|
72
|
+
raise HCLError("sizes in the report do not agree")
|
|
73
|
+
claims_raw = raw[start:start + var_size]
|
|
74
|
+
try:
|
|
75
|
+
claims = json.loads(claims_raw)
|
|
76
|
+
except (ValueError, RecursionError) as exc:
|
|
77
|
+
raise HCLError("runtime claims are not JSON") from exc
|
|
78
|
+
if not isinstance(claims, dict):
|
|
79
|
+
raise HCLError("runtime claims are not a JSON object")
|
|
80
|
+
return HCLReport(raw=raw[:size], version=version, report_size=size, request_type=rtype, status=status,
|
|
81
|
+
snp=amd.parse_report(raw[HEADER:HEADER + SLOT]), report_type=report_type, hash_type=hash_type,
|
|
82
|
+
claims_raw=claims_raw, claims=claims)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def report_data_binds_claims(h: HCLReport) -> bool:
|
|
86
|
+
"""REPORT_DATA = hash(runtime claims) in the stated type, zero after it."""
|
|
87
|
+
fn = HASHES.get(h.hash_type)
|
|
88
|
+
if fn is None:
|
|
89
|
+
return False
|
|
90
|
+
d = fn(h.claims_raw).digest()
|
|
91
|
+
return h.snp.report_data[:len(d)] == d and not any(h.snp.report_data[len(d):])
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def rsa_from_jwk(jwk: dict):
|
|
95
|
+
"""The RSA public key of a JWK (RFC 7518 §6.3.1: n and e in base64url without padding); HCLError otherwise."""
|
|
96
|
+
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers
|
|
97
|
+
|
|
98
|
+
def b64(s) -> int:
|
|
99
|
+
if not (isinstance(s, str) and B64URL.fullmatch(s) and len(s) % 4 != 1):
|
|
100
|
+
raise HCLError("JWK member is not base64url")
|
|
101
|
+
return int.from_bytes(base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)), "big")
|
|
102
|
+
if not isinstance(jwk, dict) or jwk.get("kty") != "RSA":
|
|
103
|
+
raise HCLError("not an RSA JWK")
|
|
104
|
+
try:
|
|
105
|
+
return RSAPublicNumbers(b64(jwk.get("e")), b64(jwk.get("n"))).public_key()
|
|
106
|
+
except HCLError:
|
|
107
|
+
raise
|
|
108
|
+
except ValueError as exc: # e or n that is not an RSA public key
|
|
109
|
+
raise HCLError(f"not an RSA public key: {exc}") from exc
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""NVIDIA confidential GPU (Hopper): the SPDM measurement report and its certificate chain.
|
|
2
|
+
|
|
3
|
+
What NVML returns (NVIDIA/nvtrust local GPU verifier, `attestation/`): the SPDM 1.1 GET_MEASUREMENTS request (37
|
|
4
|
+
octets: version, code 0xE0, param1, param2, nonce 32, slot) followed by the MEASUREMENTS response: version, code
|
|
5
|
+
0x60, param1, param2, number of blocks, record length (3, little-endian), the measurement blocks {index,
|
|
6
|
+
specification (1 = DMTF), size (2), DMTF {value type, value size (2), value}}, the nonce (32), opaque length (2),
|
|
7
|
+
opaque data (TLVs: type 2, size 2, value), and the signature: ECDSA P-384, r || s, over SHA-384 of the request
|
|
8
|
+
followed by the response without its signature.
|
|
9
|
+
The certificate chain (PEM, leaf first) ends at NVIDIA's Device Identity CA, pinned here by SHA-256 of its DER (from
|
|
10
|
+
nvtrust tag 2026.06.04.001, `certs/verifier_device_root.pem`); reference integrity manifests are signed under
|
|
11
|
+
NVIDIA's RIM root, pinned the same way (`certs/verifier_RIM_root.pem`).
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
|
|
18
|
+
from cryptography import x509
|
|
19
|
+
from cryptography.exceptions import InvalidSignature
|
|
20
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
21
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
22
|
+
from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
|
|
23
|
+
|
|
24
|
+
from .pki import UNREADABLE
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
DEVICE_ROOT_SHA256 = "102bf659d5419614c9d8e6aecebc80454eb26b1df6a769ac720b9a690b167b48"
|
|
28
|
+
RIM_ROOT_SHA256 = "12977b5115acb0381179279fffeb5a8c4d264971ebb32298023a465fa41df5d1"
|
|
29
|
+
REQUEST_LEN = 37
|
|
30
|
+
SIG_LEN = 96
|
|
31
|
+
OPAQUE = {1: "cert_issuer_name", 2: "cert_authority_key_identifier", 3: "driver_version", 4: "gpu_info", 5: "sku",
|
|
32
|
+
6: "vbios_version", 7: "manufacturer_id", 8: "tamper_detection", 9: "smc", 10: "vpr", 11: "nvdec0_status",
|
|
33
|
+
12: "msrscnt", 13: "cprinfo", 14: "board_id", 15: "chip_sku", 16: "chip_sku_mod", 17: "project",
|
|
34
|
+
18: "project_sku", 19: "project_sku_mod", 20: "fwid", 21: "protected_pcie_status", 22: "switch_pdi",
|
|
35
|
+
23: "floorswept_ports", 24: "position_id", 25: "lock_switch_status", 32: "gpu_link_conn",
|
|
36
|
+
33: "sys_enable_status", 34: "opaque_data_version", 35: "chip_info", 36: "feature_flag"}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class GPUError(ValueError):
|
|
40
|
+
"""The GPU report or its chain does not hold."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class GPUReport:
|
|
45
|
+
request: bytes
|
|
46
|
+
response: bytes
|
|
47
|
+
nonce: bytes # from the request
|
|
48
|
+
response_nonce: bytes # the responder's own nonce
|
|
49
|
+
measurements: dict # index -> value
|
|
50
|
+
opaque: dict # name -> raw value
|
|
51
|
+
signature: bytes
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def parse(report: bytes) -> GPUReport:
|
|
55
|
+
"""GPUError for anything that is not a well-formed GET_MEASUREMENTS exchange (every length is checked against the
|
|
56
|
+
bytes there are)."""
|
|
57
|
+
try:
|
|
58
|
+
return _parse(report)
|
|
59
|
+
except IndexError as exc:
|
|
60
|
+
raise GPUError("GPU report truncated inside a field") from exc
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _parse(report: bytes) -> GPUReport:
|
|
64
|
+
if len(report) <= REQUEST_LEN + SIG_LEN:
|
|
65
|
+
raise GPUError("report too short")
|
|
66
|
+
req, resp = report[:REQUEST_LEN], report[REQUEST_LEN:]
|
|
67
|
+
if req[1] != 0xE0 or resp[1] != 0x60:
|
|
68
|
+
raise GPUError("not a GET_MEASUREMENTS exchange")
|
|
69
|
+
nblocks = resp[4]
|
|
70
|
+
rec_len = int.from_bytes(resp[5:8], "little")
|
|
71
|
+
if 8 + rec_len > len(resp):
|
|
72
|
+
raise GPUError("measurement record longer than the response")
|
|
73
|
+
rec, off, meas = resp[8:8 + rec_len], 0, {}
|
|
74
|
+
for _ in range(nblocks):
|
|
75
|
+
if off + 4 > rec_len:
|
|
76
|
+
raise GPUError("measurement block header beyond the record")
|
|
77
|
+
idx, spec, size = rec[off], rec[off + 1], int.from_bytes(rec[off + 2:off + 4], "little")
|
|
78
|
+
if off + 4 + size > rec_len or size < 3:
|
|
79
|
+
raise GPUError("measurement block beyond the record")
|
|
80
|
+
body = rec[off + 4:off + 4 + size]
|
|
81
|
+
if spec != 1:
|
|
82
|
+
raise GPUError("measurement block not in DMTF format")
|
|
83
|
+
vsize = int.from_bytes(body[1:3], "little")
|
|
84
|
+
if 3 + vsize > size:
|
|
85
|
+
raise GPUError("measurement value beyond its block")
|
|
86
|
+
meas[idx] = body[3:3 + vsize]
|
|
87
|
+
off += 4 + size
|
|
88
|
+
if off != rec_len:
|
|
89
|
+
raise GPUError("measurement record length does not match its blocks")
|
|
90
|
+
p = 8 + rec_len
|
|
91
|
+
if p + 34 > len(resp):
|
|
92
|
+
raise GPUError("response ends before its nonce and opaque length")
|
|
93
|
+
rnonce = resp[p:p + 32]
|
|
94
|
+
olen = int.from_bytes(resp[p + 32:p + 34], "little")
|
|
95
|
+
odata = resp[p + 34:p + 34 + olen]
|
|
96
|
+
sig = resp[p + 34 + olen:]
|
|
97
|
+
if len(sig) != SIG_LEN:
|
|
98
|
+
raise GPUError(f"signature is {len(sig)} octets, expected {SIG_LEN}")
|
|
99
|
+
opaque, o = {}, 0
|
|
100
|
+
while o + 4 <= len(odata):
|
|
101
|
+
t, n = int.from_bytes(odata[o:o + 2], "little"), int.from_bytes(odata[o + 2:o + 4], "little")
|
|
102
|
+
opaque[OPAQUE.get(t, f"type_{t}")] = odata[o + 4:o + 4 + n]
|
|
103
|
+
o += 4 + n
|
|
104
|
+
return GPUReport(request=req, response=resp, nonce=req[4:36], response_nonce=rnonce, measurements=meas,
|
|
105
|
+
opaque=opaque, signature=sig)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def text(v: bytes) -> str:
|
|
109
|
+
return v.split(b"\x00", 1)[0].decode("ascii", errors="replace").strip()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def vbios_version(raw: bytes) -> str:
|
|
113
|
+
"""The opaque VBIOS field as NVIDIA prints it (nvtrust `format_vbios_version`): read little-endian, then the upper
|
|
114
|
+
half followed by the byte just below it, dotted - 009f009604000000 -> 96.00.9f.00.04."""
|
|
115
|
+
v = raw[::-1].hex()
|
|
116
|
+
n = len(v) // 2
|
|
117
|
+
t = v[n:] + v[n - 2:n]
|
|
118
|
+
return ".".join(t[i:i + 2] for i in range(0, len(t), 2))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
TCG_DICE_TCBINFO = "2.23.133.5.4.1"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def certificate_fwid(leaf: x509.Certificate) -> bytes:
|
|
125
|
+
"""The firmware ID the device certificate carries: the last FWID digest (SHA-384, 48 octets) of its TCG DICE
|
|
126
|
+
TcbInfo extension - what NVIDIA's verifier reads (the extension's last 48 octets), with the OCTET STRING header
|
|
127
|
+
in front of them checked as well."""
|
|
128
|
+
for ext in leaf.extensions:
|
|
129
|
+
if ext.oid.dotted_string in (TCG_DICE_TCBINFO, TCG_DICE_TCBINFO + ".1"):
|
|
130
|
+
raw = ext.value.value
|
|
131
|
+
if len(raw) >= 50 and raw[-50:-48] == b"\x04\x30":
|
|
132
|
+
return raw[-48:]
|
|
133
|
+
raise GPUError("TcbInfo extension does not end with a 48-octet FWID")
|
|
134
|
+
raise GPUError("device certificate has no TcbInfo extension")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def verify_report(rep: GPUReport, leaf: x509.Certificate) -> None:
|
|
138
|
+
try:
|
|
139
|
+
key = leaf.public_key()
|
|
140
|
+
except UNREADABLE as exc:
|
|
141
|
+
raise GPUError(f"the attestation key cannot be read: {exc}") from exc
|
|
142
|
+
if not isinstance(key, ec.EllipticCurvePublicKey) or key.curve.name != "secp384r1":
|
|
143
|
+
raise GPUError("the attestation key is not ECDSA P-384")
|
|
144
|
+
r, s = int.from_bytes(rep.signature[:48], "big"), int.from_bytes(rep.signature[48:], "big")
|
|
145
|
+
try:
|
|
146
|
+
key.verify(encode_dss_signature(r, s), rep.request + rep.response[:-SIG_LEN], ec.ECDSA(hashes.SHA384()))
|
|
147
|
+
except InvalidSignature as exc:
|
|
148
|
+
raise GPUError("GPU report signature does not verify") from exc
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def load_chain(pem: bytes) -> list[x509.Certificate]:
|
|
152
|
+
return x509.load_pem_x509_certificates(pem)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def verify_chain(chain: list[x509.Certificate], root_sha256: str, at) -> None:
|
|
156
|
+
"""Leaf first; every certificate signed by the next (ECDSA), the last the pinned root, all valid at ``at``."""
|
|
157
|
+
if not chain:
|
|
158
|
+
raise GPUError("empty certificate chain")
|
|
159
|
+
root = chain[-1]
|
|
160
|
+
if hashlib.sha256(root.public_bytes(serialization.Encoding.DER)).hexdigest() != root_sha256:
|
|
161
|
+
raise GPUError("chain does not end at NVIDIA's pinned root")
|
|
162
|
+
for child, parent in zip(chain, chain[1:] + [root]):
|
|
163
|
+
try:
|
|
164
|
+
child.verify_directly_issued_by(parent)
|
|
165
|
+
except (*UNREADABLE, InvalidSignature) as exc: # an unreadable key included
|
|
166
|
+
raise GPUError(f"{child.subject.rfc4514_string()} is not signed by its issuer") from exc
|
|
167
|
+
if not child.not_valid_before_utc <= at <= child.not_valid_after_utc:
|
|
168
|
+
raise GPUError(f"{child.subject.rfc4514_string()} not valid at {at.isoformat()}")
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""OCSP for NVIDIA's certificate chains (RFC 6960), as NVIDIA's local verifier asks it (nvtrust `cc_admin_utils.py`):
|
|
2
|
+
one request per certificate below the root (for a GPU chain, from the second certificate: the leaf is the per-boot
|
|
3
|
+
attestation key), CertID over SHA-384, a critical nonce extension; responder https://ocsp.ndis.nvidia.com/.
|
|
4
|
+
A response counts when it is successful, signed by a responder whose certificate chains to the pinned root, echoes
|
|
5
|
+
the nonce (NVIDIA puts it in responseExtensions), names the asked certificate, and its validity window covers the
|
|
6
|
+
time of the check. The raw responses are kept: the offline check re-reads them at the time of the original appraisal.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import datetime as dt
|
|
11
|
+
import os
|
|
12
|
+
import urllib.request
|
|
13
|
+
|
|
14
|
+
from cryptography import x509
|
|
15
|
+
from cryptography.exceptions import InvalidSignature
|
|
16
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
17
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
18
|
+
from cryptography.x509 import ocsp
|
|
19
|
+
|
|
20
|
+
from .nvidia import GPUError, verify_chain
|
|
21
|
+
from .pki import UNREADABLE
|
|
22
|
+
|
|
23
|
+
OCSP_URL = "https://ocsp.ndis.nvidia.com/"
|
|
24
|
+
SKEW = dt.timedelta(seconds=300) # tolerated clock difference with the responder (as `openssl ocsp -validity_period`)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def request(cert: x509.Certificate, issuer: x509.Certificate, nonce: bytes) -> bytes:
|
|
28
|
+
b = ocsp.OCSPRequestBuilder().add_certificate(cert, issuer, hashes.SHA384())
|
|
29
|
+
return b.add_extension(x509.OCSPNonce(nonce), critical=True).build().public_bytes(serialization.Encoding.DER)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def post(req: bytes, url: str = OCSP_URL, timeout: int = 20) -> bytes:
|
|
33
|
+
r = urllib.request.Request(url, data=req, headers={"Content-Type": "application/ocsp-request"})
|
|
34
|
+
with urllib.request.urlopen(r, timeout=timeout) as resp: # noqa: S310 - fixed https URL
|
|
35
|
+
return resp.read()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _responder_chain(given: list[x509.Certificate], known: list[x509.Certificate]) -> list[x509.Certificate]:
|
|
39
|
+
"""The responder's certificates as the response gives them, completed upward from ``known`` (the chain being
|
|
40
|
+
checked, which ends at the pinned root) by issuer name."""
|
|
41
|
+
chain = list(given)
|
|
42
|
+
while chain[-1].issuer != chain[-1].subject:
|
|
43
|
+
up = next((c for c in known if c.subject == chain[-1].issuer), None)
|
|
44
|
+
if up is None or up in chain:
|
|
45
|
+
break
|
|
46
|
+
chain.append(up)
|
|
47
|
+
return chain
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def check(resp_der: bytes, cert: x509.Certificate, issuer: x509.Certificate, nonce: bytes, root_sha256: str,
|
|
51
|
+
at: dt.datetime, known: list[x509.Certificate]) -> str:
|
|
52
|
+
""""good", or GPUError naming what failed ("revoked: <reason>" is an error too)."""
|
|
53
|
+
r = ocsp.load_der_ocsp_response(resp_der)
|
|
54
|
+
if r.response_status != ocsp.OCSPResponseStatus.SUCCESSFUL:
|
|
55
|
+
raise GPUError(f"OCSP response status {r.response_status.name}")
|
|
56
|
+
if not r.certificates:
|
|
57
|
+
raise GPUError("OCSP response carries no responder certificate")
|
|
58
|
+
responder = r.certificates[0]
|
|
59
|
+
verify_chain(_responder_chain(list(r.certificates), known), root_sha256, at)
|
|
60
|
+
try:
|
|
61
|
+
key = responder.public_key()
|
|
62
|
+
if not isinstance(key, ec.EllipticCurvePublicKey):
|
|
63
|
+
raise GPUError("the OCSP responder's key is not ECDSA")
|
|
64
|
+
key.verify(r.signature, r.tbs_response_bytes, ec.ECDSA(r.signature_hash_algorithm))
|
|
65
|
+
except (InvalidSignature, *UNREADABLE) as exc:
|
|
66
|
+
if isinstance(exc, GPUError):
|
|
67
|
+
raise
|
|
68
|
+
raise GPUError(f"OCSP response signature does not verify: {exc}") from exc
|
|
69
|
+
try:
|
|
70
|
+
echoed = r.extensions.get_extension_for_class(x509.OCSPNonce).value.nonce
|
|
71
|
+
except x509.ExtensionNotFound as exc:
|
|
72
|
+
raise GPUError("OCSP response does not echo the nonce") from exc
|
|
73
|
+
if echoed != nonce:
|
|
74
|
+
raise GPUError("OCSP nonce mismatch")
|
|
75
|
+
asked = ocsp.load_der_ocsp_request(request(cert, issuer, nonce))
|
|
76
|
+
if (r.serial_number, r.issuer_key_hash, r.issuer_name_hash) != (asked.serial_number, asked.issuer_key_hash,
|
|
77
|
+
asked.issuer_name_hash):
|
|
78
|
+
raise GPUError("OCSP response is about another certificate (CertID differs)")
|
|
79
|
+
upd, nxt = r.this_update_utc, r.next_update_utc
|
|
80
|
+
if upd > at + SKEW or (nxt is not None and at > nxt + SKEW):
|
|
81
|
+
raise GPUError(f"OCSP response not current at {at.isoformat()} (this update {upd}, next {nxt})")
|
|
82
|
+
if r.certificate_status == ocsp.OCSPCertStatus.GOOD:
|
|
83
|
+
return "good"
|
|
84
|
+
if r.certificate_status == ocsp.OCSPCertStatus.REVOKED:
|
|
85
|
+
raise GPUError(f"revoked: {r.revocation_reason.name if r.revocation_reason else 'unspecified'}")
|
|
86
|
+
raise GPUError("certificate status unknown to the responder")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def fresh_nonce() -> bytes:
|
|
90
|
+
return os.urandom(32)
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""The authority's certificates: a root and statement-key certificates (Ed25519).
|
|
2
|
+
|
|
3
|
+
The root signs the attestation results itself (COSE) and issues one end-entity certificate per certified statement
|
|
4
|
+
key (subject = the target, validity = the result's lifetime, extended key usage id-kp-documentSigning, RFC 9336).
|
|
5
|
+
Results are not signed under an end-entity certificate: a sealer holds one, and a result that verified under any
|
|
6
|
+
leaf of the root could then be forged by a sealer for itself. A relying party pins the root; statement certificates
|
|
7
|
+
arrive in x5chain headers (RFC 9360, label 33) and are checked against it.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import datetime as dt
|
|
12
|
+
|
|
13
|
+
from cryptography import x509
|
|
14
|
+
from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
|
|
15
|
+
from cryptography.hazmat.primitives import serialization
|
|
16
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
|
|
17
|
+
from cryptography.x509.oid import NameOID
|
|
18
|
+
|
|
19
|
+
STATEMENT_EKU = x509.ObjectIdentifier("1.3.6.1.5.5.7.3.36") # id-kp-documentSigning (RFC 9336)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# What reading a certificate, CSR or key out of evidence can raise: besides ValueError, an unknown key algorithm and an
|
|
23
|
+
# invalid X.509 version, neither of which is a ValueError. Every verifier here turns them into its own refusal.
|
|
24
|
+
UNREADABLE = (ValueError, TypeError, UnsupportedAlgorithm, x509.InvalidVersion)
|
|
25
|
+
|
|
26
|
+
class PKIError(ValueError):
|
|
27
|
+
"""A certificate does not chain to the root, or is not valid for its use."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def der(cert: x509.Certificate) -> bytes:
|
|
31
|
+
return cert.public_bytes(serialization.Encoding.DER)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _name(cn: str, org: str | None = None) -> x509.Name:
|
|
35
|
+
attrs = [x509.NameAttribute(NameOID.COMMON_NAME, cn)]
|
|
36
|
+
if org:
|
|
37
|
+
attrs.append(x509.NameAttribute(NameOID.ORGANIZATION_NAME, org))
|
|
38
|
+
return x509.Name(attrs)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def make_root(key: Ed25519PrivateKey, cn: str, org: str, years: int = 10) -> x509.Certificate:
|
|
42
|
+
now = dt.datetime.now(dt.timezone.utc).replace(microsecond=0)
|
|
43
|
+
name = _name(cn, org)
|
|
44
|
+
return (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
|
|
45
|
+
.serial_number(x509.random_serial_number()).not_valid_before(now)
|
|
46
|
+
.not_valid_after(now + dt.timedelta(days=365 * years))
|
|
47
|
+
.add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
|
|
48
|
+
.add_extension(x509.KeyUsage(False, False, False, False, False, True, True, False, False), critical=True)
|
|
49
|
+
.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False)
|
|
50
|
+
.sign(key, None))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def issue(root_key: Ed25519PrivateKey, root: x509.Certificate, public_key: Ed25519PublicKey, cn: str, *,
|
|
54
|
+
lifetime: int, eku: x509.ObjectIdentifier, not_before: dt.datetime | None = None) -> x509.Certificate:
|
|
55
|
+
nb = (not_before or dt.datetime.now(dt.timezone.utc)).replace(microsecond=0)
|
|
56
|
+
return (x509.CertificateBuilder().subject_name(_name(cn)).issuer_name(root.subject).public_key(public_key)
|
|
57
|
+
.serial_number(x509.random_serial_number()).not_valid_before(nb)
|
|
58
|
+
.not_valid_after(nb + dt.timedelta(seconds=int(lifetime)))
|
|
59
|
+
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
|
|
60
|
+
.add_extension(x509.KeyUsage(True, False, False, False, False, False, False, False, False), critical=True)
|
|
61
|
+
.add_extension(x509.ExtendedKeyUsage([eku]), critical=False)
|
|
62
|
+
.add_extension(x509.SubjectKeyIdentifier.from_public_key(public_key), critical=False)
|
|
63
|
+
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(root.public_key()), critical=False)
|
|
64
|
+
.sign(root_key, None))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def check_leaf(leaf_der: bytes, root: x509.Certificate, at: dt.datetime, eku: x509.ObjectIdentifier) -> Ed25519PublicKey:
|
|
68
|
+
"""The leaf is signed by the root, valid at ``at``, an end entity with ``eku``; returns its Ed25519 key."""
|
|
69
|
+
try:
|
|
70
|
+
leaf = x509.load_der_x509_certificate(leaf_der)
|
|
71
|
+
except UNREADABLE as exc:
|
|
72
|
+
raise PKIError(f"leaf is not a certificate: {exc}") from exc
|
|
73
|
+
if leaf.issuer != root.subject:
|
|
74
|
+
raise PKIError("leaf not issued by this root")
|
|
75
|
+
try:
|
|
76
|
+
leaf.verify_directly_issued_by(root)
|
|
77
|
+
except (*UNREADABLE, InvalidSignature) as exc:
|
|
78
|
+
raise PKIError("leaf signature does not verify under the root") from exc
|
|
79
|
+
if not leaf.not_valid_before_utc <= at <= leaf.not_valid_after_utc:
|
|
80
|
+
raise PKIError(f"leaf not valid at {at.isoformat()}")
|
|
81
|
+
try:
|
|
82
|
+
bc = leaf.extensions.get_extension_for_class(x509.BasicConstraints).value
|
|
83
|
+
ekus = leaf.extensions.get_extension_for_class(x509.ExtendedKeyUsage).value
|
|
84
|
+
key = leaf.public_key()
|
|
85
|
+
except (*UNREADABLE, x509.ExtensionNotFound) as exc:
|
|
86
|
+
raise PKIError(f"leaf lacks what an end-entity certificate of this authority carries: {exc}") from exc
|
|
87
|
+
if bc.ca:
|
|
88
|
+
raise PKIError("leaf is a CA certificate")
|
|
89
|
+
if eku not in ekus:
|
|
90
|
+
raise PKIError("leaf not issued for this use")
|
|
91
|
+
if not isinstance(key, Ed25519PublicKey):
|
|
92
|
+
raise PKIError("leaf key is not Ed25519")
|
|
93
|
+
return key
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def make_csr(key: Ed25519PrivateKey, target: str) -> bytes:
|
|
97
|
+
return der_csr(x509.CertificateSigningRequestBuilder().subject_name(_name(target)).sign(key, None))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def der_csr(csr: x509.CertificateSigningRequest) -> bytes:
|
|
101
|
+
return csr.public_bytes(serialization.Encoding.DER)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def read_csr(csr_der: bytes) -> tuple[Ed25519PublicKey, str]:
|
|
105
|
+
"""(key, subject CN) of a CSR whose self-signature verifies (proof of possession)."""
|
|
106
|
+
try:
|
|
107
|
+
csr = x509.load_der_x509_csr(csr_der)
|
|
108
|
+
valid = csr.is_signature_valid
|
|
109
|
+
key = csr.public_key()
|
|
110
|
+
except UNREADABLE as exc:
|
|
111
|
+
raise PKIError(f"not a readable CSR: {exc}") from exc
|
|
112
|
+
if not valid:
|
|
113
|
+
raise PKIError("CSR signature does not verify (no proof of possession)")
|
|
114
|
+
if not isinstance(key, Ed25519PublicKey):
|
|
115
|
+
raise PKIError("CSR key is not Ed25519")
|
|
116
|
+
cn = csr.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
|
|
117
|
+
return key, (cn[0].value if cn else "")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def spki(key: Ed25519PublicKey) -> bytes:
|
|
121
|
+
return key.public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
|