Skip to content

Commit 02cfa9a

Browse files
fix(mdm): CU-17tkuw6a8c2 make the Windows lock safe against lost results, races and re-enrollment
1 parent bc97e8b commit 02cfa9a

10 files changed

Lines changed: 612 additions & 140 deletions

‎openframe/docs/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ The agent has its own switch, `--openframe-mode` / `ORBIT_OPENFRAME_MODE`.
4848
| [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. |
4949
| [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. |
5050
| [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. |
51-
| [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. |
51+
| [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. |
5252

5353
## Agent-side (orbit / fleetd)
5454

‎openframe/docs/windows-lock.md‎

Lines changed: 44 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -23,48 +23,65 @@ Refused:
2323
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
2424
pair has to decrypt the key.
2525

26-
The lock is queued by upstream's `LockHostViaScript` as an internal script, so the host's status is upstream's: pending
27-
lock until fleetd reports the result, locked once it reports exit code 0. `locked_host` is recorded with the request.
26+
The lock is queued as an internal script with upstream's `lock_ref`, so the host's status is upstream's: pending lock
27+
until fleetd reports the result, locked once it reports exit code 0. The host's lock, unlock and wipe references are
28+
read before its status is checked, and the lock is queued only if they are still the same, in one transaction under
29+
the host's row lock (`OpenframeLockWindowsHostViaScript`): of two concurrent locks one is queued, the other answers
30+
422. `locked_host` is recorded with the request.
2831

2932
## The lock script
3033

31-
It runs on the PC as SYSTEM, in PowerShell, and on `%SystemDrive%`:
34+
It runs on the PC as SYSTEM, in PowerShell, and on `%SystemDrive%`. Each request gets its own id.
3235

33-
1. checks that BitLocker protects the drive (exit 2);
34-
2. checks that one of the drive's recovery passwords is the key Fleet holds: the script carries its SHA-256, never
36+
1. exits 0 if this request's lock ran on the PC already (`BitLockerLastLockId` under `HKLM\SOFTWARE\OpenFrame`, kept
37+
after the unlock). fleetd keeps no record of the scripts it ran: when the result of a lock is lost before the
38+
restart, fleetd runs the script again once the PC is back, and it must not lock the PC a second time;
39+
2. checks that BitLocker protects the drive (exit 2);
40+
3. checks that one of the drive's recovery passwords is the key Fleet holds: the script carries its SHA-256, never
3541
the key (exit 3). A locked PC that Fleet's key doesn't open could not be started again;
36-
3. refuses a drive with a TPM protector that has a PIN or a startup key, which the lock would delete and the unlock
42+
4. refuses a drive with a TPM protector that has a PIN or a startup key, which the lock would delete and the unlock
3743
couldn't restore (exit 4);
38-
4. records under `HKLM\SOFTWARE\OpenFrame\BitLockerLock` when it locked, whether the drive had a TPM protector, and
39-
the recovery message policy it replaces;
40-
5. sets the message, if any, as the recovery message policy (`HKLM\SOFTWARE\Policies\Microsoft\FVE`,
44+
5. records under `HKLM\SOFTWARE\OpenFrame\BitLockerLock` whether the drive had a TPM protector and the recovery message
45+
policy it replaces. A record left by a lock that didn't finish is kept, and its message is restored when the new
46+
lock has none;
47+
6. sets the message, if any, as the recovery message policy (`HKLM\SOFTWARE\Policies\Microsoft\FVE`,
4148
`RecoveryKeyMessageSource` = 2 and `RecoveryKeyMessage`). The message reaches the script in base64, so nothing in
4249
it runs;
43-
6. runs `manage-bde -forcerecovery`, which also deletes the drive's TPM protectors (exit 5 if it fails, with the
44-
message and the record undone);
45-
7. restarts the PC in 30 seconds, closing open apps, and exits 0, so that fleetd reports the result before it.
50+
7. registers the startup task `\OpenFrame\BitLocker unlock` (SYSTEM), which runs the unlock script below, carried in
51+
the task as an encoded command and not as a file, and creates the volatile key
52+
`HKLM\SOFTWARE\OpenFrame\BitLockerLockBoot`, which Windows drops at restart (exit 6 if either fails);
53+
8. runs `manage-bde -forcerecovery`, which also deletes the drive's TPM protectors (exit 5 if it fails, with the
54+
message, the record, the task and the volatile key undone). Its error output doesn't end the script;
55+
9. records the request's id, restarts the PC in 30 seconds, closing open apps, and exits 0, so that fleetd reports
56+
the result before it.
4657

4758
A failed lock clears the pending lock and records `failed_lock` with the exit code; a lock that succeeded records
4859
`completed_lock` (`server/fleet/openframe_windows_lock.go`).
4960

5061
## Unlock
5162

52-
When a locked Windows host checks in (orbit config) at least 15 minutes after its lock succeeded, someone has typed
53-
the recovery key. The fork then queues an internal unlock script with upstream's `unlock_ref`
54-
(`OpenframeQueueWindowsUnlock`, `server/datastore/mysql/openframe_windows_lock.go`), unless an unlock is pending, a
55-
wipe is, or an unlock was tried within the last 15 minutes. The host's row is locked while the script is queued, so
56-
concurrent check-ins queue one.
63+
The unlock script runs twice over: on the PC at the first start after the recovery key was typed, from the startup
64+
task, so the TPM protector comes back even when fleetd doesn't or the host's lock was cleared in Fleet (an agent
65+
re-enrollment clears it); and from Fleet, which confirms the unlock and marks the host unlocked.
66+
67+
When a locked Windows host checks in (orbit config) at least 2 minutes after its lock succeeded, someone has typed the
68+
recovery key. The fork then queues the internal unlock script with upstream's `unlock_ref` (`OpenframeQueueWindowsUnlock`,
69+
`server/datastore/mysql/openframe_windows_lock.go`), unless an unlock or a wipe is pending. A failed attempt is tried
70+
again 15 minutes later, then after twice as long each time, up to a day (`OpenframeWindowsUnlockDue`). The host's row
71+
is locked while the script is queued, so concurrent check-ins queue one.
5772

5873
The script:
5974

60-
1. exits 0 if no lock is recorded on the PC;
61-
2. exits 10 if the PC hasn't restarted since the lock: the host stays locked and the unlock is tried again later;
75+
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;
76+
2. exits 10 if the volatile key is there: the PC hasn't restarted since the lock, e.g. as someone cancelled the
77+
restart with `shutdown /a`. The host stays locked, the drive goes to recovery at the next restart, and nothing is
78+
recorded;
6279
3. adds a TPM protector back if the drive had one, as `-forcerecovery` deleted it and Windows would otherwise ask for
6380
the key at every start (exit 11 if it can't);
64-
4. restores the recovery message policy and removes the record.
81+
4. restores the recovery message policy and removes the record, the volatile key and the startup task.
6582

66-
Exit code 0 makes the host unlocked, as upstream, and records `unlocked_host` with no user. A failed unlock records
67-
nothing.
83+
Exit code 0 makes the host unlocked, as upstream, and records `unlocked_host` with no user. Any other failure than
84+
exit 10 records `failed_unlock` with the exit code.
6885

6986
Wipe is refused while a host is locked, by upstream's checks. Fleet can't turn MDM off for a Windows host.
7087

@@ -84,9 +101,11 @@ recorded in that request's tenant.
84101

85102
## Not verified on a real PC yet
86103

87-
- that the recovery screen shows the message set by the policy;
88-
- that fleetd always reports the lock's result within the 30 seconds before the restart. A result that is lost
89-
leaves the host pending lock.
104+
- that the recovery screen shows the message set by the policy, and how it shows characters outside ASCII;
105+
- the startup task, the volatile key (`RegistryOptions.Volatile` needs .NET Framework 4.6 or later) and
106+
`Add-BitLockerKeyProtector` at startup;
107+
- a lock whose result is lost before the restart stays pending lock in Fleet until fleetd runs it again after the
108+
unlock, which then reports it done.
90109

91110
## Tests
92111

‎server/datastore/mysql/openframe_windows_lock.go‎

Lines changed: 103 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,12 @@ import (
1313
"github.com/jmoiron/sqlx"
1414
)
1515

16-
var errOpenframeOnlyInternalScripts = fleet.NewInvalidArgumentError("script",
17-
"Fleet runs only its own scripts on hosts in OpenFrame mode.")
16+
var (
17+
errOpenframeOnlyInternalScripts = fleet.NewInvalidArgumentError("script",
18+
"Fleet runs only its own scripts on hosts in OpenFrame mode.")
19+
errOpenframeLockRaced = fleet.NewInvalidArgumentError("host_id",
20+
"The host's lock or wipe changed while it was being locked. Reload the host and try again.")
21+
)
1822

1923
func openframeWindowsLockEnabled(ctx context.Context) bool {
2024
return fleet.OpenframeWindowsLockEnabled(ctx) || openframeSharedMode(ctx)
@@ -29,44 +33,124 @@ func openframeRefuseScript(ctx context.Context, isInternal bool) error {
2933
return ctxerr.Wrap(ctx, errOpenframeOnlyInternalScripts)
3034
}
3135

32-
// openframeWindowsUnlockDue selects the locked Windows host whose unlock may be queued now: its lock succeeded at least
33-
// the delay ago, nothing else is pending for it, and no unlock was tried within the delay.
34-
const openframeWindowsUnlockDue = `SELECT hma.lock_ref
36+
const openframeHostMDMActionRefs = `SELECT lock_ref, unlock_ref, wipe_ref FROM host_mdm_actions WHERE host_id = ?`
37+
38+
// OpenframeHostMDMActionRefs returns the host's lock, unlock and wipe references as stored, all nil without a row.
39+
func (ds *Datastore) OpenframeHostMDMActionRefs(ctx context.Context, hostID uint) (fleet.OpenframeHostMDMActionRefs, error) {
40+
return openframeReadHostMDMActionRefs(ctx, ds.writer(ctx), openframeHostMDMActionRefs, hostID)
41+
}
42+
43+
// openframeReadHostMDMActionRefs reads the references, all nil without a row: sqlx allocates the pointers before it
44+
// finds there is none.
45+
func openframeReadHostMDMActionRefs(ctx context.Context, q sqlx.QueryerContext, stmt string, hostID uint) (fleet.OpenframeHostMDMActionRefs, error) {
46+
var refs fleet.OpenframeHostMDMActionRefs
47+
switch err := sqlx.GetContext(ctx, q, &refs, stmt, hostID); {
48+
case errors.Is(err, sql.ErrNoRows):
49+
return fleet.OpenframeHostMDMActionRefs{}, nil
50+
case err != nil:
51+
return fleet.OpenframeHostMDMActionRefs{}, ctxerr.Wrap(ctx, err, "read the host's MDM action references")
52+
}
53+
return refs, nil
54+
}
55+
56+
// OpenframeLockWindowsHostViaScript queues the lock as LockHostViaScript does, in one transaction with a check that
57+
// the host's references are the ones its lock status was read from: of two concurrent locks one is queued.
58+
func (ds *Datastore) OpenframeLockWindowsHostViaScript(ctx context.Context, request *fleet.HostScriptRequestPayload, expected fleet.OpenframeHostMDMActionRefs) error {
59+
return ds.withRetryTxx(ctx, func(tx sqlx.ExtContext) error {
60+
current, err := openframeReadHostMDMActionRefs(ctx, tx, openframeHostMDMActionRefs+` FOR UPDATE`, request.HostID)
61+
if err != nil {
62+
return err
63+
}
64+
if !openframeSameRef(current.LockRef, expected.LockRef) || !openframeSameRef(current.UnlockRef, expected.UnlockRef) ||
65+
!openframeSameRef(current.WipeRef, expected.WipeRef) {
66+
return ctxerr.Wrap(ctx, errOpenframeLockRaced)
67+
}
68+
69+
contents, err := insertScriptContents(ctx, tx, request.ScriptContents)
70+
if err != nil {
71+
return err
72+
}
73+
contentID, _ := contents.LastInsertId()
74+
request.ScriptContentID = uint(contentID) //nolint:gosec // dismiss G115
75+
result, err := ds.newHostScriptExecutionRequest(ctx, tx, request, true)
76+
if err != nil {
77+
return ctxerr.Wrap(ctx, err, "queue the lock script")
78+
}
79+
_, err = tx.ExecContext(ctx, `INSERT INTO host_mdm_actions (host_id, lock_ref, fleet_platform) VALUES (?, ?, 'windows')
80+
ON DUPLICATE KEY UPDATE lock_ref = VALUES(lock_ref)`, request.HostID, result.ExecutionID)
81+
return ctxerr.Wrap(ctx, err, "record the lock script")
82+
})
83+
}
84+
85+
func openframeSameRef(a, b *string) bool {
86+
if a == nil || b == nil {
87+
return a == nil && b == nil
88+
}
89+
return *a == *b
90+
}
91+
92+
// openframeWindowsUnlockStateQuery selects a locked Windows host whose unlock may be queued: its lock succeeded and no
93+
// unlock or wipe is pending. It returns how long ago the lock succeeded, and how many unlocks were tried since and how
94+
// long ago the last one was.
95+
const openframeWindowsUnlockStateQuery = `SELECT hma.lock_ref,
96+
TIMESTAMPDIFF(SECOND, lock_result.updated_at, CURRENT_TIMESTAMP) AS since_lock,
97+
COUNT(attempt.id) AS attempts,
98+
COALESCE(TIMESTAMPDIFF(SECOND, MAX(attempt.created_at), CURRENT_TIMESTAMP), 0) AS since_attempt
3599
FROM host_mdm_actions hma
36100
JOIN host_script_results lock_result ON lock_result.execution_id = hma.lock_ref AND lock_result.host_id = hma.host_id
101+
LEFT JOIN script_contents sc ON sc.md5_checksum = UNHEX(?)
102+
LEFT JOIN host_script_results attempt ON attempt.host_id = hma.host_id AND attempt.script_content_id = sc.id
103+
AND attempt.id > lock_result.id
37104
WHERE hma.host_id = ? AND hma.fleet_platform = 'windows' AND hma.unlock_ref IS NULL AND hma.wipe_ref IS NULL
38-
AND lock_result.exit_code = 0 AND lock_result.updated_at <= CURRENT_TIMESTAMP - INTERVAL ? SECOND
39-
AND NOT EXISTS (
40-
SELECT 1 FROM host_script_results attempt
41-
JOIN script_contents sc ON sc.id = attempt.script_content_id
42-
WHERE attempt.host_id = hma.host_id AND sc.md5_checksum = UNHEX(?)
43-
AND attempt.created_at > CURRENT_TIMESTAMP - INTERVAL ? SECOND)`
105+
AND lock_result.exit_code = 0
106+
GROUP BY hma.lock_ref, lock_result.updated_at`
107+
108+
type openframeWindowsUnlockState struct {
109+
LockRef string `db:"lock_ref"`
110+
SinceLock int64 `db:"since_lock"`
111+
Attempts int `db:"attempts"`
112+
SinceAttempt int64 `db:"since_attempt"`
113+
}
114+
115+
func (s openframeWindowsUnlockState) due() bool {
116+
return fleet.OpenframeWindowsUnlockDue(time.Duration(s.SinceLock)*time.Second, s.Attempts, time.Duration(s.SinceAttempt)*time.Second)
117+
}
44118

45119
// OpenframeQueueWindowsUnlock queues the unlock script of a locked Windows host and reports whether it did. A host that
46120
// checks in while it is locked was unlocked with its recovery key; the script confirms the PC restarted after the lock
47121
// and restores what the lock removed.
48-
func (ds *Datastore) OpenframeQueueWindowsUnlock(ctx context.Context, hostID uint, script string, delay time.Duration) (bool, error) {
49-
seconds := int64(delay / time.Second)
50-
checksum := md5ChecksumScriptContent(script)
51-
args := []any{hostID, seconds, checksum, seconds}
122+
func (ds *Datastore) OpenframeQueueWindowsUnlock(ctx context.Context, hostID uint, script string) (bool, error) {
123+
args := []any{md5ChecksumScriptContent(script), hostID}
52124

53-
var lockRef string
54-
switch err := sqlx.GetContext(ctx, ds.reader(ctx), &lockRef, openframeWindowsUnlockDue, args...); {
125+
var state openframeWindowsUnlockState
126+
switch err := sqlx.GetContext(ctx, ds.reader(ctx), &state, openframeWindowsUnlockStateQuery, args...); {
55127
case errors.Is(err, sql.ErrNoRows):
56128
return false, nil
57129
case err != nil:
58130
return false, ctxerr.Wrap(ctx, err, "check whether a locked Windows host is due its unlock")
131+
case !state.due():
132+
return false, nil
59133
}
60134

61135
var queued bool
62136
err := ds.withRetryTxx(ctx, func(tx sqlx.ExtContext) error {
63137
queued = false
64-
if err := sqlx.GetContext(ctx, tx, &lockRef, openframeWindowsUnlockDue+` FOR UPDATE OF hma`, args...); err != nil {
138+
var locked string
139+
if err := sqlx.GetContext(ctx, tx, &locked, `SELECT host_id FROM host_mdm_actions WHERE host_id = ? FOR UPDATE`, hostID); err != nil {
65140
if errors.Is(err, sql.ErrNoRows) {
66141
return nil
67142
}
68143
return ctxerr.Wrap(ctx, err, "lock the host's MDM actions")
69144
}
145+
if err := sqlx.GetContext(ctx, tx, &state, openframeWindowsUnlockStateQuery, args...); err != nil {
146+
if errors.Is(err, sql.ErrNoRows) {
147+
return nil
148+
}
149+
return ctxerr.Wrap(ctx, err, "check the locked Windows host again")
150+
}
151+
if !state.due() {
152+
return nil
153+
}
70154
contents, err := insertScriptContents(ctx, tx, script)
71155
if err != nil {
72156
return err
@@ -81,7 +165,7 @@ func (ds *Datastore) OpenframeQueueWindowsUnlock(ctx context.Context, hostID uin
81165
return ctxerr.Wrap(ctx, err, "queue the unlock script")
82166
}
83167
if _, err := tx.ExecContext(ctx, `UPDATE host_mdm_actions SET unlock_ref = ? WHERE host_id = ? AND lock_ref = ?`,
84-
result.ExecutionID, hostID, lockRef); err != nil {
168+
result.ExecutionID, hostID, state.LockRef); err != nil {
85169
return ctxerr.Wrap(ctx, err, "record the unlock script")
86170
}
87171
queued = true

0 commit comments

Comments
 (0)