diff --git a/CHANGELOG.md b/CHANGELOG.md index 77fbffeaf8..2798458e09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 CPU that supports it; an older QEMU exits at startup on the unknown `secure-tsc` property. Such a guest also needs a KMS and verifier of this release. Apps with `secure_time: false` launch as before. +- **RTMR3 of KMS apps changes.** Guests of this release add an `app-epoch` + runtime event, so the runtime RTMR3 (PCR14 on TPM platforms) of every app with + KMS keys differs from earlier images. Boot-time measurements are unchanged. +- **Certificates follow the measured app epoch.** `SignCert` signs under the + app epoch the CVM's attestation records, so after an app epoch rotation a + running CVM of this release keeps getting certificates from the old epoch, + under that epoch's policy row, until it restarts; once that row is revoked, + its certificate renewals are denied until then. Where nothing records it + (older guests, Nitro Enclave) the current epoch is used as before. +- **SEV-SNP apps with KMS keys: upgrade the KMS, gateways and verifiers + first.** SEV-SNP has no runtime register, so the VMM now binds the app epoch + in MrConfigV3 at every launch, asking the KMS for the current one when no pin + is set, and the guest refuses to boot without it. Older KMS, gateways and + verifiers reject such a document, so upgrade them before the VMM and the + guest images. The VMM binds the epoch only for images whose `metadata.json` + sets `app_epoch_pin`, so older images launch as before. A new SEV-SNP image + does not boot under an older VMM, and the VMM must reach the VM's KMS URLs at + every cold start and automatic restart. ### Added @@ -27,6 +45,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Secure TSC when `secure_time` is on, so the host cannot skew the guest clock. - `vmm-cli compose --init-script` sets `init_script` in the app compose file. +- **The app key epoch is measured.** A guest with KMS keys records its app + epoch in an `app-epoch` runtime event after `key-provider`, and certificates + from the KMS `SignCert` carry it in the `PHALA_RATLS_APP_EPOCH` extension. A + deployment can pin the app epoch with the MrConfigV3 field `app_epoch` + (`vmm-cli deploy --app-epoch` or the VMM web UI), and `GetSealedEnvPubKey` + takes an optional `app_epoch` to seal an env for such a VM. dstack-verifier + reports the measured epoch as `app_epoch`. Older guests refuse a document + with the field; on SEV-SNP, older KMS and verifiers do too. See + [Measurement](docs/app-key-epochs.md#measurement). - **`allowed_envs` entries can constrain values.** An entry may be `NAME: spec`, such as `PORT: int(1..=65535)` or `NETWORK: /mainnet|testnet/`, and the guest refuses to boot when a value does not match. `dstack-util validate-env` diff --git a/docs/app-key-epochs.md b/docs/app-key-epochs.md index 5cf3b052b0..6a2660300f 100644 --- a/docs/app-key-epochs.md +++ b/docs/app-key-epochs.md @@ -192,6 +192,66 @@ image or restoring a compatible header backup. App rotation isolates future app keys from an exposed old derived key, but cannot recover from compromise of the KMS root or revoke already disclosed secrets. +Certificates issued by `SignCert` carry the app epoch they were issued under in +the `PHALA_RATLS_APP_EPOCH` extension (OID `1.3.6.1.4.1.62397.1.10`, a DER +OCTET STRING holding a 4-byte big-endian integer), which +`CertExt::get_app_epoch` reads. The root epoch needs no extension: the issuing +root CA identifies it. There is no revocation list: +certificates issued before a rotation stay valid until they expire, and the +requester chooses their `not_after`. A verifier that reads the current app epoch +from the policy can reject a peer certificate from an older one. Certificates +without the extension come from a local CA or a KMS predating it, so a verifier +enforcing epochs must reject them as well. + +## Measurement + +A guest with KMS keys measures the app epoch it booted with in an `app-epoch` +runtime event, right after `key-provider`, as a 4-byte big-endian integer. The +root epoch is already identified by the KMS root key in `key-provider`. The +event extends RTMR3 on TDX and PCR14 on TPM platforms. SEV-SNP and Nitro Enclave +have no runtime register, so there the event is only logged and proves nothing. +`SignCert` signs under the app epoch the attestation records: the boot-time +`app-epoch` event where a register replays it, or the MrConfigV3 pin on +SEV-SNP. The requester cannot choose it, and the certificate's +`PHALA_RATLS_APP_EPOCH` matches the measurement. Where nothing records it, on +older guests and Nitro Enclave, `SignCert` uses the current app epoch. + +A deployment can pin the app epoch with the optional MrConfigV3 field +`app_epoch`, bound by TDX `MR_CONFIG_ID` or SEV-SNP `HOST_DATA`. The guest then +requests that app epoch instead of the current one and refuses to boot when the +KMS serves another. The pin requires the KMS key provider, and on TDX it requires +`use_mrconfigid`. Set it with `vmm-cli.py deploy --app-epoch N`, change it with +`update --app-epoch N`, and remove it with `update --no-app-epoch`; the VMM web +UI has an App Epoch field in its deploy and update dialogs. The VMM +refuses the pin for other key providers, for launches without MrConfigV3, +including `no_tee` and every simulator except SEV-SNP, and for images whose +`metadata.json` lacks `app_epoch_pin`. `ListImages` reports that flag, and +vmm-cli and the web UI offer the pin only for an image it marks, so a VMM +predating pins, which never sets the flag, is never sent a pin it would drop. + +SEV-SNP has no runtime register, so there the document always carries the app +epoch for KMS keys: without a pin, the VMM asks the KMS for the current app +epoch at every launch and binds it, so a restart still moves to a new epoch. A +guest of this release refuses to boot on SEV-SNP with KMS keys when the +document has no `app_epoch`, so it needs a VMM of this release, and that VMM +must reach the KMS URLs of the VM itself. Older KMS, gateways and verifiers +reject a document carrying `app_epoch`, so upgrade them before the VMM and the +guest images. + +The pin lets the host choose any app epoch whose policy row still allows the +instance, and the CVM then runs on that epoch's keys. Clear the rows of an epoch +whose keys may be exposed, and have relying parties check the `app-epoch` event +or, on SEV-SNP, the `app_epoch` in the document; dstack-verifier reports either +as `app_epoch`. + +Boot fails when the disk header records an app epoch newer than the pin, like +any other request for an older epoch. The env of a pinned VM must be sealed at +the pinned epoch, since the guest rejects one sealed at a newer epoch than its +own: vmm-cli and the VMM web UI pass the pin to `GetSealedEnvPubKey`, which then +returns the key of that app epoch. For the same reason, lowering the pin of a VM +below the epoch of its existing env makes its next boot fail until a new env is +sealed. + ## SDK selection Both selectors are optional; specify zero explicitly to recover an old key. diff --git a/docs/aws-attested-instance-security-evaluation.md b/docs/aws-attested-instance-security-evaluation.md index 42703390b4..a2f7981ed8 100644 --- a/docs/aws-attested-instance-security-evaluation.md +++ b/docs/aws-attested-instance-security-evaluation.md @@ -35,7 +35,7 @@ NitroTPM path meets them today. | P1 | Verifiable platform root of trust | TDX/SNP/Nitro quote verification against vendor root; debug rejected; TCB surfaced | NitroTPM Attestation Documents are verified against the AWS Nitro Attestation PKI, including document timestamp sanity. AWS exposes no TDX/SNP-style TCB advisory field, so a verified attestation is normalized to `tcbStatus = "UpToDate"` and passes the standard authorization gate unchanged. | | P2 | Reproducible or independently computable base image measurement | meta-dstack rebuild plus `dstack-mr` computes `MRTD`/`RTMR0-2` | The unified `os/build.sh` flow emits the AWS image archive with `sha256sum.txt`, `digest.txt`, and `measurement.aws.cbor`; its output directory also contains the reference-PCR side-car `aws-pcrs.json`. `os_image_hash = sha256(sha256sum.txt)` is the same identity used on all platforms; the verifier recomputes it from the downloaded image directory (`dstack/verifier/src/verification.rs`). The hardening audit script `os/yocto/tools/aws/audit-aws-ec2-image-hardening.sh` checks the image for operator mutation channels. | | P3 | Boot command line and root filesystem integrity are measured | `RTMR1/2`, rootfs hash, dm-verity, measured initrd/cmdline | The UKI commits kernel, initrd, and embedded cmdline into `PCR4`; the rootfs is dm-verity-protected. `VmConfig.aws_measurement` is required and must bind `boot_pcr_digest = sha256(PCR4||PCR7||PCR12)` to the attested PCRs, so `PCR12` (external cmdline) is always part of the bound digest — a missing-PCR12 bypass is not expressible. Enforced in guest quote generation (`dstack/dstack-attest/src/attestation.rs`), `verify_os_image_hash_for_aws_nitro_tpm` (`dstack/verifier/src/verification.rs`), and the KMS pipeline via the same verifier check. | -| P4 | Runtime application identity is cryptographically bound | RTMR3 `compose-hash`, `app-id`, `instance-id`, `key-provider`; event log replay | SHA384 `PCR14` event-log replay is the authoritative binding (RTMR3 analogue; non-resettable). Launch events: `system-preparing`, `app-id`, `compose-hash`, zero or more ordered `init-script-hash` events, `instance-id`, `boot-mr-done`, `key-provider`, `storage-fs`, `storage-encrypted`, `system-ready` (`dstack/dstack-util/src/system_setup.rs`). GPU launches also include `gpu-policy-hash` before `instance-id`, and `gpu-attestation` after `boot-mr-done` and before `key-provider`. `dstack-attest`, `dstack-verifier`, and KMS reject missing/mismatched PCR14 and bad replay. Optionally, the guest extends the raw `MrConfig` V2 `config_id` into `PCR8` once (`PCR8 = sha384(0^48 || config_id)`) so a lightweight third-party verifier can check compose hash + key provider without event-log replay; dstack's own verifier and KMS do not check PCR8. | +| P4 | Runtime application identity is cryptographically bound | RTMR3 `compose-hash`, `app-id`, `instance-id`, `key-provider`; event log replay | SHA384 `PCR14` event-log replay is the authoritative binding (RTMR3 analogue; non-resettable). Launch events: `system-preparing`, `app-id`, `compose-hash`, zero or more ordered `init-script-hash` events, `instance-id`, `boot-mr-done`, `key-provider`, `app-epoch` (KMS keys only), `storage-fs`, `storage-encrypted`, `system-ready` (`dstack/dstack-util/src/system_setup.rs`). GPU launches also include `gpu-policy-hash` before `instance-id`, and `gpu-attestation` after `boot-mr-done` and before `key-provider`. `dstack-attest`, `dstack-verifier`, and KMS reject missing/mismatched PCR14 and bad replay. Optionally, the guest extends the raw `MrConfig` V2 `config_id` into `PCR8` once (`PCR8 = sha384(0^48 || config_id)`) so a lightweight third-party verifier can check compose hash + key provider without event-log replay; dstack's own verifier and KMS do not check PCR8. | | P5 | Challenge/liveness and caller key binding | `report_data` challenge or RA-TLS public key hash in quote | RA-TLS binds `report_data` to the TLS certificate public key. KMS key release is bound to the live RA-TLS handshake; external `/verify` callers supply and check their own `report_data` challenge. The low-level NitroTPM document verifier also rejects stale or far-future document timestamps. | | P6 | Secret release only to attested code | dstack KMS verifies attestation, checks auth policy, derives per-app keys | dstack KMS verifies the NitroTPM attestation, runs the same `verify_os_image_hash_for_aws_nitro_tpm` binding check as the verifier, builds `BootInfo` from verified boot PCRs plus PCR14 launch events, and checks auth policy before deriving app keys (`dstack/kms/src/main_service.rs`). AWS NitroTPM key release is gated behind the opt-in `aws_nitro_tpm_key_release` flag (default false in `kms.toml`). | | P7 | Key-release policy is not controlled by the untrusted account admin | KMS runs inside TEE; policy from auth API/contracts; KMS identity measured | Satisfied with dstack KMS or another verifiable secret authority outside the untrusted AWS account admin's control. A NitroTPM-backed dstack KMS keeps root material out of account-admin snapshots and clones. The policy backend (on-chain `DstackKms`/`DstackApp` or an equivalent service; dstack-auth is for development, testing and evaluation only) must be outside the workload account admin's control. Same-account AWS KMS fails this property if the admin can change key policy, create grants, or call secret-bearing operations through a policy they control. | diff --git a/docs/kms-emergency-key-rotation-protocol.md b/docs/kms-emergency-key-rotation-protocol.md index 350af7558b..52aed05ded 100644 --- a/docs/kms-emergency-key-rotation-protocol.md +++ b/docs/kms-emergency-key-rotation-protocol.md @@ -255,9 +255,10 @@ signing trust, wallets, and permissions by reading old keys with an explicit `root_epoch` before releasing business services. The guest agent fetches an older epoch's app root from the KMS the first time GetKey names it and keeps it in memory; old roots are not stored in the keys file. The frozen v0 surface -always uses the current epoch. A per-app epoch, if added later, follows the same convention. SignCert -retains existing checks and signs under current roots; GetMeta is not a trust -anchor. Change CVM/gateway certificate trust in both directions. Public ACME +always uses the current epoch. The app epoch follows the same convention. SignCert +signs under the current root and the app epoch the CVM's attestation records, so a +running CVM keeps that app epoch's certificates, and needs its policy row, until it +restarts; GetMeta is not a trust anchor. Change CVM/gateway certificate trust in both directions. Public ACME certificates remain separate. Orchestration gates all business activity, including outbound workers, until readiness. diff --git a/docs/sealed-env.md b/docs/sealed-env.md index 6258d38a70..d82607b490 100644 --- a/docs/sealed-env.md +++ b/docs/sealed-env.md @@ -31,7 +31,18 @@ The guest still enforces the application's environment-name allowlist. ## Keys and signatures `GetSealedEnvPubKey` is available on KMS and proxied by VMM. Its request contains -`app_id` (20 bytes) only and always selects the current active epochs. Historical +`app_id` (20 bytes) and an optional `app_epoch`. It always selects the current +root epoch, and the current app epoch unless `app_epoch` asks for an older one, +which a VM pinned to that app epoch needs; a future app epoch is refused. The KMS +signs the key of an older app epoch with the prefix +`dstack-sealed-env-pubkey-historical-v1` instead of `dstack-sealed-env-pubkey-v1`, +so a verifier expecting the current key rejects it even when the request was +altered in transit. Accept that prefix only for an app epoch the user chose, +never one the host reports. vmm-cli does: it accepts the prefix only for the +`--app-epoch` typed on the command line and refuses to seal at a pin only the +VMM reports. The VMM web UI verifies no signature; it trusts the key the VMM +returns over its own origin, and its update dialog prefills the pin the VMM +reports. The SDK verifiers accept only the current-epoch prefix. Historical private keys for decryption and migration are obtained through `GetAppKey`, not through either environment public-key endpoint. The response contains `public_key`, `root_epoch`, `app_epoch`, `timestamp`, and `signature`. @@ -54,6 +65,9 @@ The public-key response signs Keccak256 of this unambiguous byte sequence: || app_epoch[4, big-endian] || public_key[32] || timestamp[8, big-endian] ``` +For an app epoch older than the current one, the prefix is +`"dstack-sealed-env-pubkey-historical-v1:"` and the rest is unchanged. + The signing key is the selected epoch's secp256k1 root. The signature is `r[32] || s[32] || recovery_id[1]`. Clients must compare the recovered signer against an independently trusted epoch root key or pin. Recovering a signer diff --git a/docs/tutorials/attestation-verification.md b/docs/tutorials/attestation-verification.md index 9f7c4cfd9e..23657267f3 100644 --- a/docs/tutorials/attestation-verification.md +++ b/docs/tutorials/attestation-verification.md @@ -314,6 +314,7 @@ In the output, look for the **X509v3 extensions** section. You'll see custom ext | `1.3.6.1.4.1.62397.1.2` | Event Log | Detailed event log for RTMR3 replay verification | | `1.3.6.1.4.1.62397.1.3` | App ID / Compose Hash | Application identity and configuration hash | | `1.3.6.1.4.1.62397.1.4` | Custom Claims | Optional application-defined claims | +| `1.3.6.1.4.1.62397.1.10` | App Epoch | App key epoch the KMS signed under, as an OCTET STRING holding a 4-byte big-endian integer | ### Verify the certificate chain @@ -491,6 +492,7 @@ These are the standard events you'll see in the log: | `os-image-hash` | Guest OS image hash | Should match `tcb_info.os_image_hash` | | `gpu-attestation` | Verified GPU state, aggregate `dbgstat`/`secboot`, and digest of the boot-time `nvattest` JSON | Required for an attested GPU launch; verify as described below | | `key-provider` | Key provider type | e.g., `kms` | +| `app-epoch` | KMS keys only: the app key epoch as a 4-byte big-endian integer | Should match the app epoch you expect | | `storage-fs` | Storage filesystem type | Storage configuration | | `storage-encrypted` | `1` when the data disk is LUKS-encrypted, `0` when it is not | `0` means the host can read the application's data at rest | | `system-ready` | System ready marker | Always present at end | diff --git a/docs/vmm-cli-user-guide.md b/docs/vmm-cli-user-guide.md index 7a5ac8e3cf..c73a3fd439 100644 --- a/docs/vmm-cli-user-guide.md +++ b/docs/vmm-cli-user-guide.md @@ -296,6 +296,7 @@ Deploy your application with the compose file: - `--gateway-url`: Gateway server URL - `--stopped`: Create VM in stopped state (requires dstack-vmm >= 0.5.4) - `--launch-ticket-file`: File holding the launch ticket the guest presents to the KMS (see below) +- `--app-epoch`: Pin the app key epoch the guest requests from the KMS; `update --app-epoch N` changes the pin and `update --no-app-epoch` removes it (see [app key epochs](app-key-epochs.md#measurement)) #### Launch Tickets diff --git a/dstack/cert-client/src/lib.rs b/dstack/cert-client/src/lib.rs index d41a5e76ab..2f719d7f87 100644 --- a/dstack/cert-client/src/lib.rs +++ b/dstack/cert-client/src/lib.rs @@ -180,7 +180,7 @@ impl CertRequestClient { CertRequestClient::Local { ca } => { let app_info = local_ca_app_info(&csr.attestation); let cert = ca - .sign_csr(csr, app_info.as_ref(), "app:custom") + .sign_csr(csr, app_info.as_ref(), None, "app:custom") .context("Failed to sign certificate")?; Ok(vec![cert.pem(), ca.pem_cert.clone()]) } @@ -506,7 +506,7 @@ mod tests { let mut csr = csr_with(undecodable_attestation(), key.public_key_der()); csr.config.subject_alt_names = vec![domain.to_string()]; let leaf = app_ca - .sign_csr(&csr, Some(&app_info_for(app_id)), "app:custom") + .sign_csr(&csr, Some(&app_info_for(app_id)), None, "app:custom") .expect("sign csr"); ( format!("{}\n{}\n{}", leaf.pem(), app_ca.pem_cert, root.pem_cert), diff --git a/dstack/dstack-attest/src/attestation.rs b/dstack/dstack-attest/src/attestation.rs index 912644ccf4..8060ef7c64 100644 --- a/dstack/dstack-attest/src/attestation.rs +++ b/dstack/dstack-attest/src/attestation.rs @@ -2172,6 +2172,36 @@ impl Attestation { } impl Attestation { + /// The app key epoch the launch measurement binds, if any. + /// + /// It is the boot-time `app-epoch` event where a register replays the runtime + /// events, and the MrConfigV3 pin on SEV-SNP, whose `HOST_DATA` binds the + /// document. Nitro Enclave binds neither. + pub fn decode_app_epoch(&self) -> Result> { + match &self.quote { + AttestationQuote::DstackAmdSevSnp(q) => Ok(MrConfigV3::from_document(&q.mr_config) + .context("invalid amd sev-snp mr_config")? + .app_epoch), + AttestationQuote::DstackNitroEnclave(_) => Ok(None), + AttestationQuote::DstackTdx(_) + | AttestationQuote::DstackGcpTdx(_) + | AttestationQuote::DstackAwsNitroTpm(_) => { + match find_event_payloads(&self.runtime_events, "app-epoch").as_slice() { + [] => Ok(None), + [payload] => { + let epoch = payload + .as_slice() + .try_into() + .ok() + .context("app-epoch event must be a 4-byte big-endian integer")?; + Ok(Some(u32::from_be_bytes(epoch))) + } + _ => bail!("multiple app-epoch events"), + } + } + } + } + /// Decode the quote pub fn decode_tdx_quote(&self) -> Result { let Some(tdx_quote) = self.tdx_quote() else { @@ -2918,6 +2948,80 @@ mod tests { } } + #[test] + fn app_epoch_comes_from_the_boot_time_event() { + let with_events = |events: Vec| Attestation { + runtime_events: events, + ..dummy_tdx_attestation([0; 64]) + }; + let epoch = |epoch: u32| v1_event("app-epoch".into(), epoch.to_be_bytes().to_vec()); + let ready = || v1_event("system-ready".into(), Vec::new()); + + assert_eq!(with_events(vec![]).decode_app_epoch().unwrap(), None); + assert_eq!( + with_events(vec![epoch(3), ready()]) + .decode_app_epoch() + .unwrap(), + Some(3) + ); + // Events after system-ready are the application's own. + assert_eq!( + with_events(vec![ready(), epoch(3)]) + .decode_app_epoch() + .unwrap(), + None + ); + assert_eq!( + with_events(vec![epoch(3), ready(), epoch(1)]) + .decode_app_epoch() + .unwrap(), + Some(3) + ); + assert!(with_events(vec![epoch(3), epoch(1)]) + .decode_app_epoch() + .is_err()); + assert!(with_events(vec![v1_event("app-epoch".into(), vec![1])]) + .decode_app_epoch() + .is_err()); + } + + #[test] + fn app_epoch_without_a_runtime_register() { + let with_quote = |quote| Attestation { + quote, + // A runtime event never stands in for the bound document. + runtime_events: vec![v1_event("app-epoch".into(), 3u32.to_be_bytes().to_vec())], + ..dummy_tdx_attestation([0; 64]) + }; + let snp = |mr_config: String| { + with_quote(AttestationQuote::DstackAmdSevSnp(SnpQuote { + report: Vec::new(), + cert_chain: Vec::new(), + mr_config, + })) + }; + let document = |app_epoch| { + MrConfigV3::new( + vec![0x11; 20], + vec![0x22; 32], + None, + dstack_types::KeyProviderKind::Kms, + vec![0x33; 33], + vec![0x44; 20], + ) + .with_app_epoch(app_epoch) + .to_canonical_json() + }; + + assert_eq!(snp(document(Some(1))).decode_app_epoch().unwrap(), Some(1)); + assert_eq!(snp(document(None)).decode_app_epoch().unwrap(), None); + assert!(snp("{}".into()).decode_app_epoch().is_err()); + let nitro = with_quote(AttestationQuote::DstackNitroEnclave(DstackNitroQuote { + nsm_quote: Vec::new(), + })); + assert_eq!(nitro.decode_app_epoch().unwrap(), None); + } + fn tdx_event(imr: u32, event_type: u32, event_payload: &[u8]) -> TdxEvent { TdxEvent { imr, diff --git a/dstack/dstack-types/src/mr_config.rs b/dstack/dstack-types/src/mr_config.rs index d1cb4f347d..2a2238838e 100644 --- a/dstack/dstack-types/src/mr_config.rs +++ b/dstack/dstack-types/src/mr_config.rs @@ -129,6 +129,10 @@ pub struct MrConfigV3 { /// field disables this check; an empty list requires no init scripts. #[serde(default, with = "crate::init_script_hashes::option")] pub init_script_hashes: Option>>, + /// Optional app key epoch pin. The guest requests the keys of this app + /// epoch from the KMS instead of the current one. + #[serde(default)] + pub app_epoch: Option, } impl MrConfigV3 { @@ -149,6 +153,7 @@ impl MrConfigV3 { key_provider_id: (!key_provider_id.is_empty()).then_some(key_provider_id), instance_id: (!instance_id.is_empty()).then_some(instance_id), init_script_hashes: None, + app_epoch: None, } } @@ -157,6 +162,11 @@ impl MrConfigV3 { self } + pub fn with_app_epoch(mut self, app_epoch: Option) -> Self { + self.app_epoch = app_epoch; + self + } + pub fn to_snp_host_data(&self) -> [u8; 32] { Self::snp_host_data_from_document(&self.to_canonical_json()) } @@ -314,6 +324,26 @@ mod tests { Ok(()) } + #[test] + fn mr_config_v3_binds_app_epoch() -> Result<(), Box> { + let config = MrConfigV3::new( + vec![0x11; 20], + vec![0x22; 32], + None, + KeyProviderKind::Kms, + vec![0x33; 32], + vec![0x44; 20], + ); + assert!(!config.to_canonical_json().contains("app_epoch")); + let pinned = config.clone().with_app_epoch(Some(0)); + let document = pinned.to_canonical_json(); + + assert!(document.contains(r#""app_epoch":0"#)); + assert_eq!(MrConfigV3::from_document(&document)?, pinned); + assert_ne!(config.to_snp_host_data(), pinned.to_snp_host_data()); + Ok(()) + } + #[test] fn mr_config_v3_generates_jcs_but_hashes_document_bytes() -> Result<(), Box> { let config = MrConfigV3::new( diff --git a/dstack/dstack-util/src/system_setup.rs b/dstack/dstack-util/src/system_setup.rs index 37bd2234a3..cb622e4038 100644 --- a/dstack/dstack-util/src/system_setup.rs +++ b/dstack/dstack-util/src/system_setup.rs @@ -2616,12 +2616,20 @@ impl<'a> Stage0<'a> { if self.shared.sys_config.kms_urls.is_empty() { bail!("No KMS URLs are set"); } + // verify_app checks the served keys against this pin. + let app_epoch = config_id_verifier::bound_mr_config_v3() + .context("failed to read the app epoch pin")? + .and_then(|mr_config| mr_config.app_epoch); + // Refuse before any key is released; verify_app enforces it again. + if app_epoch.is_none() && detect_tee_variant()? == TeeVariant::DstackAmdSevSnp { + bail!("amd sev-snp mr_config must pin app_epoch for the KMS key provider; upgrade the VMM"); + } let mut errors = vec![]; for kms_url in &self.shared.sys_config.kms_urls { let kms_url = kms_rpc_url(kms_url); match self .shared - .request_app_keys_from_kms(kms_url.clone(), None, None, None) + .request_app_keys_from_kms(kms_url.clone(), None, app_epoch, None) .await { Ok((keys, os_image_hash)) => { @@ -3322,32 +3330,43 @@ impl<'a> Stage0<'a> { app_info: &AppInfo, provider: KeyProviderKind, provider_id: &[u8], + app_epoch: Option, ) -> Result<()> { - config_id_verifier::verify_mr_config_id( - &app_info.compose_hash, - &app_info.gpu_policy_hash, - &app_info.init_script_hashes, - &app_info + config_id_verifier::verify_mr_config_id(config_id_verifier::LocalMrConfigValues { + compose_hash: &app_info.compose_hash, + gpu_policy_hash: &app_info.gpu_policy_hash, + init_script_hashes: &app_info.init_script_hashes, + app_id: &app_info .instance_info .app_id .as_slice() .try_into() .ok() .context("Invalid app id")?, - &app_info.instance_info.instance_id, - provider, - provider_id, - )?; + instance_id: &app_info.instance_info.instance_id, + key_provider: provider, + key_provider_id: provider_id, + app_epoch, + })?; self.verify_key_provider_id(provider_id) } fn verify_app(&self, app_info: &AppInfo, keys: &AppKeys) -> Result<()> { - self.verify_app_config(app_info, keys.key_provider.kind(), keys.key_provider.id())?; + let app_epoch = kms_app_epoch(keys); + self.verify_app_config( + app_info, + keys.key_provider.kind(), + keys.key_provider.id(), + app_epoch, + )?; let kp_info = KeyProviderInfo::new( keys.key_provider.kind().measurement_name().into(), hex::encode(keys.key_provider.id()), ); emit_key_provider_info(&kp_info)?; + if let Some(app_epoch) = app_epoch { + emit_runtime_event("app-epoch", &app_epoch.to_be_bytes())?; + } Ok(()) } @@ -3692,6 +3711,13 @@ fn kms_root_epoch(keys: &AppKeys) -> Option { } } +fn kms_app_epoch(keys: &AppKeys) -> Option { + match keys.key_provider { + KeyProvider::Kms { app_epoch, .. } => Some(app_epoch), + _ => None, + } +} + #[cfg(test)] fn test_app_compose(manifest_version: serde_json::Value, platforms: Option<&[&str]>) -> AppCompose { let mut value = serde_json::json!({ diff --git a/dstack/dstack-util/src/system_setup/config_id_verifier.rs b/dstack/dstack-util/src/system_setup/config_id_verifier.rs index 075b58dd45..0085ed1754 100644 --- a/dstack/dstack-util/src/system_setup/config_id_verifier.rs +++ b/dstack/dstack-util/src/system_setup/config_id_verifier.rs @@ -12,14 +12,15 @@ use dstack_types::{ use tracing::info; #[derive(Clone, Copy)] -struct LocalMrConfigValues<'a> { - compose_hash: &'a [u8; 32], - gpu_policy_hash: &'a [u8; 32], - init_script_hashes: &'a [Vec], - app_id: &'a [u8; 20], - instance_id: &'a [u8], - key_provider: KeyProviderKind, - key_provider_id: &'a [u8], +pub struct LocalMrConfigValues<'a> { + pub compose_hash: &'a [u8; 32], + pub gpu_policy_hash: &'a [u8; 32], + pub init_script_hashes: &'a [Vec], + pub app_id: &'a [u8; 20], + pub instance_id: &'a [u8], + pub key_provider: KeyProviderKind, + pub key_provider_id: &'a [u8], + pub app_epoch: Option, } // TDREPORT_STRUCT.TDINFO (offset 512): ATTRIBUTES, XFAM, MRTD, then MRCONFIGID. @@ -65,28 +66,31 @@ fn read_snp_host_data() -> Result<[u8; 32]> { /// - app_id: [u8; 20] /// - key_provider_type: u8 // 0: none, 1: local, 2: kms, 3: tpm /// - key_provider_id: [u8] // KMS CA pubkey, local-sgx MR, or empty for none/tpm -pub fn verify_mr_config_id( - compose_hash: &[u8; 32], - gpu_policy_hash: &[u8; 32], - init_script_hashes: &[Vec], - app_id: &[u8; 20], - instance_id: &[u8], - key_provider: KeyProviderKind, - key_provider_id: &[u8], -) -> Result<()> { +pub fn verify_mr_config_id(local: LocalMrConfigValues<'_>) -> Result<()> { let mode = detect_tee_variant().context("Failed to detect attestation mode")?; - let local = LocalMrConfigValues { - compose_hash, - gpu_policy_hash, - init_script_hashes, - app_id, - instance_id, - key_provider, - key_provider_id, - }; verify_mr_config_id_for_mode(mode, local) } +/// The host-supplied MrConfigV3 document, when the launch measurement binds it. +pub fn bound_mr_config_v3() -> Result> { + let document = match detect_tee_variant().context("Failed to detect attestation mode")? { + TeeVariant::DstackAmdSevSnp => Some(read_snp_mr_config()?), + TeeVariant::DstackAwsNitroTpm | TeeVariant::DstackNitroEnclave => None, + _ => { + let (mr_config_id, document) = read_tdx_mr_config()?; + if let Some(document) = &document { + if MrConfigV3::tdx_mr_config_id_from_document(document) != mr_config_id { + bail!("Invalid mr_config_id"); + } + } + document + } + }; + document + .map(|document| MrConfigV3::from_document(&document).context("Invalid mr_config document")) + .transpose() +} + fn verify_mr_config_id_for_mode(mode: TeeVariant, local: LocalMrConfigValues<'_>) -> Result<()> { match mode { TeeVariant::DstackAmdSevSnp => verify_snp_mr_config(local), @@ -101,15 +105,21 @@ fn verify_mr_config_id_for_mode(mode: TeeVariant, local: LocalMrConfigValues<'_> } } -fn verify_tdx_mr_config_id(local: LocalMrConfigValues<'_>) -> Result<()> { - let read_mr_config_id = read_mr_config_id().context("Failed to read mr_config_id")?; - info!("mr_config_id: {}", hex::encode(read_mr_config_id)); - let mr_config_document = if read_mr_config_id[0] == 3 { +/// TDX MR_CONFIG_ID, and the MrConfigV3 document it names, if any. +fn read_tdx_mr_config() -> Result<([u8; 48], Option)> { + let mr_config_id = read_mr_config_id().context("Failed to read mr_config_id")?; + info!("mr_config_id: {}", hex::encode(mr_config_id)); + let mr_config_document = if mr_config_id[0] == 3 { Some(read_mr_config_document().context("Failed to read mr_config")?) } else { None }; - verify_tdx_mr_config_id_value(read_mr_config_id, mr_config_document.as_deref(), local) + Ok((mr_config_id, mr_config_document)) +} + +fn verify_tdx_mr_config_id(local: LocalMrConfigValues<'_>) -> Result<()> { + let (mr_config_id, mr_config_document) = read_tdx_mr_config()?; + verify_tdx_mr_config_id_value(mr_config_id, mr_config_document.as_deref(), local) } fn verify_tdx_mr_config_id_value( @@ -146,14 +156,24 @@ fn verify_tdx_mr_config_id_value( Ok(()) } -fn verify_snp_mr_config(local: LocalMrConfigValues<'_>) -> Result<()> { +/// The SNP MrConfigV3 document, checked against HOST_DATA. +fn read_snp_mr_config() -> Result { let mr_config_document = read_mr_config_document().context("Failed to read SNP mr_config")?; - verify_mr_config_v3_document(&mr_config_document, local)?; let read_host_data = read_snp_host_data().context("Failed to read SNP HOST_DATA")?; info!("snp host_data: {}", hex::encode(read_host_data)); if MrConfigV3::snp_host_data_from_document(&mr_config_document) != read_host_data { bail!("Invalid SNP HOST_DATA"); } + Ok(mr_config_document) +} + +fn verify_snp_mr_config(local: LocalMrConfigValues<'_>) -> Result<()> { + let mr_config = verify_mr_config_v3_document(&read_snp_mr_config()?, local)?; + // SEV-SNP has no runtime register, so the document is the only place that + // can record which app epoch the KMS served. + if local.key_provider == KeyProviderKind::Kms && mr_config.app_epoch.is_none() { + bail!("amd sev-snp mr_config must pin app_epoch for the KMS key provider"); + } Ok(()) } @@ -197,6 +217,9 @@ fn verify_mr_config_v3_document( bail!("Invalid mr_config key_provider_id"); } } + if mr_config.app_epoch.is_some() && mr_config.app_epoch != local.app_epoch { + bail!("Invalid mr_config app_epoch"); + } Ok(mr_config) } @@ -237,6 +260,7 @@ mod tests { instance_id: &instance_id, key_provider: KeyProviderKind::Kms, key_provider_id: &key_provider_id, + app_epoch: None, }; verify_tdx_mr_config_id_value(mr_config.to_tdx_mr_config_id(), Some(&document), local) @@ -267,6 +291,7 @@ mod tests { instance_id: &instance_id, key_provider: KeyProviderKind::Kms, key_provider_id: &key_provider_id, + app_epoch: None, }; match verify_mr_config_v3_document(&document, local) { @@ -299,6 +324,7 @@ mod tests { instance_id: &instance_id, key_provider: KeyProviderKind::Kms, key_provider_id: &key_provider_id, + app_epoch: None, }; verify_mr_config_v3_document(&document, local)?; @@ -326,6 +352,7 @@ mod tests { instance_id, key_provider: KeyProviderKind::Kms, key_provider_id: &[], + app_epoch: None, }; assert!(verify_mr_config_v3_document(&document, local(&[0x44u8; 20])).is_err()); @@ -357,6 +384,7 @@ mod tests { instance_id: &instance_id, key_provider: KeyProviderKind::Kms, key_provider_id: &key_provider_id, + app_epoch: None, }; match verify_mr_config_v3_document(&document, local) { @@ -391,6 +419,7 @@ mod tests { instance_id: &instance_id, key_provider: KeyProviderKind::Kms, key_provider_id: &key_provider_id, + app_epoch: None, }; verify_tdx_mr_config_id_value(mr_config.to_tdx_mr_config_id(), Some(&document), local) @@ -422,6 +451,7 @@ mod tests { instance_id: &instance_id, key_provider: KeyProviderKind::None, key_provider_id: &[], + app_epoch: None, }; assert!(verify_mr_config_v3_document(&document, local) @@ -457,6 +487,7 @@ mod tests { instance_id: &instance_id, key_provider: KeyProviderKind::None, key_provider_id: &[], + app_epoch: None, }; verify_mr_config_v3_document(&document.to_string(), local_without_scripts).unwrap(); @@ -469,6 +500,40 @@ mod tests { verify_mr_config_v3_document(&document.to_string(), local_with_script).unwrap(); } + #[test] + fn mr_config_v3_document_must_match_pinned_app_epoch() { + let compose_hash = [0x22u8; 32]; + let app_id = [0x11u8; 20]; + let document = MrConfigV3::new( + app_id.to_vec(), + compose_hash.to_vec(), + None, + KeyProviderKind::Kms, + Vec::new(), + Vec::new(), + ) + .with_app_epoch(Some(2)) + .to_canonical_json(); + let local = |app_epoch| LocalMrConfigValues { + compose_hash: &compose_hash, + gpu_policy_hash: &[0x55u8; 32], + init_script_hashes: &[], + app_id: &app_id, + instance_id: &[], + key_provider: KeyProviderKind::Kms, + key_provider_id: &[], + app_epoch, + }; + + assert!(verify_mr_config_v3_document(&document, local(Some(2))).is_ok()); + for app_epoch in [Some(1), None] { + assert!(verify_mr_config_v3_document(&document, local(app_epoch)) + .unwrap_err() + .to_string() + .contains("Invalid mr_config app_epoch")); + } + } + #[test] fn nitro_enclave_does_not_require_tdx_mr_config() -> Result<()> { let compose_hash = [0u8; 32]; @@ -483,6 +548,7 @@ mod tests { instance_id: &instance_id, key_provider: KeyProviderKind::None, key_provider_id: &[], + app_epoch: None, }; verify_mr_config_id_for_mode(TeeVariant::DstackNitroEnclave, local) diff --git a/dstack/dstack-util/src/system_setup/snp.rs b/dstack/dstack-util/src/system_setup/snp.rs index 27c561dac1..d5c81487b0 100644 --- a/dstack/dstack-util/src/system_setup/snp.rs +++ b/dstack/dstack-util/src/system_setup/snp.rs @@ -41,7 +41,7 @@ impl Stage0<'_> { } // HOST_DATA is host-supplied. The measured OS must validate its binding // to the actual app/config before deriving or using a sealing seed. - self.verify_app_config(app_info, KeyProviderKind::SevSnp, &[])?; + self.verify_app_config(app_info, KeyProviderKind::SevSnp, &[], None)?; let disk_initialized = self.sealed_disk_initialized(KeyProviderKind::SevSnp)?; let parameters = parameters_for_boot( app_info.instance_info.snp_sealing, diff --git a/dstack/dstack-util/src/system_setup/tdx_seal.rs b/dstack/dstack-util/src/system_setup/tdx_seal.rs index 83a652d54c..5f5de95e83 100644 --- a/dstack/dstack-util/src/system_setup/tdx_seal.rs +++ b/dstack/dstack-util/src/system_setup/tdx_seal.rs @@ -47,7 +47,7 @@ impl Stage0<'_> { if detect_tee_variant()? != TeeVariant::DstackTdx { bail!("the tdx-seal key provider requires a dstack TDX guest"); } - self.verify_app_config(app_info, KeyProviderKind::TdxSeal, &[])?; + self.verify_app_config(app_info, KeyProviderKind::TdxSeal, &[], None)?; let disk_initialized = self.sealed_disk_initialized(KeyProviderKind::TdxSeal)?; let parameters = parameters_for_boot( app_info.instance_info.tdx_sealing, diff --git a/dstack/kms/rpc/proto/kms_rpc.proto b/dstack/kms/rpc/proto/kms_rpc.proto index 886d352a52..e4b4a25559 100644 --- a/dstack/kms/rpc/proto/kms_rpc.proto +++ b/dstack/kms/rpc/proto/kms_rpc.proto @@ -24,6 +24,12 @@ message AppId { bytes app_id = 1; } +message SealedEnvPubKeyRequest { + bytes app_id = 1; + // App epoch of the key, at most the current one; unset means the current one. + optional uint32 app_epoch = 2; +} + message SealedEnvPubKeyResponse { bytes public_key = 1; uint32 root_epoch = 2; @@ -140,7 +146,7 @@ service KMS { rpc GetKmsKey(GetKmsKeyRequest) returns (KmsKeyResponse); // Request the app environment encryption public key given the app id rpc GetAppEnvEncryptPubKey(AppId) returns (PublicKeyResponse); - rpc GetSealedEnvPubKey(AppId) returns (SealedEnvPubKeyResponse); + rpc GetSealedEnvPubKey(SealedEnvPubKeyRequest) returns (SealedEnvPubKeyResponse); // Request the KMS instance metadata for use as a probe and health check. rpc GetMeta(google.protobuf.Empty) returns (GetMetaResponse); // Compatibility for existing OS images and tokenless legacy onboarding. @@ -155,7 +161,7 @@ service KMS { service ReadOnly { rpc GetMeta(google.protobuf.Empty) returns (GetMetaResponse); rpc GetAppEnvEncryptPubKey(AppId) returns (PublicKeyResponse); - rpc GetSealedEnvPubKey(AppId) returns (SealedEnvPubKeyResponse); + rpc GetSealedEnvPubKey(SealedEnvPubKeyRequest) returns (SealedEnvPubKeyResponse); } // The KMS admin RPC service. Served on a separate admin listener diff --git a/dstack/kms/src/main_service.rs b/dstack/kms/src/main_service.rs index 8295d20d8b..9e5634a9e7 100644 --- a/dstack/kms/src/main_service.rs +++ b/dstack/kms/src/main_service.rs @@ -14,8 +14,8 @@ use anyhow::{anyhow, bail, Context, Result}; use dstack_kms_rpc::{ kms_server::{KmsRpc, KmsServer}, AppId, AppKeyResponse, BootstrapResponse, GetAppKeyRequest, GetKmsKeyRequest, GetMetaResponse, - GetTempCaCertResponse, KmsKeyResponse, KmsKeys, PublicKeyResponse, SealedEnvPubKeyResponse, - SignCertRequest, SignCertResponse, + GetTempCaCertResponse, KmsKeyResponse, KmsKeys, PublicKeyResponse, SealedEnvPubKeyRequest, + SealedEnvPubKeyResponse, SignCertRequest, SignCertResponse, }; use dstack_verifier::{CvmVerifier, VerificationDetails}; use fs_err as fs; @@ -595,6 +595,71 @@ impl RpcHandler { self.state.self_allowed.contains_key(&operation) } + /// Sign `csr` for the CVM `attestation` was verified to describe. + async fn sign_attested_csr( + &self, + csr: &CertSigningRequestV2, + attestation: &VerifiedAttestation, + request: &SignCertRequest, + cached: bool, + ) -> Result { + let auth_api = &self.state.config.auth_api; + let boot_info = auth_api + .boot_info(attestation, true, &request.vm_config) + .await?; + let result = async { + // The epoch the CVM booted with, as its measurement records it, so the + // requester cannot choose; the current one where nothing records it. + let measured_app_epoch = attestation.decode_app_epoch()?; + let app_info = self + .ensure_app_attestation_allowed( + attestation, + boot_info.clone(), + &request.vm_config, + &request.launch_ticket, + Operation::AppGetCert, + RequestedAppEpochs { + root: None, + app: measured_app_epoch, + }, + ) + .await?; + ensure_key_release_allowed(&app_info.boot_info, (&self.state.config).into())?; + let root = self.state.epoch_root(app_info.root_epoch)?; + let app_ca = + self.derive_app_ca(&app_info.boot_info.app_id, root, app_info.app_epoch)?; + // Stamp the identity verified above, not the requester's own claims. + // Runtime measurements (`false`) are what certificates have always carried. + let cert_app_info = attestation + .decode_app_info_ex(false, &request.vm_config) + .context("Failed to decode the verified app info")?; + let cert = app_ca + .sign_csr( + csr, + Some(&cert_app_info), + Some(app_info.app_epoch), + "app:custom", + ) + .context("Failed to sign certificate")?; + self.audit_key_release( + KeyRelease::AppCert, + &app_info.boot_info, + &format!("root current app {}", epoch_label(measured_app_epoch)), + &format!("root {} app {}", app_info.root_epoch, app_info.app_epoch), + cached, + ); + Ok(SignCertResponse { + certificate_chain: vec![ + cert.pem(), + app_ca.pem_cert.clone(), + root.ca.pem_cert.clone(), + ], + }) + } + .await; + self.audit_denial(KeyRelease::AppCert, &boot_info, result) + } + pub(crate) async fn handover_keys( self, release: KeyRelease, @@ -634,6 +699,11 @@ impl RpcHandler { } } +/// An epoch selector for the audit log. +fn epoch_label(epoch: Option) -> String { + epoch.map_or("current".into(), |epoch| epoch.to_string()) +} + #[derive(Default)] struct RequestedAppEpochs { root: Option, @@ -926,14 +996,13 @@ impl KmsRpc for RpcHandler { ensure_key_release_allowed(&boot_info, (&self.state.config).into())?; let root = self.state.epoch_root(root_epoch)?; let keys = derive_app_keys(root, &boot_info.app_id, &boot_info.instance_id, app_epoch)?; - let epoch = |epoch: Option| epoch.map_or("current".into(), |e| e.to_string()); self.audit_key_release( KeyRelease::AppKey, &boot_info, &format!( "root {} app {}", - epoch(request.root_epoch), - epoch(request.app_epoch) + epoch_label(request.root_epoch), + epoch_label(request.app_epoch) ), &format!("root {root_epoch} app {app_epoch}"), cached, @@ -1012,12 +1081,19 @@ impl KmsRpc for RpcHandler { result } - async fn get_sealed_env_pub_key(self, request: AppId) -> Result { + async fn get_sealed_env_pub_key( + self, + request: SealedEnvPubKeyRequest, + ) -> Result { ensure_app_id_len(&request.app_id)?; let result = async { let epoch = self.ensure_self_allowed(Operation::KmsServe).await?; let root = self.state.epoch_root(epoch)?; - let app_epoch = self.state.app_epoch(&request.app_id).await?; + let current = self.state.app_epoch(&request.app_id).await?; + let app_epoch = request.app_epoch.unwrap_or(current); + if app_epoch > current { + bail!("app epoch {app_epoch} is beyond the current app epoch {current}"); + } let secret = derive_sealed_env_key(root, &request.app_id, app_epoch)?; let public_key = x25519_dalek::PublicKey::from(&x25519_dalek::StaticSecret::from(secret)).to_bytes(); @@ -1030,12 +1106,14 @@ impl KmsRpc for RpcHandler { message.extend_from_slice(&app_epoch.to_be_bytes()); message.extend_from_slice(&public_key); message.extend_from_slice(×tamp.to_be_bytes()); - let signature = sign_message( - &root.k256, - b"dstack-sealed-env-pubkey-v1", - &request.app_id, - &message, - )?; + // An older epoch's key may be retired. A distinct tag keeps verifiers + // that expect the current key from accepting it. + let prefix: &[u8] = if app_epoch == current { + b"dstack-sealed-env-pubkey-v1" + } else { + b"dstack-sealed-env-pubkey-historical-v1" + }; + let signature = sign_message(&root.k256, prefix, &request.app_id, &message)?; Ok(SealedEnvPubKeyResponse { public_key: public_key.to_vec(), root_epoch: epoch, @@ -1136,50 +1214,8 @@ impl KmsRpc for RpcHandler { .verify_with_ra_pubkey(&csr.pubkey, &self.state.attestation_verifier) .await .context("Quote verification failed")?; - let auth_api = &self.state.config.auth_api; - let boot_info = auth_api - .boot_info(&attestation, true, &request.vm_config) - .await?; - let result = async { - let app_info = self - .ensure_app_attestation_allowed( - &attestation, - boot_info.clone(), - &request.vm_config, - &request.launch_ticket, - Operation::AppGetCert, - RequestedAppEpochs::default(), - ) - .await?; - ensure_key_release_allowed(&app_info.boot_info, (&self.state.config).into())?; - let root = self.state.epoch_root(app_info.root_epoch)?; - let app_ca = - self.derive_app_ca(&app_info.boot_info.app_id, root, app_info.app_epoch)?; - // Stamp the identity verified above, not the requester's own claims. - // Runtime measurements (`false`) are what certificates have always carried. - let cert_app_info = attestation - .decode_app_info_ex(false, &request.vm_config) - .context("Failed to decode the verified app info")?; - let cert = app_ca - .sign_csr(&csr, Some(&cert_app_info), "app:custom") - .context("Failed to sign certificate")?; - self.audit_key_release( - KeyRelease::AppCert, - &app_info.boot_info, - "current", - &format!("root {} app {}", app_info.root_epoch, app_info.app_epoch), - cached, - ); - Ok(SignCertResponse { - certificate_chain: vec![ - cert.pem(), - app_ca.pem_cert.clone(), - root.ca.pem_cert.clone(), - ], - }) - } - .await; - self.audit_denial(KeyRelease::AppCert, &boot_info, result) + self.sign_attested_csr(&csr, &attestation, &request, cached) + .await } } @@ -2553,12 +2589,9 @@ mod tests { Vec<(String, serde_json::Value)>, KmsState, ) { - use ra_tls::{ - attestation::{ - Attestation, AttestationQuote, AttestationVerifierConfig, DstackNitroQuote, - QuoteContentType, RootCaPaths, - }, - cert::{CertConfigV2, Csr}, + use ra_tls::attestation::{ + Attestation, AttestationQuote, AttestationVerifierConfig, DstackNitroQuote, + QuoteContentType, RootCaPaths, }; let dir = tempfile::tempdir().unwrap(); let attester = mock_attestation::nsm::NsmGenerator::new().unwrap(); @@ -2595,9 +2628,54 @@ mod tests { report: (), } .into_versioned(); + let vm_config = + serde_json::json!({ "os_image_hash": hex::encode(os_image_hash) }).to_string(); + let (_, request) = cert_request(&key, attestation, vm_config); + let result = RpcHandler { + state: state.clone(), + attestation: None, + remote_endpoint: None, + } + .sign_cert(request) + .await; + (result, auth_requests(server), state) + } + + #[rocket::async_test] + async fn sign_cert_issues_from_the_current_epochs_after_rotation() { + let (result, requests, state) = rotated_sign_cert(&[true, true]).await; + let chain = result.unwrap().certificate_chain; + let root = state.epoch_root(1).unwrap(); + assert_eq!(chain[2], root.ca.pem_cert); + let app_ca_key = kdf::derive_p256_key_pair( + &root.ca.key, + &[&[0x22; 20][..], b"app-ca", &app_epoch_context(1)], + ) + .unwrap(); + assert_eq!(pem_public_key(&chain[1]), app_ca_key.public_key_der()); + assert_eq!(leaf_app_epoch(&chain[0]), Some(1)); + + let [(_, self_check), (route, check)] = &requests[..] else { + panic!("unexpected auth API requests: {requests:?}"); + }; + assert_eq!(self_check["operation"], "kms_serve"); + assert_eq!(route, "/authorizeApp"); + assert_eq!(check["operation"], "app_get_cert"); + assert!(check.get("requestedRootEpoch").is_none()); + assert!(check.get("requestedAppEpoch").is_none()); + let metrics = state.metrics().render_prometheus(); + assert!(released(&metrics, "app_get_cert", 1), "{metrics}"); + } + + fn cert_request( + key: &KeyPair, + attestation: ra_tls::attestation::VersionedAttestation, + vm_config: String, + ) -> (CertSigningRequestV2, SignCertRequest) { + use ra_tls::cert::{CertConfigV2, Csr}; let csr = CertSigningRequestV2 { confirm: "please sign cert:".into(), - pubkey, + pubkey: key.public_key_der(), config: CertConfigV2 { org_name: None, subject: "app.test".into(), @@ -2613,45 +2691,107 @@ mod tests { }; let request = SignCertRequest { api_version: 2, - signature: csr.signed_by(&key).unwrap(), + signature: csr.signed_by(key).unwrap(), csr: csr.to_vec(), - vm_config: serde_json::json!({ "os_image_hash": hex::encode(os_image_hash) }) - .to_string(), + vm_config, ..Default::default() }; - let result = RpcHandler { + (csr, request) + } + + /// Sign a certificate for a verified SNP caller whose MrConfigV3 binds + /// `app_epoch`, while the auth API reports root and app epoch 1 as current. + async fn snp_sign_cert( + allowed: bool, + app_epoch: Option, + ) -> ( + Result, + Vec<(String, serde_json::Value)>, + KmsState, + ) { + let dir = tempfile::tempdir().unwrap(); + let (state, server) = rotated_kms(dir.path(), &[allowed], |config| { + config.sev_snp_key_release = true + }) + .await; + let input = valid_snp_measurement_input(); + let mr_config = valid_snp_mr_config().with_app_epoch(app_epoch); + let vm_config = snp_vm_config(&input, &mr_config); + let measurement = compute_expected_measurement(&input).unwrap(); + let mut attestation = verified_snp_attestation_with_config( + measurement, + [0xab; 64], + vm_config.clone(), + &mr_config, + ); + // The certificate carries app info decoded from the raw report. + let ra_tls::attestation::AttestationQuote::DstackAmdSevSnp(quote) = &mut attestation.quote + else { + unreachable!(); + }; + quote.report = mock_attestation::sev_snp::SevSnpGenerator::new() + .unwrap() + .attest_with_measurement( + attestation.report_data, + mr_config.to_snp_host_data(), + measurement, + ) + .unwrap() + .report; + let unverified = ra_tls::attestation::Attestation { + quote: attestation.quote.clone(), + runtime_events: vec![], + report_data: attestation.report_data, + config: attestation.config.clone(), + report: (), + } + .into_versioned(); + let key = KeyPair::generate_for(&ra_tls::rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let (csr, request) = cert_request(&key, unverified, vm_config); + let handler = RpcHandler { state: state.clone(), attestation: None, remote_endpoint: None, - } - .sign_cert(request) - .await; + }; + let result = handler + .sign_attested_csr(&csr, &attestation, &request, false) + .await; (result, auth_requests(server), state) } #[rocket::async_test] - async fn sign_cert_issues_from_the_current_epochs_after_rotation() { - let (result, requests, state) = rotated_sign_cert(&[true, true]).await; + async fn sign_cert_issues_from_the_measured_app_epoch() { + let (result, requests, state) = snp_sign_cert(true, Some(0)).await; let chain = result.unwrap().certificate_chain; - let root = state.epoch_root(1).unwrap(); - assert_eq!(chain[2], root.ca.pem_cert); let app_ca_key = kdf::derive_p256_key_pair( - &root.ca.key, - &[&[0x22; 20][..], b"app-ca", &app_epoch_context(1)], + &state.epoch_root(1).unwrap().ca.key, + &[&[0x11; 20][..], b"app-ca", &app_epoch_context(0)], ) .unwrap(); assert_eq!(pem_public_key(&chain[1]), app_ca_key.public_key_der()); - - let [(_, self_check), (route, check)] = &requests[..] else { + assert_eq!(leaf_app_epoch(&chain[0]), Some(0)); + let [(route, check)] = &requests[..] else { panic!("unexpected auth API requests: {requests:?}"); }; - assert_eq!(self_check["operation"], "kms_serve"); assert_eq!(route, "/authorizeApp"); - assert_eq!(check["operation"], "app_get_cert"); - assert!(check.get("requestedRootEpoch").is_none()); - assert!(check.get("requestedAppEpoch").is_none()); - let metrics = state.metrics().render_prometheus(); - assert!(released(&metrics, "app_get_cert", 1), "{metrics}"); + assert_eq!(check["requestedAppEpoch"], 0); + + // The backend denies a measured epoch whose policy row was revoked. + let (result, requests, _) = snp_sign_cert(false, Some(0)).await; + let err = format!("{:#}", result.unwrap_err()); + assert!(err.contains("Authorization denied"), "{err}"); + assert_eq!(requests[0].1["requestedAppEpoch"], 0); + + // A measured epoch beyond the current one is refused. + let (result, _, _) = snp_sign_cert(true, Some(2)).await; + let err = format!("{:#}", result.unwrap_err()); + assert!(err.contains("requested app epoch is not active"), "{err}"); + } + + fn leaf_app_epoch(pem: &str) -> Option { + use ra_tls::traits::CertExt; + let (_, pem) = x509_parser::pem::parse_x509_pem(pem.as_bytes()).unwrap(); + pem.parse_x509().unwrap().get_app_epoch().unwrap() } #[rocket::async_test] @@ -2680,13 +2820,20 @@ mod tests { attestation: None, remote_endpoint: None, }; - let request = AppId { - app_id: vec![0x11; 20], - }; + let app_id = vec![0x11; 20]; let result = if sealed { - handler.get_sealed_env_pub_key(request).await.map(drop) + handler + .get_sealed_env_pub_key(SealedEnvPubKeyRequest { + app_id, + app_epoch: None, + }) + .await + .map(drop) } else { - handler.get_app_env_encrypt_pub_key(request).await.map(drop) + handler + .get_app_env_encrypt_pub_key(AppId { app_id }) + .await + .map(drop) }; let requests = auth_requests(server); assert_eq!(requests[1].0, format!("/app/0x{}", "11".repeat(20))); @@ -2731,8 +2878,9 @@ mod tests { attestation: None, remote_endpoint: None, } - .get_sealed_env_pub_key(AppId { + .get_sealed_env_pub_key(SealedEnvPubKeyRequest { app_id: app_id.to_vec(), + app_epoch: None, }) .await .unwrap(); @@ -2762,6 +2910,55 @@ mod tests { assert_eq!(response.signature, signature); } + #[rocket::async_test] + async fn sealed_env_pub_key_at_an_older_app_epoch() { + let request = |app_epoch| async move { + let (url, server) = + upgrade_authority::tests::serve(vec![AUTH_API_INFO, r#"{"currentAppEpoch":1}"#]); + let dir = tempfile::tempdir().unwrap(); + let state = kms_state(dir.path(), &url); + let result = RpcHandler { + state: state.clone(), + attestation: None, + remote_endpoint: None, + } + .get_sealed_env_pub_key(SealedEnvPubKeyRequest { + app_id: vec![0x11; 20], + app_epoch, + }) + .await; + auth_requests(server); + (result, state) + }; + let (response, state) = request(Some(0)).await; + let response = response.unwrap(); + assert_eq!(response.app_epoch, 0); + let root = state.epoch_root(0).unwrap(); + let secret = derive_sealed_env_key(root, &[0x11; 20], 0).unwrap(); + let public_key = + x25519_dalek::PublicKey::from(&x25519_dalek::StaticSecret::from(secret)).to_bytes(); + assert_eq!(response.public_key, public_key); + let message = [ + &0u32.to_be_bytes()[..], + &0u32.to_be_bytes(), + &public_key, + &response.timestamp.to_be_bytes(), + ] + .concat(); + let signature = |prefix: &[u8]| sign_message(&root.k256, prefix, &[0x11; 20], &message); + assert_eq!( + response.signature, + signature(b"dstack-sealed-env-pubkey-historical-v1").unwrap() + ); + assert_ne!( + response.signature, + signature(b"dstack-sealed-env-pubkey-v1").unwrap() + ); + + let err = request(Some(2)).await.0.unwrap_err(); + assert!(format!("{err:#}").contains("beyond the current"), "{err:#}"); + } + #[rocket::async_test] async fn legacy_temp_ca_rpc_returns_a_separate_ca_and_the_served_root() { assert!(dstack_kms_rpc::kms_server::KMSMethod::from_str("GetTempCaCert").is_some()); diff --git a/dstack/kms/src/readonly_service.rs b/dstack/kms/src/readonly_service.rs index 8c6a8ad71f..5b8bcb7547 100644 --- a/dstack/kms/src/readonly_service.rs +++ b/dstack/kms/src/readonly_service.rs @@ -8,7 +8,7 @@ use anyhow::Result; use dstack_kms_rpc::{ kms_server::KmsRpc, read_only_server::{ReadOnlyRpc, ReadOnlyServer}, - AppId, GetMetaResponse, PublicKeyResponse, SealedEnvPubKeyResponse, + AppId, GetMetaResponse, PublicKeyResponse, SealedEnvPubKeyRequest, SealedEnvPubKeyResponse, }; use ra_rpc::{CallContext, RpcCall}; @@ -25,7 +25,10 @@ impl ReadOnlyRpc for ReadOnlyRpcHandler { self.0.get_app_env_encrypt_pub_key(request).await } - async fn get_sealed_env_pub_key(self, request: AppId) -> Result { + async fn get_sealed_env_pub_key( + self, + request: SealedEnvPubKeyRequest, + ) -> Result { self.0.get_sealed_env_pub_key(request).await } } diff --git a/dstack/ra-tls/src/cert.rs b/dstack/ra-tls/src/cert.rs index 5c748cad5e..64925dfb46 100644 --- a/dstack/ra-tls/src/cert.rs +++ b/dstack/ra-tls/src/cert.rs @@ -24,7 +24,8 @@ use x509_parser::public_key::PublicKey; use x509_parser::x509::SubjectPublicKeyInfo; use crate::oids::{ - PHALA_RATLS_APP_ID, PHALA_RATLS_APP_INFO, PHALA_RATLS_ATTESTATION, PHALA_RATLS_CERT_USAGE, + PHALA_RATLS_APP_EPOCH, PHALA_RATLS_APP_ID, PHALA_RATLS_APP_INFO, PHALA_RATLS_ATTESTATION, + PHALA_RATLS_CERT_USAGE, }; use crate::traits::CertExt; #[cfg(feature = "quote")] @@ -94,6 +95,7 @@ impl CaCert { &self, csr: &CertSigningRequestV2, app_info: Option<&AppInfo>, + app_epoch: Option, usage: &str, ) -> Result { let pki = rcgen::SubjectPublicKeyInfo::from_der(&csr.pubkey) @@ -118,6 +120,7 @@ impl CaCert { .maybe_attestation(attestation) .maybe_app_id(app_id) .maybe_app_info(ext_app_info) + .maybe_app_epoch(app_epoch) .special_usage(usage) .maybe_not_before( cfg.not_before @@ -362,6 +365,7 @@ pub struct CertRequest<'a, Key> { ca_level: Option, app_id: Option<&'a [u8]>, app_info: Option<&'a AppInfo>, + app_epoch: Option, special_usage: Option<&'a str>, attestation: Option<&'a VersionedAttestation>, not_before: Option, @@ -405,6 +409,9 @@ impl CertRequest<'_, Key> { rmp_serde::to_vec_named(&app_info).context("failed to serialize app info")?; add_ext(&mut params, PHALA_RATLS_APP_INFO, app_info_bytes); } + if let Some(app_epoch) = self.app_epoch { + add_ext(&mut params, PHALA_RATLS_APP_EPOCH, app_epoch.to_be_bytes()); + } if let Some(usage) = self.special_usage { add_ext(&mut params, PHALA_RATLS_CERT_USAGE, usage); } @@ -797,7 +804,7 @@ mod tests { .into_versioned(), }; - let error = match ca.sign_csr(&csr, None, "app:custom") { + let error = match ca.sign_csr(&csr, None, None, "app:custom") { Ok(_) => panic!("an unrepresentable not_after must be rejected"), Err(error) => error, }; @@ -1004,6 +1011,20 @@ mod tests { assert_eq!(decoded.key_provider_info, app_info.key_provider_info); assert_eq!(decoded.init_script_hashes, app_info.init_script_hashes); } + + #[test] + fn app_epoch_survives_a_certificate_round_trip() { + let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap(); + let cert = CertRequest::builder() + .key(&key) + .subject("test.example.com") + .app_epoch(7) + .build() + .self_signed() + .unwrap(); + + assert_eq!(cert.get_app_epoch().unwrap(), Some(7)); + } } #[test] @@ -1043,7 +1064,7 @@ mod tests { } .into_versioned(), }; - let Err(err) = CaCert::from_parts(ca_key, ca_cert).sign_csr(&csr, None, "app:custom") + let Err(err) = CaCert::from_parts(ca_key, ca_cert).sign_csr(&csr, None, None, "app:custom") else { panic!("app info must not be invented"); }; diff --git a/dstack/ra-tls/src/oids.rs b/dstack/ra-tls/src/oids.rs index 3535ac1fb1..20237a3471 100644 --- a/dstack/ra-tls/src/oids.rs +++ b/dstack/ra-tls/src/oids.rs @@ -16,3 +16,5 @@ pub const PHALA_RATLS_CERT_USAGE: &[u64] = &[1, 3, 6, 1, 4, 1, 62397, 1, 4]; pub const PHALA_RATLS_ATTESTATION: &[u64] = &[1, 3, 6, 1, 4, 1, 62397, 1, 8]; /// OID for app info pub const PHALA_RATLS_APP_INFO: &[u64] = &[1, 3, 6, 1, 4, 1, 62397, 1, 9]; +/// OID for the app key epoch a certificate was issued under +pub const PHALA_RATLS_APP_EPOCH: &[u64] = &[1, 3, 6, 1, 4, 1, 62397, 1, 10]; diff --git a/dstack/ra-tls/src/traits.rs b/dstack/ra-tls/src/traits.rs index 0916039c1c..d9cd757d50 100644 --- a/dstack/ra-tls/src/traits.rs +++ b/dstack/ra-tls/src/traits.rs @@ -7,7 +7,9 @@ use anyhow::{Context, Result}; use dstack_attest::attestation::AppInfo; -use crate::oids::{PHALA_RATLS_APP_ID, PHALA_RATLS_APP_INFO, PHALA_RATLS_CERT_USAGE}; +use crate::oids::{ + PHALA_RATLS_APP_EPOCH, PHALA_RATLS_APP_ID, PHALA_RATLS_APP_INFO, PHALA_RATLS_CERT_USAGE, +}; /// Types that can get custom cert extensions from. pub trait CertExt { @@ -47,4 +49,17 @@ pub trait CertExt { .context("failed to decode app info as msgpack")?; Ok(app_info) } + + /// Get the app key epoch the certificate was issued under. `None` means it was + /// issued without one, by a local CA or a KMS predating this extension. + fn get_app_epoch(&self) -> Result> { + let Some(bytes) = self.get_extension_bytes(PHALA_RATLS_APP_EPOCH)? else { + return Ok(None); + }; + let bytes = bytes + .try_into() + .ok() + .context("app epoch must be a 4-byte big-endian integer")?; + Ok(Some(u32::from_be_bytes(bytes))) + } } diff --git a/dstack/verifier/README.md b/dstack/verifier/README.md index ef5b0393d7..d90ca853a3 100644 --- a/dstack/verifier/README.md +++ b/dstack/verifier/README.md @@ -45,6 +45,7 @@ against the returned evidence. "tcb_status": "UpToDate", // surfaced, not gated: is_valid ignores it "advisory_ids": [], "key_provider": { "name": "kms", "id": "hex-string" }, // decoded; null if absent + "app_epoch": 0, // measured app key epoch; null where nothing records it "app_info": { "app_id": "hex-string", "compose_hash": "hex-string", @@ -164,6 +165,10 @@ that: perform — use `/verify` for that path. Only trust `os_image_hash` when `os_image_hash_verified` is `true`. +Both `/verify` and this mode report `app_epoch`, the app key epoch the +measurement binds, or `null` where nothing records it (older guests, Nitro +Enclave, keys not provided by a KMS). + Clients, gateways, or release validators should combine this certificate-level check with the policy fields emitted by `/verify`: accepted OS image, `teeVariant`, `mrAggregated`, app compose hash, KMS identity, a diff --git a/dstack/verifier/src/main.rs b/dstack/verifier/src/main.rs index 3ab62b2c09..25cd71277d 100644 --- a/dstack/verifier/src/main.rs +++ b/dstack/verifier/src/main.rs @@ -228,7 +228,9 @@ async fn run_cert_oneshot(file_path: &str, config: &Config) -> anyhow::Result<() .await .map_err(|e| anyhow::anyhow!("failed to verify RA-TLS certificate: {:#}", e))?; - let app_info = verified.decode_app_info(false); + let app_info = verified + .decode_app_info(false) + .and_then(|info| Ok((info, verified.attestation.decode_app_epoch()?))); // Bind the reported os_image_hash to the attested boot measurement. For // every platform except TDX legacy this is a self-contained check (no image // download); relying parties should only trust `os_image_hash` when @@ -272,7 +274,7 @@ fn cert_oneshot_result( tee_variant: ra_tls::attestation::TeeVariant, report_data: &[u8], public_key_der: &[u8], - app_info: Result, + app_info: Result<(ra_tls::attestation::AppInfo, Option)>, os_image_hash_verified: bool, ) -> serde_json::Value { let reason = app_info @@ -286,7 +288,8 @@ fn cert_oneshot_result( "tee_variant": tee_variant, "report_data": hex::encode(report_data), "public_key_der": hex::encode(public_key_der), - "app_info": app_info.ok().map(|info| serde_json::json!({ + "app_epoch": app_info.as_ref().ok().and_then(|(_, app_epoch)| *app_epoch), + "app_info": app_info.ok().map(|(info, _)| serde_json::json!({ "app_id": hex::encode(info.app_id), "compose_hash": hex::encode(info.compose_hash), "instance_id": hex::encode(info.instance_id), @@ -564,10 +567,11 @@ mod cert_oneshot_result_tests { TeeVariant::DstackTdx, &[0u8; 64], b"spki", - Ok(app_info()), + Ok((app_info(), Some(2))), true, ); assert_eq!(valid["is_valid"], serde_json::json!(true)); + assert_eq!(valid["details"]["app_epoch"], serde_json::json!(2)); assert_eq!(valid["reason"], serde_json::Value::Null); assert_eq!( valid["details"]["app_info"]["compose_hash"], diff --git a/dstack/verifier/src/types.rs b/dstack/verifier/src/types.rs index 75c55076aa..49b048ae34 100644 --- a/dstack/verifier/src/types.rs +++ b/dstack/verifier/src/types.rs @@ -122,6 +122,11 @@ pub struct VerificationDetails { pub advisory_ids: Vec, /// decoded app_info.key_provider_info; name is e.g. "kms" or "local". pub key_provider: Option, + /// App key epoch the measurement binds: the boot-time `app-epoch` event on + /// dstack TDX, GCP TDX and AWS NitroTPM, the MrConfigV3 `app_epoch` on + /// SEV-SNP. None where nothing records it, such as older guests, Nitro + /// Enclave or keys not provided by a KMS. + pub app_epoch: Option, pub app_info: Option, /// Canonical auth-policy input matching the KMS bootAuth payload. #[serde(skip_serializing_if = "Option::is_none")] diff --git a/dstack/verifier/src/verification.rs b/dstack/verifier/src/verification.rs index 27ba8dcfed..6e2a745f45 100644 --- a/dstack/verifier/src/verification.rs +++ b/dstack/verifier/src/verification.rs @@ -684,8 +684,11 @@ impl CvmVerifier { } }; details.os_image_hash_verified = true; - match verified_attestation.decode_app_info_ex(false, &request_vm_config) { - Ok(mut info) => { + let app_info = verified_attestation + .decode_app_info_ex(false, &request_vm_config) + .and_then(|info| Ok((info, verified_attestation.decode_app_epoch()?))); + match app_info { + Ok((mut info, app_epoch)) => { info.os_image_hash = vm_config.os_image_hash; details.boot_info = Some(policy_boot_info_from_verified_app_info( &verified_attestation, @@ -693,6 +696,7 @@ impl CvmVerifier { )); details.event_log_verified = true; details.key_provider = decode_key_provider_info(&info.key_provider_info); + details.app_epoch = app_epoch; details.app_info = Some(info); } Err(e) => { diff --git a/dstack/vmm/rpc/proto/vmm_rpc.proto b/dstack/vmm/rpc/proto/vmm_rpc.proto index 2c8924176f..678d722c42 100644 --- a/dstack/vmm/rpc/proto/vmm_rpc.proto +++ b/dstack/vmm/rpc/proto/vmm_rpc.proto @@ -158,6 +158,10 @@ message VmConfiguration { // contract must allow (see dstack/kms/README.md#launch-tickets). The VMM // passes it to the guest's sys-config and never returns it. string launch_ticket = 25; + // Pin the app key epoch the guest requests from the KMS. Bound into + // MrConfigV3 and only valid with the KMS key provider. Unset uses the + // app's current epoch. + optional uint32 app_epoch = 26; } // Per-VM networking configuration. @@ -255,6 +259,10 @@ message UpdateVmRequest { map annotations = 22; // Optional update launch ticket; an empty one removes it. optional string launch_ticket = 25; + // Optional update app epoch pin. With update_app_epoch set, an unset + // app_epoch removes the pin. + bool update_app_epoch = 26; + optional uint32 app_epoch = 27; } // Parameters for listing CVMs with pagination and filtering. @@ -297,6 +305,8 @@ message ImageInfo { bool is_dev = 4; // Whether this guest supports SealedEnv; absent means legacy encryption only. bool sealed_env = 5; + // Whether this guest honors an app epoch pin. + bool app_epoch_pin = 6; } // App identifier used for encrypting env vars and routing telemetry. @@ -304,6 +314,12 @@ message AppId { bytes app_id = 1; } +message SealedEnvPubKeyRequest { + bytes app_id = 1; + // App epoch of the key, at most the current one; unset means the current one. + optional uint32 app_epoch = 2; +} + // Response with the KMS-backed public key used for env encryption plus audit signature. message SealedEnvPubKeyResponse { bytes public_key = 1; @@ -446,7 +462,7 @@ service Vmm { // Get Env encrypt public key rpc GetAppEnvEncryptPubKey(AppId) returns (PublicKeyResponse); - rpc GetSealedEnvPubKey(AppId) returns (SealedEnvPubKeyResponse); + rpc GetSealedEnvPubKey(SealedEnvPubKeyRequest) returns (SealedEnvPubKeyResponse); // Get VM info by ID rpc GetInfo(Id) returns (GetInfoResponse); diff --git a/dstack/vmm/src/app.rs b/dstack/vmm/src/app.rs index 3e3dd0046e..a85f25136a 100644 --- a/dstack/vmm/src/app.rs +++ b/dstack/vmm/src/app.rs @@ -43,6 +43,7 @@ use supervisor_client::SupervisorClient; use tracing::{debug, error, info, warn}; pub use image::{Image, ImageInfo}; +pub(crate) use mr_config::{launch_app_epoch, validate_app_epoch_pin}; pub(crate) use network::{ filters_bridge_traffic, mode_carries_ingress, needs_netd_interface, resolve_networking, resolved_networks, settle_vhost, stranded_ingress, validate_resolved_network, @@ -151,6 +152,9 @@ pub struct Manifest { /// Written to the guest's sys-config, never returned by the RPCs. #[serde(default, skip_serializing_if = "Option::is_none")] pub launch_ticket: Option, + /// App key epoch pinned in MrConfigV3; see `VmConfiguration.app_epoch`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub app_epoch: Option, } impl Manifest { @@ -548,16 +552,20 @@ impl App { } is_running = false; } - self.sync_dynamic_config(id)?; - self.set_started(id, true)?; - // Adopting a running guest leaves its boot's window as it is: open only - // while a boot this VMM launched has not reached application code, and - // closed for a guest it did not launch, which may already run it. + // Launch inputs are written for a launch only. A running guest copied + // its own at boot and never reads these again, so rewriting them from + // a manifest edited since would only make the host's copy disagree + // with the measured one. Adopting it also leaves its boot's env window + // as it is: open only while a boot this VMM launched has not reached + // application code, and closed for a guest it did not launch. let env_update = if is_running { None } else { + let app_epoch = self.launch_app_epoch(id).await?; + self.sync_dynamic_config(id, app_epoch)?; Some(self.sha256_of_env(id)?) }; + self.set_started(id, true)?; let vm_config = { let mut state = self.lock(); let vm_state = state.get_mut(id).context("VM not found")?; @@ -1772,7 +1780,19 @@ impl App { Ok(work_dir) } - pub(crate) fn sync_dynamic_config(&self, id: &str) -> Result<()> { + async fn launch_app_epoch(&self, id: &str) -> Result> { + let work_dir = self.work_dir(id)?; + let manifest = work_dir.manifest().context("Failed to read manifest")?; + let app_compose = work_dir + .app_compose() + .context("Failed to get app compose")?; + let image_dir = self.config.image.image_dir(&manifest.image)?; + let image = Image::load(&image_dir) + .with_context(|| format!("failed to load image {:?}", manifest.image))?; + launch_app_epoch(&manifest, &self.config, &app_compose, &image.info).await + } + + pub(crate) fn sync_dynamic_config(&self, id: &str, app_epoch: Option) -> Result<()> { let work_dir = self.work_dir(id)?; let shared_dir = self.shared_dir(id)?; let manifest = work_dir.manifest().context("Failed to read manifest")?; @@ -1782,7 +1802,7 @@ impl App { .app_compose() .context("Failed to get app compose")?; let mr_config = work_dir - .prepare_mr_config(&manifest, &cfg.cvm, &app_compose) + .prepare_mr_config(&manifest, &cfg.cvm, &app_compose, app_epoch) .context("Failed to prepare mr_config")?; let sys_config_str = make_sys_config( cfg, @@ -2471,7 +2491,7 @@ pub(crate) fn needs_swtpm( #[cfg(test)] mod tests { - use super::mr_config::{mr_config_version, MrConfigVersion}; + use super::mr_config::{mr_config_version, MrConfigVersion, MR_CONFIG_V3_REQUIRED}; use super::*; fn test_app() -> App { @@ -4104,9 +4124,50 @@ mod tests { disk_prealloc: DiskPrealloc::Off, annotations: Default::default(), launch_ticket: None, + app_epoch: None, } } + #[rocket::async_test] + async fn launch_app_epoch_pins_sev_snp_kms_launches() -> Result<()> { + let mut config: Config = Figment::from(load_config_figment(None)).extract()?; + config.cvm.platform = Some(CvmPlatform::AmdSevSnp); + config.cvm.kms_urls = vec!["http://127.0.0.1:1".into()]; + let image = |capable: bool| -> ImageInfo { + serde_json::from_value(serde_json::json!({ + "kernel": "bzImage", "initrd": "initrd", "app_epoch_pin": capable, + })) + .unwrap() + }; + let compose = |key_provider: &str| -> AppCompose { + serde_json::from_value(serde_json::json!({ + "manifest_version": 2, "name": "test", "runner": "docker-compose", + "key_provider": key_provider, + })) + .unwrap() + }; + let config = &config; + let epoch = |app_epoch: Option, key_provider: &'static str, capable: bool| async move { + let manifest = Manifest { + app_epoch, + ..test_manifest(2048) + }; + launch_app_epoch(&manifest, config, &compose(key_provider), &image(capable)).await + }; + + // Older images get no pin, and refuse an explicit one. + assert_eq!(epoch(None, "kms", false).await?, None); + let err = epoch(Some(2), "kms", false).await.unwrap_err(); + assert!(err.to_string().contains("does not support"), "{err:#}"); + // Without KMS keys there is no app epoch to bind. + assert_eq!(epoch(None, "none", true).await?, None); + assert_eq!(epoch(Some(2), "kms", true).await?, Some(2)); + // SEV-SNP with KMS keys asks the KMS for the current epoch. + let err = epoch(None, "kms", true).await.unwrap_err(); + assert!(err.to_string().contains("current app epoch"), "{err:#}"); + Ok(()) + } + #[test] fn selects_mr_config_version_for_each_tee_mode() -> Result<()> { let manifest = test_manifest(2048); @@ -4130,7 +4191,19 @@ mod tests { mr_config_version(&manifest, CvmPlatform::Tdx, false, true) .err() .map(|error| error.to_string()), - Some("key provider ID requires MrConfigV3, but use_mrconfigid is disabled".to_string()) + Some(MR_CONFIG_V3_REQUIRED.to_string()) + ); + let mut pinned = manifest.clone(); + pinned.app_epoch = Some(1); + assert_eq!( + mr_config_version(&pinned, CvmPlatform::Tdx, true, false)?, + Some(MrConfigVersion::V3) + ); + assert_eq!( + mr_config_version(&pinned, CvmPlatform::Tdx, false, false) + .err() + .map(|error| error.to_string()), + Some(MR_CONFIG_V3_REQUIRED.to_string()) ); let mut no_tee = manifest.clone(); @@ -4180,6 +4253,7 @@ mod tests { Image { info: ImageInfo { sealed_env: false, + app_epoch_pin: false, cmdline: None, kernel: "kernel".to_string(), initrd: "initrd".to_string(), @@ -4518,6 +4592,7 @@ mod tests { disk_prealloc: DiskPrealloc::Off, annotations: Default::default(), launch_ticket: Some("t".repeat(32)), + app_epoch: None, }; let mr_config = MrConfigV3::new( diff --git a/dstack/vmm/src/app/image.rs b/dstack/vmm/src/app/image.rs index 686680c4d6..4e7ee5d78f 100644 --- a/dstack/vmm/src/app/image.rs +++ b/dstack/vmm/src/app/image.rs @@ -39,6 +39,10 @@ pub struct ImageInfo { /// Whether this guest supports SealedEnv. Missing metadata means legacy only. #[serde(default)] pub sealed_env: bool, + /// Whether this guest understands the MrConfigV3 `app_epoch` pin. Older + /// guests reject a document carrying it. + #[serde(default)] + pub app_epoch_pin: bool, #[serde(default)] pub is_dev: bool, /// OVMF measurement layout declared by the image. Older metadata.json files diff --git a/dstack/vmm/src/app/mr_config.rs b/dstack/vmm/src/app/mr_config.rs index c8b08170b4..76094891a5 100644 --- a/dstack/vmm/src/app/mr_config.rs +++ b/dstack/vmm/src/app/mr_config.rs @@ -6,13 +6,15 @@ use anyhow::{bail, Context, Result}; use base64::prelude::*; +use dstack_kms_rpc::{kms_client::KmsClient, SealedEnvPubKeyRequest}; use dstack_types::mr_config::{MrConfig, MrConfigV3}; -use dstack_types::{gpu_policy_hash, AppCompose}; +use dstack_types::{gpu_policy_hash, AppCompose, TeeVariant}; use fs_err as fs; +use ra_rpc::client::RaClient; use sha2::{Digest, Sha256}; -use super::{GpuConfig, Manifest, VmWorkDir}; -use crate::config::{CvmConfig, CvmPlatform}; +use super::{GpuConfig, ImageInfo, Manifest, VmWorkDir}; +use crate::config::{Config, CvmConfig, CvmPlatform}; fn bind_init_script_hashes(mut mr_config: MrConfigV3, app_compose: &AppCompose) -> MrConfigV3 { if app_compose.manifest_version_u32().unwrap_or_default() >= 3 { @@ -26,6 +28,9 @@ fn bind_init_script_hashes(mut mr_config: MrConfigV3, app_compose: &AppCompose) mr_config } +pub(super) const MR_CONFIG_V3_REQUIRED: &str = + "key provider ID and app epoch pins require MrConfigV3, but use_mrconfigid is disabled"; + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum MrConfigVersion { V1, @@ -44,13 +49,12 @@ pub(super) fn mr_config_version( if manifest.no_tee { return Ok(None); } + let has_pins = has_key_provider_id || manifest.app_epoch.is_some(); match platform { CvmPlatform::AmdSevSnp => Ok(Some(MrConfigVersion::V3)), - CvmPlatform::Tdx if has_key_provider_id && !use_mrconfigid => { - bail!("key provider ID requires MrConfigV3, but use_mrconfigid is disabled") - } + CvmPlatform::Tdx if has_pins && !use_mrconfigid => bail!(MR_CONFIG_V3_REQUIRED), CvmPlatform::Tdx if !use_mrconfigid => Ok(None), - CvmPlatform::Tdx if has_key_provider_id => Ok(Some(MrConfigVersion::V3)), + CvmPlatform::Tdx if has_pins => Ok(Some(MrConfigVersion::V3)), CvmPlatform::Tdx => Ok(Some(MrConfigVersion::V1)), } } @@ -101,31 +105,136 @@ pub(super) fn snp_host_data(workdir: &VmWorkDir) -> Result { Ok(BASE64_STANDARD.encode(MrConfigV3::snp_host_data_from_document(&document))) } +/// The MrConfig version of a launch, refusing an app epoch pin it cannot bind. +fn launch_mr_config_version( + manifest: &Manifest, + config: &CvmConfig, + app_compose: &AppCompose, +) -> Result> { + let version = mr_config_version( + manifest, + config.resolved_platform(), + config.use_mrconfigid, + !app_compose.key_provider_id.is_empty(), + )?; + if manifest.app_epoch.is_some() { + if !app_compose.key_provider().is_kms() { + bail!("an app epoch pin requires the KMS key provider"); + } + if version != Some(MrConfigVersion::V3) { + bail!("an app epoch pin requires a TEE launch that binds MrConfigV3"); + } + } + Ok(version) +} + +fn is_snp_launch(manifest: &Manifest, platform: CvmPlatform) -> bool { + manifest.simulated_tee == Some(TeeVariant::DstackAmdSevSnp) + || (!manifest.no_tee && platform == CvmPlatform::AmdSevSnp) +} + +/// The app epoch a launch binds in MrConfigV3: the pin, or on SEV-SNP with KMS +/// keys the KMS's current app epoch, since SEV-SNP has no runtime register to +/// measure the epoch the guest is served. Images predating the field get none. +pub(crate) async fn launch_app_epoch( + manifest: &Manifest, + config: &Config, + app_compose: &AppCompose, + image: &ImageInfo, +) -> Result> { + if !image.app_epoch_pin { + if manifest.app_epoch.is_some() { + bail!("image {:?} does not support app epoch pins", manifest.image); + } + return Ok(None); + } + if manifest.app_epoch.is_some() + || !app_compose.key_provider().is_kms() + || !is_snp_launch(manifest, config.cvm.resolved_platform()) + { + return Ok(manifest.app_epoch); + } + let kms_urls = if manifest.kms_urls.is_empty() { + &config.cvm.kms_urls + } else { + &manifest.kms_urls + }; + if kms_urls.is_empty() { + bail!("an amd sev-snp launch with KMS keys needs a KMS URL to read the app epoch"); + } + let app_id = hex::decode(&manifest.app_id).context("invalid app ID")?; + let mut errors = vec![]; + for url in kms_urls { + // The answer needs no authentication: it is measured, and the KMS + // policy decides whether the epoch may serve this instance. The URL is + // the one the guest derives (`kms_rpc_url` in dstack-util). + let base = url.trim_end_matches('/'); + let url = if base.ends_with("/prpc") { + base.to_string() + } else { + format!("{base}/prpc") + }; + let request = SealedEnvPubKeyRequest { + app_id: app_id.clone(), + app_epoch: None, + }; + let response = async { + KmsClient::new(RaClient::new(url.clone(), true)?) + .get_sealed_env_pub_key(request) + .await + }; + match response.await { + Ok(response) => return Ok(Some(response.app_epoch)), + Err(err) => errors.push(format!("{url}: {err:#}")), + } + } + bail!( + "failed to read the current app epoch from the KMS: {}", + errors.join("; ") + ) +} + +/// Refuse an app epoch pin at deployment rather than at the next launch. +pub(crate) fn validate_app_epoch_pin( + manifest: &Manifest, + config: &CvmConfig, + compose_file: &str, +) -> Result<()> { + if manifest.app_epoch.is_none() { + return Ok(()); + } + let app_compose: AppCompose = + serde_json::from_str(compose_file).context("invalid app compose")?; + launch_mr_config_version(manifest, config, &app_compose).map(drop) +} + impl VmWorkDir { + /// `app_epoch` is what [`launch_app_epoch`] resolved for this launch. pub(crate) fn prepare_mr_config( &self, manifest: &Manifest, config: &CvmConfig, app_compose: &AppCompose, + app_epoch: Option, ) -> Result> { - let version = mr_config_version( - manifest, - config.resolved_platform(), - config.use_mrconfigid, - !app_compose.key_provider_id.is_empty(), - )?; - match version { + match launch_mr_config_version(manifest, config, app_compose)? { Some(MrConfigVersion::V3) => self .prepare_mr_config_v3( app_compose, manifest.gpus.as_ref().is_some_and(GpuConfig::has_gpus), + app_epoch, ) .map(Some), Some(MrConfigVersion::V1) | None => Ok(None), } } - fn prepare_mr_config_v3(&self, app_compose: &AppCompose, has_gpus: bool) -> Result { + fn prepare_mr_config_v3( + &self, + app_compose: &AppCompose, + has_gpus: bool, + app_epoch: Option, + ) -> Result { let compose_hash = self .app_compose_hash() .context("failed to get compose hash")?; @@ -189,7 +298,8 @@ impl VmWorkDir { app_compose.key_provider(), app_compose.key_provider_id.clone(), instance_id, - ); + ) + .with_app_epoch(app_epoch); Ok(bind_init_script_hashes(mr_config, app_compose).to_canonical_json()) } } @@ -218,7 +328,7 @@ mod tests { "snp_sealing": {"version": 1, "tcb_version": "257"} }); fs::write(workdir.instance_info_path(), original.to_string()).unwrap(); - workdir.prepare_mr_config_v3(&compose, false).unwrap(); + workdir.prepare_mr_config_v3(&compose, false, None).unwrap(); let saved: serde_json::Value = serde_json::from_slice(&fs::read(workdir.instance_info_path()).unwrap()).unwrap(); assert_eq!(saved["snp_sealing"], original["snp_sealing"]); diff --git a/dstack/vmm/src/app/qemu.rs b/dstack/vmm/src/app/qemu.rs index c620e1a70b..9e80291026 100644 --- a/dstack/vmm/src/app/qemu.rs +++ b/dstack/vmm/src/app/qemu.rs @@ -1520,10 +1520,12 @@ mod tests { disk_prealloc: DiskPrealloc::Off, annotations: Default::default(), launch_ticket: None, + app_epoch: None, }, image: Image { info: ImageInfo { sealed_env: false, + app_epoch_pin: false, cmdline: Some("console=hvc0".into()), kernel: "kernel".into(), initrd: "initrd".into(), diff --git a/dstack/vmm/src/app/vm_info.rs b/dstack/vmm/src/app/vm_info.rs index 1fda160157..b53fdfc5a1 100644 --- a/dstack/vmm/src/app/vm_info.rs +++ b/dstack/vmm/src/app/vm_info.rs @@ -258,6 +258,7 @@ impl VmInfo { annotations: self.manifest.annotations.clone().into_iter().collect(), // A secret the VMM passes to the guest and never returns. launch_ticket: String::new(), + app_epoch: self.manifest.app_epoch, }) }, app_url: self diff --git a/dstack/vmm/src/main_service.rs b/dstack/vmm/src/main_service.rs index f694d6b757..9cce83de11 100644 --- a/dstack/vmm/src/main_service.rs +++ b/dstack/vmm/src/main_service.rs @@ -14,9 +14,9 @@ use dstack_vmm_rpc::vmm_server::{VmmRpc, VmmServer}; use dstack_vmm_rpc::{ AppId, ComposeHash as RpcComposeHash, GatewaySettings, GetInfoResponse, GetMetaResponse, Id, ImageInfo as RpcImageInfo, ImageListResponse, KmsSettings, ListGpusResponse, PublicKeyResponse, - ReloadVmsResponse, ResizeVmRequest, ResourcesSettings, SealedEnvPubKeyResponse, StatusRequest, - StatusResponse, SvListResponse, SvProcessInfo, UpdateVmRequest, VersionResponse, - VmConfiguration, + ReloadVmsResponse, ResizeVmRequest, ResourcesSettings, SealedEnvPubKeyRequest, + SealedEnvPubKeyResponse, StatusRequest, StatusResponse, SvListResponse, SvProcessInfo, + UpdateVmRequest, VersionResponse, VmConfiguration, }; use fs_err as fs; use path_absolutize::Absolutize; @@ -24,9 +24,9 @@ use ra_rpc::{CallContext, RpcCall}; use tracing::{info, warn}; use crate::app::{ - mode_carries_ingress, needs_swtpm, resolve_networking, validate_resolved_network, - validate_resolved_networks, App, AttachMode, GpuConfig, GpuSpec, Image, Manifest, PortMapping, - VmWorkDir, + mode_carries_ingress, needs_swtpm, resolve_networking, validate_app_epoch_pin, + validate_resolved_network, validate_resolved_networks, App, AttachMode, GpuConfig, GpuSpec, + Image, Manifest, PortMapping, VmWorkDir, }; use crate::config::{ CvmConfig, DiskPrealloc, Networking, NetworkingMode, NicNetworking, PortMappingConfig, @@ -380,7 +380,7 @@ pub fn create_manifest_from_vm_config( validate_disk_prealloc_against_compose(disk_prealloc, &request.compose_file)?; validate_allowed_envs(&allowed_envs_from_compose(&request.compose_file)?)?; - Ok(Manifest { + let manifest = Manifest { id, name: request.name.clone(), app_id, @@ -403,7 +403,10 @@ pub fn create_manifest_from_vm_config( disk_prealloc, annotations: annotations_from_proto(&request.annotations)?, launch_ticket: launch_ticket_from_proto(&request.launch_ticket)?, - }) + app_epoch: request.app_epoch, + }; + validate_app_epoch_pin(&manifest, cvm_config, &request.compose_file)?; + Ok(manifest) } /// Refuse a ticket the KMS would refuse, so the mistake surfaces here rather @@ -993,6 +996,20 @@ impl RpcHandler { Ok(true) } + /// Refuse an app epoch pin the target image would reject at boot. + fn validate_app_epoch_image(&self, manifest: &Manifest) -> Result<()> { + if manifest.app_epoch.is_none() { + return Ok(()); + } + let image_dir = self.app.config.image.image_dir(&manifest.image)?; + let image = Image::load(&image_dir) + .with_context(|| format!("failed to load image {:?}", manifest.image))?; + if !image.info.app_epoch_pin { + bail!("image {:?} does not support app epoch pins", manifest.image); + } + Ok(()) + } + fn validate_env_image( &self, work_dir: &VmWorkDir, @@ -1065,6 +1082,7 @@ impl VmmRpc for RpcHandler { async fn create_vm(self, request: VmConfiguration) -> Result { let manifest = create_manifest_from_vm_config(request.clone(), &self.app.config.cvm)?; self.validate_port_mapping_conflicts(None, &manifest.port_map)?; + self.validate_app_epoch_image(&manifest)?; let id = manifest.id.clone(); info!(vm_id = %id, "create_vm RPC called"); let app_id = manifest.app_id.clone(); @@ -1152,6 +1170,7 @@ impl VmmRpc for RpcHandler { description: serde_json::to_string(&info).unwrap_or_default(), version: info.version, sealed_env: info.sealed_env, + app_epoch_pin: info.app_epoch_pin, is_dev: info.is_dev, }) .collect(), @@ -1238,6 +1257,9 @@ impl VmmRpc for RpcHandler { if let Some(ticket) = &request.launch_ticket { manifest.launch_ticket = launch_ticket_from_proto(ticket)?; } + if request.update_app_epoch { + manifest.app_epoch = request.app_epoch; + } if request.update_annotations { manifest.annotations = annotations_from_proto(&request.annotations)?; } @@ -1279,6 +1301,8 @@ impl VmmRpc for RpcHandler { key_provider_from_compose(&compose_file)?, manifest.simulated_tee, ); + validate_app_epoch_pin(&manifest, &self.app.config.cvm, &compose_file)?; + self.validate_app_epoch_image(&manifest)?; Self::grow_disk_if_needed(&vm_work_dir, &manifest, old_disk_size).await?; if request.update_networking { @@ -1334,11 +1358,15 @@ impl VmmRpc for RpcHandler { }) } - async fn get_sealed_env_pub_key(self, request: AppId) -> Result { + async fn get_sealed_env_pub_key( + self, + request: SealedEnvPubKeyRequest, + ) -> Result { let kms = self.kms_client()?; let response = kms - .get_sealed_env_pub_key(dstack_kms_rpc::AppId { + .get_sealed_env_pub_key(dstack_kms_rpc::SealedEnvPubKeyRequest { app_id: request.app_id, + app_epoch: request.app_epoch, }) .await?; Ok(SealedEnvPubKeyResponse { @@ -1399,6 +1427,7 @@ impl VmmRpc for RpcHandler { request.image.as_deref(), ) .await?; + self.validate_app_epoch_image(&manifest)?; Self::grow_disk_if_needed(&vm_work_dir, &manifest, old_disk_size).await?; vm_work_dir .put_manifest(&manifest) @@ -1627,6 +1656,36 @@ mod tests { disk_prealloc: None, annotations: Default::default(), launch_ticket: String::new(), + app_epoch: None, + } + } + + #[test] + fn app_epoch_pin_needs_kms_and_a_bound_mr_config() { + let compose = |key_provider: &str| { + serde_json::json!({ + "manifest_version": 2, + "name": "test", + "runner": "docker-compose", + "key_provider": key_provider, + }) + .to_string() + }; + let request = |compose_file: String, no_tee: bool| VmConfiguration { + compose_file, + no_tee, + app_epoch: Some(1), + ..test_vm_configuration() + }; + for (request, error) in [ + ( + request(compose("none"), false), + "requires the KMS key provider", + ), + (request(compose("kms"), true), "binds MrConfigV3"), + ] { + let err = create_manifest_from_vm_config(request, &test_cvm_config()).unwrap_err(); + assert!(err.to_string().contains(error), "{err:#}"); } } diff --git a/dstack/vmm/src/one_shot.rs b/dstack/vmm/src/one_shot.rs index 9b494d092f..7e46833d5c 100644 --- a/dstack/vmm/src/one_shot.rs +++ b/dstack/vmm/src/one_shot.rs @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 use crate::app::{ - make_sys_config, needs_netd_interface, resolved_networks, settle_vhost, + launch_app_epoch, make_sys_config, needs_netd_interface, resolved_networks, settle_vhost, simulator_config_for_manifest, sync_tee_simulator_config, Image, VmConfig, VmWorkDir, }; use crate::config::Config; @@ -241,8 +241,9 @@ Compose file content (first 200 chars): let app_compose = vm_work_dir .app_compose() .context("Failed to get app compose")?; + let app_epoch = launch_app_epoch(&manifest, &config, &app_compose, &image.info).await?; let mr_config = vm_work_dir - .prepare_mr_config(&manifest, &config.cvm, &app_compose) + .prepare_mr_config(&manifest, &config.cvm, &app_compose, app_epoch) .context("Failed to prepare mr_config")?; let sys_config_str = make_sys_config( &config, diff --git a/dstack/vmm/src/tests/test_vmm_cli.py b/dstack/vmm/src/tests/test_vmm_cli.py index 32ad72a55b..3970040037 100644 --- a/dstack/vmm/src/tests/test_vmm_cli.py +++ b/dstack/vmm/src/tests/test_vmm_cli.py @@ -78,12 +78,54 @@ def test_launch_ticket_is_sent_and_removed(self) -> None: [params["launch_ticket"] for _, params in calls], ["t" * 32, ""] ) + def test_app_epoch_is_pinned_and_removed(self) -> None: + """Pin epoch zero, then remove the pin; refuse before any change lands.""" + cli = VMM_CLI.VmmCLI("http://127.0.0.1:8080") + updates: list[dict] = [] + supported = True + + def rpc(method, params=None): + if method == "GetInfo": + return {"found": True, "info": {"configuration": {"image": "img"}}} + if method == "ListImages": + return {"images": [{"name": "img", "app_epoch_pin": supported}]} + updates.append(params) + return {} + + cli.rpc_call = rpc + with contextlib.redirect_stdout(io.StringIO()): + cli.update_vm("vm-id", vcpu=2, app_epoch=0) + cli.update_vm("vm-id", no_app_epoch=True) + with self.assertRaises(ValueError): + cli.update_vm("vm-id", app_epoch=-1) + supported = False + with self.assertRaisesRegex(Exception, "does not support app epoch pins"): + cli.update_vm("vm-id", vcpu=4, app_epoch=1) + + self.assertEqual( + updates, + [ + # The resize rides on the same request as the pin. + {"id": "vm-id", "vcpu": 2, "update_app_epoch": True, "app_epoch": 0}, + {"id": "vm-id", "update_app_epoch": True}, + ], + ) + + def test_env_is_sealed_only_at_a_typed_app_epoch(self) -> None: + """Never seal at an epoch only the host reports.""" + seal = VMM_CLI.VmmCLI.sealing_app_epoch + self.assertIsNone(seal("vm", {}, None, False)) + self.assertEqual(seal("vm", {"app_epoch": 1}, 1, False), 1) + self.assertIsNone(seal("vm", {"app_epoch": 1}, None, True)) + with self.assertRaisesRegex(Exception, "pass --app-epoch 1"): + seal("vm", {"app_epoch": 1}, None, False) + def test_compose_is_sent_as_is_with_env(self) -> None: """Send the rendered compose unchanged, refusing envs it does not allow.""" cli = VMM_CLI.VmmCLI("http://127.0.0.1:8080") cli.rpc_call = Mock(return_value={"found": True, "info": {"app_id": "app"}}) cli.encrypt_env_payload = Mock(return_value={"encrypted_env": "00"}) - cli.image_supports_sealed_env = Mock(return_value=False) + cli.image_supports = Mock(return_value=False) compose = '{"allowed_envs": ["A"]}' with ( @@ -115,7 +157,7 @@ def test_env_only_update_keeps_compose_and_kms_urls(self) -> None: } cli.rpc_call = Mock(return_value={"found": True, "info": info}) cli.encrypt_env_payload = Mock(return_value={"encrypted_env": "00"}) - cli.image_supports_sealed_env = Mock(return_value=False) + cli.image_supports = Mock(return_value=False) with ( patch.object(VMM_CLI, "parse_env_file", return_value={"A": "1"}), @@ -134,7 +176,7 @@ def test_launch_token_must_match_compose(self) -> None: cli = VMM_CLI.VmmCLI("http://127.0.0.1:8080") cli.rpc_call = Mock(return_value={"found": True, "info": {"app_id": "app"}}) cli.encrypt_env_payload = Mock(return_value={}) - cli.image_supports_sealed_env = Mock(return_value=False) + cli.image_supports = Mock(return_value=False) token_hash = hashlib.sha256(b"token").hexdigest() def update(token: str) -> None: @@ -326,16 +368,22 @@ def test_sealed_payload_round_trip_and_normalized_pins(self): def test_app_epoch_is_signed_and_used_for_sealing(self): """Bind the app epoch in both the signature and HPKE context.""" + + def sign(prefix: bytes) -> None: + digest = keccak( + prefix + + bytes.fromhex(self.app_id) + + self.epoch.to_bytes(4, "big") + + (2).to_bytes(4, "big") + + bytes.fromhex(self.response["public_key"]) + + self.timestamp.to_bytes(8, "big") + ) + self.response["signature"] = ( + self.signer.sign_msg_hash(digest).to_bytes().hex() + ) + self.response["app_epoch"] = 2 - digest = keccak( - b"dstack-sealed-env-pubkey-v1:" - + bytes.fromhex(self.app_id) - + self.epoch.to_bytes(4, "big") - + (2).to_bytes(4, "big") - + bytes.fromhex(self.response["public_key"]) - + self.timestamp.to_bytes(8, "big") - ) - self.response["signature"] = self.signer.sign_msg_hash(digest).to_bytes().hex() + sign(b"dstack-sealed-env-pubkey-v1:") payload = self.cli.encrypt_env_payload(self.envs, self.app_id, None, True) envelope = json.loads(bytes.fromhex(payload["sealed_env"])) self.assertEqual(envelope["version"], 1) @@ -349,6 +397,19 @@ def test_app_epoch_is_signed_and_used_for_sealing(self): self.assertEqual( plaintext, {"env": [{"key": k, "value": v} for k, v in self.envs.items()]} ) + self.cli.encrypt_env_payload(self.envs, self.app_id, None, True, 2) + self.assertEqual( + self.cli.client.request.call_args.kwargs["body"], + {"app_id": self.app_id, "app_epoch": 2}, + ) + # A KMS predating app epoch selection serves the current epoch instead. + with self.assertRaisesRegex(Exception, "instead of the pinned 1"): + self.cli.encrypt_env_payload(self.envs, self.app_id, None, True, 1) + # A retired epoch's key is accepted only for the epoch the caller pinned. + sign(b"dstack-sealed-env-pubkey-historical-v1:") + self.cli.encrypt_env_payload(self.envs, self.app_id, None, True, 2) + with self.assertRaises(ValueError): + self.cli.encrypt_env_payload(self.envs, self.app_id, None, True) self.response["app_epoch"] = 1 with self.assertRaises(ValueError): self.cli.encrypt_env_payload(self.envs, self.app_id, None, True) @@ -567,6 +628,7 @@ def test_create_and_update_send_only_the_negotiated_field(self): no_tee=False, annotation=None, launch_ticket_file=None, + app_epoch=None, disk_prealloc=None, simulated_tee=None, swap=None, @@ -588,7 +650,11 @@ def rpc(method, params=None): "found": True, "info": { "app_id": self.app_id, - "configuration": {"compose_file": compose, "image": "image"}, + "configuration": { + "compose_file": compose, + "image": "image", + "app_epoch": args.app_epoch, + }, }, } return {"id": "vm"} @@ -620,6 +686,20 @@ def rpc(method, params=None): self.assertIn("encrypted_env", payload) self.assertNotIn("sealed_env", payload) + # A pin is sent only to an image the VMM reports honoring it. + args.env_file, args.app_epoch = None, 0 + for capability in [{"app_epoch_pin": True}, {}]: + self.cli.rpc_call.reset_mock() + if capability: + self.cli.create_vm(args) + method, payload = self.cli.rpc_call.call_args.args + self.assertEqual((method, payload["app_epoch"]), ("CreateVm", 0)) + else: + with self.assertRaisesRegex(Exception, "does not support"): + self.cli.create_vm(args) + methods = [c.args[0] for c in self.cli.rpc_call.call_args_list] + self.assertNotIn("CreateVm", methods) + if __name__ == "__main__": unittest.main() diff --git a/dstack/vmm/src/vmm-cli.py b/dstack/vmm/src/vmm-cli.py index a53abc59a1..b273dcf3ba 100755 --- a/dstack/vmm/src/vmm-cli.py +++ b/dstack/vmm/src/vmm-cli.py @@ -348,8 +348,14 @@ def validate_uint(value: int, bits: int, name: str) -> None: raise ValueError(f"{name} must be a uint{bits}") -def verify_sealed_env_pubkey(response: Dict, app_id: str) -> None: - """Authenticate a SealedEnv key against the locally pinned epoch signers.""" +def verify_sealed_env_pubkey( + response: Dict, app_id: str, pinned_app_epoch: Optional[int] = None +) -> None: + """Authenticate a SealedEnv key against the locally pinned epoch signers. + + With a pinned epoch, only that epoch's key is accepted; the KMS signs the + key of an app epoch older than the current one with a separate tag. + """ if not CRYPTO_AVAILABLE: raise ImportError("Install the VMM CLI requirements to verify SealedEnv keys") app_id_bytes = bytes.fromhex(app_id.removeprefix("0x")) @@ -360,6 +366,11 @@ def verify_sealed_env_pubkey(response: Dict, app_id: str) -> None: validate_uint(response_app_epoch, 32, "app_epoch") validate_uint(epoch, 32, "root_epoch") validate_uint(timestamp, 64, "timestamp") + if pinned_app_epoch is not None and response_app_epoch != pinned_app_epoch: + raise ValueError( + f"the KMS returned the key of app epoch {response_app_epoch} instead of " + f"the pinned {pinned_app_epoch}; it may predate app epoch selection" + ) now = int(time.time()) if now - timestamp > 300: raise ValueError("SealedEnv public key timestamp is stale") @@ -367,19 +378,25 @@ def verify_sealed_env_pubkey(response: Dict, app_id: str) -> None: raise ValueError("SealedEnv public key timestamp is in the future") if len(app_id_bytes) != 20 or len(public_key) != 32 or len(signature) != 65: raise ValueError("Invalid SealedEnv app ID, public key or signature length") - digest = keccak( - b"dstack-sealed-env-pubkey-v1:" - + app_id_bytes + message = ( + app_id_bytes + epoch.to_bytes(4, "big") + response_app_epoch.to_bytes(4, "big") + public_key + timestamp.to_bytes(8, "big") ) - signer = keys.Signature(signature_bytes=signature).recover_public_key_from_msg_hash( - digest - ) + prefixes = [b"dstack-sealed-env-pubkey-v1:"] + if pinned_app_epoch is not None: + prefixes.append(b"dstack-sealed-env-pubkey-historical-v1:") pins = {bytes.fromhex(pin.removeprefix("0x")) for pin in load_whitelist()} - if signer.to_compressed_bytes() not in pins: + signature = keys.Signature(signature_bytes=signature) + if not any( + signature.recover_public_key_from_msg_hash( + keccak(prefix + message) + ).to_compressed_bytes() + in pins + for prefix in prefixes + ): raise ValueError( "SealedEnv signer is not pinned; configure a trusted epoch signer with kms add" ) @@ -878,22 +895,31 @@ def list_images(self, json_output: bool = False) -> None: rows = [[img["name"], img.get("version", "-")] for img in images] print(format_table(rows, headers)) - def image_supports_sealed_env(self, image: Optional[str]) -> bool: - """Read the selected image capability, treating missing metadata as legacy.""" + def image_supports(self, image: Optional[str], capability: str) -> bool: + """Read an image capability, treating missing metadata as legacy.""" if not image: return False images = self.rpc_call("ListImages").get("images", []) return any( - item.get("name") == image and item.get("sealed_env") is True + item.get("name") == image and item.get(capability) is True for item in images ) + def ensure_app_epoch_pin(self, image: Optional[str]) -> None: + """Refuse a pin before any change lands; a VMM predating pins reports no image supporting them.""" + if not self.image_supports(image, "app_epoch_pin"): + raise Exception( + f"image {image} does not support app epoch pins, " + "or the VMM predates them (needs dstack-vmm >= 0.6.7)" + ) + def get_sealed_env_pub_key( self, app_id: str, kms_url: Optional[str] = None, + app_epoch: Optional[int] = None, ) -> Dict: - """Return the authenticated current key; never downgrade on an unsigned error.""" + """Return the authenticated key of `app_epoch` (default current); never downgrade on an unsigned error.""" # KMS RA-TLS is authenticated by the pinned signer below. The VMM # path retains its configured TLS verification and authentication. client = VmmClient(kms_url, verify_tls=False) if kms_url else self.client @@ -901,13 +927,15 @@ def get_sealed_env_pub_key( "POST", "/prpc/GetSealedEnvPubKey?json", headers={"Content-Type": "application/json"}, - body={"app_id": app_id}, + body={"app_id": app_id} + if app_epoch is None + else {"app_id": app_id, "app_epoch": app_epoch}, ) if status != 200: raise RuntimeError(f"GetSealedEnvPubKey failed with HTTP {status}") if not isinstance(response, dict): raise ValueError("Invalid GetSealedEnvPubKey response") - verify_sealed_env_pubkey(response, app_id) + verify_sealed_env_pubkey(response, app_id, app_epoch) return response def encrypt_env_payload( @@ -916,11 +944,12 @@ def encrypt_env_payload( app_id: str, kms_url: Optional[str], supports_sealed_env: bool, + app_epoch: Optional[int] = None, ) -> Dict: """Select encryption using the target image capability and KMS RPC support.""" envs_list = [{"key": k, "value": v} for k, v in envs.items()] if supports_sealed_env: - key = self.get_sealed_env_pub_key(app_id, kms_url) + key = self.get_sealed_env_pub_key(app_id, kms_url, app_epoch) return { "sealed_env": seal_env( envs_list, @@ -1175,6 +1204,10 @@ def create_vm(self, args) -> None: } if args.launch_ticket_file: params["launch_ticket"] = read_launch_ticket(args.launch_ticket_file) + if args.app_epoch is not None: + validate_uint(args.app_epoch, 32, "app_epoch") + self.ensure_app_epoch_pin(args.image) + params["app_epoch"] = args.app_epoch if args.disk_prealloc: params["disk_prealloc"] = args.disk_prealloc if args.simulated_tee: @@ -1219,12 +1252,29 @@ def create_vm(self, args) -> None: envs, app_id, encrypt_url, - self.image_supports_sealed_env(args.image), + self.image_supports(args.image, "sealed_env"), + args.app_epoch, ) ) response = self.rpc_call("CreateVm", params) - print(f"Created VM with ID: {response.get('id')}") - return response.get("id") + vm_id = response.get("id") + print(f"Created VM with ID: {vm_id}") + return vm_id + + @staticmethod + def sealing_app_epoch( + vm_id: str, configuration: Dict, app_epoch: Optional[int], no_app_epoch: bool + ) -> Optional[int]: + """Return the app epoch to seal at, never one only the host reports.""" + if app_epoch is not None or no_app_epoch: + return app_epoch + pinned = configuration.get("app_epoch") + if pinned is not None: + raise Exception( + f"VM {vm_id} is pinned to app epoch {pinned}; " + f"pass --app-epoch {pinned} to seal the env at it" + ) + return None def update_vm_user_config(self, vm_id: str, user_config: str) -> None: """Update user config for a VM.""" @@ -1263,8 +1313,17 @@ def update_vm( net_queues: Optional[Union[int, str]] = None, annotations: Optional[Dict[str, str]] = None, launch_ticket: Optional[str] = None, + app_epoch: Optional[int] = None, + no_app_epoch: bool = False, ) -> None: """Update multiple aspects of a VM in one command.""" + if app_epoch is not None: + validate_uint(app_epoch, 32, "app_epoch") + target_image = image + if target_image is None: + info = self.rpc_call("GetInfo", {"id": vm_id}).get("info") or {} + target_image = (info.get("configuration") or {}).get("image") + self.ensure_app_epoch_pin(target_image) encrypt_url = kms_encrypt_url or (kms_urls[0] if kms_urls else None) if env_file and not encrypt_url: raise Exception( @@ -1289,13 +1348,16 @@ def update_vm( resize_params["image"] = image updates.append(f"image: {image}") - if resize_params and not env_file: + # Applied together with an env or pin change, so a rejected update + # leaves the VM unchanged. + atomic = env_file or app_epoch is not None or no_app_epoch + if resize_params and not atomic: resize_params["id"] = vm_id self.rpc_call("ResizeVm", resize_params) # handle upgrade operations (compose, env, user_config, ports, gpu) upgrade_params = {"id": vm_id} - if env_file: + if atomic: upgrade_params.update(resize_params) if app_compose is not None: @@ -1342,10 +1404,14 @@ def update_vm( envs, vm_info_response["info"]["app_id"], encrypt_url, - self.image_supports_sealed_env( + self.image_supports( image if image is not None - else vm_configuration.get("image") + else vm_configuration.get("image"), + "sealed_env", + ), + self.sealing_app_epoch( + vm_id, vm_configuration, app_epoch, no_app_epoch ), ) ) @@ -1477,6 +1543,16 @@ def update_vm( "launch ticket" if launch_ticket else "launch ticket removed" ) + if app_epoch is not None or no_app_epoch: + upgrade_params["update_app_epoch"] = True + if app_epoch is not None: + upgrade_params["app_epoch"] = app_epoch + updates.append( + f"app epoch: {app_epoch}" + if app_epoch is not None + else "app epoch unpinned" + ) + if no_tee is not None: upgrade_params["no_tee"] = no_tee updates.append("TEE disabled" if no_tee else "TEE enabled") @@ -1512,6 +1588,8 @@ def show_info(self, vm_id: str, json_output: bool = False) -> None: print(f"App ID: {info.get('app_id', '-')}") print(f"Instance ID: {info.get('instance_id', '-') or '-'}") print(f"Launch Ticket: {info.get('launch_ticket_hash') or '-'}") + app_epoch = config.get("app_epoch") + print(f"App Epoch: {'-' if app_epoch is None else app_epoch}") print(f"App URL: {info.get('app_url', '-') or '-'}") print(f"Image: {config.get('image', '-')}") print(f"Image Version: {info.get('image_version', '-')}") @@ -2182,6 +2260,12 @@ def _patched_format_help(): help="File holding the launch ticket the guest presents to the KMS " "(requires dstack-vmm >= 0.6.5)", ) + deploy_parser.add_argument( + "--app-epoch", + type=int, + help="Pin the app key epoch the guest requests from the KMS " + "(requires dstack-vmm >= 0.6.7)", + ) deploy_parser.add_argument( "--disk-prealloc", choices=["off", "metadata", "falloc", "full"], @@ -2452,6 +2536,15 @@ def _patched_format_help(): launch_ticket_group.add_argument( "--no-launch-ticket", action="store_true", help="Remove the launch ticket" ) + app_epoch_group = update_parser.add_mutually_exclusive_group() + app_epoch_group.add_argument( + "--app-epoch", + type=int, + help="Pin the app key epoch (requires dstack-vmm >= 0.6.7)", + ) + app_epoch_group.add_argument( + "--no-app-epoch", action="store_true", help="Remove the app epoch pin" + ) launch_ticket_parser = subparsers.add_parser( "launch-ticket", help="Create launch tickets and print their on-chain hash" @@ -2559,6 +2652,8 @@ def _patched_format_help(): else args.launch_ticket_file and read_launch_ticket(args.launch_ticket_file) ), + app_epoch=args.app_epoch, + no_app_epoch=args.no_app_epoch, ) elif args.command == "kms": if not args.kms_action: diff --git a/dstack/vmm/ui/src/components/CreateVmDialog.ts b/dstack/vmm/ui/src/components/CreateVmDialog.ts index 217e7cd5f1..0beafce4fe 100644 --- a/dstack/vmm/ui/src/components/CreateVmDialog.ts +++ b/dstack/vmm/ui/src/components/CreateVmDialog.ts @@ -19,6 +19,7 @@ const CreateVmDialogComponent = { availableGpus: { type: Array, required: true }, allowAttachAllGpus: { type: Boolean, required: true }, kmsAvailable: { type: Boolean, required: true }, + appEpochPinSupported: { type: Boolean, required: true }, portMappingEnabled: { type: Boolean, required: true }, networkingModes: { type: Array, required: true }, defaultBridge: { type: String, default: '' }, @@ -202,6 +203,11 @@ const CreateVmDialogComponent = { +
+ + +
+
diff --git a/dstack/vmm/ui/src/components/UpdateVmDialog.ts b/dstack/vmm/ui/src/components/UpdateVmDialog.ts index d4060c77f3..9dd2ad9e69 100644 --- a/dstack/vmm/ui/src/components/UpdateVmDialog.ts +++ b/dstack/vmm/ui/src/components/UpdateVmDialog.ts @@ -26,6 +26,7 @@ const UpdateVmDialogComponent = { defaultModeTunable: { type: Boolean, default: false }, defaultVhostOn: { type: Boolean, default: false }, kmsEnabled: { type: Boolean, required: true }, + appEpochPinSupported: { type: Boolean, required: true }, composeHashPreview: { type: String, required: true }, }, methods: { @@ -265,6 +266,11 @@ const UpdateVmDialogComponent = { :placeholder="dialog.vm?.launch_ticket_hash ? 'Current: ' + dialog.vm.launch_ticket_hash + '; leave empty to keep it' : 'Optional: set a launch ticket'">
+
+ + +
+