-
Notifications
You must be signed in to change notification settings - Fork 843
Expand file tree
/
Copy pathapple_mdm.go
More file actions
8093 lines (7253 loc) · 277 KB
/
apple_mdm.go
File metadata and controls
8093 lines (7253 loc) · 277 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package mysql
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/md5" // nolint:gosec // used only to hash for efficient comparisons
"crypto/rand"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"math"
"os"
"slices"
"strings"
"time"
"github.com/fleetdm/fleet/v4/server"
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
"github.com/fleetdm/fleet/v4/server/fleet"
fleetmdm "github.com/fleetdm/fleet/v4/server/mdm"
apple_mdm "github.com/fleetdm/fleet/v4/server/mdm/apple"
"github.com/fleetdm/fleet/v4/server/mdm/apple/mobileconfig"
"github.com/fleetdm/fleet/v4/server/mdm/nanodep/godep"
"github.com/fleetdm/fleet/v4/server/mdm/nanomdm/mdm"
common_mysql "github.com/fleetdm/fleet/v4/server/platform/mysql"
"github.com/fleetdm/fleet/v4/server/ptr"
"github.com/google/go-cmp/cmp"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// addHostMDMCommandsBatchSize is the number of host MDM commands to add in a single batch. This is a var so that it can be modified in tests.
var addHostMDMCommandsBatchSize = 10000
func isAppleHostConnectedToFleetMDM(ctx context.Context, q sqlx.QueryerContext, h *fleet.Host) (bool, error) {
var uuid string
// safe to use with interpolation rather than prepared statements because we're using a numeric
// ID here
err := sqlx.GetContext(ctx, q, &uuid, fmt.Sprintf(`
SELECT ne.id
FROM nano_enrollments ne
JOIN hosts h ON h.uuid = ne.id
JOIN host_mdm hm ON hm.host_id = h.id
WHERE h.id = %d
AND ne.enabled = 1
AND ne.type IN ('Device', 'User Enrollment (Device)')
AND hm.enrolled = 1 LIMIT 1
`, h.ID))
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
return false, err
}
return true, nil
}
// Checks scopes against existing profiles across the entire DB to ensure there are no conflicts
// where an existing profile with the same identifier has a different scope than the incoming
// profile. If we don't do this we must implement some sort of "move" semantics to allow for scope
// changes when a host switches teams or when a profile is updated.
func (ds *Datastore) verifyAppleConfigProfileScopesDoNotConflict(ctx context.Context, tx sqlx.ExtContext, cps []*fleet.MDMAppleConfigProfile) error {
if len(cps) == 0 {
return nil
}
incomingProfileIdentifiers := make([]string, 0, len(cps))
for i := 0; i < len(cps); i++ {
incomingProfileIdentifiers = append(incomingProfileIdentifiers, cps[i].Identifier)
}
stmt := `
SELECT
profile_uuid,
profile_id,
team_id,
name,
scope,
identifier,
mobileconfig,
created_at,
uploaded_at,
checksum
FROM
mdm_apple_configuration_profiles
WHERE
identifier IN (?)
`
stmt, args, err := sqlx.In(stmt, incomingProfileIdentifiers)
if err != nil {
return ctxerr.Wrap(ctx, err, "sqlx.In verifyAppleConfigProfileScopesDoNotConflict")
}
var existingProfiles []*fleet.MDMAppleConfigProfile
if err = sqlx.SelectContext(ctx, tx, &existingProfiles, stmt, args...); err != nil {
return ctxerr.Wrap(ctx, err, "querying existing apple config profiles by identifier")
}
existingProfilesByIdentifier := make(map[string][]*fleet.MDMAppleConfigProfile)
for _, existingProfile := range existingProfiles {
existingProfilesByIdentifier[existingProfile.Identifier] = append(existingProfilesByIdentifier[existingProfile.Identifier], existingProfile)
}
for _, cp := range cps {
existingProfiles := existingProfilesByIdentifier[cp.Identifier]
isEdit := false
scopeImplicitlyChanged := false
var conflictingProfile *fleet.MDMAppleConfigProfile
// We have to look through all profiles with the same identifier(which is potentially number
// of teams + 1, for no team) in most cases but even in the case of a large number of teams
for _, existingProfile := range existingProfiles {
var incomingProfileTeamID, existingProfileTeamID uint
if existingProfile.TeamID != nil {
existingProfileTeamID = *existingProfile.TeamID
}
if cp.TeamID != nil {
incomingProfileTeamID = *cp.TeamID
}
if incomingProfileTeamID == existingProfileTeamID {
isEdit = true
}
if existingProfile.Scope != cp.Scope {
if cp.Checksum == nil {
checksum := md5.Sum(cp.Mobileconfig) // nolint:gosec // Dismiss G401, we are not using this for secret/security reasons
cp.Checksum = checksum[:]
}
// If the existing profile is marked as system scope, the new profile is user scope
// but the checksums match, this is a profile that existed prior to User Channel
// support being added and is unmodified, so allow the existing behavior to continue
if existingProfile.Scope == fleet.PayloadScopeSystem && cp.Scope == fleet.PayloadScopeUser && bytes.Equal(existingProfile.Checksum, cp.Checksum) {
cp.Scope = existingProfile.Scope
conflictingProfile = nil
break
}
parsedConflictingMobileConfig, err := existingProfile.Mobileconfig.ParseConfigProfile()
if err != nil {
ds.logger.DebugContext(ctx, "error parsing existing profile mobileconfig while checking for scope conflicts",
"profile_uuid", existingProfile.ProfileUUID,
"err", err,
)
}
// The existing profile has a different scope in the XML than in Fleet's DB, meaning
// it existed prior to User channel profiles support being added and this is an
// implicit change the user may not be aware of.
if err == nil && fleet.PayloadScope(parsedConflictingMobileConfig.PayloadScope) != existingProfile.Scope {
scopeImplicitlyChanged = true
}
conflictingProfile = existingProfile
}
}
if conflictingProfile != nil {
var errorMessage string
// If you change this URL you may need to change the frontend code as well which adds a
// nicely formatted link to the error message.
const learnMoreSameScope = "https://fleetdm.com/learn-more-about/macos-configuration-profiles-same-scope"
if isEdit {
if scopeImplicitlyChanged {
errorMessage = fmt.Sprintf(`Couldn't edit configuration profile (%s) because it was previously delivered to some hosts on the device channel. Change "PayloadScope" to "System" to keep existing behavior. Alternatively, if you want this profile to be delivered on the user channel, please specify a new identifier for this profile and delete the old profile. Learn more: %s`, cp.Identifier, learnMoreSameScope)
} else {
errorMessage = fmt.Sprintf(`Couldn't edit configuration profile (%s) because the profile's "PayloadScope" has changed. To change the “PayloadScope” of an existing profile, add a new profile with a new identifier with the desired scope and delete the old profile. Learn more: %s`, cp.Identifier, learnMoreSameScope)
}
} else {
errorMessage = fmt.Sprintf(`Couldn't add configuration profile. This profile has the same "PayloadIdentifier" but a different "PayloadScope" as another profile in a separate team. Learn more: %s`, learnMoreSameScope)
}
return &fleet.BadRequestError{Message: errorMessage}
}
}
return nil
}
func (ds *Datastore) NewMDMAppleConfigProfile(ctx context.Context, cp fleet.MDMAppleConfigProfile, usesFleetVars []fleet.FleetVarName) (*fleet.MDMAppleConfigProfile, error) {
profUUID := fleet.MDMAppleProfileUUIDPrefix + uuid.New().String()
// Set default scope if not provided
if cp.Scope == "" {
cp.Scope = fleet.PayloadScopeSystem
}
stmt := `
INSERT INTO
mdm_apple_configuration_profiles (profile_uuid, team_id, identifier, name, scope, mobileconfig, checksum, uploaded_at, secrets_updated_at)
(SELECT ?, ?, ?, ?, ?, ?, UNHEX(MD5(?)), CURRENT_TIMESTAMP(), ? FROM DUAL WHERE
NOT EXISTS (
SELECT 1 FROM mdm_windows_configuration_profiles WHERE name = ? AND team_id = ?
) AND NOT EXISTS (
SELECT 1 FROM mdm_apple_declarations WHERE name = ? AND team_id = ?
) AND NOT EXISTS (
SELECT 1 FROM mdm_android_configuration_profiles WHERE name = ? AND team_id = ?
)
)`
var teamID uint
if cp.TeamID != nil {
teamID = *cp.TeamID
}
var profileID int64
err := ds.withTx(ctx, func(tx sqlx.ExtContext) error {
err := ds.verifyAppleConfigProfileScopesDoNotConflict(ctx, tx, []*fleet.MDMAppleConfigProfile{&cp})
if err != nil {
return err
}
res, err := tx.ExecContext(ctx, stmt,
profUUID, teamID, cp.Identifier, cp.Name, cp.Scope, cp.Mobileconfig, cp.Mobileconfig, cp.SecretsUpdatedAt, cp.Name, teamID, cp.Name,
teamID, cp.Name, teamID)
if err != nil {
switch {
case IsDuplicate(err):
return ctxerr.Wrap(ctx, formatErrorDuplicateConfigProfile(err, &cp))
default:
return ctxerr.Wrap(ctx, err, "creating new apple mdm config profile")
}
}
aff, _ := res.RowsAffected()
if aff == 0 {
return &existsError{
ResourceType: "MDMAppleConfigProfile.PayloadDisplayName",
Identifier: cp.Name,
TeamID: cp.TeamID,
}
}
// record the ID as we want to return a fleet.Profile instance with it
// filled in.
profileID, _ = res.LastInsertId()
labels := make([]fleet.ConfigurationProfileLabel, 0, len(cp.LabelsIncludeAll)+len(cp.LabelsIncludeAny)+len(cp.LabelsExcludeAny))
for i := range cp.LabelsIncludeAll {
cp.LabelsIncludeAll[i].ProfileUUID = profUUID
cp.LabelsIncludeAll[i].Exclude = false
cp.LabelsIncludeAll[i].RequireAll = true
labels = append(labels, cp.LabelsIncludeAll[i])
}
for i := range cp.LabelsIncludeAny {
cp.LabelsIncludeAny[i].ProfileUUID = profUUID
cp.LabelsIncludeAny[i].Exclude = false
cp.LabelsIncludeAny[i].RequireAll = false
labels = append(labels, cp.LabelsIncludeAny[i])
}
for i := range cp.LabelsExcludeAny {
cp.LabelsExcludeAny[i].ProfileUUID = profUUID
cp.LabelsExcludeAny[i].Exclude = true
cp.LabelsExcludeAny[i].RequireAll = false
labels = append(labels, cp.LabelsExcludeAny[i])
}
var profWithoutLabels []string
if len(labels) == 0 {
profWithoutLabels = append(profWithoutLabels, profUUID)
}
if _, err := batchSetProfileLabelAssociationsDB(ctx, tx, labels, profWithoutLabels, "darwin"); err != nil {
return ctxerr.Wrap(ctx, err, "inserting darwin profile label associations")
}
if _, err := batchSetProfileVariableAssociationsDB(ctx, tx, []fleet.MDMProfileUUIDFleetVariables{
{ProfileUUID: profUUID, FleetVariables: usesFleetVars},
}, "darwin"); err != nil {
return ctxerr.Wrap(ctx, err, "inserting darwin profile variable associations")
}
return nil
})
if err != nil {
return nil, ctxerr.Wrap(ctx, err, "inserting profile and label associations")
}
return &fleet.MDMAppleConfigProfile{
ProfileUUID: profUUID,
ProfileID: uint(profileID), //nolint:gosec // dismiss G115
Identifier: cp.Identifier,
Name: cp.Name,
Scope: cp.Scope,
Mobileconfig: cp.Mobileconfig,
TeamID: cp.TeamID,
}, nil
}
func formatErrorDuplicateConfigProfile(err error, cp *fleet.MDMAppleConfigProfile) error {
switch {
case strings.Contains(err.Error(), "idx_mdm_apple_config_prof_team_identifier"):
return &existsError{
ResourceType: "MDMAppleConfigProfile.PayloadIdentifier",
Identifier: cp.Identifier,
TeamID: cp.TeamID,
}
case strings.Contains(err.Error(), "idx_mdm_apple_config_prof_team_name"):
return &existsError{
ResourceType: "MDMAppleConfigProfile.PayloadDisplayName",
Identifier: cp.Name,
TeamID: cp.TeamID,
}
default:
return err
}
}
func formatErrorDuplicateDeclaration(err error, decl *fleet.MDMAppleDeclaration) error {
switch {
case strings.Contains(err.Error(), "idx_mdm_apple_declaration_team_identifier"):
return &existsError{
ResourceType: "MDMAppleDeclaration.Identifier",
Identifier: decl.Identifier,
TeamID: decl.TeamID,
}
case strings.Contains(err.Error(), "idx_mdm_apple_declaration_team_name"):
return &existsError{
ResourceType: "MDMAppleDeclaration.Name",
Identifier: decl.Name,
TeamID: decl.TeamID,
}
default:
return err
}
}
func (ds *Datastore) ListMDMAppleConfigProfiles(ctx context.Context, teamID *uint) ([]*fleet.MDMAppleConfigProfile, error) {
stmt := `
SELECT
profile_uuid,
profile_id,
team_id,
name,
scope,
identifier,
mobileconfig,
created_at,
uploaded_at,
checksum
FROM
mdm_apple_configuration_profiles
WHERE
team_id=? AND identifier NOT IN (?)
ORDER BY name`
if teamID == nil {
teamID = ptr.Uint(0)
}
fleetIdentifiers := []string{}
for idf := range mobileconfig.FleetPayloadIdentifiers() {
fleetIdentifiers = append(fleetIdentifiers, idf)
}
stmt, args, err := sqlx.In(stmt, teamID, fleetIdentifiers)
if err != nil {
return nil, ctxerr.Wrap(ctx, err, "sqlx.In ListMDMAppleConfigProfiles")
}
var res []*fleet.MDMAppleConfigProfile
if err = sqlx.SelectContext(ctx, ds.reader(ctx), &res, stmt, args...); err != nil {
return nil, err
}
return res, nil
}
func (ds *Datastore) GetMDMAppleConfigProfileByDeprecatedID(ctx context.Context, profileID uint) (*fleet.MDMAppleConfigProfile, error) {
return ds.getMDMAppleConfigProfileByIDOrUUID(ctx, profileID, "")
}
func (ds *Datastore) GetMDMAppleConfigProfile(ctx context.Context, profileUUID string) (*fleet.MDMAppleConfigProfile, error) {
return ds.getMDMAppleConfigProfileByIDOrUUID(ctx, 0, profileUUID)
}
func (ds *Datastore) getMDMAppleConfigProfileByIDOrUUID(ctx context.Context, id uint, uuid string) (*fleet.MDMAppleConfigProfile, error) {
stmt := `
SELECT
profile_uuid,
profile_id,
team_id,
name,
scope,
identifier,
mobileconfig,
checksum,
created_at,
uploaded_at,
secrets_updated_at
FROM
mdm_apple_configuration_profiles
WHERE
`
var arg any
if uuid != "" {
arg = uuid
stmt += `profile_uuid = ?`
} else {
arg = id
stmt += `profile_id = ?`
}
var res fleet.MDMAppleConfigProfile
err := sqlx.GetContext(ctx, ds.reader(ctx), &res, stmt, arg)
if err != nil {
if err == sql.ErrNoRows {
if uuid != "" {
return nil, ctxerr.Wrap(ctx, notFound("MDMAppleConfigProfile").WithName(uuid))
}
return nil, ctxerr.Wrap(ctx, notFound("MDMAppleConfigProfile").WithID(id))
}
return nil, ctxerr.Wrap(ctx, err, "get mdm apple config profile")
}
// get the labels for that profile, except if the profile was loaded by the
// old (deprecated) endpoint.
if uuid != "" {
labels, err := ds.listProfileLabelsForProfiles(ctx, nil, []string{res.ProfileUUID}, nil, nil)
if err != nil {
return nil, err
}
for _, lbl := range labels {
switch {
case lbl.Exclude && lbl.RequireAll:
// this should never happen so log it for debugging
ds.logger.DebugContext(ctx, "unsupported profile label: cannot be both exclude and require all",
"profile_uuid", lbl.ProfileUUID,
"label_name", lbl.LabelName,
)
case lbl.Exclude && !lbl.RequireAll:
res.LabelsExcludeAny = append(res.LabelsExcludeAny, lbl)
case !lbl.Exclude && !lbl.RequireAll:
res.LabelsIncludeAny = append(res.LabelsIncludeAny, lbl)
default:
// default include all
res.LabelsIncludeAll = append(res.LabelsIncludeAll, lbl)
}
}
}
return &res, nil
}
func (ds *Datastore) GetMDMAppleDeclaration(ctx context.Context, declUUID string) (*fleet.MDMAppleDeclaration, error) {
stmt := `
SELECT
declaration_uuid,
team_id,
name,
identifier,
raw_json,
token,
created_at,
uploaded_at,
secrets_updated_at
FROM
mdm_apple_declarations
WHERE
declaration_uuid = ?`
var res fleet.MDMAppleDeclaration
err := sqlx.GetContext(ctx, ds.reader(ctx), &res, stmt, declUUID)
if err != nil {
if err == sql.ErrNoRows {
return nil, ctxerr.Wrap(ctx, notFound("MDMAppleDeclaration").WithName(declUUID))
}
return nil, ctxerr.Wrap(ctx, err, "get mdm apple declaration")
}
labels, err := ds.listProfileLabelsForProfiles(ctx, nil, nil, nil, []string{res.DeclarationUUID})
if err != nil {
return nil, err
}
for _, lbl := range labels {
switch {
case lbl.Exclude && lbl.RequireAll:
// this should never happen so log it for debugging
ds.logger.DebugContext(ctx, "unsupported profile label: cannot be both exclude and require all",
"profile_uuid", lbl.ProfileUUID,
"label_name", lbl.LabelName,
)
case lbl.Exclude && !lbl.RequireAll:
res.LabelsExcludeAny = append(res.LabelsExcludeAny, lbl)
case !lbl.Exclude && !lbl.RequireAll:
res.LabelsIncludeAny = append(res.LabelsIncludeAny, lbl)
default:
// default include all
res.LabelsIncludeAll = append(res.LabelsIncludeAll, lbl)
}
}
return &res, nil
}
func (ds *Datastore) DeleteMDMAppleConfigProfileByDeprecatedID(ctx context.Context, profileID uint) error {
return ds.withRetryTxx(ctx, func(tx sqlx.ExtContext) error {
return deleteMDMAppleConfigProfileByIDOrUUID(ctx, tx, profileID, "")
})
}
func (ds *Datastore) DeleteMDMAppleDeclaration(ctx context.Context, declUUID string) error {
return ds.withRetryTxx(ctx, func(tx sqlx.ExtContext) error {
return deleteMDMAppleDeclarationAndPostProcessing(ctx, tx, declUUID)
})
}
func deleteMDMAppleDeclarationAndPostProcessing(ctx context.Context, tx sqlx.ExtContext, declUUID string) error {
if err := deleteMDMAppleDeclaration(ctx, tx, declUUID); err != nil {
return err
}
// cancel any pending host installs immediately for this declaration
if err := cancelAppleHostInstallsForDeletedMDMDeclarations(ctx, tx, []string{declUUID}); err != nil {
return err
}
return nil
}
func (ds *Datastore) DeleteMDMAppleConfigProfile(ctx context.Context, profileUUID string) error {
return ds.withRetryTxx(ctx, func(tx sqlx.ExtContext) error {
if err := deleteMDMAppleConfigProfileByIDOrUUID(ctx, tx, 0, profileUUID); err != nil {
return err
}
// cancel any pending host installs immediately for this profile
if err := cancelAppleHostInstallsForDeletedMDMProfiles(ctx, tx, []string{profileUUID}); err != nil {
return err
}
return nil
})
}
func deleteMDMAppleConfigProfileByIDOrUUID(ctx context.Context, tx sqlx.ExtContext, id uint, uuid string) error {
var arg any
stmt := `DELETE FROM mdm_apple_configuration_profiles WHERE `
if uuid != "" {
arg = uuid
stmt += `profile_uuid = ?`
} else {
arg = id
stmt += `profile_id = ?`
}
res, err := tx.ExecContext(ctx, stmt, arg)
if err != nil {
return ctxerr.Wrap(ctx, err)
}
deleted, _ := res.RowsAffected()
if deleted != 1 {
if uuid != "" {
return ctxerr.Wrap(ctx, notFound("MDMAppleConfigProfile").WithName(uuid))
}
return ctxerr.Wrap(ctx, notFound("MDMAppleConfigProfile").WithID(id))
}
return nil
}
func cancelAppleHostInstallsForDeletedMDMProfiles(ctx context.Context, tx sqlx.ExtContext, profileUUIDs []string) error {
// For Apple profiles, we can safely delete the rows for hosts where status
// is NULL and operation type is install, but if the status is not NULL, the
// install command _may_ have been sent to the host, we need to change the
// operation to remove and set the status to NULL. As a precaution to avoid
// sending the Install command if possible at all, we deactivate the command
// in the nano queue if the status is Pending (that is, not NULL, but no sign
// that the host received it yet).
if len(profileUUIDs) == 0 {
return nil
}
const delStmt = `
DELETE FROM
host_mdm_apple_profiles
WHERE
profile_uuid IN (?) AND
status IS NULL AND
operation_type = ?`
stmt, args, err := sqlx.In(delStmt, profileUUIDs, fleet.MDMOperationTypeInstall)
if err != nil {
return ctxerr.Wrap(ctx, err, "building in statement")
}
if _, err := tx.ExecContext(ctx, stmt, args...); err != nil {
return ctxerr.Wrap(ctx, err, "deleting host_mdm_apple_profiles that have not been sent to host")
}
const deactivateNanoStmt = `
UPDATE
nano_enrollment_queue
JOIN nano_enrollments ne
ON nano_enrollment_queue.id = ne.id
JOIN host_mdm_apple_profiles hmap
ON hmap.command_uuid = nano_enrollment_queue.command_uuid AND
hmap.host_uuid = ne.device_id
SET
nano_enrollment_queue.active = 0
WHERE
hmap.profile_uuid IN (?) AND
hmap.status = ? AND
hmap.operation_type = ?`
stmt, args, err = sqlx.In(deactivateNanoStmt, profileUUIDs, fleet.MDMDeliveryPending, fleet.MDMOperationTypeInstall)
if err != nil {
return ctxerr.Wrap(ctx, err, "building in statement")
}
if _, err := tx.ExecContext(ctx, stmt, args...); err != nil {
return ctxerr.Wrap(ctx, err, "deactivating nano_enrollment_queue for commands that were pending send to host")
}
// we set the ignore_error flag if install status was "pending" or "failed"
// because the profile may _not_ have been delivered, so if the remove
// command fails, we don't want to show it.
const updStmt = `
UPDATE
host_mdm_apple_profiles
SET
operation_type = ?,
ignore_error = IF(status IN (?), 1, 0),
status = NULL
WHERE
profile_uuid IN (?) AND
status IS NOT NULL AND
operation_type = ?`
stmt, args, err = sqlx.In(updStmt, fleet.MDMOperationTypeRemove,
[]fleet.MDMDeliveryStatus{fleet.MDMDeliveryPending, fleet.MDMDeliveryFailed}, profileUUIDs, fleet.MDMOperationTypeInstall)
if err != nil {
return ctxerr.Wrap(ctx, err, "building in statement")
}
if _, err := tx.ExecContext(ctx, stmt, args...); err != nil {
return ctxerr.Wrap(ctx, err, "updating host_mdm_apple_profiles to pending remove")
}
return nil
}
func cancelAppleHostInstallsForDeletedMDMDeclarations(ctx context.Context, tx sqlx.ExtContext, declUUIDs []string) error {
// For Apple declarations, we can safely delete the rows for hosts where
// status is NULL and operation type is install, but if the status is not
// NULL, we need to change the operation to remove and set the status to NULL
// (i.e. Enforcing removal (pending)) so that on the next reconcile there is
// a DDM command issued to sync the host with the new declarative state
// (which will not include the deleted declaration(s) anymore).
if len(declUUIDs) == 0 {
return nil
}
const delStmt = `
DELETE FROM
host_mdm_apple_declarations
WHERE
declaration_uuid IN (?) AND
( status IS NULL OR status IN (?) ) AND
operation_type = ?`
stmt, args, err := sqlx.In(delStmt, declUUIDs, []fleet.MDMDeliveryStatus{fleet.MDMDeliveryPending, fleet.MDMDeliveryFailed}, fleet.MDMOperationTypeInstall)
if err != nil {
return ctxerr.Wrap(ctx, err, "building in statement")
}
if _, err := tx.ExecContext(ctx, stmt, args...); err != nil {
return ctxerr.Wrap(ctx, err, "deleting host_mdm_apple_declarations that have not been sent to host")
}
const updStmt = `
UPDATE
host_mdm_apple_declarations
SET
status = NULL,
operation_type = ?
WHERE
declaration_uuid IN (?) AND
status IS NOT NULL AND
operation_type = ?`
stmt, args, err = sqlx.In(updStmt, fleet.MDMOperationTypeRemove, declUUIDs, fleet.MDMOperationTypeInstall)
if err != nil {
return ctxerr.Wrap(ctx, err, "building in statement")
}
if _, err := tx.ExecContext(ctx, stmt, args...); err != nil {
return ctxerr.Wrap(ctx, err, "updating host_mdm_apple_declarations that may have been sent to host")
}
return nil
}
func (ds *Datastore) DeleteMDMAppleDeclarationByName(ctx context.Context, teamID *uint, name string) error {
return ds.withRetryTxx(ctx, func(tx sqlx.ExtContext) error {
const loadStmt = `SELECT declaration_uuid FROM mdm_apple_declarations WHERE team_id = ? AND name = ?`
var globalOrTmID uint
if teamID != nil {
globalOrTmID = *teamID
}
var declUUID string
err := sqlx.GetContext(ctx, tx, &declUUID, loadStmt, globalOrTmID, name)
switch {
case err == nil:
// Declaration exists, delete it.
return deleteMDMAppleDeclarationAndPostProcessing(ctx, tx, declUUID)
case errors.Is(err, sql.ErrNoRows):
// Declaration doesn't exist, nothing to do.
return nil
default:
return ctxerr.Wrap(ctx, err, "load apple mdm declaration")
}
})
}
func deleteMDMAppleDeclaration(ctx context.Context, tx sqlx.ExtContext, uuid string) error {
stmt := `DELETE FROM mdm_apple_declarations WHERE declaration_uuid = ?`
res, err := tx.ExecContext(ctx, stmt, uuid)
if err != nil {
return ctxerr.Wrap(ctx, err)
}
deleted, _ := res.RowsAffected()
if deleted != 1 {
return ctxerr.Wrap(ctx, notFound("MDMAppleDeclaration").WithName(uuid))
}
return nil
}
func (ds *Datastore) DeleteMDMAppleConfigProfileByTeamAndIdentifier(ctx context.Context, teamID *uint, profileIdentifier string) error {
if teamID == nil {
teamID = ptr.Uint(0)
}
res, err := ds.writer(ctx).ExecContext(ctx, `DELETE FROM mdm_apple_configuration_profiles WHERE team_id = ? AND identifier = ?`, teamID, profileIdentifier)
if err != nil {
return ctxerr.Wrap(ctx, err)
}
if deleted, _ := res.RowsAffected(); deleted == 0 {
message := fmt.Sprintf("identifier: %s, team_id: %d", profileIdentifier, teamID)
return ctxerr.Wrap(ctx, notFound("MDMAppleConfigProfile").WithMessage(message))
}
return nil
}
func (ds *Datastore) GetHostMDMAppleProfiles(ctx context.Context, hostUUID string) ([]fleet.HostMDMAppleProfile, error) {
stmt := fmt.Sprintf(`
SELECT
profile_uuid,
profile_name AS name,
profile_identifier AS identifier,
-- internally, a NULL status implies that the cron needs to pick up
-- this profile, for the user that difference doesn't exist, the
-- profile is effectively pending. This is consistent with all our
-- aggregation functions.
COALESCE(status, '%s') AS status,
COALESCE(operation_type, '') AS operation_type,
COALESCE(detail, '') AS detail,
scope,
CASE
WHEN scope = 'user' THEN COALESCE((SELECT nu.user_short_name FROM nano_enrollments ne INNER JOIN nano_users nu ON ne.user_id = nu.id WHERE ne.type = 'User' AND ne.enabled = 1 AND ne.device_id = host_uuid ORDER BY ne.created_at ASC LIMIT 1), '')
ELSE ''
END AS managed_local_account
FROM
host_mdm_apple_profiles
WHERE
host_uuid = ? AND NOT (operation_type = '%s' AND COALESCE(status, '%s') IN('%s', '%s'))
UNION ALL
SELECT
declaration_uuid AS profile_uuid,
declaration_name AS name,
declaration_identifier AS identifier,
-- internally, a NULL status implies that the cron needs to pick up
-- this profile, for the user that difference doesn't exist, the
-- profile is effectively pending. This is consistent with all our
-- aggregation functions.
COALESCE(status, '%s') AS status,
COALESCE(operation_type, '') AS operation_type,
COALESCE(detail, '') AS detail,
scope,
'' AS managed_local_account
FROM
host_mdm_apple_declarations
WHERE
host_uuid = ? AND declaration_name NOT IN (?) AND NOT (operation_type = '%s' AND COALESCE(status, '%s') IN('%s', '%s'))`,
fleet.MDMDeliveryPending,
fleet.MDMOperationTypeRemove,
fleet.MDMDeliveryPending,
fleet.MDMDeliveryVerifying,
fleet.MDMDeliveryVerified,
fleet.MDMDeliveryPending,
fleet.MDMOperationTypeRemove,
fleet.MDMDeliveryPending,
fleet.MDMDeliveryVerifying,
fleet.MDMDeliveryVerified,
)
stmt, args, err := sqlx.In(stmt, hostUUID, hostUUID, fleetmdm.ListFleetReservedMacOSDeclarationNames())
if err != nil {
return nil, ctxerr.Wrap(ctx, err, "building in statement")
}
var profiles []fleet.HostMDMAppleProfile
if err := sqlx.SelectContext(ctx, ds.reader(ctx), &profiles, stmt, args...); err != nil {
return nil, err
}
return profiles, nil
}
func (ds *Datastore) GetAppleHostMDMCertificateProfile(ctx context.Context, hostUUID string,
profileUUID string, caName string,
) (*fleet.HostMDMCertificateProfile, error) {
stmt := `
SELECT
hmap.host_uuid,
hmap.profile_uuid,
hmap.status,
hmmc.challenge_retrieved_at,
hmmc.not_valid_before,
hmmc.not_valid_after,
hmmc.type,
hmmc.ca_name,
hmmc.serial
FROM
host_mdm_apple_profiles hmap
JOIN host_mdm_managed_certificates hmmc
ON hmap.host_uuid = hmmc.host_uuid AND hmap.profile_uuid = hmmc.profile_uuid
WHERE
hmmc.host_uuid = ? AND hmmc.profile_uuid = ? AND hmmc.ca_name = ?`
var profile fleet.HostMDMCertificateProfile
if err := sqlx.GetContext(ctx, ds.reader(ctx), &profile, stmt, hostUUID, profileUUID, caName); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return nil, err
}
return &profile, nil
}
// ResendHostCertificateProfile marks the given profile UUID to be resent to the host with the given UUID. It
// also deactivates prior nano commands and resets the retry counter for the profile UUID and host UUID.
//
// FIXME: We really should have a more generic function to handle this. Something seems off with our
// existing methods for "resending" profiles. Scenarios have been observed where the old command
// bytes are sent again without reevaluating the profile variables, which is particularly problematic
// for certificate profiles where we need to regenerate the dynamic challenges. The main difference between
// the existing flow and the implementation below is that it zeroes out prior retries and blanks the
// command uuid to force the reconcile cron to reevaluate the command template to generate
// the challenge. It feels like we have some leaky abstractions somewhere that we need to clean up.
func (ds *Datastore) ResendHostCertificateProfile(ctx context.Context, hostUUID string, profUUID string) error {
deactivateNanoStmt := `
UPDATE
nano_enrollment_queue
JOIN nano_enrollments ne
ON nano_enrollment_queue.id = ne.id
JOIN host_mdm_apple_profiles hmap
ON hmap.command_uuid = nano_enrollment_queue.command_uuid AND
hmap.host_uuid = ne.device_id
SET
nano_enrollment_queue.active = 0
WHERE
hmap.profile_uuid = ? AND
hmap.host_uuid = ?`
// TODO: figure out variables_updated_at timing skew with jordan
updateStmt := `
UPDATE
host_mdm_apple_profiles
SET
status = NULL,
command_uuid = '',
detail = '',
retries = 0,
variables_updated_at = NOW(6)
WHERE
profile_uuid = ? AND
host_uuid = ? AND
operation_type = ?`
return ds.withRetryTxx(ctx, func(tx sqlx.ExtContext) error {
res, err := tx.ExecContext(ctx, deactivateNanoStmt, profUUID, hostUUID)
if err != nil {
return ctxerr.Wrap(ctx, err, "deactivating nano_enrollment_queue for commands that were pending send to host")
}
if rows, _ := res.RowsAffected(); rows == 0 {
// this should never happen, log for debugging
ds.logger.ErrorContext(ctx, "resend custom scep profile: nano not deactivated", "host_uuid", hostUUID, "profile_uuid", profUUID)
}
res, err = tx.ExecContext(ctx, updateStmt, profUUID, hostUUID, fleet.MDMOperationTypeInstall)
if err != nil {
return ctxerr.Wrap(ctx, err, "resending host MDM profile")
}
if rows, _ := res.RowsAffected(); rows == 0 {
// this should never happen, log for debugging
ds.logger.ErrorContext(ctx, "resend custom scep profile: host mdm apple profiles not updated", "host_uuid", hostUUID, "profile_uuid", profUUID)
}
return nil
})
}
func (ds *Datastore) NewMDMAppleEnrollmentProfile(
ctx context.Context,
payload fleet.MDMAppleEnrollmentProfilePayload,
) (*fleet.MDMAppleEnrollmentProfile, error) {
res, err := ds.writer(ctx).ExecContext(ctx,
`
INSERT INTO
mdm_apple_enrollment_profiles (token, type, dep_profile)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE
token = VALUES(token),
type = VALUES(type),
dep_profile = VALUES(dep_profile)
`,
payload.Token, payload.Type, payload.DEPProfile,
)
if err != nil {
return nil, ctxerr.Wrap(ctx, err)
}
id, _ := res.LastInsertId()
return &fleet.MDMAppleEnrollmentProfile{
ID: uint(id), //nolint:gosec // dismiss G115
Token: payload.Token,
Type: payload.Type,
DEPProfile: payload.DEPProfile,
}, nil
}
func (ds *Datastore) ListMDMAppleEnrollmentProfiles(ctx context.Context) ([]*fleet.MDMAppleEnrollmentProfile, error) {
var enrollmentProfiles []*fleet.MDMAppleEnrollmentProfile
if err := sqlx.SelectContext(
ctx,
ds.writer(ctx),
&enrollmentProfiles,
`
SELECT
id,
token,
type,
dep_profile,
created_at,
updated_at
FROM
mdm_apple_enrollment_profiles
ORDER BY created_at DESC
`,
); err != nil {
return nil, ctxerr.Wrap(ctx, err, "list enrollment profiles")
}
return enrollmentProfiles, nil
}
func (ds *Datastore) GetMDMAppleEnrollmentProfileByToken(ctx context.Context, token string) (*fleet.MDMAppleEnrollmentProfile, error) {
var enrollment fleet.MDMAppleEnrollmentProfile
if err := sqlx.GetContext(ctx, ds.reader(ctx),
&enrollment,
`
SELECT
id,
token,
type,
dep_profile,
created_at,
updated_at
FROM
mdm_apple_enrollment_profiles
WHERE
token = ?
`,
token,
); err != nil {
if err == sql.ErrNoRows {
return nil, ctxerr.Wrap(ctx, notFound("MDMAppleEnrollmentProfile"))
}
return nil, ctxerr.Wrap(ctx, err, "get enrollment profile by token")
}
return &enrollment, nil
}
func (ds *Datastore) GetMDMAppleEnrollmentProfileByType(ctx context.Context, typ fleet.MDMAppleEnrollmentType) (*fleet.MDMAppleEnrollmentProfile, error) {
var enrollment fleet.MDMAppleEnrollmentProfile
if err := sqlx.GetContext(ctx, ds.writer(ctx), // use writer as it is used just after creation in some cases
&enrollment,
`
SELECT
id,
token,
type,
dep_profile,
created_at,
updated_at
FROM
mdm_apple_enrollment_profiles
WHERE
type = ?