Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions coordinator/mdm/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package mdm

import (
"crypto/tls"
"errors"
"log/slog"
"net/http"
"strings"
"sync"
"time"
)

// Client talks to the MicroMDM API.
type Client struct {
baseURL string
apiKey string
client *http.Client
logger *slog.Logger
// Per-UDID exclusive waiters retain the exact issued CommandUUID. A late
// response from an older attempt can never satisfy a newer waiter for the
// same device.
waitMu sync.Mutex
secInfoWaiters map[string]securityInfoWaiter
attestWaiters map[string]deviceAttestationWaiter
// Callback for MDA certs that arrive after the initial wait times out.
onMDA OnMDACallback
// Callback for SecurityInfo responses that arrive after the waiter timed out.
onLateSecInfo OnLateSecurityInfoCallback

// outstanding tracks command UUIDs the coordinator has issued but not yet
// matched to a response. The webhook only honors a response whose
// CommandUUID is here — this is what makes the (unauthenticated) MicroMDM
// callback safe: a caller can only ANSWER a command we actually issued, it
// can never volunteer an unsolicited "SIP=true" to forge a trust upgrade.
// Keyed by command UUID (a random, non-public identifier).
outstandingMu sync.Mutex
outstanding map[string]outstandingCommand
}

// NewClient creates an MDM client.
func NewClient(baseURL, apiKey string, logger *slog.Logger) *Client {
httpClient := &http.Client{
Timeout: 10 * time.Second,
}
// When talking to localhost MDM, skip TLS verification since the cert
// is issued for the public domain, not localhost/127.0.0.1.
if strings.Contains(baseURL, "localhost") || strings.Contains(baseURL, "127.0.0.1") {
httpClient.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
return &Client{
baseURL: baseURL,
apiKey: apiKey,
client: httpClient,
logger: logger,
secInfoWaiters: make(map[string]securityInfoWaiter),
attestWaiters: make(map[string]deviceAttestationWaiter),
outstanding: make(map[string]outstandingCommand),
}
}

// ErrWaiterAlreadyRegistered is returned when command ownership for a UDID is
// already held by another live attempt. Overwriting a waiter could route a
// response to the wrong verification job.
var ErrWaiterAlreadyRegistered = errors.New("mdm waiter already registered")

// OnMDACallback is called for a solicited DevicePropertiesAttestation response
// with no active exact waiter. The recipient must revalidate current connection
// and command ownership before applying the DER-encoded Apple cert chain.
type OnMDACallback func(udid, commandUUID string, certChain [][]byte)

// OnLateSecurityInfoCallback is called when a solicited SecurityInfo response
// arrives after its exact waiter has departed. The recipient must revalidate
// current connection and command ownership before applying it.
type OnLateSecurityInfoCallback func(
udid, commandUUID string,
info *SecurityInfoResponse,
)

// SetOnMDA registers a callback for late-arriving MDA attestation certs.
func (c *Client) SetOnMDA(fn OnMDACallback) {
c.onMDA = fn
}

// SetOnLateSecurityInfo registers a callback for SecurityInfo responses that
// arrive after the synchronous waiter has timed out. This enables the
// coordinator to retroactively upgrade providers when APN delivery is slow.
func (c *Client) SetOnLateSecurityInfo(fn OnLateSecurityInfoCallback) {
c.onLateSecInfo = fn
}
40 changes: 40 additions & 0 deletions coordinator/mdm/command_policy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package mdm

import (
"fmt"
)

// readOnlyMDMRequestTypes is the EXHAUSTIVE allowlist of MDM command request
// types the coordinator is permitted to send to a provider's Mac. Both are pure
// queries — they read security posture and never mutate the device:
//
// SecurityInfo → SIP / Secure Boot / FileVault status
// DeviceInformation → DevicePropertiesAttestation (Apple-signed cert chain)
//
// Every command that could act ON a provider's machine — DeviceLock,
// EraseDevice, RestartDevice, ShutDownDevice, InstallProfile, RemoveProfile,
// InstallApplication, ClearPasscode, EnableRemoteDesktop, ScheduleOSUpdate, … —
// is intentionally absent. Enrolling a provider grants the coordinator
// read-only visibility into hardware trust, NEVER control. assertReadOnlyCommand
// is the single chokepoint that enforces this: a future code path (or a
// compromised coordinator) that tries to issue a mutating command fails closed
// here instead of reaching the device. To add a command type, it must be a
// read-only query AND added here in review.
var readOnlyMDMRequestTypes = map[string]struct{}{
"SecurityInfo": {},
"DeviceInformation": {},
}

// ErrMutatingCommandBlocked is returned when something attempts to send an MDM
// command that is not on the read-only allowlist.
var ErrMutatingCommandBlocked = fmt.Errorf("mdm: refusing to send non-read-only command (provider machines are read-only)")

// assertReadOnlyCommand fails closed unless requestType is a known read-only
// query. This is the guarantee that the coordinator can never "do something" to
// a provider's Mac via MDM.
func assertReadOnlyCommand(requestType string) error {
if _, ok := readOnlyMDMRequestTypes[requestType]; !ok {
return fmt.Errorf("%w: %q", ErrMutatingCommandBlocked, requestType)
}
return nil
}
58 changes: 58 additions & 0 deletions coordinator/mdm/command_tracking.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package mdm

import (
"time"
)

// outstandingCommand records a command UUID the coordinator issued, so the
// webhook can verify an inbound response was solicited.
type outstandingCommand struct {
udid string
issuedAt time.Time
}

// outstandingCommandTTL bounds how long an issued command UUID stays valid for
// matching a webhook response. It must comfortably exceed the worst-case APN /
// Power Nap delivery delay (a sleeping Mac wakes on roughly a ~15-minute Power
// Nap cadence — see the late-SecurityInfo callback in cmd/coordinator/provider_trust.go),
// otherwise the UUID expires before a genuine SecurityInfo response arrives,
// consumeCommand drops it as stale, and the self_signed→hardware recovery path
// never fires. 30 minutes covers that delay while still bounding the forge
// window if a (random, localhost-only) UUID ever leaked.
const outstandingCommandTTL = 30 * time.Minute

// trackCommand records an issued command UUID so the webhook can confirm a
// later response was solicited. Prunes expired entries opportunistically.
func (c *Client) trackCommand(commandUUID, udid string, now time.Time) {
if commandUUID == "" {
return
}
c.outstandingMu.Lock()
defer c.outstandingMu.Unlock()
for id, cmd := range c.outstanding {
if now.Sub(cmd.issuedAt) > outstandingCommandTTL {
delete(c.outstanding, id)
}
}
c.outstanding[commandUUID] = outstandingCommand{udid: udid, issuedAt: now}
}

// consumeCommand checks whether commandUUID corresponds to a command the
// coordinator issued (and has not yet expired), removing it (one-shot). It
// returns the UDID the command was sent to and whether the match succeeded.
func (c *Client) consumeCommand(commandUUID string, now time.Time) (string, bool) {
if commandUUID == "" {
return "", false
}
c.outstandingMu.Lock()
defer c.outstandingMu.Unlock()
cmd, ok := c.outstanding[commandUUID]
if !ok {
return "", false
}
delete(c.outstanding, commandUUID)
if now.Sub(cmd.issuedAt) > outstandingCommandTTL {
return "", false
}
return cmd.udid, true
}
147 changes: 147 additions & 0 deletions coordinator/mdm/commands.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
package mdm

import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"

"github.com/google/uuid"
)

func (c *Client) sendSecurityInfoCommand(
ctx context.Context,
udid string,
bindCommand func(string) bool,
) (string, error) {
const requestType = "SecurityInfo"
if err := assertReadOnlyCommand(requestType); err != nil {
return "", err
}
body, _ := json.Marshal(map[string]string{
"udid": udid, "request_type": requestType,
})
req, err := http.NewRequestWithContext(
ctx, http.MethodPost, c.baseURL+"/v1/commands", bytes.NewReader(body),
)
if err != nil {
return "", err
}
req.SetBasicAuth("micromdm", c.apiKey)
req.Header.Set("Content-Type", "application/json")
resp, err := c.client.Do(req)
if err != nil {
return "", fmt.Errorf("mdm send command failed: %w", err)
}
defer resp.Body.Close()
var result struct {
Payload struct {
CommandUUID string `json:"command_uuid"`
} `json:"payload"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", fmt.Errorf("mdm command response decode failed: %w", err)
}
if result.Payload.CommandUUID == "" {
return "", errors.New("mdm command response missing command UUID")
}
c.trackCommand(result.Payload.CommandUUID, udid, time.Now())
if !bindCommand(result.Payload.CommandUUID) {
c.consumeCommand(result.Payload.CommandUUID, time.Now())
return "", errors.New("mdm SecurityInfo waiter ownership changed before command issue")
}
// Structured /v1/commands already sends exactly one MicroMDM APNs push.
return result.Payload.CommandUUID, nil
}

// sendDeviceAttestationWithNonce queues a raw DeviceInformation plist so Apple
// binds DeviceAttestationNonce into the certificate's FreshnessCode. The caller
// must bind its exclusive waiter before the command is published.
func (c *Client) sendDeviceAttestationWithNonce(
ctx context.Context,
udid, nonce string,
bindCommand func(string) bool,
) (string, error) {
// DevicePropertiesAttestation is requested via a DeviceInformation command.
if err := assertReadOnlyCommand("DeviceInformation"); err != nil {
return "", err
}
cmdUUID := uuid.New().String()
if !bindCommand(cmdUUID) {
return "", errors.New("mdm device attestation waiter ownership changed before command issue")
}
c.trackCommand(cmdUUID, udid, time.Now())

// Build nonce XML if provided
nonceXML := ""
if nonce != "" {
nonceXML = fmt.Sprintf(`
<key>DeviceAttestationNonce</key>
<data>%s</data>`, nonce)
}

plist := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Command</key>
<dict>
<key>RequestType</key>
<string>DeviceInformation</string>
<key>Queries</key>
<array>
<string>DevicePropertiesAttestation</string>
</array>%s
</dict>
<key>CommandUUID</key>
<string>%s</string>
</dict>
</plist>`, nonceXML, cmdUUID)

req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/v1/commands/"+udid, bytes.NewReader([]byte(plist)))
if err != nil {
c.consumeCommand(cmdUUID, time.Now())
return "", err
}
req.SetBasicAuth("micromdm", c.apiKey)
req.Header.Set("Content-Type", "application/xml")

resp, err := c.client.Do(req)
if err != nil {
c.consumeCommand(cmdUUID, time.Now())
return "", fmt.Errorf("mdm send DeviceInformation with nonce failed: %w", err)
}
defer resp.Body.Close()

if resp.StatusCode >= 300 {
c.consumeCommand(cmdUUID, time.Now())
respBody, _ := io.ReadAll(resp.Body)
return "", fmt.Errorf("mdm raw command failed (status %d): %s", resp.StatusCode, string(respBody))
}

// Push to trigger device check-in (best-effort; command is already queued).
// The raw POST /v1/commands/{udid} endpoint does NOT auto-push (unlike the
// structured /v1/commands), so the explicit push is required here.
c.pushDevice(ctx, udid)

return cmdUUID, nil
}

// pushDevice sends a best-effort APNs push to a device via MicroMDM to trigger
// an immediate check-in so a freshly-queued command is pulled promptly rather
// than at the next idle wake. Errors are intentionally ignored: the command is
// already enqueued, and the push is only a latency optimization.
func (c *Client) pushDevice(ctx context.Context, udid string) {
pushReq, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+"/push/"+udid, nil)
if err != nil {
return
}
pushReq.SetBasicAuth("micromdm", c.apiKey)
if resp, err := c.client.Do(pushReq); err == nil {
_ = resp.Body.Close()
}
}
Loading
Loading