-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathattestation.rs
More file actions
2300 lines (2107 loc) · 80 KB
/
Copy pathattestation.rs
File metadata and controls
2300 lines (2107 loc) · 80 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::{mr_config::MrConfigV3, KeyProviderInfo, Platform, VmConfig};
use ez_hash::{sha256, Hasher, Sha256, 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 _;
use tpm_qvl::verify::VerifiedReport as TpmVerifiedReport;
// Re-export TpmQuote from tpm-types
pub use tpm_types::TpmQuote;
use crate::amd_sev_snp::{AmdKdsClient, VerifiedAmdSnpReport};
use crate::v1::{
is_tdx_acpi_data_event, strip_tdx_event_log_for_config, strip_tdx_runtime_event_log,
};
pub use crate::v1::{Attestation as AttestationV1, PlatformEvidence, StackEvidence};
pub const SNP_REPORT_DATA_RANGE: std::ops::Range<usize> = 0x50..0x90;
const DSTACK_TDX: &str = "dstack-tdx";
const DSTACK_AMD_SEV_SNP: &str = "dstack-amd-sev-snp";
const DSTACK_GCP_TDX: &str = "dstack-gcp-tdx";
const DSTACK_NITRO_ENCLAVE: &str = "dstack-nitro-enclave";
/// Path to sys-config.json in the host-shared dir.
///
/// Honors `DSTACK_HOST_SHARED_DIR` (exported by `dstack-util setup` because the
/// canonical `/dstack/.host-shared` is only bind-mounted after setup finishes).
#[cfg(feature = "quote")]
fn sys_config_path() -> std::path::PathBuf {
dstack_types::shared_filenames::host_shared_dir()
.join(dstack_types::shared_filenames::SYS_CONFIG)
}
/// 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)
}
/// Read the canonical mr_config document from sys-config.json.
///
/// Uses the same accessor as the guest config-id verifier so both agree on
/// where `mr_config` lives (top-level field, falling back to the one embedded
/// in `vm_config`).
#[cfg(feature = "quote")]
fn read_mr_config_document() -> Result<Option<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(None),
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.mr_config_document())
}
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::DstackAmdSevSnp(SnpQuote {
report,
cert_chain,
mr_config,
}) => PlatformEvidence::SevSnp {
report,
cert_chain,
mr_config,
},
AttestationQuote::DstackGcpTdx(DstackGcpTdxQuote {
tdx_quote: TdxQuote { quote, event_log },
tpm_quote,
}) => PlatformEvidence::GcpTdx {
quote,
event_log,
tpm_quote,
},
AttestationQuote::DstackNitroEnclave(DstackNitroQuote { nsm_quote }) => {
PlatformEvidence::NitroEnclave { nsm_quote }
}
}
}
fn platform_into_legacy_quote(platform: PlatformEvidence) -> AttestationQuote {
match platform {
PlatformEvidence::Tdx { quote, event_log } => {
AttestationQuote::DstackTdx(TdxQuote { quote, event_log })
}
PlatformEvidence::SevSnp {
report,
cert_chain,
mr_config,
} => AttestationQuote::DstackAmdSevSnp(SnpQuote {
report,
cert_chain,
mr_config,
}),
PlatformEvidence::GcpTdx {
quote,
event_log,
tpm_quote,
} => AttestationQuote::DstackGcpTdx(DstackGcpTdxQuote {
tdx_quote: TdxQuote { quote, event_log },
tpm_quote,
}),
PlatformEvidence::NitroEnclave { nsm_quote } => {
AttestationQuote::DstackNitroEnclave(DstackNitroQuote { nsm_quote })
}
}
}
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 };
let config = vm_config_json_from_config(config).unwrap_or(Cow::Borrowed(config));
serde_json::from_str(&config).context("Failed to parse vm config")
}
fn vm_config_json_from_config(config: &str) -> Option<Cow<'_, str>> {
let value = serde_json::from_str::<serde_json::Value>(config).ok()?;
value
.get("vm_config")
.and_then(|value| value.as_str())
.map(|vm_config| Cow::Owned(vm_config.to_string()))
}
fn mr_config_document_from_value(value: &serde_json::Value) -> Result<Option<String>> {
let Some(mr_config) = value.get("mr_config") else {
return Ok(None);
};
let document = mr_config
.as_str()
.context("amd sev-snp mr_config must be a JSON string")?;
MrConfigV3::from_document(document).context("Invalid amd sev-snp mr_config document")?;
Ok(Some(document.to_string()))
}
fn mr_config_document_from_config(config: &str) -> Result<Option<String>> {
let Ok(value) = serde_json::from_str::<serde_json::Value>(config) else {
return Ok(None);
};
if let Some(mr_config) = mr_config_document_from_value(&value)? {
return Ok(Some(mr_config));
}
let Some(vm_config) = value.get("vm_config").and_then(|value| value.as_str()) else {
return Ok(None);
};
let vm_config = serde_json::from_str::<serde_json::Value>(vm_config)
.context("Failed to parse nested vm_config for amd sev-snp mr_config")?;
mr_config_document_from_value(&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,
/// AMD SEV-SNP report generated by the dstack attestation SDK.
/// Keep this last to preserve SCALE discriminants for existing variants.
#[serde(rename = "dstack-amd-sev-snp")]
DstackAmdSevSnp,
}
#[cfg(feature = "quote")]
fn has_sev_snp_tsm_provider() -> bool {
crate::sev_snp::has_sev_snp_tsm_provider(std::path::Path::new("/sys/kernel/config/tsm/report"))
}
#[cfg(not(feature = "quote"))]
fn has_sev_snp_tsm_provider() -> bool {
false
}
fn choose_dstack_attestation_mode(has_tdx: bool, has_sev_snp: bool) -> Result<AttestationMode> {
if has_tdx {
return Ok(AttestationMode::DstackTdx);
}
if has_sev_snp {
return Ok(AttestationMode::DstackAmdSevSnp);
}
bail!("Unsupported platform: Dstack(-tdx/-amd-sev-snp)");
}
impl AttestationMode {
/// Detect attestation mode from system
pub fn detect() -> Result<Self> {
let has_tdx = std::path::Path::new("/dev/tdx_guest").exists();
let has_sev_snp =
std::path::Path::new("/dev/sev-guest").exists() || has_sev_snp_tsm_provider();
// First, try to detect platform from DMI product name
let platform = Platform::detect_or_dstack();
match platform {
Platform::Dstack => choose_dstack_attestation_mode(has_tdx, has_sev_snp),
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::DstackAmdSevSnp => false,
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::DstackAmdSevSnp => None,
Self::DstackNitroEnclave => None,
}
}
/// As string for debug
pub fn as_str(&self) -> &'static str {
match self {
Self::DstackTdx => DSTACK_TDX,
Self::DstackAmdSevSnp => DSTACK_AMD_SEV_SNP,
Self::DstackGcpTdx => DSTACK_GCP_TDX,
Self::DstackNitroEnclave => DSTACK_NITRO_ENCLAVE,
}
}
}
/// 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)
}
}
/// Verified Nitro Enclave attestation report
#[derive(Clone, Debug, Serialize)]
pub struct NitroVerifiedReport {
/// Module ID
pub module_id: String,
/// PCR0 - Enclave image hash
pub pcrs: NitroPcrs,
/// User data from attestation
#[serde(with = "serde_human_bytes")]
pub user_data: Vec<u8>,
/// Timestamp
pub timestamp: u64,
}
/// Represents a verified attestation
#[derive(Clone)]
pub enum DstackVerifiedReport {
DstackTdx(TdxVerifiedReport),
DstackGcpTdx {
tdx_report: TdxVerifiedReport,
tpm_report: TpmVerifiedReport,
},
DstackNitroEnclave(NitroVerifiedReport),
DstackAmdSevSnp(VerifiedAmdSnpReport),
}
impl DstackVerifiedReport {
pub fn tdx_report(&self) -> Option<&TdxVerifiedReport> {
match self {
DstackVerifiedReport::DstackTdx(report) => Some(report),
DstackVerifiedReport::DstackAmdSevSnp(_) => None,
DstackVerifiedReport::DstackGcpTdx { tdx_report, .. } => Some(tdx_report),
DstackVerifiedReport::DstackNitroEnclave(_) => None,
}
}
pub fn amd_snp_report(&self) -> Option<&VerifiedAmdSnpReport> {
match self {
DstackVerifiedReport::DstackAmdSevSnp(report) => Some(report),
DstackVerifiedReport::DstackTdx(_)
| DstackVerifiedReport::DstackGcpTdx { .. }
| 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 AMD SEV-SNP attestation report.
#[derive(Clone, Encode, Decode)]
pub struct SnpQuote {
/// Raw SNP report bytes.
pub report: Vec<u8>,
/// Optional certificate chain blobs, when exposed by the kernel/firmware path.
pub cert_chain: Vec<Vec<u8>>,
/// MrConfigV3 document bound by the report HOST_DATA field.
pub mr_config: String,
}
/// 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 {
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.
pub fn into_stripped(self) -> Self {
match self {
Self::V0 { mut attestation } => {
match &mut attestation.quote {
AttestationQuote::DstackTdx(tdx_quote) => {
tdx_quote.event_log = strip_tdx_event_log_for_config(
std::mem::take(&mut tdx_quote.event_log),
&attestation.config,
);
}
AttestationQuote::DstackGcpTdx(quote) => {
quote.tdx_quote.event_log = strip_tdx_runtime_event_log(std::mem::take(
&mut quote.tdx_quote.event_log,
));
}
AttestationQuote::DstackAmdSevSnp(_)
| AttestationQuote::DstackNitroEnclave(_) => {}
}
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 platform-specific app info source.
pub fn decode_app_info(&self, boottime_mr: bool) -> Result<AppInfo> {
self.decode_app_info_ex(boottime_mr, "")
}
/// Decode the app info from the platform-specific app info source 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 non_snp_context = || -> Result<(Vec<u8>, [u8; 32], Vec<u8>)> {
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;
Ok((key_provider_info, mr_key_provider, os_image_hash))
};
let build_app_info = |mrs: Mrs,
key_provider_info: Vec<u8>,
os_image_hash: Vec<u8>,
compose_hash: Vec<u8>| {
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,
}
};
match &self.platform {
PlatformEvidence::SevSnp {
report, mr_config, ..
} => decode_app_info_sev_snp(report, Some(mr_config), self.stack.config(), vm_config),
PlatformEvidence::Tdx { quote, .. } => {
let (key_provider_info, mr_key_provider, os_image_hash) = non_snp_context()?;
let mrs =
decode_mr_tdx_from_quote(boottime_mr, &mr_key_provider, quote, runtime_events)?;
let compose_hash =
find_event_payload(runtime_events, "compose-hash").unwrap_or_default();
Ok(build_app_info(
mrs,
key_provider_info,
os_image_hash,
compose_hash,
))
}
PlatformEvidence::GcpTdx { tpm_quote, .. } => {
let (key_provider_info, mr_key_provider, os_image_hash) = non_snp_context()?;
let mrs = decode_mr_gcp_tpm_from_v1(
boottime_mr,
&mr_key_provider,
&os_image_hash,
tpm_quote,
runtime_events,
)?;
let compose_hash =
find_event_payload(runtime_events, "compose-hash").unwrap_or_default();
Ok(build_app_info(
mrs,
key_provider_info,
os_image_hash,
compose_hash,
))
}
PlatformEvidence::NitroEnclave { nsm_quote } => {
let (key_provider_info, _mr_key_provider, os_image_hash) = non_snp_context()?;
let mrs = decode_mr_nitro_nsm_from_v1(&DstackNitroQuote {
nsm_quote: nsm_quote.clone(),
})?;
let compose_hash = os_image_hash.clone();
Ok(build_app_info(
mrs,
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> {
self.verify_with_time_with_amd_kds_client(pccs_url, now, None)
.await
}
/// Verify the quote with a caller-owned AMD KDS client.
pub async fn verify_with_amd_kds_client(
self,
pccs_url: Option<&str>,
amd_kds_client: &AmdKdsClient,
) -> Result<VerifiedAttestation> {
self.verify_with_time_with_amd_kds_client(pccs_url, None, Some(amd_kds_client))
.await
}
async fn verify_with_time_with_amd_kds_client(
self,
pccs_url: Option<&str>,
now: Option<SystemTime>,
amd_kds_client: Option<&AmdKdsClient>,
) -> 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 {
quote, tpm_quote, ..
} => {
let tdx_report =
verify_tdx_quote_with_events(pccs_url, quote, &runtime_events, &report_data)
.await?;
let tpm_report = tpm_qvl::get_collateral_and_verify(tpm_quote)
.await
.context("failed to verify TPM quote")?;
let qualifying_data = sha256(quote);
if tpm_report.attest.qualified_data != qualifying_data[..] {
bail!("tpm qualified_data mismatch");
}
let pcr_ind: u32 = 14; // GcpTdx runtime PCR
let replayed_rt_pcr = cc_eventlog::replay_events::<Sha256>(&runtime_events, None);
let quoted_rt_pcr = tpm_report
.get_pcr(pcr_ind)
.context("no runtime PCR in TPM report")?;
if replayed_rt_pcr != quoted_rt_pcr[..] {
bail!(
"PCR{pcr_ind} mismatch, quoted: {}, replayed: {}",
hex::encode(quoted_rt_pcr),
hex::encode(replayed_rt_pcr),
);
}
DstackVerifiedReport::DstackGcpTdx {
tdx_report,
tpm_report,
}
}
PlatformEvidence::NitroEnclave { nsm_quote } => {
let nsm = DstackNitroQuote {
nsm_quote: nsm_quote.clone(),
};
let verified_report = nsm_qvl::verify_attestation(
&nsm.nsm_quote,
nsm_qvl::AWS_NITRO_ENCLAVES_ROOT_G1,
None,
now,
)
.context("NSM attestation verification failed")?;
let Some(user_data) = verified_report.user_data.clone() else {
bail!("NSM attestation document does not contain user_data");
};
if user_data != report_data[..] {
bail!("NSM user_data does not match report_data");
}
// Use the PCRs from the signature-verified report, not a
// re-parse of the raw document, so the values that feed
// os_image_hash / MR derivation are authenticated.
let pcrs = NitroPcrs::from_verified(&verified_report.pcrs)
.context("verified NSM report missing PCR0/1/2")?;
DstackVerifiedReport::DstackNitroEnclave(NitroVerifiedReport {
module_id: verified_report.module_id,
pcrs,
user_data,
timestamp: verified_report.timestamp,
})
}
PlatformEvidence::SevSnp {
report,
cert_chain,
mr_config,
} => {
let owned_kds_client;
let kds_client = match amd_kds_client {
Some(client) => client,
None => {
owned_kds_client = AmdKdsClient::new()?;
&owned_kds_client
}
};
let verified = kds_client
.verify_evidence_with_kds_fallback(report, cert_chain, &report_data)
.await?;
verify_snp_mr_config_host_data(mr_config, &verified.host_data)?;
DstackVerifiedReport::DstackAmdSevSnp(verified)
}
};
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 struct DstackGcpTdxQuote {
pub tdx_quote: TdxQuote,
pub tpm_quote: TpmQuote,
}
#[derive(Clone, Encode, Decode)]
pub struct DstackNitroQuote {
pub nsm_quote: Vec<u8>,
}
#[derive(Clone, Debug, Serialize)]
pub struct NitroPcrs {
#[serde(with = "serde_human_bytes")]
pub pcr0: Vec<u8>,
#[serde(with = "serde_human_bytes")]
pub pcr1: Vec<u8>,
#[serde(with = "serde_human_bytes")]
pub pcr2: Vec<u8>,
}
impl NitroPcrs {
/// Build `NitroPcrs` from the PCR map of a signature-verified NSM report
/// (`nsm_qvl::NsmVerifiedReport::pcrs`). This is the trusted source of PCR
/// values: it has been authenticated by the COSE signature, unlike
/// [`DstackNitroQuote::decode_pcrs`] which re-parses the raw document.
pub fn from_verified(pcrs: &std::collections::BTreeMap<u16, Vec<u8>>) -> Result<NitroPcrs> {
let pcr0 = pcrs.get(&0).cloned().context("PCR 0 not found")?;
let pcr1 = pcrs.get(&1).cloned().context("PCR 1 not found")?;
let pcr2 = pcrs.get(&2).cloned().context("PCR 2 not found")?;
Ok(NitroPcrs { pcr0, pcr1, pcr2 })
}
fn is_zero(&self) -> bool {
self.pcr0.iter().all(|&b| b == 0)
&& self.pcr1.iter().all(|&b| b == 0)
&& self.pcr2.iter().all(|&b| b == 0)
}
/// Whether the enclave ran in debug mode. AWS zeroes PCR0/1/2 for debug
/// enclaves, so there is no measurement of the actual code; verifiers must
/// refuse to authorize such enclaves.
pub fn is_debug(&self) -> bool {
self.is_zero()
}
/// The OS image hash = sha256(pcr0 || pcr1 || pcr2). Callers must reject
/// debug enclaves (see [`is_debug`](Self::is_debug)) before trusting this.
pub fn image_hash(&self) -> Vec<u8> {
sha256([&self.pcr0, &self.pcr1, &self.pcr2]).to_vec()
}
}
impl DstackNitroQuote {
pub fn decode_cose(&self) -> Result<nsm_attest::AttestationDocument> {
nsm_attest::AttestationDocument::from_cose(&self.nsm_quote)
.context("Failed to decode NSM attestation document")
}
pub fn decode_image_hash(&self) -> Result<Vec<u8>> {
let pcrs = self.decode_pcrs()?;
let hash = if pcrs.is_zero() {