-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathmod.rs
554 lines (465 loc) · 19.7 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
use anyhow::anyhow;
use base64::{Engine, engine::general_purpose::STANDARD};
use log::{debug, warn};
extern crate serde;
use self::serde::{Deserialize, Serialize};
use super::*;
use asn1_rs::{oid, FromDer, Integer, OctetString, Oid};
use async_trait::async_trait;
use openssl::{
ec::EcKey,
ecdsa,
nid::Nid,
pkey::{PKey, Public},
sha::sha384,
x509::{self, X509},
};
use reqwest::{get, Response as ReqwestResponse, StatusCode};
use serde_json::json;
use sev::firmware::guest::AttestationReport;
use sev::firmware::host::{CertTableEntry, CertType};
use std::sync::OnceLock;
use x509_parser::prelude::*;
#[derive(Serialize, Deserialize)]
pub struct SnpEvidence {
attestation_report: AttestationReport,
cert_chain: Option<Vec<CertTableEntry>>,
}
const HW_ID_OID: Oid<'static> = oid!(1.3.6 .1 .4 .1 .3704 .1 .4);
const UCODE_SPL_OID: Oid<'static> = oid!(1.3.6 .1 .4 .1 .3704 .1 .3 .8);
const SNP_SPL_OID: Oid<'static> = oid!(1.3.6 .1 .4 .1 .3704 .1 .3 .3);
const TEE_SPL_OID: Oid<'static> = oid!(1.3.6 .1 .4 .1 .3704 .1 .3 .2);
const LOADER_SPL_OID: Oid<'static> = oid!(1.3.6 .1 .4 .1 .3704 .1 .3 .1);
// KDS URL parameters
const KDS_CERT_SITE: &str = "https://kdsintf.amd.com";
const KDS_VCEK: &str = "/vcek/v1";
/// Attestation report versions supported
const REPORT_VERSION_MIN: u32 = 2;
const REPORT_VERSION_MAX: u32 = 3;
#[derive(Debug)]
pub struct Snp {
vendor_certs: VendorCertificates,
}
/// Loads the Milan certificate chain and returns a static reference to it.
/// The chain is loaded lazily using `OnceLock` to ensure it's only initialized once.
/// Certificates are loaded from a PEM file and must contain exactly three certificates (ASK, ARK, ASVK).
pub(crate) fn load_milan_cert_chain() -> &'static Result<VendorCertificates> {
static MILAN_CERT_CHAIN: OnceLock<Result<VendorCertificates>> = OnceLock::new();
MILAN_CERT_CHAIN.get_or_init(|| {
let certs = X509::stack_from_pem(include_bytes!("milan_ask_ark_asvk.pem"))?;
if certs.len() != 3 {
bail!("Malformed Milan ASK/ARK/ASVK");
}
let vendor_certs = VendorCertificates {
ask: certs[0].clone(),
ark: certs[1].clone(),
asvk: certs[2].clone(),
};
Ok(vendor_certs)
})
}
impl Snp {
/// Creates a new `Snp` instance by loading the Milan certificate chain.
/// Returns an error if the certificate chain can not be loaded.
pub fn new() -> Result<Self> {
let Result::Ok(vendor_certs) = load_milan_cert_chain() else {
bail!("Failed to load Milan cert chain");
};
let vendor_certs = vendor_certs.clone();
Ok(Self { vendor_certs })
}
}
#[derive(Clone, Debug)]
pub(crate) struct VendorCertificates {
ask: X509,
ark: X509,
asvk: X509,
}
#[async_trait]
impl Verifier for Snp {
/// Evaluates the provided evidence against the expected report data and initialize data hash.
/// Validates the report signature, version, VMPL, and other fields.
/// Returns parsed claims if the verification is successful.
async fn evaluate(
&self,
evidence: &[u8],
expected_report_data: &ReportData,
expected_init_data_hash: &InitDataHash,
) -> Result<TeeEvidenceParsedClaim> {
let SnpEvidence {
attestation_report: report,
cert_chain,
} = serde_json::from_slice(evidence).context("Deserialize Quote failed.")?;
let cert_chain = match cert_chain {
Some(chain) if !chain.is_empty() => chain,
_ => fetch_vcek_from_kds(report).await?,
};
verify_report_signature(&report, &cert_chain, &self.vendor_certs)?;
// See Trustee Issue#589 https://github.com/confidential-containers/trustee/issues/589
if report.version < REPORT_VERSION_MIN || report.version > REPORT_VERSION_MAX {
return Err(anyhow!(
"Unexpected attestation report version. Check SNP Firmware ABI specification"
));
}
if report.vmpl != 0 {
return Err(anyhow!("VMPL Check Failed"));
}
if let ReportData::Value(expected_report_data) = expected_report_data {
debug!("Check the binding of REPORT_DATA.");
let expected_report_data =
regularize_data(expected_report_data, 64, "REPORT_DATA", "SNP");
if expected_report_data != report.report_data {
warn!(
"Report data mismatch. Given: {}, Expected: {}",
hex::encode(report.report_data),
hex::encode(expected_report_data)
);
bail!("Report Data Mismatch");
}
};
if let InitDataHash::Value(expected_init_data_hash) = expected_init_data_hash {
debug!("Check the binding of HOST_DATA.");
let expected_init_data_hash =
regularize_data(expected_init_data_hash, 32, "HOST_DATA", "SNP");
if expected_init_data_hash != report.host_data {
bail!("Host Data Mismatch");
}
}
let claims_map = parse_tee_evidence(&report);
let json = json!(claims_map);
Ok(json)
}
}
/// Retrieves the octet string value for a given OID from a certificate's extensions.
/// Supports both raw and DER-encoded formats.
fn get_oid_octets<const N: usize>(
vcek: &x509_parser::certificate::TbsCertificate,
oid: Oid,
) -> Result<[u8; N]> {
let val = vcek
.get_extension_unique(&oid)?
.ok_or_else(|| anyhow!("Oid not found"))?
.value;
// Previously, the hwID extension hasn't been encoded as DER octet string.
// In this case, the value of the extension is the hwID itself (64 byte long),
// and we can just return the value.
if val.len() == N {
return Ok(val.try_into().unwrap());
}
// Parse the value as DER encoded octet string.
let (_, val_octet) = OctetString::from_der(val)?;
val_octet
.as_ref()
.try_into()
.context("Unexpected data size")
}
/// Retrieves an integer value for a given OID from a certificate's extensions.
fn get_oid_int(cert: &x509_parser::certificate::TbsCertificate, oid: Oid) -> Result<u8> {
let val = cert
.get_extension_unique(&oid)?
.ok_or_else(|| anyhow!("Oid not found"))?
.value;
let (_, val_int) = Integer::from_der(val)?;
val_int.as_u8().context("Unexpected data size")
}
/// Verifies the signature of the attestation report using the provided certificate chain and vendor certificates.
pub(crate) fn verify_report_signature(
report: &AttestationReport,
cert_chain: &[CertTableEntry],
vendor_certs: &VendorCertificates,
) -> Result<()> {
// check cert chain
let VendorCertificates { ask, ark, asvk } = vendor_certs;
// verify VCEK or VLEK cert chain
// the key can be either VCEK or VLEK
let endorsement_key = verify_cert_chain(cert_chain, ask, ark, asvk)?;
// OpenSSL bindings do not expose custom extensions
// Parse the key using x509_parser
let endorsement_key_der = &endorsement_key.to_der()?;
let parsed_endorsement_key = X509Certificate::from_der(endorsement_key_der)?
.1
.tbs_certificate;
let common_name =
get_common_name(&endorsement_key).context("No common name found in certificate")?;
// if the common name is "VCEK", then the key is a VCEK
// so lets check the chip id
if common_name == "VCEK"
&& get_oid_octets::<64>(&parsed_endorsement_key, HW_ID_OID)? != report.chip_id
{
bail!("Chip ID mismatch");
}
// tcb version
// these integer extensions are 3 bytes with the last byte as the data
if get_oid_int(&parsed_endorsement_key, UCODE_SPL_OID)? != report.reported_tcb.microcode {
return Err(anyhow!("Microcode version mismatch"));
}
if get_oid_int(&parsed_endorsement_key, SNP_SPL_OID)? != report.reported_tcb.snp {
return Err(anyhow!("SNP version mismatch"));
}
if get_oid_int(&parsed_endorsement_key, TEE_SPL_OID)? != report.reported_tcb.tee {
return Err(anyhow!("TEE version mismatch"));
}
if get_oid_int(&parsed_endorsement_key, LOADER_SPL_OID)? != report.reported_tcb.bootloader {
return Err(anyhow!("Boot loader version mismatch"));
}
// verify report signature
let sig = ecdsa::EcdsaSig::try_from(&report.signature)?;
let data = &bincode::serialize(&report)?[..=0x29f];
let pub_key = EcKey::try_from(endorsement_key.public_key()?)?;
let signed = sig.verify(&sha384(data), &pub_key)?;
if !signed {
return Err(anyhow!("Signature validation failed."));
}
Ok(())
}
/// Verifies the signature of a certificate against its issuer's public key.
fn verify_signature(cert: &X509, issuer: &X509, name: &str) -> Result<()> {
cert.verify(&(issuer.public_key()? as PKey<Public>))?
.then_some(())
.ok_or_else(|| anyhow!("Invalid {name} signature"))
}
/// Verifies the certificate chain based on the provided VCEK or VLEK.
/// Ensures the chain is valid by verifying signatures and relationships between certificates.
fn verify_cert_chain(
cert_chain: &[CertTableEntry],
ask: &X509,
ark: &X509,
asvk: &X509,
) -> Result<X509> {
// get endorsement keys (VLEK or VCEK)
let endorsement_keys: Vec<&CertTableEntry> = cert_chain
.iter()
.filter(|e| e.cert_type == CertType::VCEK || e.cert_type == CertType::VLEK)
.collect();
let &[key] = endorsement_keys.as_slice() else {
bail!("Could not find either VCEK or VLEK in cert chain")
};
let decoded_key =
x509::X509::from_der(key.data()).context("Failed to decode endorsement key")?;
match key.cert_type {
CertType::VCEK => {
// Chain: ARK -> ARK -> ASK -> VCEK
verify_signature(ark, ark, "ARK")?;
verify_signature(ask, ark, "ASK")?;
verify_signature(&decoded_key, ask, "VCEK")?;
}
CertType::VLEK => {
// Chain: ARK -> ARK -> ASVK -> VLEK
verify_signature(ark, ark, "ARK")?;
verify_signature(asvk, ark, "ASVK")?;
verify_signature(&decoded_key, asvk, "VLEK")?;
}
_ => bail!("Certificate not of type versioned endorsement key (VLEK or VCEK)"),
}
Ok(decoded_key)
}
/// Parses the attestation report and extracts the TEE evidence claims.
/// Returns a JSON-formatted map of parsed claims.
pub(crate) fn parse_tee_evidence(report: &AttestationReport) -> TeeEvidenceParsedClaim {
let claims_map = json!({
// policy fields
"policy_abi_major": format!("{}",report.policy.abi_major()),
"policy_abi_minor": format!("{}", report.policy.abi_minor()),
"policy_smt_allowed": format!("{}", report.policy.smt_allowed()),
"policy_migrate_ma": format!("{}", report.policy.migrate_ma_allowed()),
"policy_debug_allowed": format!("{}", report.policy.debug_allowed()),
"policy_single_socket": format!("{}", report.policy.single_socket_required()),
// versioning info
"reported_tcb_bootloader": format!("{}", report.reported_tcb.bootloader),
"reported_tcb_tee": format!("{}", report.reported_tcb.tee),
"reported_tcb_snp": format!("{}", report.reported_tcb.snp),
"reported_tcb_microcode": format!("{}", report.reported_tcb.microcode),
// platform info
"platform_tsme_enabled": format!("{}", report.plat_info.tsme_enabled()),
"platform_smt_enabled": format!("{}", report.plat_info.smt_enabled()),
// measurements
"measurement": format!("{}", STANDARD.encode(report.measurement)),
"report_data": format!("{}", STANDARD.encode(report.report_data)),
"init_data": format!("{}", STANDARD.encode(report.host_data)),
});
claims_map as TeeEvidenceParsedClaim
}
/// Extracts the common name (CN) from the subject name of a certificate.
fn get_common_name(cert: &x509::X509) -> Result<String> {
let mut entries = cert.subject_name().entries_by_nid(Nid::COMMONNAME);
let Some(e) = entries.next() else {
bail!("No CN found");
};
if entries.count() != 0 {
bail!("No CN found");
}
Ok(e.data().as_utf8()?.to_string())
}
/// Asynchronously fetches the VCEK from the Key Distribution Service (KDS) using the provided attestation report.
/// Returns the VCEK in DER format as part of a certificate table entry.
async fn fetch_vcek_from_kds(att_report: AttestationReport) -> Result<Vec<CertTableEntry>> {
// Use attestation report to get data for URL
let hw_id: String = hex::encode(att_report.chip_id);
let vcek_url: String = format!(
"{KDS_CERT_SITE}{KDS_VCEK}/Milan/\
{hw_id}?blSPL={:02}&teeSPL={:02}&snpSPL={:02}&ucodeSPL={:02}",
att_report.reported_tcb.bootloader,
att_report.reported_tcb.tee,
att_report.reported_tcb.snp,
att_report.reported_tcb.microcode
);
// VCEK in DER format
let vcek_rsp: ReqwestResponse = get(vcek_url)
.await
.context("Unable to send request for VCEK")?;
match vcek_rsp.status() {
StatusCode::OK => {
let vcek_rsp_bytes: Vec<u8> = vcek_rsp
.bytes()
.await
.context("Unable to parse VCEK")?
.to_vec();
let key = CertTableEntry {
cert_type: CertType::VCEK,
data: vcek_rsp_bytes,
};
Ok(vec![key])
}
status => Err(anyhow!("Unable to fetch VCEK from URL: {status:?}")),
}
}
#[cfg(test)]
mod tests {
use super::*;
const VCEK: &[u8; 1360] = include_bytes!("../../test_data/snp/test-vcek.der");
const VCEK_LEGACY: &[u8; 1361] =
include_bytes!("../../test_data/snp/test-vcek-invalid-legacy.der");
const VCEK_NEW: &[u8; 1362] = include_bytes!("../../test_data/snp/test-vcek-invalid-new.der");
const VCEK_REPORT: &[u8; 1184] = include_bytes!("../../test_data/snp/test-report.bin");
const VLEK: &[u8; 1329] = include_bytes!("../../test_data/snp/test-vlek.der");
const VLEK_REPORT: &[u8; 1184] = include_bytes!("../../test_data/snp/test-vlek-report.bin");
#[test]
fn check_milan_certificates() {
let VendorCertificates { ask, ark, asvk } = load_milan_cert_chain().as_ref().unwrap();
assert_eq!(get_common_name(ark).unwrap(), "ARK-Milan");
assert_eq!(get_common_name(ask).unwrap(), "SEV-Milan");
assert_eq!(get_common_name(asvk).unwrap(), "SEV-VLEK-Milan");
assert!(ark
.verify(&(ark.public_key().unwrap() as PKey<Public>))
.context("Invalid ARK Signature")
.unwrap());
assert!(ask
.verify(&(ark.public_key().unwrap() as PKey<Public>))
.context("Invalid ASK Signature")
.unwrap());
assert!(asvk
.verify(&(ark.public_key().unwrap() as PKey<Public>))
.context("Invalid ASVK Signature")
.unwrap());
}
fn check_oid_ints(cert: &TbsCertificate) {
let oids = vec![UCODE_SPL_OID, SNP_SPL_OID, TEE_SPL_OID, LOADER_SPL_OID];
for oid in oids {
get_oid_int(&cert, oid).unwrap();
}
}
#[test]
fn check_vlek_parsing() {
let parsed_vlek = X509Certificate::from_der(VLEK).unwrap().1.tbs_certificate;
check_oid_ints(&parsed_vlek);
}
#[test]
fn check_vcek_parsing() {
let parsed_vcek = X509Certificate::from_der(VCEK).unwrap().1.tbs_certificate;
get_oid_octets::<64>(&parsed_vcek, HW_ID_OID).unwrap();
check_oid_ints(&parsed_vcek);
}
#[test]
fn check_vcek_parsing_legacy() {
let parsed_vcek = X509Certificate::from_der(VCEK_LEGACY)
.unwrap()
.1
.tbs_certificate;
get_oid_octets::<64>(&parsed_vcek, HW_ID_OID).unwrap();
check_oid_ints(&parsed_vcek);
}
#[test]
fn check_vcek_parsing_new() {
let parsed_vcek = X509Certificate::from_der(VCEK_NEW)
.unwrap()
.1
.tbs_certificate;
get_oid_octets::<64>(&parsed_vcek, HW_ID_OID).unwrap();
check_oid_ints(&parsed_vcek);
}
#[test]
fn check_vcek_signature_verification() {
let cert_table = vec![CertTableEntry::new(CertType::VCEK, VCEK.to_vec())];
let VendorCertificates { ask, ark, asvk } = load_milan_cert_chain().as_ref().unwrap();
verify_cert_chain(&cert_table, ask, ark, asvk).unwrap();
}
#[test]
fn check_vcek_signature_failure() {
let mut vcek = VCEK.clone();
// corrupt some byte, while it should remain a valid cert
vcek[42] += 1;
X509::from_der(&vcek).expect("failed to parse der");
let cert_table = vec![CertTableEntry::new(CertType::VCEK, vcek.to_vec())];
let VendorCertificates { ask, ark, asvk } = load_milan_cert_chain().as_ref().unwrap();
verify_cert_chain(&cert_table, ask, ark, asvk).unwrap_err();
}
#[test]
fn check_vlek_signature_verification() {
let cert_table = vec![CertTableEntry::new(CertType::VLEK, VLEK.to_vec())];
let VendorCertificates { ask, ark, asvk } = load_milan_cert_chain().as_ref().unwrap();
verify_cert_chain(&cert_table, ask, ark, asvk).unwrap();
}
#[test]
fn check_vlek_signature_failure() {
let mut vlek = VLEK.clone();
// corrupt some byte, while it should remain a valid cert
vlek[42] += 1;
X509::from_der(&vlek).expect("failed to parse der");
let cert_table = vec![CertTableEntry::new(CertType::VLEK, vlek.to_vec())];
let VendorCertificates { ask, ark, asvk } = load_milan_cert_chain().as_ref().unwrap();
verify_cert_chain(&cert_table, ask, ark, asvk).unwrap_err();
}
#[test]
fn check_milan_chain_signature_failure() {
let cert_table = vec![CertTableEntry::new(CertType::VCEK, VCEK.to_vec())];
let VendorCertificates { ask, ark, asvk } = load_milan_cert_chain().as_ref().unwrap();
// toggle ark <=> ask
verify_cert_chain(&cert_table, ark, ask, asvk).unwrap_err();
}
#[test]
fn check_report_signature() {
let attestation_report =
bincode::deserialize::<AttestationReport>(VCEK_REPORT.as_slice()).unwrap();
let cert_chain = vec![CertTableEntry::new(CertType::VCEK, VCEK.to_vec())];
let vendor_certs = load_milan_cert_chain().as_ref().unwrap();
verify_report_signature(&attestation_report, &cert_chain, vendor_certs).unwrap();
}
#[test]
fn check_vlek_report_signature() {
let attestation_report =
bincode::deserialize::<AttestationReport>(VLEK_REPORT.as_slice()).unwrap();
let cert_chain = vec![CertTableEntry::new(CertType::VLEK, VLEK.to_vec())];
let vendor_certs = load_milan_cert_chain().as_ref().unwrap();
verify_report_signature(&attestation_report, &cert_chain, vendor_certs).unwrap();
}
#[test]
fn check_report_signature_failure() {
let mut bytes = VCEK_REPORT.clone();
// corrupt some byte
bytes[42] += 1;
let attestation_report = bincode::deserialize::<AttestationReport>(&bytes).unwrap();
let cert_chain = vec![CertTableEntry::new(CertType::VCEK, VCEK.to_vec())];
let vendor_certs = load_milan_cert_chain().as_ref().unwrap();
verify_report_signature(&attestation_report, &cert_chain, vendor_certs).unwrap_err();
}
#[test]
fn check_vlek_report_signature_failure() {
let mut bytes = VLEK_REPORT.clone();
// corrupt some byte
bytes[42] += 1;
let attestation_report = bincode::deserialize::<AttestationReport>(&bytes).unwrap();
let cert_chain = vec![CertTableEntry::new(CertType::VLEK, VLEK.to_vec())];
let vendor_certs = load_milan_cert_chain().as_ref().unwrap();
verify_report_signature(&attestation_report, &cert_chain, vendor_certs).unwrap_err();
}
}