Skip to content

Commit e20cedc

Browse files
authored
fleetd Windows MDM wake (push vs poll) (#46594)
<!-- Add the related story/sub-task/bug number, like Resolves #123, or remove if NA --> **Related issue:** Resolves #46567 and Resolves #46737 Solution for the agressive polling: - no WNS (although we could add it later as another avenue for notifications) - fleetd advertises a sync capability, persisted as `mdm_windows_enrollments.fleetd_sync_capable` - The management session relaxes the DMClient poll (`poll_schedule_relaxed`) - When an MDM command is queued, `has_pending_commands` flips, the next orbit check-in returns `WindowsMDMSyncRequest`, and fleetd runs `deviceenroller` to deliver it immediately - older fleetd versions keep the 1-minute poll Docs: #46780 Changes to osquery_perf and any additional changes after loadtesting will be done in a separate PR. # Checklist for submitter If some of the following don't apply, delete the relevant line. - [x] Changes file added for user-visible changes in `changes/`, `orbit/changes/` or `ee/fleetd-chrome/changes`. See [Changes files](https://github.com/fleetdm/fleet/blob/main/docs/Contributing/guides/committing-changes.md#changes-files) for more information. - [x] Timeouts are implemented and retries are limited to avoid infinite loops ## Testing - [x] Added/updated automated tests - [x] Where appropriate, [automated tests simulate multiple hosts and test for host isolation](https://github.com/fleetdm/fleet/blob/main/docs/Contributing/reference/patterns-backend.md#unit-testing) (updates to one hosts's records do not affect another) - [x] QA'd all new/changed functionality manually ## Database migrations - [x] Checked schema for all modified table for columns that will auto-update timestamps during migration. - [x] Confirmed that updating the timestamps is acceptable, and will not cause unwanted side effects. - [x] Ensured the correct collation is explicitly set for character columns (`COLLATE utf8mb4_unicode_ci`). ## fleetd/orbit/Fleet Desktop - [x] Verified compatibility with the latest released version of Fleet (see [Must rule](https://github.com/fleetdm/fleet/blob/main/docs/Contributing/workflows/fleetd-development-and-release-strategy.md)) - [x] If the change applies to only one platform, confirmed that `runtime.GOOS` is used as needed to isolate changes - [x] Verified that fleetd runs on macOS, Linux and Windows - [x] Verified auto-update works from the released version of component to the new version (see [tools/tuf/test](../tools/tuf/test/README.md)) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * On-demand Windows MDM sync: servers can request immediate delivery of queued MDM commands to Windows clients; Orbit triggers client-side sync on Windows. * **Enhancements** * Orbit throttles per-device on-demand sync to avoid excessive runs. * Server reconciles and persists device poll schedule (fast vs relaxed) and exposes consolidated host MDM state (awaiting-configuration + has-pending-commands). * **Tests** * Added tests covering host config state, pending-command flows, poll-schedule toggling, and on-demand sync behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 2c56d54 commit e20cedc

24 files changed

Lines changed: 1157 additions & 164 deletions
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- Reduced Windows MDM server and database load by relaxing the device management poll schedule from 1 minute to 8 hours for hosts running a version of fleetd that supports on-demand Windows MDM sync (1.57.0 and later). When commands are queued, the server wakes these devices through fleetd to start a management session, so command delivery stays near real-time. Hosts on older fleetd versions keep the previous poll behavior.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- Added support for on-demand Windows MDM sync. When the Fleet server requests it, fleetd now starts an OMA-DM management session so queued Windows MDM commands are delivered promptly even when the device's MDM poll schedule has been relaxed. This lets the server reduce the Windows MDM poll frequency without increasing command latency.

‎orbit/cmd/orbit/orbit.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1169,6 +1169,9 @@ func orbitAction(c *cli.Context) error {
11691169
renewEnrollmentProfileCommandFrequency = 3 * time.Minute
11701170
windowsMDMEnrollmentCommandFrequency = time.Hour
11711171
windowsMDMBitlockerCommandFrequency = time.Hour
1172+
// windowsMDMSyncCommandFrequency throttles on-demand OMA-DM syncs: while a command stays queued the server keeps setting
1173+
// WindowsMDMSyncRequest on each config poll, and this bounds how often we act on it.
1174+
windowsMDMSyncCommandFrequency = time.Minute
11721175
)
11731176

11741177
scriptConfigReceiver, scriptsEnabledFn := update.ApplyRunScriptsConfigFetcherMiddleware(
@@ -1240,6 +1243,7 @@ func orbitAction(c *cli.Context) error {
12401243

12411244
case "windows":
12421245
orbitClient.RegisterConfigReceiver(update.ApplyWindowsMDMEnrollmentFetcherMiddleware(windowsMDMEnrollmentCommandFrequency, orbitHostInfo.HardwareUUID, orbitClient))
1246+
orbitClient.RegisterConfigReceiver(update.ApplyWindowsMDMSyncFetcherMiddleware(windowsMDMSyncCommandFrequency))
12431247
comWorker, err := bitlocker.NewCOMWorker()
12441248
if err != nil {
12451249
return fmt.Errorf("create BitLocker COM worker: %w", err)

‎orbit/pkg/update/execwinapi_stub.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,7 @@ func RunWindowsMDMUnenrollment(args WindowsMDMEnrollmentArgs) error {
1313
func IsRunningOnWindowsServer() (bool, error) {
1414
return false, nil
1515
}
16+
17+
func TriggerWindowsMDMSync() error {
18+
return nil
19+
}

‎orbit/pkg/update/execwinapi_windows.go‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,21 @@
44
package update
55

66
import (
7+
"context"
78
"encoding/json"
9+
"errors"
810
"fmt"
911
"net/http"
12+
"os/exec"
13+
"path/filepath"
14+
"regexp"
1015
"strings"
1116
"syscall"
17+
"time"
1218
"unsafe"
1319

1420
"github.com/fleetdm/fleet/v4/server/fleet"
21+
"github.com/fleetdm/fleet/v4/server/mdm/microsoft/syncml"
1522
"github.com/rs/zerolog/log"
1623
"golang.org/x/sys/windows"
1724
"golang.org/x/sys/windows/registry"
@@ -190,3 +197,92 @@ func IsRunningOnWindowsServer() (bool, error) {
190197

191198
return false, nil
192199
}
200+
201+
// windowsMDMSyncTriggerTimeout bounds the deviceenroller invocation. attemptSync runs it in a background goroutine that holds the receiver's
202+
// lock, so this caps how long that goroutine (and the single-flight lock) stays tied up if deviceenroller ever hangs. `deviceenroller /o /c`
203+
// returns within seconds in practice; the timeout is a generous backstop, not the expected duration.
204+
const windowsMDMSyncTriggerTimeout = 2 * time.Minute
205+
206+
// TriggerWindowsMDMSync starts an on-demand, client-initiated OMA-DM session with the Fleet MDM server so that queued Windows MDM commands
207+
// are delivered without waiting for the device's next scheduled poll. It runs the OS deviceenroller for Fleet's enrollment in
208+
// client-initiated mode: `deviceenroller.exe /o <EnrollmentGUID> /c`.
209+
//
210+
// Microsoft does not publicly document the deviceenroller flags; `/o <GUID> /c` was established empirically and validated end-to-end on
211+
// Windows 11 24H2 (build 26100) and 25H2 (build 26200). On a warm device it reliably starts a session. On a just-booted or just-resumed
212+
// device the same call can exit 0 without actually starting a session, so a nil return here is best-effort, not a guarantee of delivery.
213+
// Delivery is ultimately guaranteed by the server continuing to request a sync while the command is queued (orbit re-fires on the next
214+
// config poll) and by the relaxed scheduled poll as a floor.
215+
//
216+
// Exported so it can be built/tested for Windows from tools/. Not meant to be called from outside this package.
217+
func TriggerWindowsMDMSync() error {
218+
guid, err := fleetMDMEnrollmentGUID()
219+
if err != nil {
220+
return fmt.Errorf("find Fleet MDM enrollment: %w", err)
221+
}
222+
223+
// Resolve System32 via the Windows API rather than the process environment, so the path we execute as SYSTEM can't be redirected by a
224+
// tampered SystemRoot. orbit is a 64-bit process, so this is the real (64-bit) System32 that contains deviceenroller.exe; there is no
225+
// WOW64 redirection to account for. If the API ever fails, use the hardcoded default rather than trusting an environment variable.
226+
systemDir, sysDirErr := windows.GetSystemDirectory()
227+
if sysDirErr != nil || systemDir == "" {
228+
systemDir = `C:\Windows\System32`
229+
}
230+
deviceEnroller := filepath.Join(systemDir, "deviceenroller.exe")
231+
232+
// Bound the call so a hung deviceenroller cannot block the config-receiver loop indefinitely.
233+
ctx, cancel := context.WithTimeout(context.Background(), windowsMDMSyncTriggerTimeout)
234+
defer cancel()
235+
236+
cmd := exec.CommandContext(ctx, deviceEnroller, "/o", guid, "/c")
237+
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
238+
if out, err := cmd.CombinedOutput(); err != nil {
239+
if ctx.Err() == context.DeadlineExceeded {
240+
return fmt.Errorf("run deviceenroller /o %s /c timed out after %s (output: %q)", guid, windowsMDMSyncTriggerTimeout, string(out))
241+
}
242+
return fmt.Errorf("run deviceenroller /o %s /c: %w (output: %q)", guid, err, string(out))
243+
}
244+
return nil
245+
}
246+
247+
// windowsEnrollmentGUIDRe matches a standard enrollment GUID (8-4-4-4-12 hex). The matched subkey name becomes an argument to deviceenroller
248+
// while orbit runs as SYSTEM, so we validate its shape before using it, even though writing the Enrollments key already requires admin.
249+
var windowsEnrollmentGUIDRe = regexp.MustCompile(`^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$`)
250+
251+
// fleetMDMEnrollmentGUID returns the enrollment GUID of the active Fleet Windows MDM enrollment by scanning
252+
// HKLM\SOFTWARE\Microsoft\Enrollments for the subkey whose ProviderID is Fleet's and whose EnrollmentState is active. The subkey name is
253+
// the enrollment GUID that deviceenroller's /o argument expects.
254+
func fleetMDMEnrollmentGUID() (string, error) {
255+
const enrollmentsPath = `SOFTWARE\Microsoft\Enrollments`
256+
root, err := registry.OpenKey(registry.LOCAL_MACHINE, enrollmentsPath, registry.READ)
257+
if err != nil {
258+
return "", fmt.Errorf("open enrollments registry key: %w", err)
259+
}
260+
defer root.Close()
261+
262+
names, err := root.ReadSubKeyNames(-1)
263+
if err != nil {
264+
return "", fmt.Errorf("read enrollment subkeys: %w", err)
265+
}
266+
267+
// EnrollmentState == 1 is the active state observed for Fleet's MDM enrollment on tested Windows builds; the registry DWORD under
268+
// Enrollments is not authoritatively documented by Microsoft. The ProviderID == "Fleet" check in the loop below scopes the match to
269+
// Fleet's own enrollment, so this never selects an unrelated (e.g. Intune) enrollment that might use a different state value.
270+
const enrollmentStateActive = 1
271+
for _, name := range names {
272+
k, err := registry.OpenKey(registry.LOCAL_MACHINE, enrollmentsPath+`\`+name, registry.QUERY_VALUE)
273+
if err != nil {
274+
continue
275+
}
276+
providerID, _, providerErr := k.GetStringValue("ProviderID")
277+
state, _, stateErr := k.GetIntegerValue("EnrollmentState")
278+
k.Close()
279+
if providerErr == nil && stateErr == nil && providerID == syncml.DocProvisioningAppProviderID && state == enrollmentStateActive {
280+
// Don't hand a malformed subkey name to deviceenroller; skip it and keep looking for a well-formed enrollment GUID.
281+
if !windowsEnrollmentGUIDRe.MatchString(name) {
282+
continue
283+
}
284+
return name, nil
285+
}
286+
}
287+
return "", errors.New("no active Fleet MDM enrollment found in registry")
288+
}

‎orbit/pkg/update/notifications.go‎

Lines changed: 67 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,7 @@ type checkAssignedEnrollmentProfileFunc func(url string) error
3030
// It ensures only one renewal command is executed at any given time, and that
3131
// it doesn't re-execute the command until a certain amount of time has passed.
3232
type renewEnrollmentProfileConfigReceiver struct {
33-
// Frequency is the minimum amount of time that must pass between two
34-
// executions of the profile renewal command.
33+
// Frequency is the minimum amount of time that must pass between two executions of the profile renewal command.
3534
Frequency time.Duration
3635

3736
// for tests, to be able to mock command execution. If nil, will use
@@ -272,6 +271,72 @@ func (w *windowsMDMEnrollmentConfigReceiver) attemptUnenrollment(actionLabel str
272271
}
273272
}
274273

274+
// execSyncFunc starts an on-demand Windows MDM (OMA-DM) session with the Fleet server. Indirected so tests can mock it; if nil the receiver
275+
// uses TriggerWindowsMDMSync.
276+
type execSyncFunc func() error
277+
278+
// windowsMDMSyncConfigReceiver reacts to the server's WindowsMDMSyncRequest notification by starting an on-demand OMA-DM session, so queued
279+
// Windows MDM commands are delivered without waiting for the device's next scheduled poll. This is what lets the server relax the
280+
// aggressive Windows MDM poll while keeping command latency low.
281+
type windowsMDMSyncConfigReceiver struct {
282+
// Frequency is the minimum amount of time that must pass between two on-demand sync attempts, so a
283+
// notification that lingers for a few config polls (before the server observes the command as acked) does
284+
// not trigger back-to-back sessions.
285+
Frequency time.Duration
286+
287+
// for tests, to mock the sync trigger. If nil, uses TriggerWindowsMDMSync.
288+
execSyncFn execSyncFunc
289+
290+
// Held for the duration of the async sync goroutine so only one sync runs at a time; also protects lastRun.
291+
mu sync.Mutex
292+
lastRun time.Time
293+
}
294+
295+
func ApplyWindowsMDMSyncFetcherMiddleware(frequency time.Duration) fleet.OrbitConfigReceiver {
296+
return &windowsMDMSyncConfigReceiver{Frequency: frequency}
297+
}
298+
299+
// Run starts an on-demand Windows MDM sync when the server sets WindowsMDMSyncRequest, so queued commands are delivered promptly even when
300+
// the device's OMA-DM poll schedule has been relaxed. It returns immediately; the sync itself runs in the background (see attemptSync).
301+
func (w *windowsMDMSyncConfigReceiver) Run(cfg *fleet.OrbitConfig) error {
302+
if cfg.Notifications.WindowsMDMSyncRequest {
303+
w.attemptSync()
304+
}
305+
return nil
306+
}
307+
308+
func (w *windowsMDMSyncConfigReceiver) attemptSync() {
309+
// TryLock keeps a single sync in flight: if one is already running, drop this attempt instead of piling up sessions.
310+
if !w.mu.TryLock() {
311+
return
312+
}
313+
314+
// do not attempt a sync if the last run is not at least Frequency ago.
315+
if time.Since(w.lastRun) <= w.Frequency {
316+
log.Debug().Msg("skipped on-demand Windows MDM sync, last run was too recent")
317+
w.mu.Unlock()
318+
return
319+
}
320+
321+
fn := w.execSyncFn
322+
if fn == nil {
323+
fn = TriggerWindowsMDMSync
324+
}
325+
326+
// Run the sync in the background so deviceenroller latency never gates the config-receiver loop
327+
go func() {
328+
defer w.mu.Unlock()
329+
if err := fn(); err != nil {
330+
// lastRun is intentionally not updated on failure, so the next config poll retries while the command is still queued (matches the
331+
// enrollment receiver's behavior).
332+
log.Info().Err(err).Msg("triggering on-demand Windows MDM sync failed")
333+
return
334+
}
335+
w.lastRun = time.Now()
336+
log.Info().Msg("triggered on-demand Windows MDM sync")
337+
}()
338+
}
339+
275340
type runScriptsConfigReceiver struct {
276341
// ScriptsExecutionEnabled indicates if this agent allows scripts execution.
277342
// If it doesn't, scripts are not executed, but a response is returned to the

‎orbit/pkg/update/notifications_test.go‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -819,3 +819,103 @@ func TestBitlockerOperations(t *testing.T) {
819819
})
820820

821821
}
822+
823+
func TestWindowsMDMSync(t *testing.T) {
824+
var logBuf bytes.Buffer
825+
oldLog := log.Logger
826+
log.Logger = log.Output(&logBuf)
827+
t.Cleanup(func() { log.Logger = oldLog })
828+
829+
syncCfg := func(req bool) *fleet.OrbitConfig {
830+
return &fleet.OrbitConfig{Notifications: fleet.OrbitConfigNotifications{WindowsMDMSyncRequest: req}}
831+
}
832+
833+
// newCounting builds a receiver whose sync increments calls and returns err: the common shape for most subtests below.
834+
newCounting := func(freq time.Duration, err error) (*windowsMDMSyncConfigReceiver, *atomic.Int32) {
835+
var calls atomic.Int32
836+
r := &windowsMDMSyncConfigReceiver{Frequency: freq, execSyncFn: func() error { calls.Add(1); return err }}
837+
return r, &calls
838+
}
839+
840+
// The sync runs in a background goroutine that holds w.mu until it finishes. waitIdle blocks until that goroutine has released the
841+
// lock, so afterwards the test can read the call counter, lastRun, and the shared log buffer without racing the goroutine's writes.
842+
// Subtests must stay sequential (no t.Parallel): they share logBuf and the global log.Logger.
843+
waitIdle := func(t *testing.T, r *windowsMDMSyncConfigReceiver) {
844+
t.Helper()
845+
require.Eventually(t, func() bool {
846+
if r.mu.TryLock() {
847+
r.mu.Unlock()
848+
return true
849+
}
850+
return false
851+
}, 2*time.Second, time.Millisecond)
852+
}
853+
854+
// runSync delivers cfg and blocks until any spawned sync goroutine has finished.
855+
runSync := func(t *testing.T, r *windowsMDMSyncConfigReceiver, req bool) {
856+
t.Helper()
857+
require.NoError(t, r.Run(syncCfg(req)))
858+
waitIdle(t, r)
859+
}
860+
861+
t.Run("no sync request does not trigger", func(t *testing.T) {
862+
logBuf.Reset()
863+
r, calls := newCounting(time.Hour, nil)
864+
runSync(t, r, false)
865+
require.Equal(t, int32(0), calls.Load())
866+
})
867+
868+
t.Run("sync request triggers once and records the run", func(t *testing.T) {
869+
logBuf.Reset()
870+
r, calls := newCounting(time.Hour, nil)
871+
runSync(t, r, true)
872+
require.Equal(t, int32(1), calls.Load())
873+
require.False(t, r.lastRun.IsZero(), "a successful sync must record lastRun")
874+
})
875+
876+
t.Run("second run within frequency is throttled", func(t *testing.T) {
877+
logBuf.Reset()
878+
r, calls := newCounting(time.Hour, nil)
879+
runSync(t, r, true)
880+
runSync(t, r, true)
881+
require.Equal(t, int32(1), calls.Load(), "second run within Frequency should be throttled")
882+
})
883+
884+
t.Run("not throttled once frequency elapsed", func(t *testing.T) {
885+
logBuf.Reset()
886+
r, calls := newCounting(0, nil)
887+
runSync(t, r, true)
888+
time.Sleep(time.Millisecond)
889+
runSync(t, r, true)
890+
require.Equal(t, int32(2), calls.Load())
891+
})
892+
893+
t.Run("sync already in flight is dropped", func(t *testing.T) {
894+
logBuf.Reset()
895+
var calls atomic.Int32
896+
release, started := make(chan struct{}), make(chan struct{})
897+
r := &windowsMDMSyncConfigReceiver{Frequency: 0, execSyncFn: func() error {
898+
calls.Add(1)
899+
close(started)
900+
<-release // hold w.mu so a concurrent Run observes TryLock failing
901+
return nil
902+
}}
903+
require.NoError(t, r.Run(syncCfg(true))) // returns immediately; the sync goroutine now holds w.mu
904+
<-started
905+
require.NoError(t, r.Run(syncCfg(true))) // a sync is in flight, so this attempt must be dropped, not queued
906+
require.Equal(t, int32(1), calls.Load(), "a second sync must not start while one is in flight")
907+
close(release)
908+
waitIdle(t, r)
909+
require.Equal(t, int32(1), calls.Load())
910+
})
911+
912+
t.Run("failure does not set lastRun and retries on next run", func(t *testing.T) {
913+
logBuf.Reset()
914+
r, calls := newCounting(time.Hour, io.ErrUnexpectedEOF)
915+
runSync(t, r, true)
916+
runSync(t, r, true)
917+
require.Equal(t, int32(2), calls.Load(), "failed sync should not be throttled on the next run")
918+
require.True(t, r.lastRun.IsZero(), "lastRun must remain unset after failures")
919+
require.Contains(t, logBuf.String(), "triggering on-demand Windows MDM sync failed")
920+
})
921+
}

0 commit comments

Comments
 (0)