-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathmod.rs
More file actions
1043 lines (884 loc) · 35.4 KB
/
Copy pathmod.rs
File metadata and controls
1043 lines (884 loc) · 35.4 KB
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::*;
use self::serde::{Deserialize, Serialize};
use anyhow::anyhow;
use asn1_rs::{oid, FromDer, Integer, OctetString, Oid};
use async_trait::async_trait;
use http_cache_reqwest::{
Cache, CacheMode, HttpCache, HttpCacheOptions, MokaCacheBuilder, MokaManager,
};
use openssl::{
nid::Nid,
x509::{self, X509},
};
use reqwest::{Response as ReqwestResponse, StatusCode};
use reqwest_middleware::ClientBuilder;
use serde;
use serde_json::json;
use sev::{
certs::snp::{ca::Chain as CaChain, Certificate, Chain, Verifiable},
firmware::{
guest::AttestationReport,
host::{CertTableEntry, CertType},
},
};
use std::{
collections::HashMap,
hash::Hash,
result::Result::Ok,
sync::{LazyLock, OnceLock},
};
use strum::{Display, EnumIter, EnumString, IntoEnumIterator};
use tracing::{debug, instrument, warn};
use x509_parser::prelude::*;
use std::time::Instant;
#[derive(Serialize, Deserialize)]
pub struct SnpEvidence {
attestation_report: AttestationReport,
cert_chain: Option<Vec<CertTableEntry>>,
}
impl SnpEvidence {
pub fn new(
attestation_report: AttestationReport,
cert_chain: Option<Vec<CertTableEntry>>,
) -> Self {
Self {
attestation_report,
cert_chain,
}
}
}
pub(crate) const HW_ID_OID: Oid<'static> = oid!(1.3.6 .1 .4 .1 .3704 .1 .4);
pub(crate) const UCODE_SPL_OID: Oid<'static> = oid!(1.3.6 .1 .4 .1 .3704 .1 .3 .8);
pub(crate) const SNP_SPL_OID: Oid<'static> = oid!(1.3.6 .1 .4 .1 .3704 .1 .3 .3);
pub(crate) const TEE_SPL_OID: Oid<'static> = oid!(1.3.6 .1 .4 .1 .3704 .1 .3 .2);
pub(crate) const LOADER_SPL_OID: Oid<'static> = oid!(1.3.6 .1 .4 .1 .3704 .1 .3 .1);
pub(crate) const FMC_SPL_OID: Oid<'static> = oid!(1.3.6 .1 .4 .1 .3704 .1 .3 .9);
// KDS URL parameters
const KDS_CERT_SITE: &str = "https://kdsintf.amd.com";
const KDS_VCEK: &str = "/vcek/v1";
// KDS Offline Store
const KDS_OFFLINE_STORE_PATH: &str = "/opt/confidential-containers/attestation-service/kds-store";
/// Attestation report versions supported
const REPORT_VERSION_MIN: u32 = 3;
const REPORT_VERSION_MAX: u32 = 5;
pub(crate) static CERT_CHAINS: LazyLock<HashMap<ProcessorGeneration, VendorCertificates>> =
LazyLock::new(|| {
let mut map = HashMap::new();
for proc in ProcessorGeneration::iter() {
let cert_authority = match proc {
ProcessorGeneration::Milan => include_bytes!("milan_ask_ark_asvk.pem"),
ProcessorGeneration::Genoa => include_bytes!("genoa_ask_ark_asvk.pem"),
ProcessorGeneration::Turin => include_bytes!("turin_ask_ark_asvk.pem"),
};
let certs = X509::stack_from_pem(cert_authority).unwrap();
if certs.len() != 3 {
panic!(
"Malformed cached Vendor Certs for {} processor (ASK, ARK, ASVK)",
proc
);
}
let vendor_certs = VendorCertificates {
ask: Certificate::from(certs[0].clone()),
ark: Certificate::from(certs[1].clone()),
asvk: Certificate::from(certs[2].clone()),
};
map.insert(proc, vendor_certs);
}
map
});
static VCEK_CACHE_MANAGER: OnceLock<MokaManager> = OnceLock::new();
fn init_cache_manager() -> MokaManager {
MokaManager::new(MokaCacheBuilder::new(1024).build())
}
#[derive(Clone, Debug, Default)]
pub struct Snp {
verifier_config: SnpVerifierConfig,
}
impl Snp {
pub async fn new(config: Option<SnpVerifierConfig>) -> Result<Self> {
Ok(Snp {
verifier_config: config.unwrap_or_default(),
})
}
fn build_vcek_client(&self) -> reqwest_middleware::ClientWithMiddleware {
let client_options = HttpCacheOptions {
cache_status_headers: true,
..Default::default()
};
let cache = Cache(HttpCache {
mode: CacheMode::Default,
manager: VCEK_CACHE_MANAGER.get_or_init(init_cache_manager).clone(),
options: client_options,
});
ClientBuilder::new(reqwest::Client::new())
.with(cache)
.build()
}
/// Fetches VCEK by trying each configured source in order until one succeeds
async fn fetch_vcek(
&self,
att_report: AttestationReport,
proc_gen: ProcessorGeneration,
) -> Result<Vec<u8>> {
for source in &self.verifier_config.vcek_sources {
let result = match source {
VCEKSource::OfflineStore { path } => {
self.fetch_vcek_from_offline_store(att_report, &proc_gen, path.clone())
}
VCEKSource::KDS { base_url } => {
self.fetch_vcek_from_kds(att_report, &proc_gen, base_url.clone())
.await
}
};
if let Ok(vcek_bytes) = result {
debug!("fetched vcek from {:?}", source);
return Ok(vcek_bytes);
}
}
debug!(
"failed to fetch vcek from all configured sources {:?}",
self.verifier_config.vcek_sources
);
bail!("Failed to fetch VCEK from any configured source")
}
fn fetch_vcek_from_offline_store(
&self,
att_report: AttestationReport,
proc_gen: &ProcessorGeneration,
path: Option<String>,
) -> Result<Vec<u8>> {
// default dir should contain the /vcek segment
let path = path.unwrap_or(KDS_OFFLINE_STORE_PATH.to_string());
let hw_id = self.parse_hw_id_from_vcek(att_report, proc_gen.clone());
let vcek_path = format!("{}/vcek/{}/vcek.der", path, hw_id);
let vcek_bytes = std::fs::read(&vcek_path)
.with_context(|| format!("Failed to read VCEK from offline store at {}", vcek_path))?;
Ok(vcek_bytes)
}
fn parse_hw_id_from_vcek(
&self,
att_report: AttestationReport,
proc_gen: ProcessorGeneration,
) -> String {
match proc_gen {
ProcessorGeneration::Turin => {
let shorter_bytes: &[u8] = &att_report.chip_id[0..8];
hex::encode(shorter_bytes)
}
_ => hex::encode(att_report.chip_id),
}
}
/// Asynchronously fetches the VCEK from the Key Distribution Service (KDS) using the provided attestation report.
/// Returns the VCEK in DER format.
async fn fetch_vcek_from_kds(
&self,
att_report: AttestationReport,
proc_gen: &ProcessorGeneration,
kds_url: Option<String>,
) -> Result<Vec<u8>> {
// Use attestation report to get data for URL
if att_report.chip_id.as_slice() == [0; 64] {
bail!("Hardware ID is 0s on attestation report. Confirm that MASK_CHIP_ID is set to 0 to request VCEK from KDS.");
}
let hw_id = self.parse_hw_id_from_vcek(att_report, proc_gen.clone());
// Request VCEK from KDS
let vcek_url: String = match proc_gen {
ProcessorGeneration::Turin => {
let Some(fmc) = att_report.reported_tcb.fmc else {
bail!("A Turin processor must have a fmc value");
};
format!(
"{}{KDS_VCEK}/{}/\
{hw_id}?fmcSPL={:02}&blSPL={:02}&teeSPL={:02}&snpSPL={:02}&ucodeSPL={:02}",
kds_url.unwrap_or(KDS_CERT_SITE.to_string()),
proc_gen,
fmc,
att_report.reported_tcb.bootloader,
att_report.reported_tcb.tee,
att_report.reported_tcb.snp,
att_report.reported_tcb.microcode
)
}
_ => {
format!(
"{}{KDS_VCEK}/{}/\
{hw_id}?blSPL={:02}&teeSPL={:02}&snpSPL={:02}&ucodeSPL={:02}",
kds_url.unwrap_or(KDS_CERT_SITE.to_string()),
proc_gen,
att_report.reported_tcb.bootloader,
att_report.reported_tcb.tee,
att_report.reported_tcb.snp,
att_report.reported_tcb.microcode
)
}
};
let client = self.build_vcek_client();
let start = Instant::now();
let vcek_rsp: ReqwestResponse = client
.get(vcek_url.clone())
.send()
.await
.context("Unable to send request for VCEK")?;
let duration = start.elapsed();
// Log cache status if available, otherwise log direct fetch
if let Some(cache_status) = vcek_rsp.headers().get("x-cache") {
debug!(
"VCEK fetch: {:?} from {:?} ({:?})",
cache_status, vcek_url, duration
);
} else {
debug!(
"VCEK fetch: direct from KDS {:?} ({:?})",
vcek_url, duration
);
}
match vcek_rsp.status() {
StatusCode::OK => {
let vcek_rsp_bytes: Vec<u8> = vcek_rsp
.bytes()
.await
.context("Unable to parse VCEK")?
.to_vec();
Ok(vcek_rsp_bytes)
}
status => bail!("Unable to fetch VCEK from URL: {status:?}, {vcek_url:?}"),
}
}
}
fn default_vcek_sources() -> Vec<VCEKSource> {
vec![VCEKSource::KDS { base_url: None }]
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct SnpVerifierConfig {
#[serde(default = "default_vcek_sources")]
pub vcek_sources: Vec<VCEKSource>,
}
impl Default for SnpVerifierConfig {
fn default() -> Self {
Self {
vcek_sources: default_vcek_sources(),
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub enum VCEKSource {
OfflineStore { path: Option<String> },
KDS { base_url: Option<String> },
}
#[derive(Clone, Debug)]
pub(crate) enum VendorEndorsementKey {
Vcek,
Vlek,
}
#[derive(Clone, Debug)]
pub(crate) struct VendorCertificates {
pub(crate) ask: Certificate,
pub(crate) ark: Certificate,
pub(crate) asvk: Certificate,
}
#[derive(Debug, Clone, PartialEq, Eq, EnumString, Display, EnumIter, Hash)]
#[strum(serialize_all = "PascalCase", ascii_case_insensitive)]
pub(crate) enum ProcessorGeneration {
/// 3rd Gen AMD EPYC Processor (Standard)
Milan,
/// 4th Gen AMD EPYC Processor (Standard)
Genoa,
/// 5th Gen AMD EPYC Processor (Standard)
Turin,
}
#[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.
#[instrument(skip_all, name = "AMD SNP")]
async fn evaluate(
&self,
evidence: TeeEvidence,
expected_report_data: &ReportData,
expected_init_data_hash: &InitDataHash,
) -> Result<Vec<(TeeEvidenceParsedClaim, TeeClass)>> {
let SnpEvidence {
attestation_report: report,
cert_chain,
} = serde_json::from_value(evidence).context("Deserialize SNP Evidence failed")?;
// See Trustee Issue#589 https://github.com/confidential-containers/trustee/issues/589
// Version 3 minimum is needed to tell processor type in report
if report.version < REPORT_VERSION_MIN {
bail!("Attestation Report version is too old. Please update your firmware.");
} else if report.version > REPORT_VERSION_MAX {
bail!("Unexpected attestation report version. Check SNP Firmware ABI specification");
}
// Get the processor model from the report
let proc_gen: ProcessorGeneration = get_processor_generation(&report)?;
// Get vendor certs for specific processor type
let vendor_certs = CERT_CHAINS
.get(&proc_gen)
.ok_or_else(|| anyhow!("Vendor certs not found for processor type: {proc_gen:?}"))?;
// Get the Version Endorsement Key (VEK) from the provided certs or KDS
let vek = match cert_chain {
// If the user provided cert chain, use that.
Some(chain) => {
// Initialize certs as options, will be filled out if left as none
let mut ask: Option<Certificate> = None;
let mut ark: Option<Certificate> = None;
let mut vek: Option<Certificate> = None;
let mut vek_type = VendorEndorsementKey::Vcek;
// Iterate through the cert chain and find the ASK, ARK, and VCEK/VLEK
for cert in chain.iter() {
match cert.cert_type {
CertType::ARK => {
// If the user provided ARK, verify against our trusted ARK
let provisioned_ark = vendor_certs.ark.clone();
ark = Some(Certificate::from_bytes(cert.data.as_slice())?);
(&provisioned_ark, &ark.clone().unwrap())
.verify()
.context("Provided ARK has an invalid signature")?;
}
CertType::ASK => {
ask = Some(Certificate::from_bytes(cert.data.as_slice())?);
}
// If both VLEK and VCEK are present, use the first one found
CertType::VCEK => {
if vek.is_none() {
vek = Some(Certificate::from_bytes(cert.data.as_slice())?);
}
}
CertType::VLEK => {
if vek.is_none() {
vek_type = VendorEndorsementKey::Vlek;
vek = Some(Certificate::from_bytes(cert.data.as_slice())?);
}
}
_ => continue,
}
}
let vek = vek.as_ref().ok_or_else(|| {
anyhow!("If a cert chain is provided, it must include a VCEK/VLEK")
})?;
// Make sure we have all the required certificates
// Missing certs will be filled with the vendor certs
let chain = Chain {
ca: CaChain {
ark: ark.unwrap_or_else(|| vendor_certs.ark.clone()),
ask: ask.unwrap_or_else(|| match vek_type {
VendorEndorsementKey::Vlek => vendor_certs.asvk.clone(),
VendorEndorsementKey::Vcek => vendor_certs.ask.clone(),
}),
},
vek: vek.clone(),
};
// Verify the chain and return vek if succesful
chain
.verify()
.context("Certificate chain provided by user failed to verify")?;
// Return the vek
vek.clone()
}
// No certificate chain provided, so we need to request the VCEK from configured sources
_ => {
// Get VCEK from configured sources (tries each in order)
let vcek_buf = self
.fetch_vcek(report, proc_gen.clone())
.await
.context("Failed to fetch VCEK from any configured source")?;
let vcek = Certificate::from_bytes(&vcek_buf)
.context("Failed to convert KDS VCEK into certificate")?;
let chain = Chain {
ca: CaChain {
ark: vendor_certs.ark.clone(),
ask: vendor_certs.ask.clone(),
},
vek: vcek.clone(),
};
// Verify the chain and return vek if succesful
chain
.verify()
.context("Certificate chain from KDS failed verification")?;
// Return the vcek
vcek.clone()
}
};
// Verify the report signature using the VEK
(&vek, &report)
.verify()
.context("Report signature verification against VEK signature failed")?;
// Verify the TCB values in the report against the VEK
verify_report_tcb(&report, vek, proc_gen).context("Reported TCB values do not match")?;
if report.vmpl != 0 {
bail!("VMPL Check Failed");
}
// Verify expected data
if let ReportData::Value(expected_report_data) = expected_report_data {
debug!("Check the binding of REPORT_DATA.");
let expected_report_data: Vec<u8> =
regularize_data(expected_report_data, 64, "REPORT_DATA", "SNP");
if expected_report_data != report.report_data.to_vec() {
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.to_vec() {
bail!("Host Data Mismatch");
}
}
let claims_map = parse_tee_evidence(&report);
let json = json!(claims_map);
Ok(vec![(json, "cpu".to_string())])
}
}
/// Retrieves the octet string value for a given OID from a certificate's extensions.
/// Supports both raw and DER-encoded formats.
pub(crate) 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.
pub(crate) 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 Vendor Endorsement Key (VEK).
pub(crate) fn verify_report_tcb(
report: &AttestationReport,
vek: Certificate,
proc_gen: ProcessorGeneration,
) -> Result<()> {
// OpenSSL bindings do not expose custom extensions
// Parse the key using x509_parser
let endorsement_key_der = vek.to_der()?;
let parsed_endorsement_key = X509Certificate::from_der(&endorsement_key_der)?
.1
.tbs_certificate;
let common_name =
get_common_name(&vek.into()).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"));
}
// FMC is a Turin+ field only
if proc_gen == ProcessorGeneration::Turin
&& get_oid_int(&parsed_endorsement_key, FMC_SPL_OID)? != report.reported_tcb.fmc.unwrap()
{
return Err(anyhow!("FMC version mismatch"));
}
Ok(())
}
/// Parses the attestation report and extracts the TEE evidence claims.
/// Returns a JSON-formatted map of parsed claims.
/// Note: Uses hex encoding for consistency with other verifiers (TDX, SGX, vTPM).
pub(crate) fn parse_tee_evidence(report: &AttestationReport) -> TeeEvidenceParsedClaim {
let claims_map = json!({
// policy fields
"policy_abi_major": report.policy.abi_major(),
"policy_abi_minor": report.policy.abi_minor(),
"policy_smt_allowed": report.policy.smt_allowed(),
"policy_migrate_ma": report.policy.migrate_ma_allowed(),
"policy_debug_allowed": report.policy.debug_allowed(),
"policy_single_socket": report.policy.single_socket_required(),
// versioning info
"reported_tcb_bootloader": report.reported_tcb.bootloader,
"reported_tcb_tee": report.reported_tcb.tee,
"reported_tcb_snp": report.reported_tcb.snp,
"reported_tcb_microcode": report.reported_tcb.microcode,
// platform info
"platform_tsme_enabled": report.plat_info.tsme_enabled(),
"platform_smt_enabled": report.plat_info.smt_enabled(),
// measurements
"measurement": hex::encode(report.measurement),
"report_data": hex::encode(report.report_data),
"init_data": hex::encode(report.host_data),
});
claims_map as TeeEvidenceParsedClaim
}
/// Extracts the common name (CN) from the subject name of a certificate.
pub(crate) 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");
}
let common_name = e
.data()
.to_string()
.context("Failed to convert CN to string")?;
Ok(common_name)
}
/// Determines the processor model based on the family and model IDs from the attestation report.
pub(crate) fn get_processor_generation(
att_report: &AttestationReport,
) -> Result<ProcessorGeneration> {
let cpu_fam = att_report
.cpuid_fam_id
.ok_or_else(|| anyhow::anyhow!("Attestation report version 3+ is missing CPU family ID"))?;
let cpu_mod = att_report
.cpuid_mod_id
.ok_or_else(|| anyhow::anyhow!("Attestation report version 3+ is missing CPU model ID"))?;
match cpu_fam {
0x19 => match cpu_mod {
0x0..=0xF => Ok(ProcessorGeneration::Milan),
0x10..=0x1F | 0xA0..0xAF => Ok(ProcessorGeneration::Genoa),
_ => Err(anyhow::anyhow!("Processor model not supported")),
},
0x1A => match cpu_mod {
0x0..=0x11 => Ok(ProcessorGeneration::Turin),
_ => Err(anyhow::anyhow!("Processor model not supported")),
},
_ => Err(anyhow::anyhow!("Processor family not supported")),
}
}
#[cfg(test)]
mod tests {
use super::*;
use sev::parser::ByteParser;
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; 1319] = include_bytes!("../../test_data/snp/test-vlek.der");
const VLEK_REPORT: &[u8; 1184] = include_bytes!("../../test_data/snp/test-vlek-report.bin");
const DYNAMIC_EVIDENCE: &[u8; 6714] =
include_bytes!("../../../../attestation-service/tests/e2e/evidence.json");
#[test]
fn check_milan_certificates() {
let VendorCertificates { ask, ark, asvk } =
CERT_CHAINS.get(&ProcessorGeneration::Milan).unwrap();
assert_eq!(get_common_name(ark.into()).unwrap(), "ARK-Milan");
assert_eq!(get_common_name(ask.into()).unwrap(), "SEV-Milan");
assert_eq!(get_common_name(asvk.into()).unwrap(), "SEV-VLEK-Milan");
(ark, ark)
.verify()
.context("Invalid ARK Signature")
.unwrap();
(ark, ask)
.verify()
.context("Invalid ASK Signature")
.unwrap();
(ark, asvk)
.verify()
.context("Invalid ASVK Signature")
.unwrap();
}
#[test]
fn check_genoa_certificates() {
let VendorCertificates { ask, ark, asvk } =
CERT_CHAINS.get(&ProcessorGeneration::Genoa).unwrap();
assert_eq!(get_common_name(ark.into()).unwrap(), "ARK-Genoa");
assert_eq!(get_common_name(ask.into()).unwrap(), "SEV-Genoa");
assert_eq!(get_common_name(asvk.into()).unwrap(), "SEV-VLEK-Genoa");
(ark, ark)
.verify()
.context("Invalid ARK Signature")
.unwrap();
(ark, ask)
.verify()
.context("Invalid ASK Signature")
.unwrap();
(ark, asvk)
.verify()
.context("Invalid ASVK Signature")
.unwrap();
}
#[test]
fn check_turin_certificates() {
let VendorCertificates { ask, ark, asvk } =
CERT_CHAINS.get(&ProcessorGeneration::Turin).unwrap();
assert_eq!(get_common_name(ark.into()).unwrap(), "ARK-Turin");
assert_eq!(get_common_name(ask.into()).unwrap(), "SEV-Turin");
assert_eq!(get_common_name(asvk.into()).unwrap(), "SEV-VLEK-Turin");
(ark, ark)
.verify()
.context("Invalid ARK Signature")
.unwrap();
(ark, ask)
.verify()
.context("Invalid ASK Signature")
.unwrap();
(ark, asvk)
.verify()
.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 vcek = Certificate::from_bytes(VCEK).unwrap();
let VendorCertificates { ask, ark, asvk: _ } =
CERT_CHAINS.get(&ProcessorGeneration::Milan).unwrap();
let chain = Chain {
ca: CaChain {
ark: ark.clone(),
ask: ask.clone(),
},
vek: vcek.clone(),
};
chain.verify().unwrap();
}
#[test]
fn check_vcek_signature_failure() {
let mut vcek_bytes = *VCEK;
// corrupt some byte, while it should remain a valid cert
vcek_bytes[42] += 1;
let vcek = Certificate::from_bytes(&vcek_bytes).unwrap();
let VendorCertificates { ask, ark, asvk: _ } =
CERT_CHAINS.get(&ProcessorGeneration::Milan).unwrap();
let chain = Chain {
ca: CaChain {
ark: ark.clone(),
ask: ask.clone(),
},
vek: vcek.clone(),
};
chain.verify().unwrap_err();
}
#[test]
fn check_vlek_signature_verification() {
let vlek = Certificate::from_bytes(VLEK).unwrap();
let VendorCertificates { ask: _, ark, asvk } =
CERT_CHAINS.get(&ProcessorGeneration::Milan).unwrap();
let chain = Chain {
ca: CaChain {
ark: ark.clone(),
ask: asvk.clone(),
},
vek: vlek.clone(),
};
chain.verify().unwrap();
}
#[test]
fn check_vlek_signature_failure() {
let mut vlek_bytes = *VCEK;
// corrupt some byte, while it should remain a valid cert
vlek_bytes[42] += 1;
let vlek = Certificate::from_bytes(&vlek_bytes).unwrap();
let VendorCertificates { ask: _, ark, asvk } =
CERT_CHAINS.get(&ProcessorGeneration::Milan).unwrap();
let chain = Chain {
ca: CaChain {
ark: ark.clone(),
ask: asvk.clone(),
},
vek: vlek.clone(),
};
chain.verify().unwrap_err();
}
#[test]
fn check_milan_chain_signature_failure() {
let vcek = Certificate::from_bytes(VCEK).unwrap();
let VendorCertificates { ask: _, ark, asvk } =
CERT_CHAINS.get(&ProcessorGeneration::Milan).unwrap();
// toggle ark <=> ask
let chain = Chain {
ca: CaChain {
ark: ark.clone(),
ask: asvk.clone(),
},
vek: vcek.clone(),
};
chain.verify().unwrap_err();
}
#[test]
fn check_report_signature() {
let attestation_report = AttestationReport::from_bytes(VCEK_REPORT).unwrap();
let vcek = Certificate::from_bytes(VCEK).unwrap();
(&vcek, &attestation_report).verify().unwrap();
verify_report_tcb(&attestation_report, vcek, ProcessorGeneration::Milan).unwrap();
}
#[test]
fn check_vlek_report_signature() {
let attestation_report = AttestationReport::from_bytes(VLEK_REPORT).unwrap();
let vlek = Certificate::from_bytes(VLEK).unwrap();
(&vlek, &attestation_report).verify().unwrap();
verify_report_tcb(&attestation_report, vlek, ProcessorGeneration::Milan).unwrap();
}
#[test]
fn check_report_signature_failure() {
let mut bytes = *VCEK_REPORT;
// corrupt some byte
bytes[42] += 1;
let attestation_report = AttestationReport::from_bytes(&bytes).unwrap();
let vcek = Certificate::from_bytes(VCEK).unwrap();
(&vcek, &attestation_report).verify().unwrap_err();
}
#[test]
fn check_report_tcb_failure() {
let mut bytes = *VCEK_REPORT;
// corrupt some byte
bytes[384] += 1;
let attestation_report = AttestationReport::from_bytes(&bytes).unwrap();
let vcek = Certificate::from_bytes(VCEK).unwrap();
verify_report_tcb(&attestation_report, vcek, ProcessorGeneration::Milan).unwrap_err();
}
#[test]
fn check_vlek_report_signature_failure() {
let mut bytes = *VLEK_REPORT;
// corrupt some byte
bytes[42] += 1;
let attestation_report = AttestationReport::from_bytes(&bytes).unwrap();
let vlek = Certificate::from_bytes(VLEK).unwrap();
(&vlek, &attestation_report).verify().unwrap_err();
}
#[test]
fn check_vlek_report_tcb_failure() {
let mut bytes = *VLEK_REPORT;
// corrupt some byte
bytes[384] += 1;
let attestation_report = AttestationReport::from_bytes(&bytes).unwrap();
let vlek = Certificate::from_bytes(VLEK).unwrap();
verify_report_tcb(&attestation_report, vlek, ProcessorGeneration::Milan).unwrap_err();
}
#[test]
fn check_json_deserialize_report() {
let attestation_report = AttestationReport::from_bytes(VCEK_REPORT).unwrap();
let json_string = serde_json::to_string(&attestation_report).unwrap();
let deserialized_report: AttestationReport =
serde_json::from_str(&json_string).expect("Failed to deserialize JSON");
assert_eq!(attestation_report, deserialized_report);
}
#[test]
fn test_dynamic_evidence() {
let SnpEvidence {
attestation_report: report,
cert_chain,
} = serde_json::from_slice(DYNAMIC_EVIDENCE)
.context("Deserialize SNP Evidence failed")
.unwrap();
let vcek: Certificate = if let Some(chain) = cert_chain {
Certificate::from_bytes(chain[0].data.as_slice()).unwrap()
} else {
unreachable!("Test evidence should always have a cert chain")
};
(&vcek, &report)
.verify()
.context("Report signature verification against VEK signature failed")
.unwrap();
}
#[test]
fn test_hex_encoding_in_parsed_claims() {
// Parse attestation report
let attestation_report = AttestationReport::from_bytes(VCEK_REPORT).unwrap();
// Generate parsed claims
let claims = parse_tee_evidence(&attestation_report);
// Extract the three key fields that should be hex-encoded