-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathmain.rs
More file actions
1818 lines (1618 loc) · 57.7 KB
/
Copy pathmain.rs
File metadata and controls
1818 lines (1618 loc) · 57.7 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
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use dstack_attest::emit_runtime_event;
use dstack_types::{KeyProvider, KeyProviderKind};
use fs_err as fs;
use gateway_checker::{cmd_gateway_checker, GatewayCheckerArgs};
use getrandom::fill as getrandom;
use host_api::HostApi;
use k256::schnorr::SigningKey;
use ra_rpc::Attestation;
use ra_tls::{
attestation::{AttestationQuote, QuoteContentType, VersionedAttestation},
cert::{generate_ra_cert, generate_ra_cert_with_app_id},
kdf::{derive_key, derive_p256_key_pair_from_bytes},
rcgen::KeyPair,
};
use safe_write::{safe_write, safe_write_with_mode};
use scale::Encode;
use std::path::Path;
use std::{
io::{self, Read, Write},
path::PathBuf,
};
use system_setup::{cmd_gateway_refresh, cmd_sys_setup, GatewayRefreshArgs, SetupArgs};
use tdx_attest as att;
use utils::AppKeys;
mod crypto;
mod docker_compose;
mod gateway_checker;
mod host_api;
mod host_shared;
mod parse_env_file;
mod system_setup;
mod utils;
/// dstack guest utility
#[derive(Parser)]
#[command(author, version, about)]
struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Generate a TDX quote given report data from stdin
Quote,
/// Get TDX event logs
Eventlog,
/// Extend RTMRs
Extend(ExtendArgs),
/// Show the current RTMR state
Show,
/// Replay event log and show calculated IMR/RTMR values
ReplayImr,
/// Hex encode data
Hex(HexCommand),
/// Generate a RA-TLS certificate
GenRaCert(GenRaCertArgs),
/// Generate a CA certificate
GenCaCert(GenCaCertArgs),
/// Generate app keys for an dstack app
GenAppKeys(GenAppKeysArgs),
/// Generate random data
Rand(RandArgs),
/// Prepare dstack system.
Setup(SetupArgs),
/// Mount or unmount the host-provided shared directory.
HostShared(host_shared::HostSharedArgs),
/// Refresh the dstack gateway configuration
GatewayRefresh(GatewayRefreshArgs),
/// Keep the dstack gateway registration fresh (long-running)
GatewayChecker(GatewayCheckerArgs),
/// Notify the host about the dstack app
NotifyHost(HostNotifyArgs),
/// Remove orphaned containers
RemoveOrphans(RemoveOrphansArgs),
/// Perform vTPM attestation (for GCP TEE instances)
VtpmAttest(VtpmAttestArgs),
/// Generate a TPM quote
TpmQuote(TpmQuoteArgs),
/// Verify a TPM quote
TpmVerify(TpmVerifyArgs),
QuoteReport(QuoteReportArgs),
/// Generate a versioned attestation for simulator use
Attest(AttestArgs),
/// Show size breakdown for a versioned attestation file
AttestInfo(AttestInfoArgs),
/// Dump a versioned attestation as JSON
AttestJson(AttestJsonArgs),
/// Strip attestation for certificate embedding
AttestStrip(AttestStripArgs),
/// Get app keys from a KMS server
GetKeys(GetKeysArgs),
/// Decrypt data encrypted with the app's environment encryption public key
Decrypt(DecryptArgs),
/// Encrypt data for an app using its KMS-provided environment encryption key
Encrypt(EncryptArgs),
}
#[derive(Parser)]
/// Hex encode data
struct HexCommand {
#[clap(value_parser)]
/// filename to hex encode
filename: Option<String>,
}
#[derive(Parser)]
/// Extend RTMR
struct ExtendArgs {
#[clap(short, long)]
/// event name
event: String,
#[clap(short, long)]
/// hex encoded payload of the event
payload: String,
}
#[derive(Parser)]
/// Generate a certificate
struct GenRaCertArgs {
/// CA certificate used to sign the RA certificate
#[arg(long)]
ca_cert: PathBuf,
/// CA private key used to sign the RA certificate
#[arg(long)]
ca_key: PathBuf,
#[arg(short, long)]
/// file path to store the certificate
cert_path: PathBuf,
#[arg(short, long)]
/// file path to store the private key
key_path: PathBuf,
}
#[derive(Parser)]
/// Generate CA certificate
struct GenCaCertArgs {
/// path to store the certificate
#[arg(long)]
cert: PathBuf,
/// path to store the private key
#[arg(long)]
key: PathBuf,
/// CA level
#[arg(long, default_value_t = 1)]
ca_level: u8,
}
#[derive(Parser)]
/// Generate app keys
struct GenAppKeysArgs {
/// CA level
#[arg(long, default_value_t = 1)]
ca_level: u8,
/// path to store the app keys
#[arg(short, long)]
output: PathBuf,
}
#[derive(Parser)]
/// Generate random data
struct RandArgs {
/// number of bytes to generate
#[arg(short = 'n', long, default_value_t = 20)]
bytes: usize,
/// output to file
#[arg(short = 'o', long)]
output: Option<String>,
/// hex encode output
#[arg(short = 'x', long)]
hex: bool,
}
#[derive(Parser)]
/// Test app feature. Print "true" if the feature is supported, otherwise print "false".
struct TestAppFeatureArgs {
/// path to the app keys
#[arg(short, long)]
feature: String,
/// path to the app compose file
#[arg(short, long)]
compose: String,
}
#[derive(Parser)]
/// Notify the host about the dstack app
struct HostNotifyArgs {
#[arg(short, long)]
url: Option<String>,
/// event name
#[arg(short, long)]
event: String,
/// event payload
#[arg(short = 'd', long)]
payload: String,
}
#[derive(Parser)]
/// Remove orphaned containers
struct RemoveOrphansArgs {
/// path to the docker-compose.yaml file
#[arg(short = 'f', long)]
compose: String,
/// show what would be removed without actually removing
#[arg(short = 'n', long)]
dry_run: bool,
/// Offline mode: operate without Docker daemon by directly reading Docker data directory
#[arg(long)]
no_dockerd: bool,
/// Docker data root directory for offline mode (default: /var/lib/docker)
#[arg(short = 'd', long, default_value = "/var/lib/docker")]
docker_root: String,
}
#[derive(Parser)]
/// Perform vTPM attestation
struct VtpmAttestArgs {
/// path to Root CA certificate (PEM format)
#[arg(long)]
root_ca: PathBuf,
/// nonce for replay protection
#[arg(long)]
nonce: String,
/// expected OS image SHA256 hash (optional)
#[arg(long)]
expected_os_hash: Option<String>,
/// key algorithm (rsa or ecc, default: rsa)
#[arg(long, default_value = "rsa")]
key_algo: String,
/// output format (json or text, default: text)
#[arg(long, default_value = "text")]
format: String,
}
#[derive(Parser)]
/// Generate a TPM quote
struct TpmQuoteArgs {
/// qualifying data (hex encoded, default: 32 zeros)
#[arg(short, long)]
data: Option<String>,
/// output file (default: stdout)
#[arg(short, long)]
output: Option<PathBuf>,
/// key algorithm (auto, ecc, or rsa; default: auto)
#[arg(short = 'k', long, default_value = "auto")]
key_algo: String,
/// The hash algorithm to use (default: none)
#[arg(short = 'H', long, default_value = "none")]
hash_algo: String,
}
#[derive(Parser)]
/// Verify a TPM quote
struct TpmVerifyArgs {
/// path to Root CA certificate (PEM format)
#[arg(long)]
root_ca: PathBuf,
/// path to TPM quote JSON file
#[arg(short, long)]
quote: PathBuf,
}
#[derive(Parser)]
struct QuoteReportArgs {
#[arg(long)]
report_data: Option<String>,
#[arg(long, default_value = "/dstack/.host-shared/.sys-config.json")]
sys_config: PathBuf,
#[arg(short, long)]
output: Option<PathBuf>,
#[arg(long, default_value_t = false)]
debug: bool,
}
#[derive(Parser)]
struct AttestArgs {
/// report data in hex (max 64 bytes)
#[arg(long)]
report_data: Option<String>,
/// app id (20 bytes in hex) - optional
#[arg(long)]
app_id: Option<String>,
/// output file (default: attestation.bin)
#[arg(short, long)]
output: Option<PathBuf>,
/// hex encode output
#[arg(long, default_value_t = false)]
hex: bool,
}
#[derive(Parser)]
struct AttestInfoArgs {
/// input file (default: attestation.bin)
#[arg(short, long)]
input: Option<PathBuf>,
}
#[derive(Parser)]
struct AttestJsonArgs {
/// input file (default: attestation.bin)
#[arg(short, long)]
input: Option<PathBuf>,
/// output file (default: stdout)
#[arg(short, long)]
output: Option<PathBuf>,
}
#[derive(Parser)]
struct AttestStripArgs {
/// input file (default: attestation.bin)
#[arg(short, long)]
input: Option<PathBuf>,
/// output file (default: attestation.strip.bin)
#[arg(short, long)]
output: Option<PathBuf>,
}
#[derive(Parser)]
/// Get app keys from a KMS server
struct GetKeysArgs {
/// KMS server URL (e.g., https://kms.example.com)
#[arg(short, long)]
kms_url: String,
/// Application ID (20 bytes in hex) - optional
#[arg(long)]
app_id: Option<String>,
/// Output file path (default: stdout as JSON)
#[arg(short, long)]
output: Option<PathBuf>,
/// Root CA certificate (PEM format) to pin for TLS verification.
/// If not provided, TLS certificate verification is skipped for the initial connection.
#[arg(long)]
root_ca: Option<PathBuf>,
}
#[derive(Parser)]
/// Decrypt data encrypted with the app's environment encryption public key
struct DecryptArgs {
/// Input file (default: stdin)
#[arg(short, long)]
input: Option<PathBuf>,
/// Output file (default: stdout)
#[arg(short, long)]
output: Option<PathBuf>,
/// App keys file containing env_crypt_key
#[arg(long)]
key_file: Option<PathBuf>,
/// Decode the input as hexadecimal text before decrypting
#[arg(long)]
hex: bool,
}
#[derive(Parser)]
/// Encrypt data for an app using its KMS-provided environment encryption key
struct EncryptArgs {
/// KMS server URL
#[arg(short, long)]
kms_url: String,
/// Application ID (20 bytes in hex)
#[arg(long)]
app_id: String,
/// Input file (default: stdin)
#[arg(short, long)]
input: Option<PathBuf>,
/// Output file (default: stdout)
#[arg(short, long)]
output: Option<PathBuf>,
/// Plaintext bytes per independently authenticated chunk
#[arg(long, default_value_t = crypto::DEFAULT_CHUNK_SIZE)]
chunk_size: usize,
/// Root CA certificate (PEM format) used to verify the KMS TLS certificate
#[arg(long)]
root_ca: Option<PathBuf>,
/// Trusted compressed secp256k1 KMS signer public key (hex)
#[arg(long)]
kms_pubkey: String,
/// Maximum accepted age of the KMS public-key signature in seconds
#[arg(long, default_value_t = 300)]
max_signature_age: u64,
}
fn pad64(data: &[u8]) -> Result<[u8; 64]> {
if data.len() > 64 {
anyhow::bail!("report_data must be at most 64 bytes");
}
let mut out = [0u8; 64];
out[..data.len()].copy_from_slice(data);
Ok(out)
}
fn cmd_quote_report(args: QuoteReportArgs) -> Result<()> {
#[derive(serde::Serialize)]
struct VerificationRequestJson {
pub attestation: String,
}
let report_data = match args.report_data {
Some(hex_data) => {
pad64(&hex_decode(&hex_data).context("Failed to decode report_data hex")?)?
}
None => [0u8; 64],
};
if args.debug {
eprintln!("debug: quote diagnostics enabled; attestation policy is unchanged");
}
let attestation = Attestation::quote_with_sys_config(&report_data, &args.sys_config)
.context("Failed to get attestation")?;
let request = VerificationRequestJson {
attestation: hex::encode(attestation.into_versioned().to_scale()?),
};
let json =
serde_json::to_string_pretty(&request).context("Failed to serialize request JSON")?;
if let Some(output_path) = args.output {
safe_write::safe_write(&output_path, json).context("Failed to write quote report")?;
} else {
println!("{json}");
}
Ok(())
}
fn decode_app_id(hex_str: Option<&str>) -> Result<Option<[u8; 20]>> {
let Some(hex_str) = hex_str else {
return Ok(None);
};
let bytes = hex_decode(hex_str).context("Invalid app_id hex string")?;
if bytes.len() != 20 {
anyhow::bail!("app_id must be exactly 20 bytes (40 hex characters)");
}
let mut arr = [0u8; 20];
arr.copy_from_slice(&bytes);
Ok(Some(arr))
}
fn cmd_attest(args: AttestArgs) -> Result<()> {
let report_data = match args.report_data {
Some(hex_data) => {
pad64(&hex_decode(&hex_data).context("Failed to decode report_data hex")?)?
}
None => [0u8; 64],
};
let app_id = decode_app_id(args.app_id.as_deref())?;
let attestation = Attestation::quote_with_app_id(&report_data, app_id)
.context("Failed to get attestation")?;
let attestation = attestation.into_versioned().to_scale()?;
if args.hex {
let encoded = hex::encode(&attestation);
if let Some(output) = args.output {
safe_write::safe_write(&output, encoded).context("Failed to write attestation hex")?;
} else {
println!("{encoded}");
}
return Ok(());
}
let output = args
.output
.unwrap_or_else(|| PathBuf::from("attestation.bin"));
safe_write::safe_write(&output, &attestation).context("Failed to write attestation sample")?;
Ok(())
}
fn cmd_attest_info(args: AttestInfoArgs) -> Result<()> {
let input = args
.input
.unwrap_or_else(|| PathBuf::from("attestation.bin"));
let data = fs::read(&input).context("Failed to read attestation file")?;
let attestation =
VersionedAttestation::from_scale(&data).context("Failed to decode attestation")?;
println!("file: {}", input.display());
println!("total_bytes: {}", data.len());
match attestation {
VersionedAttestation::V0 { attestation } => {
println!("version: V0");
println!("mode: {:?}", attestation.quote.variant());
println!("config_bytes: {}", attestation.config.len());
match attestation.tdx_quote() {
Some(tdx) => {
let event_log_json = serde_json::to_vec(&tdx.event_log)
.context("Failed to serialize event log")?;
println!("tdx_quote_bytes: {}", tdx.quote.len());
println!("event_log_entries: {}", tdx.event_log.len());
println!("event_log_json_bytes: {}", event_log_json.len());
}
None => {
println!("tdx_quote_bytes: 0");
println!("event_log_entries: 0");
println!("event_log_json_bytes: 0");
}
}
match attestation.tpm_quote() {
Some(tpm) => {
let tpm_bytes = tpm.encode();
println!("tpm_quote_bytes: {}", tpm_bytes.len());
}
None => println!("tpm_quote_bytes: 0"),
}
}
VersionedAttestation::V1 { attestation } => {
println!("version: V1");
println!("platform: {:?}", attestation.platform);
println!("stack: {:?}", attestation.stack);
}
}
Ok(())
}
fn cmd_attest_json(args: AttestJsonArgs) -> Result<()> {
let input = args
.input
.unwrap_or_else(|| PathBuf::from("attestation.bin"));
let data = fs::read(&input).context("Failed to read attestation file")?;
let attestation =
VersionedAttestation::from_scale(&data).context("Failed to decode attestation")?;
let json = match attestation {
VersionedAttestation::V0 { attestation } => {
let mode = attestation.quote.variant().as_str();
let tdx_quote = match attestation.tdx_quote() {
Some(tdx) => serde_json::json!({
"quote": hex::encode(&tdx.quote),
"event_log": tdx.event_log,
}),
None => serde_json::Value::Null,
};
let tpm_quote = match attestation.tpm_quote() {
Some(tpm) => serde_json::to_value(tpm).context("Failed to serialize TPM quote")?,
None => serde_json::Value::Null,
};
serde_json::json!({
"version": "V0",
"mode": mode,
"config": attestation.config,
"tdx_quote": tdx_quote,
"tpm_quote": tpm_quote,
})
}
VersionedAttestation::V1 { attestation } => {
serde_json::to_value(&attestation).context("Failed to serialize V1 attestation")?
}
};
let output = serde_json::to_string_pretty(&json).context("Failed to serialize JSON")?;
if let Some(path) = args.output {
safe_write::safe_write(&path, output).context("Failed to write JSON output")?;
} else {
println!("{output}");
}
Ok(())
}
fn cmd_attest_strip(args: AttestStripArgs) -> Result<()> {
let input = args
.input
.unwrap_or_else(|| PathBuf::from("attestation.bin"));
let data = fs::read(&input).context("Failed to read attestation file")?;
let attestation =
VersionedAttestation::from_scale(&data).context("Failed to decode attestation")?;
let stripped = attestation.into_stripped();
let output = args
.output
.unwrap_or_else(|| PathBuf::from("attestation.strip.bin"));
safe_write::safe_write(&output, stripped.to_scale()?)
.context("Failed to write stripped attestation")?;
Ok(())
}
async fn cmd_get_keys(args: GetKeysArgs) -> Result<()> {
use dstack_kms_rpc::kms_client::KmsClient;
use ra_rpc::client::RaClientConfig;
let kms_url = normalize_prpc_url(&args.kms_url);
// Load root CA if provided for TLS pinning
let root_ca_pem = if let Some(root_ca_path) = &args.root_ca {
let pem = fs::read_to_string(root_ca_path)
.with_context(|| format!("failed to read root CA from {}", root_ca_path.display()))?;
Some(pem)
} else {
None
};
// Step 1: Get temporary CA certificate
eprintln!("Connecting to KMS: {kms_url}");
let tls_no_check = root_ca_pem.is_none();
if tls_no_check {
eprintln!("Warning: no --root-ca provided, TLS certificate verification is disabled for initial connection");
}
let tmp_ca = {
let client = RaClientConfig::builder()
.remote_uri(kms_url.clone())
.tls_no_check(tls_no_check)
.tls_built_in_root_certs(false)
.maybe_tls_ca_cert(root_ca_pem.clone())
.build()
.into_client()
.context("failed to create client")?;
let kms_client = KmsClient::new(client);
kms_client
.get_temp_ca_cert()
.await
.context("Failed to get temp CA cert")?
};
// Step 2: Generate RA-TLS client certificate
let app_id = decode_app_id(args.app_id.as_deref())?;
let cert_pair = generate_ra_cert_with_app_id(
tmp_ca.temp_ca_cert.clone(),
tmp_ca.temp_ca_key.clone(),
app_id,
)
.context("Failed to generate RA cert")?;
// Step 3: Create authenticated client and request app keys
let ra_client = RaClientConfig::builder()
.tls_no_check(false)
.tls_built_in_root_certs(false)
.remote_uri(kms_url.clone())
.tls_client_cert(cert_pair.cert_pem)
.tls_client_key(cert_pair.key_pem)
.tls_ca_cert(tmp_ca.ca_cert.clone())
.build()
.into_client()
.context("Failed to create RA client")?;
let kms_client = KmsClient::new(ra_client);
let response = kms_client
.get_app_key(dstack_kms_rpc::GetAppKeyRequest {
api_version: 1,
vm_config: "".to_string(),
})
.await
.context("Failed to get app key")?;
// Step 4: Build AppKeys structure
let (_, ca_pem) = x509_parser::pem::parse_x509_pem(tmp_ca.ca_cert.as_bytes())
.context("Failed to parse CA cert")?;
let x509 = ca_pem.parse_x509().context("Failed to parse CA cert")?;
let root_pubkey = x509.public_key().raw.to_vec();
let keys = utils::AppKeys {
ca_cert: tmp_ca.ca_cert,
disk_crypt_key: response.disk_crypt_key,
env_crypt_key: response.env_crypt_key,
k256_key: response.k256_key,
k256_signature: response.k256_signature,
gateway_app_id: response.gateway_app_id,
key_provider: KeyProvider::Kms {
url: kms_url,
pubkey: root_pubkey,
tmp_ca_key: tmp_ca.temp_ca_key,
tmp_ca_cert: tmp_ca.temp_ca_cert,
},
};
// Step 5: Output result
let json = serde_json::to_string_pretty(&keys).context("Failed to serialize app keys")?;
if let Some(output_path) = args.output {
safe_write_with_mode(&output_path, &json, 0o600).context("Failed to write app keys")?;
eprintln!("App keys written to: {}", output_path.display());
} else {
println!("{json}");
}
Ok(())
}
fn cmd_decrypt(args: DecryptArgs) -> Result<()> {
use dstack_types::shared_filenames::{host_shared_dir, APP_KEYS};
let key_file = args
.key_file
.unwrap_or_else(|| host_shared_dir().join(APP_KEYS));
let keys: AppKeys = utils::deserialize_json_file(&key_file)
.with_context(|| format!("failed to load app keys from {}", key_file.display()))?;
let env_crypt_key: [u8; 32] = keys
.env_crypt_key
.try_into()
.map_err(|key: Vec<u8>| anyhow::anyhow!("invalid env crypt key length: {}", key.len()))?;
if args.hex {
let input = read_all_input(args.input.as_deref())?;
let input = decode_hex_ciphertext(&input)?;
return decrypt_auto(
env_crypt_key,
input.as_slice(),
open_output(args.output.as_deref())?,
);
}
let input = open_input(args.input.as_deref())?;
decrypt_auto(env_crypt_key, input, open_output(args.output.as_deref())?)
}
fn decrypt_auto(
env_crypt_key: [u8; 32],
mut input: impl Read,
mut output: impl Write,
) -> Result<()> {
let mut prefix = Vec::with_capacity(crypto::STREAM_MAGIC.len());
input
.by_ref()
.take(crypto::STREAM_MAGIC.len() as u64)
.read_to_end(&mut prefix)
.context("failed to read ciphertext")?;
if prefix == crypto::STREAM_MAGIC {
crypto::dh_decrypt_stream(env_crypt_key, input, output)
.context("failed to decrypt stream")?;
} else {
let mut ciphertext = prefix;
input
.read_to_end(&mut ciphertext)
.context("failed to read ciphertext")?;
let plaintext = crypto::dh_decrypt(env_crypt_key, &ciphertext)
.context("failed to decrypt legacy input")?;
output
.write_all(&plaintext)
.context("failed to write plaintext")?;
}
Ok(())
}
async fn cmd_encrypt(args: EncryptArgs) -> Result<()> {
use dstack_kms_rpc::kms_client::KmsClient;
use ra_rpc::client::RaClientConfig;
let app_id = decode_app_id(Some(&args.app_id))?.context("app_id is required")?;
let kms_url = normalize_prpc_url(&args.kms_url);
let root_ca_pem = args
.root_ca
.as_ref()
.map(|path| {
fs::read_to_string(path)
.with_context(|| format!("failed to read root CA from {}", path.display()))
})
.transpose()?;
let client = RaClientConfig::builder()
.remote_uri(kms_url)
.tls_no_check(false)
.tls_built_in_root_certs(root_ca_pem.is_none())
.maybe_tls_ca_cert(root_ca_pem)
.build()
.into_client()
.context("failed to create KMS client")?;
let response = KmsClient::new(client)
.get_app_env_encrypt_pub_key(dstack_kms_rpc::AppId {
app_id: app_id.to_vec(),
})
.await
.context("failed to get app environment encryption public key")?;
let public_key: [u8; 32] = response
.public_key
.try_into()
.map_err(|key: Vec<u8>| anyhow::anyhow!("invalid public key length: {}", key.len()))?;
verify_env_encrypt_public_key(
&public_key,
&response.signature_v1,
&app_id,
response.timestamp,
&args.kms_pubkey,
args.max_signature_age,
)?;
crypto::dh_encrypt_stream(
public_key,
open_input(args.input.as_deref())?,
open_output(args.output.as_deref())?,
args.chunk_size,
)
.context("failed to encrypt stream")
}
fn normalize_prpc_url(url: &str) -> String {
let url = url.trim_end_matches('/');
if url.ends_with("/prpc") {
url.to_string()
} else {
format!("{url}/prpc")
}
}
fn decode_hex_ciphertext(input: &[u8]) -> Result<Vec<u8>> {
hex_decode(
std::str::from_utf8(input)
.context("hex ciphertext is not valid UTF-8")?
.trim(),
)
.context("failed to decode hex ciphertext")
}
fn verify_env_encrypt_public_key(
public_key: &[u8; 32],
signature: &[u8],
app_id: &[u8; 20],
timestamp: u64,
trusted_pubkey: &str,
max_age: u64,
) -> Result<()> {
use k256::ecdsa::{RecoveryId, Signature, VerifyingKey};
use sha3::{Digest, Keccak256};
use std::time::{SystemTime, UNIX_EPOCH};
const FUTURE_SKEW: u64 = 60;
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.context("system time is before the Unix epoch")?
.as_secs();
anyhow::ensure!(
timestamp <= now.saturating_add(FUTURE_SKEW),
"kms public-key signature timestamp is too far in the future"
);
anyhow::ensure!(
now.saturating_sub(timestamp) <= max_age,
"kms public-key signature is too old"
);
anyhow::ensure!(signature.len() == 65, "invalid KMS signature length");
let signature_value =
Signature::from_slice(&signature[..64]).context("invalid KMS signature")?;
let recovery_id = RecoveryId::from_byte(signature[64]).context("invalid KMS recovery ID")?;
let digest = Keccak256::new_with_prefix(
[
b"dstack-env-encrypt-pubkey".as_slice(),
b":".as_slice(),
app_id.as_slice(),
×tamp.to_be_bytes(),
public_key.as_slice(),
]
.concat(),
);
let recovered = VerifyingKey::recover_from_digest(digest, &signature_value, recovery_id)
.context("failed to recover KMS signer public key")?;
let trusted_pubkey = trusted_pubkey.strip_prefix("0x").unwrap_or(trusted_pubkey);
let trusted_pubkey =
hex_decode(trusted_pubkey).context("invalid trusted KMS public key hex")?;
let trusted =
VerifyingKey::from_sec1_bytes(&trusted_pubkey).context("invalid trusted KMS public key")?;
anyhow::ensure!(
recovered == trusted,
"kms public-key signature was made by an untrusted signer"
);
Ok(())
}
fn read_all_input(path: Option<&Path>) -> Result<Vec<u8>> {
let mut input = open_input(path)?;
let mut data = Vec::new();
input
.read_to_end(&mut data)
.context("failed to read input")?;
Ok(data)
}
fn open_input(path: Option<&Path>) -> Result<Box<dyn Read>> {
match path {
Some(path) => {
Ok(Box::new(fs::File::open(path).with_context(|| {
format!("failed to open input {}", path.display())
})?))
}
None => Ok(Box::new(io::stdin())),
}
}
fn open_output(path: Option<&Path>) -> Result<Box<dyn Write>> {
use fs_err::os::unix::fs::OpenOptionsExt;
use std::os::unix::fs::PermissionsExt;
match path {
Some(path) => {
let file = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(path)
.with_context(|| format!("failed to open output {}", path.display()))?;
file.set_permissions(std::fs::Permissions::from_mode(0o600))
.with_context(|| format!("Failed to set permissions on {}", path.display()))?;
Ok(Box::new(file))
}
None => Ok(Box::new(io::stdout())),
}
}
fn cmd_quote() -> Result<()> {
let mut input = Vec::with_capacity(65);
io::stdin()
.take(65)
.read_to_end(&mut input)
.context("Failed to read report data")?;
anyhow::ensure!(
input.len() == 64,
"report data must be exactly 64 bytes (received {})",
input.len()
);
let report_data: [u8; 64] = input
.try_into()
.map_err(|_| anyhow::anyhow!("invalid report data length"))?;
// Platform-adaptive: detect the running TEE and emit its raw hardware quote
// (the TDX DCAP quote, or the AMD SEV-SNP report). For a verifier-ready,
// platform-agnostic payload (with event log / mr_config), use `quote-report`.
let attestation = Attestation::quote(&report_data).context("Failed to get quote")?;
let quote = match &attestation.quote {
AttestationQuote::DstackTdx(tdx) => tdx.quote.clone(),
AttestationQuote::DstackGcpTdx(gcp) => gcp.tdx_quote.quote.clone(),
AttestationQuote::DstackAmdSevSnp(snp) => snp.report.clone(),
AttestationQuote::DstackNitroEnclave(_) => {
anyhow::bail!("nitro enclave has no raw quote; use `quote-report` instead");
}
AttestationQuote::DstackAwsNitroTpm(aws) => aws.attestation_doc.clone(),
};
io::stdout()
.write_all("e)
.context("Failed to write quote")?;
Ok(())
}
fn cmd_eventlog() -> Result<()> {
let event_logs = cc_eventlog::tdx::read_event_log().context("Failed to read event logs")?;
serde_json::to_writer_pretty(io::stdout(), &event_logs)
.context("Failed to write event logs")?;
Ok(())
}
fn hex_decode(hex_str: &str) -> Result<Vec<u8>> {
hex::decode(hex_str.trim_start_matches("0x")).context("Invalid hex string")
}
fn cmd_extend(extend_args: ExtendArgs) -> Result<()> {
let payload = hex_decode(&extend_args.payload).context("Failed to decode payload")?;
emit_runtime_event(&extend_args.event, &payload).context("Failed to extend RTMR")
}
fn cmd_rand(rand_args: RandArgs) -> Result<()> {
let mut data = vec![0u8; rand_args.bytes];
getrandom(&mut data).context("Failed to generate random data")?;
if rand_args.hex {
data = hex::encode(data).into_bytes();
}
if let Some(output) = rand_args.output {
// key material: owner-only, and never half-written — a truncated
// random file would pass for a valid secret.
safe_write::safe_write_with_mode(&output, &data, 0o600)
.with_context(|| format!("Failed to write random output {output}"))?;
} else {