-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathverify.rs
More file actions
2024 lines (1826 loc) · 71.8 KB
/
Copy pathverify.rs
File metadata and controls
2024 lines (1826 loc) · 71.8 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 core::time::Duration;
use anyhow::{bail, ensure, Context, Result};
use rustls_pki_types::UnixTime;
use scale::Decode;
#[cfg(feature = "default-x509")]
use crate::policy::{PckIdentity, PlatformInfo, Policy, QeInfo, QuoteClaims, TcbVerdict};
use {
crate::constants::*,
crate::policy::PckCertFlag,
crate::qe_identity::{QeIdentity, QeTcbLevel},
crate::tcb_info::{TcbInfo, TcbLevel, TcbStatus, TcbStatusWithAdvisory, TdxModuleTcbLevel},
alloc::string::String,
alloc::vec::Vec,
};
pub use crate::quote::{AuthData, EnclaveReport, Quote};
use crate::{
config::{Config, CryptoProvider},
quote::{Report, TDAttributes},
utils::{
encode_as_der_with, extract_certs, parse_crls, parse_rfc3339_unix_secs,
verify_certificate_chain,
},
};
use crate::{
quote::{TDReport10, TDReport15},
QuoteCollateralV3,
};
use rustls_pki_types::CertificateDer;
use serde::{Deserialize, Serialize};
/// Crypto backend configuration for quote verification.
///
/// Holds the signature verification algorithm and SHA-256 implementation
/// needed by the verification logic. Use [`ring::backend()`] or
/// [`rustcrypto::backend()`] to obtain a pre-configured instance.
pub struct CryptoBackend {
/// ECDSA P-256 SHA-256 algorithm for certificate and raw signature verification
pub sig_algo: &'static dyn rustls_pki_types::SignatureVerificationAlgorithm,
/// SHA-256 hash function
pub sha256: fn(&[u8]) -> [u8; 32],
/// SHA-384 hash function (used for root_key_id computation)
pub sha384: fn(&[u8]) -> [u8; 48],
/// Raw ECDSA `r || s` to DER encoder.
pub encode_ecdsa: fn(&[u8]) -> Result<Vec<u8>>,
/// Parse Intel PCK extensions with the configured X.509 backend.
pub parse_pck_extension: fn(&[u8]) -> Result<crate::intel::PckExtension>,
}
fn backend_for<C: Config>() -> CryptoBackend {
CryptoBackend {
sig_algo: C::Crypto::sig_algo(),
sha256: C::Crypto::sha256,
sha384: C::Crypto::sha384,
encode_ecdsa: encode_as_der_with::<C>,
parse_pck_extension: crate::intel::parse_pck_extension_with::<C>,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TeeType {
Sgx,
Tdx,
}
impl TeeType {
fn from_u32(value: u32) -> Result<Self> {
match value {
TEE_TYPE_SGX => Ok(TeeType::Sgx),
TEE_TYPE_TDX => Ok(TeeType::Tdx),
_ => bail!("Unsupported TEE type: {value}"),
}
}
fn is_tdx(&self) -> bool {
matches!(self, TeeType::Tdx)
}
}
#[cfg(feature = "js")]
use wasm_bindgen::prelude::*;
#[cfg(feature = "js")]
fn format_error_chain(e: &anyhow::Error) -> String {
use alloc::format;
let mut msg = format!("{}", e);
let mut source = e.source();
while let Some(err) = source {
msg.push_str(&format!("\n Caused by: {}", err));
source = err.source();
}
msg
}
#[cfg(feature = "borsh_schema")]
use borsh::BorshSchema;
#[cfg(feature = "borsh")]
use borsh::{BorshDeserialize, BorshSerialize};
use core::marker::PhantomData;
/// Result of cryptographic quote verification, before policy validation.
///
/// The enclave report is private — it can only be obtained by passing a [`Policy`]
/// via [`validate()`](Self::validate).
///
/// [`QuoteClaims`] is built lazily via [`claims()`](Self::claims) —
/// the `verify()` call itself does the minimum work (crypto only).
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[cfg_attr(feature = "borsh", derive(BorshSerialize, BorshDeserialize))]
#[cfg_attr(feature = "borsh_schema", derive(BorshSchema))]
struct QuoteVerificationResult {
header: crate::quote::Header,
report: Report,
collateral: QuoteCollateralV3,
#[serde(with = "crate::utils::serde_vec_bytes")]
pck_cert_chain_der: Vec<Vec<u8>>,
// -- core verification results (always computed) --
tee_type: u32,
tcb_status: TcbStatus,
advisory_ids: Vec<String>,
platform_tcb_level: TcbLevel,
qe_tcb_level: QeTcbLevel,
pck_ext: PckCertChainResult,
qe_report: EnclaveReport,
tcb_eval_data_number: u32,
qe_tcb_eval_data_number: u32,
#[serde(with = "serde_bytes")]
root_key_id: [u8; 48],
}
impl QuoteVerificationResult {
/// Build the full [`QuoteClaims`] from verification intermediates.
///
/// Computes the collateral time window from all 8 sources (TCBInfo, QEIdentity,
/// 2 CRLs, 4 certificate chains), root_key_id SHA-384, CRL numbers, and tcb_date_tag.
#[cfg(feature = "default-x509")]
pub fn claims(&self) -> Result<QuoteClaims> {
// Parse collateral JSON for time window computation
let tcb_info: TcbInfo = serde_json::from_str(&self.collateral.tcb_info)
.context("Failed to parse TcbInfo for claims")?;
let qe_identity: QeIdentity = serde_json::from_str(&self.collateral.qe_identity)
.context("Failed to parse QeIdentity for claims")?;
let pck_certs: Vec<CertificateDer<'_>> = self
.pck_cert_chain_der
.iter()
.map(|cert| CertificateDer::from(cert.as_slice()))
.collect();
let collateral_dates =
compute_collateral_time_window(&self.collateral, &pck_certs, &tcb_info, &qe_identity)?;
// root_key_id: SHA-384 of root CA's raw public key bytes
let root_key_id = self.root_key_id;
// CRL numbers
let root_ca_crl_num = crate::utils::extract_crl_number(&self.collateral.root_ca_crl)
.context("Failed to extract root CA CRL number")?;
let pck_crl_num = crate::utils::extract_crl_number(&self.collateral.pck_crl)
.context("Failed to extract PCK CRL number")?;
// tcb_date_tag
let tcb_date_tag = parse_rfc3339_unix_secs(&self.platform_tcb_level.tcb_date)
.context("Failed to parse platform TCB date")?;
Ok(QuoteClaims {
claims_version: 1,
header: self.header,
tee_type: self.tee_type,
tcb: TcbVerdict {
status: self.tcb_status,
advisory_ids: self.advisory_ids.clone(),
eval_data_number: self.tcb_eval_data_number,
},
platform: PlatformInfo {
tcb_level: self.platform_tcb_level.clone(),
tcb_date_tag,
pck: PckIdentity {
ppid: self.pck_ext.ppid.clone(),
cpu_svn: self.pck_ext.cpu_svn,
pce_svn: self.pck_ext.pce_svn,
pce_id: self.pck_ext.pce_id.clone(),
fmspc: self.pck_ext.fmspc,
sgx_type: self.pck_ext.sgx_type,
platform_instance_id: self.pck_ext.platform_instance_id,
dynamic_platform: self.pck_ext.dynamic_platform,
cached_keys: self.pck_ext.cached_keys,
smt_enabled: self.pck_ext.smt_enabled,
// Intel's upstream DCAP Rego policy checks
// `platform_provider_id`, but the upstream QvE producer
// currently leaves it as a TODO when building the platform
// measurement JSON:
// https://github.com/intel/confidential-computing.tee.dcap/blob/main/ae/QvE/qve/qve.cpp
platform_provider_id: None,
},
root_key_id: root_key_id.to_vec(),
pck_crl_num,
root_ca_crl_num,
},
qe: QeInfo {
tcb_level: self.qe_tcb_level.clone(),
report: self.qe_report,
tcb_eval_data_number: self.qe_tcb_eval_data_number,
},
report: self.report.clone(),
earliest_issue_date: collateral_dates.earliest_issue,
latest_issue_date: collateral_dates.latest_issue,
earliest_expiration_date: collateral_dates.earliest_expiration,
qe_iden_earliest_issue_date: collateral_dates.qe_iden_earliest_issue,
qe_iden_latest_issue_date: collateral_dates.qe_iden_latest_issue,
qe_iden_earliest_expiration_date: collateral_dates.qe_iden_earliest_expiration,
})
}
/// Convert directly into [`VerifiedReport`] **without applying any policy**.
///
/// # Warning
/// This skips all policy checks (TCB status, advisory IDs, collateral
/// freshness, platform flags). Use only when you handle validation
/// externally or intentionally accept any verification result.
pub fn into_report_unchecked(self) -> VerifiedReport {
let platform_status = TcbStatusWithAdvisory::new(
self.platform_tcb_level.tcb_status,
self.platform_tcb_level.advisory_ids.clone(),
);
let qe_status = TcbStatusWithAdvisory::new(
self.qe_tcb_level.tcb_status,
self.qe_tcb_level.advisory_ids.clone(),
);
VerifiedReport {
status: self.tcb_status.to_string(),
advisory_ids: self.advisory_ids,
report: self.report,
ppid: self.pck_ext.ppid,
platform_status,
qe_status,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[cfg_attr(feature = "borsh", derive(BorshSerialize, BorshDeserialize))]
#[cfg_attr(feature = "borsh_schema", derive(BorshSchema))]
pub struct VerifiedReport {
pub status: String,
pub advisory_ids: Vec<String>,
pub report: Report,
#[serde(with = "serde_bytes")]
pub ppid: Vec<u8>,
pub qe_status: TcbStatusWithAdvisory,
pub platform_status: TcbStatusWithAdvisory,
}
/// Quote verifier with configurable root certificate and crypto backend.
///
/// Provides both the backwards-compatible report API and the detailed claims API.
pub struct QuoteVerifier<C: Config = crate::configs::DefaultConfig> {
root_ca_der: Vec<u8>,
allow_service_td: bool,
allow_debug: bool,
config: PhantomData<C>,
}
#[cfg(feature = "default-x509")]
impl QuoteVerifier<crate::configs::DefaultConfig> {
/// Create a new verifier with a custom root certificate.
pub fn new(root_ca_der: Vec<u8>) -> Self {
Self {
root_ca_der,
allow_service_td: false,
allow_debug: false,
config: PhantomData,
}
}
/// Create a new verifier using Intel's production root certificate.
pub fn new_prod() -> Self {
Self::new(TRUSTED_ROOT_CA_DER.to_vec())
}
}
impl<C: Config> QuoteVerifier<C> {
/// Create a verifier for `C` with a custom root certificate.
pub fn new_with_config(root_ca_der: Vec<u8>) -> Self {
Self {
root_ca_der,
allow_service_td: false,
allow_debug: false,
config: PhantomData,
}
}
/// Select a different compile-time verification backend.
pub fn with_config<D: Config>(self) -> QuoteVerifier<D> {
QuoteVerifier {
root_ca_der: self.root_ca_der,
allow_service_td: self.allow_service_td,
allow_debug: self.allow_debug,
config: PhantomData,
}
}
pub fn allow_service_td(mut self, allow: bool) -> Self {
self.allow_service_td = allow;
self
}
pub fn allow_debug(mut self, allow: bool) -> Self {
self.allow_debug = allow;
self
}
/// Verify a quote, apply a policy, and return detailed serializable claims.
#[cfg(feature = "default-x509")]
pub fn verify_with_policy<P: Policy + ?Sized>(
&self,
raw_quote: &[u8],
collateral: impl Into<QuoteCollateralV3>,
now_secs: u64,
policy: &P,
) -> Result<QuoteClaims> {
let claims = self
.verify_result(raw_quote, collateral, now_secs)?
.claims()?;
policy.validate(&claims)?;
Ok(claims)
}
fn verify_result(
&self,
raw_quote: &[u8],
collateral: impl Into<QuoteCollateralV3>,
now_secs: u64,
) -> Result<QuoteVerificationResult> {
let backend = backend_for::<C>();
verify_impl(
raw_quote,
collateral.into(),
now_secs,
&self.root_ca_der,
&backend,
self.allow_service_td,
self.allow_debug,
#[cfg(feature = "danger-allow-tcb-override")]
None::<fn(TcbInfo) -> TcbInfo>,
)
}
/// Verify with the one-shot API using this verifier's [`Config`].
pub fn verify(
&self,
raw_quote: &[u8],
collateral: &QuoteCollateralV3,
now_secs: u64,
) -> Result<VerifiedReport> {
self.verify_result(raw_quote, collateral, now_secs)
.map(QuoteVerificationResult::into_report_unchecked)
}
/// Verify a quote with the configured root certificate, passing a TCB info override.
///
/// The override function receives `TcbInfo` after signature verification and can
/// modify it before TCB level matching. Use with extreme caution.
#[cfg(all(feature = "danger-allow-tcb-override", feature = "default-x509"))]
pub fn dangerous_verify_claims_with_tcb_override(
&self,
raw_quote: &[u8],
collateral: impl Into<QuoteCollateralV3>,
now_secs: u64,
override_tcb_info: impl FnOnce(TcbInfo) -> TcbInfo,
) -> Result<QuoteClaims> {
verify_impl(
raw_quote,
collateral.into(),
now_secs,
&self.root_ca_der,
&backend_for::<C>(),
self.allow_service_td,
self.allow_debug,
Some(override_tcb_info),
)?
.claims()
}
#[cfg(feature = "danger-allow-tcb-override")]
fn dangerous_verify_result_with_tcb_override<F: FnOnce(TcbInfo) -> TcbInfo>(
&self,
raw_quote: &[u8],
collateral: impl Into<QuoteCollateralV3>,
now_secs: u64,
override_tcb_info: F,
) -> Result<QuoteVerificationResult> {
let backend = backend_for::<C>();
verify_impl(
raw_quote,
collateral.into(),
now_secs,
&self.root_ca_der,
&backend,
self.allow_service_td,
self.allow_debug,
Some(override_tcb_info),
)
}
#[cfg(all(feature = "danger-allow-tcb-override", feature = "default-x509"))]
pub fn dangerous_verify_with_tcb_override(
&self,
raw_quote: &[u8],
collateral: &QuoteCollateralV3,
now_secs: u64,
override_tcb_info: impl FnOnce(TcbInfo) -> TcbInfo,
) -> Result<VerifiedReport> {
self.dangerous_verify_result_with_tcb_override(
raw_quote,
collateral,
now_secs,
override_tcb_info,
)
.map(QuoteVerificationResult::into_report_unchecked)
}
}
/// Backwards-compatible one-shot verification using [`DefaultConfig`].
#[cfg(feature = "default-x509")]
pub fn verify(
raw_quote: &[u8],
collateral: &QuoteCollateralV3,
now_secs: u64,
) -> Result<VerifiedReport> {
QuoteVerifier::<crate::configs::DefaultConfig>::new_prod()
.verify(raw_quote, collateral, now_secs)
}
#[cfg(all(feature = "default-x509", feature = "danger-allow-tcb-override"))]
pub fn dangerous_verify_with_tcb_override(
raw_quote: &[u8],
collateral: &QuoteCollateralV3,
now_secs: u64,
override_tcb_info: impl FnOnce(TcbInfo) -> TcbInfo,
) -> Result<VerifiedReport> {
QuoteVerifier::<crate::configs::DefaultConfig>::new_prod().dangerous_verify_with_tcb_override(
raw_quote,
collateral,
now_secs,
override_tcb_info,
)
}
/// Verification policy builder for JS/WASM.
///
/// ```js
/// const policy = new QuotePolicy(now)
/// .allow_status("OutOfDate")
/// .platform_grace_period(7n * 86400n)
/// .allow_smt(true);
/// ```
#[cfg(feature = "js")]
#[wasm_bindgen(js_name = "QuotePolicy")]
pub struct JsQuotePolicy {
inner: crate::policy::QuotePolicy,
}
#[cfg(feature = "js")]
fn js_parse_tcb_status(s: &str) -> Result<TcbStatus, JsValue> {
match s {
"UpToDate" => Ok(TcbStatus::UpToDate),
"SWHardeningNeeded" => Ok(TcbStatus::SWHardeningNeeded),
"ConfigurationNeeded" => Ok(TcbStatus::ConfigurationNeeded),
"ConfigurationAndSWHardeningNeeded" => Ok(TcbStatus::ConfigurationAndSWHardeningNeeded),
"OutOfDate" => Ok(TcbStatus::OutOfDate),
"OutOfDateConfigurationNeeded" => Ok(TcbStatus::OutOfDateConfigurationNeeded),
"Revoked" => Ok(TcbStatus::Revoked),
_ => Err(JsValue::from_str(&alloc::format!(
"Unknown TCB status: {s}"
))),
}
}
#[cfg(feature = "js")]
#[wasm_bindgen(js_class = "QuotePolicy")]
impl JsQuotePolicy {
/// Create a strict policy: only `UpToDate`, no grace period, no advisory blacklist.
#[wasm_bindgen(constructor)]
pub fn strict(now_secs: u64) -> Self {
Self {
inner: crate::policy::QuotePolicy::strict(now_secs),
}
}
/// Create a pass-through policy for downstream appraisal.
#[wasm_bindgen(js_name = "claimsOnly")]
pub fn claims_only(now_secs: u64) -> Self {
Self {
inner: crate::policy::QuotePolicy::claims_only(now_secs),
}
}
/// Allow an additional TCB status (e.g. "OutOfDate", "SWHardeningNeeded").
pub fn allow_status(self, status: &str) -> Result<JsQuotePolicy, JsValue> {
let s = js_parse_tcb_status(status)?;
Ok(Self {
inner: self.inner.allow_status(s),
})
}
/// Reject a specific advisory ID (e.g. "INTEL-SA-00334").
pub fn reject_advisory(self, id: &str) -> Self {
Self {
inner: self.inner.reject_advisory(id),
}
}
/// Reject multiple advisory IDs at once.
pub fn reject_advisories(self, ids: Vec<String>) -> Self {
Self {
inner: self.inner.reject_advisories(&ids),
}
}
/// Set platform grace period in seconds.
pub fn platform_grace_period(self, secs: u64) -> Self {
Self {
inner: self.inner.platform_grace_period(Duration::from_secs(secs)),
}
}
/// Set QE grace period in seconds.
pub fn qe_grace_period(self, secs: u64) -> Self {
Self {
inner: self.inner.qe_grace_period(Duration::from_secs(secs)),
}
}
/// Set minimum TCB evaluation data number.
pub fn min_tcb_eval_data_number(self, min: u32) -> Self {
Self {
inner: self.inner.min_tcb_eval_data_number(min),
}
}
/// Set whether dynamic platforms are allowed.
pub fn allow_dynamic_platform(self, allow: bool) -> Self {
Self {
inner: self.inner.allow_dynamic_platform(allow),
}
}
/// Set whether cached keys are allowed.
pub fn allow_cached_keys(self, allow: bool) -> Self {
Self {
inner: self.inner.allow_cached_keys(allow),
}
}
/// Set whether SMT (hyperthreading) is allowed.
pub fn allow_smt(self, allow: bool) -> Self {
Self {
inner: self.inner.allow_smt(allow),
}
}
/// Set accepted SGX types (e.g. [0, 1, 2]).
pub fn accepted_sgx_types(self, types: Vec<u8>) -> Self {
Self {
inner: self.inner.accepted_sgx_types(&types),
}
}
}
/// Quote verifier for JS/WASM.
///
/// ```js
/// const verifier = new QuoteVerifier(); // Intel production root CA
/// const verifier = new QuoteVerifier(rootCaDer); // custom root CA
/// const result = verifier.verify(quote, collateral, now);
/// ```
#[cfg(feature = "js")]
#[wasm_bindgen(js_name = "QuoteVerifier")]
pub struct JsQuoteVerifier {
inner: QuoteVerifier,
}
#[cfg(feature = "js")]
#[wasm_bindgen(js_class = "QuoteVerifier")]
impl JsQuoteVerifier {
/// Create a verifier. No argument = Intel production root CA; pass `rootCaDer` for custom.
#[wasm_bindgen(constructor)]
pub fn new(root_ca_der: Option<Vec<u8>>) -> Self {
let inner = match root_ca_der {
Some(der) => QuoteVerifier::new(der),
None => QuoteVerifier::new_prod(),
};
Self { inner }
}
/// Backwards-compatible one-shot verification returning `VerifiedReport`.
pub fn verify(
&self,
raw_quote: JsValue,
quote_collateral: JsValue,
now: u64,
) -> Result<JsValue, JsValue> {
let raw_quote: Vec<u8> = serde_wasm_bindgen::from_value(raw_quote)
.map_err(|_| JsValue::from_str("Failed to decode raw_quote"))?;
let quote_collateral =
serde_wasm_bindgen::from_value::<QuoteCollateralV3>(quote_collateral)?;
let report = self
.inner
.verify(&raw_quote, "e_collateral, now)
.map_err(|e| JsValue::from_str(&format_error_chain(&e)))?;
serde_wasm_bindgen::to_value(&report)
.map_err(|_| JsValue::from_str("Failed to encode verified report"))
}
/// Verify the quote, apply the built-in policy, and return claims.
pub fn verify_with_policy(
&self,
raw_quote: JsValue,
quote_collateral: JsValue,
now: u64,
policy: &JsQuotePolicy,
) -> Result<JsValue, JsValue> {
let raw_quote: Vec<u8> = serde_wasm_bindgen::from_value(raw_quote)
.map_err(|_| JsValue::from_str("Failed to decode raw_quote"))?;
let quote_collateral =
serde_wasm_bindgen::from_value::<QuoteCollateralV3>(quote_collateral)?;
let claims = self
.inner
.verify_with_policy(&raw_quote, quote_collateral, now, &policy.inner)
.map_err(|e| JsValue::from_str(&format_error_chain(&e)))?;
serde_wasm_bindgen::to_value(&claims)
.map_err(|_| JsValue::from_str("Failed to encode quote claims"))
}
/// Fetch collateral from a PCCS server.
pub async fn get_collateral(pccs_url: &str, raw_quote: JsValue) -> Result<JsValue, JsValue> {
let raw_quote: Vec<u8> = serde_wasm_bindgen::from_value(raw_quote)
.map_err(|_| JsValue::from_str("Failed to decode raw_quote"))?;
let collateral: QuoteCollateralV3 =
crate::collateral::CollateralClient::with_default_http(pccs_url)
.map_err(|e| JsValue::from_str(&format_error_chain(&e)))?
.fetch(&raw_quote)
.await
.map_err(|e| JsValue::from_str(&format_error_chain(&e)))?;
serde_wasm_bindgen::to_value(&collateral)
.map_err(|_| JsValue::from_str("Failed to encode collateral"))
}
}
// =============================================================================
// Step 1: Verify TCB Info signature (Intel Root -> TCB Signing Cert -> TCB Info JSON)
// =============================================================================
/// Verify TCB Info collateral: certificate chain, signature, parsing, and expiration check
fn verify_tcb_info_signature(
collateral: &QuoteCollateralV3,
now: UnixTime,
crls: &[webpki::CertRevocationList<'_>],
trust_anchor: rustls_pki_types::TrustAnchor,
backend: &CryptoBackend,
) -> Result<TcbInfo> {
// Parse TCB Info
let tcb_info = serde_json::from_str::<TcbInfo>(&collateral.tcb_info)
.context("Failed to decode TcbInfo")?;
// Check validity window
let issue_date = parse_rfc3339_unix_secs(&tcb_info.issue_date)
.context("Failed to parse TCB Info issue date")?;
let next_update = parse_rfc3339_unix_secs(&tcb_info.next_update)
.context("Failed to parse TCB Info next update")?;
if now.as_secs() < issue_date {
bail!("TCBInfo issue date is in the future");
}
if now.as_secs() > next_update {
bail!("TCBInfo expired");
}
// Verify certificate chain
let tcb_certs = extract_certs(collateral.tcb_info_issuer_chain.as_bytes())?;
let [tcb_leaf, tcb_chain @ ..] = &tcb_certs[..] else {
bail!("Certificate chain is too short for TCB Info");
};
let tcb_leaf_cert = webpki::EndEntityCert::try_from(tcb_leaf)
.context("Failed to parse TCB Info leaf certificate")?;
verify_certificate_chain(&tcb_leaf_cert, tcb_chain, now, crls, trust_anchor)?;
// Verify signature
let asn1_signature = (backend.encode_ecdsa)(&collateral.tcb_info_signature)?;
if tcb_leaf_cert
.verify_signature(
backend.sig_algo,
collateral.tcb_info.as_bytes(),
&asn1_signature,
)
.is_err()
{
bail!("Signature is invalid for tcb_info in quote_collateral");
}
Ok(tcb_info)
}
// =============================================================================
// Step 2: Verify QE Identity signature (Intel Root -> QE Identity Signing Cert -> QE Identity JSON)
// =============================================================================
/// Verify QE Identity collateral: certificate chain, signature, parsing, and expiration check
fn verify_qe_identity_signature(
collateral: &QuoteCollateralV3,
now: UnixTime,
crls: &[webpki::CertRevocationList<'_>],
trust_anchor: rustls_pki_types::TrustAnchor,
backend: &CryptoBackend,
) -> Result<QeIdentity> {
// Parse QE Identity
let qe_identity = serde_json::from_str::<QeIdentity>(&collateral.qe_identity)
.context("Failed to decode QeIdentity")?;
// Check validity window
let issue_date = parse_rfc3339_unix_secs(&qe_identity.issue_date)
.context("Failed to parse QE Identity issue date")?;
let next_update = parse_rfc3339_unix_secs(&qe_identity.next_update)
.context("Failed to parse QE Identity next update")?;
if now.as_secs() < issue_date {
bail!("QE Identity issue date is in the future");
}
if now.as_secs() > next_update {
bail!("QE Identity expired");
}
// Verify certificate chain
let qe_id_certs = extract_certs(collateral.qe_identity_issuer_chain.as_bytes())?;
let [qe_id_leaf, qe_id_chain @ ..] = &qe_id_certs[..] else {
bail!("Certificate chain is too short for QE Identity");
};
let qe_id_leaf_cert = webpki::EndEntityCert::try_from(qe_id_leaf)
.context("Failed to parse QE Identity leaf certificate")?;
verify_certificate_chain(&qe_id_leaf_cert, qe_id_chain, now, crls, trust_anchor)?;
// Verify signature
let qe_id_asn1_signature = (backend.encode_ecdsa)(&collateral.qe_identity_signature)?;
if qe_id_leaf_cert
.verify_signature(
backend.sig_algo,
collateral.qe_identity.as_bytes(),
&qe_id_asn1_signature,
)
.is_err()
{
bail!("Signature is invalid for qe_identity in quote_collateral");
}
Ok(qe_identity)
}
// =============================================================================
// Step 3: Verify PCK certificate chain (Intel Root -> PCK CA -> PCK Cert)
// =============================================================================
/// Verify PCK certificate chain and extract platform data
///
/// Verifies the PCK certificate chain against the trusted root and CRLs.
/// Extracts cpu_svn, pce_svn, fmspc, and ppid from the certificate.
fn verify_pck_cert_chain(
collateral: &QuoteCollateralV3,
certification_data: &crate::quote::CertificationData,
now: UnixTime,
crls: &[webpki::CertRevocationList<'_>],
trust_anchor: rustls_pki_types::TrustAnchor,
backend: &CryptoBackend,
) -> Result<PckCertChainResult> {
// Extract PCK certificate chain - prefer collateral, fall back to quote
let certification_certs = if let Some(pem_chain) = &collateral.pck_certificate_chain {
extract_certs(pem_chain.as_bytes())
.context("Failed to extract PCK certificates from collateral")?
} else {
if certification_data.cert_type != PCK_CERT_CHAIN {
bail!("Unsupported DCAP PCK cert format: {}. Use get_collateral() to fetch PCK certificate.", certification_data.cert_type);
}
extract_certs(&certification_data.body.data)
.context("Failed to extract PCK certificates from quote")?
};
let [pck_leaf, pck_chain @ ..] = &certification_certs[..] else {
bail!("Certificate chain is too short in quote");
};
// Verify PCK certificate chain
let pck_leaf_cert =
webpki::EndEntityCert::try_from(pck_leaf).context("Failed to parse PCK certificate")?;
verify_certificate_chain(&pck_leaf_cert, pck_chain, now, crls, trust_anchor)?;
// Extract Intel extension data from PCK cert (parsed once)
let pck_ext = (backend.parse_pck_extension)(pck_leaf)?;
// Preserve pce_id as the raw value from the PCK cert SGX extension.
let pce_id = pck_ext.pce_id.clone();
// Convert platform_instance_id to fixed-size array
let platform_instance_id = pck_ext.platform_instance_id.as_ref().and_then(|v| {
let arr: [u8; 16] = v.as_slice().try_into().ok()?;
Some(arr)
});
Ok(PckCertChainResult {
pck_cert_chain_der: certification_certs
.iter()
.map(|cert| cert.as_ref().to_vec())
.collect(),
pck_leaf_der: pck_leaf.as_ref().to_vec(),
ppid: pck_ext.ppid,
cpu_svn: pck_ext.cpu_svn,
pce_svn: pck_ext.pce_svn,
fmspc: pck_ext.fmspc,
pce_id,
sgx_type: pck_ext.sgx_type as u8,
platform_instance_id,
dynamic_platform: pck_ext.dynamic_platform.into(),
cached_keys: pck_ext.cached_keys.into(),
smt_enabled: pck_ext.smt_enabled.into(),
})
}
/// Result from PCK certificate chain verification
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "borsh", derive(BorshSerialize, BorshDeserialize))]
#[cfg_attr(feature = "borsh_schema", derive(BorshSchema))]
struct PckCertChainResult {
#[serde(with = "crate::utils::serde_vec_bytes")]
pck_cert_chain_der: Vec<Vec<u8>>,
#[serde(with = "serde_bytes")]
pck_leaf_der: Vec<u8>,
#[serde(with = "serde_bytes")]
ppid: Vec<u8>,
#[serde(with = "serde_bytes")]
cpu_svn: [u8; 16],
pce_svn: u16,
#[serde(with = "serde_bytes")]
fmspc: [u8; 6],
#[serde(with = "serde_bytes")]
pce_id: Vec<u8>,
sgx_type: u8,
platform_instance_id: Option<[u8; 16]>,
dynamic_platform: PckCertFlag,
cached_keys: PckCertFlag,
smt_enabled: PckCertFlag,
}
// =============================================================================
// Step 4: Verify QE Report signature (PCK Cert signs QE Report)
// =============================================================================
/// Verify QE report signature using PCK certificate
fn verify_qe_report_signature(
pck_leaf: &CertificateDer,
auth_data: &crate::quote::AuthDataV3,
backend: &CryptoBackend,
) -> Result<EnclaveReport> {
let pck_leaf_cert =
webpki::EndEntityCert::try_from(pck_leaf).context("Failed to parse PCK certificate")?;
// Verify QE report signature (signed by PCK)
let qe_report_signature = (backend.encode_ecdsa)(&auth_data.qe_report_signature)?;
if pck_leaf_cert
.verify_signature(backend.sig_algo, &auth_data.qe_report, &qe_report_signature)
.is_err()
{
bail!("Signature is invalid for qe_report in quote");
}
// Decode QE report
let mut qe_report_slice = auth_data.qe_report.as_slice();
let qe_report =
EnclaveReport::decode(&mut qe_report_slice).context("Failed to decode QE report")?;
Ok(qe_report)
}
// =============================================================================
// Step 5: Verify QE Report content (QE Hash = hash(attestation_key + auth_data))
// =============================================================================
/// Verify QE report hash matches attestation key and auth data (panic-free)
fn verify_qe_report_data(
qe_report: &EnclaveReport,
auth_data: &crate::quote::AuthDataV3,
backend: &CryptoBackend,
) -> Result<()> {
use crate::constants::{ATTESTATION_KEY_LEN, AUTHENTICATION_DATA_LEN};
ensure!(
auth_data.qe_auth_data.data.len() == AUTHENTICATION_DATA_LEN,
"Invalid QE auth data length"
);
// Build hash data: attestation_key || qe_auth_data
let mut qe_hash_data = [0u8; ATTESTATION_KEY_LEN + AUTHENTICATION_DATA_LEN];
qe_hash_data[..ATTESTATION_KEY_LEN].copy_from_slice(&auth_data.ecdsa_attestation_key);
qe_hash_data[ATTESTATION_KEY_LEN..].copy_from_slice(&auth_data.qe_auth_data.data);
let qe_hash = (backend.sha256)(&qe_hash_data);
if qe_hash[..] != qe_report.report_data[..32] {
bail!("QE report hash mismatch");
}
Ok(())
}
// =============================================================================
// Step 6: Verify QE Report policy (QE Report fields match QE Identity policy)
// =============================================================================
// verify_qe_identity_policy is defined below (after verify_impl)
// =============================================================================
// Step 7: Verify ISV Report signature (Attestation Key signs ISV Report)
// =============================================================================
/// Verify ISV enclave report signature using attestation key
fn verify_isv_report_signature(
raw_quote: &[u8],
quote: &Quote,
auth_data: &crate::quote::AuthDataV3,
backend: &CryptoBackend,
) -> Result<()> {
// Prepend 0x04 to raw public key for SEC1 uncompressed format
let mut pub_key = [0x04u8; 65];
pub_key[1..].copy_from_slice(&auth_data.ecdsa_attestation_key);
// DER-encode the raw r||s signature for SignatureVerificationAlgorithm
let der_sig = (backend.encode_ecdsa)(&auth_data.ecdsa_signature)?;
let signed_data = raw_quote
.get(..quote.signed_length())
.context("Failed to get signed quote scope")?;
backend
.sig_algo
.verify_signature(&pub_key, signed_data, &der_sig)
.map_err(|_| anyhow::anyhow!("ISV enclave report signature is invalid"))
}
// =============================================================================
// Step 8: Match Platform TCB (PCK Cert's CPU_SVN/PCE_SVN/FMSPC vs TCB Info)
// =============================================================================
/// Match platform TCB level and return the matched TcbLevel
fn match_platform_tcb(
tcb_info: &TcbInfo,
quote: &Quote,
tee_type: TeeType,
cpu_svn: &[u8],
pce_svn: u16,
fmspc: &[u8],
) -> Result<TcbLevel> {
// Verify FMSPC matches
let tcb_fmspc = hex::decode(&tcb_info.fmspc)
.ok()
.context("Failed to decode TCB FMSPC")?;
if fmspc[..] != tcb_fmspc[..] {
bail!("Fmspc mismatch");
}
// Verify TCB Info type matches quote TEE type
match tee_type {
TeeType::Tdx => {
if tcb_info.version < 3 || tcb_info.id != "TDX" {
bail!("TDX quote with non-TDX TCB info in the collateral");
}
}
TeeType::Sgx => {
if tcb_info.version < 2 || tcb_info.id != "SGX" {
bail!("SGX quote with non-SGX TCB info in the collateral");
}
}
}
// Find matching TCB level
for tcb_level in &tcb_info.tcb_levels {
if pce_svn < tcb_level.tcb.pce_svn {
continue;
}
let sgx_components: Vec<u8> = tcb_level.tcb.sgx_components.iter().map(|c| c.svn).collect();
if sgx_components.len() != cpu_svn.len() {
bail!(
"SGX component count mismatch: expected {}, got {}",
cpu_svn.len(),
sgx_components.len()
);
}
// Component-wise comparison: every cpu_svn[i] must be >= sgx_components[i]
if cpu_svn.iter().zip(&sgx_components).any(|(a, b)| a < b) {
continue;
}
// For TDX, also check TDX components