fleet/server/mdm/apple/util.go
Magnus Jensen 3371b48373
accept 89 error on RemoveProfile as valid (#43172)
<!-- Add the related story/sub-task/bug number, like Resolves #123, or
remove if NA -->
**Related issue:** Resolves #42103 

# 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] Input data is properly validated, `SELECT *` is avoided, SQL
injection is prevented (using placeholders for values in statements), JS
inline code is prevented especially for url redirects, and untrusted
data interpolated into shell scripts/commands is validated against shell
metacharacters.
- [x] Timeouts are implemented and retries are limited to avoid infinite
loops
- [x] If paths of existing endpoints are modified without backwards
compatibility, checked the frontend/CLI for any necessary changes

## Testing

- [x] Added/updated automated tests
- [x] QA'd all new/changed functionality manually

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Improved profile removal handling: Fleet now successfully removes host
OS setting entries even when the removal command encounters a "profile
not found" error from the device.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-04-07 15:23:37 -05:00

143 lines
4.2 KiB
Go

package apple_mdm
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/pem"
"fmt"
"math"
"net/url"
"path"
"strings"
"github.com/fleetdm/fleet/v4/server/fleet"
"github.com/fleetdm/fleet/v4/server/mdm/nanomdm/mdm"
)
// Note Apple rejects CSRs if the key size is not 2048.
const rsaKeySize = 2048
// newPrivateKey creates an RSA private key
func newPrivateKey() (*rsa.PrivateKey, error) {
return rsa.GenerateKey(rand.Reader, rsaKeySize)
}
func EncodeCertRequestPEM(cert *x509.CertificateRequest) []byte {
pemBlock := &pem.Block{
Type: "CERTIFICATE REQUEST",
Headers: nil,
Bytes: cert.Raw,
}
return pem.EncodeToMemory(pemBlock)
}
// GenerateRandomPin generates a `length`-digit random PIN number
//
// The implementation details for converting the randomness to a PIN
// have been mostly taken from https://github.com/pquerna/otp
func GenerateRandomPin(length int) (string, error) {
buf := make([]byte, 16)
_, err := rand.Read(buf)
if err != nil {
return "", err
}
m := sha256.New()
m.Write(buf)
sum := m.Sum(nil)
offset := sum[len(sum)-1] & 0xf
value := int64(((int(sum[offset]) & 0x7f) << 24) |
((int(sum[offset+1] & 0xff)) << 16) |
((int(sum[offset+2] & 0xff)) << 8) |
(int(sum[offset+3]) & 0xff))
v := int32(value % int64(math.Pow10(length))) //nolint:gosec // dismiss G115
f := fmt.Sprintf("%%0%dd", length)
return fmt.Sprintf(f, v), nil
}
// FmtErrorChain formats Command error message for macOS MDM v1
func FmtErrorChain(chain []mdm.ErrorChain) string {
var sb strings.Builder
for _, mdmErr := range chain {
desc := mdmErr.USEnglishDescription
if desc == "" {
desc = mdmErr.LocalizedDescription
}
sb.WriteString(fmt.Sprintf("%s (%d): %s\n", mdmErr.ErrorDomain, mdmErr.ErrorCode, desc))
}
return sb.String()
}
// IsRecoveryLockPasswordMismatchError checks if the error chain indicates that the
// recovery lock password provided does not match the one on the device. This is a
// terminal error that should not be retried automatically.
//
// Known error signatures:
// - MDMClientError (70): "Existing recovery lock password not provided"
// - ROSLockoutServiceDaemonErrorDomain (8): "The provided recovery password failed to validate."
func IsRecoveryLockPasswordMismatchError(chain []mdm.ErrorChain) bool {
for _, e := range chain {
// MDMClientError 70: "Existing recovery lock password not provided"
if e.ErrorDomain == "MDMClientError" && e.ErrorCode == 70 {
return true
}
// ROSLockoutServiceDaemonErrorDomain 8: "The provided recovery password failed to validate"
if e.ErrorDomain == "ROSLockoutServiceDaemonErrorDomain" && e.ErrorCode == 8 {
return true
}
}
return false
}
// IsProfileNotFoundError checks if the error chain indicates that a profile
// was not found on the device. When this error occurs during a RemoveProfile
// command, it means the profile is already absent — the desired outcome.
//
// Known error signature:
// - MDMClientError (89): "Profile with identifier '...' not found."
func IsProfileNotFoundError(chain []mdm.ErrorChain) bool {
for _, e := range chain {
if e.ErrorDomain == "MDMClientError" && e.ErrorCode == 89 {
return true
}
}
return false
}
// FmtDDMError formats a DDM error message
func FmtDDMError(reasons []fleet.MDMAppleDDMStatusErrorReason) string {
var errMsg strings.Builder
for _, r := range reasons {
errMsg.WriteString(fmt.Sprintf("%s: %s %+v\n", r.Code, r.Description, r.Details))
}
return errMsg.String()
}
func EnrollURL(token string, appConfig *fleet.AppConfig) (string, error) {
enrollURL, err := url.Parse(appConfig.MDMUrl())
if err != nil {
return "", err
}
enrollURL.Path = path.Join(enrollURL.Path, EnrollPath)
q := enrollURL.Query()
q.Set("token", token)
enrollURL.RawQuery = q.Encode()
return enrollURL.String(), nil
}
// IsLessThanVersion returns true if the current version is less than the target version.
// If either version is invalid, an error is returned.
func IsLessThanVersion(current string, target string) (bool, error) {
cv, err := fleet.VersionToSemverVersion(current)
if err != nil {
return false, fmt.Errorf("invalid current version: %w", err)
}
tv, err := fleet.VersionToSemverVersion(target)
if err != nil {
return false, fmt.Errorf("invalid target version: %w", err)
}
return cv.LessThan(tv), nil
}