From 48fb5ce6c580a5e643954f4e779ac034ce3c856c Mon Sep 17 00:00:00 2001 From: Andrii Koropets Date: Tue, 1 Dec 2026 23:44:30 +0200 Subject: [PATCH 1/7] feat(mdm): CU-17tkuw6a8db require BitLocker per Windows host on Fleet Free Upstream requires disk encryption per team and only on Premium. A team is a tenant here, and a tenant requires encryption for some of its organizations only, so in OpenFrame mode each Windows host has its own requirement. POST and DELETE /disk_encryption/hosts set and lift it, within the pinned tenant. The fleetd notification, the key escrow and the BitLocker status follow the host. A key is accepted after the requirement is lifted, archived keys are not looked up by serial, and fleetd's last error and the time the key was stored are kept in openframe_host_disk_encryption, without the key. --- openframe/docs/README.md | 1 + openframe/docs/fork-file-manifest.md | 1 + openframe/docs/mysql-multitenancy-feature.md | 4 + openframe/docs/windows-disk-encryption.md | 62 ++++ openframe/scripts/verify.sh | 2 +- server/datastore/mysql/apple_mdm.go | 5 + server/datastore/mysql/disk_encryption.go | 11 +- server/datastore/mysql/hosts.go | 1 + server/datastore/mysql/hosts_test.go | 7 + server/datastore/mysql/microsoft_mdm.go | 4 +- ...261201000001_AddHostDiskEncryptionTable.go | 37 +++ .../migrations/openframe/migration_test.go | 1 + .../openframe_windows_disk_encryption.go | 151 +++++++++ .../openframe_windows_disk_encryption_test.go | 314 ++++++++++++++++++ server/datastore/mysql/schema.sql | 12 + server/fleet/datastore.go | 10 + .../openframe_windows_disk_encryption.go | 21 ++ server/fleet/service.go | 6 + server/mock/datastore_mock.go | 36 ++ server/mock/service/service_mock.go | 12 + server/service/handler.go | 4 + server/service/hosts.go | 4 +- .../openframe_windows_disk_encryption.go | 93 ++++++ .../openframe_windows_disk_encryption_test.go | 269 +++++++++++++++ server/service/orbit.go | 19 +- 25 files changed, 1081 insertions(+), 6 deletions(-) create mode 100644 openframe/docs/windows-disk-encryption.md create mode 100644 server/datastore/mysql/migrations/openframe/20261201000001_AddHostDiskEncryptionTable.go create mode 100644 server/datastore/mysql/openframe_windows_disk_encryption.go create mode 100644 server/datastore/mysql/openframe_windows_disk_encryption_test.go create mode 100644 server/fleet/openframe_windows_disk_encryption.go create mode 100644 server/service/openframe_windows_disk_encryption.go create mode 100644 server/service/openframe_windows_disk_encryption_test.go diff --git a/openframe/docs/README.md b/openframe/docs/README.md index c2c614e4a5c..af9802e0a40 100644 --- a/openframe/docs/README.md +++ b/openframe/docs/README.md @@ -47,6 +47,7 @@ The agent has its own switch, `--openframe-mode` / `ORBIT_OPENFRAME_MODE`. | [server-private-key-kms.md](server-private-key-kms.md) | Server private key wrapped with Google Cloud KMS and stored in MySQL (`FLEET_SERVER_PRIVATE_KEY_KMS_KEY`) instead of passed in plaintext. | | [enroll-machine-identity.md](enroll-machine-identity.md) | One Fleet host per OpenFrame machine: with `FLEET_OPENFRAME_MACHINE_IDENTITY` on, agents enroll with the OpenFrame machine id and move their host to it with the node key they held, so machines sharing a hardware UUID stop overwriting each other; a second machine (another osquery instance) with the same hardware UUID refused while the owner is live, takeover log for alerting, MDM refused for a UUID shared within a team. | | [windows-wipe.md](windows-wipe.md) | `POST /hosts/{id}/wipe` wipes Windows hosts on Fleet Free, over Windows MDM (RemoteWipe CSP); refused, or cancelled before it is sent, when the hardware UUID does not identify one device; `completed_wipe` activity when the device accepts it. | +| [windows-disk-encryption.md](windows-disk-encryption.md) | BitLocker required per Windows host on Fleet Free (`POST`/`DELETE /disk_encryption/hosts`): the fleetd notification, the key and the status follow the host, not its team; archived keys are never looked up by serial. | ## Agent-side (orbit / fleetd) diff --git a/openframe/docs/fork-file-manifest.md b/openframe/docs/fork-file-manifest.md index 5301f152a67..02436afb7bd 100644 --- a/openframe/docs/fork-file-manifest.md +++ b/openframe/docs/fork-file-manifest.md @@ -175,6 +175,7 @@ and the heaviest standing rebase cost. | Agent OpenFrame mode | `orbit/cmd/orbit/orbit.go`, `orbit/cmd/orbit/openframe_identifier_test.go`, `orbit/pkg/constant/constant.go`, `orbit/pkg/osquery/osquery.go`, `orbit/pkg/osquery/openframe_command.go`, `orbit/pkg/osquery/openframe_command_test.go`, `client/orbit_client.go`, `server/fleet/api_orbit.go`, `server/fleet/orbit.go`, `server/service/orbit.go`, `server/service/orbit_client.go`, `server/service/base_client.go` | | Shared-mode MDM | instance-wide MDM flags: `server/fleet/openframe.go`, `server/datastore/mysql/app_configs.go`, `server/service/mdm.go`; instance settings and instance-config reads: `cmd/fleet/serve.go`, `server/datastore/cached_mysql/cached_mysql.go`, `server/mdm/android/service/service.go`; enrollment routes: `server/service/openframe_middleware.go`; Android enrollment: `server/mdm/android/service/pubsub.go`; tenant change: `server/datastore/mysql/{hosts,openframe}.go`; Apple OTA: `server/datastore/mysql/apple_mdm.go`; Windows profile cleanup: `server/datastore/mysql/mdm.go`; per-tenant Windows MDM: `server/fleet/{app,datastore,microsoft_mdm,openframe_windows_mdm}.go`, `server/service/{openframe_windows_mdm,orbit,microsoft_mdm,hosts,appconfig,service,openframe_middleware}.go`, `server/service/osquery_utils/{queries,queries_openframe_windows_mdm}.go`, `{cmd/fleet,server/datastore/mysql}/openframe_windows_wstep.go`, `server/datastore/mysql/{microsoft_mdm,microsoft_mdm_batched,apple_mdm,openframe_windows_mdm}.go`, `migrations/openframe/20261127000001_AddTeamIdToMdmWindowsEnrollments.go`, `server/mdm/microsoft/openframe_wstep.go`, `server/mock/datastore_mock.go`; tests: `server/datastore/mysql/{app_configs,android,apple_ota,windows_mdm}_openframe_test.go`, `server/datastore/mysql/openframe_windows_{wstep,mdm}_test.go`, `server/service/{openframe_middleware,openframe_windows_mdm}_test.go`, `server/service/osquery_utils/queries_openframe_mdm_link_test.go`, `migrations/openframe/migration_test.go`, `server/fleet/openframe_windows_mdm_test.go`, `cmd/fleet/openframe_windows_wstep_test.go`, `server/mdm/android/service/pubsub_openframe_test.go` — see [mysql-multitenancy-feature.md](mysql-multitenancy-feature.md) | | Windows wipe (`openframe/docs/windows-wipe.md`) | `server/service/{scripts,mdm,microsoft_mdm,openframe_windows_mdm,openframe_windows_wipe}.go`, `server/fleet/{datastore,microsoft_mdm,openframe_windows_wipe}.go`, `server/mock/datastore_mock.go`, `server/datastore/mysql/{microsoft_mdm,hosts,openframe_windows_wipe}.go`; tests: `server/service/openframe_windows_wipe_test.go`, `server/datastore/mysql/openframe_windows_wipe_test.go` | +| Windows disk encryption (`openframe/docs/windows-disk-encryption.md`) | `server/service/{orbit,hosts,handler,openframe_windows_disk_encryption}.go`, `server/fleet/{datastore,service,openframe_windows_disk_encryption}.go`, `server/mock/datastore_mock.go`, `server/mock/service/service_mock.go`, `server/datastore/mysql/{apple_mdm,disk_encryption,hosts,microsoft_mdm,openframe_windows_disk_encryption}.go`, `migrations/openframe/20261201000001_AddHostDiskEncryptionTable.go`, `schema.sql`; tests: `server/service/openframe_windows_disk_encryption_test.go`, `server/datastore/mysql/openframe_windows_disk_encryption_test.go`, `server/datastore/mysql/hosts_test.go`, `migrations/openframe/migration_test.go` | | Agent options kept | `cmd/fleet/serve.go` (starter-library skip under multitenancy), `server/fleet/openframe.go` (trimmed seed/fallback defaults), `server/datastore/mysql/teams_openframe_test.go`, `server/fleet/openframe_test.go` | | Agent JSON content-type | `client/orbit_client.go`, `client/device_client.go`, `orbit/cmd/fetch_cert/main.go`, `client/orbit_client_content_type_test.go` | | Orbit 401 streak across restarts | `client/orbit_client.go`, `client/orbit_reenroll_openframe.go`; tests: `client/orbit_reenroll_openframe_test.go` — see [node-key-management.md](node-key-management.md) | diff --git a/openframe/docs/mysql-multitenancy-feature.md b/openframe/docs/mysql-multitenancy-feature.md index b17b285e749..e83d2565551 100644 --- a/openframe/docs/mysql-multitenancy-feature.md +++ b/openframe/docs/mysql-multitenancy-feature.md @@ -81,6 +81,10 @@ role-authz grouping upstream; here it is a hard boundary regardless of token rol Fleet where every tenant operates as the same Admin user. - **host-assignments** (`policy_hosts`/`query_hosts`) — parent verified in team + foreign host ids dropped (pre-existing `OPENFRAME(host-assignments)` feature, extended here). +- **disk encryption** (`openframe_host_disk_encryption`): only the pinned team's Windows hosts can be required or + released, a call without a tenant is refused in shared mode, and the requirement counts only in the tenant it was set + in (`OpenframeSetHostsDiskEncryption`, `OpenframeHostDiskEncryption`). `GetHostArchivedDiskEncryptionKey` does not + fall back to the hardware serial in OpenFrame mode ([windows-disk-encryption.md](windows-disk-encryption.md)). - **teams** — `TeamLite`/`ListTeams` read fence. - **app_config** cache (`cached_mysql.go`) — cache key includes the pinned team so one tenant's config is never served to another; unpinned keeps the constant key. diff --git a/openframe/docs/windows-disk-encryption.md b/openframe/docs/windows-disk-encryption.md new file mode 100644 index 00000000000..acdc5ddaa60 --- /dev/null +++ b/openframe/docs/windows-disk-encryption.md @@ -0,0 +1,62 @@ +# BitLocker required per host on Fleet Free (OpenFrame) + +Upstream requires disk encryption per team and only on Premium. In the fork a team is a tenant, and a tenant +requires encryption for some of its customers only, so each Windows host has its own requirement. + +Only in OpenFrame mode (`FLEET_OPENFRAME_MODE`) or shared mode; otherwise everything below is upstream's. macOS +and Linux keep the team's setting, except the archived keys (below). + +## Requirement + +- `POST /api/_version_/fleet/disk_encryption/hosts` with `{"host_ids": [1, 2]}` requires the hosts to encrypt; + `DELETE` on the same path with the same body lifts that. Both answer `{"hosts": }`, the number of hosts they + applied to, and can be repeated. Permission is the one for upstream's `POST /disk_encryption`, on the pinned team. +- Hosts of another tenant, hosts that don't exist and hosts that don't run Windows are dropped. In shared mode a + call without a tenant is refused. +- `openframe_host_disk_encryption` (`migrations/openframe/20261201000001_AddHostDiskEncryptionTable.go`) keeps a row + per host that was ever required, with the tenant it was required in. Lifting keeps the row with `required = 0`. + A host moved to another tenant is not required there, and starts there without the old tenant's error and key + time; deleting the host deletes the row. + +## Result + +The same row keeps what fleetd reported, without the key, so that the table can be captured by the CDC connector and +`host_disk_encryption_keys`, which holds the keys, never has to be: + +- `client_error`: fleetd's last error, empty when there is none. A failing fleetd reports it again every config cycle; + a repeated error changes nothing in the row. Cleared where upstream deletes the key row: MDM re-enrollment and team + change. Lifting the requirement keeps it. +- `key_stored_at`: when the host's last key was stored, NULL before the first. It stays after an error, MDM + re-enrollment or lifting: Fleet still returns the key from its archive. + +## What follows it + +- **fleetd** (`setDiskEncryptionNotifications`): a required host that is in MDM gets `EnforceBitLockerEncryption` + under upstream's conditions; any other host does not, whatever the team's setting is. Lifting never turns + BitLocker off. +- **The key** (`SetOrUpdateDiskEncryptionKey`): stored for a host that was ever required, also after the requirement + was lifted. On a drive that was already encrypted fleetd removes the other recovery keys before it sends the new + one, so a dropped key would leave none that opens the drive. +- **The status** (`GetMDMWindowsBitLockerStatus`, `os_settings.disk_encryption` in host details): shown on Free for a + required host, empty for any other. No startup PIN is ever required. + +`GET /hosts/{id}/encryption_key` is upstream's. The host is fenced (`HostLite`), and in shared mode the key is +decrypted with the pair of the host's tenant. + +## Archived keys + +Without an archived key of the host itself, upstream returns one by hardware serial. In OpenFrame mode it does not, +on any platform: the serial can be another machine's, of the tenant or of another one. + +## Known limits + +- fleetd sends again a key that Fleet did not take only while the host is told to encrypt. A key that failed to + reach Fleet is lost if the requirement is lifted before the next try. +- The result is written after the key, not with it. Its write is retried on a deadlock or a lock timeout; if it + fails, `key_stored_at` stays as it was until the next key. +- Reading a key needs Windows MDM to be on for the tenant (`VerifyMDMWindowsConfigured`), as upstream. + +## Tests + +- `server/service/openframe_windows_disk_encryption_test.go` +- `server/datastore/mysql/openframe_windows_disk_encryption_test.go` (`MYSQL_TEST=1`) diff --git a/openframe/scripts/verify.sh b/openframe/scripts/verify.sh index a5c9248bbf2..da7439345af 100755 --- a/openframe/scripts/verify.sh +++ b/openframe/scripts/verify.sh @@ -46,7 +46,7 @@ rm -f vet.err # 3. Marker presence: if a merge silently dropped fork code, its OPENFRAME markers # vanish too. A slug dropping to zero is a red flag worth a human look. step "OPENFRAME marker presence (dropped-fork-code detector)" -for slug in host-assignments managed-policies managed-queries redis-key-prefix redis-seed-nodes query-results-ttl osquery-host-id agent-openframe-mode agent-json-content-type agent-skip-setup-experience agent-host-info-diagnostics agent-verify-server-tls migration-race server-private-key-kms enroll-machine-identity; do +for slug in host-assignments managed-policies managed-queries redis-key-prefix redis-seed-nodes query-results-ttl osquery-host-id agent-openframe-mode agent-json-content-type agent-skip-setup-experience agent-host-info-diagnostics agent-verify-server-tls migration-race server-private-key-kms enroll-machine-identity windows-disk-encryption; do n=$(grep -rIl "OPENFRAME($slug" --include='*.go' --include='*.yaml' --include='*.tpl' . 2>/dev/null | wc -l | tr -d ' ') if [ "$n" -gt 0 ]; then ok "$slug — present in $n file(s)"; else bad "$slug — NO markers found (fork code may have been dropped in the merge)"; fi done diff --git a/server/datastore/mysql/apple_mdm.go b/server/datastore/mysql/apple_mdm.go index 66f5e5af6b8..adfb06b8fa3 100644 --- a/server/datastore/mysql/apple_mdm.go +++ b/server/datastore/mysql/apple_mdm.go @@ -4424,6 +4424,11 @@ func (ds *Datastore) MDMResetEnrollment(ctx context.Context, hostUUID string, sc if err != nil { return ctxerr.Wrap(ctx, err, "resetting disk encryption key information for host") } + // >>> OPENFRAME(windows-disk-encryption): the error goes with the key — openframe/docs/windows-disk-encryption.md + if err := openframeClearDiskEncryptionErrors(ctx, tx, []uint{host.ID}); err != nil { + return err + } + // <<< OPENFRAME(windows-disk-encryption) // Clear MDM-delivered certs for the same re-enroll-without-CheckOut // cases (local wipe, restore from backup, manual MDM profile removal). diff --git a/server/datastore/mysql/disk_encryption.go b/server/datastore/mysql/disk_encryption.go index bc7a87de04d..3b8d1d27b1b 100644 --- a/server/datastore/mysql/disk_encryption.go +++ b/server/datastore/mysql/disk_encryption.go @@ -317,7 +317,9 @@ LIMIT 1` var key fleet.HostArchivedDiskEncryptionKey err := sqlx.GetContext(ctx, ds.reader(ctx), &key, fmt.Sprintf(sqlFmt, `WHERE host_id = ?`), host.ID) - if err == sql.ErrNoRows && host.HardwareSerial != "" { + // >>> OPENFRAME(windows-disk-encryption): in OpenFrame mode a key is never looked up by serial: it can be another machine's, of any tenant — openframe/docs/windows-disk-encryption.md + if err == sql.ErrNoRows && host.HardwareSerial != "" && !openframeWindowsDiskEncryptionEnabled(ctx) { + // <<< OPENFRAME(windows-disk-encryption) // If we didn't find a key by host ID, try to find it by hardware serial. ds.logger.DebugContext(ctx, "get archived disk encryption key by host serial", "serial", host.HardwareSerial, "host_id", host.ID) err = sqlx.GetContext(ctx, ds.reader(ctx), &key, fmt.Sprintf(sqlFmt, `WHERE hardware_serial = ?`), host.HardwareSerial) @@ -380,5 +382,10 @@ func bulkDeleteHostDiskEncryptionKeysDB(ctx context.Context, tx sqlx.ExtContext, } _, err = tx.ExecContext(ctx, deleteStmt, deleteArgs...) - return err + // >>> OPENFRAME(windows-disk-encryption): the error goes with the key — openframe/docs/windows-disk-encryption.md + if err != nil { + return err + } + return openframeClearDiskEncryptionErrors(ctx, tx, hostIDs) + // <<< OPENFRAME(windows-disk-encryption) } diff --git a/server/datastore/mysql/hosts.go b/server/datastore/mysql/hosts.go index 139380f2785..9c47c0abbd6 100644 --- a/server/datastore/mysql/hosts.go +++ b/server/datastore/mysql/hosts.go @@ -587,6 +587,7 @@ var hostRefs = []string{ "host_disks", "host_updates", "host_disk_encryption_keys", + "openframe_host_disk_encryption", // OPENFRAME(windows-disk-encryption) "host_software_installed_paths", "host_software_windows_details", // OPENFRAME(software-windows-details) "query_results", diff --git a/server/datastore/mysql/hosts_test.go b/server/datastore/mysql/hosts_test.go index 0758d5020f7..8adce017325 100644 --- a/server/datastore/mysql/hosts_test.go +++ b/server/datastore/mysql/hosts_test.go @@ -9400,6 +9400,13 @@ func testHostsDeleteHosts(t *testing.T, ds *Datastore) { Username: "test-user", }}, fleet.HostCertificateOriginOsquery)) + // OPENFRAME(windows-disk-encryption) + _, err = ds.writer(context.Background()).Exec(` + INSERT INTO openframe_host_disk_encryption (host_id, team_id, required) + VALUES (?, ?, 1); + `, host.ID, team.ID) + require.NoError(t, err) + // create an android device from this host deviceID := strings.ReplaceAll(uuid.NewString(), "-", "") _, err = ds.writer(context.Background()).Exec(` diff --git a/server/datastore/mysql/microsoft_mdm.go b/server/datastore/mysql/microsoft_mdm.go index df6222b4693..53d62fa8e6c 100644 --- a/server/datastore/mysql/microsoft_mdm.go +++ b/server/datastore/mysql/microsoft_mdm.go @@ -1519,7 +1519,9 @@ func (ds *Datastore) GetMDMWindowsBitLockerStatus(ctx context.Context, host *fle return nil, nil } - diskEncryptionConfig, err := ds.GetConfigEnableDiskEncryption(ctx, host.TeamID) + // >>> OPENFRAME(windows-disk-encryption): in OpenFrame mode the host's own requirement, not its team's — openframe/docs/windows-disk-encryption.md + diskEncryptionConfig, err := ds.openframeDiskEncryptionConfig(ctx, host) + // <<< OPENFRAME(windows-disk-encryption) if err != nil { return nil, err } diff --git a/server/datastore/mysql/migrations/openframe/20261201000001_AddHostDiskEncryptionTable.go b/server/datastore/mysql/migrations/openframe/20261201000001_AddHostDiskEncryptionTable.go new file mode 100644 index 00000000000..f8afcb4184f --- /dev/null +++ b/server/datastore/mysql/migrations/openframe/20261201000001_AddHostDiskEncryptionTable.go @@ -0,0 +1,37 @@ +package openframe + +import ( + "database/sql" + "fmt" +) + +func init() { + MigrationClient.AddMigration(Up_20261201000001, Down_20261201000001) +} + +// Up_20261201000001 adds `openframe_host_disk_encryption`: the Windows hosts OpenFrame has ever required to encrypt, and +// whether it still does. A row stays when the requirement is lifted, so that a key on its way is accepted. `team_id` is +// the host's tenant when the row was written: a row does not follow the host to another tenant. `client_error` and +// `key_stored_at` repeat what host_disk_encryption_keys knows without the key, so that this table can be captured by the +// CDC connector and that one never has to be. See openframe/docs/windows-disk-encryption.md. +// +// Idempotent. +func Up_20261201000001(tx *sql.Tx) error { + if _, err := tx.Exec(` +CREATE TABLE IF NOT EXISTS openframe_host_disk_encryption ( + host_id INT UNSIGNED NOT NULL, + team_id INT UNSIGNED DEFAULT NULL, + required TINYINT(1) NOT NULL, + client_error VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + key_stored_at TIMESTAMP(6) NULL DEFAULT NULL, + updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + PRIMARY KEY (host_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`); err != nil { + return fmt.Errorf("creating openframe_host_disk_encryption: %w", err) + } + return nil +} + +func Down_20261201000001(tx *sql.Tx) error { + return nil +} diff --git a/server/datastore/mysql/migrations/openframe/migration_test.go b/server/datastore/mysql/migrations/openframe/migration_test.go index 27d19aa2564..510ad329626 100644 --- a/server/datastore/mysql/migrations/openframe/migration_test.go +++ b/server/datastore/mysql/migrations/openframe/migration_test.go @@ -35,6 +35,7 @@ func TestAllOpenframeMigrationsRegistered(t *testing.T) { 20261123000001, // WidenSoftwareCveId 20261123000002, // AddHostEnrollOwnersTable 20261127000001, // AddTeamIdToMdmWindowsEnrollments + 20261201000001, // AddHostDiskEncryptionTable } var got []int64 diff --git a/server/datastore/mysql/openframe_windows_disk_encryption.go b/server/datastore/mysql/openframe_windows_disk_encryption.go new file mode 100644 index 00000000000..75382585f4d --- /dev/null +++ b/server/datastore/mysql/openframe_windows_disk_encryption.go @@ -0,0 +1,151 @@ +// >>> OPENFRAME(windows-disk-encryption): BitLocker required per host on Fleet Free — openframe/docs/windows-disk-encryption.md + +package mysql + +import ( + "context" + "database/sql" + "errors" + "slices" + "strings" + + "github.com/fleetdm/fleet/v4/server/contexts/ctxerr" + "github.com/fleetdm/fleet/v4/server/fleet" + "github.com/jmoiron/sqlx" +) + +const openframeDiskEncryptionBatchSize = 1000 + +func openframeWindowsDiskEncryptionEnabled(ctx context.Context) bool { + return fleet.OpenframeWindowsDiskEncryptionEnabled(ctx) || openframeSharedMode(ctx) +} + +// OpenframeSetHostsDiskEncryption requires the Windows hosts among hostIDs to encrypt, or lifts that, and returns how +// many hosts it applied to. Hosts of another tenant and of other platforms are dropped. Lifting keeps the row of a host +// that has one and adds none. A call that failed midway can be repeated. +func (ds *Datastore) OpenframeSetHostsDiskEncryption(ctx context.Context, hostIDs []uint, required bool) (uint, error) { + teamID, pinned := fleet.OpenframeTeamID(ctx) + if openframeSharedMode(ctx) && !pinned { + return 0, ctxerr.New(ctx, "disk encryption requirement without a tenant in shared mode") + } + selectHosts := `SELECT id, team_id FROM hosts WHERE id IN (?) AND platform = 'windows'` + if pinned { + selectHosts += ` AND team_id = ?` + } + + var applied uint + for batch := range slices.Chunk(hostIDs, openframeDiskEncryptionBatchSize) { + args := []any{batch} + if pinned { + args = append(args, teamID) + } + stmt, args, err := sqlx.In(selectHosts, args...) + if err != nil { + return 0, ctxerr.Wrap(ctx, err, "build the Windows hosts query") + } + var hosts []openframeDiskEncryptionHost + if err := sqlx.SelectContext(ctx, ds.writer(ctx), &hosts, stmt, args...); err != nil { + return 0, ctxerr.Wrap(ctx, err, "select the Windows hosts") + } + if len(hosts) == 0 { + continue + } + write := ds.openframeLiftDiskEncryption + if required { + write = ds.openframeRequireDiskEncryption + } + if err := write(ctx, hosts); err != nil { + return 0, err + } + applied += uint(len(hosts)) + } + return applied, nil +} + +type openframeDiskEncryptionHost struct { + ID uint `db:"id"` + TeamID *uint `db:"team_id"` +} + +func (ds *Datastore) openframeRequireDiskEncryption(ctx context.Context, hosts []openframeDiskEncryptionHost) error { + args := make([]any, 0, len(hosts)*2) + for _, host := range hosts { + args = append(args, host.ID, host.TeamID) + } + values := strings.TrimSuffix(strings.Repeat(`(?, ?, 1),`, len(hosts)), ",") + _, err := ds.writer(ctx).ExecContext(ctx, ` + INSERT INTO openframe_host_disk_encryption (host_id, team_id, required) VALUES `+values+` + ON DUPLICATE KEY UPDATE + client_error = IF(team_id <=> VALUES(team_id), client_error, ''), + key_stored_at = IF(team_id <=> VALUES(team_id), key_stored_at, NULL), + team_id = VALUES(team_id), + required = VALUES(required)`, args...) + return ctxerr.Wrap(ctx, err, "require the hosts to encrypt") +} + +func (ds *Datastore) openframeLiftDiskEncryption(ctx context.Context, hosts []openframeDiskEncryptionHost) error { + ids := make([]uint, 0, len(hosts)) + for _, host := range hosts { + ids = append(ids, host.ID) + } + stmt, args, err := sqlx.In(`UPDATE openframe_host_disk_encryption SET required = 0 WHERE host_id IN (?)`, ids) + if err != nil { + return ctxerr.Wrap(ctx, err, "build the lifted disk encryption requirement") + } + _, err = ds.writer(ctx).ExecContext(ctx, stmt, args...) + return ctxerr.Wrap(ctx, err, "lift the disk encryption requirement") +} + +// OpenframeHostDiskEncryption returns what OpenFrame asked of the host in the tenant it is in now. +func (ds *Datastore) OpenframeHostDiskEncryption(ctx context.Context, host *fleet.Host) (fleet.OpenframeDiskEncryption, error) { + var asked fleet.OpenframeDiskEncryption + err := sqlx.GetContext(ctx, ds.reader(ctx), &asked, ` + SELECT required, TRUE AS ever_required + FROM openframe_host_disk_encryption + WHERE host_id = ? AND team_id <=> ?`, host.ID, host.TeamID) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return fleet.OpenframeDiskEncryption{}, ctxerr.Wrap(ctx, err, "read the host's disk encryption requirement") + } + return asked, nil +} + +// OpenframeRecordDiskEncryptionResult records what fleetd reported for the host: its error, empty when there is none, +// and that its key was stored. A repeated error changes nothing. +func (ds *Datastore) OpenframeRecordDiskEncryptionResult(ctx context.Context, host *fleet.Host, clientError string, keyStored bool) error { + return ds.withRetryTxx(ctx, func(tx sqlx.ExtContext) error { + _, err := tx.ExecContext(ctx, ` + UPDATE openframe_host_disk_encryption + SET client_error = ?, key_stored_at = IF(?, CURRENT_TIMESTAMP(6), key_stored_at) + WHERE host_id = ? AND team_id <=> ?`, clientError, keyStored, host.ID, host.TeamID) + return ctxerr.Wrap(ctx, err, "record the host's disk encryption result") + }) +} + +// openframeClearDiskEncryptionErrors follows upstream where it deletes the hosts' key rows, which hold the error, too. +// The time the key was stored stays: the key can still be read from the archive. +func openframeClearDiskEncryptionErrors(ctx context.Context, tx sqlx.ExtContext, hostIDs []uint) error { + if !openframeWindowsDiskEncryptionEnabled(ctx) || len(hostIDs) == 0 { + return nil + } + stmt, args, err := sqlx.In(`UPDATE openframe_host_disk_encryption SET client_error = '' WHERE host_id IN (?)`, hostIDs) + if err != nil { + return ctxerr.Wrap(ctx, err, "build the cleared disk encryption errors") + } + _, err = tx.ExecContext(ctx, stmt, args...) + return ctxerr.Wrap(ctx, err, "clear the disk encryption errors") +} + +// openframeDiskEncryptionConfig replaces the team's setting with the host's own requirement in OpenFrame mode. A +// startup PIN is never required there. +func (ds *Datastore) openframeDiskEncryptionConfig(ctx context.Context, host *fleet.Host) (fleet.DiskEncryptionConfig, error) { + if !openframeWindowsDiskEncryptionEnabled(ctx) { + return ds.GetConfigEnableDiskEncryption(ctx, host.TeamID) + } + asked, err := ds.OpenframeHostDiskEncryption(ctx, host) + if err != nil { + return fleet.DiskEncryptionConfig{}, err + } + return fleet.DiskEncryptionConfig{Enabled: asked.Required}, nil +} + +// <<< OPENFRAME(windows-disk-encryption) diff --git a/server/datastore/mysql/openframe_windows_disk_encryption_test.go b/server/datastore/mysql/openframe_windows_disk_encryption_test.go new file mode 100644 index 00000000000..6d0b60fc17c --- /dev/null +++ b/server/datastore/mysql/openframe_windows_disk_encryption_test.go @@ -0,0 +1,314 @@ +// OPENFRAME(windows-disk-encryption) +package mysql + +import ( + "context" + "testing" + "time" + + "github.com/fleetdm/fleet/v4/server/fleet" + "github.com/jmoiron/sqlx" + "github.com/stretchr/testify/require" +) + +func openframeDiskEncryptionCtx(ctx context.Context, teamID uint) context.Context { + return fleet.NewOpenframeModeContext(openframePinnedSharedCtx(ctx, teamID)) +} + +func (f *openframeWindowsMDMFixture) exec(t *testing.T, stmt string, args ...any) { + ExecAdhocSQL(t, f.ds, func(q sqlx.ExtContext) error { + _, err := q.ExecContext(t.Context(), stmt, args...) + return err + }) +} + +func (f *openframeWindowsMDMFixture) requireAsked(t *testing.T, h *fleet.Host, required, ever bool) { + asked, err := f.ds.OpenframeHostDiskEncryption(t.Context(), h) + require.NoError(t, err) + require.Equal(t, fleet.OpenframeDiskEncryption{Required: required, EverRequired: ever}, asked) +} + +func TestOpenframeDiskEncryptionTwoTenants(t *testing.T) { + f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) + a1, a2 := f.host(t, "de-a1", "uuid-de-a1", f.teamA.ID), f.host(t, "de-a2", "uuid-de-a2", f.teamA.ID) + b1 := f.host(t, "de-b1", "uuid-de-b1", f.teamB.ID) + mac := f.host(t, "de-mac", "uuid-de-mac", f.teamA.ID) + f.exec(t, `UPDATE hosts SET platform = 'darwin' WHERE id = ?`, mac.ID) + ctxA, ctxB := openframeDiskEncryptionCtx(t.Context(), f.teamA.ID), openframeDiskEncryptionCtx(t.Context(), f.teamB.ID) + const missing = 999999 + + n, err := f.ds.OpenframeSetHostsDiskEncryption(ctxA, []uint{a1.ID, b1.ID, mac.ID, missing}, true) + require.NoError(t, err) + require.EqualValues(t, 1, n) + f.requireAsked(t, a1, true, true) + f.requireAsked(t, a2, false, false) + f.requireAsked(t, b1, false, false) + require.Equal(t, 1, f.count(t, `SELECT COUNT(*) FROM openframe_host_disk_encryption`)) + + n, err = f.ds.OpenframeSetHostsDiskEncryption(ctxA, []uint{a1.ID}, true) + require.NoError(t, err) + require.EqualValues(t, 1, n, "a repeated call applies again") + + n, err = f.ds.OpenframeSetHostsDiskEncryption(ctxB, []uint{a1.ID}, false) + require.NoError(t, err) + require.Zero(t, n) + f.requireAsked(t, a1, true, true) + + n, err = f.ds.OpenframeSetHostsDiskEncryption(ctxA, []uint{a1.ID, a2.ID}, false) + require.NoError(t, err) + require.EqualValues(t, 2, n) + f.requireAsked(t, a1, false, true) + f.requireAsked(t, a2, false, false) + + n, err = f.ds.OpenframeSetHostsDiskEncryption(ctxA, nil, true) + require.NoError(t, err) + require.Zero(t, n) +} + +func TestOpenframeDiskEncryptionWithoutTenant(t *testing.T) { + f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) + a, b := f.host(t, "de-a", "uuid-de-a", f.teamA.ID), f.host(t, "de-b", "uuid-de-b", f.teamB.ID) + noTeam := f.host(t, "de-n", "uuid-de-n", f.teamA.ID) + f.exec(t, `UPDATE hosts SET team_id = NULL WHERE id = ?`, noTeam.ID) + noTeam.TeamID = nil + + _, err := f.ds.OpenframeSetHostsDiskEncryption(openframeSharedCtx(t.Context()), []uint{a.ID}, true) + require.Error(t, err, "shared mode needs a tenant") + f.requireAsked(t, a, false, false) + + n, err := f.ds.OpenframeSetHostsDiskEncryption(fleet.NewOpenframeModeContext(t.Context()), []uint{a.ID, b.ID, noTeam.ID}, true) + require.NoError(t, err) + require.EqualValues(t, 3, n) + f.requireAsked(t, a, true, true) + f.requireAsked(t, b, true, true) + f.requireAsked(t, noTeam, true, true) +} + +func TestOpenframeDiskEncryptionMoreHostsThanABatch(t *testing.T) { + f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) + a, b := f.host(t, "de-a", "uuid-de-a", f.teamA.ID), f.host(t, "de-b", "uuid-de-b", f.teamA.ID) + ids := []uint{a.ID} + for i := range uint(openframeDiskEncryptionBatchSize) { + ids = append(ids, 900000+i) + } + ids = append(ids, b.ID) + ctx := openframeDiskEncryptionCtx(t.Context(), f.teamA.ID) + + n, err := f.ds.OpenframeSetHostsDiskEncryption(ctx, ids, true) + require.NoError(t, err) + require.EqualValues(t, 2, n) + f.requireAsked(t, a, true, true) + f.requireAsked(t, b, true, true) + + n, err = f.ds.OpenframeSetHostsDiskEncryption(ctx, ids, false) + require.NoError(t, err) + require.EqualValues(t, 2, n) + f.requireAsked(t, a, false, true) + f.requireAsked(t, b, false, true) +} + +func TestOpenframeDiskEncryptionFollowsNoHostToAnotherTenant(t *testing.T) { + f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) + h := f.host(t, "de-a", "uuid-de-a", f.teamA.ID) + ctxA, ctxB := openframeDiskEncryptionCtx(t.Context(), f.teamA.ID), openframeDiskEncryptionCtx(t.Context(), f.teamB.ID) + _, err := f.ds.OpenframeSetHostsDiskEncryption(ctxA, []uint{h.ID}, true) + require.NoError(t, err) + + f.exec(t, `UPDATE hosts SET team_id = ? WHERE id = ?`, f.teamB.ID, h.ID) + h.TeamID = &f.teamB.ID + f.requireAsked(t, h, false, false) + + _, err = f.ds.OpenframeSetHostsDiskEncryption(ctxB, []uint{h.ID}, false) + require.NoError(t, err) + _, err = f.ds.OpenframeSetHostsDiskEncryption(ctxB, []uint{h.ID}, true) + require.NoError(t, err) + f.requireAsked(t, h, true, true) + + _, err = f.ds.OpenframeSetHostsDiskEncryption(ctxA, []uint{h.ID}, false) + require.NoError(t, err) + f.requireAsked(t, h, true, true) +} + +func TestOpenframeDiskEncryptionDeletedWithHost(t *testing.T) { + f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) + h := f.host(t, "de-a", "uuid-de-a", f.teamA.ID) + ctx := openframeDiskEncryptionCtx(t.Context(), f.teamA.ID) + _, err := f.ds.OpenframeSetHostsDiskEncryption(ctx, []uint{h.ID}, true) + require.NoError(t, err) + + require.NoError(t, f.ds.DeleteHost(ctx, h.ID)) + require.Zero(t, f.count(t, `SELECT COUNT(*) FROM openframe_host_disk_encryption`)) +} + +func TestOpenframeDiskEncryptionBitLockerStatus(t *testing.T) { + f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) + h, other := f.host(t, "de-a", "uuid-de-a", f.teamA.ID), f.host(t, "de-b", "uuid-de-b", f.teamA.ID) + ctx := openframeDiskEncryptionCtx(t.Context(), f.teamA.ID) + for _, host := range []*fleet.Host{h, other} { + require.NoError(t, f.ds.SetOrUpdateMDMData(t.Context(), host.ID, false, true, "https://example.com", false, fleet.WellKnownMDMFleet, "", false)) + } + requireStatus := func(host *fleet.Host, want fleet.DiskEncryptionStatus, detail string) { + t.Helper() + got, err := f.ds.GetMDMWindowsBitLockerStatus(ctx, host) + require.NoError(t, err) + if want == "" { + require.Nil(t, got) + return + } + require.NotNil(t, got) + require.Equal(t, want, *got.Status) + require.Equal(t, detail, got.Detail) + } + + requireStatus(h, "", "") + f.exec(t, `UPDATE teams SET config = JSON_SET(config, '$.mdm.enable_disk_encryption', true) WHERE id = ?`, f.teamA.ID) + requireStatus(h, "", "") + upstream, err := f.ds.GetMDMWindowsBitLockerStatus(t.Context(), h) + require.NoError(t, err) + require.NotNil(t, upstream, "outside OpenFrame mode the team's setting counts") + f.exec(t, `UPDATE teams SET config = JSON_SET(config, '$.mdm.enable_disk_encryption', false) WHERE id = ?`, f.teamA.ID) + + _, err = f.ds.OpenframeSetHostsDiskEncryption(ctx, []uint{h.ID}, true) + require.NoError(t, err) + requireStatus(h, fleet.DiskEncryptionEnforcing, "") + requireStatus(other, "", "") + + _, err = f.ds.SetOrUpdateHostDiskEncryptionKey(ctx, h, "", "no TPM found", nil) + require.NoError(t, err) + requireStatus(h, fleet.DiskEncryptionFailed, "no TPM found") + + _, err = f.ds.SetOrUpdateHostDiskEncryptionKey(ctx, h, "key", "", new(true)) + require.NoError(t, err) + require.NoError(t, f.ds.SetOrUpdateHostDisksEncryption(ctx, h.ID, true, new(fleet.BitLockerProtectionStatusOn))) + requireStatus(h, fleet.DiskEncryptionVerified, "") + + _, err = f.ds.OpenframeSetHostsDiskEncryption(ctx, []uint{h.ID}, false) + require.NoError(t, err) + requireStatus(h, "", "") + key, err := f.ds.GetHostDiskEncryptionKey(ctx, h.ID) + require.NoError(t, err) + require.Equal(t, "key", key.Base64Encrypted, "the key stays when the requirement is lifted") +} + +func TestOpenframeDiskEncryptionArchivedKeyNotBySerial(t *testing.T) { + f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) + a, b := f.host(t, "de-a", "uuid-de-a", f.teamA.ID), f.host(t, "de-b", "uuid-de-b", f.teamB.ID) + a.HardwareSerial, b.HardwareSerial = "SHARED", "SHARED" + ctxA, ctxB := openframeDiskEncryptionCtx(t.Context(), f.teamA.ID), openframeDiskEncryptionCtx(t.Context(), f.teamB.ID) + archived, err := f.ds.SetOrUpdateHostDiskEncryptionKey(ctxA, a, "key-a", "", new(true)) + require.NoError(t, err) + require.True(t, archived) + + key, err := f.ds.GetHostArchivedDiskEncryptionKey(ctxA, a) + require.NoError(t, err) + require.Equal(t, "key-a", key.Base64Encrypted) + require.WithinDuration(t, time.Now(), key.CreatedAt, time.Hour) + + _, err = f.ds.GetHostArchivedDiskEncryptionKey(ctxB, b) + require.True(t, fleet.IsNotFound(err)) + + key, err = f.ds.GetHostArchivedDiskEncryptionKey(t.Context(), b) + require.NoError(t, err) + require.Equal(t, "key-a", key.Base64Encrypted, "upstream outside OpenFrame mode") +} + +type openframeDiskEncryptionRow struct { + ClientError string `db:"client_error"` + KeyStoredAt *time.Time `db:"key_stored_at"` + UpdatedAt time.Time `db:"updated_at"` +} + +func (f *openframeWindowsMDMFixture) diskEncryptionRow(t *testing.T, h *fleet.Host) openframeDiskEncryptionRow { + var row openframeDiskEncryptionRow + require.NoError(t, sqlx.GetContext(t.Context(), f.ds.reader(t.Context()), &row, + `SELECT client_error, key_stored_at, updated_at FROM openframe_host_disk_encryption WHERE host_id = ?`, h.ID)) + return row +} + +func TestOpenframeDiskEncryptionResult(t *testing.T) { + f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) + h, other := f.host(t, "de-a", "uuid-de-a", f.teamA.ID), f.host(t, "de-b", "uuid-de-b", f.teamA.ID) + ctx := openframeDiskEncryptionCtx(t.Context(), f.teamA.ID) + + require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctx, h, "no TPM found", true)) + require.Zero(t, f.count(t, `SELECT COUNT(*) FROM openframe_host_disk_encryption`), "a host never required gets no row") + + _, err := f.ds.OpenframeSetHostsDiskEncryption(ctx, []uint{h.ID, other.ID}, true) + require.NoError(t, err) + row := f.diskEncryptionRow(t, h) + require.Empty(t, row.ClientError) + require.Nil(t, row.KeyStoredAt) + + require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctx, h, "no TPM found", false)) + failed := f.diskEncryptionRow(t, h) + require.Equal(t, "no TPM found", failed.ClientError) + require.Nil(t, failed.KeyStoredAt) + require.Empty(t, f.diskEncryptionRow(t, other).ClientError) + + require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctx, h, "no TPM found", false)) + require.Equal(t, failed, f.diskEncryptionRow(t, h), "a repeated error changes nothing") + + require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctx, h, "", true)) + stored := f.diskEncryptionRow(t, h) + require.Empty(t, stored.ClientError) + require.NotNil(t, stored.KeyStoredAt) + + require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctx, h, "rotation failed", false)) + row = f.diskEncryptionRow(t, h) + require.Equal(t, "rotation failed", row.ClientError) + require.Equal(t, stored.KeyStoredAt, row.KeyStoredAt, "the archive still has the key") + + _, err = f.ds.OpenframeSetHostsDiskEncryption(ctx, []uint{h.ID}, false) + require.NoError(t, err) + _, err = f.ds.OpenframeSetHostsDiskEncryption(ctx, []uint{h.ID}, true) + require.NoError(t, err) + row = f.diskEncryptionRow(t, h) + require.Equal(t, "rotation failed", row.ClientError) + require.Equal(t, stored.KeyStoredAt, row.KeyStoredAt) + + h.TeamID = &f.teamB.ID + require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctx, h, "", true)) + require.Equal(t, row, f.diskEncryptionRow(t, h), "the row is another tenant's") + + f.exec(t, `UPDATE hosts SET team_id = ? WHERE id = ?`, f.teamB.ID, h.ID) + _, err = f.ds.OpenframeSetHostsDiskEncryption(openframeDiskEncryptionCtx(t.Context(), f.teamB.ID), []uint{h.ID}, true) + require.NoError(t, err) + row = f.diskEncryptionRow(t, h) + require.Empty(t, row.ClientError) + require.Nil(t, row.KeyStoredAt) +} + +func TestOpenframeDiskEncryptionErrorGoesWithTheKey(t *testing.T) { + f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) + h, other := f.host(t, "de-a", "uuid-de-a", f.teamA.ID), f.host(t, "de-b", "uuid-de-b", f.teamA.ID) + ctx := openframeDiskEncryptionCtx(t.Context(), f.teamA.ID) + _, err := f.ds.OpenframeSetHostsDiskEncryption(ctx, []uint{h.ID, other.ID}, true) + require.NoError(t, err) + require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctx, other, "other", false)) + + for _, c := range []struct { + name string + clear func(ctx context.Context) error + }{ + {"MDM re-enrollment", func(ctx context.Context) error { return f.ds.MDMResetEnrollment(ctx, h.UUID, false) }}, + {"team change", func(ctx context.Context) error { + return f.ds.CleanupDiskEncryptionKeysOnTeamChange(ctx, []uint{h.ID}, &f.teamB.ID) + }}, + } { + t.Run(c.name, func(t *testing.T) { + require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctx, h, "", true)) + require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctx, h, "no TPM found", false)) + stored := f.diskEncryptionRow(t, h).KeyStoredAt + require.NotNil(t, stored) + + require.NoError(t, c.clear(t.Context())) + require.Equal(t, "no TPM found", f.diskEncryptionRow(t, h).ClientError, "upstream outside OpenFrame mode") + + require.NoError(t, c.clear(ctx)) + row := f.diskEncryptionRow(t, h) + require.Empty(t, row.ClientError) + require.Equal(t, stored, row.KeyStoredAt) + require.Equal(t, "other", f.diskEncryptionRow(t, other).ClientError) + }) + } +} diff --git a/server/datastore/mysql/schema.sql b/server/datastore/mysql/schema.sql index de70f17e874..e91cac40935 100644 --- a/server/datastore/mysql/schema.sql +++ b/server/datastore/mysql/schema.sql @@ -2355,6 +2355,18 @@ CREATE TABLE `network_interfaces` ( /*!40101 SET character_set_client = @saved_cs_client */; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `openframe_host_disk_encryption` ( + `host_id` int unsigned NOT NULL, + `team_id` int unsigned DEFAULT NULL, + `required` tinyint(1) NOT NULL, + `client_error` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `key_stored_at` timestamp(6) NULL DEFAULT NULL, + `updated_at` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + PRIMARY KEY (`host_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `openframe_host_enroll_owners` ( `host_id` int unsigned NOT NULL, `instance_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, diff --git a/server/fleet/datastore.go b/server/fleet/datastore.go index b5f6b271c4a..dc5cb0784d1 100644 --- a/server/fleet/datastore.go +++ b/server/fleet/datastore.go @@ -1251,6 +1251,16 @@ type Datastore interface { OpenframeCancelWindowsWipe(ctx context.Context, wipe OpenframeWindowsWipe) (bool, error) // <<< OPENFRAME(windows-wipe) + // >>> OPENFRAME(windows-disk-encryption): BitLocker required per host — openframe/docs/windows-disk-encryption.md + // OpenframeSetHostsDiskEncryption requires the Windows hosts to encrypt, or lifts that, and returns how many hosts it + // applied to. + OpenframeSetHostsDiskEncryption(ctx context.Context, hostIDs []uint, required bool) (uint, error) + // OpenframeHostDiskEncryption returns what OpenFrame asked of the host in its tenant. + OpenframeHostDiskEncryption(ctx context.Context, host *Host) (OpenframeDiskEncryption, error) + // OpenframeRecordDiskEncryptionResult records what fleetd reported for the host, without the key. + OpenframeRecordDiskEncryptionResult(ctx context.Context, host *Host, clientError string, keyStored bool) error + // <<< OPENFRAME(windows-disk-encryption) + // >>> OPENFRAME(enroll-machine-identity) // OpenframeRefuseSharedHardwareUUID refuses the MDM enrollment of a host whose hardware UUID another host of its team // shares. diff --git a/server/fleet/openframe_windows_disk_encryption.go b/server/fleet/openframe_windows_disk_encryption.go new file mode 100644 index 00000000000..f04312318ad --- /dev/null +++ b/server/fleet/openframe_windows_disk_encryption.go @@ -0,0 +1,21 @@ +// >>> OPENFRAME(windows-disk-encryption): BitLocker required per host on Fleet Free — openframe/docs/windows-disk-encryption.md + +package fleet + +import "context" + +// OpenframeDiskEncryption is what OpenFrame asked of a Windows host. The zero value is a host it never required to +// encrypt. +type OpenframeDiskEncryption struct { + Required bool `db:"required"` + // EverRequired stays true after the requirement is lifted. + EverRequired bool `db:"ever_required"` +} + +// OpenframeWindowsDiskEncryptionEnabled reports whether the BitLocker requirement of a Windows host is its own instead +// of its team's. Shared mode counts as OpenFrame mode: the two are separate settings. +func OpenframeWindowsDiskEncryptionEnabled(ctx context.Context) bool { + return IsOpenframeModeContext(ctx) || IsOpenframeSharedMode() +} + +// <<< OPENFRAME(windows-disk-encryption) diff --git a/server/fleet/service.go b/server/fleet/service.go index 969746901b1..94c165f76c7 100644 --- a/server/fleet/service.go +++ b/server/fleet/service.go @@ -1269,6 +1269,12 @@ type Service interface { // Returns empty status if the host is not a supported Linux host LinuxHostDiskEncryptionStatus(ctx context.Context, host Host) (HostMDMDiskEncryption, error) + // >>> OPENFRAME(windows-disk-encryption): BitLocker required per host — openframe/docs/windows-disk-encryption.md + // OpenframeSetHostsDiskEncryption requires the Windows hosts to encrypt, or lifts that, and returns how many hosts it + // applied to. + OpenframeSetHostsDiskEncryption(ctx context.Context, hostIDs []uint, required bool) (uint, error) + // <<< OPENFRAME(windows-disk-encryption) + // GetMDMLinuxProfilesSummary summarizes the current status of Linux disk encryption for // the provided team (or hosts without a team if teamId is nil), or returns zeroes if disk // encryption is not enforced on the selected team diff --git a/server/mock/datastore_mock.go b/server/mock/datastore_mock.go index 87212a388e8..b80ba961adf 100644 --- a/server/mock/datastore_mock.go +++ b/server/mock/datastore_mock.go @@ -868,6 +868,12 @@ type OpenframeCheckWindowsWipeDeliveryFunc func(ctx context.Context, enrollmentI type OpenframeCancelWindowsWipeFunc func(ctx context.Context, wipe fleet.OpenframeWindowsWipe) (bool, error) +type OpenframeSetHostsDiskEncryptionFunc func(ctx context.Context, hostIDs []uint, required bool) (uint, error) + +type OpenframeHostDiskEncryptionFunc func(ctx context.Context, host *fleet.Host) (fleet.OpenframeDiskEncryption, error) + +type OpenframeRecordDiskEncryptionResultFunc func(ctx context.Context, host *fleet.Host, clientError string, keyStored bool) error + type OpenframeRefuseSharedHardwareUUIDFunc func(ctx context.Context, hostID uint, hardwareUUID string) error type UpdateHostFunc func(ctx context.Context, host *fleet.Host) error @@ -3417,6 +3423,15 @@ type DataStore struct { OpenframeCancelWindowsWipeFunc OpenframeCancelWindowsWipeFunc OpenframeCancelWindowsWipeFuncInvoked bool + OpenframeSetHostsDiskEncryptionFunc OpenframeSetHostsDiskEncryptionFunc + OpenframeSetHostsDiskEncryptionFuncInvoked bool + + OpenframeHostDiskEncryptionFunc OpenframeHostDiskEncryptionFunc + OpenframeHostDiskEncryptionFuncInvoked bool + + OpenframeRecordDiskEncryptionResultFunc OpenframeRecordDiskEncryptionResultFunc + OpenframeRecordDiskEncryptionResultFuncInvoked bool + OpenframeRefuseSharedHardwareUUIDFunc OpenframeRefuseSharedHardwareUUIDFunc OpenframeRefuseSharedHardwareUUIDFuncInvoked bool @@ -8297,6 +8312,27 @@ func (s *DataStore) OpenframeCancelWindowsWipe(ctx context.Context, wipe fleet.O return s.OpenframeCancelWindowsWipeFunc(ctx, wipe) } +func (s *DataStore) OpenframeSetHostsDiskEncryption(ctx context.Context, hostIDs []uint, required bool) (uint, error) { + s.mu.Lock() + s.OpenframeSetHostsDiskEncryptionFuncInvoked = true + s.mu.Unlock() + return s.OpenframeSetHostsDiskEncryptionFunc(ctx, hostIDs, required) +} + +func (s *DataStore) OpenframeHostDiskEncryption(ctx context.Context, host *fleet.Host) (fleet.OpenframeDiskEncryption, error) { + s.mu.Lock() + s.OpenframeHostDiskEncryptionFuncInvoked = true + s.mu.Unlock() + return s.OpenframeHostDiskEncryptionFunc(ctx, host) +} + +func (s *DataStore) OpenframeRecordDiskEncryptionResult(ctx context.Context, host *fleet.Host, clientError string, keyStored bool) error { + s.mu.Lock() + s.OpenframeRecordDiskEncryptionResultFuncInvoked = true + s.mu.Unlock() + return s.OpenframeRecordDiskEncryptionResultFunc(ctx, host, clientError, keyStored) +} + func (s *DataStore) OpenframeRefuseSharedHardwareUUID(ctx context.Context, hostID uint, hardwareUUID string) error { s.mu.Lock() s.OpenframeRefuseSharedHardwareUUIDFuncInvoked = true diff --git a/server/mock/service/service_mock.go b/server/mock/service/service_mock.go index bdcb7be2ea6..59f87959390 100644 --- a/server/mock/service/service_mock.go +++ b/server/mock/service/service_mock.go @@ -776,6 +776,8 @@ type BatchSetMDMProfilesFunc func(ctx context.Context, teamID *uint, teamName *s type LinuxHostDiskEncryptionStatusFunc func(ctx context.Context, host fleet.Host) (fleet.HostMDMDiskEncryption, error) +type OpenframeSetHostsDiskEncryptionFunc func(ctx context.Context, hostIDs []uint, required bool) (uint, error) + type GetMDMLinuxProfilesSummaryFunc func(ctx context.Context, teamId *uint) (fleet.MDMProfilesSummary, error) type NewMDMAndroidConfigProfileFunc func(ctx context.Context, teamID uint, profileName string, data []byte, labelsInclude []string, labelsMembershipMode fleet.MDMLabelsMode, labelsExcludeAny []string) (*fleet.MDMAndroidConfigProfile, error) @@ -2093,6 +2095,9 @@ type Service struct { LinuxHostDiskEncryptionStatusFunc LinuxHostDiskEncryptionStatusFunc LinuxHostDiskEncryptionStatusFuncInvoked bool + OpenframeSetHostsDiskEncryptionFunc OpenframeSetHostsDiskEncryptionFunc + OpenframeSetHostsDiskEncryptionFuncInvoked bool + GetMDMLinuxProfilesSummaryFunc GetMDMLinuxProfilesSummaryFunc GetMDMLinuxProfilesSummaryFuncInvoked bool @@ -5015,6 +5020,13 @@ func (s *Service) LinuxHostDiskEncryptionStatus(ctx context.Context, host fleet. return s.LinuxHostDiskEncryptionStatusFunc(ctx, host) } +func (s *Service) OpenframeSetHostsDiskEncryption(ctx context.Context, hostIDs []uint, required bool) (uint, error) { + s.mu.Lock() + s.OpenframeSetHostsDiskEncryptionFuncInvoked = true + s.mu.Unlock() + return s.OpenframeSetHostsDiskEncryptionFunc(ctx, hostIDs, required) +} + func (s *Service) GetMDMLinuxProfilesSummary(ctx context.Context, teamId *uint) (fleet.MDMProfilesSummary, error) { s.mu.Lock() s.GetMDMLinuxProfilesSummaryFuncInvoked = true diff --git a/server/service/handler.go b/server/service/handler.go index b9d1c0f6af7..3e9c8c52551 100644 --- a/server/service/handler.go +++ b/server/service/handler.go @@ -854,6 +854,10 @@ func attachFleetAPIRoutes(r *mux.Router, svc fleet.Service, config config.FleetC // It was only used to set disk encryption. mdmAnyMW.PATCH("/api/_version_/fleet/mdm/apple/settings", updateMDMAppleSettingsEndpoint, updateMDMAppleSettingsRequest{}) ue.POST("/api/_version_/fleet/disk_encryption", updateDiskEncryptionEndpoint, updateDiskEncryptionRequest{}) + // >>> OPENFRAME(windows-disk-encryption): the Windows hosts required to encrypt — openframe/docs/windows-disk-encryption.md + ue.POST("/api/_version_/fleet/disk_encryption/hosts", openframeRequireHostsDiskEncryptionEndpoint, openframeHostsDiskEncryptionRequest{}) + ue.DELETE("/api/_version_/fleet/disk_encryption/hosts", openframeLiftHostsDiskEncryptionEndpoint, openframeHostsDiskEncryptionRequest{}) + // <<< OPENFRAME(windows-disk-encryption) // the following set of mdm endpoints must always be accessible (even // if MDM is not configured) as it bootstraps the setup of MDM diff --git a/server/service/hosts.go b/server/service/hosts.go index df3ce6c1b78..4f6951cd232 100644 --- a/server/service/hosts.go +++ b/server/service/hosts.go @@ -1773,7 +1773,9 @@ func (svc *Service) getHostDetails(ctx context.Context, host *fleet.Host, opts f break } - if license.IsPremium(ctx) { + // >>> OPENFRAME(windows-disk-encryption): Free shows the status in OpenFrame mode — openframe/docs/windows-disk-encryption.md + if openframeShowsBitLockerStatus(ctx) { + // <<< OPENFRAME(windows-disk-encryption) // we include disk encryption status only for premium so initialize it to default struct host.MDM.OSSettings.DiskEncryption = fleet.HostMDMDiskEncryption{} // ensure host mdm info is loaded (we don't know if our caller populated it) diff --git a/server/service/openframe_windows_disk_encryption.go b/server/service/openframe_windows_disk_encryption.go new file mode 100644 index 00000000000..8d1183100ad --- /dev/null +++ b/server/service/openframe_windows_disk_encryption.go @@ -0,0 +1,93 @@ +// >>> OPENFRAME(windows-disk-encryption): BitLocker required per host on Fleet Free — openframe/docs/windows-disk-encryption.md + +package service + +import ( + "context" + + "github.com/fleetdm/fleet/v4/server/contexts/ctxerr" + "github.com/fleetdm/fleet/v4/server/contexts/license" + "github.com/fleetdm/fleet/v4/server/fleet" + "github.com/fleetdm/fleet/v4/server/service/osquery_utils" +) + +type openframeHostsDiskEncryptionRequest struct { + HostIDs []uint `json:"host_ids"` +} + +type openframeHostsDiskEncryptionResponse struct { + Hosts uint `json:"hosts"` + Err error `json:"error,omitempty"` +} + +func (r openframeHostsDiskEncryptionResponse) Error() error { return r.Err } + +func openframeRequireHostsDiskEncryptionEndpoint(ctx context.Context, request any, svc fleet.Service) (fleet.Errorer, error) { + return openframeSetHostsDiskEncryption(ctx, request, svc, true), nil +} + +func openframeLiftHostsDiskEncryptionEndpoint(ctx context.Context, request any, svc fleet.Service) (fleet.Errorer, error) { + return openframeSetHostsDiskEncryption(ctx, request, svc, false), nil +} + +func openframeSetHostsDiskEncryption(ctx context.Context, request any, svc fleet.Service, required bool) fleet.Errorer { + req := request.(*openframeHostsDiskEncryptionRequest) + hosts, err := svc.OpenframeSetHostsDiskEncryption(ctx, req.HostIDs, required) + return openframeHostsDiskEncryptionResponse{Hosts: hosts, Err: err} +} + +func (svc *Service) OpenframeSetHostsDiskEncryption(ctx context.Context, hostIDs []uint, required bool) (uint, error) { + payload := fleet.MDMAppleSettingsPayload{} + if teamID, ok := fleet.OpenframeTeamID(ctx); ok { + payload.TeamID = &teamID + } + if err := svc.authz.Authorize(ctx, payload, fleet.ActionWrite); err != nil { + return 0, ctxerr.Wrap(ctx, err) + } + if !fleet.OpenframeWindowsDiskEncryptionEnabled(ctx) { + return 0, &fleet.BadRequestError{Message: "openframe mode is not enabled"} + } + return svc.ds.OpenframeSetHostsDiskEncryption(ctx, hostIDs, required) +} + +// openframeDiskEncryptionConfigured replaces the team's setting with the host's own requirement for a Windows host in +// OpenFrame mode. Read only for a host that could be told to encrypt. +func (svc *Service) openframeDiskEncryptionConfigured(ctx context.Context, host *fleet.Host, teamConfigured, connected bool) (bool, error) { + if !fleet.OpenframeWindowsDiskEncryptionEnabled(ctx) || host.FleetPlatform() != "windows" { + return teamConfigured, nil + } + if !connected { + return false, nil + } + asked, err := svc.ds.OpenframeHostDiskEncryption(ctx, host) + if err != nil { + return false, ctxerr.Wrap(ctx, err, "read the host's disk encryption requirement") + } + return asked.Required, nil +} + +// openframeAcceptsDiskEncryptionKey reports whether the host's key is stored. In OpenFrame mode the key of a Windows +// host that was ever required to encrypt is: fleetd may have removed the host's other recovery keys before sending it. +func (svc *Service) openframeAcceptsDiskEncryptionKey(ctx context.Context, host *fleet.Host) (bool, error) { + if !fleet.OpenframeWindowsDiskEncryptionEnabled(ctx) || host.FleetPlatform() != "windows" { + return osquery_utils.IsDiskEncryptionEnabledForHost(ctx, svc.logger, svc.ds, host), nil + } + asked, err := svc.ds.OpenframeHostDiskEncryption(ctx, host) + if err != nil { + return false, ctxerr.Wrap(ctx, err, "read the host's disk encryption requirement") + } + return asked.EverRequired, nil +} + +func (svc *Service) openframeRecordDiskEncryptionResult(ctx context.Context, host *fleet.Host, clientError string, keyStored bool) error { + if !fleet.OpenframeWindowsDiskEncryptionEnabled(ctx) || host.FleetPlatform() != "windows" { + return nil + } + return svc.ds.OpenframeRecordDiskEncryptionResult(ctx, host, clientError, keyStored) +} + +func openframeShowsBitLockerStatus(ctx context.Context) bool { + return license.IsPremium(ctx) || fleet.OpenframeWindowsDiskEncryptionEnabled(ctx) +} + +// <<< OPENFRAME(windows-disk-encryption) diff --git a/server/service/openframe_windows_disk_encryption_test.go b/server/service/openframe_windows_disk_encryption_test.go new file mode 100644 index 00000000000..8e739ebfd91 --- /dev/null +++ b/server/service/openframe_windows_disk_encryption_test.go @@ -0,0 +1,269 @@ +// OPENFRAME(windows-disk-encryption) +package service + +import ( + "context" + "errors" + "log/slog" + "net/http" + "testing" + "time" + + "github.com/fleetdm/fleet/v4/server/authz" + "github.com/fleetdm/fleet/v4/server/config" + hostctx "github.com/fleetdm/fleet/v4/server/contexts/host" + "github.com/fleetdm/fleet/v4/server/contexts/license" + "github.com/fleetdm/fleet/v4/server/contexts/viewer" + "github.com/fleetdm/fleet/v4/server/fleet" + "github.com/fleetdm/fleet/v4/server/mock" + "github.com/fleetdm/fleet/v4/server/test" + "github.com/stretchr/testify/require" +) + +func TestOpenframeSetHostsDiskEncryption(t *testing.T) { + ds := new(mock.Store) + svc, ctx := newTestService(t, ds, nil, nil) + as := func(role string) context.Context { + return viewer.NewContext(ctx, viewer.Viewer{User: &fleet.User{ID: 1, GlobalRole: &role}}) + } + ds.OpenframeSetHostsDiskEncryptionFunc = func(_ context.Context, hostIDs []uint, required bool) (uint, error) { + require.Equal(t, []uint{1, 2}, hostIDs) + require.True(t, required) + return 2, nil + } + + _, err := svc.OpenframeSetHostsDiskEncryption(as(fleet.RoleAdmin), []uint{1, 2}, true) + var badRequest *fleet.BadRequestError + require.ErrorAs(t, err, &badRequest) + _, err = svc.OpenframeSetHostsDiskEncryption(fleet.NewOpenframeModeContext(as(fleet.RoleObserver)), []uint{1, 2}, true) + var forbidden *authz.Forbidden + require.ErrorAs(t, err, &forbidden) + require.False(t, ds.OpenframeSetHostsDiskEncryptionFuncInvoked) + + n, err := svc.OpenframeSetHostsDiskEncryption(fleet.NewOpenframeModeContext(as(fleet.RoleAdmin)), []uint{1, 2}, true) + require.NoError(t, err) + require.EqualValues(t, 2, n) + + teamAdmin := func(teamID uint) context.Context { + user := &fleet.User{ID: 1, Teams: []fleet.UserTeam{{Team: fleet.Team{ID: 7}, Role: fleet.RoleAdmin}}} + return fleet.NewOpenframeTeamContext(fleet.NewOpenframeModeContext(viewer.NewContext(ctx, viewer.Viewer{User: user})), teamID) + } + _, err = svc.OpenframeSetHostsDiskEncryption(teamAdmin(7), []uint{1, 2}, true) + require.NoError(t, err) + _, err = svc.OpenframeSetHostsDiskEncryption(teamAdmin(8), []uint{1, 2}, true) + require.ErrorAs(t, err, &forbidden) +} + +func TestOpenframeDiskEncryptionEndpoints(t *testing.T) { + ds := new(mock.Store) + svc, ctx := newTestService(t, ds, nil, nil) + ctx = fleet.NewOpenframeModeContext(test.UserContext(ctx, test.UserAdmin)) + var calls []bool + ds.OpenframeSetHostsDiskEncryptionFunc = func(_ context.Context, hostIDs []uint, required bool) (uint, error) { + require.Equal(t, []uint{5}, hostIDs) + calls = append(calls, required) + return 1, nil + } + req := &openframeHostsDiskEncryptionRequest{HostIDs: []uint{5}} + + resp, err := openframeRequireHostsDiskEncryptionEndpoint(ctx, req, svc) + require.NoError(t, err) + require.Equal(t, openframeHostsDiskEncryptionResponse{Hosts: 1}, resp) + resp, err = openframeLiftHostsDiskEncryptionEndpoint(ctx, req, svc) + require.NoError(t, err) + require.Equal(t, openframeHostsDiskEncryptionResponse{Hosts: 1}, resp) + require.Equal(t, []bool{true, false}, calls) +} + +func TestOpenframeDiskEncryptionNotification(t *testing.T) { + ds := new(mock.Store) + svc := &Service{ds: ds, logger: slog.New(slog.DiscardHandler)} + var asked fleet.OpenframeDiskEncryption + var askedErr error + ds.OpenframeHostDiskEncryptionFunc = func(context.Context, *fleet.Host) (fleet.OpenframeDiskEncryption, error) { + return asked, askedErr + } + ds.GetHostDiskEncryptionKeyFunc = func(context.Context, uint) (*fleet.HostDiskEncryptionKey, error) { + return nil, newNotFoundError() + } + appConfig := &fleet.AppConfig{MDM: fleet.MDM{WindowsEnabledAndConfigured: true}} + notify := func(ctx context.Context, teamConfigured, connected bool) (bool, error) { + host := &fleet.Host{ID: 1, Platform: "windows", OsqueryHostID: new("osq"), DiskEncryptionEnabled: new(false)} + notifs := &fleet.OrbitConfigNotifications{} + err := svc.setDiskEncryptionNotifications(ctx, notifs, host, appConfig, teamConfigured, connected, &fleet.HostMDM{Enrolled: true}) + return notifs.EnforceBitLockerEncryption, err + } + openframe := fleet.NewOpenframeModeContext(t.Context()) + + for _, c := range []struct { + name string + ctx context.Context + asked fleet.OpenframeDiskEncryption + team, connected bool + want bool + }{ + {"required", openframe, fleet.OpenframeDiskEncryption{Required: true, EverRequired: true}, false, true, true}, + {"not required", openframe, fleet.OpenframeDiskEncryption{}, false, true, false}, + {"lifted", openframe, fleet.OpenframeDiskEncryption{EverRequired: true}, false, true, false}, + {"the team's setting does not count", openframe, fleet.OpenframeDiskEncryption{}, true, true, false}, + {"required but not in MDM", openframe, fleet.OpenframeDiskEncryption{Required: true, EverRequired: true}, false, false, false}, + {"upstream", t.Context(), fleet.OpenframeDiskEncryption{}, true, true, true}, + {"upstream off", t.Context(), fleet.OpenframeDiskEncryption{Required: true, EverRequired: true}, false, true, false}, + } { + t.Run(c.name, func(t *testing.T) { + asked = c.asked + got, err := notify(c.ctx, c.team, c.connected) + require.NoError(t, err) + require.Equal(t, c.want, got) + }) + } + + ds.OpenframeHostDiskEncryptionFuncInvoked = false + _, err := notify(openframe, true, false) + require.NoError(t, err) + require.False(t, ds.OpenframeHostDiskEncryptionFuncInvoked, "not read for a host outside MDM") + + askedErr = errors.New("database is down") + _, err = notify(openframe, true, true) + require.ErrorIs(t, err, askedErr) +} + +func TestOpenframeDiskEncryptionKeyAccepted(t *testing.T) { + ds := new(mock.Store) + svc, ctx := newTestService(t, ds, nil, nil) + host := &fleet.Host{ID: 1, Platform: "windows", TeamID: new(uint(7))} + var asked fleet.OpenframeDiskEncryption + var askedErr error + ds.IsHostConnectedToFleetMDMFunc = func(context.Context, *fleet.Host) (bool, error) { return true, nil } + ds.OpenframeHostDiskEncryptionFunc = func(context.Context, *fleet.Host) (fleet.OpenframeDiskEncryption, error) { + return asked, askedErr + } + ds.TeamMDMConfigFunc = func(context.Context, uint) (*fleet.TeamMDM, error) { + return &fleet.TeamMDM{}, nil + } + ds.SetOrUpdateHostDiskEncryptionKeyFunc = func(_ context.Context, h *fleet.Host, _, clientError string, _ *bool) (bool, error) { + require.Equal(t, host.ID, h.ID) + require.Equal(t, "no TPM found", clientError) + return false, nil + } + ds.OpenframeRecordDiskEncryptionResultFunc = func(_ context.Context, h *fleet.Host, clientError string, keyStored bool) error { + require.Equal(t, host.ID, h.ID) + require.Equal(t, "no TPM found", clientError) + require.False(t, keyStored) + return nil + } + stored := func(ctx context.Context, h *fleet.Host) bool { + t.Helper() + ds.SetOrUpdateHostDiskEncryptionKeyFuncInvoked = false + ds.OpenframeRecordDiskEncryptionResultFuncInvoked = false + require.NoError(t, svc.SetOrUpdateDiskEncryptionKey(hostctx.NewContext(ctx, h), "", "no TPM found")) + require.Equal(t, ds.SetOrUpdateHostDiskEncryptionKeyFuncInvoked, ds.OpenframeRecordDiskEncryptionResultFuncInvoked) + return ds.SetOrUpdateHostDiskEncryptionKeyFuncInvoked + } + openframe := fleet.NewOpenframeModeContext(ctx) + + require.False(t, stored(openframe, host), "never required") + asked = fleet.OpenframeDiskEncryption{Required: true, EverRequired: true} + require.True(t, stored(openframe, host)) + require.False(t, stored(ctx, host), "outside OpenFrame mode the team's setting counts") + asked = fleet.OpenframeDiskEncryption{EverRequired: true} + require.True(t, stored(openframe, host), "lifted while the key was on its way") + + askedErr = errors.New("database is down") + err := svc.SetOrUpdateDiskEncryptionKey(hostctx.NewContext(openframe, host), "", "no TPM found") + require.ErrorIs(t, err, askedErr) +} + +func TestOpenframeDiskEncryptionKeyResult(t *testing.T) { + ds := new(mock.Store) + cfg := config.TestConfig() + cfg.MDM.WindowsWSTEPIdentityCert = "testdata/server.pem" + cfg.MDM.WindowsWSTEPIdentityKey = "testdata/server.key" + svc, ctx := newTestServiceWithConfig(t, ds, cfg, nil, nil) + host := &fleet.Host{ID: 1, Platform: "windows", TeamID: new(uint(7))} + ds.IsHostConnectedToFleetMDMFunc = func(context.Context, *fleet.Host) (bool, error) { return true, nil } + ds.OpenframeHostDiskEncryptionFunc = func(context.Context, *fleet.Host) (fleet.OpenframeDiskEncryption, error) { + return fleet.OpenframeDiskEncryption{Required: true, EverRequired: true}, nil + } + ds.TeamMDMConfigFunc = func(context.Context, uint) (*fleet.TeamMDM, error) { + return &fleet.TeamMDM{EnableDiskEncryption: true}, nil + } + var keyErr, recordErr error + ds.SetOrUpdateHostDiskEncryptionKeyFunc = func(_ context.Context, _ *fleet.Host, key, clientError string, _ *bool) (bool, error) { + require.NotEmpty(t, key) + require.Empty(t, clientError) + return false, keyErr + } + ds.OpenframeRecordDiskEncryptionResultFunc = func(_ context.Context, _ *fleet.Host, clientError string, keyStored bool) error { + require.Empty(t, clientError) + require.True(t, keyStored) + return recordErr + } + send := func(ctx context.Context) error { + ds.OpenframeRecordDiskEncryptionResultFuncInvoked = false + return svc.SetOrUpdateDiskEncryptionKey(hostctx.NewContext(ctx, host), "123456-123456", "") + } + openframe := fleet.NewOpenframeModeContext(ctx) + + require.NoError(t, send(openframe)) + require.True(t, ds.OpenframeRecordDiskEncryptionResultFuncInvoked) + require.NoError(t, send(ctx)) + require.False(t, ds.OpenframeRecordDiskEncryptionResultFuncInvoked, "upstream outside OpenFrame mode") + + recordErr = errors.New("record failed") + require.ErrorIs(t, send(openframe), recordErr) + keyErr = errors.New("key not stored") + require.ErrorIs(t, send(openframe), keyErr) + require.False(t, ds.OpenframeRecordDiskEncryptionResultFuncInvoked) +} + +func TestOpenframeDiskEncryptionStatusOnFree(t *testing.T) { + ds := new(mock.Store) + svc := &Service{ds: ds, logger: slog.New(slog.DiscardHandler)} + ds.AppConfigFunc = func(context.Context) (*fleet.AppConfig, error) { + return &fleet.AppConfig{MDM: fleet.MDM{WindowsEnabledAndConfigured: true}}, nil + } + ds.ListLabelsForHostFunc = func(context.Context, uint) ([]*fleet.Label, error) { return nil, nil } + ds.ListPacksForHostFunc = func(context.Context, uint) ([]*fleet.Pack, error) { return nil, nil } + ds.ListPoliciesForHostFunc = func(context.Context, *fleet.Host) ([]*fleet.HostPolicy, error) { return nil, nil } + ds.ListHostBatteriesFunc = func(context.Context, uint) ([]*fleet.HostBattery, error) { return nil, nil } + ds.ListUpcomingHostMaintenanceWindowsFunc = func(context.Context, uint) ([]*fleet.HostMaintenanceWindow, error) { return nil, nil } + ds.GetHostLockWipeStatusFunc = func(context.Context, *fleet.Host) (*fleet.HostLockWipeStatus, error) { + return &fleet.HostLockWipeStatus{}, nil + } + ds.ScimUserByHostIDFunc = func(context.Context, uint) (*fleet.ScimUser, error) { return nil, nil } + ds.ListHostDeviceMappingFunc = func(context.Context, uint) ([]*fleet.HostDeviceMapping, error) { return nil, nil } + ds.ConditionalAccessBypassedAtFunc = func(context.Context, uint) (*time.Time, error) { return nil, nil } + ds.IsHostDiskEncryptionKeyArchivedFunc = func(context.Context, uint) (bool, error) { return false, nil } + ds.LoadHostSoftwareFunc = func(context.Context, *fleet.Host, bool) error { return nil } + ds.GetHostMDMFunc = func(context.Context, uint) (*fleet.HostMDM, error) { return &fleet.HostMDM{Enrolled: true}, nil } + ds.GetHostMDMWindowsProfilesFunc = func(context.Context, string) ([]fleet.HostMDMWindowsProfile, error) { return nil, nil } + failed := fleet.DiskEncryptionFailed + ds.GetMDMWindowsBitLockerStatusFunc = func(context.Context, *fleet.Host) (*fleet.HostMDMDiskEncryption, error) { + return &fleet.HostMDMDiskEncryption{Status: &failed, Detail: "no TPM found"}, nil + } + details := func(ctx context.Context) fleet.HostMDMDiskEncryption { + ctx = license.NewContext(test.UserContext(ctx, test.UserAdmin), &fleet.LicenseInfo{Tier: fleet.TierFree}) + host, err := svc.getHostDetails(ctx, &fleet.Host{ID: 42, Platform: "windows"}, fleet.HostDetailOptions{}) + require.NoError(t, err) + return host.MDM.OSSettings.DiskEncryption + } + + require.Nil(t, details(t.Context()).Status) + got := details(fleet.NewOpenframeModeContext(t.Context())) + require.NotNil(t, got.Status) + require.Equal(t, fleet.DiskEncryptionFailed, *got.Status) + require.Equal(t, "no TPM found", got.Detail) +} + +func TestOpenframeEncryptionKeyOfAnotherTenant(t *testing.T) { + ds := new(mock.Store) + svc, ctx := newTestService(t, ds, nil, nil) + ds.HostLiteFunc = func(context.Context, uint) (*fleet.Host, error) { return nil, newNotFoundError() } + + _, err := svc.HostEncryptionKey(fleet.NewOpenframeModeContext(test.UserContext(ctx, test.UserAdmin)), 1) + var status interface{ StatusCode() int } + require.True(t, fleet.IsNotFound(err) || (errors.As(err, &status) && status.StatusCode() == http.StatusNotFound)) + require.False(t, ds.GetHostDiskEncryptionKeyFuncInvoked) + require.False(t, ds.GetHostArchivedDiskEncryptionKeyFuncInvoked) +} diff --git a/server/service/orbit.go b/server/service/orbit.go index b6780336f7d..542cccfa525 100644 --- a/server/service/orbit.go +++ b/server/service/orbit.go @@ -954,6 +954,12 @@ func (svc *Service) setDiskEncryptionNotifications( isConnectedToFleetMDM bool, mdmInfo *fleet.HostMDM, ) error { + // >>> OPENFRAME(windows-disk-encryption): in OpenFrame mode the host's own requirement, not its team's — openframe/docs/windows-disk-encryption.md + diskEncryptionConfigured, err := svc.openframeDiskEncryptionConfigured(ctx, host, diskEncryptionConfigured, isConnectedToFleetMDM) + if err != nil { + return err + } + // <<< OPENFRAME(windows-disk-encryption) anyMDMConfigured := appConfig.MDM.EnabledAndConfigured || appConfig.MDM.WindowsEnabledAndConfigured if !anyMDMConfigured || !isConnectedToFleetMDM || @@ -1372,7 +1378,13 @@ func (svc *Service) SetOrUpdateDiskEncryptionKey(ctx context.Context, encryption } // Only archive the key if disk encryption is enabled for this host (team/globally) - if !osquery_utils.IsDiskEncryptionEnabledForHost(ctx, svc.logger, svc.ds, host) { + // >>> OPENFRAME(windows-disk-encryption): in OpenFrame mode, if the host was ever required to encrypt — openframe/docs/windows-disk-encryption.md + accepts, err := svc.openframeAcceptsDiskEncryptionKey(ctx, host) + if err != nil { + return err + } + if !accepts { + // <<< OPENFRAME(windows-disk-encryption) svc.logger.DebugContext(ctx, "skipping key archival, disk encryption not enabled for host team/globally", "host_id", host.ID, @@ -1407,6 +1419,11 @@ func (svc *Service) SetOrUpdateDiskEncryptionKey(ctx context.Context, encryption if err != nil { return ctxerr.Wrap(ctx, err, "set or update disk encryption key") } + // >>> OPENFRAME(windows-disk-encryption): the result without the key, for CDC — openframe/docs/windows-disk-encryption.md + if err := svc.openframeRecordDiskEncryptionResult(ctx, host, clientError, encryptedEncryptionKey != ""); err != nil { + return err + } + // <<< OPENFRAME(windows-disk-encryption) // We only want to record the activity if the key was successfully archived. if !keyArchived { From fc8cbd07a738598065c83dc56f2b898cfa464347 Mon Sep 17 00:00:00 2001 From: Andrii Koropets Date: Tue, 1 Dec 2026 23:53:30 +0200 Subject: [PATCH 2/7] fix(mdm): CU-17tkuw6avb8 require the server URL on a tenant config update outside shared mode --- openframe/docs/mysql-multitenancy-feature.md | 4 ++-- server/service/openframe_windows_mdm.go | 9 +++++---- server/service/openframe_windows_mdm_test.go | 15 +++++++++------ 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/openframe/docs/mysql-multitenancy-feature.md b/openframe/docs/mysql-multitenancy-feature.md index e83d2565551..ef6c8d54181 100644 --- a/openframe/docs/mysql-multitenancy-feature.md +++ b/openframe/docs/mysql-multitenancy-feature.md @@ -237,8 +237,8 @@ and a malformed URL or flag stops the boot. Windows MDM runs per tenant. Each tenant has its own public Windows MDM address, `mdm.windows_server_url` on its tenant row (`https:///mdm`, an https URL with a valid host and no query, fragment, credentials or whitespace; `server/fleet/openframe_windows_mdm.go`), -written by OpenFrame. A tenant row is seeded without an org name and a server URL, so a pinned config -update accepts them empty as long as the row never had them (`openframeTenantNeverHad`); a tenant that +written by OpenFrame. A tenant row is seeded without an org name and a server URL, so in shared mode +a pinned config update accepts them empty as long as the row never had them (`openframeTenantNeverHad`); a tenant that has them still can't clear them. Every Windows MDM URL is built from it (`server/service/openframe_windows_mdm.go`): the discovery URL in the pinned orbit config; the policy and enroll URLs of discovery, which the middleware pins by the gateway's `X-Tenant-Id` (the only diff --git a/server/service/openframe_windows_mdm.go b/server/service/openframe_windows_mdm.go index 400547549c1..09ae60c596a 100644 --- a/server/service/openframe_windows_mdm.go +++ b/server/service/openframe_windows_mdm.go @@ -267,12 +267,13 @@ func openframeValidateWindowsMDM(oldMdm, mdm *fleet.MDM, shared bool, invalid *f } } -// openframeTenantNeverHad is true when the pinned tenant's stored config has no value for a field upstream -// requires on every config update. EnsureOpenframeTeamID seeds a tenant row without an org name and a -// server URL, and nothing sets them later. +// openframeTenantNeverHad is true in shared mode when the pinned tenant's stored config has no value for a +// field upstream requires on every config update. EnsureOpenframeTeamID seeds a tenant row without an org +// name and a server URL, and nothing sets them later. Outside shared mode the Windows MDM URLs are built +// from the server URL, so it stays required. func openframeTenantNeverHad(ctx context.Context, stored string) bool { _, pinned := fleet.OpenframeTeamID(ctx) - return pinned && stored == "" + return pinned && openframeSharedMode(ctx) && stored == "" } type openframeSharedModeCtxKey struct{} diff --git a/server/service/openframe_windows_mdm_test.go b/server/service/openframe_windows_mdm_test.go index 3106f4b748c..ff864a69ac9 100644 --- a/server/service/openframe_windows_mdm_test.go +++ b/server/service/openframe_windows_mdm_test.go @@ -365,16 +365,18 @@ func TestOpenframeModifyAppConfigOfSeededTenant(t *testing.T) { cases := []struct { name string stored *fleet.AppConfig + shared bool pinned bool patch string invalid []string }{ - {"seeded tenant takes the address", seeded(), true, address, nil}, - {"seeded tenant turns Windows MDM on", seeded(), true, `{"mdm":{"windows_enabled_and_configured":true}}`, nil}, - {"unpinned row without them is refused", seeded(), false, address, []string{"org_name", "server_url"}}, - {"tenant can't clear its org name", configured(), true, `{"org_info":{"org_name":""}}`, []string{"org_name"}}, - {"tenant can't clear its server URL", configured(), true, `{"server_settings":{"server_url":""}}`, []string{"server_url"}}, - {"seeded tenant can't set a bad server URL", seeded(), true, `{"server_settings":{"server_url":"nope"}}`, []string{"server_url"}}, + {"seeded tenant takes the address", seeded(), true, true, address, nil}, + {"seeded tenant turns Windows MDM on with the address", seeded(), true, true, `{"mdm":{"windows_enabled_and_configured":true,"windows_server_url":"https://acme.example.com/mdm"}}`, nil}, + {"seeded tenant outside shared mode can't turn Windows MDM on", seeded(), false, true, `{"mdm":{"windows_enabled_and_configured":true}}`, []string{"org_name", "server_url"}}, + {"unpinned row without them is refused", seeded(), true, false, address, []string{"org_name", "server_url"}}, + {"tenant can't clear its org name", configured(), true, true, `{"org_info":{"org_name":""}}`, []string{"org_name"}}, + {"tenant can't clear its server URL", configured(), true, true, `{"server_settings":{"server_url":""}}`, []string{"server_url"}}, + {"seeded tenant can't set a bad server URL", seeded(), true, true, `{"server_settings":{"server_url":"nope"}}`, []string{"server_url"}}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { @@ -384,6 +386,7 @@ func TestOpenframeModifyAppConfigOfSeededTenant(t *testing.T) { cfg.MDM.WindowsWSTEPIdentityKey = "testdata/server.key" svc, ctx := newTestServiceWithConfig(t, ds, cfg, nil, nil) ctx = viewer.NewContext(ctx, viewer.Viewer{User: &fleet.User{GlobalRole: new(fleet.RoleAdmin)}}) + ctx = context.WithValue(ctx, openframeSharedModeCtxKey{}, c.shared) if c.pinned { ctx = fleet.NewOpenframeTeamContext(ctx, openframeTestTeamA) } From 928a8fc6d584fe1a6fd7b78f7408ed117559b751 Mon Sep 17 00:00:00 2001 From: Andrii Koropets Date: Wed, 2 Dec 2026 00:17:58 +0200 Subject: [PATCH 3/7] fix(mdm): CU-17tkuw6a8db clear the key time with the BitLocker key row --- openframe/docs/windows-disk-encryption.md | 10 ++++++---- server/datastore/mysql/apple_mdm.go | 4 ++-- server/datastore/mysql/disk_encryption.go | 4 ++-- .../mysql/openframe_windows_disk_encryption.go | 12 ++++++------ .../openframe_windows_disk_encryption_test.go | 15 +++++++++------ 5 files changed, 25 insertions(+), 20 deletions(-) diff --git a/openframe/docs/windows-disk-encryption.md b/openframe/docs/windows-disk-encryption.md index acdc5ddaa60..ba0caaacf0d 100644 --- a/openframe/docs/windows-disk-encryption.md +++ b/openframe/docs/windows-disk-encryption.md @@ -24,10 +24,12 @@ The same row keeps what fleetd reported, without the key, so that the table can `host_disk_encryption_keys`, which holds the keys, never has to be: - `client_error`: fleetd's last error, empty when there is none. A failing fleetd reports it again every config cycle; - a repeated error changes nothing in the row. Cleared where upstream deletes the key row: MDM re-enrollment and team - change. Lifting the requirement keeps it. -- `key_stored_at`: when the host's last key was stored, NULL before the first. It stays after an error, MDM - re-enrollment or lifting: Fleet still returns the key from its archive. + a repeated error changes nothing in the row. +- `key_stored_at`: when the host's last key was stored, NULL before the first. An error keeps it. + +Both are cleared where upstream deletes the key row, MDM re-enrollment and team change: after a wipe or a reinstall the +disk is another one. A required host's fleetd then sends a new key. Lifting the requirement keeps both. The archived key +stays readable after a re-enrollment, so NULL in `key_stored_at` does not mean that Fleet has no key. ## What follows it diff --git a/server/datastore/mysql/apple_mdm.go b/server/datastore/mysql/apple_mdm.go index adfb06b8fa3..05766818624 100644 --- a/server/datastore/mysql/apple_mdm.go +++ b/server/datastore/mysql/apple_mdm.go @@ -4424,8 +4424,8 @@ func (ds *Datastore) MDMResetEnrollment(ctx context.Context, hostUUID string, sc if err != nil { return ctxerr.Wrap(ctx, err, "resetting disk encryption key information for host") } - // >>> OPENFRAME(windows-disk-encryption): the error goes with the key — openframe/docs/windows-disk-encryption.md - if err := openframeClearDiskEncryptionErrors(ctx, tx, []uint{host.ID}); err != nil { + // >>> OPENFRAME(windows-disk-encryption): the result goes with the key — openframe/docs/windows-disk-encryption.md + if err := openframeClearDiskEncryptionResults(ctx, tx, []uint{host.ID}); err != nil { return err } // <<< OPENFRAME(windows-disk-encryption) diff --git a/server/datastore/mysql/disk_encryption.go b/server/datastore/mysql/disk_encryption.go index 3b8d1d27b1b..601fd681244 100644 --- a/server/datastore/mysql/disk_encryption.go +++ b/server/datastore/mysql/disk_encryption.go @@ -382,10 +382,10 @@ func bulkDeleteHostDiskEncryptionKeysDB(ctx context.Context, tx sqlx.ExtContext, } _, err = tx.ExecContext(ctx, deleteStmt, deleteArgs...) - // >>> OPENFRAME(windows-disk-encryption): the error goes with the key — openframe/docs/windows-disk-encryption.md + // >>> OPENFRAME(windows-disk-encryption): the result goes with the key — openframe/docs/windows-disk-encryption.md if err != nil { return err } - return openframeClearDiskEncryptionErrors(ctx, tx, hostIDs) + return openframeClearDiskEncryptionResults(ctx, tx, hostIDs) // <<< OPENFRAME(windows-disk-encryption) } diff --git a/server/datastore/mysql/openframe_windows_disk_encryption.go b/server/datastore/mysql/openframe_windows_disk_encryption.go index 75382585f4d..3407e4d1e2b 100644 --- a/server/datastore/mysql/openframe_windows_disk_encryption.go +++ b/server/datastore/mysql/openframe_windows_disk_encryption.go @@ -121,18 +121,18 @@ func (ds *Datastore) OpenframeRecordDiskEncryptionResult(ctx context.Context, ho }) } -// openframeClearDiskEncryptionErrors follows upstream where it deletes the hosts' key rows, which hold the error, too. -// The time the key was stored stays: the key can still be read from the archive. -func openframeClearDiskEncryptionErrors(ctx context.Context, tx sqlx.ExtContext, hostIDs []uint) error { +// openframeClearDiskEncryptionResults follows upstream where it deletes the hosts' key rows: the disk may be another one +// by then. fleetd of a required host sends a new key. +func openframeClearDiskEncryptionResults(ctx context.Context, tx sqlx.ExtContext, hostIDs []uint) error { if !openframeWindowsDiskEncryptionEnabled(ctx) || len(hostIDs) == 0 { return nil } - stmt, args, err := sqlx.In(`UPDATE openframe_host_disk_encryption SET client_error = '' WHERE host_id IN (?)`, hostIDs) + stmt, args, err := sqlx.In(`UPDATE openframe_host_disk_encryption SET client_error = '', key_stored_at = NULL WHERE host_id IN (?)`, hostIDs) if err != nil { - return ctxerr.Wrap(ctx, err, "build the cleared disk encryption errors") + return ctxerr.Wrap(ctx, err, "build the cleared disk encryption results") } _, err = tx.ExecContext(ctx, stmt, args...) - return ctxerr.Wrap(ctx, err, "clear the disk encryption errors") + return ctxerr.Wrap(ctx, err, "clear the disk encryption results") } // openframeDiskEncryptionConfig replaces the team's setting with the host's own requirement in OpenFrame mode. A diff --git a/server/datastore/mysql/openframe_windows_disk_encryption_test.go b/server/datastore/mysql/openframe_windows_disk_encryption_test.go index 6d0b60fc17c..1685ccbfbc4 100644 --- a/server/datastore/mysql/openframe_windows_disk_encryption_test.go +++ b/server/datastore/mysql/openframe_windows_disk_encryption_test.go @@ -278,13 +278,15 @@ func TestOpenframeDiskEncryptionResult(t *testing.T) { require.Nil(t, row.KeyStoredAt) } -func TestOpenframeDiskEncryptionErrorGoesWithTheKey(t *testing.T) { +func TestOpenframeDiskEncryptionResultGoesWithTheKey(t *testing.T) { f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) h, other := f.host(t, "de-a", "uuid-de-a", f.teamA.ID), f.host(t, "de-b", "uuid-de-b", f.teamA.ID) ctx := openframeDiskEncryptionCtx(t.Context(), f.teamA.ID) _, err := f.ds.OpenframeSetHostsDiskEncryption(ctx, []uint{h.ID, other.ID}, true) require.NoError(t, err) + require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctx, other, "", true)) require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctx, other, "other", false)) + untouched := f.diskEncryptionRow(t, other) for _, c := range []struct { name string @@ -298,17 +300,18 @@ func TestOpenframeDiskEncryptionErrorGoesWithTheKey(t *testing.T) { t.Run(c.name, func(t *testing.T) { require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctx, h, "", true)) require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctx, h, "no TPM found", false)) - stored := f.diskEncryptionRow(t, h).KeyStoredAt - require.NotNil(t, stored) + failed := f.diskEncryptionRow(t, h) + require.NotNil(t, failed.KeyStoredAt) require.NoError(t, c.clear(t.Context())) - require.Equal(t, "no TPM found", f.diskEncryptionRow(t, h).ClientError, "upstream outside OpenFrame mode") + require.Equal(t, failed, f.diskEncryptionRow(t, h), "upstream outside OpenFrame mode") require.NoError(t, c.clear(ctx)) row := f.diskEncryptionRow(t, h) require.Empty(t, row.ClientError) - require.Equal(t, stored, row.KeyStoredAt) - require.Equal(t, "other", f.diskEncryptionRow(t, other).ClientError) + require.Nil(t, row.KeyStoredAt) + require.Equal(t, untouched, f.diskEncryptionRow(t, other)) + f.requireAsked(t, h, true, true) }) } } From 48ba46dc2a218a8bdcc7bd3b2b947ca0625fc89a Mon Sep 17 00:00:00 2001 From: Andrii Koropets Date: Wed, 2 Dec 2026 00:29:21 +0200 Subject: [PATCH 4/7] fix(mdm): CU-17tkuw6a8db count a repeated host id once in the BitLocker requirement --- openframe/docs/windows-disk-encryption.md | 2 ++ server/datastore/mysql/openframe_windows_disk_encryption.go | 4 +++- .../mysql/openframe_windows_disk_encryption_test.go | 5 ++++- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/openframe/docs/windows-disk-encryption.md b/openframe/docs/windows-disk-encryption.md index ba0caaacf0d..9f7e4187d59 100644 --- a/openframe/docs/windows-disk-encryption.md +++ b/openframe/docs/windows-disk-encryption.md @@ -52,6 +52,8 @@ on any platform: the serial can be another machine's, of the tenant or of anothe ## Known limits +- A host that was deleted and enrolls again is a new host: it is not required, and its archived key stays under the old + host and is not found. Requiring the new host makes fleetd send a new key. - fleetd sends again a key that Fleet did not take only while the host is told to encrypt. A key that failed to reach Fleet is lost if the requirement is lifted before the next try. - The result is written after the key, not with it. Its write is retried on a deadlock or a lock timeout; if it diff --git a/server/datastore/mysql/openframe_windows_disk_encryption.go b/server/datastore/mysql/openframe_windows_disk_encryption.go index 3407e4d1e2b..6241d113d37 100644 --- a/server/datastore/mysql/openframe_windows_disk_encryption.go +++ b/server/datastore/mysql/openframe_windows_disk_encryption.go @@ -33,8 +33,10 @@ func (ds *Datastore) OpenframeSetHostsDiskEncryption(ctx context.Context, hostID selectHosts += ` AND team_id = ?` } + unique := slices.Compact(slices.Sorted(slices.Values(hostIDs))) + var applied uint - for batch := range slices.Chunk(hostIDs, openframeDiskEncryptionBatchSize) { + for batch := range slices.Chunk(unique, openframeDiskEncryptionBatchSize) { args := []any{batch} if pinned { args = append(args, teamID) diff --git a/server/datastore/mysql/openframe_windows_disk_encryption_test.go b/server/datastore/mysql/openframe_windows_disk_encryption_test.go index 1685ccbfbc4..6d2f57ac7ac 100644 --- a/server/datastore/mysql/openframe_windows_disk_encryption_test.go +++ b/server/datastore/mysql/openframe_windows_disk_encryption_test.go @@ -87,11 +87,14 @@ func TestOpenframeDiskEncryptionWithoutTenant(t *testing.T) { func TestOpenframeDiskEncryptionMoreHostsThanABatch(t *testing.T) { f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) a, b := f.host(t, "de-a", "uuid-de-a", f.teamA.ID), f.host(t, "de-b", "uuid-de-b", f.teamA.ID) + const inSecondBatch = 2000000 + f.exec(t, `UPDATE hosts SET id = ? WHERE id = ?`, inSecondBatch, b.ID) + b.ID = inSecondBatch ids := []uint{a.ID} for i := range uint(openframeDiskEncryptionBatchSize) { ids = append(ids, 900000+i) } - ids = append(ids, b.ID) + ids = append(ids, b.ID, a.ID) ctx := openframeDiskEncryptionCtx(t.Context(), f.teamA.ID) n, err := f.ds.OpenframeSetHostsDiskEncryption(ctx, ids, true) From f0a0ef43d87db276a5780fb3bb687ae4186476d6 Mon Sep 17 00:00:00 2001 From: Andrii Koropets Date: Wed, 2 Dec 2026 00:39:03 +0200 Subject: [PATCH 5/7] fix(mdm): CU-17tkuw6a8db take the BitLocker key of a host that left MDM --- openframe/docs/windows-disk-encryption.md | 7 +- .../openframe_windows_disk_encryption.go | 10 +++ .../openframe_windows_disk_encryption_test.go | 70 +++++++++++++++++++ server/service/orbit.go | 10 ++- 4 files changed, 93 insertions(+), 4 deletions(-) diff --git a/openframe/docs/windows-disk-encryption.md b/openframe/docs/windows-disk-encryption.md index 9f7e4187d59..cb960224ae7 100644 --- a/openframe/docs/windows-disk-encryption.md +++ b/openframe/docs/windows-disk-encryption.md @@ -37,8 +37,9 @@ stays readable after a re-enrollment, so NULL in `key_stored_at` does not mean t under upstream's conditions; any other host does not, whatever the team's setting is. Lifting never turns BitLocker off. - **The key** (`SetOrUpdateDiskEncryptionKey`): stored for a host that was ever required, also after the requirement - was lifted. On a drive that was already encrypted fleetd removes the other recovery keys before it sends the new - one, so a dropped key would leave none that opens the drive. + was lifted or the host left MDM. On a drive that was already encrypted fleetd removes the other recovery keys before + it sends the new one, so a dropped key would leave none that opens the drive. Outside MDM only a key is taken: an + error is refused, as upstream refuses everything. - **The status** (`GetMDMWindowsBitLockerStatus`, `os_settings.disk_encryption` in host details): shown on Free for a required host, empty for any other. No startup PIN is ever required. @@ -55,7 +56,7 @@ on any platform: the serial can be another machine's, of the tenant or of anothe - A host that was deleted and enrolls again is a new host: it is not required, and its archived key stays under the old host and is not found. Requiring the new host makes fleetd send a new key. - fleetd sends again a key that Fleet did not take only while the host is told to encrypt. A key that failed to - reach Fleet is lost if the requirement is lifted before the next try. + reach Fleet is lost if the requirement is lifted, or the host leaves MDM, before the next try. - The result is written after the key, not with it. Its write is retried on a deadlock or a lock timeout; if it fails, `key_stored_at` stays as it was until the next key. - Reading a key needs Windows MDM to be on for the tenant (`VerifyMDMWindowsConfigured`), as upstream. diff --git a/server/service/openframe_windows_disk_encryption.go b/server/service/openframe_windows_disk_encryption.go index 8d1183100ad..17fd27716bc 100644 --- a/server/service/openframe_windows_disk_encryption.go +++ b/server/service/openframe_windows_disk_encryption.go @@ -79,6 +79,16 @@ func (svc *Service) openframeAcceptsDiskEncryptionKey(ctx context.Context, host return asked.EverRequired, nil } +// openframeAcceptsKeyOutsideMDM reports whether a key is stored for a host that is not in MDM: it may have left MDM while +// fleetd was sending the key, and fleetd sends it again only while it is told to encrypt. Errors are not taken. +func (svc *Service) openframeAcceptsKeyOutsideMDM(ctx context.Context, host *fleet.Host, encryptionKey, clientError string) (bool, error) { + if encryptionKey == "" || clientError != "" || + !fleet.OpenframeWindowsDiskEncryptionEnabled(ctx) || host.FleetPlatform() != "windows" { + return false, nil + } + return svc.openframeAcceptsDiskEncryptionKey(ctx, host) +} + func (svc *Service) openframeRecordDiskEncryptionResult(ctx context.Context, host *fleet.Host, clientError string, keyStored bool) error { if !fleet.OpenframeWindowsDiskEncryptionEnabled(ctx) || host.FleetPlatform() != "windows" { return nil diff --git a/server/service/openframe_windows_disk_encryption_test.go b/server/service/openframe_windows_disk_encryption_test.go index 8e739ebfd91..3d1b13c9e03 100644 --- a/server/service/openframe_windows_disk_encryption_test.go +++ b/server/service/openframe_windows_disk_encryption_test.go @@ -217,6 +217,76 @@ func TestOpenframeDiskEncryptionKeyResult(t *testing.T) { require.False(t, ds.OpenframeRecordDiskEncryptionResultFuncInvoked) } +func TestOpenframeDiskEncryptionKeyOutsideMDM(t *testing.T) { + ds := new(mock.Store) + cfg := config.TestConfig() + cfg.MDM.WindowsWSTEPIdentityCert = "testdata/server.pem" + cfg.MDM.WindowsWSTEPIdentityKey = "testdata/server.key" + svc, ctx := newTestServiceWithConfig(t, ds, cfg, nil, nil) + openframe := fleet.NewOpenframeModeContext(ctx) + var asked fleet.OpenframeDiskEncryption + var askedErr error + ds.IsHostConnectedToFleetMDMFunc = func(context.Context, *fleet.Host) (bool, error) { return false, nil } + ds.OpenframeHostDiskEncryptionFunc = func(context.Context, *fleet.Host) (fleet.OpenframeDiskEncryption, error) { + return asked, askedErr + } + ds.TeamMDMConfigFunc = func(context.Context, uint) (*fleet.TeamMDM, error) { + return &fleet.TeamMDM{EnableDiskEncryption: true}, nil + } + ds.SetOrUpdateHostDiskEncryptionKeyFunc = func(_ context.Context, _ *fleet.Host, key, clientError string, decryptable *bool) (bool, error) { + require.NotEmpty(t, key) + require.Empty(t, clientError) + require.Equal(t, new(true), decryptable) + return false, nil + } + ds.OpenframeRecordDiskEncryptionResultFunc = func(_ context.Context, _ *fleet.Host, clientError string, keyStored bool) error { + require.Empty(t, clientError) + require.True(t, keyStored) + return nil + } + required := fleet.OpenframeDiskEncryption{Required: true, EverRequired: true} + + for _, c := range []struct { + name string + ctx context.Context + platform string + asked fleet.OpenframeDiskEncryption + key, clientError string + stored bool + }{ + {"required", openframe, "windows", required, "123456", "", true}, + {"lifted", openframe, "windows", fleet.OpenframeDiskEncryption{EverRequired: true}, "123456", "", true}, + {"never required", openframe, "windows", fleet.OpenframeDiskEncryption{}, "123456", "", false}, + {"error", openframe, "windows", required, "", "no TPM found", false}, + {"key with an error", openframe, "windows", required, "123456", "no TPM found", false}, + {"neither", openframe, "windows", required, "", "", false}, + {"another platform", openframe, "darwin", required, "123456", "", false}, + {"upstream", ctx, "windows", required, "123456", "", false}, + } { + t.Run(c.name, func(t *testing.T) { + asked = c.asked + ds.SetOrUpdateHostDiskEncryptionKeyFuncInvoked = false + ds.OpenframeRecordDiskEncryptionResultFuncInvoked = false + host := &fleet.Host{ID: 1, Platform: c.platform, TeamID: new(uint(7))} + + err := svc.SetOrUpdateDiskEncryptionKey(hostctx.NewContext(c.ctx, host), c.key, c.clientError) + + if c.stored { + require.NoError(t, err) + } else { + var badRequest *fleet.BadRequestError + require.ErrorAs(t, err, &badRequest) + } + require.Equal(t, c.stored, ds.SetOrUpdateHostDiskEncryptionKeyFuncInvoked) + require.Equal(t, c.stored, ds.OpenframeRecordDiskEncryptionResultFuncInvoked) + }) + } + + askedErr = errors.New("database is down") + host := &fleet.Host{ID: 1, Platform: "windows", TeamID: new(uint(7))} + require.ErrorIs(t, svc.SetOrUpdateDiskEncryptionKey(hostctx.NewContext(openframe, host), "123456", ""), askedErr) +} + func TestOpenframeDiskEncryptionStatusOnFree(t *testing.T) { ds := new(mock.Store) svc := &Service{ds: ds, logger: slog.New(slog.DiscardHandler)} diff --git a/server/service/orbit.go b/server/service/orbit.go index 542cccfa525..171dcb95a88 100644 --- a/server/service/orbit.go +++ b/server/service/orbit.go @@ -1374,7 +1374,15 @@ func (svc *Service) SetOrUpdateDiskEncryptionKey(ctx context.Context, encryption } if !connected { - return badRequest("host is not enrolled with fleet") + // >>> OPENFRAME(windows-disk-encryption): in OpenFrame mode a key is taken outside MDM, too, if the host was ever required to encrypt — openframe/docs/windows-disk-encryption.md + accepts, err := svc.openframeAcceptsKeyOutsideMDM(ctx, host, encryptionKey, clientError) + if err != nil { + return err + } + if !accepts { + return badRequest("host is not enrolled with fleet") + } + // <<< OPENFRAME(windows-disk-encryption) } // Only archive the key if disk encryption is enabled for this host (team/globally) From 830210182b54c51a52a4b582fe3f2f2d44c8a991 Mon Sep 17 00:00:00 2001 From: Andrii Koropets Date: Wed, 2 Dec 2026 00:53:47 +0200 Subject: [PATCH 6/7] fix(mdm): CU-17tkuw6a8db move the BitLocker requirement to the Windows MDM section --- server/fleet/service.go | 12 ++++++------ server/mock/service/service_mock.go | 24 ++++++++++++------------ 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/server/fleet/service.go b/server/fleet/service.go index 94c165f76c7..58835377892 100644 --- a/server/fleet/service.go +++ b/server/fleet/service.go @@ -1244,6 +1244,12 @@ type Service interface { // the specified team. NewMDMWindowsConfigProfile(ctx context.Context, teamID uint, profileName string, data []byte, labelsInclude []string, labelsMembershipMode MDMLabelsMode, labelsExcludeAny []string) (*MDMWindowsConfigProfile, error) + // >>> OPENFRAME(windows-disk-encryption): BitLocker required per host — openframe/docs/windows-disk-encryption.md + // OpenframeSetHostsDiskEncryption requires the Windows hosts to encrypt, or lifts that, and returns how many hosts it + // applied to. + OpenframeSetHostsDiskEncryption(ctx context.Context, hostIDs []uint, required bool) (uint, error) + // <<< OPENFRAME(windows-disk-encryption) + // NewMDMUnsupportedConfigProfile is called when a profile with an // unsupported extension is uploaded. NewMDMUnsupportedConfigProfile(ctx context.Context, teamID uint, filename string) error @@ -1269,12 +1275,6 @@ type Service interface { // Returns empty status if the host is not a supported Linux host LinuxHostDiskEncryptionStatus(ctx context.Context, host Host) (HostMDMDiskEncryption, error) - // >>> OPENFRAME(windows-disk-encryption): BitLocker required per host — openframe/docs/windows-disk-encryption.md - // OpenframeSetHostsDiskEncryption requires the Windows hosts to encrypt, or lifts that, and returns how many hosts it - // applied to. - OpenframeSetHostsDiskEncryption(ctx context.Context, hostIDs []uint, required bool) (uint, error) - // <<< OPENFRAME(windows-disk-encryption) - // GetMDMLinuxProfilesSummary summarizes the current status of Linux disk encryption for // the provided team (or hosts without a team if teamId is nil), or returns zeroes if disk // encryption is not enforced on the selected team diff --git a/server/mock/service/service_mock.go b/server/mock/service/service_mock.go index 59f87959390..42822f8ca32 100644 --- a/server/mock/service/service_mock.go +++ b/server/mock/service/service_mock.go @@ -766,6 +766,8 @@ type GetMDMWindowsProfilesSummaryFunc func(ctx context.Context, teamID *uint) (* type NewMDMWindowsConfigProfileFunc func(ctx context.Context, teamID uint, profileName string, data []byte, labelsInclude []string, labelsMembershipMode fleet.MDMLabelsMode, labelsExcludeAny []string) (*fleet.MDMWindowsConfigProfile, error) +type OpenframeSetHostsDiskEncryptionFunc func(ctx context.Context, hostIDs []uint, required bool) (uint, error) + type NewMDMUnsupportedConfigProfileFunc func(ctx context.Context, teamID uint, filename string) error type NewMDMInvalidJSONConfigProfileFunc func(ctx context.Context, teamID uint, err error) error @@ -776,8 +778,6 @@ type BatchSetMDMProfilesFunc func(ctx context.Context, teamID *uint, teamName *s type LinuxHostDiskEncryptionStatusFunc func(ctx context.Context, host fleet.Host) (fleet.HostMDMDiskEncryption, error) -type OpenframeSetHostsDiskEncryptionFunc func(ctx context.Context, hostIDs []uint, required bool) (uint, error) - type GetMDMLinuxProfilesSummaryFunc func(ctx context.Context, teamId *uint) (fleet.MDMProfilesSummary, error) type NewMDMAndroidConfigProfileFunc func(ctx context.Context, teamID uint, profileName string, data []byte, labelsInclude []string, labelsMembershipMode fleet.MDMLabelsMode, labelsExcludeAny []string) (*fleet.MDMAndroidConfigProfile, error) @@ -2080,6 +2080,9 @@ type Service struct { NewMDMWindowsConfigProfileFunc NewMDMWindowsConfigProfileFunc NewMDMWindowsConfigProfileFuncInvoked bool + OpenframeSetHostsDiskEncryptionFunc OpenframeSetHostsDiskEncryptionFunc + OpenframeSetHostsDiskEncryptionFuncInvoked bool + NewMDMUnsupportedConfigProfileFunc NewMDMUnsupportedConfigProfileFunc NewMDMUnsupportedConfigProfileFuncInvoked bool @@ -2095,9 +2098,6 @@ type Service struct { LinuxHostDiskEncryptionStatusFunc LinuxHostDiskEncryptionStatusFunc LinuxHostDiskEncryptionStatusFuncInvoked bool - OpenframeSetHostsDiskEncryptionFunc OpenframeSetHostsDiskEncryptionFunc - OpenframeSetHostsDiskEncryptionFuncInvoked bool - GetMDMLinuxProfilesSummaryFunc GetMDMLinuxProfilesSummaryFunc GetMDMLinuxProfilesSummaryFuncInvoked bool @@ -4985,6 +4985,13 @@ func (s *Service) NewMDMWindowsConfigProfile(ctx context.Context, teamID uint, p return s.NewMDMWindowsConfigProfileFunc(ctx, teamID, profileName, data, labelsInclude, labelsMembershipMode, labelsExcludeAny) } +func (s *Service) OpenframeSetHostsDiskEncryption(ctx context.Context, hostIDs []uint, required bool) (uint, error) { + s.mu.Lock() + s.OpenframeSetHostsDiskEncryptionFuncInvoked = true + s.mu.Unlock() + return s.OpenframeSetHostsDiskEncryptionFunc(ctx, hostIDs, required) +} + func (s *Service) NewMDMUnsupportedConfigProfile(ctx context.Context, teamID uint, filename string) error { s.mu.Lock() s.NewMDMUnsupportedConfigProfileFuncInvoked = true @@ -5020,13 +5027,6 @@ func (s *Service) LinuxHostDiskEncryptionStatus(ctx context.Context, host fleet. return s.LinuxHostDiskEncryptionStatusFunc(ctx, host) } -func (s *Service) OpenframeSetHostsDiskEncryption(ctx context.Context, hostIDs []uint, required bool) (uint, error) { - s.mu.Lock() - s.OpenframeSetHostsDiskEncryptionFuncInvoked = true - s.mu.Unlock() - return s.OpenframeSetHostsDiskEncryptionFunc(ctx, hostIDs, required) -} - func (s *Service) GetMDMLinuxProfilesSummary(ctx context.Context, teamId *uint) (fleet.MDMProfilesSummary, error) { s.mu.Lock() s.GetMDMLinuxProfilesSummaryFuncInvoked = true From 3d24a1cfd01268d041772734c379926e330efcf1 Mon Sep 17 00:00:00 2001 From: Andrii Koropets Date: Wed, 2 Dec 2026 13:57:46 +0200 Subject: [PATCH 7/7] fix(mdm): CU-17tkuw6a8db lift the old tenant's BitLocker requirement on team change and never look up a pinned tenant's key by serial --- openframe/docs/mysql-multitenancy-feature.md | 2 +- openframe/docs/windows-disk-encryption.md | 8 ++-- server/datastore/mysql/disk_encryption.go | 4 +- server/datastore/mysql/hosts.go | 5 +++ .../openframe_windows_disk_encryption.go | 27 ++++++++++++ .../openframe_windows_disk_encryption_test.go | 41 ++++++++++++++++++- 6 files changed, 80 insertions(+), 7 deletions(-) diff --git a/openframe/docs/mysql-multitenancy-feature.md b/openframe/docs/mysql-multitenancy-feature.md index ef6c8d54181..1f003e5db83 100644 --- a/openframe/docs/mysql-multitenancy-feature.md +++ b/openframe/docs/mysql-multitenancy-feature.md @@ -84,7 +84,7 @@ role-authz grouping upstream; here it is a hard boundary regardless of token rol - **disk encryption** (`openframe_host_disk_encryption`): only the pinned team's Windows hosts can be required or released, a call without a tenant is refused in shared mode, and the requirement counts only in the tenant it was set in (`OpenframeSetHostsDiskEncryption`, `OpenframeHostDiskEncryption`). `GetHostArchivedDiskEncryptionKey` does not - fall back to the hardware serial in OpenFrame mode ([windows-disk-encryption.md](windows-disk-encryption.md)). + fall back to the hardware serial in OpenFrame mode or for a pinned request ([windows-disk-encryption.md](windows-disk-encryption.md)). - **teams** — `TeamLite`/`ListTeams` read fence. - **app_config** cache (`cached_mysql.go`) — cache key includes the pinned team so one tenant's config is never served to another; unpinned keeps the constant key. diff --git a/openframe/docs/windows-disk-encryption.md b/openframe/docs/windows-disk-encryption.md index cb960224ae7..1d378fa9327 100644 --- a/openframe/docs/windows-disk-encryption.md +++ b/openframe/docs/windows-disk-encryption.md @@ -16,7 +16,8 @@ and Linux keep the team's setting, except the archived keys (below). - `openframe_host_disk_encryption` (`migrations/openframe/20261201000001_AddHostDiskEncryptionTable.go`) keeps a row per host that was ever required, with the tenant it was required in. Lifting keeps the row with `required = 0`. A host moved to another tenant is not required there, and starts there without the old tenant's error and key - time; deleting the host deletes the row. + time. The move lifts the old tenant's requirement in the same row, which keeps the old tenant: a consumer of the + row sees the requirement end. Deleting the host deletes the row. ## Result @@ -48,8 +49,9 @@ decrypted with the pair of the host's tenant. ## Archived keys -Without an archived key of the host itself, upstream returns one by hardware serial. In OpenFrame mode it does not, -on any platform: the serial can be another machine's, of the tenant or of another one. +Without an archived key of the host itself, upstream returns one by hardware serial. In OpenFrame mode, and for a +request pinned to a tenant, it does not, on any platform: the serial can be another machine's, of the tenant or of +another one. ## Known limits diff --git a/server/datastore/mysql/disk_encryption.go b/server/datastore/mysql/disk_encryption.go index 601fd681244..466321dabe2 100644 --- a/server/datastore/mysql/disk_encryption.go +++ b/server/datastore/mysql/disk_encryption.go @@ -317,8 +317,8 @@ LIMIT 1` var key fleet.HostArchivedDiskEncryptionKey err := sqlx.GetContext(ctx, ds.reader(ctx), &key, fmt.Sprintf(sqlFmt, `WHERE host_id = ?`), host.ID) - // >>> OPENFRAME(windows-disk-encryption): in OpenFrame mode a key is never looked up by serial: it can be another machine's, of any tenant — openframe/docs/windows-disk-encryption.md - if err == sql.ErrNoRows && host.HardwareSerial != "" && !openframeWindowsDiskEncryptionEnabled(ctx) { + // >>> OPENFRAME(windows-disk-encryption): in OpenFrame mode or pinned to a tenant a key is never looked up by serial: it can be another machine's, of any tenant — openframe/docs/windows-disk-encryption.md + if err == sql.ErrNoRows && host.HardwareSerial != "" && openframeArchivedKeyBySerial(ctx) { // <<< OPENFRAME(windows-disk-encryption) // If we didn't find a key by host ID, try to find it by hardware serial. ds.logger.DebugContext(ctx, "get archived disk encryption key by host serial", "serial", host.HardwareSerial, "host_id", host.ID) diff --git a/server/datastore/mysql/hosts.go b/server/datastore/mysql/hosts.go index 9c47c0abbd6..00b5ff108bc 100644 --- a/server/datastore/mysql/hosts.go +++ b/server/datastore/mysql/hosts.go @@ -3736,6 +3736,11 @@ func (ds *Datastore) AddHostsToTeam(ctx context.Context, params *fleet.AddHostsT if err := cleanupDiskEncryptionKeysOnTeamChangeDB(ctx, tx, hostIDsBatch, teamID); err != nil { return ctxerr.Wrap(ctx, err, "AddHostsToTeam cleanup disk encryption keys") } + // >>> OPENFRAME(windows-disk-encryption): the tenant a host left no longer requires it — openframe/docs/windows-disk-encryption.md + if err := openframeLiftDiskEncryptionOnTeamChange(ctx, tx, hostIDsBatch, teamID); err != nil { + return ctxerr.Wrap(ctx, err, "AddHostsToTeam lift disk encryption requirement") + } + // <<< OPENFRAME(windows-disk-encryption) return nil }, diff --git a/server/datastore/mysql/openframe_windows_disk_encryption.go b/server/datastore/mysql/openframe_windows_disk_encryption.go index 6241d113d37..d48caff9e4d 100644 --- a/server/datastore/mysql/openframe_windows_disk_encryption.go +++ b/server/datastore/mysql/openframe_windows_disk_encryption.go @@ -137,6 +137,33 @@ func openframeClearDiskEncryptionResults(ctx context.Context, tx sqlx.ExtContext return ctxerr.Wrap(ctx, err, "clear the disk encryption results") } +// openframeLiftDiskEncryptionOnTeamChange lifts the requirement of the tenant the hosts left, which keeps the row: its +// consumers see the requirement end. The tenant the hosts join has asked nothing yet. +func openframeLiftDiskEncryptionOnTeamChange(ctx context.Context, tx sqlx.ExtContext, hostIDs []uint, teamID *uint) error { + if !openframeWindowsDiskEncryptionEnabled(ctx) || len(hostIDs) == 0 { + return nil + } + stmt, args, err := sqlx.In(` + UPDATE openframe_host_disk_encryption + SET required = 0, client_error = '', key_stored_at = NULL + WHERE host_id IN (?) AND NOT (team_id <=> ?)`, hostIDs, teamID) + if err != nil { + return ctxerr.Wrap(ctx, err, "build the requirement lifted on team change") + } + _, err = tx.ExecContext(ctx, stmt, args...) + return ctxerr.Wrap(ctx, err, "lift the requirement on team change") +} + +// openframeArchivedKeyBySerial says whether upstream may look an archived key up by serial: not in OpenFrame mode and +// not for a request pinned to a tenant, where the serial can be another tenant's machine. +func openframeArchivedKeyBySerial(ctx context.Context) bool { + if openframeWindowsDiskEncryptionEnabled(ctx) { + return false + } + _, pinned := fleet.OpenframeTeamID(ctx) + return !pinned +} + // openframeDiskEncryptionConfig replaces the team's setting with the host's own requirement in OpenFrame mode. A // startup PIN is never required there. func (ds *Datastore) openframeDiskEncryptionConfig(ctx context.Context, host *fleet.Host) (fleet.DiskEncryptionConfig, error) { diff --git a/server/datastore/mysql/openframe_windows_disk_encryption_test.go b/server/datastore/mysql/openframe_windows_disk_encryption_test.go index 6d2f57ac7ac..dbcf9e44424 100644 --- a/server/datastore/mysql/openframe_windows_disk_encryption_test.go +++ b/server/datastore/mysql/openframe_windows_disk_encryption_test.go @@ -132,6 +132,40 @@ func TestOpenframeDiskEncryptionFollowsNoHostToAnotherTenant(t *testing.T) { f.requireAsked(t, h, true, true) } +func TestOpenframeDiskEncryptionLiftedOnTeamChange(t *testing.T) { + f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) + moved, stays := f.host(t, "de-a", "uuid-de-a", f.teamA.ID), f.host(t, "de-b", "uuid-de-b", f.teamA.ID) + ctxA := openframeDiskEncryptionCtx(t.Context(), f.teamA.ID) + _, err := f.ds.OpenframeSetHostsDiskEncryption(ctxA, []uint{moved.ID, stays.ID}, true) + require.NoError(t, err) + for _, h := range []*fleet.Host{moved, stays} { + require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctxA, h, "", true)) + require.NoError(t, f.ds.OpenframeRecordDiskEncryptionResult(ctxA, h, "no TPM found", false)) + } + failed := f.diskEncryptionRow(t, moved) + moveTo := func(ctx context.Context, teamID uint, h *fleet.Host) { + require.NoError(t, f.ds.AddHostsToTeam(ctx, fleet.NewAddHostsToTeamParams(&teamID, []uint{h.ID}))) + } + + moveTo(t.Context(), f.teamB.ID, moved) + moveTo(t.Context(), f.teamA.ID, moved) + require.Equal(t, failed, f.diskEncryptionRow(t, moved), "upstream outside OpenFrame mode") + + ctx := fleet.NewOpenframeModeContext(t.Context()) + moveTo(ctx, f.teamA.ID, stays) + f.requireAsked(t, stays, true, true) + + moveTo(ctx, f.teamB.ID, moved) + row := f.diskEncryptionRow(t, moved) + require.Equal(t, &f.teamA.ID, row.TeamID, "the row stays the old tenant's") + require.False(t, row.Required) + require.Empty(t, row.ClientError) + require.Nil(t, row.KeyStoredAt) + moved.TeamID = &f.teamB.ID + f.requireAsked(t, moved, false, false) + f.requireAsked(t, stays, true, true) +} + func TestOpenframeDiskEncryptionDeletedWithHost(t *testing.T) { f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) h := f.host(t, "de-a", "uuid-de-a", f.teamA.ID) @@ -210,12 +244,17 @@ func TestOpenframeDiskEncryptionArchivedKeyNotBySerial(t *testing.T) { _, err = f.ds.GetHostArchivedDiskEncryptionKey(ctxB, b) require.True(t, fleet.IsNotFound(err)) + _, err = f.ds.GetHostArchivedDiskEncryptionKey(fleet.NewOpenframeTeamContext(t.Context(), f.teamB.ID), b) + require.True(t, fleet.IsNotFound(err), "pinned to a tenant outside OpenFrame mode") + key, err = f.ds.GetHostArchivedDiskEncryptionKey(t.Context(), b) require.NoError(t, err) require.Equal(t, "key-a", key.Base64Encrypted, "upstream outside OpenFrame mode") } type openframeDiskEncryptionRow struct { + TeamID *uint `db:"team_id"` + Required bool `db:"required"` ClientError string `db:"client_error"` KeyStoredAt *time.Time `db:"key_stored_at"` UpdatedAt time.Time `db:"updated_at"` @@ -224,7 +263,7 @@ type openframeDiskEncryptionRow struct { func (f *openframeWindowsMDMFixture) diskEncryptionRow(t *testing.T, h *fleet.Host) openframeDiskEncryptionRow { var row openframeDiskEncryptionRow require.NoError(t, sqlx.GetContext(t.Context(), f.ds.reader(t.Context()), &row, - `SELECT client_error, key_stored_at, updated_at FROM openframe_host_disk_encryption WHERE host_id = ?`, h.ID)) + `SELECT team_id, required, client_error, key_stored_at, updated_at FROM openframe_host_disk_encryption WHERE host_id = ?`, h.ID)) return row }