From bc97e8bb2dfcbac8c857fca1bb74e976df0a279a Mon Sep 17 00:00:00 2001 From: Andrii Koropets Date: Thu, 3 Dec 2026 17:54:28 +0200 Subject: [PATCH 1/3] feat(mdm): CU-17tkuw6a8c2 lock Windows hosts with BitLocker on Fleet Free --- openframe/docs/README.md | 1 + openframe/docs/fork-file-manifest.md | 1 + openframe/docs/windows-lock.md | 94 +++++ openframe/scripts/verify.sh | 2 +- .../datastore/mysql/openframe_windows_lock.go | 93 +++++ .../mysql/openframe_windows_lock_test.go | 137 +++++++ server/datastore/mysql/scripts.go | 6 + server/fleet/api_scripts.go | 3 + server/fleet/datastore.go | 6 + server/fleet/openframe_windows_lock.go | 60 +++ server/fleet/service.go | 6 + server/mock/datastore_mock.go | 12 + server/mock/service/service_mock.go | 12 + server/service/openframe_windows_lock.go | 298 +++++++++++++++ server/service/openframe_windows_lock_test.go | 359 ++++++++++++++++++ server/service/orbit.go | 7 + server/service/scripts.go | 11 + 17 files changed, 1107 insertions(+), 1 deletion(-) create mode 100644 openframe/docs/windows-lock.md create mode 100644 server/datastore/mysql/openframe_windows_lock.go create mode 100644 server/datastore/mysql/openframe_windows_lock_test.go create mode 100644 server/fleet/openframe_windows_lock.go create mode 100644 server/service/openframe_windows_lock.go create mode 100644 server/service/openframe_windows_lock_test.go diff --git a/openframe/docs/README.md b/openframe/docs/README.md index af9802e0a40..84b6f9b7fb0 100644 --- a/openframe/docs/README.md +++ b/openframe/docs/README.md @@ -48,6 +48,7 @@ The agent has its own switch, `--openframe-mode` / `ORBIT_OPENFRAME_MODE`. | [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. | +| [windows-lock.md](windows-lock.md) | `POST /hosts/{id}/lock` locks Windows hosts on Fleet Free with BitLocker: forced recovery and a restart, with an optional message on the recovery screen; refused without a recovery key Fleet can decrypt and finds on the drive; the unlock script restores the TPM protector once the PC checks in after someone typed the key; only Fleet's own scripts in OpenFrame mode; `completed_lock` and `failed_lock` activities. | ## Agent-side (orbit / fleetd) diff --git a/openframe/docs/fork-file-manifest.md b/openframe/docs/fork-file-manifest.md index 02436afb7bd..2ffdf3d6415 100644 --- a/openframe/docs/fork-file-manifest.md +++ b/openframe/docs/fork-file-manifest.md @@ -176,6 +176,7 @@ and the heaviest standing rebase cost. | 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` | +| Windows lock (`openframe/docs/windows-lock.md`) | `server/service/{scripts,orbit,openframe_windows_lock}.go`, `server/fleet/{api_scripts,datastore,service,openframe_windows_lock}.go`, `server/mock/datastore_mock.go`, `server/mock/service/service_mock.go`, `server/datastore/mysql/{scripts,openframe_windows_lock}.go`; tests: `server/service/openframe_windows_lock_test.go`, `server/datastore/mysql/openframe_windows_lock_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/windows-lock.md b/openframe/docs/windows-lock.md new file mode 100644 index 00000000000..cb70ff8a0d4 --- /dev/null +++ b/openframe/docs/windows-lock.md @@ -0,0 +1,94 @@ +# Windows lock on Fleet Free (OpenFrame) + +Upstream locks Windows hosts on Premium only, with a script that disables local accounts. The fork's lock on Free +is a hard lock with BitLocker: the system drive is forced into recovery and the PC restarts to the BitLocker +recovery screen. It starts again only with the drive's recovery key, which Fleet holds. There is no unlock command: +someone types the key at the PC, and Fleet notices when the PC checks in again. + +Only in OpenFrame mode (`FLEET_OPENFRAME_MODE`) or shared mode, and only for Windows hosts; otherwise the request goes +to upstream's `LockHost` (402 on Free). + +## Request + +`POST /api/_version_/fleet/hosts/{id}/lock`, with an optional body `{"message": "..."}` +(`server/service/scripts.go`, `server/service/openframe_windows_lock.go`). The message, up to 240 characters with no +line breaks or other control characters, is set as the custom message of the recovery screen. + +Refused: + +- without permission to run MDM commands on the host's team (403); another tenant's host is 404; +- when fleetd doesn't run scripts on the host (`scripts_enabled` not true, or no fleetd) (422); +- with a pending lock, unlock or wipe, or when the host is locked (422) or wiped (409); +- when Fleet has no current recovery key for the host that it can decrypt (422, "Lock needs BitLocker"). An archived + key is not used: it may be of another disk. Windows MDM doesn't have to be on for the host, but the tenant's WSTEP + pair has to decrypt the key. + +The lock is queued by upstream's `LockHostViaScript` as an internal script, so the host's status is upstream's: pending +lock until fleetd reports the result, locked once it reports exit code 0. `locked_host` is recorded with the request. + +## The lock script + +It runs on the PC as SYSTEM, in PowerShell, and on `%SystemDrive%`: + +1. checks that BitLocker protects the drive (exit 2); +2. checks that one of the drive's recovery passwords is the key Fleet holds: the script carries its SHA-256, never + the key (exit 3). A locked PC that Fleet's key doesn't open could not be started again; +3. refuses a drive with a TPM protector that has a PIN or a startup key, which the lock would delete and the unlock + couldn't restore (exit 4); +4. records under `HKLM\SOFTWARE\OpenFrame\BitLockerLock` when it locked, whether the drive had a TPM protector, and + the recovery message policy it replaces; +5. sets the message, if any, as the recovery message policy (`HKLM\SOFTWARE\Policies\Microsoft\FVE`, + `RecoveryKeyMessageSource` = 2 and `RecoveryKeyMessage`). The message reaches the script in base64, so nothing in + it runs; +6. runs `manage-bde -forcerecovery`, which also deletes the drive's TPM protectors (exit 5 if it fails, with the + message and the record undone); +7. restarts the PC in 30 seconds, closing open apps, and exits 0, so that fleetd reports the result before it. + +A failed lock clears the pending lock and records `failed_lock` with the exit code; a lock that succeeded records +`completed_lock` (`server/fleet/openframe_windows_lock.go`). + +## Unlock + +When a locked Windows host checks in (orbit config) at least 15 minutes after its lock succeeded, someone has typed +the recovery key. The fork then queues an internal unlock script with upstream's `unlock_ref` +(`OpenframeQueueWindowsUnlock`, `server/datastore/mysql/openframe_windows_lock.go`), unless an unlock is pending, a +wipe is, or an unlock was tried within the last 15 minutes. The host's row is locked while the script is queued, so +concurrent check-ins queue one. + +The script: + +1. exits 0 if no lock is recorded on the PC; +2. exits 10 if the PC hasn't restarted since the lock: the host stays locked and the unlock is tried again later; +3. adds a TPM protector back if the drive had one, as `-forcerecovery` deleted it and Windows would otherwise ask for + the key at every start (exit 11 if it can't); +4. restores the recovery message policy and removes the record. + +Exit code 0 makes the host unlocked, as upstream, and records `unlocked_host` with no user. A failed unlock records +nothing. + +Wipe is refused while a host is locked, by upstream's checks. Fleet can't turn MDM off for a Windows host. + +## Scripts in OpenFrame mode + +fleetd on Windows runs scripts only when started with `--enable-scripts`, so OpenFrame has to start it with that flag; +without it the lock is refused. In +OpenFrame and shared mode the fork then refuses every script that isn't Fleet's own (`openframeRefuseScript`, in +upstream's `insertNewHostScriptExecution`): a user's, a batch's or a policy's script is refused (422) and not queued. +Internal scripts (lock, unlock, upstream's internal cleanups) and software installs and uninstalls are not affected. + +## Tenancy + +The lock reads the host through the fenced `Host`, so another tenant's host is 404, and decrypts the key with the +host's tenant's WSTEP pair. The unlock is queued for the host that authenticated the check-in, and its result is +recorded in that request's tenant. + +## Not verified on a real PC yet + +- that the recovery screen shows the message set by the policy; +- that fleetd always reports the lock's result within the 30 seconds before the restart. A result that is lost + leaves the host pending lock. + +## Tests + +- `server/service/openframe_windows_lock_test.go` +- `server/datastore/mysql/openframe_windows_lock_test.go` (`MYSQL_TEST=1`) diff --git a/openframe/scripts/verify.sh b/openframe/scripts/verify.sh index da7439345af..51dabaf3667 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 windows-disk-encryption; 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 windows-lock; 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/openframe_windows_lock.go b/server/datastore/mysql/openframe_windows_lock.go new file mode 100644 index 00000000000..9be348d8e4f --- /dev/null +++ b/server/datastore/mysql/openframe_windows_lock.go @@ -0,0 +1,93 @@ +// >>> OPENFRAME(windows-lock): BitLocker hard lock of Windows hosts on Fleet Free — openframe/docs/windows-lock.md + +package mysql + +import ( + "context" + "database/sql" + "errors" + "time" + + "github.com/fleetdm/fleet/v4/server/contexts/ctxerr" + "github.com/fleetdm/fleet/v4/server/fleet" + "github.com/jmoiron/sqlx" +) + +var errOpenframeOnlyInternalScripts = fleet.NewInvalidArgumentError("script", + "Fleet runs only its own scripts on hosts in OpenFrame mode.") + +func openframeWindowsLockEnabled(ctx context.Context) bool { + return fleet.OpenframeWindowsLockEnabled(ctx) || openframeSharedMode(ctx) +} + +// openframeRefuseScript refuses, in OpenFrame mode, a script a user or a policy asked for: fleetd runs scripts there +// for Fleet's own actions only. +func openframeRefuseScript(ctx context.Context, isInternal bool) error { + if isInternal || !openframeWindowsLockEnabled(ctx) { + return nil + } + return ctxerr.Wrap(ctx, errOpenframeOnlyInternalScripts) +} + +// openframeWindowsUnlockDue selects the locked Windows host whose unlock may be queued now: its lock succeeded at least +// the delay ago, nothing else is pending for it, and no unlock was tried within the delay. +const openframeWindowsUnlockDue = `SELECT hma.lock_ref + FROM host_mdm_actions hma + JOIN host_script_results lock_result ON lock_result.execution_id = hma.lock_ref AND lock_result.host_id = hma.host_id + WHERE hma.host_id = ? AND hma.fleet_platform = 'windows' AND hma.unlock_ref IS NULL AND hma.wipe_ref IS NULL + AND lock_result.exit_code = 0 AND lock_result.updated_at <= CURRENT_TIMESTAMP - INTERVAL ? SECOND + AND NOT EXISTS ( + SELECT 1 FROM host_script_results attempt + JOIN script_contents sc ON sc.id = attempt.script_content_id + WHERE attempt.host_id = hma.host_id AND sc.md5_checksum = UNHEX(?) + AND attempt.created_at > CURRENT_TIMESTAMP - INTERVAL ? SECOND)` + +// OpenframeQueueWindowsUnlock queues the unlock script of a locked Windows host and reports whether it did. A host that +// checks in while it is locked was unlocked with its recovery key; the script confirms the PC restarted after the lock +// and restores what the lock removed. +func (ds *Datastore) OpenframeQueueWindowsUnlock(ctx context.Context, hostID uint, script string, delay time.Duration) (bool, error) { + seconds := int64(delay / time.Second) + checksum := md5ChecksumScriptContent(script) + args := []any{hostID, seconds, checksum, seconds} + + var lockRef string + switch err := sqlx.GetContext(ctx, ds.reader(ctx), &lockRef, openframeWindowsUnlockDue, args...); { + case errors.Is(err, sql.ErrNoRows): + return false, nil + case err != nil: + return false, ctxerr.Wrap(ctx, err, "check whether a locked Windows host is due its unlock") + } + + var queued bool + err := ds.withRetryTxx(ctx, func(tx sqlx.ExtContext) error { + queued = false + if err := sqlx.GetContext(ctx, tx, &lockRef, openframeWindowsUnlockDue+` FOR UPDATE OF hma`, args...); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil + } + return ctxerr.Wrap(ctx, err, "lock the host's MDM actions") + } + contents, err := insertScriptContents(ctx, tx, script) + if err != nil { + return err + } + contentID, _ := contents.LastInsertId() + result, err := ds.newHostScriptExecutionRequest(ctx, tx, &fleet.HostScriptRequestPayload{ + HostID: hostID, + ScriptContents: script, + ScriptContentID: uint(contentID), //nolint:gosec // dismiss G115 + }, true) + if err != nil { + return ctxerr.Wrap(ctx, err, "queue the unlock script") + } + if _, err := tx.ExecContext(ctx, `UPDATE host_mdm_actions SET unlock_ref = ? WHERE host_id = ? AND lock_ref = ?`, + result.ExecutionID, hostID, lockRef); err != nil { + return ctxerr.Wrap(ctx, err, "record the unlock script") + } + queued = true + return nil + }) + return queued, err +} + +// <<< OPENFRAME(windows-lock) diff --git a/server/datastore/mysql/openframe_windows_lock_test.go b/server/datastore/mysql/openframe_windows_lock_test.go new file mode 100644 index 00000000000..921c5a21e57 --- /dev/null +++ b/server/datastore/mysql/openframe_windows_lock_test.go @@ -0,0 +1,137 @@ +// OPENFRAME(windows-lock) +package mysql + +import ( + "context" + "testing" + "time" + + "github.com/fleetdm/fleet/v4/server/fleet" + "github.com/stretchr/testify/require" +) + +const openframeTestUnlockScript = "Write-Output 'unlock'" + +func openframeLockCtx(ctx context.Context, teamID uint) context.Context { + return fleet.NewOpenframeModeContext(openframePinnedSharedCtx(ctx, teamID)) +} + +func (f *openframeWindowsMDMFixture) lock(t *testing.T, ctx context.Context, h *fleet.Host, exitCode int) string { + require.NoError(t, f.ds.LockHostViaScript(ctx, &fleet.HostScriptRequestPayload{HostID: h.ID, ScriptContents: "Write-Output 'lock " + h.UUID + "'"}, "windows")) + status, err := f.ds.GetHostLockWipeStatus(ctx, h) + require.NoError(t, err) + require.True(t, status.IsPendingLock()) + f.result(t, ctx, h, status.LockScript.ExecutionID, exitCode) + return status.LockScript.ExecutionID +} + +func (f *openframeWindowsMDMFixture) result(t *testing.T, ctx context.Context, h *fleet.Host, executionID string, exitCode int) { + _, _, err := f.ds.SetHostScriptExecutionResult(ctx, &fleet.HostScriptResultPayload{HostID: h.ID, ExecutionID: executionID, ExitCode: exitCode}, nil) + require.NoError(t, err) +} + +func (f *openframeWindowsMDMFixture) age(t *testing.T, h *fleet.Host, by time.Duration) { + f.exec(t, `UPDATE host_script_results SET created_at = created_at - INTERVAL ? SECOND, updated_at = updated_at - INTERVAL ? SECOND + WHERE host_id = ?`, int(by.Seconds()), int(by.Seconds()), h.ID) +} + +func (f *openframeWindowsMDMFixture) lockStatus(t *testing.T, ctx context.Context, h *fleet.Host) *fleet.HostLockWipeStatus { + status, err := f.ds.GetHostLockWipeStatus(ctx, h) + require.NoError(t, err) + return status +} + +func (f *openframeWindowsMDMFixture) queueUnlock(t *testing.T, ctx context.Context, h *fleet.Host) bool { + queued, err := f.ds.OpenframeQueueWindowsUnlock(ctx, h.ID, openframeTestUnlockScript, fleet.OpenframeWindowsUnlockDelay) + require.NoError(t, err) + return queued +} + +func TestOpenframeWindowsLockOnlyInternalScripts(t *testing.T) { + f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) + a := f.host(t, "lock-scripts-a", "uuid-lock-scripts-a", f.teamA.ID) + ctxA := openframeLockCtx(t.Context(), f.teamA.ID) + request := func() *fleet.HostScriptRequestPayload { + return &fleet.HostScriptRequestPayload{HostID: a.ID, ScriptContents: "Write-Output 'user'"} + } + + _, err := f.ds.NewHostScriptExecutionRequest(ctxA, request()) + require.ErrorIs(t, err, errOpenframeOnlyInternalScripts) + _, err = f.ds.NewHostScriptExecutionRequest(openframeSharedCtx(t.Context()), request()) + require.ErrorIs(t, err, errOpenframeOnlyInternalScripts, "shared mode is OpenFrame mode") + require.Zero(t, f.count(t, `SELECT COUNT(*) FROM upcoming_activities WHERE host_id = ?`, a.ID)) + + _, err = f.ds.NewInternalHostScriptExecutionRequest(ctxA, request()) + require.NoError(t, err) + _, err = f.ds.NewHostScriptExecutionRequest(t.Context(), request()) + require.NoError(t, err, "outside OpenFrame mode any script runs") +} + +func TestOpenframeWindowsUnlockQueued(t *testing.T) { + f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) + a := f.host(t, "lock-a", "uuid-lock-a", f.teamA.ID) + b := f.host(t, "lock-b", "uuid-lock-b", f.teamB.ID) + ctxA, ctxB := openframeLockCtx(t.Context(), f.teamA.ID), openframeLockCtx(t.Context(), f.teamB.ID) + + f.lock(t, ctxA, a, 0) + f.lock(t, ctxB, b, 0) + require.True(t, f.lockStatus(t, ctxA, a).IsLocked()) + require.False(t, f.queueUnlock(t, ctxA, a), "not before the delay: the PC is about to restart") + + f.age(t, a, fleet.OpenframeWindowsUnlockDelay+time.Minute) + require.True(t, f.queueUnlock(t, ctxA, a)) + status := f.lockStatus(t, ctxA, a) + require.True(t, status.IsLocked()) + require.True(t, status.IsPendingUnlock()) + require.False(t, f.queueUnlock(t, ctxA, a), "one unlock at a time") + require.Nil(t, f.lockStatus(t, ctxB, b).UnlockScript, "the other tenant's locked host is untouched") + + f.result(t, ctxA, a, status.UnlockScript.ExecutionID, 10) + status = f.lockStatus(t, ctxA, a) + require.True(t, status.IsLocked(), "a PC that hasn't restarted stays locked") + require.False(t, status.IsPendingUnlock()) + require.False(t, f.queueUnlock(t, ctxA, a), "not again within the delay of the last attempt") + + f.age(t, a, fleet.OpenframeWindowsUnlockDelay+time.Minute) + require.True(t, f.queueUnlock(t, ctxA, a)) + status = f.lockStatus(t, ctxA, a) + f.result(t, ctxA, a, status.UnlockScript.ExecutionID, 0) + status = f.lockStatus(t, ctxA, a) + require.True(t, status.IsUnlocked()) + require.Equal(t, fleet.PendingActionNone, status.PendingAction()) + require.False(t, f.queueUnlock(t, ctxA, a), "an unlocked host has nothing to unlock") + + require.True(t, f.lockStatus(t, ctxB, b).IsLocked()) + require.Equal(t, 1, f.count(t, `SELECT COUNT(*) FROM host_script_results WHERE host_id = ?`, b.ID), "only the lock ran on the other tenant's host") +} + +func TestOpenframeWindowsUnlockNotQueued(t *testing.T) { + f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) + ctx := openframeLockCtx(t.Context(), f.teamA.ID) + + failed := f.host(t, "lock-failed", "uuid-lock-failed", f.teamA.ID) + f.lock(t, ctx, failed, 3) + f.age(t, failed, 2*fleet.OpenframeWindowsUnlockDelay) + require.False(t, f.lockStatus(t, ctx, failed).IsLocked()) + require.False(t, f.queueUnlock(t, ctx, failed), "a lock that failed left the host unlocked") + + pending := f.host(t, "lock-pending", "uuid-lock-pending", f.teamA.ID) + require.NoError(t, f.ds.LockHostViaScript(ctx, &fleet.HostScriptRequestPayload{HostID: pending.ID, ScriptContents: "Write-Output 'lock pending'"}, "windows")) + f.age(t, pending, 2*fleet.OpenframeWindowsUnlockDelay) + require.False(t, f.queueUnlock(t, ctx, pending), "a lock without a result is pending") + + wiping := f.host(t, "lock-wiping", "uuid-lock-wiping", f.teamA.ID) + f.lock(t, ctx, wiping, 0) + f.age(t, wiping, 2*fleet.OpenframeWindowsUnlockDelay) + f.exec(t, `UPDATE host_mdm_actions SET wipe_ref = 'a-wipe' WHERE host_id = ?`, wiping.ID) + require.False(t, f.queueUnlock(t, ctx, wiping), "a host being wiped is not unlocked") + + linux := f.host(t, "lock-linux", "uuid-lock-linux", f.teamA.ID) + require.NoError(t, f.ds.LockHostViaScript(ctx, &fleet.HostScriptRequestPayload{HostID: linux.ID, ScriptContents: "echo lock"}, "linux")) + status := f.lockStatus(t, ctx, linux) + f.result(t, ctx, linux, status.LockScript.ExecutionID, 0) + f.age(t, linux, 2*fleet.OpenframeWindowsUnlockDelay) + require.False(t, f.queueUnlock(t, ctx, linux), "only a Windows lock is unlocked with its recovery key") + + require.Zero(t, f.count(t, `SELECT COUNT(*) FROM host_mdm_actions WHERE unlock_ref IS NOT NULL`)) +} diff --git a/server/datastore/mysql/scripts.go b/server/datastore/mysql/scripts.go index 9aad11d19d7..f679b466c88 100644 --- a/server/datastore/mysql/scripts.go +++ b/server/datastore/mysql/scripts.go @@ -121,6 +121,12 @@ VALUES ` ) + // >>> OPENFRAME(windows-lock): fleetd runs only Fleet's own scripts in OpenFrame mode — openframe/docs/windows-lock.md + if err := openframeRefuseScript(ctx, isInternal); err != nil { + return "", 0, err + } + // <<< OPENFRAME(windows-lock) + execID := uuid.New().String() result, err := tx.ExecContext(ctx, insUAStmt, request.HostID, diff --git a/server/fleet/api_scripts.go b/server/fleet/api_scripts.go index fa134d3820d..1a737038647 100644 --- a/server/fleet/api_scripts.go +++ b/server/fleet/api_scripts.go @@ -380,6 +380,9 @@ func (r BatchScriptRunResponse) Error() error { return r.Err } type LockHostRequest struct { HostID uint `url:"id"` ViewPin bool `query:"view_pin,optional"` + // >>> OPENFRAME(windows-lock): the message a Windows lock shows on the BitLocker recovery screen — openframe/docs/windows-lock.md + OpenframeMessage string `json:"message"` + // <<< OPENFRAME(windows-lock) } type LockHostResponse struct { diff --git a/server/fleet/datastore.go b/server/fleet/datastore.go index dc5cb0784d1..81a08f73d32 100644 --- a/server/fleet/datastore.go +++ b/server/fleet/datastore.go @@ -1261,6 +1261,12 @@ type Datastore interface { OpenframeRecordDiskEncryptionResult(ctx context.Context, host *Host, clientError string, keyStored bool) error // <<< OPENFRAME(windows-disk-encryption) + // >>> OPENFRAME(windows-lock): BitLocker hard lock of Windows hosts — openframe/docs/windows-lock.md + // OpenframeQueueWindowsUnlock queues the unlock script of a locked Windows host whose lock succeeded at least the + // delay ago, unless an unlock is pending or was tried within the delay, and reports whether it did. + OpenframeQueueWindowsUnlock(ctx context.Context, hostID uint, script string, delay time.Duration) (bool, error) + // <<< OPENFRAME(windows-lock) + // >>> 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_lock.go b/server/fleet/openframe_windows_lock.go new file mode 100644 index 00000000000..d85a1b6044a --- /dev/null +++ b/server/fleet/openframe_windows_lock.go @@ -0,0 +1,60 @@ +// >>> OPENFRAME(windows-lock): BitLocker hard lock of Windows hosts on Fleet Free — openframe/docs/windows-lock.md + +package fleet + +import ( + "context" + "time" +) + +// OpenframeWindowsLockMessageMaxLength is the longest message, in characters, a lock may show on the recovery screen. +const OpenframeWindowsLockMessageMaxLength = 240 + +// OpenframeWindowsUnlockDelay is how long after a lock succeeded, and after an unlock attempt, the host must check in +// before the unlock script is queued: the PC restarts to the recovery screen shortly after it reports the lock. +const OpenframeWindowsUnlockDelay = 15 * time.Minute + +// OpenframeWindowsLockEnabled reports whether Fleet Free locks Windows hosts with BitLocker and runs only its own +// scripts on hosts. Shared mode counts as OpenFrame mode: the two are separate settings. +func OpenframeWindowsLockEnabled(ctx context.Context) bool { + return IsOpenframeModeContext(ctx) || IsOpenframeSharedMode() +} + +type ActivityTypeOpenframeLockCompletedHost struct { + HostID uint `json:"host_id"` + HostDisplayName string `json:"host_display_name"` + HostPlatform string `json:"host_platform"` +} + +func (a ActivityTypeOpenframeLockCompletedHost) ActivityName() string { + return "completed_lock" +} + +func (a ActivityTypeOpenframeLockCompletedHost) HostIDs() []uint { + return []uint{a.HostID} +} + +func (a ActivityTypeOpenframeLockCompletedHost) WasFromAutomation() bool { + return true +} + +type ActivityTypeOpenframeLockFailedHost struct { + HostID uint `json:"host_id"` + HostDisplayName string `json:"host_display_name"` + HostPlatform string `json:"host_platform"` + ExitCode int `json:"exit_code"` +} + +func (a ActivityTypeOpenframeLockFailedHost) ActivityName() string { + return "failed_lock" +} + +func (a ActivityTypeOpenframeLockFailedHost) HostIDs() []uint { + return []uint{a.HostID} +} + +func (a ActivityTypeOpenframeLockFailedHost) WasFromAutomation() bool { + return true +} + +// <<< OPENFRAME(windows-lock) diff --git a/server/fleet/service.go b/server/fleet/service.go index 58835377892..1f60aba4ae9 100644 --- a/server/fleet/service.go +++ b/server/fleet/service.go @@ -1250,6 +1250,12 @@ type Service interface { OpenframeSetHostsDiskEncryption(ctx context.Context, hostIDs []uint, required bool) (uint, error) // <<< OPENFRAME(windows-disk-encryption) + // >>> OPENFRAME(windows-lock): BitLocker hard lock of Windows hosts — openframe/docs/windows-lock.md + // OpenframeLockWindowsHost queues the lock of a Windows host, which restarts it to the BitLocker recovery screen + // with the message, if any. It reports false, having done nothing, for a host of another platform. + OpenframeLockWindowsHost(ctx context.Context, hostID uint, message string) (bool, error) + // <<< OPENFRAME(windows-lock) + // NewMDMUnsupportedConfigProfile is called when a profile with an // unsupported extension is uploaded. NewMDMUnsupportedConfigProfile(ctx context.Context, teamID uint, filename string) error diff --git a/server/mock/datastore_mock.go b/server/mock/datastore_mock.go index b80ba961adf..3f10afdb2c4 100644 --- a/server/mock/datastore_mock.go +++ b/server/mock/datastore_mock.go @@ -874,6 +874,8 @@ type OpenframeHostDiskEncryptionFunc func(ctx context.Context, host *fleet.Host) type OpenframeRecordDiskEncryptionResultFunc func(ctx context.Context, host *fleet.Host, clientError string, keyStored bool) error +type OpenframeQueueWindowsUnlockFunc func(ctx context.Context, hostID uint, script string, delay time.Duration) (bool, error) + type OpenframeRefuseSharedHardwareUUIDFunc func(ctx context.Context, hostID uint, hardwareUUID string) error type UpdateHostFunc func(ctx context.Context, host *fleet.Host) error @@ -3432,6 +3434,9 @@ type DataStore struct { OpenframeRecordDiskEncryptionResultFunc OpenframeRecordDiskEncryptionResultFunc OpenframeRecordDiskEncryptionResultFuncInvoked bool + OpenframeQueueWindowsUnlockFunc OpenframeQueueWindowsUnlockFunc + OpenframeQueueWindowsUnlockFuncInvoked bool + OpenframeRefuseSharedHardwareUUIDFunc OpenframeRefuseSharedHardwareUUIDFunc OpenframeRefuseSharedHardwareUUIDFuncInvoked bool @@ -8333,6 +8338,13 @@ func (s *DataStore) OpenframeRecordDiskEncryptionResult(ctx context.Context, hos return s.OpenframeRecordDiskEncryptionResultFunc(ctx, host, clientError, keyStored) } +func (s *DataStore) OpenframeQueueWindowsUnlock(ctx context.Context, hostID uint, script string, delay time.Duration) (bool, error) { + s.mu.Lock() + s.OpenframeQueueWindowsUnlockFuncInvoked = true + s.mu.Unlock() + return s.OpenframeQueueWindowsUnlockFunc(ctx, hostID, script, delay) +} + 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 42822f8ca32..035ab3fe7be 100644 --- a/server/mock/service/service_mock.go +++ b/server/mock/service/service_mock.go @@ -768,6 +768,8 @@ type NewMDMWindowsConfigProfileFunc func(ctx context.Context, teamID uint, profi type OpenframeSetHostsDiskEncryptionFunc func(ctx context.Context, hostIDs []uint, required bool) (uint, error) +type OpenframeLockWindowsHostFunc func(ctx context.Context, hostID uint, message string) (bool, error) + type NewMDMUnsupportedConfigProfileFunc func(ctx context.Context, teamID uint, filename string) error type NewMDMInvalidJSONConfigProfileFunc func(ctx context.Context, teamID uint, err error) error @@ -2083,6 +2085,9 @@ type Service struct { OpenframeSetHostsDiskEncryptionFunc OpenframeSetHostsDiskEncryptionFunc OpenframeSetHostsDiskEncryptionFuncInvoked bool + OpenframeLockWindowsHostFunc OpenframeLockWindowsHostFunc + OpenframeLockWindowsHostFuncInvoked bool + NewMDMUnsupportedConfigProfileFunc NewMDMUnsupportedConfigProfileFunc NewMDMUnsupportedConfigProfileFuncInvoked bool @@ -4992,6 +4997,13 @@ func (s *Service) OpenframeSetHostsDiskEncryption(ctx context.Context, hostIDs [ return s.OpenframeSetHostsDiskEncryptionFunc(ctx, hostIDs, required) } +func (s *Service) OpenframeLockWindowsHost(ctx context.Context, hostID uint, message string) (bool, error) { + s.mu.Lock() + s.OpenframeLockWindowsHostFuncInvoked = true + s.mu.Unlock() + return s.OpenframeLockWindowsHostFunc(ctx, hostID, message) +} + func (s *Service) NewMDMUnsupportedConfigProfile(ctx context.Context, teamID uint, filename string) error { s.mu.Lock() s.NewMDMUnsupportedConfigProfileFuncInvoked = true diff --git a/server/service/openframe_windows_lock.go b/server/service/openframe_windows_lock.go new file mode 100644 index 00000000000..076db1adb04 --- /dev/null +++ b/server/service/openframe_windows_lock.go @@ -0,0 +1,298 @@ +// >>> OPENFRAME(windows-lock): Fleet Free locks Windows hosts with BitLocker — openframe/docs/windows-lock.md + +package service + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "net/http" + "strconv" + "strings" + "unicode" + "unicode/utf8" + + "github.com/fleetdm/fleet/v4/server/authz" + "github.com/fleetdm/fleet/v4/server/contexts/ctxerr" + "github.com/fleetdm/fleet/v4/server/fleet" + "github.com/fleetdm/fleet/v4/server/mdm" +) + +var ( + errOpenframeLockNoKey = fleet.NewInvalidArgumentError("host_id", + "Lock needs BitLocker. Fleet has no recovery key it can read for this PC, so a locked PC couldn't be started again.") + errOpenframeLockNoScripts = fleet.NewInvalidArgumentError("host_id", + "Can't lock the host because fleetd doesn't run scripts on it.") +) + +// OpenframeLockWindowsHost queues the lock of a Windows host: a script that forces the system drive into BitLocker +// recovery and restarts the PC, after checking on the PC that the recovery key Fleet holds unlocks the drive. +func (svc *Service) OpenframeLockWindowsHost(ctx context.Context, hostID uint, message string) (bool, error) { + if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil { + return false, err + } + host, err := svc.ds.Host(ctx, hostID) + if err != nil { + return false, ctxerr.Wrap(ctx, err, "get host") + } + if host.FleetPlatform() != "windows" { + return false, nil + } + if err := svc.authz.Authorize(ctx, fleet.MDMCommandAuthz{TeamID: host.TeamID}, fleet.ActionWrite); err != nil { + return false, err + } + + if err := openframeValidateWindowsLockMessage(message); err != nil { + return false, ctxerr.Wrap(ctx, err) + } + if host.OrbitNodeKey == nil || *host.OrbitNodeKey == "" || host.ScriptsEnabled == nil || !*host.ScriptsEnabled { + return false, ctxerr.Wrap(ctx, errOpenframeLockNoScripts) + } + + lockWipe, err := svc.ds.GetHostLockWipeStatus(ctx, host) + if err != nil { + return false, ctxerr.Wrap(ctx, err, "get host lock/wipe status") + } + switch { + case lockWipe.IsPendingLock(): + return false, ctxerr.Wrap(ctx, fleet.NewInvalidArgumentError("host_id", "Host has pending lock request. The host will lock when it comes online.")) + case lockWipe.IsPendingUnlock(): + return false, ctxerr.Wrap(ctx, fleet.NewInvalidArgumentError("host_id", "Host has pending unlock request. Host cannot be locked again until unlock is complete.")) + case lockWipe.IsPendingWipe(): + return false, ctxerr.Wrap(ctx, fleet.NewInvalidArgumentError("host_id", "Host has pending wipe request. The host will be wiped when it comes online.")) + case lockWipe.IsLocked(): + return false, ctxerr.Wrap(ctx, fleet.NewInvalidArgumentError("host_id", "Host is already locked.")) + case lockWipe.IsWiped(): + return false, ctxerr.Wrap(ctx, fleet.NewInvalidArgumentError("host_id", "Host is already wiped.").WithStatus(http.StatusConflict)) + } + + keyHash, err := svc.openframeWindowsRecoveryKeyHash(ctx, host) + if err != nil { + return false, err + } + + request := &fleet.HostScriptRequestPayload{ + HostID: host.ID, + ScriptContents: openframeWindowsLockScript(keyHash, message), + } + user := authz.UserFromContext(ctx) + if user != nil { + request.UserID = &user.ID + } + if err := svc.ds.LockHostViaScript(ctx, request, host.FleetPlatform()); err != nil { + return false, ctxerr.Wrap(ctx, err, "lock windows host") + } + + if err := svc.NewActivity(ctx, user, fleet.ActivityTypeLockedHost{ + HostID: host.ID, + HostDisplayName: host.DisplayName(), + }); err != nil { + return false, ctxerr.Wrap(ctx, err, "create activity for lock host request") + } + return true, nil +} + +func openframeValidateWindowsLockMessage(message string) error { + if !utf8.ValidString(message) || utf8.RuneCountInString(message) > fleet.OpenframeWindowsLockMessageMaxLength { + return fleet.NewInvalidArgumentError("message", + "The message can have up to "+strconv.Itoa(fleet.OpenframeWindowsLockMessageMaxLength)+" characters.") + } + if strings.IndexFunc(message, unicode.IsControl) >= 0 { + return fleet.NewInvalidArgumentError("message", "The message can't have line breaks or other control characters.") + } + return nil +} + +// openframeWindowsRecoveryKeyHash returns the SHA-256 of the host's current BitLocker recovery key, which the lock script +// looks for among the drive's recovery passwords. An archived key is not used: it may be of another disk. +func (svc *Service) openframeWindowsRecoveryKeyHash(ctx context.Context, host *fleet.Host) (string, error) { + key, err := svc.ds.GetHostDiskEncryptionKey(ctx, host.ID) + switch { + case fleet.IsNotFound(err): + return "", ctxerr.Wrap(ctx, errOpenframeLockNoKey) + case err != nil: + return "", ctxerr.Wrap(ctx, err, "get host disk encryption key") + case key.Base64Encrypted == "": + return "", ctxerr.Wrap(ctx, errOpenframeLockNoKey) + } + cert, err := svc.openframeWindowsWSTEPCertificate(ctx, host.TeamID, fleet.IsOpenframeSharedMode()) + if err != nil { + return "", ctxerr.Wrap(ctx, err, "get the WSTEP certificate to decrypt the recovery key") + } + decrypted, err := mdm.DecryptBase64CMS(key.Base64Encrypted, cert.Leaf, cert.PrivateKey) + recoveryKey := strings.TrimSpace(string(decrypted)) + if err != nil || recoveryKey == "" { + svc.logger.WarnContext(ctx, "the host's BitLocker recovery key can't be decrypted, not locking", "host_id", host.ID, "err", err) + return "", ctxerr.Wrap(ctx, errOpenframeLockNoKey) + } + sum := sha256.Sum256([]byte(recoveryKey)) + return hex.EncodeToString(sum[:]), nil +} + +// openframeQueueWindowsUnlock queues, in OpenFrame mode, the unlock script of a locked Windows host that checks in: a +// locked PC is back only once someone typed its recovery key. +func (svc *Service) openframeQueueWindowsUnlock(ctx context.Context, host *fleet.Host) { + if !fleet.OpenframeWindowsLockEnabled(ctx) || host.FleetPlatform() != "windows" { + return + } + if _, err := svc.ds.OpenframeQueueWindowsUnlock(ctx, host.ID, openframeWindowsUnlockScript, fleet.OpenframeWindowsUnlockDelay); err != nil { + svc.logger.ErrorContext(ctx, "failed to queue the unlock script of a locked Windows host", "host_id", host.ID, "err", err) + ctxerr.Handle(ctx, err) + } +} + +// openframeRecordWindowsLockResult records, in OpenFrame mode, what the lock or unlock script of a Windows host did. An +// unlock that failed records nothing: it is tried again. +func (svc *Service) openframeRecordWindowsLockResult(ctx context.Context, host *fleet.Host, action string, result *fleet.HostScriptResult) { + if !fleet.OpenframeWindowsLockEnabled(ctx) || host.FleetPlatform() != "windows" || result == nil || result.Canceled || result.ExitCode == nil { + return + } + succeeded := *result.ExitCode == 0 + var activity fleet.ActivityDetails + switch { + case action == "lock_ref" && succeeded: + activity = fleet.ActivityTypeOpenframeLockCompletedHost{HostID: host.ID, HostDisplayName: host.DisplayName(), HostPlatform: host.Platform} + case action == "lock_ref": + activity = fleet.ActivityTypeOpenframeLockFailedHost{ + HostID: host.ID, HostDisplayName: host.DisplayName(), HostPlatform: host.Platform, ExitCode: int(*result.ExitCode), + } + case action == "unlock_ref" && succeeded: + activity = fleet.ActivityTypeUnlockedHost{HostID: host.ID, HostDisplayName: host.DisplayName(), HostPlatform: host.Platform} + default: + return + } + if err := svc.NewActivity(context.WithoutCancel(ctx), nil, activity); err != nil { + svc.logger.ErrorContext(ctx, "failed to create the activity of a Windows lock result", "host_id", host.ID, "activity", activity.ActivityName(), "err", err) + ctxerr.Handle(ctx, err) + } +} + +const openframeWindowsLockState = `$drive = $env:SystemDrive +$stateKey = 'HKLM:\SOFTWARE\OpenFrame\BitLockerLock' +$policyKey = 'HKLM:\SOFTWARE\Policies\Microsoft\FVE' + +function Restore-RecoveryMessage($state) { + if ($state.MessageSet -ne 1) { return } + foreach ($name in 'RecoveryKeyMessageSource', 'RecoveryKeyMessage') { + $previous = $state."Previous$name" + if ($null -eq $previous) { + Remove-ItemProperty -Path $policyKey -Name $name -ErrorAction SilentlyContinue + } elseif ($name -eq 'RecoveryKeyMessageSource') { + Set-ItemProperty -Path $policyKey -Name $name -Value $previous -Type DWord + } else { + Set-ItemProperty -Path $policyKey -Name $name -Value $previous + } + } +} +` + +const openframeWindowsLockScriptTemplate = `$ErrorActionPreference = 'Stop' +$keyHash = '{{KEY_HASH}}' +$message = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('{{MESSAGE}}')) +` + openframeWindowsLockState + ` +try { + $volume = Get-BitLockerVolume -MountPoint $drive +} catch { + Write-Output "BitLocker isn't available on this PC: $_" + exit 2 +} +if ($volume.ProtectionStatus -ne 'On') { + Write-Output "BitLocker doesn't protect $drive." + exit 2 +} + +$sha256 = [Security.Cryptography.SHA256]::Create() +$keyOnDrive = $false +foreach ($protector in $volume.KeyProtector) { + if ($protector.KeyProtectorType -ne 'RecoveryPassword') { continue } + $bytes = [Text.Encoding]::UTF8.GetBytes($protector.RecoveryPassword.Trim()) + $hash = -join ($sha256.ComputeHash($bytes) | ForEach-Object { $_.ToString('x2') }) + if ($hash -eq $keyHash) { $keyOnDrive = $true } +} +if (-not $keyOnDrive) { + Write-Output "The recovery key Fleet holds for this PC doesn't unlock $drive." + exit 3 +} + +$tpm = @($volume.KeyProtector | Where-Object { "$($_.KeyProtectorType)" -like 'Tpm*' }) +if (@($tpm | Where-Object { "$($_.KeyProtectorType)" -ne 'Tpm' }).Count -gt 0) { + Write-Output "$drive has a TPM protector with a PIN or a startup key, which the lock would delete and can't restore." + exit 4 +} + +$state = Get-ItemProperty -Path $stateKey -ErrorAction SilentlyContinue +if ($null -eq $state) { + New-Item -Path $stateKey -Force | Out-Null + $policy = Get-ItemProperty -Path $policyKey -ErrorAction SilentlyContinue + foreach ($name in 'RecoveryKeyMessageSource', 'RecoveryKeyMessage') { + if ($null -ne $policy -and $null -ne $policy.$name) { + Set-ItemProperty -Path $stateKey -Name "Previous$name" -Value $policy.$name + } + } + Set-ItemProperty -Path $stateKey -Name HadTpm -Value ([int]($tpm.Count -gt 0)) -Type DWord +} elseif ($tpm.Count -gt 0) { + Set-ItemProperty -Path $stateKey -Name HadTpm -Value 1 -Type DWord +} +Set-ItemProperty -Path $stateKey -Name LockedAt -Value ([DateTime]::UtcNow.Ticks) -Type QWord + +if ($message -ne '') { + if (-not (Test-Path $policyKey)) { New-Item -Path $policyKey | Out-Null } + Set-ItemProperty -Path $policyKey -Name RecoveryKeyMessageSource -Value 2 -Type DWord + Set-ItemProperty -Path $policyKey -Name RecoveryKeyMessage -Value $message + Set-ItemProperty -Path $stateKey -Name MessageSet -Value 1 -Type DWord +} + +$output = & manage-bde.exe -forcerecovery $drive 2>&1 +if ($LASTEXITCODE -ne 0) { + Write-Output "manage-bde -forcerecovery failed with exit code ${LASTEXITCODE}: $output" + Restore-RecoveryMessage (Get-ItemProperty -Path $stateKey) + Remove-Item -Path $stateKey -Recurse -Force + exit 5 +} + +& shutdown.exe /r /f /t 30 /d p:4:1 /c 'This PC is locked. It starts again with its BitLocker recovery key.' +Write-Output "Locked $drive; the PC restarts to the BitLocker recovery screen in 30 seconds." +exit 0 +` + +const openframeWindowsUnlockScript = `$ErrorActionPreference = 'Stop' +` + openframeWindowsLockState + ` +$state = Get-ItemProperty -Path $stateKey -ErrorAction SilentlyContinue +if ($null -eq $state) { + Write-Output "No lock is recorded on this PC." + exit 0 +} + +$bootedAt = (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().Ticks +if ($bootedAt -le [long]$state.LockedAt) { + Write-Output "The PC hasn't restarted since it was locked." + exit 10 +} + +if ($state.HadTpm -eq 1) { + $volume = Get-BitLockerVolume -MountPoint $drive + if (-not ($volume.KeyProtector | Where-Object { "$($_.KeyProtectorType)" -eq 'Tpm' })) { + try { + Add-BitLockerKeyProtector -MountPoint $drive -TpmProtector | Out-Null + } catch { + Write-Output "The PC was unlocked, but its TPM protector couldn't be added back: $_" + exit 11 + } + } +} + +Restore-RecoveryMessage $state +Remove-Item -Path $stateKey -Recurse -Force +Write-Output "Unlocked: the PC started with its recovery key." +exit 0 +` + +func openframeWindowsLockScript(keyHash, message string) string { + return strings.NewReplacer( + "{{KEY_HASH}}", keyHash, + "{{MESSAGE}}", base64.StdEncoding.EncodeToString([]byte(message)), + ).Replace(openframeWindowsLockScriptTemplate) +} + +// <<< OPENFRAME(windows-lock) diff --git a/server/service/openframe_windows_lock_test.go b/server/service/openframe_windows_lock_test.go new file mode 100644 index 00000000000..c7b1a4d1108 --- /dev/null +++ b/server/service/openframe_windows_lock_test.go @@ -0,0 +1,359 @@ +// OPENFRAME(windows-lock) +package service + +import ( + "context" + "crypto/sha256" + "crypto/tls" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "strings" + "testing" + "time" + + activity_api "github.com/fleetdm/fleet/v4/server/activity/api" + "github.com/fleetdm/fleet/v4/server/authz" + "github.com/fleetdm/fleet/v4/server/config" + "github.com/fleetdm/fleet/v4/server/contexts/viewer" + "github.com/fleetdm/fleet/v4/server/fleet" + microsoft_mdm "github.com/fleetdm/fleet/v4/server/mdm/microsoft" + "github.com/fleetdm/fleet/v4/server/mock" + "github.com/stretchr/testify/require" +) + +const openframeTestRecoveryKey = "111111-222222-333333-444444-555555-666666-777777-888888" + +type openframeWindowsLockFixture struct { + svc fleet.Service + impl *Service + ctx context.Context + baseCtx context.Context + ds *mock.Store + host *fleet.Host + status *fleet.HostLockWipeStatus + key *fleet.HostDiskEncryptionKey + keyErr error + request *fleet.HostScriptRequestPayload + platform string + activities []activity_api.ActivityDetails +} + +func newOpenframeWindowsLockFixture(t *testing.T) *openframeWindowsLockFixture { + cfg := config.TestConfig() + cfg.MDM.WindowsWSTEPIdentityCert = "testdata/server.pem" + cfg.MDM.WindowsWSTEPIdentityKey = "testdata/server.key" + cert, err := tls.LoadX509KeyPair(cfg.MDM.WindowsWSTEPIdentityCert, cfg.MDM.WindowsWSTEPIdentityKey) + require.NoError(t, err) + encrypted, err := microsoft_mdm.Encrypt(openframeTestRecoveryKey+"\n", cert.Leaf) + require.NoError(t, err) + + f := &openframeWindowsLockFixture{ + ds: new(mock.Store), + host: &fleet.Host{ + ID: 1, UUID: "uuid-1", Hostname: "pc-1", Platform: "windows", TeamID: new(uint(7)), + OrbitNodeKey: new("orbit-key"), ScriptsEnabled: new(true), + }, + status: &fleet.HostLockWipeStatus{HostFleetPlatform: "windows"}, + key: &fleet.HostDiskEncryptionKey{HostID: 1, Base64Encrypted: encrypted}, + } + opts := &TestServerOpts{} + f.svc, f.ctx = newTestServiceWithConfig(t, f.ds, cfg, nil, nil, opts) + f.impl = f.svc.(validationMiddleware).Service.(*Service) + f.baseCtx = f.ctx + opts.ActivityMock.NewActivityFunc = func(_ context.Context, _ *activity_api.User, details activity_api.ActivityDetails) error { + f.activities = append(f.activities, details) + return nil + } + f.ctx = fleet.NewOpenframeModeContext(viewer.NewContext(f.ctx, viewer.Viewer{User: &fleet.User{ID: 3, GlobalRole: new(fleet.RoleAdmin)}})) + + f.ds.HostFunc = func(_ context.Context, id uint) (*fleet.Host, error) { + if id != f.host.ID { + return nil, newNotFoundError() + } + return f.host, nil + } + f.ds.GetHostLockWipeStatusFunc = func(context.Context, *fleet.Host) (*fleet.HostLockWipeStatus, error) { return f.status, nil } + f.ds.GetHostDiskEncryptionKeyFunc = func(_ context.Context, hostID uint) (*fleet.HostDiskEncryptionKey, error) { + require.Equal(t, f.host.ID, hostID) + return f.key, f.keyErr + } + f.ds.LockHostViaScriptFunc = func(_ context.Context, request *fleet.HostScriptRequestPayload, platform string) error { + f.request, f.platform = request, platform + return nil + } + return f +} + +func (f *openframeWindowsLockFixture) lock(message string) (bool, error) { + return f.svc.OpenframeLockWindowsHost(f.ctx, f.host.ID, message) +} + +func openframeTestKeyHash(key string) string { + sum := sha256.Sum256([]byte(key)) + return hex.EncodeToString(sum[:]) +} + +func TestOpenframeLockWindowsHostQueuesScript(t *testing.T) { + f := newOpenframeWindowsLockFixture(t) + message := "Property of Example Ltd. Call +1 555 0100 — ünïcödé" + + locked, err := f.lock(message) + require.NoError(t, err) + require.True(t, locked) + + require.Equal(t, "windows", f.platform) + require.Equal(t, f.host.ID, f.request.HostID) + require.Equal(t, new(uint(3)), f.request.UserID) + script := f.request.ScriptContents + require.Contains(t, script, "$keyHash = '"+openframeTestKeyHash(openframeTestRecoveryKey)+"'", "the key is trimmed before hashing") + require.Contains(t, script, "FromBase64String('"+base64.StdEncoding.EncodeToString([]byte(message))+"')") + require.NotContains(t, script, openframeTestRecoveryKey, "the script never carries the key") + require.NotContains(t, script, "Example Ltd", "the message is only in base64") + require.Contains(t, script, "manage-bde.exe -forcerecovery $drive") + require.Contains(t, script, "shutdown.exe /r /f /t 30") + require.Less(t, strings.Index(script, "$keyOnDrive"), strings.Index(script, "-forcerecovery"), "the key is checked on the PC first") + + require.Equal(t, []activity_api.ActivityDetails{ + fleet.ActivityTypeLockedHost{HostID: f.host.ID, HostDisplayName: "pc-1"}, + }, f.activities) +} + +func TestOpenframeLockWindowsHostMessageLength(t *testing.T) { + f := newOpenframeWindowsLockFixture(t) + _, err := f.lock(strings.Repeat("é", fleet.OpenframeWindowsLockMessageMaxLength)) + require.NoError(t, err, "the limit counts characters, not bytes") + + f = newOpenframeWindowsLockFixture(t) + locked, err := f.lock("") + require.NoError(t, err) + require.True(t, locked) + require.Contains(t, f.request.ScriptContents, "FromBase64String('')") +} + +func TestOpenframeLockWindowsHostRefused(t *testing.T) { + cases := []struct { + name string + message string + setup func(f *openframeWindowsLockFixture) + status int + msg string + }{ + {"message too long", strings.Repeat("a", fleet.OpenframeWindowsLockMessageMaxLength+1), nil, http.StatusUnprocessableEntity, "up to 240 characters"}, + {"message with a line break", "call\nme", nil, http.StatusUnprocessableEntity, "line breaks"}, + {"message not UTF-8", "\xff", nil, http.StatusUnprocessableEntity, "up to 240 characters"}, + {"scripts off in fleetd", "", func(f *openframeWindowsLockFixture) { f.host.ScriptsEnabled = new(false) }, http.StatusUnprocessableEntity, "doesn't run scripts"}, + {"scripts unknown", "", func(f *openframeWindowsLockFixture) { f.host.ScriptsEnabled = nil }, http.StatusUnprocessableEntity, "doesn't run scripts"}, + {"no fleetd", "", func(f *openframeWindowsLockFixture) { f.host.OrbitNodeKey = nil }, http.StatusUnprocessableEntity, "doesn't run scripts"}, + {"pending lock", "", func(f *openframeWindowsLockFixture) { + f.status.LockScript = &fleet.HostScriptResult{} + }, http.StatusUnprocessableEntity, "pending lock"}, + {"locked", "", func(f *openframeWindowsLockFixture) { + f.status.LockScript = &fleet.HostScriptResult{ExitCode: new(int64(0))} + }, http.StatusUnprocessableEntity, "already locked"}, + {"pending unlock", "", func(f *openframeWindowsLockFixture) { + f.status.UnlockScript = &fleet.HostScriptResult{} + }, http.StatusUnprocessableEntity, "pending unlock"}, + {"pending wipe", "", func(f *openframeWindowsLockFixture) { + f.status.WipeMDMCommand = &fleet.MDMCommand{} + }, http.StatusUnprocessableEntity, "pending wipe"}, + {"wiped", "", func(f *openframeWindowsLockFixture) { + f.status.WipeMDMCommand = &fleet.MDMCommand{} + f.status.WipeMDMCommandResult = &fleet.MDMCommandResult{Status: "200"} + }, http.StatusConflict, "already wiped"}, + {"no key", "", func(f *openframeWindowsLockFixture) { f.key, f.keyErr = nil, newNotFoundError() }, http.StatusUnprocessableEntity, "Lock needs BitLocker"}, + {"key with a client error only", "", func(f *openframeWindowsLockFixture) { + f.key = &fleet.HostDiskEncryptionKey{HostID: 1, ClientError: "no TPM"} + }, http.StatusUnprocessableEntity, "Lock needs BitLocker"}, + {"key not decryptable", "", func(f *openframeWindowsLockFixture) { + f.key = &fleet.HostDiskEncryptionKey{HostID: 1, Base64Encrypted: base64.StdEncoding.EncodeToString([]byte("not cms"))} + }, http.StatusUnprocessableEntity, "Lock needs BitLocker"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newOpenframeWindowsLockFixture(t) + if tc.setup != nil { + tc.setup(f) + } + locked, err := f.lock(tc.message) + require.False(t, locked) + require.ErrorContains(t, err, tc.msg) + status := http.StatusUnprocessableEntity + var withStatus interface{ Status() int } + if errors.As(err, &withStatus) { + status = withStatus.Status() + } else { + var invalid *fleet.InvalidArgumentError + require.ErrorAs(t, err, &invalid) + } + require.Equal(t, tc.status, status) + require.False(t, f.ds.LockHostViaScriptFuncInvoked) + require.Empty(t, f.activities) + }) + } +} + +func TestOpenframeLockWindowsHostAccess(t *testing.T) { + t.Run("another tenant's host", func(t *testing.T) { + f := newOpenframeWindowsLockFixture(t) + _, err := f.svc.OpenframeLockWindowsHost(f.ctx, 2, "") + require.True(t, fleet.IsNotFound(err)) + require.False(t, f.ds.GetHostDiskEncryptionKeyFuncInvoked) + }) + t.Run("observer", func(t *testing.T) { + f := newOpenframeWindowsLockFixture(t) + ctx := fleet.NewOpenframeModeContext(viewer.NewContext(f.baseCtx, viewer.Viewer{User: &fleet.User{ID: 4, GlobalRole: new(fleet.RoleObserver)}})) + _, err := f.svc.OpenframeLockWindowsHost(ctx, f.host.ID, "") + var forbidden *authz.Forbidden + require.ErrorAs(t, err, &forbidden) + require.False(t, f.ds.LockHostViaScriptFuncInvoked) + }) + t.Run("another platform", func(t *testing.T) { + f := newOpenframeWindowsLockFixture(t) + f.host.Platform = "darwin" + locked, err := f.lock("") + require.NoError(t, err) + require.False(t, locked, "left to upstream") + require.False(t, f.ds.GetHostLockWipeStatusFuncInvoked) + }) +} + +func TestOpenframeLockEndpoint(t *testing.T) { + call := func(f *openframeWindowsLockFixture, ctx context.Context) fleet.LockHostResponse { + t.Helper() + resp, err := lockHostEndpoint(ctx, &fleet.LockHostRequest{HostID: f.host.ID, OpenframeMessage: "call IT"}, f.svc) + require.NoError(t, err) + switch r := resp.(type) { + case *fleet.LockHostResponse: + return *r + case fleet.LockHostResponse: + return r + } + t.Fatalf("unexpected response %T", resp) + return fleet.LockHostResponse{} + } + + f := newOpenframeWindowsLockFixture(t) + resp := call(f, f.ctx) + require.NoError(t, resp.Err) + require.Equal(t, fleet.PendingActionLock, resp.PendingAction) + require.Equal(t, fleet.DeviceStatusUnlocked, resp.DeviceStatus) + require.Contains(t, f.request.ScriptContents, base64.StdEncoding.EncodeToString([]byte("call IT"))) + + f = newOpenframeWindowsLockFixture(t) + f.host.Platform = "darwin" + require.ErrorIs(t, call(f, f.ctx).Err, fleet.ErrMissingLicense, "another platform goes to upstream") + + f = newOpenframeWindowsLockFixture(t) + outside := viewer.NewContext(f.baseCtx, viewer.Viewer{User: &fleet.User{ID: 3, GlobalRole: new(fleet.RoleAdmin)}}) + require.ErrorIs(t, call(f, outside).Err, fleet.ErrMissingLicense, "upstream outside OpenFrame mode") + require.False(t, f.ds.LockHostViaScriptFuncInvoked) +} + +func TestOpenframeWindowsLockResultActivities(t *testing.T) { + host := &fleet.Host{ID: 1, Hostname: "pc-1", Platform: "windows"} + exit := func(code int64) *fleet.HostScriptResult { return &fleet.HostScriptResult{ExitCode: &code} } + cases := []struct { + name string + host *fleet.Host + action string + result *fleet.HostScriptResult + outside bool + expected []activity_api.ActivityDetails + }{ + {"lock done", host, "lock_ref", exit(0), false, []activity_api.ActivityDetails{ + fleet.ActivityTypeOpenframeLockCompletedHost{HostID: 1, HostDisplayName: "pc-1", HostPlatform: "windows"}, + }}, + {"lock failed", host, "lock_ref", exit(3), false, []activity_api.ActivityDetails{ + fleet.ActivityTypeOpenframeLockFailedHost{HostID: 1, HostDisplayName: "pc-1", HostPlatform: "windows", ExitCode: 3}, + }}, + {"unlocked", host, "unlock_ref", exit(0), false, []activity_api.ActivityDetails{ + fleet.ActivityTypeUnlockedHost{HostID: 1, HostDisplayName: "pc-1", HostPlatform: "windows"}, + }}, + {"not restarted yet", host, "unlock_ref", exit(10), false, nil}, + {"another script", host, "", exit(0), false, nil}, + {"wipe", host, "wipe_ref", exit(0), false, nil}, + {"duplicate result", host, "lock_ref", nil, false, nil}, + {"canceled", host, "lock_ref", &fleet.HostScriptResult{Canceled: true, ExitCode: new(int64(0))}, false, nil}, + {"no exit code", host, "lock_ref", &fleet.HostScriptResult{}, false, nil}, + {"linux", &fleet.Host{ID: 2, Platform: "ubuntu"}, "lock_ref", exit(0), false, nil}, + {"outside OpenFrame mode", host, "lock_ref", exit(0), true, nil}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newOpenframeWindowsLockFixture(t) + ctx := f.ctx + if tc.outside { + ctx = f.baseCtx + } + f.impl.openframeRecordWindowsLockResult(ctx, tc.host, tc.action, tc.result) + require.Equal(t, tc.expected, f.activities) + }) + } +} + +func TestOpenframeLockActivities(t *testing.T) { + completed := fleet.ActivityTypeOpenframeLockCompletedHost{HostID: 42, HostDisplayName: "pc-1", HostPlatform: "windows"} + require.Equal(t, "completed_lock", completed.ActivityName()) + require.Equal(t, []uint{42}, completed.HostIDs()) + require.True(t, completed.WasFromAutomation()) + details, err := json.Marshal(completed) + require.NoError(t, err) + require.JSONEq(t, `{"host_id": 42, "host_display_name": "pc-1", "host_platform": "windows"}`, string(details)) + + failed := fleet.ActivityTypeOpenframeLockFailedHost{HostID: 42, HostDisplayName: "pc-1", HostPlatform: "windows", ExitCode: 3} + require.Equal(t, "failed_lock", failed.ActivityName()) + require.Equal(t, []uint{42}, failed.HostIDs()) + require.True(t, failed.WasFromAutomation()) + details, err = json.Marshal(failed) + require.NoError(t, err) + require.JSONEq(t, `{"host_id": 42, "host_display_name": "pc-1", "host_platform": "windows", "exit_code": 3}`, string(details)) +} + +func TestOpenframeWindowsUnlockQueuedOnCheckIn(t *testing.T) { + cases := []struct { + name string + host *fleet.Host + outside bool + queued bool + }{ + {"Windows host", &fleet.Host{ID: 1, Platform: "windows"}, false, true}, + {"Linux host", &fleet.Host{ID: 1, Platform: "ubuntu"}, false, false}, + {"outside OpenFrame mode", &fleet.Host{ID: 1, Platform: "windows"}, true, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newOpenframeWindowsLockFixture(t) + f.ds.OpenframeQueueWindowsUnlockFunc = func(_ context.Context, hostID uint, script string, delay time.Duration) (bool, error) { + require.Equal(t, tc.host.ID, hostID) + require.Equal(t, openframeWindowsUnlockScript, script) + require.Equal(t, fleet.OpenframeWindowsUnlockDelay, delay) + return true, nil + } + ctx := f.ctx + if tc.outside { + ctx = f.baseCtx + } + f.impl.openframeQueueWindowsUnlock(ctx, tc.host) + require.Equal(t, tc.queued, f.ds.OpenframeQueueWindowsUnlockFuncInvoked) + }) + } + + f := newOpenframeWindowsLockFixture(t) + f.ds.OpenframeQueueWindowsUnlockFunc = func(context.Context, uint, string, time.Duration) (bool, error) { + return false, errors.New("database is down") + } + f.impl.openframeQueueWindowsUnlock(f.ctx, &fleet.Host{ID: 1, Platform: "windows"}) + require.True(t, f.ds.OpenframeQueueWindowsUnlockFuncInvoked, "an error doesn't fail the check-in") +} + +func TestOpenframeWindowsUnlockScript(t *testing.T) { + script := openframeWindowsUnlockScript + require.Contains(t, script, "LastBootUpTime") + require.Contains(t, script, "exit 10") + require.Contains(t, script, "Add-BitLockerKeyProtector -MountPoint $drive -TpmProtector") + require.Less(t, strings.Index(script, "exit 10"), strings.Index(script, "Add-BitLockerKeyProtector"), "nothing changes before the PC restarted") + require.Contains(t, script, "Restore-RecoveryMessage $state") +} diff --git a/server/service/orbit.go b/server/service/orbit.go index 171dcb95a88..e3da2cee8fd 100644 --- a/server/service/orbit.go +++ b/server/service/orbit.go @@ -655,6 +655,10 @@ func (svc *Service) GetOrbitConfig(ctx context.Context) (fleet.OrbitConfig, erro } } + // >>> OPENFRAME(windows-lock): a locked Windows host that checks in was unlocked with its recovery key — openframe/docs/windows-lock.md + svc.openframeQueueWindowsUnlock(ctx, host) + // <<< OPENFRAME(windows-lock) + // load the (active, ready to execute) pending script executions for that host pending, err := svc.ds.ListReadyToExecuteScriptsForHost(ctx, host.ID, appConfig.ServerSettings.ScriptsDisabled) if err != nil { @@ -1184,6 +1188,9 @@ func (svc *Service) SaveHostScriptResult(ctx context.Context, result *fleet.Host if err != nil { return ctxerr.Wrap(ctx, err, "save host script result") } + // >>> OPENFRAME(windows-lock): what a Windows lock or unlock did — openframe/docs/windows-lock.md + svc.openframeRecordWindowsLockResult(ctx, host, action, hsr) + // <<< OPENFRAME(windows-lock) // FIXME: datastore implementation of action seems rather brittle, can it be refactored? var fromSetupExperience bool diff --git a/server/service/scripts.go b/server/service/scripts.go index e0580692984..ac4b77754cf 100644 --- a/server/service/scripts.go +++ b/server/service/scripts.go @@ -1213,6 +1213,17 @@ func (svc *Service) BatchScriptExecute(ctx context.Context, scriptID uint, hostI func lockHostEndpoint(ctx context.Context, request interface{}, svc fleet.Service) (fleet.Errorer, error) { req := request.(*fleet.LockHostRequest) + // >>> OPENFRAME(windows-lock): Fleet Free locks a Windows host with BitLocker — openframe/docs/windows-lock.md + if fleet.OpenframeWindowsLockEnabled(ctx) { + locked, err := svc.OpenframeLockWindowsHost(ctx, req.HostID, req.OpenframeMessage) + if err != nil { + return fleet.LockHostResponse{Err: err}, nil + } + if locked { + return &fleet.LockHostResponse{DeviceStatus: fleet.DeviceStatusUnlocked, PendingAction: fleet.PendingActionLock}, nil + } + } + // <<< OPENFRAME(windows-lock) unlockPIN, err := svc.LockHost(ctx, req.HostID, req.ViewPin) if err != nil { return fleet.LockHostResponse{Err: err}, nil From 02cfa9acd38bfa23a569458e1106f6ef1d7ce4fd Mon Sep 17 00:00:00 2001 From: Andrii Koropets Date: Thu, 3 Dec 2026 20:44:57 +0200 Subject: [PATCH 2/3] fix(mdm): CU-17tkuw6a8c2 make the Windows lock safe against lost results, races and re-enrollment --- openframe/docs/README.md | 2 +- openframe/docs/windows-lock.md | 69 ++++--- .../datastore/mysql/openframe_windows_lock.go | 122 ++++++++++-- .../mysql/openframe_windows_lock_test.go | 90 +++++++-- server/fleet/api_scripts.go | 4 +- server/fleet/datastore.go | 11 +- server/fleet/openframe_windows_lock.go | 80 +++++++- server/mock/datastore_mock.go | 30 ++- server/service/openframe_windows_lock.go | 162 +++++++++++----- server/service/openframe_windows_lock_test.go | 182 +++++++++++++++--- 10 files changed, 612 insertions(+), 140 deletions(-) diff --git a/openframe/docs/README.md b/openframe/docs/README.md index 84b6f9b7fb0..c22af57bbe9 100644 --- a/openframe/docs/README.md +++ b/openframe/docs/README.md @@ -48,7 +48,7 @@ The agent has its own switch, `--openframe-mode` / `ORBIT_OPENFRAME_MODE`. | [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. | -| [windows-lock.md](windows-lock.md) | `POST /hosts/{id}/lock` locks Windows hosts on Fleet Free with BitLocker: forced recovery and a restart, with an optional message on the recovery screen; refused without a recovery key Fleet can decrypt and finds on the drive; the unlock script restores the TPM protector once the PC checks in after someone typed the key; only Fleet's own scripts in OpenFrame mode; `completed_lock` and `failed_lock` activities. | +| [windows-lock.md](windows-lock.md) | `POST /hosts/{id}/lock` locks Windows hosts on Fleet Free with BitLocker: forced recovery and a restart, with an optional message on the recovery screen; refused without a recovery key Fleet can decrypt and finds on the drive, and for a second concurrent lock; a startup task on the PC and the unlock script Fleet queues when the PC checks in restore the TPM protector; only Fleet's own scripts in OpenFrame mode; `completed_lock`, `failed_lock` and `failed_unlock` activities. | ## Agent-side (orbit / fleetd) diff --git a/openframe/docs/windows-lock.md b/openframe/docs/windows-lock.md index cb70ff8a0d4..ad671e74a3f 100644 --- a/openframe/docs/windows-lock.md +++ b/openframe/docs/windows-lock.md @@ -23,48 +23,65 @@ Refused: key is not used: it may be of another disk. Windows MDM doesn't have to be on for the host, but the tenant's WSTEP pair has to decrypt the key. -The lock is queued by upstream's `LockHostViaScript` as an internal script, so the host's status is upstream's: pending -lock until fleetd reports the result, locked once it reports exit code 0. `locked_host` is recorded with the request. +The lock is queued as an internal script with upstream's `lock_ref`, so the host's status is upstream's: pending lock +until fleetd reports the result, locked once it reports exit code 0. The host's lock, unlock and wipe references are +read before its status is checked, and the lock is queued only if they are still the same, in one transaction under +the host's row lock (`OpenframeLockWindowsHostViaScript`): of two concurrent locks one is queued, the other answers +422. `locked_host` is recorded with the request. ## The lock script -It runs on the PC as SYSTEM, in PowerShell, and on `%SystemDrive%`: +It runs on the PC as SYSTEM, in PowerShell, and on `%SystemDrive%`. Each request gets its own id. -1. checks that BitLocker protects the drive (exit 2); -2. checks that one of the drive's recovery passwords is the key Fleet holds: the script carries its SHA-256, never +1. exits 0 if this request's lock ran on the PC already (`BitLockerLastLockId` under `HKLM\SOFTWARE\OpenFrame`, kept + after the unlock). fleetd keeps no record of the scripts it ran: when the result of a lock is lost before the + restart, fleetd runs the script again once the PC is back, and it must not lock the PC a second time; +2. checks that BitLocker protects the drive (exit 2); +3. checks that one of the drive's recovery passwords is the key Fleet holds: the script carries its SHA-256, never the key (exit 3). A locked PC that Fleet's key doesn't open could not be started again; -3. refuses a drive with a TPM protector that has a PIN or a startup key, which the lock would delete and the unlock +4. refuses a drive with a TPM protector that has a PIN or a startup key, which the lock would delete and the unlock couldn't restore (exit 4); -4. records under `HKLM\SOFTWARE\OpenFrame\BitLockerLock` when it locked, whether the drive had a TPM protector, and - the recovery message policy it replaces; -5. sets the message, if any, as the recovery message policy (`HKLM\SOFTWARE\Policies\Microsoft\FVE`, +5. records under `HKLM\SOFTWARE\OpenFrame\BitLockerLock` whether the drive had a TPM protector and the recovery message + policy it replaces. A record left by a lock that didn't finish is kept, and its message is restored when the new + lock has none; +6. sets the message, if any, as the recovery message policy (`HKLM\SOFTWARE\Policies\Microsoft\FVE`, `RecoveryKeyMessageSource` = 2 and `RecoveryKeyMessage`). The message reaches the script in base64, so nothing in it runs; -6. runs `manage-bde -forcerecovery`, which also deletes the drive's TPM protectors (exit 5 if it fails, with the - message and the record undone); -7. restarts the PC in 30 seconds, closing open apps, and exits 0, so that fleetd reports the result before it. +7. registers the startup task `\OpenFrame\BitLocker unlock` (SYSTEM), which runs the unlock script below, carried in + the task as an encoded command and not as a file, and creates the volatile key + `HKLM\SOFTWARE\OpenFrame\BitLockerLockBoot`, which Windows drops at restart (exit 6 if either fails); +8. runs `manage-bde -forcerecovery`, which also deletes the drive's TPM protectors (exit 5 if it fails, with the + message, the record, the task and the volatile key undone). Its error output doesn't end the script; +9. records the request's id, restarts the PC in 30 seconds, closing open apps, and exits 0, so that fleetd reports + the result before it. A failed lock clears the pending lock and records `failed_lock` with the exit code; a lock that succeeded records `completed_lock` (`server/fleet/openframe_windows_lock.go`). ## Unlock -When a locked Windows host checks in (orbit config) at least 15 minutes after its lock succeeded, someone has typed -the recovery key. The fork then queues an internal unlock script with upstream's `unlock_ref` -(`OpenframeQueueWindowsUnlock`, `server/datastore/mysql/openframe_windows_lock.go`), unless an unlock is pending, a -wipe is, or an unlock was tried within the last 15 minutes. The host's row is locked while the script is queued, so -concurrent check-ins queue one. +The unlock script runs twice over: on the PC at the first start after the recovery key was typed, from the startup +task, so the TPM protector comes back even when fleetd doesn't or the host's lock was cleared in Fleet (an agent +re-enrollment clears it); and from Fleet, which confirms the unlock and marks the host unlocked. + +When a locked Windows host checks in (orbit config) at least 2 minutes after its lock succeeded, someone has typed the +recovery key. The fork then queues the internal unlock script with upstream's `unlock_ref` (`OpenframeQueueWindowsUnlock`, +`server/datastore/mysql/openframe_windows_lock.go`), unless an unlock or a wipe is pending. A failed attempt is tried +again 15 minutes later, then after twice as long each time, up to a day (`OpenframeWindowsUnlockDue`). The host's row +is locked while the script is queued, so concurrent check-ins queue one. The script: -1. exits 0 if no lock is recorded on the PC; -2. exits 10 if the PC hasn't restarted since the lock: the host stays locked and the unlock is tried again later; +1. exits 0 if no lock is recorded on the PC, e.g. as the startup task has unlocked it already, and removes the task; +2. exits 10 if the volatile key is there: the PC hasn't restarted since the lock, e.g. as someone cancelled the + restart with `shutdown /a`. The host stays locked, the drive goes to recovery at the next restart, and nothing is + recorded; 3. adds a TPM protector back if the drive had one, as `-forcerecovery` deleted it and Windows would otherwise ask for the key at every start (exit 11 if it can't); -4. restores the recovery message policy and removes the record. +4. restores the recovery message policy and removes the record, the volatile key and the startup task. -Exit code 0 makes the host unlocked, as upstream, and records `unlocked_host` with no user. A failed unlock records -nothing. +Exit code 0 makes the host unlocked, as upstream, and records `unlocked_host` with no user. Any other failure than +exit 10 records `failed_unlock` with the exit code. Wipe is refused while a host is locked, by upstream's checks. Fleet can't turn MDM off for a Windows host. @@ -84,9 +101,11 @@ recorded in that request's tenant. ## Not verified on a real PC yet -- that the recovery screen shows the message set by the policy; -- that fleetd always reports the lock's result within the 30 seconds before the restart. A result that is lost - leaves the host pending lock. +- that the recovery screen shows the message set by the policy, and how it shows characters outside ASCII; +- the startup task, the volatile key (`RegistryOptions.Volatile` needs .NET Framework 4.6 or later) and + `Add-BitLockerKeyProtector` at startup; +- a lock whose result is lost before the restart stays pending lock in Fleet until fleetd runs it again after the + unlock, which then reports it done. ## Tests diff --git a/server/datastore/mysql/openframe_windows_lock.go b/server/datastore/mysql/openframe_windows_lock.go index 9be348d8e4f..9841a78a13f 100644 --- a/server/datastore/mysql/openframe_windows_lock.go +++ b/server/datastore/mysql/openframe_windows_lock.go @@ -13,8 +13,12 @@ import ( "github.com/jmoiron/sqlx" ) -var errOpenframeOnlyInternalScripts = fleet.NewInvalidArgumentError("script", - "Fleet runs only its own scripts on hosts in OpenFrame mode.") +var ( + errOpenframeOnlyInternalScripts = fleet.NewInvalidArgumentError("script", + "Fleet runs only its own scripts on hosts in OpenFrame mode.") + errOpenframeLockRaced = fleet.NewInvalidArgumentError("host_id", + "The host's lock or wipe changed while it was being locked. Reload the host and try again.") +) func openframeWindowsLockEnabled(ctx context.Context) bool { return fleet.OpenframeWindowsLockEnabled(ctx) || openframeSharedMode(ctx) @@ -29,44 +33,124 @@ func openframeRefuseScript(ctx context.Context, isInternal bool) error { return ctxerr.Wrap(ctx, errOpenframeOnlyInternalScripts) } -// openframeWindowsUnlockDue selects the locked Windows host whose unlock may be queued now: its lock succeeded at least -// the delay ago, nothing else is pending for it, and no unlock was tried within the delay. -const openframeWindowsUnlockDue = `SELECT hma.lock_ref +const openframeHostMDMActionRefs = `SELECT lock_ref, unlock_ref, wipe_ref FROM host_mdm_actions WHERE host_id = ?` + +// OpenframeHostMDMActionRefs returns the host's lock, unlock and wipe references as stored, all nil without a row. +func (ds *Datastore) OpenframeHostMDMActionRefs(ctx context.Context, hostID uint) (fleet.OpenframeHostMDMActionRefs, error) { + return openframeReadHostMDMActionRefs(ctx, ds.writer(ctx), openframeHostMDMActionRefs, hostID) +} + +// openframeReadHostMDMActionRefs reads the references, all nil without a row: sqlx allocates the pointers before it +// finds there is none. +func openframeReadHostMDMActionRefs(ctx context.Context, q sqlx.QueryerContext, stmt string, hostID uint) (fleet.OpenframeHostMDMActionRefs, error) { + var refs fleet.OpenframeHostMDMActionRefs + switch err := sqlx.GetContext(ctx, q, &refs, stmt, hostID); { + case errors.Is(err, sql.ErrNoRows): + return fleet.OpenframeHostMDMActionRefs{}, nil + case err != nil: + return fleet.OpenframeHostMDMActionRefs{}, ctxerr.Wrap(ctx, err, "read the host's MDM action references") + } + return refs, nil +} + +// OpenframeLockWindowsHostViaScript queues the lock as LockHostViaScript does, in one transaction with a check that +// the host's references are the ones its lock status was read from: of two concurrent locks one is queued. +func (ds *Datastore) OpenframeLockWindowsHostViaScript(ctx context.Context, request *fleet.HostScriptRequestPayload, expected fleet.OpenframeHostMDMActionRefs) error { + return ds.withRetryTxx(ctx, func(tx sqlx.ExtContext) error { + current, err := openframeReadHostMDMActionRefs(ctx, tx, openframeHostMDMActionRefs+` FOR UPDATE`, request.HostID) + if err != nil { + return err + } + if !openframeSameRef(current.LockRef, expected.LockRef) || !openframeSameRef(current.UnlockRef, expected.UnlockRef) || + !openframeSameRef(current.WipeRef, expected.WipeRef) { + return ctxerr.Wrap(ctx, errOpenframeLockRaced) + } + + contents, err := insertScriptContents(ctx, tx, request.ScriptContents) + if err != nil { + return err + } + contentID, _ := contents.LastInsertId() + request.ScriptContentID = uint(contentID) //nolint:gosec // dismiss G115 + result, err := ds.newHostScriptExecutionRequest(ctx, tx, request, true) + if err != nil { + return ctxerr.Wrap(ctx, err, "queue the lock script") + } + _, err = tx.ExecContext(ctx, `INSERT INTO host_mdm_actions (host_id, lock_ref, fleet_platform) VALUES (?, ?, 'windows') + ON DUPLICATE KEY UPDATE lock_ref = VALUES(lock_ref)`, request.HostID, result.ExecutionID) + return ctxerr.Wrap(ctx, err, "record the lock script") + }) +} + +func openframeSameRef(a, b *string) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + return *a == *b +} + +// openframeWindowsUnlockStateQuery selects a locked Windows host whose unlock may be queued: its lock succeeded and no +// unlock or wipe is pending. It returns how long ago the lock succeeded, and how many unlocks were tried since and how +// long ago the last one was. +const openframeWindowsUnlockStateQuery = `SELECT hma.lock_ref, + TIMESTAMPDIFF(SECOND, lock_result.updated_at, CURRENT_TIMESTAMP) AS since_lock, + COUNT(attempt.id) AS attempts, + COALESCE(TIMESTAMPDIFF(SECOND, MAX(attempt.created_at), CURRENT_TIMESTAMP), 0) AS since_attempt FROM host_mdm_actions hma JOIN host_script_results lock_result ON lock_result.execution_id = hma.lock_ref AND lock_result.host_id = hma.host_id + LEFT JOIN script_contents sc ON sc.md5_checksum = UNHEX(?) + LEFT JOIN host_script_results attempt ON attempt.host_id = hma.host_id AND attempt.script_content_id = sc.id + AND attempt.id > lock_result.id WHERE hma.host_id = ? AND hma.fleet_platform = 'windows' AND hma.unlock_ref IS NULL AND hma.wipe_ref IS NULL - AND lock_result.exit_code = 0 AND lock_result.updated_at <= CURRENT_TIMESTAMP - INTERVAL ? SECOND - AND NOT EXISTS ( - SELECT 1 FROM host_script_results attempt - JOIN script_contents sc ON sc.id = attempt.script_content_id - WHERE attempt.host_id = hma.host_id AND sc.md5_checksum = UNHEX(?) - AND attempt.created_at > CURRENT_TIMESTAMP - INTERVAL ? SECOND)` + AND lock_result.exit_code = 0 + GROUP BY hma.lock_ref, lock_result.updated_at` + +type openframeWindowsUnlockState struct { + LockRef string `db:"lock_ref"` + SinceLock int64 `db:"since_lock"` + Attempts int `db:"attempts"` + SinceAttempt int64 `db:"since_attempt"` +} + +func (s openframeWindowsUnlockState) due() bool { + return fleet.OpenframeWindowsUnlockDue(time.Duration(s.SinceLock)*time.Second, s.Attempts, time.Duration(s.SinceAttempt)*time.Second) +} // OpenframeQueueWindowsUnlock queues the unlock script of a locked Windows host and reports whether it did. A host that // checks in while it is locked was unlocked with its recovery key; the script confirms the PC restarted after the lock // and restores what the lock removed. -func (ds *Datastore) OpenframeQueueWindowsUnlock(ctx context.Context, hostID uint, script string, delay time.Duration) (bool, error) { - seconds := int64(delay / time.Second) - checksum := md5ChecksumScriptContent(script) - args := []any{hostID, seconds, checksum, seconds} +func (ds *Datastore) OpenframeQueueWindowsUnlock(ctx context.Context, hostID uint, script string) (bool, error) { + args := []any{md5ChecksumScriptContent(script), hostID} - var lockRef string - switch err := sqlx.GetContext(ctx, ds.reader(ctx), &lockRef, openframeWindowsUnlockDue, args...); { + var state openframeWindowsUnlockState + switch err := sqlx.GetContext(ctx, ds.reader(ctx), &state, openframeWindowsUnlockStateQuery, args...); { case errors.Is(err, sql.ErrNoRows): return false, nil case err != nil: return false, ctxerr.Wrap(ctx, err, "check whether a locked Windows host is due its unlock") + case !state.due(): + return false, nil } var queued bool err := ds.withRetryTxx(ctx, func(tx sqlx.ExtContext) error { queued = false - if err := sqlx.GetContext(ctx, tx, &lockRef, openframeWindowsUnlockDue+` FOR UPDATE OF hma`, args...); err != nil { + var locked string + if err := sqlx.GetContext(ctx, tx, &locked, `SELECT host_id FROM host_mdm_actions WHERE host_id = ? FOR UPDATE`, hostID); err != nil { if errors.Is(err, sql.ErrNoRows) { return nil } return ctxerr.Wrap(ctx, err, "lock the host's MDM actions") } + if err := sqlx.GetContext(ctx, tx, &state, openframeWindowsUnlockStateQuery, args...); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil + } + return ctxerr.Wrap(ctx, err, "check the locked Windows host again") + } + if !state.due() { + return nil + } contents, err := insertScriptContents(ctx, tx, script) if err != nil { return err @@ -81,7 +165,7 @@ func (ds *Datastore) OpenframeQueueWindowsUnlock(ctx context.Context, hostID uin return ctxerr.Wrap(ctx, err, "queue the unlock script") } if _, err := tx.ExecContext(ctx, `UPDATE host_mdm_actions SET unlock_ref = ? WHERE host_id = ? AND lock_ref = ?`, - result.ExecutionID, hostID, lockRef); err != nil { + result.ExecutionID, hostID, state.LockRef); err != nil { return ctxerr.Wrap(ctx, err, "record the unlock script") } queued = true diff --git a/server/datastore/mysql/openframe_windows_lock_test.go b/server/datastore/mysql/openframe_windows_lock_test.go index 921c5a21e57..9ad9b17e0f0 100644 --- a/server/datastore/mysql/openframe_windows_lock_test.go +++ b/server/datastore/mysql/openframe_windows_lock_test.go @@ -3,6 +3,7 @@ package mysql import ( "context" + "errors" "testing" "time" @@ -17,7 +18,9 @@ func openframeLockCtx(ctx context.Context, teamID uint) context.Context { } func (f *openframeWindowsMDMFixture) lock(t *testing.T, ctx context.Context, h *fleet.Host, exitCode int) string { - require.NoError(t, f.ds.LockHostViaScript(ctx, &fleet.HostScriptRequestPayload{HostID: h.ID, ScriptContents: "Write-Output 'lock " + h.UUID + "'"}, "windows")) + refs, err := f.ds.OpenframeHostMDMActionRefs(ctx, h.ID) + require.NoError(t, err) + require.NoError(t, f.ds.OpenframeLockWindowsHostViaScript(ctx, &fleet.HostScriptRequestPayload{HostID: h.ID, ScriptContents: "Write-Output 'lock " + h.UUID + "'"}, refs)) status, err := f.ds.GetHostLockWipeStatus(ctx, h) require.NoError(t, err) require.True(t, status.IsPendingLock()) @@ -42,7 +45,7 @@ func (f *openframeWindowsMDMFixture) lockStatus(t *testing.T, ctx context.Contex } func (f *openframeWindowsMDMFixture) queueUnlock(t *testing.T, ctx context.Context, h *fleet.Host) bool { - queued, err := f.ds.OpenframeQueueWindowsUnlock(ctx, h.ID, openframeTestUnlockScript, fleet.OpenframeWindowsUnlockDelay) + queued, err := f.ds.OpenframeQueueWindowsUnlock(ctx, h.ID, openframeTestUnlockScript) require.NoError(t, err) return queued } @@ -76,9 +79,9 @@ func TestOpenframeWindowsUnlockQueued(t *testing.T) { f.lock(t, ctxA, a, 0) f.lock(t, ctxB, b, 0) require.True(t, f.lockStatus(t, ctxA, a).IsLocked()) - require.False(t, f.queueUnlock(t, ctxA, a), "not before the delay: the PC is about to restart") + require.False(t, f.queueUnlock(t, ctxA, a), "not before the first delay: the PC is about to restart") - f.age(t, a, fleet.OpenframeWindowsUnlockDelay+time.Minute) + f.age(t, a, fleet.OpenframeWindowsUnlockFirstDelay+time.Minute) require.True(t, f.queueUnlock(t, ctxA, a)) status := f.lockStatus(t, ctxA, a) require.True(t, status.IsLocked()) @@ -86,14 +89,21 @@ func TestOpenframeWindowsUnlockQueued(t *testing.T) { require.False(t, f.queueUnlock(t, ctxA, a), "one unlock at a time") require.Nil(t, f.lockStatus(t, ctxB, b).UnlockScript, "the other tenant's locked host is untouched") - f.result(t, ctxA, a, status.UnlockScript.ExecutionID, 10) + f.result(t, ctxA, a, status.UnlockScript.ExecutionID, fleet.OpenframeWindowsUnlockNotRestarted) status = f.lockStatus(t, ctxA, a) require.True(t, status.IsLocked(), "a PC that hasn't restarted stays locked") require.False(t, status.IsPendingUnlock()) - require.False(t, f.queueUnlock(t, ctxA, a), "not again within the delay of the last attempt") + require.False(t, f.queueUnlock(t, ctxA, a), "not again within the retry delay") - f.age(t, a, fleet.OpenframeWindowsUnlockDelay+time.Minute) + f.age(t, a, fleet.OpenframeWindowsUnlockRetryDelay) + require.True(t, f.queueUnlock(t, ctxA, a), "the first retry after the retry delay") + status = f.lockStatus(t, ctxA, a) + f.result(t, ctxA, a, status.UnlockScript.ExecutionID, 11) + f.age(t, a, fleet.OpenframeWindowsUnlockRetryDelay) + require.False(t, f.queueUnlock(t, ctxA, a), "the second retry waits twice as long") + f.age(t, a, fleet.OpenframeWindowsUnlockRetryDelay) require.True(t, f.queueUnlock(t, ctxA, a)) + status = f.lockStatus(t, ctxA, a) f.result(t, ctxA, a, status.UnlockScript.ExecutionID, 0) status = f.lockStatus(t, ctxA, a) @@ -101,28 +111,84 @@ func TestOpenframeWindowsUnlockQueued(t *testing.T) { require.Equal(t, fleet.PendingActionNone, status.PendingAction()) require.False(t, f.queueUnlock(t, ctxA, a), "an unlocked host has nothing to unlock") + f.lock(t, ctxA, a, 0) + f.age(t, a, fleet.OpenframeWindowsUnlockFirstDelay+time.Minute) + require.True(t, f.queueUnlock(t, ctxA, a), "the attempts of an earlier lock don't count for the next one") + require.True(t, f.lockStatus(t, ctxB, b).IsLocked()) require.Equal(t, 1, f.count(t, `SELECT COUNT(*) FROM host_script_results WHERE host_id = ?`, b.ID), "only the lock ran on the other tenant's host") } +func TestOpenframeWindowsLockRaced(t *testing.T) { + f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) + a := f.host(t, "lock-race-a", "uuid-lock-race-a", f.teamA.ID) + b := f.host(t, "lock-race-b", "uuid-lock-race-b", f.teamB.ID) + ctxA := openframeLockCtx(t.Context(), f.teamA.ID) + request := func(h *fleet.Host) *fleet.HostScriptRequestPayload { + return &fleet.HostScriptRequestPayload{HostID: h.ID, ScriptContents: "Write-Output 'lock race'"} + } + + read, err := f.ds.OpenframeHostMDMActionRefs(ctxA, a.ID) + require.NoError(t, err) + require.Equal(t, fleet.OpenframeHostMDMActionRefs{}, read, "no row reads as no references") + require.NoError(t, f.ds.OpenframeLockWindowsHostViaScript(ctxA, request(a), read)) + err = f.ds.OpenframeLockWindowsHostViaScript(ctxA, request(a), read) + require.ErrorIs(t, err, errOpenframeLockRaced, "a second lock read before the first was queued is refused") + require.Equal(t, 1, f.count(t, `SELECT COUNT(*) FROM upcoming_activities WHERE host_id = ?`, a.ID)) + + status := f.lockStatus(t, ctxA, a) + f.result(t, ctxA, a, status.LockScript.ExecutionID, 3) + read, err = f.ds.OpenframeHostMDMActionRefs(ctxA, a.ID) + require.NoError(t, err) + require.Equal(t, fleet.OpenframeHostMDMActionRefs{}, read, "a failed lock clears its reference") + require.NoError(t, f.ds.OpenframeLockWindowsHostViaScript(ctxA, request(a), read), "the host can be locked again") + + f.exec(t, `INSERT INTO host_mdm_actions (host_id, wipe_ref, fleet_platform) VALUES (?, 'a-wipe', 'windows')`, b.ID) + err = f.ds.OpenframeLockWindowsHostViaScript(ctxA, request(b), fleet.OpenframeHostMDMActionRefs{}) + require.ErrorIs(t, err, errOpenframeLockRaced, "a wipe queued since the read refuses the lock") + require.Zero(t, f.count(t, `SELECT COUNT(*) FROM upcoming_activities WHERE host_id = ?`, b.ID)) + + errs := make(chan error, 2) + c := f.host(t, "lock-race-c", "uuid-lock-race-c", f.teamA.ID) + for range 2 { + go func() { + errs <- f.ds.OpenframeLockWindowsHostViaScript(ctxA, request(c), fleet.OpenframeHostMDMActionRefs{}) + }() + } + var queued, refused int + for range 2 { + switch err := <-errs; { + case err == nil: + queued++ + case errors.Is(err, errOpenframeLockRaced): + refused++ + default: + require.NoError(t, err) + } + } + require.Equal(t, 1, queued, "of two concurrent locks one is queued") + require.Equal(t, 1, refused) + require.Equal(t, 1, f.count(t, `SELECT COUNT(*) FROM upcoming_activities WHERE host_id = ?`, c.ID)) +} + func TestOpenframeWindowsUnlockNotQueued(t *testing.T) { f := newOpenframeWindowsMDMFixture(t, CreateMySQLDS(t)) ctx := openframeLockCtx(t.Context(), f.teamA.ID) failed := f.host(t, "lock-failed", "uuid-lock-failed", f.teamA.ID) f.lock(t, ctx, failed, 3) - f.age(t, failed, 2*fleet.OpenframeWindowsUnlockDelay) + f.age(t, failed, time.Hour) require.False(t, f.lockStatus(t, ctx, failed).IsLocked()) require.False(t, f.queueUnlock(t, ctx, failed), "a lock that failed left the host unlocked") pending := f.host(t, "lock-pending", "uuid-lock-pending", f.teamA.ID) - require.NoError(t, f.ds.LockHostViaScript(ctx, &fleet.HostScriptRequestPayload{HostID: pending.ID, ScriptContents: "Write-Output 'lock pending'"}, "windows")) - f.age(t, pending, 2*fleet.OpenframeWindowsUnlockDelay) + require.NoError(t, f.ds.OpenframeLockWindowsHostViaScript(ctx, &fleet.HostScriptRequestPayload{HostID: pending.ID, ScriptContents: "Write-Output 'lock pending'"}, fleet.OpenframeHostMDMActionRefs{})) + f.age(t, pending, time.Hour) require.False(t, f.queueUnlock(t, ctx, pending), "a lock without a result is pending") wiping := f.host(t, "lock-wiping", "uuid-lock-wiping", f.teamA.ID) f.lock(t, ctx, wiping, 0) - f.age(t, wiping, 2*fleet.OpenframeWindowsUnlockDelay) + f.age(t, wiping, time.Hour) f.exec(t, `UPDATE host_mdm_actions SET wipe_ref = 'a-wipe' WHERE host_id = ?`, wiping.ID) require.False(t, f.queueUnlock(t, ctx, wiping), "a host being wiped is not unlocked") @@ -130,7 +196,7 @@ func TestOpenframeWindowsUnlockNotQueued(t *testing.T) { require.NoError(t, f.ds.LockHostViaScript(ctx, &fleet.HostScriptRequestPayload{HostID: linux.ID, ScriptContents: "echo lock"}, "linux")) status := f.lockStatus(t, ctx, linux) f.result(t, ctx, linux, status.LockScript.ExecutionID, 0) - f.age(t, linux, 2*fleet.OpenframeWindowsUnlockDelay) + f.age(t, linux, time.Hour) require.False(t, f.queueUnlock(t, ctx, linux), "only a Windows lock is unlocked with its recovery key") require.Zero(t, f.count(t, `SELECT COUNT(*) FROM host_mdm_actions WHERE unlock_ref IS NOT NULL`)) diff --git a/server/fleet/api_scripts.go b/server/fleet/api_scripts.go index 1a737038647..001225ab8e0 100644 --- a/server/fleet/api_scripts.go +++ b/server/fleet/api_scripts.go @@ -380,8 +380,8 @@ func (r BatchScriptRunResponse) Error() error { return r.Err } type LockHostRequest struct { HostID uint `url:"id"` ViewPin bool `query:"view_pin,optional"` - // >>> OPENFRAME(windows-lock): the message a Windows lock shows on the BitLocker recovery screen — openframe/docs/windows-lock.md - OpenframeMessage string `json:"message"` + // >>> OPENFRAME(windows-lock): the message a Windows lock shows on the BitLocker recovery screen, read by DecodeBody, as the body is optional — openframe/docs/windows-lock.md + OpenframeMessage string // <<< OPENFRAME(windows-lock) } diff --git a/server/fleet/datastore.go b/server/fleet/datastore.go index 81a08f73d32..23688054a30 100644 --- a/server/fleet/datastore.go +++ b/server/fleet/datastore.go @@ -1262,9 +1262,14 @@ type Datastore interface { // <<< OPENFRAME(windows-disk-encryption) // >>> OPENFRAME(windows-lock): BitLocker hard lock of Windows hosts — openframe/docs/windows-lock.md - // OpenframeQueueWindowsUnlock queues the unlock script of a locked Windows host whose lock succeeded at least the - // delay ago, unless an unlock is pending or was tried within the delay, and reports whether it did. - OpenframeQueueWindowsUnlock(ctx context.Context, hostID uint, script string, delay time.Duration) (bool, error) + // OpenframeQueueWindowsUnlock queues the unlock script of a locked Windows host when OpenframeWindowsUnlockDue says + // it is due, unless an unlock or a wipe is pending, and reports whether it did. + OpenframeQueueWindowsUnlock(ctx context.Context, hostID uint, script string) (bool, error) + // OpenframeHostMDMActionRefs returns the host's lock, unlock and wipe references as stored, read on the primary. + OpenframeHostMDMActionRefs(ctx context.Context, hostID uint) (OpenframeHostMDMActionRefs, error) + // OpenframeLockWindowsHostViaScript queues the lock script of a Windows host as LockHostViaScript does, if the host's + // references are still the expected ones, and refuses it otherwise. + OpenframeLockWindowsHostViaScript(ctx context.Context, request *HostScriptRequestPayload, expected OpenframeHostMDMActionRefs) error // <<< OPENFRAME(windows-lock) // >>> OPENFRAME(enroll-machine-identity) diff --git a/server/fleet/openframe_windows_lock.go b/server/fleet/openframe_windows_lock.go index d85a1b6044a..0dd7e15ae13 100644 --- a/server/fleet/openframe_windows_lock.go +++ b/server/fleet/openframe_windows_lock.go @@ -4,15 +4,45 @@ package fleet import ( "context" + "crypto/x509" + "encoding/json" + "errors" + "io" + "net/url" "time" ) // OpenframeWindowsLockMessageMaxLength is the longest message, in characters, a lock may show on the recovery screen. const OpenframeWindowsLockMessageMaxLength = 240 -// OpenframeWindowsUnlockDelay is how long after a lock succeeded, and after an unlock attempt, the host must check in -// before the unlock script is queued: the PC restarts to the recovery screen shortly after it reports the lock. -const OpenframeWindowsUnlockDelay = 15 * time.Minute +// The unlock script of a locked Windows host is queued when the host checks in at least OpenframeWindowsUnlockFirstDelay +// after its lock succeeded: the PC restarts to the recovery screen 30 seconds after it reports the lock. A failed +// attempt is tried again after OpenframeWindowsUnlockRetryDelay, doubled after each further one up to +// OpenframeWindowsUnlockMaxRetryDelay. +const ( + OpenframeWindowsUnlockFirstDelay = 2 * time.Minute + OpenframeWindowsUnlockRetryDelay = 15 * time.Minute + OpenframeWindowsUnlockMaxRetryDelay = 24 * time.Hour +) + +// OpenframeWindowsUnlockDue reports whether the unlock of a locked host may be queued now, given how long ago its lock +// succeeded, how many unlocks were tried since, and how long ago the last one was. +func OpenframeWindowsUnlockDue(sinceLock time.Duration, attempts int, sinceLastAttempt time.Duration) bool { + if sinceLock < OpenframeWindowsUnlockFirstDelay { + return false + } + if attempts == 0 { + return true + } + delay := OpenframeWindowsUnlockRetryDelay + for i := 1; i < attempts && delay < OpenframeWindowsUnlockMaxRetryDelay; i++ { + delay *= 2 + } + return sinceLastAttempt >= min(delay, OpenframeWindowsUnlockMaxRetryDelay) +} + +// OpenframeWindowsUnlockNotRestarted is the exit code of an unlock script on a PC that hasn't restarted since the lock. +const OpenframeWindowsUnlockNotRestarted = 10 // OpenframeWindowsLockEnabled reports whether Fleet Free locks Windows hosts with BitLocker and runs only its own // scripts on hosts. Shared mode counts as OpenFrame mode: the two are separate settings. @@ -20,6 +50,31 @@ func OpenframeWindowsLockEnabled(ctx context.Context) bool { return IsOpenframeModeContext(ctx) || IsOpenframeSharedMode() } +// DecodeBody reads the optional message of a lock. The body is optional: upstream's callers send none. +func (req *LockHostRequest) DecodeBody(_ context.Context, r io.Reader, _ url.Values, _ []*x509.Certificate) error { + if r == nil { + return nil + } + var body struct { + Message string `json:"message"` + } + if err := json.NewDecoder(io.LimitReader(r, 16*1024)).Decode(&body); err != nil { + if errors.Is(err, io.EOF) { + return nil + } + return &BadRequestError{Message: "failed to unmarshal request body", InternalErr: err} + } + req.OpenframeMessage = body.Message + return nil +} + +// OpenframeHostMDMActionRefs are the lock, unlock and wipe references of a host as stored, nil when unset. +type OpenframeHostMDMActionRefs struct { + LockRef *string `db:"lock_ref"` + UnlockRef *string `db:"unlock_ref"` + WipeRef *string `db:"wipe_ref"` +} + type ActivityTypeOpenframeLockCompletedHost struct { HostID uint `json:"host_id"` HostDisplayName string `json:"host_display_name"` @@ -57,4 +112,23 @@ func (a ActivityTypeOpenframeLockFailedHost) WasFromAutomation() bool { return true } +type ActivityTypeOpenframeUnlockFailedHost struct { + HostID uint `json:"host_id"` + HostDisplayName string `json:"host_display_name"` + HostPlatform string `json:"host_platform"` + ExitCode int `json:"exit_code"` +} + +func (a ActivityTypeOpenframeUnlockFailedHost) ActivityName() string { + return "failed_unlock" +} + +func (a ActivityTypeOpenframeUnlockFailedHost) HostIDs() []uint { + return []uint{a.HostID} +} + +func (a ActivityTypeOpenframeUnlockFailedHost) WasFromAutomation() bool { + return true +} + // <<< OPENFRAME(windows-lock) diff --git a/server/mock/datastore_mock.go b/server/mock/datastore_mock.go index 3f10afdb2c4..9fcf5a31568 100644 --- a/server/mock/datastore_mock.go +++ b/server/mock/datastore_mock.go @@ -874,7 +874,11 @@ type OpenframeHostDiskEncryptionFunc func(ctx context.Context, host *fleet.Host) type OpenframeRecordDiskEncryptionResultFunc func(ctx context.Context, host *fleet.Host, clientError string, keyStored bool) error -type OpenframeQueueWindowsUnlockFunc func(ctx context.Context, hostID uint, script string, delay time.Duration) (bool, error) +type OpenframeQueueWindowsUnlockFunc func(ctx context.Context, hostID uint, script string) (bool, error) + +type OpenframeHostMDMActionRefsFunc func(ctx context.Context, hostID uint) (fleet.OpenframeHostMDMActionRefs, error) + +type OpenframeLockWindowsHostViaScriptFunc func(ctx context.Context, request *fleet.HostScriptRequestPayload, expected fleet.OpenframeHostMDMActionRefs) error type OpenframeRefuseSharedHardwareUUIDFunc func(ctx context.Context, hostID uint, hardwareUUID string) error @@ -3437,6 +3441,12 @@ type DataStore struct { OpenframeQueueWindowsUnlockFunc OpenframeQueueWindowsUnlockFunc OpenframeQueueWindowsUnlockFuncInvoked bool + OpenframeHostMDMActionRefsFunc OpenframeHostMDMActionRefsFunc + OpenframeHostMDMActionRefsFuncInvoked bool + + OpenframeLockWindowsHostViaScriptFunc OpenframeLockWindowsHostViaScriptFunc + OpenframeLockWindowsHostViaScriptFuncInvoked bool + OpenframeRefuseSharedHardwareUUIDFunc OpenframeRefuseSharedHardwareUUIDFunc OpenframeRefuseSharedHardwareUUIDFuncInvoked bool @@ -8338,11 +8348,25 @@ func (s *DataStore) OpenframeRecordDiskEncryptionResult(ctx context.Context, hos return s.OpenframeRecordDiskEncryptionResultFunc(ctx, host, clientError, keyStored) } -func (s *DataStore) OpenframeQueueWindowsUnlock(ctx context.Context, hostID uint, script string, delay time.Duration) (bool, error) { +func (s *DataStore) OpenframeQueueWindowsUnlock(ctx context.Context, hostID uint, script string) (bool, error) { s.mu.Lock() s.OpenframeQueueWindowsUnlockFuncInvoked = true s.mu.Unlock() - return s.OpenframeQueueWindowsUnlockFunc(ctx, hostID, script, delay) + return s.OpenframeQueueWindowsUnlockFunc(ctx, hostID, script) +} + +func (s *DataStore) OpenframeHostMDMActionRefs(ctx context.Context, hostID uint) (fleet.OpenframeHostMDMActionRefs, error) { + s.mu.Lock() + s.OpenframeHostMDMActionRefsFuncInvoked = true + s.mu.Unlock() + return s.OpenframeHostMDMActionRefsFunc(ctx, hostID) +} + +func (s *DataStore) OpenframeLockWindowsHostViaScript(ctx context.Context, request *fleet.HostScriptRequestPayload, expected fleet.OpenframeHostMDMActionRefs) error { + s.mu.Lock() + s.OpenframeLockWindowsHostViaScriptFuncInvoked = true + s.mu.Unlock() + return s.OpenframeLockWindowsHostViaScriptFunc(ctx, request, expected) } func (s *DataStore) OpenframeRefuseSharedHardwareUUID(ctx context.Context, hostID uint, hardwareUUID string) error { diff --git a/server/service/openframe_windows_lock.go b/server/service/openframe_windows_lock.go index 076db1adb04..e41e4c4d4ab 100644 --- a/server/service/openframe_windows_lock.go +++ b/server/service/openframe_windows_lock.go @@ -6,17 +6,21 @@ import ( "context" "crypto/sha256" "encoding/base64" + "encoding/binary" "encoding/hex" "net/http" "strconv" "strings" "unicode" + "unicode/utf16" "unicode/utf8" "github.com/fleetdm/fleet/v4/server/authz" + "github.com/fleetdm/fleet/v4/server/contexts/ctxdb" "github.com/fleetdm/fleet/v4/server/contexts/ctxerr" "github.com/fleetdm/fleet/v4/server/fleet" "github.com/fleetdm/fleet/v4/server/mdm" + "github.com/google/uuid" ) var ( @@ -50,7 +54,12 @@ func (svc *Service) OpenframeLockWindowsHost(ctx context.Context, hostID uint, m return false, ctxerr.Wrap(ctx, errOpenframeLockNoScripts) } - lockWipe, err := svc.ds.GetHostLockWipeStatus(ctx, host) + refs, err := svc.ds.OpenframeHostMDMActionRefs(ctx, host.ID) + if err != nil { + return false, ctxerr.Wrap(ctx, err, "get host lock/wipe references") + } + // read on the primary, as the references are: a lagging replica would check an older state than they were read in + lockWipe, err := svc.ds.GetHostLockWipeStatus(ctxdb.RequirePrimary(ctx, true), host) if err != nil { return false, ctxerr.Wrap(ctx, err, "get host lock/wipe status") } @@ -74,13 +83,13 @@ func (svc *Service) OpenframeLockWindowsHost(ctx context.Context, hostID uint, m request := &fleet.HostScriptRequestPayload{ HostID: host.ID, - ScriptContents: openframeWindowsLockScript(keyHash, message), + ScriptContents: openframeWindowsLockScript(uuid.NewString(), keyHash, message), } user := authz.UserFromContext(ctx) if user != nil { request.UserID = &user.ID } - if err := svc.ds.LockHostViaScript(ctx, request, host.FleetPlatform()); err != nil { + if err := svc.ds.OpenframeLockWindowsHostViaScript(ctx, request, refs); err != nil { return false, ctxerr.Wrap(ctx, err, "lock windows host") } @@ -136,14 +145,14 @@ func (svc *Service) openframeQueueWindowsUnlock(ctx context.Context, host *fleet if !fleet.OpenframeWindowsLockEnabled(ctx) || host.FleetPlatform() != "windows" { return } - if _, err := svc.ds.OpenframeQueueWindowsUnlock(ctx, host.ID, openframeWindowsUnlockScript, fleet.OpenframeWindowsUnlockDelay); err != nil { + if _, err := svc.ds.OpenframeQueueWindowsUnlock(ctx, host.ID, openframeWindowsUnlockScript); err != nil { svc.logger.ErrorContext(ctx, "failed to queue the unlock script of a locked Windows host", "host_id", host.ID, "err", err) ctxerr.Handle(ctx, err) } } // openframeRecordWindowsLockResult records, in OpenFrame mode, what the lock or unlock script of a Windows host did. An -// unlock that failed records nothing: it is tried again. +// unlock on a PC that hasn't restarted yet records nothing; any unlock that failed is tried again later. func (svc *Service) openframeRecordWindowsLockResult(ctx context.Context, host *fleet.Host, action string, result *fleet.HostScriptResult) { if !fleet.OpenframeWindowsLockEnabled(ctx) || host.FleetPlatform() != "windows" || result == nil || result.Canceled || result.ExitCode == nil { return @@ -159,6 +168,10 @@ func (svc *Service) openframeRecordWindowsLockResult(ctx context.Context, host * } case action == "unlock_ref" && succeeded: activity = fleet.ActivityTypeUnlockedHost{HostID: host.ID, HostDisplayName: host.DisplayName(), HostPlatform: host.Platform} + case action == "unlock_ref" && *result.ExitCode != fleet.OpenframeWindowsUnlockNotRestarted: + activity = fleet.ActivityTypeOpenframeUnlockFailedHost{ + HostID: host.ID, HostDisplayName: host.DisplayName(), HostPlatform: host.Platform, ExitCode: int(*result.ExitCode), + } default: return } @@ -168,9 +181,17 @@ func (svc *Service) openframeRecordWindowsLockResult(ctx context.Context, host * } } -const openframeWindowsLockState = `$drive = $env:SystemDrive +// openframeWindowsLockCommon is what the lock and unlock scripts share. The lock is recorded under stateKey; the +// volatile bootKey, which Windows drops at restart, says the PC hasn't restarted since; a startup task runs the unlock +// script on the PC itself, so the TPM protector comes back even when fleetd doesn't; BitLockerLastLockId under +// rootKey keeps the last lock that ran, so a lock fleetd runs again after its result was lost does nothing. +const openframeWindowsLockCommon = `$drive = $env:SystemDrive +$rootKey = 'HKLM:\SOFTWARE\OpenFrame' $stateKey = 'HKLM:\SOFTWARE\OpenFrame\BitLockerLock' +$bootKeyPath = 'SOFTWARE\OpenFrame\BitLockerLockBoot' $policyKey = 'HKLM:\SOFTWARE\Policies\Microsoft\FVE' +$taskPath = '\OpenFrame\' +$taskName = 'BitLocker unlock' function Restore-RecoveryMessage($state) { if ($state.MessageSet -ne 1) { return } @@ -185,12 +206,58 @@ function Restore-RecoveryMessage($state) { } } } + +function Remove-LockState { + Remove-Item -Path $stateKey -Recurse -Force -ErrorAction SilentlyContinue + Remove-Item -Path "HKLM:\$bootKeyPath" -Recurse -Force -ErrorAction SilentlyContinue + Unregister-ScheduledTask -TaskPath $taskPath -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue +} +` + +const openframeWindowsUnlockScript = `$ErrorActionPreference = 'Stop' +` + openframeWindowsLockCommon + ` +$state = Get-ItemProperty -Path $stateKey -ErrorAction SilentlyContinue +if ($null -eq $state) { + Unregister-ScheduledTask -TaskPath $taskPath -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue + Write-Output "No lock is recorded on this PC." + exit 0 +} + +if (Test-Path "HKLM:\$bootKeyPath") { + Write-Output "The PC hasn't restarted since it was locked." + exit 10 +} + +if ($state.HadTpm -eq 1) { + $volume = Get-BitLockerVolume -MountPoint $drive + if (-not ($volume.KeyProtector | Where-Object { "$($_.KeyProtectorType)" -eq 'Tpm' })) { + try { + Add-BitLockerKeyProtector -MountPoint $drive -TpmProtector | Out-Null + } catch { + Write-Output "The PC was unlocked, but its TPM protector couldn't be added back: $_" + exit 11 + } + } +} + +Restore-RecoveryMessage $state +Remove-LockState +Write-Output "Unlocked: the PC started with its recovery key." +exit 0 ` const openframeWindowsLockScriptTemplate = `$ErrorActionPreference = 'Stop' +$lockId = '{{LOCK_ID}}' $keyHash = '{{KEY_HASH}}' $message = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('{{MESSAGE}}')) -` + openframeWindowsLockState + ` +$unlockCommand = '{{UNLOCK_COMMAND}}' +` + openframeWindowsLockCommon + ` +$root = Get-ItemProperty -Path $rootKey -ErrorAction SilentlyContinue +if ($null -ne $root -and $root.BitLockerLastLockId -eq $lockId) { + Write-Output "This lock already ran on this PC." + exit 0 +} + try { $volume = Get-BitLockerVolume -MountPoint $drive } catch { @@ -231,10 +298,15 @@ if ($null -eq $state) { } } Set-ItemProperty -Path $stateKey -Name HadTpm -Value ([int]($tpm.Count -gt 0)) -Type DWord -} elseif ($tpm.Count -gt 0) { - Set-ItemProperty -Path $stateKey -Name HadTpm -Value 1 -Type DWord +} else { + if ($tpm.Count -gt 0) { + Set-ItemProperty -Path $stateKey -Name HadTpm -Value 1 -Type DWord + } + if ($message -eq '' -and $state.MessageSet -eq 1) { + Restore-RecoveryMessage $state + Set-ItemProperty -Path $stateKey -Name MessageSet -Value 0 -Type DWord + } } -Set-ItemProperty -Path $stateKey -Name LockedAt -Value ([DateTime]::UtcNow.Ticks) -Type QWord if ($message -ne '') { if (-not (Test-Path $policyKey)) { New-Item -Path $policyKey | Out-Null } @@ -243,56 +315,54 @@ if ($message -ne '') { Set-ItemProperty -Path $stateKey -Name MessageSet -Value 1 -Type DWord } +try { + $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $unlockCommand" + $trigger = New-ScheduledTaskTrigger -AtStartup + $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest + Register-ScheduledTask -TaskPath $taskPath -TaskName $taskName -Action $action -Trigger $trigger -Principal $principal -Force | Out-Null + [Microsoft.Win32.Registry]::LocalMachine.CreateSubKey($bootKeyPath, $true, [Microsoft.Win32.RegistryOptions]::Volatile).Close() +} catch { + Write-Output "The lock couldn't be prepared: $_" + Restore-RecoveryMessage (Get-ItemProperty -Path $stateKey) + Remove-LockState + exit 6 +} + +$ErrorActionPreference = 'Continue' $output = & manage-bde.exe -forcerecovery $drive 2>&1 -if ($LASTEXITCODE -ne 0) { - Write-Output "manage-bde -forcerecovery failed with exit code ${LASTEXITCODE}: $output" +$exitCode = $LASTEXITCODE +$ErrorActionPreference = 'Stop' +if ($exitCode -ne 0) { + Write-Output "manage-bde -forcerecovery failed with exit code ${exitCode}: $output" Restore-RecoveryMessage (Get-ItemProperty -Path $stateKey) - Remove-Item -Path $stateKey -Recurse -Force + Remove-LockState exit 5 } +Set-ItemProperty -Path $rootKey -Name BitLockerLastLockId -Value $lockId & shutdown.exe /r /f /t 30 /d p:4:1 /c 'This PC is locked. It starts again with its BitLocker recovery key.' Write-Output "Locked $drive; the PC restarts to the BitLocker recovery screen in 30 seconds." exit 0 ` -const openframeWindowsUnlockScript = `$ErrorActionPreference = 'Stop' -` + openframeWindowsLockState + ` -$state = Get-ItemProperty -Path $stateKey -ErrorAction SilentlyContinue -if ($null -eq $state) { - Write-Output "No lock is recorded on this PC." - exit 0 -} - -$bootedAt = (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().Ticks -if ($bootedAt -le [long]$state.LockedAt) { - Write-Output "The PC hasn't restarted since it was locked." - exit 10 -} - -if ($state.HadTpm -eq 1) { - $volume = Get-BitLockerVolume -MountPoint $drive - if (-not ($volume.KeyProtector | Where-Object { "$($_.KeyProtectorType)" -eq 'Tpm' })) { - try { - Add-BitLockerKeyProtector -MountPoint $drive -TpmProtector | Out-Null - } catch { - Write-Output "The PC was unlocked, but its TPM protector couldn't be added back: $_" - exit 11 - } - } -} - -Restore-RecoveryMessage $state -Remove-Item -Path $stateKey -Recurse -Force -Write-Output "Unlocked: the PC started with its recovery key." -exit 0 -` - -func openframeWindowsLockScript(keyHash, message string) string { +// openframeWindowsLockScript returns the lock script of one request: lockID tells a repeated run of it apart. +func openframeWindowsLockScript(lockID, keyHash, message string) string { return strings.NewReplacer( + "{{LOCK_ID}}", lockID, "{{KEY_HASH}}", keyHash, "{{MESSAGE}}", base64.StdEncoding.EncodeToString([]byte(message)), + "{{UNLOCK_COMMAND}}", openframePowerShellEncodedCommand(openframeWindowsUnlockScript), ).Replace(openframeWindowsLockScriptTemplate) } +// openframePowerShellEncodedCommand encodes a script for powershell.exe -EncodedCommand: base64 of its UTF-16LE text. +func openframePowerShellEncodedCommand(script string) string { + units := utf16.Encode([]rune(script)) + b := make([]byte, 0, len(units)*2) + for _, u := range units { + b = binary.LittleEndian.AppendUint16(b, u) + } + return base64.StdEncoding.EncodeToString(b) +} + // <<< OPENFRAME(windows-lock) diff --git a/server/service/openframe_windows_lock_test.go b/server/service/openframe_windows_lock_test.go index c7b1a4d1108..24339e1faff 100644 --- a/server/service/openframe_windows_lock_test.go +++ b/server/service/openframe_windows_lock_test.go @@ -10,6 +10,8 @@ import ( "encoding/json" "errors" "net/http" + "net/http/httptest" + "strconv" "strings" "testing" "time" @@ -17,28 +19,35 @@ import ( activity_api "github.com/fleetdm/fleet/v4/server/activity/api" "github.com/fleetdm/fleet/v4/server/authz" "github.com/fleetdm/fleet/v4/server/config" + "github.com/fleetdm/fleet/v4/server/contexts/ctxdb" "github.com/fleetdm/fleet/v4/server/contexts/viewer" "github.com/fleetdm/fleet/v4/server/fleet" microsoft_mdm "github.com/fleetdm/fleet/v4/server/mdm/microsoft" "github.com/fleetdm/fleet/v4/server/mock" + "github.com/google/uuid" + "github.com/gorilla/mux" "github.com/stretchr/testify/require" ) const openframeTestRecoveryKey = "111111-222222-333333-444444-555555-666666-777777-888888" type openframeWindowsLockFixture struct { - svc fleet.Service - impl *Service - ctx context.Context - baseCtx context.Context - ds *mock.Store - host *fleet.Host - status *fleet.HostLockWipeStatus - key *fleet.HostDiskEncryptionKey - keyErr error - request *fleet.HostScriptRequestPayload - platform string - activities []activity_api.ActivityDetails + svc fleet.Service + impl *Service + ctx context.Context + baseCtx context.Context + ds *mock.Store + host *fleet.Host + status *fleet.HostLockWipeStatus + key *fleet.HostDiskEncryptionKey + keyErr error + request *fleet.HostScriptRequestPayload + refs fleet.OpenframeHostMDMActionRefs + expected fleet.OpenframeHostMDMActionRefs + lockErr error + + statusOnPrimary bool + activities []activity_api.ActivityDetails } func newOpenframeWindowsLockFixture(t *testing.T) *openframeWindowsLockFixture { @@ -75,14 +84,21 @@ func newOpenframeWindowsLockFixture(t *testing.T) *openframeWindowsLockFixture { } return f.host, nil } - f.ds.GetHostLockWipeStatusFunc = func(context.Context, *fleet.Host) (*fleet.HostLockWipeStatus, error) { return f.status, nil } + f.ds.GetHostLockWipeStatusFunc = func(ctx context.Context, _ *fleet.Host) (*fleet.HostLockWipeStatus, error) { + f.statusOnPrimary = ctxdb.IsPrimaryRequired(ctx) + return f.status, nil + } f.ds.GetHostDiskEncryptionKeyFunc = func(_ context.Context, hostID uint) (*fleet.HostDiskEncryptionKey, error) { require.Equal(t, f.host.ID, hostID) return f.key, f.keyErr } - f.ds.LockHostViaScriptFunc = func(_ context.Context, request *fleet.HostScriptRequestPayload, platform string) error { - f.request, f.platform = request, platform - return nil + f.ds.OpenframeHostMDMActionRefsFunc = func(_ context.Context, hostID uint) (fleet.OpenframeHostMDMActionRefs, error) { + require.Equal(t, f.host.ID, hostID) + return f.refs, nil + } + f.ds.OpenframeLockWindowsHostViaScriptFunc = func(_ context.Context, request *fleet.HostScriptRequestPayload, expected fleet.OpenframeHostMDMActionRefs) error { + f.request, f.expected = request, expected + return f.lockErr } return f } @@ -104,15 +120,24 @@ func TestOpenframeLockWindowsHostQueuesScript(t *testing.T) { require.NoError(t, err) require.True(t, locked) - require.Equal(t, "windows", f.platform) require.Equal(t, f.host.ID, f.request.HostID) + require.True(t, f.statusOnPrimary, "the status is read where the references are") require.Equal(t, new(uint(3)), f.request.UserID) script := f.request.ScriptContents require.Contains(t, script, "$keyHash = '"+openframeTestKeyHash(openframeTestRecoveryKey)+"'", "the key is trimmed before hashing") require.Contains(t, script, "FromBase64String('"+base64.StdEncoding.EncodeToString([]byte(message))+"')") require.NotContains(t, script, openframeTestRecoveryKey, "the script never carries the key") require.NotContains(t, script, "Example Ltd", "the message is only in base64") - require.Contains(t, script, "manage-bde.exe -forcerecovery $drive") + require.Contains(t, script, "& manage-bde.exe -forcerecovery $drive 2>&1") + require.Less(t, strings.Index(script, "$ErrorActionPreference = 'Continue'"), strings.Index(script, "-forcerecovery"), + "manage-bde's error output doesn't end the script before the cleanup") + require.Regexp(t, `\$lockId = '[0-9a-f-]{36}'`, script) + require.Less(t, strings.Index(script, "BitLockerLastLockId -eq $lockId"), strings.Index(script, "Get-BitLockerVolume"), + "a lock that ran already does nothing") + require.Less(t, strings.Index(script, "Register-ScheduledTask"), strings.Index(script, "-forcerecovery"), + "the startup task that restores the TPM protector is there before the TPM protector is gone") + require.Contains(t, script, "[Microsoft.Win32.RegistryOptions]::Volatile") + require.Contains(t, script, "$unlockCommand = '"+openframePowerShellEncodedCommand(openframeWindowsUnlockScript)+"'") require.Contains(t, script, "shutdown.exe /r /f /t 30") require.Less(t, strings.Index(script, "$keyOnDrive"), strings.Index(script, "-forcerecovery"), "the key is checked on the PC first") @@ -189,7 +214,7 @@ func TestOpenframeLockWindowsHostRefused(t *testing.T) { require.ErrorAs(t, err, &invalid) } require.Equal(t, tc.status, status) - require.False(t, f.ds.LockHostViaScriptFuncInvoked) + require.False(t, f.ds.OpenframeLockWindowsHostViaScriptFuncInvoked) require.Empty(t, f.activities) }) } @@ -208,7 +233,7 @@ func TestOpenframeLockWindowsHostAccess(t *testing.T) { _, err := f.svc.OpenframeLockWindowsHost(ctx, f.host.ID, "") var forbidden *authz.Forbidden require.ErrorAs(t, err, &forbidden) - require.False(t, f.ds.LockHostViaScriptFuncInvoked) + require.False(t, f.ds.OpenframeLockWindowsHostViaScriptFuncInvoked) }) t.Run("another platform", func(t *testing.T) { f := newOpenframeWindowsLockFixture(t) @@ -249,7 +274,7 @@ func TestOpenframeLockEndpoint(t *testing.T) { f = newOpenframeWindowsLockFixture(t) outside := viewer.NewContext(f.baseCtx, viewer.Viewer{User: &fleet.User{ID: 3, GlobalRole: new(fleet.RoleAdmin)}}) require.ErrorIs(t, call(f, outside).Err, fleet.ErrMissingLicense, "upstream outside OpenFrame mode") - require.False(t, f.ds.LockHostViaScriptFuncInvoked) + require.False(t, f.ds.OpenframeLockWindowsHostViaScriptFuncInvoked) } func TestOpenframeWindowsLockResultActivities(t *testing.T) { @@ -273,6 +298,9 @@ func TestOpenframeWindowsLockResultActivities(t *testing.T) { fleet.ActivityTypeUnlockedHost{HostID: 1, HostDisplayName: "pc-1", HostPlatform: "windows"}, }}, {"not restarted yet", host, "unlock_ref", exit(10), false, nil}, + {"TPM protector not added back", host, "unlock_ref", exit(11), false, []activity_api.ActivityDetails{ + fleet.ActivityTypeOpenframeUnlockFailedHost{HostID: 1, HostDisplayName: "pc-1", HostPlatform: "windows", ExitCode: 11}, + }}, {"another script", host, "", exit(0), false, nil}, {"wipe", host, "wipe_ref", exit(0), false, nil}, {"duplicate result", host, "lock_ref", nil, false, nil}, @@ -310,6 +338,14 @@ func TestOpenframeLockActivities(t *testing.T) { details, err = json.Marshal(failed) require.NoError(t, err) require.JSONEq(t, `{"host_id": 42, "host_display_name": "pc-1", "host_platform": "windows", "exit_code": 3}`, string(details)) + + unlockFailed := fleet.ActivityTypeOpenframeUnlockFailedHost{HostID: 42, HostDisplayName: "pc-1", HostPlatform: "windows", ExitCode: 11} + require.Equal(t, "failed_unlock", unlockFailed.ActivityName()) + require.Equal(t, []uint{42}, unlockFailed.HostIDs()) + require.True(t, unlockFailed.WasFromAutomation()) + details, err = json.Marshal(unlockFailed) + require.NoError(t, err) + require.JSONEq(t, `{"host_id": 42, "host_display_name": "pc-1", "host_platform": "windows", "exit_code": 11}`, string(details)) } func TestOpenframeWindowsUnlockQueuedOnCheckIn(t *testing.T) { @@ -326,10 +362,9 @@ func TestOpenframeWindowsUnlockQueuedOnCheckIn(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { f := newOpenframeWindowsLockFixture(t) - f.ds.OpenframeQueueWindowsUnlockFunc = func(_ context.Context, hostID uint, script string, delay time.Duration) (bool, error) { + f.ds.OpenframeQueueWindowsUnlockFunc = func(_ context.Context, hostID uint, script string) (bool, error) { require.Equal(t, tc.host.ID, hostID) require.Equal(t, openframeWindowsUnlockScript, script) - require.Equal(t, fleet.OpenframeWindowsUnlockDelay, delay) return true, nil } ctx := f.ctx @@ -342,7 +377,7 @@ func TestOpenframeWindowsUnlockQueuedOnCheckIn(t *testing.T) { } f := newOpenframeWindowsLockFixture(t) - f.ds.OpenframeQueueWindowsUnlockFunc = func(context.Context, uint, string, time.Duration) (bool, error) { + f.ds.OpenframeQueueWindowsUnlockFunc = func(context.Context, uint, string) (bool, error) { return false, errors.New("database is down") } f.impl.openframeQueueWindowsUnlock(f.ctx, &fleet.Host{ID: 1, Platform: "windows"}) @@ -351,9 +386,104 @@ func TestOpenframeWindowsUnlockQueuedOnCheckIn(t *testing.T) { func TestOpenframeWindowsUnlockScript(t *testing.T) { script := openframeWindowsUnlockScript - require.Contains(t, script, "LastBootUpTime") - require.Contains(t, script, "exit 10") + require.Contains(t, script, `if (Test-Path "HKLM:\$bootKeyPath")`) + require.NotContains(t, script, "LastBootUpTime", "the restart isn't told by the clock") + require.Contains(t, script, "exit "+strconv.Itoa(fleet.OpenframeWindowsUnlockNotRestarted)) require.Contains(t, script, "Add-BitLockerKeyProtector -MountPoint $drive -TpmProtector") require.Less(t, strings.Index(script, "exit 10"), strings.Index(script, "Add-BitLockerKeyProtector"), "nothing changes before the PC restarted") require.Contains(t, script, "Restore-RecoveryMessage $state") + require.Contains(t, script, "Unregister-ScheduledTask") +} + +func TestOpenframePowerShellEncodedCommand(t *testing.T) { + decoded, err := base64.StdEncoding.DecodeString(openframePowerShellEncodedCommand("exit 0 # é")) + require.NoError(t, err) + require.Equal(t, []byte{'e', 0, 'x', 0, 'i', 0, 't', 0, ' ', 0, '0', 0, ' ', 0, '#', 0, ' ', 0, 0xe9, 0}, decoded) + require.Less(t, len(openframeWindowsLockScript(uuid.NewString(), strings.Repeat("a", 64), strings.Repeat("é", 240))), 32000, + "the startup task's command stays under its length limit") +} + +func TestOpenframeLockPassesTheReferencesRead(t *testing.T) { + f := newOpenframeWindowsLockFixture(t) + f.refs = fleet.OpenframeHostMDMActionRefs{LockRef: new("failed-lock"), WipeRef: nil} + _, err := f.lock("") + require.NoError(t, err) + require.Equal(t, f.refs, f.expected) + + f = newOpenframeWindowsLockFixture(t) + f.lockErr = fleet.NewInvalidArgumentError("host_id", "The host's lock or wipe changed while it was being locked.") + locked, err := f.lock("") + require.False(t, locked) + require.ErrorContains(t, err, "changed while it was being locked") + require.Empty(t, f.activities, "a refused lock records nothing") +} + +func TestOpenframeLockRequestBody(t *testing.T) { + decoder := makeDecoder(fleet.LockHostRequest{}, 1<<20) + decode := func(body string, header map[string]string) (*fleet.LockHostRequest, error) { + var reader *strings.Reader + if body != "" { + reader = strings.NewReader(body) + } + var req *http.Request + if reader == nil { + req = httptest.NewRequest(http.MethodPost, "/api/latest/fleet/hosts/7/lock", nil) + } else { + req = httptest.NewRequest(http.MethodPost, "/api/latest/fleet/hosts/7/lock", reader) + } + for k, v := range header { + req.Header.Set(k, v) + } + req = mux.SetURLVars(req, map[string]string{"id": "7"}) + decoded, err := decoder(t.Context(), req) + if err != nil { + return nil, err + } + return decoded.(*fleet.LockHostRequest), nil + } + + req, err := decode("", nil) + require.NoError(t, err, "upstream's callers send no body") + require.Equal(t, uint(7), req.HostID) + require.Empty(t, req.OpenframeMessage) + + req, err = decode("", map[string]string{"Origin": "https://fleet.example"}) + require.NoError(t, err, "nor does the browser") + require.Empty(t, req.OpenframeMessage) + + req, err = decode(`{}`, nil) + require.NoError(t, err) + require.Empty(t, req.OpenframeMessage) + + req, err = decode(`{"message": "Call IT"}`, map[string]string{"Content-Type": "application/json"}) + require.NoError(t, err) + require.Equal(t, "Call IT", req.OpenframeMessage) + + _, err = decode(`{"message":`, nil) + var badRequest *fleet.BadRequestError + require.ErrorAs(t, err, &badRequest) +} + +func TestOpenframeWindowsUnlockDue(t *testing.T) { + cases := []struct { + name string + sinceLock time.Duration + attempts int + sinceAttempt time.Duration + due bool + }{ + {"right after the lock", time.Minute, 0, 0, false}, + {"after the first delay", fleet.OpenframeWindowsUnlockFirstDelay, 0, 0, true}, + {"retry too soon", time.Hour, 1, 14 * time.Minute, false}, + {"first retry", time.Hour, 1, 15 * time.Minute, true}, + {"second retry waits twice as long", time.Hour, 2, 29 * time.Minute, false}, + {"second retry", time.Hour, 2, 30 * time.Minute, true}, + {"many retries wait a day", 72 * time.Hour, 20, 23 * time.Hour, false}, + {"many retries after a day", 72 * time.Hour, 20, 24 * time.Hour, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.due, fleet.OpenframeWindowsUnlockDue(tc.sinceLock, tc.attempts, tc.sinceAttempt)) + }) + } } From e7b11e743f0b6558520623e3952ed0f4137fa0cc Mon Sep 17 00:00:00 2001 From: Andrii Koropets Date: Thu, 3 Dec 2026 21:40:13 +0200 Subject: [PATCH 3/3] fix(mdm): CU-17tkuw6a8c2 skip policy scripts in OpenFrame mode and test the lock switches --- openframe/docs/fork-file-manifest.md | 2 +- openframe/docs/windows-lock.md | 3 ++- server/fleet/openframe_windows_lock_test.go | 16 ++++++++++++++ server/service/openframe_windows_lock_test.go | 22 +++++++++++++++++-- server/service/osquery.go | 5 +++++ 5 files changed, 44 insertions(+), 4 deletions(-) create mode 100644 server/fleet/openframe_windows_lock_test.go diff --git a/openframe/docs/fork-file-manifest.md b/openframe/docs/fork-file-manifest.md index 2ffdf3d6415..808d03a993e 100644 --- a/openframe/docs/fork-file-manifest.md +++ b/openframe/docs/fork-file-manifest.md @@ -176,7 +176,7 @@ and the heaviest standing rebase cost. | 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` | -| Windows lock (`openframe/docs/windows-lock.md`) | `server/service/{scripts,orbit,openframe_windows_lock}.go`, `server/fleet/{api_scripts,datastore,service,openframe_windows_lock}.go`, `server/mock/datastore_mock.go`, `server/mock/service/service_mock.go`, `server/datastore/mysql/{scripts,openframe_windows_lock}.go`; tests: `server/service/openframe_windows_lock_test.go`, `server/datastore/mysql/openframe_windows_lock_test.go` | +| Windows lock (`openframe/docs/windows-lock.md`) | `server/service/{scripts,orbit,osquery,openframe_windows_lock}.go`, `server/fleet/{api_scripts,datastore,service,openframe_windows_lock}.go`, `server/mock/datastore_mock.go`, `server/mock/service/service_mock.go`, `server/datastore/mysql/{scripts,openframe_windows_lock}.go`; tests: `server/service/openframe_windows_lock_test.go`, `server/datastore/mysql/openframe_windows_lock_test.go`, `server/fleet/openframe_windows_lock_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/windows-lock.md b/openframe/docs/windows-lock.md index ad671e74a3f..c6e7b015b18 100644 --- a/openframe/docs/windows-lock.md +++ b/openframe/docs/windows-lock.md @@ -90,7 +90,8 @@ Wipe is refused while a host is locked, by upstream's checks. Fleet can't turn M fleetd on Windows runs scripts only when started with `--enable-scripts`, so OpenFrame has to start it with that flag; without it the lock is refused. In OpenFrame and shared mode the fork then refuses every script that isn't Fleet's own (`openframeRefuseScript`, in -upstream's `insertNewHostScriptExecution`): a user's, a batch's or a policy's script is refused (422) and not queued. +upstream's `insertNewHostScriptExecution`): a user's or a batch's script is refused (422) and not queued, and a policy's script +is not queued when the policy starts failing (`processScriptsForNewlyFailingPolicies`), so it logs no error. Internal scripts (lock, unlock, upstream's internal cleanups) and software installs and uninstalls are not affected. ## Tenancy diff --git a/server/fleet/openframe_windows_lock_test.go b/server/fleet/openframe_windows_lock_test.go new file mode 100644 index 00000000000..ea981304a00 --- /dev/null +++ b/server/fleet/openframe_windows_lock_test.go @@ -0,0 +1,16 @@ +// OPENFRAME(windows-lock) +package fleet + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestOpenframeWindowsLockEnabled(t *testing.T) { + if IsOpenframeMode() || IsOpenframeSharedMode() { + t.Skip("OpenFrame mode is on for the whole process") + } + require.False(t, OpenframeWindowsLockEnabled(t.Context())) + require.True(t, OpenframeWindowsLockEnabled(NewOpenframeModeContext(t.Context()))) +} diff --git a/server/service/openframe_windows_lock_test.go b/server/service/openframe_windows_lock_test.go index 24339e1faff..7fbc2868c08 100644 --- a/server/service/openframe_windows_lock_test.go +++ b/server/service/openframe_windows_lock_test.go @@ -478,8 +478,8 @@ func TestOpenframeWindowsUnlockDue(t *testing.T) { {"first retry", time.Hour, 1, 15 * time.Minute, true}, {"second retry waits twice as long", time.Hour, 2, 29 * time.Minute, false}, {"second retry", time.Hour, 2, 30 * time.Minute, true}, - {"many retries wait a day", 72 * time.Hour, 20, 23 * time.Hour, false}, - {"many retries after a day", 72 * time.Hour, 20, 24 * time.Hour, true}, + {"many retries wait the longest delay", 72 * time.Hour, 20, fleet.OpenframeWindowsUnlockMaxRetryDelay - time.Hour, false}, + {"many retries after the longest delay", 72 * time.Hour, 20, fleet.OpenframeWindowsUnlockMaxRetryDelay, true}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -487,3 +487,21 @@ func TestOpenframeWindowsUnlockDue(t *testing.T) { }) } } + +func TestOpenframePolicyScriptsNotQueued(t *testing.T) { + f := newOpenframeWindowsLockFixture(t) + f.ds.AppConfigFunc = func(context.Context) (*fleet.AppConfig, error) { + return &fleet.AppConfig{ServerSettings: fleet.ServerSettings{ScriptsDisabled: true}}, nil + } + failing := map[uint]*bool{1: new(false)} + process := func(ctx context.Context) error { + return f.impl.processScriptsForNewlyFailingPolicies(ctx, f.host.ID, f.host.TeamID, "windows", new("orbit-key"), new(true), + failing, map[uint]struct{}{1: {}}) + } + + require.NoError(t, process(f.ctx)) + require.False(t, f.ds.AppConfigFuncInvoked, "OpenFrame mode stops before any policy's script is looked at") + + require.NoError(t, process(f.baseCtx)) + require.True(t, f.ds.AppConfigFuncInvoked, "upstream outside OpenFrame mode") +} diff --git a/server/service/osquery.go b/server/service/osquery.go index 1e60ab4ec59..7f2d951866f 100644 --- a/server/service/osquery.go +++ b/server/service/osquery.go @@ -2413,6 +2413,11 @@ func (svc *Service) processScriptsForNewlyFailingPolicies( if hostOrbitNodeKey == nil || *hostOrbitNodeKey == "" { return nil // vanilla osquery hosts can't run scripts } + // >>> OPENFRAME(windows-lock): fleetd runs only Fleet's own scripts in OpenFrame mode, so a policy's script is not queued — openframe/docs/windows-lock.md + if fleet.OpenframeWindowsLockEnabled(ctx) { + return nil + } + // <<< OPENFRAME(windows-lock) // not logging here to avoid spamming logs on every policy failure for every no-scripts host even if the policy // doesn't have a script attached if hostScriptsEnabled != nil && !*hostScriptsEnabled {