Skip to content
Open
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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ 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.
- **Apps can restrict the OS images they boot on.** `DstackApp` keeps a
per-app-epoch OS image list (`addOsImageHashAtEpoch(s)`,
`removeOsImageHashAtEpoch(s)`, `allowedOsImagesAtEpoch`) that applies once
the owner calls `setAllowAnyOsImage(false)`, so an app can refuse images the
`DstackKms` allowlist still admits, such as development or vulnerable
releases. `allowAnyOsImage` is on by default and after upgrading a proxy, so
existing apps keep their decisions; the KMS allowlist applies either way.
`dstack-auth` takes the same narrowing as an optional `apps.<appId>.osImages`.
- **`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`
Expand Down
12 changes: 7 additions & 5 deletions docs/app-key-epochs.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,13 @@ Authorization checks only the selected row, with O(1) add, removal and lookup:

- `DstackKms`: OS images, KMS aggregated measurements and KMS device IDs are
indexed by **root epoch**. OS image limits also apply to app key requests.
- `DstackApp`: compose hashes and device IDs are indexed by **app epoch**. Each
required material must be allowed in the selected row. `allowAnyDevice` is a
single switch over every app epoch: which hosts may run the app is not a
property of a key generation, and a per-epoch switch could leave an older
epoch open to any host after the current one is restricted.
- `DstackApp`: compose hashes, device IDs and OS images are indexed by **app
epoch**. Each required material must be allowed in the selected row.
`allowAnyDevice` is a single switch over every app epoch: which hosts may run
the app is not a property of a key generation, and a per-epoch switch could
leave an older epoch open to any host after the current one is restricted.
`allowAnyOsImage` is likewise one switch, on by default; once off, the
selected row must also allow the OS image, on top of the `DstackKms` row.

There is no implicit access in either direction. Rotating keys starts an empty
row; approving a new row neither copies old approvals nor grants historical keys.
Expand Down
4 changes: 3 additions & 1 deletion docs/dstack-auth-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ Hex values are compared case-insensitively, with or without a `0x` prefix.
| `apps.<appId>.composeHashes` | No | Allowed compose hashes for this app |
| `apps.<appId>.devices` | No | Allowed device IDs for this app. Empty denies all unless `allowAnyDevice` is true. |
| `apps.<appId>.allowAnyDevice` | No | If true, skip the device ID check for this app |
| `apps.<appId>.osImages` | No | When set, the OS image must also be listed here, narrowing `osImages` for this app; `[]` denies every image. **Absent: any image in `osImages`.** |
| `apps.<appId>.currentAppEpoch` | No | Current app key epoch (default `0`), served by `GET /app/<appId>`. A non-zero epoch denies the legacy `/bootAuth/app` route. |
| `rootEpochs` | No | KMS root public keys of each root epoch, indexed by epoch, `[{"caPubkey": "0x...", "k256Pubkey": "0x..."}]`. Epoch 0 is the original roots. Append only. `GET /` reports the current epoch as `rootEpoch` with its chain hash as `rootEpochHash`; the last entry is reported as `latestRootEpoch`, and entries beyond `currentRootEpoch` are pending activation. |
| `currentRootEpoch` | No | Root epoch KMS instances serve (default 0). Key-issuing operations (`kms_serve`, `app_get_key`, `app_get_cert`) may request up to this epoch; KMS key handover (`kms_export_keys`, `kms_import_keys`) may request any registered epoch, so the other KMS nodes can onboard from the rotated one while the new epoch is pending. Raise it only once every KMS node holds that epoch. |
Expand All @@ -136,7 +137,8 @@ Apps (`/authorizeApp`, `/bootAuth/app`):
3. `osImageHash` must be in `osImages`
4. `appId` must exist in `apps`
5. `composeHash` must be in the app's `composeHashes`
6. `deviceId` must be in the app's `devices` unless `allowAnyDevice` is true
6. `osImageHash` must be in the app's `osImages`, if set
7. `deviceId` must be in the app's `devices` unless `allowAnyDevice` is true

KMS requests are not matched against `osImages`: `mrAggregated` already pins
the OS image measurements. The `/authorize*` endpoints and legacy `/bootAuth/*`
Expand Down
7 changes: 5 additions & 2 deletions docs/onchain-governance.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,8 @@ The central governance contract that manages OS image whitelisting, app registra

### DstackApp (Per-App Contract)

Each app has its own contract controlling which compose hashes and devices are allowed,
per app epoch. Every setter names the app epoch rows it writes: one epoch, or a range up
Each app has its own contract controlling which compose hashes, devices and OS images are
allowed, per app epoch. Every setter names the app epoch rows it writes: one epoch, or a range up
to the next epoch. Removing a value from rows `0` through the current epoch revokes it.

| Function | Description |
Expand All @@ -179,6 +179,9 @@ to the next epoch. Removing a value from rows `0` through the current epoch revo
| `removeDeviceAtEpoch(uint256,bytes32)` / `removeDeviceAtEpochs(uint256,uint256,bytes32)` | Remove a device |
| `setAllowAnyDevice(bool)` | Allow any device to run this app, at every app epoch |
| `setAllowAnyTeeVariant(bool)` / `setAllowedTeeVariants(string[])` | Allow any TEE platform, or only the listed ones (e.g. `dstack-tdx`), at every app epoch. Set the list before restricting: a restricted empty list refuses every platform |
| `addOsImageHashAtEpoch(uint256,bytes32)` / `addOsImageHashAtEpochs(uint256,uint256,bytes32)` | Allow an OS image for this app in one app epoch or a range |
| `removeOsImageHashAtEpoch(uint256,bytes32)` / `removeOsImageHashAtEpochs(uint256,uint256,bytes32)` | Remove an OS image from one app epoch or a range |
| `setAllowAnyOsImage(bool)` | Allow any OS image the `DstackKms` allows (the default), or only the app's own list, at every app epoch. The KMS allowlist applies either way, so the app list can only narrow it. Add the images before restricting: a restricted empty row refuses every image |
| `currentAppEpoch()` | The app epoch new keys are derived for |
| `isAppAllowed(AppBootInfo)` | Check if app can boot with given config (app epoch 0 only) |
| `disableUpgrades()` | Permanently disable contract upgrades |
Expand Down
36 changes: 36 additions & 0 deletions dstack/crates/dstack-auth/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,10 @@ struct AppRules {
/// when set, the app must present one of these launch ticket hashes; an
/// empty list denies everything. Absent: no ticket is needed.
launch_tickets: Option<Vec<String>>,
/// when set, the OS image must also be listed here, narrowing the global
/// `osImages`; an empty list denies everything. Absent: any image `osImages`
/// allows.
os_images: Option<Vec<String>>,
}

/// normalize a hex string for comparison: trim, drop a `0x`/`0X` prefix,
Expand Down Expand Up @@ -338,6 +342,13 @@ fn app_policy(info: &BootInfo, al: &Allowlist) -> BootResponse {
if !contains(&app.compose_hashes, &info.compose_hash) {
return deny(al, "compose hash not allowed");
}
if app
.os_images
.as_ref()
.is_some_and(|images| !contains(images, &info.os_image_hash))
{
return deny(al, "os image not allowed by the app");
}
if !device_ok(app.allow_any_device, &app.devices, &info.device_id) {
return deny(al, "device not allowed");
}
Expand Down Expand Up @@ -1258,6 +1269,31 @@ mod tests {
assert_eq!(serve.rejection_reason, "requested root epoch is not active");
}

#[test]
fn app_os_images_narrow_the_global_allowlist() {
let mut al: Allowlist = serde_json::from_value(json!({
"osImages": ["0xIMG", "0xOLD"],
"apps": {"0xApp1": {"composeHashes": ["0xHASH"], "allowAnyDevice": true, "osImages": ["0ximg", "0xOTHER"]}}
}))
.unwrap();
assert!(check_app(&boot("0xApp1", "0xHASH", "img"), &al).is_allowed);
assert_eq!(
check_app(&boot("0xApp1", "0xHASH", "0xOLD"), &al).reason,
"os image not allowed by the app"
);
// The app list cannot admit an image the global list does not.
assert_eq!(
check_app(&boot("0xApp1", "0xHASH", "0xOTHER"), &al).reason,
"os image not allowed"
);
let app = al.apps.values_mut().next().unwrap();
app.os_images = Some(vec![]);
assert!(!check_app(&boot("0xApp1", "0xHASH", "0xIMG"), &al).is_allowed);
let app = al.apps.values_mut().next().unwrap();
app.os_images = None;
assert!(check_app(&boot("0xApp1", "0xHASH", "0xOLD"), &al).is_allowed);
}

#[test]
fn launch_tickets_are_required_only_when_configured() {
let mut al: Allowlist = serde_json::from_value(json!({
Expand Down
55 changes: 54 additions & 1 deletion dstack/kms/auth-eth/contracts/DstackApp.sol
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ contract DstackApp is
// Allowed launch tickets, by sha256("dstack-launch-ticket/v1:" || ticket), at every app epoch.
EnumerableSet.Bytes32Set private _launchTickets;

// Zero-initialized as unrestricted, so proxies upgraded from before this
// policy keep admitting every OS image the KMS admits.
bool private _osImagesRestricted;
// Allowed OS images by app epoch, epoch 0 included; checked only while restricted.
mapping(uint256 => mapping(bytes32 => bool)) private _osImagesByEpoch;

event EpochPolicyChanged(bytes32 indexed policy, bytes32 indexed value, uint256 indexed epoch, bool enabled);

/// @notice Legacy material events. Epoch 0 only; for other epochs use the *AtEpoch getters and EpochPolicyChanged.
Expand All @@ -73,6 +79,7 @@ contract DstackApp is
event AllowAnyDeviceSet(bool allowAny);
event AllowAnyTeeVariantSet(bool allowAny);
event AllowedTeeVariantsSet(string[] teeVariants);
event AllowAnyOsImageSet(bool allowAny);
event RequireTcbUpToDateSet(bool requireUpToDate);
event RequireLaunchTicketSet(bool required);
event LaunchTicketAdded(bytes32 indexed ticketHash, string label);
Expand Down Expand Up @@ -188,6 +195,10 @@ contract DstackApp is
return epoch == 0 ? allowedDeviceIds[deviceId] : _deviceIdsByEpoch[epoch][deviceId];
}

function allowedOsImagesAtEpoch(uint256 epoch, bytes32 osImageHash) public view returns (bool) {
return _osImagesByEpoch[epoch][osImageHash];
}

// A request may select any app epoch up to the current one and is decided
// on that epoch's row, so revoking a value takes every row that allows it:
// 0 through currentAppEpoch.
Expand Down Expand Up @@ -273,6 +284,43 @@ contract DstackApp is
_emitPolicy("allowed-tee-variants", bytes32(uint256(mask)), true);
}

/// @notice Whether this app may boot any OS image the KMS allows, rather than only those in
/// {allowedOsImagesAtEpoch}. Covers every app epoch; the KMS allowlist applies either way.
function allowAnyOsImage() public view returns (bool) {
return !_osImagesRestricted;
}

function setAllowAnyOsImage(bool allowed) external onlyOwner {
_osImagesRestricted = !allowed;
emit AllowAnyOsImageSet(allowed);
_emitPolicy("allow-any-os-image", bytes32(0), allowed);
}

function addOsImageHashAtEpoch(uint256 epoch, bytes32 osImageHash) external onlyOwner {
require(osImageHash != bytes32(0), "invalid OS image hash");
_setOsImageHash(epoch, osImageHash, true);
}

function addOsImageHashAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 osImageHash) external onlyOwner {
require(osImageHash != bytes32(0), "invalid OS image hash");
_setAtEpochs(_setOsImageHash, fromEpoch, toEpoch, osImageHash, true);
}

function removeOsImageHashAtEpoch(uint256 epoch, bytes32 osImageHash) external onlyOwner {
_setOsImageHash(epoch, osImageHash, false);
}

function removeOsImageHashAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 osImageHash) external onlyOwner {
_setAtEpochs(_setOsImageHash, fromEpoch, toEpoch, osImageHash, false);
}

function _setOsImageHash(uint256 epoch, bytes32 osImageHash, bool allowed) private {
_requireWritableEpoch(epoch);
_osImagesByEpoch[epoch][osImageHash] = allowed;
if (epoch == 0) _emitPolicy("os-image", osImageHash, allowed);
emit EpochPolicyChanged(keccak256("os-image"), osImageHash, epoch, allowed);
}

// Set whether TCB status must be UpToDate to boot this app
function setRequireTcbUpToDate(bool _requireUpToDate) external onlyOwner {
requireTcbUpToDate = _requireUpToDate;
Expand Down Expand Up @@ -403,6 +451,11 @@ contract DstackApp is
return (false, "Device not allowed");
}

// Narrows the KMS OS image allowlist, which the KMS checks itself.
if (_osImagesRestricted && !allowedOsImagesAtEpoch(appEpoch, bootInfo.osImageHash)) {
return (false, "OS image not allowed");
}

if (!teeVariantAllowed) {
return (false, "TEE variant not allowed");
}
Expand Down Expand Up @@ -434,5 +487,5 @@ contract DstackApp is
}

// Add storage gap for upgradeable contracts
uint256[42] private __gap;
uint256[40] private __gap;
}
36 changes: 36 additions & 0 deletions dstack/kms/auth-eth/script/Manage.s.sol
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,42 @@ contract SetTeeVariants is BaseScript {
}
}

contract SetAllowAnyAppOsImage is BaseScript {
function run() external {
bool allow = vm.envBool("ALLOW_ANY_OS_IMAGE");
require(address(legacyApp()) == address(0), "this app predates OS image policies");
require(
!vm.envExists("APP_EPOCH") && !vm.envExists("FROM_APP_EPOCH") && !vm.envExists("TO_APP_EPOCH"),
"allowAnyOsImage covers every app epoch: unset APP_EPOCH, FROM_APP_EPOCH and TO_APP_EPOCH"
);
vm.broadcast(vm.envUint("PRIVATE_KEY"));
app.setAllowAnyOsImage(allow);
console.log("Set allowAnyOsImage to:", allow);
}
}

contract AddAppOsImage is BaseScript {
function run() external {
bytes32 imageHash = vm.envBytes32("OS_IMAGE_HASH");
require(address(legacyApp()) == address(0), "this app predates OS image policies");
(uint256 from, uint256 to) = appEpochs();
vm.broadcast(vm.envUint("PRIVATE_KEY"));
app.addOsImageHashAtEpochs(from, to, imageHash);
console.log("Added app OS image hash:", vm.toString(imageHash));
}
}

contract RemoveAppOsImage is BaseScript {
function run() external {
bytes32 imageHash = vm.envBytes32("OS_IMAGE_HASH");
require(address(legacyApp()) == address(0), "this app predates OS image policies");
(uint256 from, uint256 to) = appEpochs();
vm.broadcast(vm.envUint("PRIVATE_KEY"));
app.removeOsImageHashAtEpochs(from, to, imageHash);
console.log("Removed app OS image hash:", vm.toString(imageHash));
}
}

contract RequireLaunchTicket is BaseScript {
function run() external {
bool required = vm.envBool("REQUIRE_LAUNCH_TICKET");
Expand Down
1 change: 1 addition & 0 deletions dstack/kms/auth-eth/script/Query.s.sol
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ contract GetAppSettings is BaseQueryScript {
console.log("Owner:", app.owner());
console.log("Allow Any Device:", app.allowAnyDevice());
logTeeVariants(app.allowAnyTeeVariant(), app.allowedTeeVariants());
console.log("Allow Any OS Image:", app.allowAnyOsImage());

// Check implementation via storage
bytes32 implSlot = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
Expand Down
13 changes: 13 additions & 0 deletions dstack/kms/auth-eth/script/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,19 @@ KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... TEE_VARIANTS=dstack-tdx,dstack-g
forge script script/Manage.s.sol:SetTeeVariants --broadcast --rpc-url $RPC_URL
```

#### Restrict OS Images
An app admits any OS image `DstackKms` allows until `ALLOW_ANY_OS_IMAGE=false`;
then the selected app epoch row must allow the image too. Add the images first:
a restricted empty row refuses every image. The switch covers every app epoch.
```bash
KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... APP_EPOCH=0 OS_IMAGE_HASH=0x1234... \
forge script script/Manage.s.sol:AddAppOsImage --broadcast --rpc-url $RPC_URL
KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... ALLOW_ANY_OS_IMAGE=false \
forge script script/Manage.s.sol:SetAllowAnyAppOsImage --broadcast --rpc-url $RPC_URL
KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... FROM_APP_EPOCH=0 TO_APP_EPOCH=0 OS_IMAGE_HASH=0x1234... \
forge script script/Manage.s.sol:RemoveAppOsImage --broadcast --rpc-url $RPC_URL
```

#### Require Launch Tickets
The app must then present an allowed launch ticket, at every app epoch. For a new
app, deploy it without `INITIAL_COMPOSE_HASH`, require the ticket and add it, then
Expand Down
Loading
Loading