diff --git a/CHANGELOG.md b/CHANGELOG.md index 387d2a0ba..cced83c48 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Upgrade notes + +- **`secure_time` refuses a clock the host controls.** `secure_time` is on + unless the app compose sets it to `false`, so this applies to every app + that leaves it out. Such an app no longer boots on AWS, nor when the + clocksource is not `tsc`. On AMD SEV-SNP the VMM launches it with Secure + TSC, which needs QEMU >= 11.2 (not released yet), host kernel >= 6.18 and a + 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. + ### Added +- **Secure TSC for AMD SEV-SNP guests.** The VMM launches an SNP guest with + 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. - **`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 diff --git a/docs/design-and-hardening-decisions.md b/docs/design-and-hardening-decisions.md index b6ffbb9cd..cfb883a1e 100644 --- a/docs/design-and-hardening-decisions.md +++ b/docs/design-and-hardening-decisions.md @@ -57,7 +57,9 @@ See [here](https://intel.github.io/ccc-linux-guest-hardening-docs/security-spec. **Implementation**: dstack OS enforces the guest kernel uses TSC as the only timer source by appending `tsc=reliable no-kvmclock` to the kernel cmdline. It also enforces the use of NTS with built-in [trusted servers](../os/yocto/layers/meta-dstack/recipes-core/chrony/files/chrony.conf) to synchronize system time. -**Behavior**: When `secure_time` is enabled in the app-compose.json configuration, the system ensures time synchronization is completed before requesting application keys. If `secure_time` is disabled, time synchronization is not enforced before application launch. +On AMD SEV-SNP the hypervisor controls the guest TSC unless the guest is launched with Secure TSC. The VMM enables it whenever `secure_time` is on in app-compose.json (the default), which needs QEMU >= 11.2, host kernel >= 6.18 and a CPU that supports Secure TSC. + +**Behavior**: When `secure_time` is enabled in the app-compose.json configuration, the system ensures time synchronization is completed before requesting application keys. It first checks that the host cannot move the clock between syncs and refuses to boot otherwise: the clocksource must be `tsc`, an AMD SEV-SNP guest must run with Secure TSC, and AWS is not supported. If `secure_time` is disabled, time synchronization is not enforced before application launch. **Rationale**: Time synchronization is provided as an optional feature because the process typically requires tens of seconds to complete. Applications can function without the `secure_time` option enabled and may implement their own time synchronization mechanisms if required. diff --git a/dstack/dstack-mr/src/sev.rs b/dstack/dstack-mr/src/sev.rs index b413e8b43..1e023b746 100644 --- a/dstack/dstack-mr/src/sev.rs +++ b/dstack/dstack-mr/src/sev.rs @@ -39,6 +39,18 @@ const VMSA_GPA: u64 = 0x0000_FFFF_FFFF_F000; /// the same bit layout the SEV-SNP ABI's `GUEST_FEATURES` field in /// `SNP_LAUNCH_START` carries). Set on every SNP guest. const SEV_FEATURE_SNP_ACTIVE: u64 = 1 << 0; +/// `SecureTSC`, bit 9: the PSP fixes the guest TSC scale and offset, so the +/// hypervisor can no longer intercept or skew the guest's TSC. +const SEV_FEATURE_SECURE_TSC: u64 = 1 << 9; + +/// `SEV_FEATURES` dstack launches an amd sev-snp guest with. +pub fn launch_guest_features(secure_tsc: bool) -> u64 { + if secure_tsc { + SEV_FEATURE_SNP_ACTIVE | SEV_FEATURE_SECURE_TSC + } else { + SEV_FEATURE_SNP_ACTIVE + } +} /// `SEV_FEATURES` bits a dstack launch may carry. /// @@ -55,16 +67,13 @@ const SEV_FEATURE_SNP_ACTIVE: u64 = 1 << 0; /// SecureTSC (bit 9) or VmsaRegProt (bit 14) likewise removes a guest-side /// protection the operator may believe is on. /// -/// dstack has exactly one launch path, and it sets no feature property: -/// `sev-snp-guest,id=sev0,policy=0x30000,...` in `dstack/vmm/src/app/qemu.rs`, -/// which leaves KVM to start the guest with `SNPActive` alone, and the VMM -/// writes the matching `guest_features: 1` into the measurement document -/// (`dstack/vmm/src/app.rs`). `1` is therefore the only value dstack has ever -/// produced — the captured real-hardware vector in this module's tests carries -/// it too — so it is the only value accepted. Widening this is a one-line -/// change once a launch path actually sets another bit; accepting bits nothing -/// emits would only ever admit a guest dstack did not configure. -const ALLOWED_GUEST_FEATURES: u64 = SEV_FEATURE_SNP_ACTIVE; +/// dstack has exactly one launch path, `sev-snp-guest,id=sev0,policy=0x30000,...` +/// in `dstack/vmm/src/app/qemu.rs`. It starts the guest with `SNPActive`, plus +/// `SecureTSC` when the app compose sets `secure_time`, and the VMM writes the +/// matching `guest_features` into the measurement document +/// (`dstack/vmm/src/app.rs`). Those are the only bits accepted; accepting bits +/// nothing emits would only ever admit a guest dstack did not configure. +const ALLOWED_GUEST_FEATURES: u64 = SEV_FEATURE_SNP_ACTIVE | SEV_FEATURE_SECURE_TSC; #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] @@ -150,7 +159,7 @@ pub fn validate_measurement_input(input: &MeasurementInput) -> Result<()> { if unexpected_features != 0 { bail!( "guest_features {:#x} carries unsupported SEV_FEATURES bits {unexpected_features:#x}; \ - dstack launches amd sev-snp guests with SNPActive only ({ALLOWED_GUEST_FEATURES:#x})", + dstack launches amd sev-snp guests with at most {ALLOWED_GUEST_FEATURES:#x}", input.guest_features ); } @@ -1657,7 +1666,7 @@ mod tests { let cases: [(&str, u64); 4] = [ ("RestrictedInjection", SNP_ACTIVE | (1 << 3)), ("DebugSwap", SNP_ACTIVE | (1 << 5)), - ("SecureTSC", SNP_ACTIVE | (1 << 9)), + ("VmsaRegProt", SNP_ACTIVE | (1 << 14)), ("reserved bit 63", SNP_ACTIVE | (1 << 63)), ]; for (name, features) in cases { @@ -1683,10 +1692,12 @@ mod tests { "unexpected error: {err}" ); - // The one value dstack's launch path produces stays accepted. - let mut input = valid_input(); - input.guest_features = SNP_ACTIVE; - validate_measurement_input(&input).expect("SNPActive-only launch is accepted"); + // The values dstack's launch path produces stay accepted. + for secure_tsc in [false, true] { + let mut input = valid_input(); + input.guest_features = launch_guest_features(secure_tsc); + validate_measurement_input(&input).expect("dstack launch features are accepted"); + } } #[test] diff --git a/dstack/dstack-util/src/system_setup.rs b/dstack/dstack-util/src/system_setup.rs index 74edaa8e5..119773188 100644 --- a/dstack/dstack-util/src/system_setup.rs +++ b/dstack/dstack-util/src/system_setup.rs @@ -1377,6 +1377,34 @@ fn verify_health_check_requirement(app_compose: &AppCompose) -> Result<()> { Ok(()) } +/// NTS fixes the absolute time; only a TSC the host cannot move keeps it +/// between syncs. +fn verify_secure_clock(platform: TeeVariant) -> Result<()> { + match platform { + TeeVariant::DstackTdx | TeeVariant::DstackGcpTdx => {} + TeeVariant::DstackAmdSevSnp => { + let secure_tsc = fs::read_to_string("/sys/devices/system/cpu/sev/secure_tsc") + .context("failed to read amd sev-snp Secure TSC status")?; + if secure_tsc.trim() != "1" { + bail!("secure_time requires amd sev-snp Secure TSC, which the host did not enable"); + } + } + TeeVariant::DstackAwsNitroTpm | TeeVariant::DstackNitroEnclave => { + bail!("secure_time is not supported on AWS") + } + } + let clocksource = + fs::read_to_string("/sys/devices/system/clocksource/clocksource0/current_clocksource") + .context("failed to read the current clocksource")?; + if clocksource.trim() != "tsc" { + bail!( + "secure_time requires the tsc clocksource, found {}", + clocksource.trim() + ); + } + Ok(()) +} + fn verify_platform_requirements( app_compose: &AppCompose, current_platform: TeeVariant, @@ -1515,6 +1543,8 @@ pub async fn cmd_sys_setup(args: SetupArgs) -> Result<()> { async fn do_sys_setup(stage0: Stage0<'_>) -> Result<()> { verify_app_compose_policy(&stage0.shared).context("Failed to verify app-compose policy")?; if stage0.shared.app_compose.secure_time { + let platform = detect_tee_variant().context("secure_time requires a TEE platform")?; + verify_secure_clock(platform)?; info!("Waiting for the system time to be synchronized"); cmd! { chronyc waitsync 30 0.1 0 5; diff --git a/dstack/vmm/src/app.rs b/dstack/vmm/src/app.rs index df023d778..3e3dd0046 100644 --- a/dstack/vmm/src/app.rs +++ b/dstack/vmm/src/app.rs @@ -20,6 +20,7 @@ use dstack_types::shared_filenames::{ USER_CONFIG, }; use dstack_types::version::Version; +use dstack_types::AppCompose; use dstack_vmm_rpc::{ self as pb, GpuInfo, ReloadVmsResponse, StatusRequest, StatusResponse, VmConfiguration, }; @@ -1788,7 +1789,7 @@ impl App { &manifest, &hex::encode(compose_hash), mr_config, - app_compose.requirements.as_ref(), + Some(&app_compose), )?; fs::write(shared_dir.join(SYS_CONFIG), &sys_config_str) .context("Failed to write vm config")?; @@ -2146,7 +2147,7 @@ pub(crate) fn make_sys_config( manifest: &Manifest, compose_hash: &str, mr_config: Option, - requirements: Option<&dstack_types::Requirements>, + app_compose: Option<&AppCompose>, ) -> Result { let image_path = cfg.image.path.join(&manifest.image); let image = Image::load(image_path).context("Failed to load image info")?; @@ -2187,7 +2188,7 @@ pub(crate) fn make_sys_config( &image, compose_hash, mr_config.clone(), - requirements, + app_compose, )?; let mut sys_config = json!({ "kms_urls": kms_urls, @@ -2274,8 +2275,9 @@ fn make_vm_config( image: &Image, _compose_hash: &str, mr_config: Option, - requirements: Option<&dstack_types::Requirements>, + app_compose: Option<&AppCompose>, ) -> Result { + let requirements = app_compose.and_then(|compose| compose.requirements.as_ref()); let platform = cfg.cvm.resolved_platform(); let is_amd_sev_snp = platform == crate::config::CvmPlatform::AmdSevSnp && !manifest.no_tee; // A simulated TDX guest gets the vm_config of a TDX guest, so the simulator @@ -2447,7 +2449,9 @@ fn make_vm_config( measurement: image_measurement.measurement.clone(), vcpus: effective_vcpus, vcpu_type: Some("EPYC-v4".to_string()), - guest_features: 1, + guest_features: dstack_mr::sev::launch_guest_features( + app_compose.is_some_and(|compose| compose.secure_time), + ), }; config["sev_snp_measurement"] = serde_json::Value::String( serde_json::to_string(&measurement) @@ -4398,23 +4402,34 @@ mod tests { Ok(()) } + fn test_app_compose(extra: serde_json::Value) -> AppCompose { + let mut compose = json!({ + "manifest_version": 2, + "name": "test", + "runner": "docker-compose" + }); + if let (Some(compose), Some(extra)) = (compose.as_object_mut(), extra.as_object()) { + compose.extend(extra.clone()); + } + serde_json::from_value(compose).expect("valid app compose") + } + #[test] fn tdx_requirements_measure_acpi_tables_overrides_lite_to_legacy() -> Result<()> { let mut config = test_tdx_config()?; config.cvm.tdx_attestation_variant = TdxAttestationVariantConfig::Lite; let manifest = test_manifest(2048); let image = test_tdx_image(true); - let requirements = dstack_types::Requirements { - tdx_measure_acpi_tables: Some(true), - ..Default::default() - }; + let app_compose = test_app_compose(json!({ + "requirements": { "tdx_measure_acpi_tables": true } + })); let vm_config = make_vm_config( &config, &manifest, &image, &hex_of(0x22, 32), None, - Some(&requirements), + Some(&app_compose), )?; assert!(vm_config.get("tdx_attestation_variant").is_none()); @@ -4430,17 +4445,16 @@ mod tests { config.cvm.tdx_attestation_variant = TdxAttestationVariantConfig::Legacy; let manifest = test_manifest(2048); let image = test_tdx_image(true); - let requirements = dstack_types::Requirements { - tdx_measure_acpi_tables: Some(false), - ..Default::default() - }; + let app_compose = test_app_compose(json!({ + "requirements": { "tdx_measure_acpi_tables": false } + })); let vm_config = make_vm_config( &config, &manifest, &image, &hex_of(0x22, 32), None, - Some(&requirements), + Some(&app_compose), )?; assert_eq!(vm_config["tdx_attestation_variant"], "lite"); @@ -4541,6 +4555,22 @@ mod tests { let build_hash = Sha256::digest(sha256sum.as_bytes()).to_vec(); fs::write(image_dir.join("digest.txt"), hex::encode(&build_hash))?; + let secure_time = test_app_compose(json!({ "secure_time": true })); + let image = Image::load(&image_dir)?; + let secure_time_vm_config = make_vm_config( + &config, + &manifest, + &image, + &compose_hash, + None, + Some(&secure_time), + )?; + let secure_time_measurement: dstack_mr::sev::SnpMeasurementDocument = serde_json::from_str( + secure_time_vm_config["sev_snp_measurement"] + .as_str() + .context("sev_snp_measurement must be a string")?, + )?; + assert_eq!(secure_time_measurement.guest_features, 0x201); let sys_config_document = make_sys_config(&config, &manifest, &compose_hash, Some(mr_config), None)?; let sys_config: serde_json::Value = serde_json::from_str(&sys_config_document)?; diff --git a/dstack/vmm/src/app/qemu.rs b/dstack/vmm/src/app/qemu.rs index 58403bd12..c620e1a70 100644 --- a/dstack/vmm/src/app/qemu.rs +++ b/dstack/vmm/src/app/qemu.rs @@ -45,6 +45,19 @@ struct AmdSevSnpLaunchParams { reduced_phys_bits: u32, } +fn amd_sev_snp_guest_arg( + host_data: &str, + params: AmdSevSnpLaunchParams, + secure_tsc: bool, +) -> String { + format!( + "sev-snp-guest,id=sev0,policy=0x30000,sev-device=/dev/sev,kernel-hashes=on,host-data={host_data},cbitpos={},reduced-phys-bits={}{}", + params.cbitpos, + params.reduced_phys_bits, + if secure_tsc { ",secure-tsc=on" } else { "" } + ) +} + fn parse_amd_sev_snp_qmp_capabilities(stdout: &[u8]) -> Result { let stdout = std::str::from_utf8(stdout).context("QMP output is not valid UTF-8")?; let mut qmp_error = None; @@ -265,6 +278,7 @@ struct PreparedQemuLaunch { tdx_mr_config_id: Option, snp_host_data: Option, snp_launch_params: Option, + snp_secure_tsc: bool, } impl PreparedQemuLaunch { @@ -367,6 +381,7 @@ impl PreparedQemuLaunch { tdx_mr_config_id, snp_host_data, snp_launch_params, + snp_secure_tsc: app_compose.secure_time, }) } } @@ -1100,7 +1115,14 @@ impl VmConfig { let launch_params = prepared.snp_launch_params.context( "snp launch parameters should be detected during launch preparation", )?; - self.configure_amd_sev_snp_guest(command, cfg, mem, host_data, launch_params); + self.configure_amd_sev_snp_guest( + command, + cfg, + mem, + host_data, + launch_params, + prepared.snp_secure_tsc, + ); } } Ok(()) @@ -1159,14 +1181,14 @@ impl VmConfig { mem: u32, host_data: &str, snp_params: AmdSevSnpLaunchParams, + secure_tsc: bool, ) { command .arg("-object") .arg(amd_sev_snp_memory_backend_arg(mem)); - command.arg("-object").arg(format!( - "sev-snp-guest,id=sev0,policy=0x30000,sev-device=/dev/sev,kernel-hashes=on,host-data={host_data},cbitpos={},reduced-phys-bits={}", - snp_params.cbitpos, snp_params.reduced_phys_bits - )); + command + .arg("-object") + .arg(amd_sev_snp_guest_arg(host_data, snp_params, secure_tsc)); command.arg("-machine").arg( "q35,kernel-irqchip=split,confidential-guest-support=sev0,memory-backend=ram1,hpet=off", ); @@ -1252,10 +1274,10 @@ mod tests { use crate::vm_launcher::SidecarChannel; use super::{ - amd_sev_snp_memory_backend_arg, create_hd, fs, nic_fd_layout, + amd_sev_snp_guest_arg, amd_sev_snp_memory_backend_arg, create_hd, fs, nic_fd_layout, parse_amd_sev_snp_qmp_capabilities, prepare_data_disk, qemu_img_create_args, - virtio_pci_device, Command, Path, PreparedQemuLaunch, PreparedVolume, QemuCommandBuilder, - VmConfig, + virtio_pci_device, AmdSevSnpLaunchParams, Command, Path, PreparedQemuLaunch, + PreparedVolume, QemuCommandBuilder, VmConfig, }; use crate::app::image::{Image, ImageInfo}; use crate::app::{needs_swtpm, GpuConfig, GpuSpec, Manifest, PortMapping, VmVolume, VmWorkDir}; @@ -1289,6 +1311,19 @@ mod tests { ); } + #[test] + fn amd_sev_snp_guest_arg_enables_secure_tsc_on_request() { + let params = AmdSevSnpLaunchParams { + cbitpos: 51, + reduced_phys_bits: 1, + }; + assert_eq!( + amd_sev_snp_guest_arg("aa", params, false), + "sev-snp-guest,id=sev0,policy=0x30000,sev-device=/dev/sev,kernel-hashes=on,host-data=aa,cbitpos=51,reduced-phys-bits=1" + ); + assert!(amd_sev_snp_guest_arg("aa", params, true).ends_with(",secure-tsc=on")); + } + #[test] fn amd_sev_snp_qmp_capabilities_extracts_launch_params() { let stdout = br#"{"QMP":{"version":{"qemu":{"major":10,"minor":0,"micro":2}}}} @@ -1536,6 +1571,7 @@ mod tests { tdx_mr_config_id: None, snp_host_data: None, snp_launch_params: None, + snp_secure_tsc: false, }; (config, vm, prepared) } diff --git a/dstack/vmm/src/one_shot.rs b/dstack/vmm/src/one_shot.rs index 6eafeeab6..9b494d092 100644 --- a/dstack/vmm/src/one_shot.rs +++ b/dstack/vmm/src/one_shot.rs @@ -249,7 +249,7 @@ Compose file content (first 200 chars): &manifest, &compose_hash, mr_config, - app_compose.requirements.as_ref(), + Some(&app_compose), )?; let sys_config_path = vm_work_dir.shared_dir().join(".sys-config.json"); fs_err::write(&sys_config_path, &sys_config_str).context("Failed to write sys config")?; diff --git a/os/mkosi/components/kernel/kernel-build.sh b/os/mkosi/components/kernel/kernel-build.sh index d21c16442..a32263b3d 100755 --- a/os/mkosi/components/kernel/kernel-build.sh +++ b/os/mkosi/components/kernel/kernel-build.sh @@ -67,7 +67,8 @@ for patch in \ "$ROOT/os/yocto/layers/meta-dstack/recipes-kernel/linux/files/0013-ovl-handle-idmapped-mounts-in-setattr.patch" \ "$ROOT/os/yocto/layers/meta-dstack/recipes-kernel/linux/files/0014-ovl-handle-idmapped-mounts-in-getattr.patch" \ "$ROOT/os/yocto/layers/meta-dstack/recipes-kernel/linux/files/0015-ovl-handle-idmapped-mounts-in-set-acl.patch" \ - "$ROOT/os/yocto/layers/meta-dstack/recipes-kernel/linux/files/0016-ovl-allow-idmapping-overlay-mounts.patch"; do + "$ROOT/os/yocto/layers/meta-dstack/recipes-kernel/linux/files/0016-ovl-allow-idmapping-overlay-mounts.patch" \ + "$MKOSI_DIR/components/kernel/patches/0001-x86-sev-expose-secure-tsc-status-in-sysfs.patch"; do patch -d "$src" -p1 --fuzz=0 < "$patch" done diff --git a/os/mkosi/components/kernel/kernel.sh b/os/mkosi/components/kernel/kernel.sh index 98ebe592c..a5e8de77e 100644 --- a/os/mkosi/components/kernel/kernel.sh +++ b/os/mkosi/components/kernel/kernel.sh @@ -23,7 +23,8 @@ component_cache_key() { "$ROOT/os/yocto/layers/meta-dstack/recipes-kernel/linux/files/0013-ovl-handle-idmapped-mounts-in-setattr.patch" \ "$ROOT/os/yocto/layers/meta-dstack/recipes-kernel/linux/files/0014-ovl-handle-idmapped-mounts-in-getattr.patch" \ "$ROOT/os/yocto/layers/meta-dstack/recipes-kernel/linux/files/0015-ovl-handle-idmapped-mounts-in-set-acl.patch" \ - "$ROOT/os/yocto/layers/meta-dstack/recipes-kernel/linux/files/0016-ovl-allow-idmapping-overlay-mounts.patch" + "$ROOT/os/yocto/layers/meta-dstack/recipes-kernel/linux/files/0016-ovl-allow-idmapping-overlay-mounts.patch" \ + "$COMPONENT_PATH/patches/0001-x86-sev-expose-secure-tsc-status-in-sysfs.patch" key_tools gcc ld make pahole key_packages binutils dwarves bc bison flex libssl-dev libelf-dev } diff --git a/os/mkosi/components/kernel/patches/0001-x86-sev-expose-secure-tsc-status-in-sysfs.patch b/os/mkosi/components/kernel/patches/0001-x86-sev-expose-secure-tsc-status-in-sysfs.patch new file mode 100644 index 000000000..c9da6d894 --- /dev/null +++ b/os/mkosi/components/kernel/patches/0001-x86-sev-expose-secure-tsc-status-in-sysfs.patch @@ -0,0 +1,34 @@ +From: Kevin Wang +Subject: [PATCH] x86/sev: expose Secure TSC status in sysfs + +Userspace has no way to tell whether an SEV-SNP guest runs with Secure +TSC: CPUID only says the CPU supports it, and the SEV_STATUS MSR needs +the msr driver. Add /sys/devices/system/cpu/sev/secure_tsc next to +vmpl, so dstack can refuse secure_time when the hypervisor still +controls the guest TSC. + +Upstream-Status: Inappropriate [dstack specific] +Signed-off-by: Kevin Wang +--- +--- a/arch/x86/coco/sev/core.c ++++ b/arch/x86/coco/sev/core.c +@@ -1431,10 +1431,19 @@ static ssize_t vmpl_show(struct kobject + return sysfs_emit(buf, "%d\n", snp_vmpl); + } + ++static ssize_t secure_tsc_show(struct kobject *kobj, ++ struct kobj_attribute *attr, char *buf) ++{ ++ return sysfs_emit(buf, "%d\n", ++ cc_platform_has(CC_ATTR_GUEST_SNP_SECURE_TSC)); ++} ++ + static struct kobj_attribute vmpl_attr = __ATTR_RO(vmpl); ++static struct kobj_attribute secure_tsc_attr = __ATTR_RO(secure_tsc); + + static struct attribute *vmpl_attrs[] = { + &vmpl_attr.attr, ++ &secure_tsc_attr.attr, + NULL + }; +