Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion docs/design-and-hardening-decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
43 changes: 27 additions & 16 deletions dstack/dstack-mr/src/sev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand All @@ -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)]
Expand Down Expand Up @@ -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
);
}
Expand Down Expand Up @@ -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 {
Expand All @@ -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]
Expand Down
30 changes: 30 additions & 0 deletions dstack/dstack-util/src/system_setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down
60 changes: 45 additions & 15 deletions dstack/vmm/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down Expand Up @@ -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")?;
Expand Down Expand Up @@ -2146,7 +2147,7 @@ pub(crate) fn make_sys_config(
manifest: &Manifest,
compose_hash: &str,
mr_config: Option<String>,
requirements: Option<&dstack_types::Requirements>,
app_compose: Option<&AppCompose>,
) -> Result<String> {
let image_path = cfg.image.path.join(&manifest.image);
let image = Image::load(image_path).context("Failed to load image info")?;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -2274,8 +2275,9 @@ fn make_vm_config(
image: &Image,
_compose_hash: &str,
mr_config: Option<String>,
requirements: Option<&dstack_types::Requirements>,
app_compose: Option<&AppCompose>,
) -> Result<serde_json::Value> {
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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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());
Expand All @@ -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");
Expand Down Expand Up @@ -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)?;
Expand Down
Loading
Loading