From 03effbee2b0e912697f0164e6a3d2b2ef3297a6e Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Tue, 1 Dec 2026 01:22:50 -0800 Subject: [PATCH 1/2] feat(auth-eth): let apps restrict the OS images they boot on Signed-off-by: Kevin Wang --- CHANGELOG.md | 7 ++ docs/app-key-epochs.md | 12 ++- docs/onchain-governance.md | 7 +- dstack/kms/auth-eth/contracts/DstackApp.sol | 55 ++++++++++- dstack/kms/auth-eth/script/Manage.s.sol | 36 +++++++ dstack/kms/auth-eth/script/Query.s.sol | 1 + dstack/kms/auth-eth/script/README.md | 13 +++ dstack/kms/auth-eth/test/DstackApp.t.sol | 96 +++++++++++++++++++ dstack/kms/auth-eth/test/DstackKms.t.sol | 31 ++++++ dstack/kms/auth-eth/test/EventAudit.t.sol | 7 ++ dstack/kms/auth-eth/test/ManageScript.t.sol | 25 +++++ .../auth-eth/test/UpgradesWithPlugin.t.sol | 19 ++++ 12 files changed, 301 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 77fbffeaf..d43ab5c14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,13 @@ 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. - **`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 5cf3b052b..c2900701f 100644 --- a/docs/app-key-epochs.md +++ b/docs/app-key-epochs.md @@ -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. diff --git a/docs/onchain-governance.md b/docs/onchain-governance.md index d9ff879a3..66e8cfe94 100644 --- a/docs/onchain-governance.md +++ b/docs/onchain-governance.md @@ -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 | @@ -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 | diff --git a/dstack/kms/auth-eth/contracts/DstackApp.sol b/dstack/kms/auth-eth/contracts/DstackApp.sol index b484214d0..eaf4e4e9b 100644 --- a/dstack/kms/auth-eth/contracts/DstackApp.sol +++ b/dstack/kms/auth-eth/contracts/DstackApp.sol @@ -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. @@ -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); @@ -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. @@ -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; @@ -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"); } @@ -434,5 +487,5 @@ contract DstackApp is } // Add storage gap for upgradeable contracts - uint256[42] private __gap; + uint256[40] private __gap; } diff --git a/dstack/kms/auth-eth/script/Manage.s.sol b/dstack/kms/auth-eth/script/Manage.s.sol index 75e64be37..6d62ea69c 100644 --- a/dstack/kms/auth-eth/script/Manage.s.sol +++ b/dstack/kms/auth-eth/script/Manage.s.sol @@ -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"); diff --git a/dstack/kms/auth-eth/script/Query.s.sol b/dstack/kms/auth-eth/script/Query.s.sol index 9e35ba376..2acac3a80 100644 --- a/dstack/kms/auth-eth/script/Query.s.sol +++ b/dstack/kms/auth-eth/script/Query.s.sol @@ -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; diff --git a/dstack/kms/auth-eth/script/README.md b/dstack/kms/auth-eth/script/README.md index 90e7b5db7..75d5cce5b 100644 --- a/dstack/kms/auth-eth/script/README.md +++ b/dstack/kms/auth-eth/script/README.md @@ -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 diff --git a/dstack/kms/auth-eth/test/DstackApp.t.sol b/dstack/kms/auth-eth/test/DstackApp.t.sol index 2f797718d..ebacee8b0 100644 --- a/dstack/kms/auth-eth/test/DstackApp.t.sol +++ b/dstack/kms/auth-eth/test/DstackApp.t.sol @@ -548,6 +548,102 @@ contract DstackAppTest is Test { vm.stopPrank(); } + function test_OsImagesAreUnrestrictedUntilRestrictedAndCoverEveryEpoch() public { + IAppAuth.AppInfo memory info = epochInfo(); + info.osImageHash = bytes32(uint256(0x1a)); + bytes32 otherImage = bytes32(uint256(0x1b)); + vm.startPrank(owner); + app.addComposeHashAtEpochs(0, 1, info.composeHash); + app.addDeviceAtEpochs(0, 1, info.deviceId); + vm.stopPrank(); + AuthorizationRequest memory request = appRequest(info, OptionalUint256(true, 0), keccak256("app_get_key")); + // By default any image the KMS admits passes. + assertTrue(app.allowAnyOsImage()); + assertTrue(app.authorizeApp(request).authorized); + + vm.startPrank(owner); + vm.expectRevert("invalid OS image hash"); + app.addOsImageHashAtEpoch(0, bytes32(0)); + app.addOsImageHashAtEpoch(0, otherImage); + // The list applies only once the policy is restricted. + assertTrue(app.authorizeApp(request).authorized); + app.setAllowAnyOsImage(false); + vm.stopPrank(); + assertFalse(app.allowAnyOsImage()); + assertEq(app.authorizeApp(request).rejectionReason, "OS image not allowed"); + (bool allowed, string memory reason) = app.isAppAllowed(info); + assertFalse(allowed); + assertEq(reason, "OS image not allowed"); + + vm.prank(owner); + app.addOsImageHashAtEpoch(0, info.osImageHash); + assertTrue(app.allowedOsImagesAtEpoch(0, info.osImageHash)); + assertTrue(app.authorizeApp(request).authorized); + (allowed,) = app.isAppAllowed(info); + assertTrue(allowed); + + // Allowing any image lifts the restriction at every epoch. + vm.startPrank(owner); + app.advanceAppEpoch(0); + request.requestedAppEpoch = OptionalUint256(true, 1); + assertEq(app.authorizeApp(request).rejectionReason, "OS image not allowed"); + app.setAllowAnyOsImage(true); + assertTrue(app.authorizeApp(request).authorized); + vm.stopPrank(); + + vm.startPrank(user); + bytes memory unauthorized = abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, user); + vm.expectRevert(unauthorized); + app.setAllowAnyOsImage(false); + vm.expectRevert(unauthorized); + app.addOsImageHashAtEpoch(0, otherImage); + vm.expectRevert(unauthorized); + app.addOsImageHashAtEpochs(0, 1, otherImage); + vm.expectRevert(unauthorized); + app.removeOsImageHashAtEpoch(0, otherImage); + vm.expectRevert(unauthorized); + app.removeOsImageHashAtEpochs(0, 1, otherImage); + vm.stopPrank(); + } + + function test_OsImageRowsAreIndependentPerAppEpoch() public { + IAppAuth.AppInfo memory info = epochInfo(); + info.osImageHash = bytes32(uint256(0x1a)); + vm.startPrank(owner); + app.addComposeHashAtEpochs(0, 1, info.composeHash); + app.addDeviceAtEpochs(0, 1, info.deviceId); + app.setAllowAnyOsImage(false); + app.addOsImageHashAtEpoch(0, info.osImageHash); + app.advanceAppEpoch(0); + vm.stopPrank(); + + (bool allowed, string memory reason) = authorizeAt(info, 1, keccak256("app_get_key")); + assertFalse(allowed, "a new app epoch starts with an empty row"); + assertEq(reason, "OS image not allowed"); + (allowed,) = authorizeAt(info, 0, keccak256("app_get_key")); + assertTrue(allowed); + + vm.startPrank(owner); + // The next epoch's row can be prepared before advancing. + app.addOsImageHashAtEpochs(1, 2, info.osImageHash); + vm.expectRevert("Unknown app epoch"); + app.addOsImageHashAtEpoch(3, info.osImageHash); + app.removeOsImageHashAtEpoch(0, info.osImageHash); + vm.stopPrank(); + assertFalse(app.allowedOsImagesAtEpoch(0, info.osImageHash)); + assertTrue(app.allowedOsImagesAtEpoch(2, info.osImageHash)); + (allowed,) = authorizeAt(info, 0, keccak256("app_get_key")); + assertFalse(allowed); + (allowed,) = authorizeAt(info, 1, keccak256("app_get_key")); + assertTrue(allowed, "revoking epoch zero must not revoke epoch one"); + + // Removing rows 0 through the current epoch revokes the image everywhere. + vm.prank(owner); + app.removeOsImageHashAtEpochs(0, 1, info.osImageHash); + (allowed,) = authorizeAt(info, 1, keccak256("app_get_key")); + assertFalse(allowed); + } + function test_AuthorizeAppOwnsOperationScopeAndAppEpoch() public { IAppAuth.AppInfo memory info = epochInfo(); vm.startPrank(owner); diff --git a/dstack/kms/auth-eth/test/DstackKms.t.sol b/dstack/kms/auth-eth/test/DstackKms.t.sol index ce580a30b..1fda0e002 100644 --- a/dstack/kms/auth-eth/test/DstackKms.t.sol +++ b/dstack/kms/auth-eth/test/DstackKms.t.sol @@ -592,6 +592,37 @@ contract DstackKmsTest is Test { kms.setAllowAnyTeeVariant(false); } + function test_AppOsImagesNarrowTheKmsAllowlist() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(0)); + bytes32 otherImage = bytes32(uint256(222)); + vm.startPrank(owner); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "https://example.com/epoch-0"); + kms.addOsImageHashAtEpochs(0, 0, info.osImageHash); + info.appId = kms.deployAndRegisterApp(user, false, true, info.deviceId, info.composeHash); + vm.stopPrank(); + DstackApp app = DstackApp(info.appId); + assertTrue(authorize(info, false).authorized); + + // An app listing an image the KMS does not admit cannot widen the KMS policy. + vm.startPrank(user); + app.addOsImageHashAtEpoch(0, otherImage); + app.setAllowAnyOsImage(false); + vm.stopPrank(); + assertEq(authorize(info, false).rejectionReason, "OS image not allowed"); + (bool allowed, string memory reason) = kms.isAppAllowed(info); + assertFalse(allowed); + assertEq(reason, "OS image not allowed"); + info.osImageHash = otherImage; + assertEq(authorize(info, false).rejectionReason, "OS image is not allowed"); + + info.osImageHash = bytes32(uint256(111)); + vm.prank(user); + app.addOsImageHashAtEpoch(0, info.osImageHash); + assertTrue(authorize(info, false).authorized); + (allowed,) = kms.isAppAllowed(info); + assertTrue(allowed); + } + function test_AuthorizationOperationsFailClosedAndBootstrapBeforeRegistration() public { IAppAuth.AppInfo memory info = authorizationInfo(address(kms)); vm.startPrank(owner); diff --git a/dstack/kms/auth-eth/test/EventAudit.t.sol b/dstack/kms/auth-eth/test/EventAudit.t.sol index 1fd48a8bb..99c6d7d43 100644 --- a/dstack/kms/auth-eth/test/EventAudit.t.sol +++ b/dstack/kms/auth-eth/test/EventAudit.t.sol @@ -80,12 +80,15 @@ contract EventAuditTest is Test { function test_AppPolicyEventsReconstructQueriedState() public { bytes32 composeHash = keccak256("audit-compose"); bytes32 device = keccak256("audit-app-device"); + bytes32 image = keccak256("audit-app-image"); vm.recordLogs(); vm.startPrank(owner); app.addComposeHashAtEpoch(0, composeHash); app.addDeviceAtEpoch(0, device); app.setAllowAnyDevice(true); + app.addOsImageHashAtEpoch(0, image); + app.setAllowAnyOsImage(false); app.setRequireTcbUpToDate(true); app.removeDeviceAtEpoch(0, device); app.disableUpgrades(); @@ -95,6 +98,8 @@ contract EventAuditTest is Test { _assertAudit(logs, owner, "compose-hash", composeHash, true); _assertAudit(logs, owner, "device", device, true); _assertAudit(logs, owner, "allow-any-device", bytes32(0), true); + _assertAudit(logs, owner, "os-image", image, true); + _assertAudit(logs, owner, "allow-any-os-image", bytes32(0), false); _assertAudit(logs, owner, "require-tcb-up-to-date", bytes32(0), true); _assertAudit(logs, owner, "device", device, false); _assertAudit(logs, owner, "upgrades-disabled", bytes32(0), true); @@ -102,6 +107,8 @@ contract EventAuditTest is Test { assertTrue(app.allowedComposeHashes(composeHash)); assertFalse(app.allowedDeviceIds(device)); assertTrue(app.allowAnyDevice()); + assertTrue(app.allowedOsImagesAtEpoch(0, image)); + assertFalse(app.allowAnyOsImage()); assertTrue(app.requireTcbUpToDate()); } diff --git a/dstack/kms/auth-eth/test/ManageScript.t.sol b/dstack/kms/auth-eth/test/ManageScript.t.sol index 1b19bb0fd..883a23288 100644 --- a/dstack/kms/auth-eth/test/ManageScript.t.sol +++ b/dstack/kms/auth-eth/test/ManageScript.t.sol @@ -77,5 +77,30 @@ contract ManageScriptTest is Test { teeScript.setUp(); vm.expectRevert(bytes("this app predates TEE variant policies")); teeScript.run(); + + // App OS image rows take app epochs, and exist only in current apps; the + // switch covers every epoch, so it refuses one. + bytes32 imageHash = bytes32(uint256(0x1a)); + vm.setEnv("OS_IMAGE_HASH", vm.toString(imageHash)); + AddAppOsImage imageScript = new AddAppOsImage(); + imageScript.setUp(); + vm.expectRevert(bytes("this app predates OS image policies")); + imageScript.run(); + vm.setEnv("APP_CONTRACT_ADDR", vm.toString(current)); + imageScript = new AddAppOsImage(); + imageScript.setUp(); + imageScript.run(); + assertTrue(DstackApp(current).allowedOsImagesAtEpoch(0, imageHash)); + SetAllowAnyAppOsImage anyImageScript = new SetAllowAnyAppOsImage(); + anyImageScript.setUp(); + vm.setEnv("ALLOW_ANY_OS_IMAGE", "false"); + vm.expectRevert( + bytes("allowAnyOsImage covers every app epoch: unset APP_EPOCH, FROM_APP_EPOCH and TO_APP_EPOCH") + ); + anyImageScript.run(); + RemoveAppOsImage removeImageScript = new RemoveAppOsImage(); + removeImageScript.setUp(); + removeImageScript.run(); + assertFalse(DstackApp(current).allowedOsImagesAtEpoch(0, imageHash)); } } diff --git a/dstack/kms/auth-eth/test/UpgradesWithPlugin.t.sol b/dstack/kms/auth-eth/test/UpgradesWithPlugin.t.sol index a2ab3860a..140373293 100644 --- a/dstack/kms/auth-eth/test/UpgradesWithPlugin.t.sol +++ b/dstack/kms/auth-eth/test/UpgradesWithPlugin.t.sol @@ -61,6 +61,25 @@ contract UpgradesWithPluginTest is Test { assertEq(app.currentAppEpoch(), 0); assertTrue(app.allowedComposeHashesAtEpoch(0, composeHash)); assertTrue(app.allowedDeviceIdsAtEpoch(0, deviceId)); + + // The upgraded app keeps admitting any OS image until its owner restricts it. + IAppAuth.AppInfo memory info; + info.appId = proxy; + info.composeHash = composeHash; + info.deviceId = deviceId; + info.osImageHash = bytes32(uint256(0x1a)); + info.tcbStatus = "UpToDate"; + assertTrue(app.allowAnyOsImage()); + (bool allowed,) = app.isAppAllowed(info); + assertTrue(allowed); + vm.startPrank(owner); + app.setAllowAnyOsImage(false); + (allowed,) = app.isAppAllowed(info); + assertFalse(allowed); + app.addOsImageHashAtEpoch(0, info.osImageHash); + vm.stopPrank(); + (allowed,) = app.isAppAllowed(info); + assertTrue(allowed); } function test_ReleasedKmsDeploysAppsOnceItsAppImplementationIsCurrent() public { From a1f5c91b0a92548538e66b6d3cf728d4f18c92b1 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Tue, 1 Dec 2026 01:22:50 -0800 Subject: [PATCH 2/2] feat(dstack-auth): let apps narrow the OS image allowlist Signed-off-by: Kevin Wang --- CHANGELOG.md | 1 + docs/dstack-auth-operations.md | 4 ++- dstack/crates/dstack-auth/src/main.rs | 36 +++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d43ab5c14..330d110c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `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..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` diff --git a/docs/dstack-auth-operations.md b/docs/dstack-auth-operations.md index 216f59af8..21f197ea8 100644 --- a/docs/dstack-auth-operations.md +++ b/docs/dstack-auth-operations.md @@ -116,6 +116,7 @@ Hex values are compared case-insensitively, with or without a `0x` prefix. | `apps..composeHashes` | No | Allowed compose hashes for this app | | `apps..devices` | No | Allowed device IDs for this app. Empty denies all unless `allowAnyDevice` is true. | | `apps..allowAnyDevice` | No | If true, skip the device ID check for this app | +| `apps..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..currentAppEpoch` | No | Current app key epoch (default `0`), served by `GET /app/`. 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. | @@ -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/*` diff --git a/dstack/crates/dstack-auth/src/main.rs b/dstack/crates/dstack-auth/src/main.rs index ab54b7694..2f626fd1d 100644 --- a/dstack/crates/dstack-auth/src/main.rs +++ b/dstack/crates/dstack-auth/src/main.rs @@ -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>, + /// 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>, } /// normalize a hex string for comparison: trim, drop a `0x`/`0X` prefix, @@ -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"); } @@ -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!({