diff --git a/docs/onboarding.md b/docs/onboarding.md index c46db76f5..ec4a23f3b 100644 --- a/docs/onboarding.md +++ b/docs/onboarding.md @@ -315,14 +315,15 @@ The KMS VM ID is printed by `dstackup install` when it creates or reuses the KMS ### Upgrading the local KMS to root epochs -Upgrade the bundled `dstack-auth` together with the KMS. Before normal key release, -set `kmsContractAddr` in the host's `auth-allowlist.json` to the KMS's attested app ID -and register the verified bootstrap CA/k256 public keys in `rootEpochs` (epoch zero). -Use the bootstrap evidence to verify these keys; do not trust an unauthenticated -metadata response. Set `currentRootEpoch` to the active registered epoch (initially +Fresh `dstackup install` runs deploy KMS 0.6+ and automatically verify the KMS +bootstrap attestation before recording `kmsContractAddr` and `rootEpochs[0]` in +`auth-allowlist.json`. When upgrading an older local install, upgrade the +bundled `dstack-auth` together with the KMS, set `kmsContractAddr` in the host's +`auth-allowlist.json` to the KMS's attested app ID, and register the verified +bootstrap CA/k256 public keys in `rootEpochs` (epoch zero). Use the bootstrap +evidence to verify these keys; do not trust an unauthenticated metadata +response. Set `currentRootEpoch` to the active registered epoch (initially zero). See [root registration and rotation](deployment.md#rotating-kms-root-keys). -The local installer does not register these keys automatically; an older installed -KMS can continue using the legacy boot routes while this migration is prepared. The Rust backend implements `/authorizeKms` and `/authorizeApp` with the same registered-root requirement as the other backends. Missing registration denies key diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index 6b4dae1d2..10155ca7b 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -1984,6 +1984,7 @@ version = "0.6.7" dependencies = [ "anyhow", "clap", + "dstack-cli-core", "dstack-types", "hex", "rocket", @@ -2023,10 +2024,12 @@ dependencies = [ "anyhow", "dstack-types", "dstack-vmm-rpc", + "hex", "http-client", "rustix 0.38.44", "safe-write", "serde_json", + "tempfile", "toml", ] @@ -2662,15 +2665,24 @@ version = "0.6.7" dependencies = [ "anyhow", "clap", + "dstack-attest", "dstack-cli-core", + "dstack-kms-rpc", + "dstack-mr", + "dstack-types", "hex", + "mock-attestation", + "ra-rpc", + "ra-tls", "rand 0.8.6", "reqwest", "serde", "serde_json", "sha2 0.10.9", + "sha3", "tempfile", "tokio", + "x509-parser 0.16.0", ] [[package]] diff --git a/dstack/crates/dstack-auth/Cargo.toml b/dstack/crates/dstack-auth/Cargo.toml index 518c712c2..b51d6a665 100644 --- a/dstack/crates/dstack-auth/Cargo.toml +++ b/dstack/crates/dstack-auth/Cargo.toml @@ -22,4 +22,5 @@ serde.workspace = true serde_json.workspace = true [dev-dependencies] +dstack-cli-core.workspace = true tempfile.workspace = true diff --git a/dstack/crates/dstack-auth/src/main.rs b/dstack/crates/dstack-auth/src/main.rs index ab54b7694..2e8396ef6 100644 --- a/dstack/crates/dstack-auth/src/main.rs +++ b/dstack/crates/dstack-auth/src/main.rs @@ -1446,4 +1446,60 @@ mod tests { .unwrap(); assert!(check_app(&info2, &al).is_allowed); } + + /// An allowlist initialized by `dstackup`, populated with the attested KMS + /// identity + epoch-0 roots, and extended by `dstack deploy` authorizes app + /// key release through `/authorizeApp`. + #[test] + fn dstackup_registered_allowlist_authorizes_apps() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("auth-allowlist.json"); + let os_image = "aa".repeat(32); + let kms_id = "11".repeat(20); + let app_id = "22".repeat(20); + let compose_hash = "33".repeat(32); + let ca_pubkey = [0x30u8; 48]; + let k256_pubkey = [0x02u8; 33]; + + dstack_cli_core::config::ensure_allowlist( + &path, + &dstack_cli_core::config::HostConfig { + os_image_hash: os_image.clone(), + ..Default::default() + }, + ) + .unwrap(); + dstack_cli_core::config::register_app_in_allowlist(&path, &app_id, &compose_hash).unwrap(); + + let req = AuthorizationRequest { + operation: Operation::AppGetKey, + boot_info: boot(&app_id, &compose_hash, &os_image), + requested_root_epoch: Some(0), + requested_app_epoch: Some(0), + }; + // Before post-bootstrap root-epoch registration, /authorizeApp denies. + let before = authorize(&req, false, &load(&path)).unwrap(); + assert!(!before.authorized); + assert_eq!(before.rejection_reason, "root epoch not registered"); + + // After post-bootstrap root-epoch registration, /authorizeApp authorizes. + dstack_cli_core::config::register_kms_root_epoch_in_allowlist( + &path, + &kms_id, + &ca_pubkey, + &k256_pubkey, + ) + .unwrap(); + let after = authorize(&req, false, &load(&path)).unwrap(); + assert!(after.authorized, "rejected: {}", after.rejection_reason); + assert_eq!(after.current_root_epoch, 0); + assert_eq!(after.latest_root_epoch, 0); + let expected_hash = format!( + "0x{}", + hex::encode( + dstack_types::root_epoch::chain_hashes([(&ca_pubkey[..], &k256_pubkey[..])])[0] + ) + ); + assert_eq!(after.current_root_epoch_hash, expected_hash); + } } diff --git a/dstack/crates/dstack-cli-core/Cargo.toml b/dstack/crates/dstack-cli-core/Cargo.toml index 3f4d0bdcc..92c3524ae 100644 --- a/dstack/crates/dstack-cli-core/Cargo.toml +++ b/dstack/crates/dstack-cli-core/Cargo.toml @@ -10,6 +10,7 @@ license.workspace = true [dependencies] anyhow.workspace = true +hex = { workspace = true, features = ["alloc"] } http-client = { workspace = true, features = ["prpc"] } dstack-vmm-rpc.workspace = true dstack-types.workspace = true @@ -20,4 +21,5 @@ safe-write.workspace = true rustix = { version = "0.38", features = ["fs"] } [dev-dependencies] +tempfile.workspace = true toml.workspace = true diff --git a/dstack/crates/dstack-cli-core/src/config.rs b/dstack/crates/dstack-cli-core/src/config.rs index 774e817f7..ef7e69a48 100644 --- a/dstack/crates/dstack-cli-core/src/config.rs +++ b/dstack/crates/dstack-cli-core/src/config.rs @@ -13,7 +13,7 @@ //! set by `dstackup install`). use crate::host::Platform; -use anyhow::{Context, Result}; +use anyhow::{bail, Context, Result}; use serde_json::json; use std::path::Path; @@ -80,6 +80,213 @@ pub fn register_app_in_allowlist(path: &Path, app_id: &str, compose_hash: &str) Ok(()) } +/// Ensure the auth allowlist exists on disk without clobbering previously +/// registered apps, KMS identity, or root epochs on re-install. +/// +/// If `path` does not exist yet, writes the initial allowlist rendered from +/// `cfg`. If it already exists, preserves existing fields and appends +/// `cfg.os_image_hash` to `osImages` when non-empty and not already present. +pub fn ensure_allowlist(path: &Path, cfg: &HostConfig) -> Result<()> { + let _lock = crate::fsutil::lock_exclusive(path)?; + match std::fs::read_to_string(path) { + Ok(body) => { + let mut v: serde_json::Value = serde_json::from_str(&body) + .with_context(|| format!("parsing allowlist {}", path.display()))?; + let obj = v + .as_object_mut() + .with_context(|| format!("allowlist {} must be a JSON object", path.display()))?; + if !cfg.os_image_hash.is_empty() { + let images = obj + .entry("osImages") + .or_insert_with(|| json!([])) + .as_array_mut() + .context("allowlist `osImages` must be an array")?; + let target = norm_hex(&cfg.os_image_hash); + let present = images + .iter() + .any(|entry| entry.as_str().is_some_and(|s| norm_hex(s) == target)); + if !present { + images.push(serde_json::Value::String(cfg.os_image_hash.clone())); + } + } + crate::fsutil::write_atomic(path, &serde_json::to_string_pretty(&v)?) + .with_context(|| format!("writing allowlist {}", path.display()))?; + Ok(()) + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + crate::fsutil::write_atomic(path, &auth_allowlist_json(cfg)) + .with_context(|| format!("writing allowlist {}", path.display()))?; + Ok(()) + } + Err(e) => Err(e).with_context(|| format!("reading allowlist {}", path.display())), + } +} + +/// Returns whether the allowlist already records both `kmsContractAddr` and at +/// least one registered root epoch. +pub fn allowlist_has_registered_kms(path: &Path) -> Result { + let body = match std::fs::read_to_string(path) { + Ok(b) => b, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(e) => return Err(e).with_context(|| format!("reading allowlist {}", path.display())), + }; + let v: serde_json::Value = serde_json::from_str(&body) + .with_context(|| format!("parsing allowlist {}", path.display()))?; + let has_addr = v + .get("kmsContractAddr") + .and_then(|s| s.as_str()) + .is_some_and(|s| !norm_hex(s).is_empty()); + let has_epoch = v + .get("rootEpochs") + .and_then(|a| a.as_array()) + .is_some_and(|a| !a.is_empty()); + Ok(has_addr && has_epoch) +} + +/// Register the attested KMS app ID (`kmsContractAddr`) and bootstrap root +/// epoch 0 (`rootEpochs[0]`) in `auth-allowlist.json`. +/// +/// Read-modify-write under an exclusive lock; idempotent when the allowlist +/// already records the exact same KMS app ID and epoch-0 keys (preserving any +/// later rotated epochs and `currentRootEpoch`), and refuses to overwrite a +/// conflicting identity or root key. +pub fn register_kms_root_epoch_in_allowlist( + path: &Path, + kms_app_id: &str, + ca_pubkey: &[u8], + k256_pubkey: &[u8], +) -> Result<()> { + let norm_app_id = norm_hex(kms_app_id); + if norm_app_id.len() != 40 || hex::decode(&norm_app_id).is_err() { + bail!("invalid KMS app ID '{kms_app_id}': expected 20 hex-encoded bytes"); + } + if ca_pubkey.is_empty() { + bail!("KMS root CA public key must not be empty"); + } + if k256_pubkey.is_empty() { + bail!("KMS root k256 public key must not be empty"); + } + + let _lock = crate::fsutil::lock_exclusive(path)?; + let body = std::fs::read_to_string(path) + .with_context(|| format!("reading allowlist {}", path.display()))?; + let mut v: serde_json::Value = serde_json::from_str(&body) + .with_context(|| format!("parsing allowlist {}", path.display()))?; + let obj = v + .as_object_mut() + .with_context(|| format!("allowlist {} must be a JSON object", path.display()))?; + + let formatted_addr = format!("0x{norm_app_id}"); + match obj.get("kmsContractAddr") { + Some(serde_json::Value::String(existing)) if !norm_hex(existing).is_empty() => { + if norm_hex(existing) != norm_app_id { + bail!( + "allowlist {} already sets kmsContractAddr to {existing}, \ + which does not match the attested KMS app ID {formatted_addr}", + path.display() + ); + } + } + None | Some(serde_json::Value::Null) | Some(serde_json::Value::String(_)) => { + obj.insert( + "kmsContractAddr".to_string(), + serde_json::Value::String(formatted_addr), + ); + } + Some(_) => bail!("allowlist `kmsContractAddr` must be a string"), + } + + let ca_hex = hex::encode(ca_pubkey); + let k256_hex = hex::encode(k256_pubkey); + match obj.get("rootEpochs") { + Some(serde_json::Value::Array(epochs)) if !epochs.is_empty() => { + let epoch0 = epochs[0] + .as_object() + .context("allowlist `rootEpochs[0]` must be a JSON object")?; + let existing_ca = epoch0 + .get("caPubkey") + .and_then(|s| s.as_str()) + .map(norm_hex) + .unwrap_or_default(); + let existing_k256 = epoch0 + .get("k256Pubkey") + .and_then(|s| s.as_str()) + .map(norm_hex) + .unwrap_or_default(); + if existing_ca != ca_hex || existing_k256 != k256_hex { + bail!( + "allowlist {} already registers a different rootEpochs[0]; \ + refusing to overwrite existing root keys", + path.display() + ); + } + } + None | Some(serde_json::Value::Null) | Some(serde_json::Value::Array(_)) => { + obj.insert( + "rootEpochs".to_string(), + json!([{ + "caPubkey": format!("0x{ca_hex}"), + "k256Pubkey": format!("0x{k256_hex}"), + }]), + ); + obj.entry("currentRootEpoch").or_insert_with(|| json!(0)); + } + Some(_) => bail!("allowlist `rootEpochs` must be an array"), + } + + crate::fsutil::write_atomic(path, &serde_json::to_string_pretty(&v)?) + .with_context(|| format!("writing allowlist {}", path.display()))?; + Ok(()) +} + +/// Reject empty or explicitly pre-0.6 KMS container image tags. +/// +/// `dstackup` renders the 0.6+ `[listeners.*]` `kms.toml` layout and registers +/// root epoch 0 after bootstrap, neither of which pre-0.6 KMS releases support. +/// Unversioned tags (such as `latest` or custom local tags) and digest-only +/// references are allowed. +pub fn validate_kms_image(image: &str) -> Result<()> { + let image = image.trim(); + if image.is_empty() { + bail!("--kms-image must not be empty"); + } + let without_digest = image.split('@').next().unwrap_or(image); + let last_segment = without_digest.rsplit('/').next().unwrap_or(without_digest); + if let Some((_, tag)) = last_segment.split_once(':') { + if let Some((major, minor)) = parse_semver_major_minor(tag) { + if (major, minor) < (0, 6) { + bail!( + "--kms-image '{image}' targets KMS {major}.{minor}, which is older than 0.6; \ + dstackup requires KMS 0.6+ for the [listeners.*] config layout and \ + root-epoch authorization" + ); + } + } + } + Ok(()) +} + +fn parse_semver_major_minor(tag: &str) -> Option<(u64, u64)> { + let s = tag + .strip_prefix('v') + .or_else(|| tag.strip_prefix('V')) + .unwrap_or(tag); + let (major_str, rest) = s.split_once('.')?; + if major_str.is_empty() || !major_str.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let minor_len = rest.bytes().take_while(|b| b.is_ascii_digit()).count(); + if minor_len == 0 { + return None; + } + let minor_str = &rest[..minor_len]; + let trailing = &rest[minor_len..]; + if !trailing.is_empty() && !matches!(trailing.as_bytes()[0], b'.' | b'-' | b'+' | b'_') { + return None; + } + Some((major_str.parse().ok()?, minor_str.parse().ok()?)) +} + /// public OS-image download URL template used by the KMS image-hash verifier. pub const DEFAULT_IMAGE_DOWNLOAD_URL: &str = "https://download.dstack.org/os-images/mr_{OS_IMAGE_HASH}.tar.gz"; @@ -123,16 +330,29 @@ pub fn kms_toml(cfg: &HostConfig) -> String { format!( r#"# generated by `dstackup install` — single-node KMS -[rpc] +[listeners.default.tls] +key = "/kms/certs/rpc.key" +certs = "/kms/certs/rpc.crt" + +[listeners.guest] address = "0.0.0.0" port = 8000 -[rpc.tls] -key = "/kms/certs/rpc.key" -certs = "/kms/certs/rpc.crt" +# the key handover path a serving KMS requires; the token stays on the host. +[listeners.admin] +enabled = true +address = "127.0.0.1" +port = 8001 +auth_token_hash = "{admin_token_hash}" + +[listeners.onboard] +address = "0.0.0.0" +port = 8000 [core] cert_dir = "/kms/certs" +# the root keys of every epoch; on the persistent kms-volume. +keyring_dir = "/kms/keyring" # single-node: the KMS does not self-attest to its own auth API before # bootstrap (it still attests the genesis keys via the guest agent, and app # auth + per-app quote checks are unaffected). @@ -152,22 +372,9 @@ type = "webhook" [core.auth_api.webhook] url = "{webhook_url}" -# the key handover path a serving KMS requires; the token stays on the host. -[core.admin] -enabled = true -address = "127.0.0.1" -port = 8001 -auth_token_hash = "{admin_token_hash}" - -[core.admin.tls] -key = "/kms/certs/rpc.key" -certs = "/kms/certs/rpc.crt" - [core.onboard] enabled = true auto_bootstrap_domain = "{bootstrap_domain}" -address = "0.0.0.0" -port = 8000 "#, // AMD SEV-SNP gates EVERY key release (incl. the KMS's own bootstrap) on // `sev_snp_key_release`, which defaults to false — so it must be set on @@ -207,8 +414,8 @@ pub fn auth_allowlist_json(cfg: &HostConfig) -> String { } /// default reproducibly-built KMS image, digest-pinned since it is measured into the -/// compose hash. -pub const DEFAULT_KMS_IMAGE: &str = "dstacktee/dstack-kms:0.5.11@sha256:84b793feed825a5b5e70d04386e931e0e110461492793f17ab2128e39808d989"; +/// compose hash. It has to read the `[listeners.*]` layout `kms_toml` renders. +pub const DEFAULT_KMS_IMAGE: &str = "ghcr.io/dstack-tee/dstack-kms:0.6.7@sha256:693b7c80bad6f759a17f3cc62503eb1ef768852527d448dcfbbb9edb3e8f99f3"; /// Build the KMS app-compose manifest with an embedded `kms.toml` init script. /// Select SGX local provisioning on TDX and native SNP provisioning on AMD. @@ -525,14 +732,27 @@ mod tests { let toml = kms_toml(&cfg); assert!(toml.contains("enforce_self_authorization = false")); let v: toml::Value = toml::from_str(&toml).unwrap(); - let admin = &v["core"]["admin"]; + // the 0.6 KMS refuses to start on listener settings at their old + // locations: [rpc], [core.admin], core.onboard.address/port. + let top: Vec<&String> = v.as_table().unwrap().keys().collect(); + assert_eq!(top, ["core", "listeners"]); + assert!(v["core"].get("admin").is_none()); + assert!(v["core"]["onboard"].get("address").is_none()); + assert!(v["core"]["onboard"].get("port").is_none()); + let listeners = &v["listeners"]; + assert_eq!(listeners["guest"]["port"].as_integer(), Some(8000)); + let admin = &listeners["admin"]; assert_eq!(admin["enabled"].as_bool(), Some(true)); + assert_eq!(admin["address"].as_str(), Some("127.0.0.1")); assert_eq!( admin["auth_token_hash"].as_str(), Some("ab".repeat(32).as_str()) ); - assert_eq!(admin["tls"]["key"].as_str(), Some("/kms/certs/rpc.key")); - assert_eq!(admin["tls"]["certs"].as_str(), Some("/kms/certs/rpc.crt")); + let tls = &listeners["default"]["tls"]; + assert_eq!(tls["key"].as_str(), Some("/kms/certs/rpc.key")); + assert_eq!(tls["certs"].as_str(), Some("/kms/certs/rpc.crt")); + // keep the root keys on the persistent kms-volume instead of /var/lib/kms. + assert_eq!(v["core"]["keyring_dir"].as_str(), Some("/kms/keyring")); assert!(toml.contains(r#"auto_bootstrap_domain = "10.0.2.2""#)); assert!(toml.contains(r#"type = "webhook""#)); assert!(toml.contains(r#"url = "http://10.0.2.2:8001""#)); @@ -590,4 +810,124 @@ mod tests { assert_eq!(v["kms"]["mrAggregated"].as_array().unwrap().len(), 0); assert!(v["apps"].as_object().unwrap().is_empty()); } + + #[test] + fn validate_kms_image_requires_0_6_or_newer() { + for ok in [ + DEFAULT_KMS_IMAGE, + "ghcr.io/dstack-tee/dstack-kms:0.6.0", + "ghcr.io/dstack-tee/dstack-kms:0.6.7-snp", + "ghcr.io/dstack-tee/dstack-kms:v0.6.7@sha256:abcdef", + "ghcr.io/dstack-tee/dstack-kms:1.0.0", + "ghcr.io/dstack-tee/dstack-kms:latest", + "localhost:5000/dstack-kms:dev", + "localhost:5000/dstack-kms", + "ghcr.io/dstack-tee/dstack-kms@sha256:693b7c80bad6f759a17f3cc62503eb1ef768852527d448dcfbbb9edb3e8f99f3", + ] { + validate_kms_image(ok).unwrap_or_else(|e| panic!("expected {ok} to be valid: {e}")); + } + + for bad in [ + "", + " ", + "ghcr.io/dstack-tee/dstack-kms:0.5.11", + "ghcr.io/dstack-tee/dstack-kms:0.5.11@sha256:abcdef", + "ghcr.io/dstack-tee/dstack-kms:v0.5.8", + "ghcr.io/dstack-tee/dstack-kms:0.5", + "ghcr.io/dstack-tee/dstack-kms:0.5.0-rc1", + "ghcr.io/dstack-tee/dstack-kms:0.4.2", + "localhost:5000/dstack-kms:0.5.11", + ] { + assert!( + validate_kms_image(bad).is_err(), + "expected {bad} to be rejected" + ); + } + } + + #[test] + fn register_kms_root_epoch_writes_is_idempotent_and_rejects_conflicts() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("auth-allowlist.json"); + let cfg = HostConfig { + os_image_hash: "0xaa".into(), + ..Default::default() + }; + ensure_allowlist(&path, &cfg).unwrap(); + assert!(!allowlist_has_registered_kms(&path).unwrap()); + + let kms_id = "11".repeat(20); + let ca = [0x30u8; 48]; + let k256 = [0x02u8; 33]; + register_kms_root_epoch_in_allowlist(&path, &kms_id, &ca, &k256).unwrap(); + assert!(allowlist_has_registered_kms(&path).unwrap()); + + let v: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + assert_eq!(v["kmsContractAddr"], format!("0x{kms_id}")); + assert_eq!(v["currentRootEpoch"], 0); + assert_eq!(v["rootEpochs"].as_array().unwrap().len(), 1); + assert_eq!( + v["rootEpochs"][0]["caPubkey"], + format!("0x{}", hex::encode(ca)) + ); + assert_eq!( + v["rootEpochs"][0]["k256Pubkey"], + format!("0x{}", hex::encode(k256)) + ); + + // Idempotent re-registration succeeds and preserves rotated epochs. + let mut rotated = v.clone(); + rotated["rootEpochs"] + .as_array_mut() + .unwrap() + .push(json!({"caPubkey": "0xbb", "k256Pubkey": "0xcc"})); + rotated["currentRootEpoch"] = json!(1); + std::fs::write(&path, serde_json::to_string_pretty(&rotated).unwrap()).unwrap(); + register_kms_root_epoch_in_allowlist(&path, &format!("0x{kms_id}"), &ca, &k256).unwrap(); + let after: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + assert_eq!(after["rootEpochs"].as_array().unwrap().len(), 2); + assert_eq!(after["currentRootEpoch"], 1); + + // Conflicting KMS app ID or epoch-0 keys are rejected. + assert!(register_kms_root_epoch_in_allowlist(&path, &"22".repeat(20), &ca, &k256).is_err()); + assert!( + register_kms_root_epoch_in_allowlist(&path, &kms_id, &[0x31u8; 48], &k256).is_err() + ); + assert!(register_kms_root_epoch_in_allowlist(&path, &kms_id, &ca, &[0x03u8; 33]).is_err()); + } + + #[test] + fn ensure_allowlist_preserves_registered_state_and_merges_os_images() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("auth-allowlist.json"); + ensure_allowlist( + &path, + &HostConfig { + os_image_hash: "0xaa".into(), + ..Default::default() + }, + ) + .unwrap(); + register_kms_root_epoch_in_allowlist(&path, &"11".repeat(20), &[0x30; 48], &[0x02; 33]) + .unwrap(); + register_app_in_allowlist(&path, &"33".repeat(20), &"44".repeat(32)).unwrap(); + + // Re-running with a new OS image appends it without wiping apps or KMS roots. + ensure_allowlist( + &path, + &HostConfig { + os_image_hash: "0xbb".into(), + ..Default::default() + }, + ) + .unwrap(); + let v: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + assert_eq!(v["osImages"], json!(["0xaa", "0xbb"])); + assert_eq!(v["kmsContractAddr"], format!("0x{}", "11".repeat(20))); + assert_eq!(v["rootEpochs"].as_array().unwrap().len(), 1); + assert!(v["apps"].get("33".repeat(20)).is_some()); + } } diff --git a/dstack/crates/dstackup/Cargo.toml b/dstack/crates/dstackup/Cargo.toml index 11bca8fc5..176d38b0e 100644 --- a/dstack/crates/dstackup/Cargo.toml +++ b/dstack/crates/dstackup/Cargo.toml @@ -15,8 +15,14 @@ path = "src/main.rs" [dependencies] anyhow.workspace = true clap.workspace = true +dstack-attest.workspace = true dstack-cli-core.workspace = true +dstack-kms-rpc.workspace = true +dstack-mr.workspace = true +dstack-types.workspace = true hex = { workspace = true, features = ["alloc"] } +ra-rpc = { workspace = true, features = ["client"] } +ra-tls.workspace = true rand.workspace = true # reqwest (+ rustls/hyper) is already linked via dstack-cli-core's prpc client, # so using it for http here adds ~no binary cost and drops the curl dependency. @@ -24,7 +30,10 @@ reqwest = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json.workspace = true sha2.workspace = true +sha3.workspace = true tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] } +x509-parser = { workspace = true, features = ["verify"] } [dev-dependencies] +mock-attestation = { path = "../mock-attestation" } tempfile.workspace = true diff --git a/dstack/crates/dstackup/src/install.rs b/dstack/crates/dstackup/src/install.rs index 46794e79e..4a83fb6a7 100644 --- a/dstack/crates/dstackup/src/install.rs +++ b/dstack/crates/dstackup/src/install.rs @@ -6,6 +6,7 @@ use crate::cid::pick_cid_start; use crate::cli::{InstallOpts, DEFAULT_AUTH_BIN, DEFAULT_SUPERVISOR_BIN, DEFAULT_VMM_BIN}; +use crate::kms_bootstrap::{wait_and_verify_kms_bootstrap, ExpectedKms}; use crate::state::{read_state, write, write_state, State}; use crate::systemd::{auth_unit_file, install_unit, tool, unit_active, unit_name, vmm_unit_file}; use anyhow::{bail, Context, Result}; @@ -17,6 +18,7 @@ use dstack_cli_core::{host, ports, rpc}; use sha2::{Digest, Sha256}; use std::env; use std::fs; +use std::io::Write as _; use std::path::{Path, PathBuf}; use std::process::Command as PCommand; use std::time::Duration; @@ -177,7 +179,7 @@ pub(crate) async fn cmd_install(mut o: InstallOpts, release_api_base_url: &str) host_api_port: o.host_api_port, key_provider_addr: kp_addr, key_provider_port: kp_port as u32, - kms_url, + kms_url: kms_url.clone(), kms_urls: kms_urls.clone(), platform, auth_enabled: true, @@ -191,6 +193,7 @@ pub(crate) async fn cmd_install(mut o: InstallOpts, release_api_base_url: &str) // measurement.snp.cbor committed by sha256sum.txt), so an app cannot boot // under a different, unmeasured image and still receive keys. // bootAuth/kms ignores osImages, so the KMS bootstrap itself is unaffected. + let os_image_hash_pin = os_image_hash.clone(); let host_cfg = HostConfig { auth_webhook_url: format!("http://10.0.2.2:{}", o.auth_port), os_image_hash: os_image_hash.unwrap_or_default(), @@ -199,14 +202,13 @@ pub(crate) async fn cmd_install(mut o: InstallOpts, release_api_base_url: &str) ..Default::default() }; let kms = config::kms_toml(&host_cfg); - let allowlist = config::auth_allowlist_json(&host_cfg); let vmm_path = layout.config_dir.join("vmm.toml"); let kms_path = layout.config_dir.join("kms.toml"); let allow_path = layout.config_dir.join("auth-allowlist.json"); write(&vmm_path, &vmm)?; write(&kms_path, &kms)?; - write(&allow_path, &allowlist)?; + config::ensure_allowlist(&allow_path, &host_cfg)?; println!( " [ok] wrote {}, {}, {}", vmm_path.display(), @@ -275,7 +277,7 @@ pub(crate) async fn cmd_install(mut o: InstallOpts, release_api_base_url: &str) st.kp_own_project = kp_own_project; write_state(&layout.state_dir, &st)?; - // 12. deploy + bootstrap the KMS-in-CVM (idempotent). + // 12. deploy + bootstrap the KMS-in-CVM and register epoch 0 (idempotent). if o.no_kms { println!(" (--no-kms: skipping KMS deploy)"); } else { @@ -286,6 +288,48 @@ pub(crate) async fn cmd_install(mut o: InstallOpts, release_api_base_url: &str) }; if let Some(id) = existing { println!(" [ok] KMS CVM already deployed (vm {id})"); + if config::allowlist_has_registered_kms(&allow_path)? { + println!( + " [ok] KMS root epoch already registered in {}", + allow_path.display() + ); + } else { + let existing_app_id = vmm + .status() + .await + .ok() + .and_then(|s| s.vms.into_iter().find(|vm| vm.id == id)) + .map(|vm| vm.app_id) + .filter(|app_id| !app_id.trim().is_empty()); + let expected = ExpectedKms { + platform, + app_id: existing_app_id.as_deref(), + compose_hash: None, + os_image_hash: None, + }; + print!(" [..] verifying KMS bootstrap attestation and registering root epoch 0 "); + let _ = std::io::stdout().flush(); + let verified = wait_and_verify_kms_bootstrap( + &vmm, + &id, + &kms_url, + &expected, + Duration::from_secs(180), + ) + .await + .with_context(|| { + format!( + "verifying KMS bootstrap attestation (check `dstack logs {id}` / VMM log)" + ) + })?; + config::register_kms_root_epoch_in_allowlist( + &allow_path, + &verified.kms_app_id, + &verified.ca_pubkey, + &verified.k256_pubkey, + )?; + println!("=> registered (kms 0x{})", verified.kms_app_id); + } } else { let img = o .image @@ -310,24 +354,63 @@ pub(crate) async fn cmd_install(mut o: InstallOpts, release_api_base_url: &str) }], ..Default::default() }; + let expected_compose_hash = vmm + .get_compose_hash(&cfg) + .await + .context("computing KMS compose hash")?; + let norm_compose = config::norm_hex(&expected_compose_hash); + let expected_app_id = norm_compose + .get(..40) + .context("KMS compose hash shorter than 20 bytes")?; println!(" [..] deploying KMS CVM (os {img}, kms {})", o.kms_image); let vm_id = vmm .create_vm(cfg) .await .context("createVm for the kms cvm failed")?; + st.kms_vm_id = Some(vm_id.clone()); + st.kms_url = format!("https://10.0.2.2:{kms_port}"); + write_state(&layout.state_dir, &st)?; print!(" [..] waiting for KMS CVM boot (vm {vm_id}) "); + let _ = std::io::stdout().flush(); match wait_kms_vm_booted(&vmm, &vm_id, Duration::from_secs(240)).await { KmsVmBootState::Ready => println!("=> booted"), KmsVmBootState::Failed(reason) => { - println!("=> failed ({reason}; check `dstack logs {vm_id}` / VMM log)") + println!("=> failed ({reason}; check `dstack logs {vm_id}` / VMM log)"); + bail!("KMS CVM failed to boot: {reason}"); } KmsVmBootState::Pending => { - println!("=> not ready in time (check `dstack logs {vm_id}` / VMM log)") + println!("=> not ready in time (check `dstack logs {vm_id}` / VMM log)"); + bail!("KMS CVM did not finish booting within timeout"); } } - st.kms_vm_id = Some(vm_id); - st.kms_url = format!("https://10.0.2.2:{kms_port}"); - write_state(&layout.state_dir, &st)?; + let expected = ExpectedKms { + platform, + app_id: Some(expected_app_id), + compose_hash: Some(&expected_compose_hash), + os_image_hash: os_image_hash_pin.as_deref(), + }; + print!(" [..] verifying KMS bootstrap attestation and registering root epoch 0 "); + let _ = std::io::stdout().flush(); + let verified = wait_and_verify_kms_bootstrap( + &vmm, + &vm_id, + &kms_url, + &expected, + Duration::from_secs(180), + ) + .await + .with_context(|| { + format!( + "verifying KMS bootstrap attestation (check `dstack logs {vm_id}` / VMM log)" + ) + })?; + config::register_kms_root_epoch_in_allowlist( + &allow_path, + &verified.kms_app_id, + &verified.ca_pubkey, + &verified.k256_pubkey, + )?; + println!("=> registered (kms 0x{})", verified.kms_app_id); } } @@ -1139,6 +1222,9 @@ fn validate_install_opts(o: &InstallOpts) -> Result<()> { if o.key_provider_port == 0 { bail!("--key-provider-port must be between 1 and 65535"); } + if !o.no_kms { + config::validate_kms_image(&o.kms_image)?; + } if !o.no_kms && host::other_vmm_host_api_ports().contains(&o.host_api_port) { bail!( "host-api vsock port {} is already reserved by another dstack-vmm; pass --host-api-port ", @@ -1375,4 +1461,34 @@ mod tests { KmsVmBootState::Failed("boot error: failed to start containers".to_string()) ); } + + #[test] + fn validate_install_opts_rejects_pre_0_6_kms_image() { + use clap::Parser; + let cli = crate::cli::Cli::try_parse_from([ + "dstackup", + "install", + "--kms-image", + "ghcr.io/dstack-tee/dstack-kms:0.5.11", + ]) + .unwrap(); + let crate::cli::Command::Install(opts) = cli.command else { + unreachable!(); + }; + let err = validate_install_opts(&opts).unwrap_err().to_string(); + assert!(err.contains("0.6+"), "unexpected error: {err}"); + + let cli_no_kms = crate::cli::Cli::try_parse_from([ + "dstackup", + "install", + "--no-kms", + "--kms-image", + "ghcr.io/dstack-tee/dstack-kms:0.5.11", + ]) + .unwrap(); + let crate::cli::Command::Install(opts_no_kms) = cli_no_kms.command else { + unreachable!(); + }; + validate_install_opts(&opts_no_kms).unwrap(); + } } diff --git a/dstack/crates/dstackup/src/kms_bootstrap.rs b/dstack/crates/dstackup/src/kms_bootstrap.rs new file mode 100644 index 000000000..9598852a8 --- /dev/null +++ b/dstack/crates/dstackup/src/kms_bootstrap.rs @@ -0,0 +1,650 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! Post-bootstrap attested KMS root-epoch verification for `dstackup install`. +//! +//! After the single-node KMS CVM finishes `auto_bootstrap_domain`, `dstackup` +//! queries `KMS.GetMeta` over the loopback port forward, verifies both the live +//! `kms:rpc` TLS certificate and the embedded `bootstrap_info` attestation +//! against built-in hardware roots, checks that `report_data` commits to the +//! epoch-0 `(ca_pubkey, k256_pubkey)` pair, and checks that the attested KMS +//! identity (`app_id`, `compose_hash`, and pinned `os_image_hash`) matches the +//! KMS CVM `dstackup` deployed before writing `kmsContractAddr` and +//! `rootEpochs[0]` into `auth-allowlist.json`. + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use anyhow::{anyhow, bail, ensure, Context, Result}; +use dstack_attest::attestation::{AttestationVerifier, DstackVerifiedReport, VersionedAttestation}; +use dstack_cli_core::config::norm_hex; +use dstack_cli_core::host::Platform; +use dstack_cli_core::vmm::Vmm; +use dstack_kms_rpc::{kms_client::KmsClient, GetMetaResponse}; +use ra_rpc::client::RaClientConfig; +use ra_tls::traits::CertExt; +use sha3::{Digest, Keccak256}; +use x509_parser::prelude::{FromDer, SubjectPublicKeyInfo, X509Certificate}; + +const KMS_RPC_CERT_USAGE: &str = "kms:rpc"; + +/// Expected identity of the KMS CVM being bootstrapped on this host. +#[derive(Debug, Clone)] +pub(crate) struct ExpectedKms<'a> { + pub platform: Platform, + /// Expected 20-byte KMS app ID (hex, with or without `0x`), when known. + pub app_id: Option<&'a str>, + /// Expected 32-byte KMS compose hash (hex, with or without `0x`), when known. + pub compose_hash: Option<&'a str>, + /// Expected 32-byte OS image hash (hex, with or without `0x`), when pinned. + pub os_image_hash: Option<&'a str>, +} + +/// Verified root-epoch-0 registration material extracted from KMS bootstrap +/// evidence. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct VerifiedKmsBootstrap { + /// Lowercase 40-char hex KMS app ID (`kmsContractAddr` without `0x`). + pub kms_app_id: String, + /// DER-encoded SubjectPublicKeyInfo of the epoch-0 root CA key. + pub ca_pubkey: Vec, + /// SEC1 compressed secp256k1 public key of epoch 0. + pub k256_pubkey: Vec, +} + +/// Report data committed by `dstack-kms` when attesting freshly generated root +/// keys. The `"genereted"` spelling is part of the released protocol format. +pub(crate) fn generated_keys_report_data(ca_pubkey: &[u8], k256_pubkey: &[u8]) -> [u8; 64] { + let content = format!( + "dstack-kms-genereted-keys-v1:{};{};", + hex::encode(ca_pubkey), + hex::encode(k256_pubkey) + ); + let digest: [u8; 32] = Keccak256::digest(content.as_bytes()).into(); + let mut padded = [0u8; 64]; + padded[..32].copy_from_slice(&digest); + padded +} + +/// Poll `KMS.GetMeta` on `kms_url` until the bootstrapped KMS serves its +/// attested `bootstrap_info`, then cryptographically verify the bootstrap +/// evidence and return the material to record in `auth-allowlist.json`. +pub(crate) async fn wait_and_verify_kms_bootstrap( + vmm: &Vmm, + vm_id: &str, + kms_url: &str, + expected: &ExpectedKms<'_>, + timeout: Duration, +) -> Result { + let verifier = Arc::new( + AttestationVerifier::new_prod(None) + .context("initializing attestation verifier for KMS bootstrap")?, + ); + let prpc_url = format!("{}/prpc", kms_url.trim_end_matches('/')); + let peer_cert: Arc>>> = Arc::new(Mutex::new(None)); + let captured = peer_cert.clone(); + let ra_client = RaClientConfig::builder() + .remote_uri(prpc_url) + .tls_skip_ca_verification(true) + .tls_built_in_root_certs(false) + .attestation_verifier(verifier.clone()) + .cert_validator(Box::new(move |info| { + let info = info.context("missing KMS server certificate")?; + if info.attestation.is_none() { + bail!("KMS server certificate has no verified attestation"); + } + let Some(usage) = info.special_usage.as_deref() else { + bail!("KMS server certificate is missing special usage"); + }; + if usage != KMS_RPC_CERT_USAGE { + bail!("unexpected KMS server certificate usage: {usage}"); + } + *captured + .lock() + .map_err(|_| anyhow!("KMS certificate lock poisoned"))? = Some(info.cert_der); + Ok(()) + })) + .build() + .into_client() + .context("creating KMS RA-TLS client")?; + let client = KmsClient::new(ra_client); + + let deadline = tokio::time::Instant::now() + timeout; + let mut last_err: Option; + loop { + if let Ok(mut guard) = peer_cert.lock() { + *guard = None; + } + match client.get_meta().await { + Ok(meta) => { + let cert_der = peer_cert + .lock() + .map_err(|_| anyhow!("KMS certificate lock poisoned"))? + .take() + .context("missing KMS TLS peer certificate")?; + return verify_kms_bootstrap(&meta, Some(&cert_der), expected, &verifier).await; + } + Err(err) => { + last_err = Some(format!("{err:#}")); + if let Ok(status) = vmm.status().await { + if let Some(vm) = status.vms.iter().find(|vm| vm.id == vm_id) { + if matches!(vm.status.as_str(), "exited" | "stopped" | "removing") { + bail!( + "KMS CVM {vm_id} stopped ({}) before GetMeta became ready: {}", + vm.status, + last_err.as_deref().unwrap_or("unknown error") + ); + } + if !vm.boot_error.trim().is_empty() { + bail!( + "KMS CVM {vm_id} reported boot error: {}", + vm.boot_error.trim() + ); + } + } + } + } + } + if tokio::time::Instant::now() >= deadline { + bail!( + "KMS did not become ready for root-epoch registration within {}s (last error: {})", + timeout.as_secs(), + last_err.as_deref().unwrap_or("timeout") + ); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } +} + +/// Cryptographically verify a `KMS.GetMeta` response's `bootstrap_info` and +/// optional TLS peer certificate before registering `kmsContractAddr` and +/// `rootEpochs[0]`. +pub(crate) async fn verify_kms_bootstrap( + meta: &GetMetaResponse, + peer_cert_der: Option<&[u8]>, + expected: &ExpectedKms<'_>, + verifier: &AttestationVerifier, +) -> Result { + let bootstrap = meta.bootstrap_info.as_ref().context( + "KMS GetMeta returned no bootstrap_info attestation \ + (requires KMS 0.6+ with attested bootstrap)", + )?; + ensure!( + !bootstrap.ca_pubkey.is_empty(), + "KMS bootstrap_info has empty ca_pubkey" + ); + ensure!( + !bootstrap.k256_pubkey.is_empty(), + "KMS bootstrap_info has empty k256_pubkey" + ); + ensure!( + !bootstrap.attestation.is_empty(), + "KMS bootstrap_info has empty attestation" + ); + ensure!( + bootstrap.k256_pubkey == meta.k256_pubkey, + "KMS GetMeta k256_pubkey does not match bootstrap_info.k256_pubkey" + ); + + let (_, ca_spki) = SubjectPublicKeyInfo::from_der(&bootstrap.ca_pubkey) + .context("KMS bootstrap_info.ca_pubkey is not valid SubjectPublicKeyInfo DER")?; + + let root_pem = if meta.ca_cert.is_empty() { + None + } else { + let (_, pem) = x509_parser::pem::parse_x509_pem(meta.ca_cert.as_bytes()) + .context("invalid KMS root CA PEM in GetMeta")?; + Some(pem) + }; + let root_cert = match &root_pem { + None => None, + Some(pem) => { + let root = pem + .parse_x509() + .context("invalid KMS root CA certificate in GetMeta")?; + ensure!(root.is_ca(), "KMS GetMeta ca_cert is not a CA certificate"); + ensure!( + root.validity().is_valid(), + "KMS GetMeta ca_cert is expired or not yet valid" + ); + ensure!( + root.public_key().raw == bootstrap.ca_pubkey.as_slice(), + "KMS GetMeta ca_cert public key does not match bootstrap_info.ca_pubkey" + ); + Some(root) + } + }; + + if let Some(cert_der) = peer_cert_der { + let (_, leaf) = + X509Certificate::from_der(cert_der).context("invalid KMS TLS peer certificate")?; + ensure!( + !leaf.is_ca(), + "KMS TLS peer certificate must not be a CA certificate" + ); + ensure!( + leaf.validity().is_valid(), + "KMS TLS peer certificate is expired or not yet valid" + ); + ensure!( + leaf.get_special_usage() + .context("reading KMS TLS peer certificate usage")? + .as_deref() + == Some(KMS_RPC_CERT_USAGE), + "KMS TLS peer certificate does not have usage `{KMS_RPC_CERT_USAGE}`" + ); + if let Some(root) = &root_cert { + ensure!( + leaf.issuer() == root.subject(), + "KMS TLS peer certificate issuer does not match root CA subject" + ); + } + leaf.verify_signature(Some(&ca_spki)) + .context("KMS TLS peer certificate was not signed by bootstrap_info.ca_pubkey")?; + } + + let versioned = VersionedAttestation::from_bytes(&bootstrap.attestation) + .context("decoding KMS bootstrap attestation")?; + let verified = versioned + .into_v1() + .verify(verifier) + .await + .context("KMS bootstrap attestation verification failed")?; + + match expected.platform { + Platform::Tdx => ensure!( + matches!( + verified.report, + DstackVerifiedReport::DstackTdx(_) | DstackVerifiedReport::DstackGcpTdx { .. } + ), + "expected a TDX KMS bootstrap attestation, got {:?}", + verified.quote.variant() + ), + Platform::AmdSevSnp => ensure!( + matches!(verified.report, DstackVerifiedReport::DstackAmdSevSnp(_)), + "expected an AMD SEV-SNP KMS bootstrap attestation, got {:?}", + verified.quote.variant() + ), + } + + let expected_rd = generated_keys_report_data(&bootstrap.ca_pubkey, &bootstrap.k256_pubkey); + ensure!( + verified.report_data == expected_rd, + "KMS bootstrap attestation report_data does not match bootstrap_info public keys" + ); + + let app_info = verified + .decode_app_info(false) + .context("decoding KMS app info from bootstrap attestation")?; + ensure!( + app_info.app_id.len() == 20, + "attested KMS app_id must be 20 bytes, got {}", + app_info.app_id.len() + ); + ensure!( + app_info.compose_hash.len() == 32, + "attested KMS compose_hash must be 32 bytes, got {}", + app_info.compose_hash.len() + ); + + let kms_app_id = hex::encode(&app_info.app_id); + if let Some(expected_app_id) = expected.app_id { + ensure!( + norm_hex(&kms_app_id) == norm_hex(expected_app_id), + "attested KMS app_id 0x{kms_app_id} does not match expected 0x{}", + norm_hex(expected_app_id) + ); + } + + let attested_compose_hash = hex::encode(&app_info.compose_hash); + if let Some(expected_compose_hash) = expected.compose_hash { + ensure!( + norm_hex(&attested_compose_hash) == norm_hex(expected_compose_hash), + "attested KMS compose_hash 0x{attested_compose_hash} does not match expected 0x{}", + norm_hex(expected_compose_hash) + ); + } + + if let Some(expected_os_image) = expected.os_image_hash { + let verified_os_image = match &verified.report { + DstackVerifiedReport::DstackAmdSevSnp(report) => { + let binding = dstack_mr::sev::verify_sev_launch( + &report.measurement, + &report.host_data, + &verified.config, + ) + .context("verifying AMD SEV-SNP launch measurement for KMS")?; + hex::encode(&binding.os_image_hash) + } + _ => { + ensure!( + !app_info.os_image_hash.is_empty(), + "attested KMS bootstrap evidence does not carry os_image_hash" + ); + hex::encode(&app_info.os_image_hash) + } + }; + ensure!( + norm_hex(&verified_os_image) == norm_hex(expected_os_image), + "attested KMS os_image_hash 0x{verified_os_image} does not match pinned 0x{}", + norm_hex(expected_os_image) + ); + } + + Ok(VerifiedKmsBootstrap { + kms_app_id, + ca_pubkey: bootstrap.ca_pubkey.clone(), + k256_pubkey: bootstrap.k256_pubkey.clone(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use dstack_attest::attestation::{ + Attestation, AttestationQuote, AttestationVerifierConfig, CollateralUrls, RootCaPaths, + SnpQuote, + }; + use dstack_kms_rpc::BootstrapResponse; + use dstack_mr::sev::{ + compute_expected_measurement, sev_os_image_measurement_from_input, MeasurementInput, + OvmfSectionParam, SnpMeasurementDocument, + }; + use dstack_types::mr_config::MrConfigV3; + use dstack_types::KeyProviderKind; + use ra_tls::cert::CertRequest; + use ra_tls::rcgen::{KeyPair, PKCS_ECDSA_P256_SHA256}; + use sha2::Sha256; + + struct SnpFixture { + meta: GetMetaResponse, + peer_cert_der: Vec, + app_id: String, + compose_hash: String, + os_image_hash: String, + verifier: AttestationVerifier, + _server: tokio::task::JoinHandle<()>, + _dir: tempfile::TempDir, + } + + async fn build_snp_fixture() -> SnpFixture { + let dir = tempfile::tempdir().unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let base_url = format!("http://{addr}"); + let state = Arc::new( + mock_attestation::server::MockCollateralState::from_seed([0x42; 32], &base_url) + .unwrap(), + ); + let gen = state.sev_snp.clone(); + let root_path = dir.path().join("sev-snp-root.pem"); + std::fs::write(&root_path, gen.root_ca_pem()).unwrap(); + let server = tokio::spawn(async move { + let _ = mock_attestation::server::serve_listener(listener, state).await; + }); + let verifier = AttestationVerifier::load(&AttestationVerifierConfig { + insecure_allow_external_trust_anchors: true, + root_ca: RootCaPaths { + sev_snp_milan: Some(root_path), + ..Default::default() + }, + urls: CollateralUrls { + amd_kds: Some(format!("{base_url}/vcek/v1")), + ..Default::default() + }, + ..Default::default() + }) + .unwrap(); + + let ca_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap(); + let ca_cert = CertRequest::builder() + .org_name("Dstack") + .subject("Dstack KMS CA") + .ca_level(1) + .key(&ca_key) + .build() + .self_signed() + .unwrap(); + let rpc_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap(); + let rpc_cert = CertRequest::builder() + .subject("10.0.2.2") + .special_usage(KMS_RPC_CERT_USAGE) + .key(&rpc_key) + .build() + .signed_by(&ca_cert, &ca_key) + .unwrap(); + + let ca_pubkey = ca_key.public_key_der(); + let k256_pubkey = vec![0x02; 33]; + let compose_hash_bytes = [0xaa; 32]; + let app_id_bytes = [0xaa; 20]; + + let mr_config = MrConfigV3::new( + app_id_bytes.to_vec(), + compose_hash_bytes.to_vec(), + None, + KeyProviderKind::SevSnp, + Vec::new(), + vec![0x11; 20], + ); + let mr_config_doc = mr_config.to_canonical_json(); + let host_data = MrConfigV3::snp_host_data_from_document(&mr_config_doc); + + let rootfs_hash = "33".repeat(32); + let input = MeasurementInput { + base_cmdline: format!("console=ttyS0 dstack.rootfs_hash={rootfs_hash}"), + ovmf_hash: "44".repeat(48), + kernel_hash: "55".repeat(32), + initrd_hash: "66".repeat(32), + sev_hashes_table_gpa: 0x80_1000, + sev_es_reset_eip: 0xffff_fff0, + vcpus: 4, + vcpu_type: Some("epyc-v4".to_string()), + guest_features: 1, + ovmf_sections: vec![ + OvmfSectionParam { + gpa: 0x100000, + size: 0x2000, + section_type: 1, + }, + OvmfSectionParam { + gpa: 0x80_0000, + size: 0x1000, + section_type: 0x10, + }, + OvmfSectionParam { + gpa: 0x81_0000, + size: 0x1000, + section_type: 2, + }, + OvmfSectionParam { + gpa: 0x82_0000, + size: 0x1000, + section_type: 3, + }, + ], + }; + let image_cbor = sev_os_image_measurement_from_input(&input) + .unwrap() + .to_cbor_vec(); + let checksum_file = format!( + "{} {}\n", + hex::encode(Sha256::digest(&image_cbor)), + dstack_types::SNP_MEASUREMENT_FILENAME + ) + .into_bytes(); + let os_image_hash_bytes = dstack_types::image_hash_from_sha256sum(&checksum_file); + let measurement_doc = SnpMeasurementDocument { + checksum_file, + measurement: image_cbor, + vcpus: input.vcpus, + vcpu_type: input.vcpu_type.clone(), + guest_features: input.guest_features, + }; + let launch_measurement = compute_expected_measurement(&input).unwrap(); + let vm_config = serde_json::json!({ + "os_image_hash": hex::encode(os_image_hash_bytes), + "mr_config": mr_config_doc, + "sev_snp_measurement": serde_json::to_string(&measurement_doc).unwrap(), + }) + .to_string(); + + let report_data = generated_keys_report_data(&ca_pubkey, &k256_pubkey); + let evidence = gen + .attest_with_measurement(report_data, host_data, launch_measurement) + .unwrap(); + let attestation = Attestation { + quote: AttestationQuote::DstackAmdSevSnp(SnpQuote { + report: evidence.report, + cert_chain: evidence.cert_chain, + mr_config: mr_config_doc, + }), + runtime_events: vec![], + report_data, + config: vm_config, + report: (), + } + .into_versioned() + .to_bytes() + .unwrap(); + + let meta = GetMetaResponse { + ca_cert: ca_cert.pem(), + k256_pubkey: k256_pubkey.clone(), + bootstrap_info: Some(BootstrapResponse { + ca_pubkey, + k256_pubkey, + attestation, + }), + ..Default::default() + }; + + SnpFixture { + meta, + peer_cert_der: rpc_cert.der().to_vec(), + app_id: hex::encode(app_id_bytes), + compose_hash: hex::encode(compose_hash_bytes), + os_image_hash: hex::encode(os_image_hash_bytes), + verifier, + _server: server, + _dir: dir, + } + } + + #[tokio::test] + async fn verifies_attested_sev_snp_bootstrap_and_rejects_tampering() { + let fx = build_snp_fixture().await; + let expected = ExpectedKms { + platform: Platform::AmdSevSnp, + app_id: Some(&fx.app_id), + compose_hash: Some(&fx.compose_hash), + os_image_hash: Some(&fx.os_image_hash), + }; + let verified = + verify_kms_bootstrap(&fx.meta, Some(&fx.peer_cert_der), &expected, &fx.verifier) + .await + .expect("valid SNP bootstrap must verify"); + assert_eq!(verified.kms_app_id, fx.app_id); + assert_eq!( + verified.ca_pubkey, + fx.meta.bootstrap_info.as_ref().unwrap().ca_pubkey + ); + assert_eq!(verified.k256_pubkey, fx.meta.k256_pubkey); + + // Missing bootstrap_info is rejected. + let mut no_boot = fx.meta.clone(); + no_boot.bootstrap_info = None; + assert!( + verify_kms_bootstrap(&no_boot, Some(&fx.peer_cert_der), &expected, &fx.verifier) + .await + .is_err() + ); + + // Tampered k256_pubkey breaks report_data binding. + let mut tampered_key = fx.meta.clone(); + tampered_key.k256_pubkey[0] ^= 0x01; + tampered_key.bootstrap_info.as_mut().unwrap().k256_pubkey[0] ^= 0x01; + let err = verify_kms_bootstrap( + &tampered_key, + Some(&fx.peer_cert_der), + &expected, + &fx.verifier, + ) + .await + .unwrap_err() + .to_string(); + assert!(err.contains("report_data"), "unexpected error: {err}"); + + // Wrong expected app_id, compose_hash, os_image_hash, or platform are rejected. + let wrong_app = ExpectedKms { + app_id: Some(&"bb".repeat(20)), + ..expected.clone() + }; + assert!( + verify_kms_bootstrap(&fx.meta, Some(&fx.peer_cert_der), &wrong_app, &fx.verifier) + .await + .is_err() + ); + + let wrong_compose = ExpectedKms { + compose_hash: Some(&"cc".repeat(32)), + ..expected.clone() + }; + assert!(verify_kms_bootstrap( + &fx.meta, + Some(&fx.peer_cert_der), + &wrong_compose, + &fx.verifier + ) + .await + .is_err()); + + let wrong_os = ExpectedKms { + os_image_hash: Some(&"dd".repeat(32)), + ..expected.clone() + }; + assert!( + verify_kms_bootstrap(&fx.meta, Some(&fx.peer_cert_der), &wrong_os, &fx.verifier) + .await + .is_err() + ); + + let wrong_platform = ExpectedKms { + platform: Platform::Tdx, + ..expected.clone() + }; + assert!(verify_kms_bootstrap( + &fx.meta, + Some(&fx.peer_cert_der), + &wrong_platform, + &fx.verifier + ) + .await + .is_err()); + + // A peer TLS cert signed by a different CA is rejected. + let rogue_ca_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap(); + let rogue_ca = CertRequest::builder() + .org_name("Rogue") + .subject("Rogue CA") + .ca_level(1) + .key(&rogue_ca_key) + .build() + .self_signed() + .unwrap(); + let rogue_rpc_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap(); + let rogue_peer = CertRequest::builder() + .subject("10.0.2.2") + .special_usage(KMS_RPC_CERT_USAGE) + .key(&rogue_rpc_key) + .build() + .signed_by(&rogue_ca, &rogue_ca_key) + .unwrap(); + assert!( + verify_kms_bootstrap(&fx.meta, Some(rogue_peer.der()), &expected, &fx.verifier) + .await + .is_err() + ); + } +} diff --git a/dstack/crates/dstackup/src/main.rs b/dstack/crates/dstackup/src/main.rs index 9529231e5..f6b5123a1 100644 --- a/dstack/crates/dstackup/src/main.rs +++ b/dstack/crates/dstackup/src/main.rs @@ -16,6 +16,7 @@ mod cli; mod destroy; mod image; mod install; +mod kms_bootstrap; mod state; mod systemd;