-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathattestation.rs
More file actions
1390 lines (1260 loc) · 45.5 KB
/
Copy pathattestation.rs
File metadata and controls
1390 lines (1260 loc) · 45.5 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
// SPDX-FileCopyrightText: © 2024-2025 Phala Network <dstack@phala.network>
//
// SPDX-License-Identifier: Apache-2.0
//! Attestation functions
/// Byte range of the REPORT_DATA field within a TDX quote.
/// In Intel TDX ECDSA quote format, the TD Report body starts at offset 568
/// and REPORT_DATA occupies bytes 568..632 (64 bytes).
pub const TDX_QUOTE_REPORT_DATA_RANGE: std::ops::Range<usize> = 568..632;
use std::{borrow::Cow, time::SystemTime};
use anyhow::{anyhow, bail, Context, Result};
use cc_eventlog::{RuntimeEvent, TdxEvent};
use dcap_qvl::{
quote::{EnclaveReport, Quote, Report, TDReport10, TDReport15},
verify::VerifiedReport as TdxVerifiedReport,
};
#[cfg(feature = "quote")]
use dstack_types::SysConfig;
use dstack_types::{Platform, VmConfig};
use ez_hash::{sha256, Hasher, Sha384};
use or_panic::ResultOrPanic;
use scale::{Decode, Encode, Error as ScaleError, Input, Output};
use serde::{Deserialize, Serialize};
use serde_human_bytes as hex_bytes;
use sha2::Digest as _;
pub use crate::v1::{Attestation as AttestationV1, PlatformEvidence, StackEvidence};
const DSTACK_TDX: &str = "dstack-tdx";
const DSTACK_GCP_TDX: &str = "dstack-gcp-tdx";
const DSTACK_NITRO_ENCLAVE: &str = "dstack-nitro-enclave";
#[cfg(feature = "quote")]
const SYS_CONFIG_PATH: &str = "/dstack/.host-shared/.sys-config.json";
/// Global lock for quote generation. The underlying TDX driver does not support concurrent access.
#[cfg(feature = "quote")]
static QUOTE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Read vm_config from sys-config.json
#[cfg(feature = "quote")]
fn read_vm_config() -> Result<String> {
let content = match fs_err::read_to_string(SYS_CONFIG_PATH) {
Ok(content) => content,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(String::new()),
Err(err) => return Err(err).context("Failed to read sys-config"),
};
let sys_config: SysConfig =
serde_json::from_str(&content).context("Failed to parse sys-config")?;
Ok(sys_config.vm_config)
}
fn is_msgpack_map_prefix(byte: u8) -> bool {
// fixmap (0x80..=0x8f), map16 (0xde), map32 (0xdf)
matches!(byte, 0x80..=0x8f | 0xde | 0xdf)
}
impl From<Attestation> for AttestationV1 {
fn from(attestation: Attestation) -> Self {
let Attestation {
quote,
runtime_events,
report_data,
config,
report: _,
} = attestation;
let platform = platform_from_legacy_quote(quote);
let stack = StackEvidence::Dstack {
report_data: report_data.to_vec(),
runtime_events,
config,
};
Self::new(platform, stack)
}
}
fn platform_from_legacy_quote(quote: AttestationQuote) -> PlatformEvidence {
match quote {
AttestationQuote::DstackTdx(TdxQuote { quote, event_log }) => {
PlatformEvidence::Tdx { quote, event_log }
}
AttestationQuote::DstackGcpTdx => PlatformEvidence::GcpTdx,
AttestationQuote::DstackNitroEnclave => PlatformEvidence::NitroEnclave,
}
}
fn platform_into_legacy_quote(platform: PlatformEvidence) -> AttestationQuote {
match platform {
PlatformEvidence::Tdx { quote, event_log } => {
AttestationQuote::DstackTdx(TdxQuote { quote, event_log })
}
PlatformEvidence::GcpTdx => AttestationQuote::DstackGcpTdx,
PlatformEvidence::NitroEnclave => AttestationQuote::DstackNitroEnclave,
}
}
fn platform_attestation_mode(platform: &PlatformEvidence) -> AttestationMode {
match platform {
PlatformEvidence::Tdx { .. } => AttestationMode::DstackTdx,
PlatformEvidence::GcpTdx => AttestationMode::DstackGcpTdx,
PlatformEvidence::NitroEnclave => AttestationMode::DstackNitroEnclave,
}
}
fn replay_runtime_events<H: Hasher>(
runtime_events: &[RuntimeEvent],
to_event: Option<&str>,
) -> H::Output {
cc_eventlog::replay_events::<H>(runtime_events, to_event)
}
fn find_event(runtime_events: &[RuntimeEvent], name: &str) -> Result<RuntimeEvent> {
for event in runtime_events {
if event.event == "system-ready" {
break;
}
if event.event == name {
return Ok(event.clone());
}
}
Err(anyhow!("event {name} not found"))
}
fn find_event_payload(runtime_events: &[RuntimeEvent], event: &str) -> Result<Vec<u8>> {
find_event(runtime_events, event).map(|event| event.payload)
}
fn decode_vm_config_with_fallback(config: &str, fallback_config: &str) -> Result<VmConfig> {
let config = if config.is_empty() {
fallback_config
} else {
config
};
let config = if config.is_empty() { "{}" } else { config };
serde_json::from_str(config).context("Failed to parse vm config")
}
/// Attestation mode
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Encode, Decode, Serialize, Deserialize)]
pub enum AttestationMode {
/// Intel TDX with DCAP quote only
#[default]
#[serde(rename = "dstack-tdx")]
DstackTdx,
/// GCP TDX with DCAP quote only
#[serde(rename = "dstack-gcp-tdx")]
DstackGcpTdx,
/// Dstack attestation SDK in AWS Nitro Enclave
#[serde(rename = "dstack-nitro-enclave")]
DstackNitroEnclave,
}
impl AttestationMode {
/// Detect attestation mode from system
pub fn detect() -> Result<Self> {
let has_tdx = std::path::Path::new("/dev/tdx_guest").exists();
// First, try to detect platform from DMI product name
let platform = Platform::detect_or_dstack();
match platform {
Platform::Dstack => {
if has_tdx {
return Ok(Self::DstackTdx);
}
bail!("Unsupported platform: Dstack(-tdx)");
}
Platform::Gcp => {
// GCP platform: TDX + TPM dual mode
if has_tdx {
return Ok(Self::DstackGcpTdx);
}
bail!("Unsupported platform: GCP(-tdx)");
}
Platform::NitroEnclave => Ok(Self::DstackNitroEnclave),
}
}
/// Check if TDX quote should be included
pub fn has_tdx(&self) -> bool {
match self {
Self::DstackTdx => true,
Self::DstackGcpTdx => true,
Self::DstackNitroEnclave => false,
}
}
/// Get TPM runtime event PCR index
pub fn tpm_runtime_pcr(&self) -> Option<u32> {
match self {
Self::DstackGcpTdx => Some(14),
Self::DstackTdx => None,
Self::DstackNitroEnclave => None,
}
}
/// As string for debug
pub fn as_str(&self) -> &'static str {
match self {
Self::DstackTdx => DSTACK_TDX,
Self::DstackGcpTdx => DSTACK_GCP_TDX,
Self::DstackNitroEnclave => DSTACK_NITRO_ENCLAVE,
}
}
/// Returns true if the attestation mode supports composability (OS image + runtime loadable application)
pub fn is_composable(&self) -> bool {
match self {
Self::DstackTdx => true,
Self::DstackGcpTdx => true,
Self::DstackNitroEnclave => false,
}
}
}
/// The content type of a quote. A CVM should only generate quotes for these types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuoteContentType<'a> {
/// The public key of KMS root CA
KmsRootCa,
/// The public key of the RA-TLS certificate
RaTlsCert,
/// App defined data
AppData,
/// The custom content type
Custom(&'a str),
}
/// The default hash algorithm used to hash the report data.
pub const DEFAULT_HASH_ALGORITHM: &str = "sha512";
impl QuoteContentType<'_> {
/// The tag of the content type used in the report data.
pub fn tag(&self) -> &str {
match self {
Self::KmsRootCa => "kms-root-ca",
Self::RaTlsCert => "ratls-cert",
Self::AppData => "app-data",
Self::Custom(tag) => tag,
}
}
/// Convert the content to the report data.
pub fn to_report_data(&self, content: &[u8]) -> [u8; 64] {
self.to_report_data_with_hash(content, "")
.or_panic("sha512 hash should not fail")
}
/// Convert the content to the report data with a specific hash algorithm.
pub fn to_report_data_with_hash(&self, content: &[u8], hash: &str) -> Result<[u8; 64]> {
macro_rules! do_hash {
($hash: ty) => {{
// The format is:
// hash(<tag>:<content>)
let mut hasher = <$hash>::new();
hasher.update(self.tag().as_bytes());
hasher.update(b":");
hasher.update(content);
let output = hasher.finalize();
let mut padded = [0u8; 64];
padded[..output.len()].copy_from_slice(&output);
padded
}};
}
let hash = if hash.is_empty() {
DEFAULT_HASH_ALGORITHM
} else {
hash
};
let output = match hash {
"sha256" => do_hash!(sha2::Sha256),
"sha384" => do_hash!(sha2::Sha384),
"sha512" => do_hash!(sha2::Sha512),
"sha3-256" => do_hash!(sha3::Sha3_256),
"sha3-384" => do_hash!(sha3::Sha3_384),
"sha3-512" => do_hash!(sha3::Sha3_512),
"keccak256" => do_hash!(sha3::Keccak256),
"keccak384" => do_hash!(sha3::Keccak384),
"keccak512" => do_hash!(sha3::Keccak512),
"raw" => content.try_into().ok().context("invalid content length")?,
_ => bail!("invalid hash algorithm"),
};
Ok(output)
}
}
#[allow(clippy::large_enum_variant)]
/// Represents a verified attestation
#[derive(Clone)]
pub enum DstackVerifiedReport {
DstackTdx(TdxVerifiedReport),
DstackGcpTdx,
DstackNitroEnclave,
}
impl DstackVerifiedReport {
pub fn tdx_report(&self) -> Option<&TdxVerifiedReport> {
match self {
DstackVerifiedReport::DstackTdx(report) => Some(report),
DstackVerifiedReport::DstackGcpTdx => None,
DstackVerifiedReport::DstackNitroEnclave => None,
}
}
}
/// Represents a verified attestation
pub type VerifiedAttestation = Attestation<DstackVerifiedReport>;
/// Represents a TDX quote
#[derive(Clone, Encode, Decode)]
pub struct TdxQuote {
/// The quote gererated by Intel QE
pub quote: Vec<u8>,
/// The event log
pub event_log: Vec<TdxEvent>,
}
/// Represents an NSM (Nitro Security Module) attestation document
#[derive(Clone, Encode, Decode)]
pub struct NsmQuote {
/// The COSE Sign1 attestation document from NSM
pub document: Vec<u8>,
}
#[derive(Clone, Encode, Decode)]
enum LegacyVersionedAttestation {
V0 { attestation: Attestation },
}
/// Maximum size for encoded attestation bytes (10 MiB).
/// Prevents OOM when decoding untrusted input.
const MAX_ATTESTATION_BYTES: usize = 10 * 1024 * 1024;
/// Represents a versioned attestation.
///
/// **SCALE note**: `VersionedAttestation` implements `Encode`/`Decode` so it can
/// be embedded in SCALE structs (e.g. `CertSigningRequestV2`). The `Decode` impl
/// consumes all remaining input, so it **must** be the last field in any SCALE
/// container.
#[derive(Clone)]
pub enum VersionedAttestation {
/// Legacy SCALE-encoded attestation.
V0 {
/// The attestation report
attestation: Attestation,
},
/// CBOR-encoded attestation schema.
V1 {
/// The version 1 attestation.
attestation: AttestationV1,
},
}
impl Encode for VersionedAttestation {
fn size_hint(&self) -> usize {
self.to_bytes().map(|b| b.len()).unwrap_or(0)
}
fn encode_to<T: Output + ?Sized>(&self, dest: &mut T) {
let bytes = self
.to_bytes()
.or_panic("VersionedAttestation should always encode successfully");
dest.write(&bytes);
}
}
impl Decode for VersionedAttestation {
fn decode<I: Input>(input: &mut I) -> Result<Self, ScaleError> {
let Some(remaining_len) = input.remaining_len()? else {
return Err(ScaleError::from(
"VersionedAttestation requires a bounded input to decode",
));
};
if remaining_len > MAX_ATTESTATION_BYTES {
return Err(ScaleError::from(
"attestation bytes exceed maximum allowed size",
));
}
let mut bytes = vec![0u8; remaining_len];
input.read(&mut bytes)?;
Self::from_bytes(&bytes).map_err(|err| {
ScaleError::from(std::io::Error::new(
std::io::ErrorKind::InvalidData,
err.to_string(),
))
})
}
}
impl VersionedAttestation {
/// Decode versioned attestation bytes.
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
if bytes.len() > MAX_ATTESTATION_BYTES {
bail!(
"attestation bytes too large: {} > {}",
bytes.len(),
MAX_ATTESTATION_BYTES
);
}
let Some(first) = bytes.first().copied() else {
bail!("Empty attestation bytes");
};
if first == 0x00 {
let legacy = LegacyVersionedAttestation::decode(&mut &bytes[..])
.context("Failed to decode legacy VersionedAttestation")?;
return match legacy {
LegacyVersionedAttestation::V0 { attestation } => Ok(Self::V0 { attestation }),
};
}
if is_msgpack_map_prefix(first) {
let attestation = AttestationV1::from_msgpack(bytes)?;
return Ok(Self::V1 { attestation });
}
bail!("Unknown attestation wire format");
}
/// Encode versioned attestation bytes.
pub fn to_bytes(&self) -> Result<Vec<u8>> {
match self {
Self::V0 { attestation } => Ok(LegacyVersionedAttestation::V0 {
attestation: attestation.clone(),
}
.encode()),
Self::V1 { attestation } => attestation.to_msgpack(),
}
}
#[doc(hidden)]
pub fn from_scale(bytes: &[u8]) -> Result<Self> {
Self::from_bytes(bytes)
}
#[doc(hidden)]
pub fn to_scale(&self) -> Result<Vec<u8>> {
self.to_bytes()
}
/// Project any version into the V1 attestation schema.
pub fn into_v1(self) -> AttestationV1 {
match self {
Self::V0 { attestation } => attestation.into_v1(),
Self::V1 { attestation } => attestation,
}
}
/// Strip data for certificate embedding (e.g. keep RTMR3 event logs only).
pub fn into_stripped(self) -> Self {
match self {
Self::V0 { mut attestation } => {
if let Some(tdx_quote) = attestation.tdx_quote_mut() {
tdx_quote.event_log = tdx_quote
.event_log
.iter()
.filter(|e| e.imr == 3)
.map(|e| e.stripped())
.collect();
}
Self::V0 { attestation }
}
Self::V1 { attestation } => Self::V1 {
attestation: attestation.into_stripped(),
},
}
}
}
/// TDX-specific helpers for attestation schemas that carry TDX platform evidence.
pub trait TdxAttestationExt {
/// Returns the raw TDX quote bytes if the attestation is backed by TDX.
fn tdx_quote_bytes(&self) -> Option<Vec<u8>>;
/// Returns the parsed TDX event log if the attestation is backed by TDX.
fn tdx_event_log(&self) -> Option<&[TdxEvent]>;
/// Returns the TDX event log serialized as JSON.
fn tdx_event_log_string(&self) -> Option<String> {
self.tdx_event_log()
.map(|event_log| serde_json::to_string(event_log).unwrap_or_default())
}
/// Returns the parsed TD10 report from the embedded TDX quote.
fn td10_report(&self) -> Option<TDReport10>;
}
impl TdxAttestationExt for AttestationV1 {
fn tdx_quote_bytes(&self) -> Option<Vec<u8>> {
self.platform.tdx_quote().map(|quote| quote.to_vec())
}
fn tdx_event_log(&self) -> Option<&[TdxEvent]> {
self.platform.tdx_event_log()
}
fn td10_report(&self) -> Option<TDReport10> {
self.platform
.tdx_quote()
.and_then(|quote| Quote::parse(quote).ok())
.and_then(|quote| quote.report.as_td10().cloned())
}
}
impl AttestationV1 {
/// Decode the VM config from the external or embedded config.
pub fn decode_vm_config<'a>(&'a self, config: &'a str) -> Result<VmConfig> {
decode_vm_config_with_fallback(config, self.stack.config())
}
/// Decode the app info from the event log.
pub fn decode_app_info(&self, boottime_mr: bool) -> Result<AppInfo> {
self.decode_app_info_ex(boottime_mr, "")
}
/// Decode the app info from the event log with an optional external vm_config.
#[errify::errify("decode app info")]
pub fn decode_app_info_ex(&self, boottime_mr: bool, vm_config: &str) -> Result<AppInfo> {
let runtime_events = self.stack.runtime_events();
let key_provider_info = if boottime_mr {
vec![]
} else {
find_event_payload(runtime_events, "key-provider").unwrap_or_default()
};
let mr_key_provider = if key_provider_info.is_empty() {
[0u8; 32]
} else {
sha256(&key_provider_info)
};
let os_image_hash = self
.decode_vm_config(vm_config)
.context("Failed to decode os image hash")?
.os_image_hash;
let mrs = match &self.platform {
PlatformEvidence::Tdx { quote, .. } => {
decode_mr_tdx_from_quote(boottime_mr, &mr_key_provider, quote, runtime_events)?
}
PlatformEvidence::GcpTdx | PlatformEvidence::NitroEnclave => {
bail!("Unsupported attestation quote");
}
};
let compose_hash = if platform_attestation_mode(&self.platform).is_composable() {
find_event_payload(runtime_events, "compose-hash").unwrap_or_default()
} else {
os_image_hash.clone()
};
Ok(AppInfo {
app_id: find_event_payload(runtime_events, "app-id").unwrap_or_default(),
instance_id: find_event_payload(runtime_events, "instance-id").unwrap_or_default(),
device_id: sha256(Vec::<u8>::new()).to_vec(),
mr_system: mrs.mr_system,
mr_aggregated: mrs.mr_aggregated,
key_provider_info,
os_image_hash,
compose_hash,
})
}
/// Verify the quote with optional custom time (testing hook).
pub async fn verify_with_time(
self,
pccs_url: Option<&str>,
_now: Option<SystemTime>,
) -> Result<VerifiedAttestation> {
let AttestationV1 {
version: _,
platform,
stack,
} = self;
// Verify report_data_payload binding: if present, the report_data must
// be derived from the payload via the AppData content type scheme.
if let Some(payload) = stack.report_data_payload() {
let report_data: [u8; 64] = stack.report_data()?;
let expected = QuoteContentType::AppData.to_report_data(payload.as_bytes());
if report_data != expected {
bail!("report_data does not match report_data_payload");
}
}
let (report_data, runtime_events, config) = match stack {
StackEvidence::Dstack {
report_data,
runtime_events,
config,
}
| StackEvidence::DstackPod {
report_data,
runtime_events,
config,
..
} => (
report_data
.as_slice()
.try_into()
.map_err(|_| anyhow!("stack.report_data must be 64 bytes"))?,
runtime_events,
config,
),
};
let report = match &platform {
PlatformEvidence::Tdx { quote, .. } => DstackVerifiedReport::DstackTdx(
verify_tdx_quote_with_events(pccs_url, quote, &runtime_events, &report_data)
.await?,
),
PlatformEvidence::GcpTdx | PlatformEvidence::NitroEnclave => {
bail!(
"Unsupported attestation mode: {:?}",
platform_attestation_mode(&platform)
);
}
};
Ok(VerifiedAttestation {
quote: platform_into_legacy_quote(platform),
runtime_events,
report_data,
config,
report,
})
}
/// Verify the quote against a RA-TLS public key.
pub async fn verify_with_ra_pubkey(
self,
ra_pubkey_der: &[u8],
pccs_url: Option<&str>,
) -> Result<VerifiedAttestation> {
let expected_report_data = QuoteContentType::RaTlsCert.to_report_data(ra_pubkey_der);
if self.report_data()? != expected_report_data {
bail!("report data mismatch");
}
self.verify(pccs_url).await
}
/// Verify the quote.
pub async fn verify(self, pccs_url: Option<&str>) -> Result<VerifiedAttestation> {
self.verify_with_time(pccs_url, None).await
}
}
#[derive(Clone, Encode, Decode)]
pub enum AttestationQuote {
DstackTdx(TdxQuote),
DstackGcpTdx,
DstackNitroEnclave,
}
impl AttestationQuote {
pub fn mode(&self) -> AttestationMode {
match self {
AttestationQuote::DstackTdx { .. } => AttestationMode::DstackTdx,
AttestationQuote::DstackGcpTdx => AttestationMode::DstackGcpTdx,
AttestationQuote::DstackNitroEnclave => AttestationMode::DstackNitroEnclave,
}
}
}
/// Attestation data
#[derive(Clone, Encode, Decode)]
pub struct Attestation<R = ()> {
/// The quote
pub quote: AttestationQuote,
/// Runtime events (only for TDX mode)
pub runtime_events: Vec<RuntimeEvent>,
/// The report data
pub report_data: [u8; 64],
/// The configuration of the VM
pub config: String,
/// Verified report
pub report: R,
}
impl<T> Attestation<T> {
pub fn report_data_payload(&self) -> Option<&str> {
None
}
pub fn tdx_quote_mut(&mut self) -> Option<&mut TdxQuote> {
match &mut self.quote {
AttestationQuote::DstackTdx(quote) => Some(quote),
AttestationQuote::DstackGcpTdx => None,
AttestationQuote::DstackNitroEnclave => None,
}
}
pub fn tdx_quote(&self) -> Option<&TdxQuote> {
match &self.quote {
AttestationQuote::DstackTdx(quote) => Some(quote),
AttestationQuote::DstackGcpTdx => None,
AttestationQuote::DstackNitroEnclave => None,
}
}
/// Get TDX quote bytes
pub fn get_tdx_quote_bytes(&self) -> Option<Vec<u8>> {
self.tdx_quote().map(|q| q.quote.clone())
}
/// Get TDX event log bytes
pub fn get_tdx_event_log_bytes(&self) -> Option<Vec<u8>> {
self.tdx_quote()
.map(|q| serde_json::to_vec(&q.event_log).unwrap_or_default())
}
/// Get TDX event log string with RTMR[0-2] payloads stripped to reduce size.
/// Only digests are kept for boot-time events; runtime events (RTMR3) retain full payload.
pub fn get_tdx_event_log_string(&self) -> Option<String> {
self.tdx_quote().map(|q| {
let stripped: Vec<_> = q.event_log.iter().map(|e| e.stripped()).collect();
serde_json::to_string(&stripped).unwrap_or_default()
})
}
pub fn get_td10_report(&self) -> Option<TDReport10> {
self.tdx_quote()
.and_then(|q| Quote::parse(&q.quote).ok())
.and_then(|quote| quote.report.as_td10().cloned())
}
}
pub trait GetDeviceId {
fn get_devide_id(&self) -> Vec<u8>;
}
impl GetDeviceId for () {
fn get_devide_id(&self) -> Vec<u8> {
Vec::new()
}
}
impl GetDeviceId for DstackVerifiedReport {
fn get_devide_id(&self) -> Vec<u8> {
match self {
DstackVerifiedReport::DstackTdx(tdx_report) => tdx_report.ppid.to_vec(),
DstackVerifiedReport::DstackGcpTdx => Vec::new(),
DstackVerifiedReport::DstackNitroEnclave => Vec::new(),
}
}
}
struct Mrs {
mr_system: [u8; 32],
mr_aggregated: [u8; 32],
}
fn decode_mr_tdx_from_quote(
boottime_mr: bool,
mr_key_provider: &[u8],
quote: &[u8],
runtime_events: &[RuntimeEvent],
) -> Result<Mrs> {
let quote = Quote::parse(quote).context("Failed to parse quote")?;
let rtmr3 =
replay_runtime_events::<Sha384>(runtime_events, boottime_mr.then_some("boot-mr-done"));
let td_report = quote.report.as_td10().context("TDX report not found")?;
let mr_system = sha256([
&td_report.mr_td[..],
&td_report.rt_mr0,
&td_report.rt_mr1,
&td_report.rt_mr2,
mr_key_provider,
]);
let mr_aggregated = {
let mut hasher = sha2::Sha256::new();
for d in [
&td_report.mr_td,
&td_report.rt_mr0,
&td_report.rt_mr1,
&td_report.rt_mr2,
&rtmr3,
] {
hasher.update(d);
}
if td_report.mr_config_id != [0u8; 48]
|| td_report.mr_owner != [0u8; 48]
|| td_report.mr_owner_config != [0u8; 48]
{
hasher.update(td_report.mr_config_id);
hasher.update(td_report.mr_owner);
hasher.update(td_report.mr_owner_config);
}
hasher.finalize().into()
};
Ok(Mrs {
mr_system,
mr_aggregated,
})
}
async fn verify_tdx_quote_with_events(
pccs_url: Option<&str>,
quote: &[u8],
runtime_events: &[RuntimeEvent],
report_data: &[u8; 64],
) -> Result<TdxVerifiedReport> {
let mut pccs_url = Cow::Borrowed(pccs_url.unwrap_or_default());
if pccs_url.is_empty() {
pccs_url = match std::env::var("PCCS_URL") {
Ok(url) => Cow::Owned(url),
Err(_) => Cow::Borrowed(""),
};
}
let tdx_report =
dcap_qvl::collateral::get_collateral_and_verify(quote, Some(pccs_url.as_ref()))
.await
.context("Failed to get collateral")?;
validate_tcb(&tdx_report)?;
let td_report = tdx_report.report.as_td10().context("no td report")?;
let replayed_rtmr = replay_runtime_events::<Sha384>(runtime_events, None);
if replayed_rtmr != td_report.rt_mr3 {
bail!(
"RTMR3 mismatch, quoted: {}, replayed: {}",
hex::encode(td_report.rt_mr3),
hex::encode(replayed_rtmr)
);
}
if td_report.report_data != report_data[..] {
bail!("tdx report_data mismatch");
}
Ok(tdx_report)
}
impl<T: GetDeviceId> Attestation<T> {
fn decode_mr_tdx(
&self,
boottime_mr: bool,
mr_key_provider: &[u8],
tdx_quote: &TdxQuote,
) -> Result<Mrs> {
let quote = Quote::parse(&tdx_quote.quote).context("Failed to parse quote")?;
let rtmr3 = self.replay_runtime_events::<Sha384>(boottime_mr.then_some("boot-mr-done"));
let td_report = quote.report.as_td10().context("TDX report not found")?;
let mr_system = sha256([
&td_report.mr_td[..],
&td_report.rt_mr0,
&td_report.rt_mr1,
&td_report.rt_mr2,
mr_key_provider,
]);
let mr_aggregated = {
let mut hasher = sha2::Sha256::new();
for d in [
&td_report.mr_td,
&td_report.rt_mr0,
&td_report.rt_mr1,
&td_report.rt_mr2,
&rtmr3,
] {
hasher.update(d);
}
// For backward compatibility. Don't include mr_config_id, mr_owner, mr_owner_config if they are all 0.
if td_report.mr_config_id != [0u8; 48]
|| td_report.mr_owner != [0u8; 48]
|| td_report.mr_owner_config != [0u8; 48]
{
hasher.update(td_report.mr_config_id);
hasher.update(td_report.mr_owner);
hasher.update(td_report.mr_owner_config);
}
hasher.finalize().into()
};
Ok(Mrs {
mr_system,
mr_aggregated,
})
}
/// Decode the VM config from the external or embedded config
pub fn decode_vm_config<'a>(&'a self, mut config: &'a str) -> Result<VmConfig> {
if config.is_empty() {
config = &self.config;
}
if config.is_empty() {
// No vm config for nitro enclave
config = "{}";
}
let vm_config: VmConfig =
serde_json::from_str(config).context("Failed to parse vm config")?;
Ok(vm_config)
}
/// Decode the app info from the event log
pub fn decode_app_info(&self, boottime_mr: bool) -> Result<AppInfo> {
self.decode_app_info_ex(boottime_mr, "")
}
#[errify::errify("decode app info")]
pub fn decode_app_info_ex(&self, boottime_mr: bool, vm_config: &str) -> Result<AppInfo> {
let key_provider_info = if boottime_mr {
vec![]
} else {
self.find_event_payload("key-provider").unwrap_or_default()
};
let mr_key_provider = if key_provider_info.is_empty() {
[0u8; 32]
} else {
sha256(&key_provider_info)
};
let os_image_hash = self
.decode_vm_config(vm_config)
.context("Failed to decode os image hash")?
.os_image_hash;
let mrs = match &self.quote {
AttestationQuote::DstackTdx(q) => {
self.decode_mr_tdx(boottime_mr, &mr_key_provider, q)?
}
AttestationQuote::DstackGcpTdx | AttestationQuote::DstackNitroEnclave => {
bail!("Unsupported attestation quote");
}
};
let compose_hash = if self.quote.mode().is_composable() {
self.find_event_payload("compose-hash").unwrap_or_default()
} else {
os_image_hash.clone()
};
Ok(AppInfo {
app_id: self.find_event_payload("app-id").unwrap_or_default(),
instance_id: self.find_event_payload("instance-id").unwrap_or_default(),
device_id: sha256(self.report.get_devide_id()).to_vec(),
mr_system: mrs.mr_system,
mr_aggregated: mrs.mr_aggregated,
key_provider_info,
os_image_hash,
compose_hash,
})
}
}
impl<T> Attestation<T> {
/// Decode the quote
pub fn decode_tdx_quote(&self) -> Result<Quote> {
let Some(tdx_quote) = self.tdx_quote() else {
bail!("tdx_quote not found");
};
Quote::parse(&tdx_quote.quote)
}
fn find_event(&self, name: &str) -> Result<RuntimeEvent> {
for event in &self.runtime_events {
if event.event == "system-ready" {
break;
}
if event.event == name {
return Ok(event.clone());
}
}
Err(anyhow!("event {name} not found"))
}
/// Replay event logs
pub fn replay_runtime_events<H: Hasher>(&self, to_event: Option<&str>) -> H::Output {
cc_eventlog::replay_events::<H>(&self.runtime_events, to_event)
}
fn find_event_payload(&self, event: &str) -> Result<Vec<u8>> {
self.find_event(event).map(|event| event.payload)
}
fn find_event_hex_payload(&self, event: &str) -> Result<String> {
self.find_event(event)
.map(|event| hex::encode(&event.payload))
}
/// Decode the app-id from the event log
pub fn decode_app_id(&self) -> Result<String> {
self.find_event_hex_payload("app-id")
}
/// Decode the instance-id from the event log
pub fn decode_instance_id(&self) -> Result<String> {
self.find_event_hex_payload("instance-id")
}
/// Decode the upgraded app-id from the event log
pub fn decode_compose_hash(&self) -> Result<String> {
self.find_event_hex_payload("compose-hash")
}
/// Decode the rootfs hash from the event log
pub fn decode_rootfs_hash(&self) -> Result<String> {
self.find_event_hex_payload("rootfs-hash")
}
}
impl Attestation {
/// Reconstruct from tdx quote and event log, for backward compatibility
pub fn from_tdx_quote(quote: Vec<u8>, event_log: &[u8]) -> Result<Self> {
let tdx_eventlog: Vec<TdxEvent> =
serde_json::from_slice(event_log).context("Failed to parse tdx_event_log")?;
let runtime_events = tdx_eventlog
.iter()
.flat_map(|event| event.to_runtime_event())
.collect();
let report_data = {
let quote = Quote::parse("e).context("Invalid TDX quote")?;