-
Notifications
You must be signed in to change notification settings - Fork 478
/
Copy pathhosts.go
5545 lines (5060 loc) · 176 KB
/
hosts.go
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 (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"time"
"unicode/utf8"
"github.com/cenkalti/backoff/v4"
"github.com/doug-martin/goqu/v9"
"github.com/fleetdm/fleet/v4/server/config"
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
"github.com/fleetdm/fleet/v4/server/contexts/license"
"github.com/fleetdm/fleet/v4/server/fleet"
microsoft_mdm "github.com/fleetdm/fleet/v4/server/mdm/microsoft"
"github.com/fleetdm/fleet/v4/server/ptr"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/jmoiron/sqlx"
)
// Since many hosts may have issues, we need to batch the inserts of host issues.
// This is a variable, so it can be adjusted during unit testing.
var (
hostIssuesInsertBatchSize = 10000
hostIssuesUpdateFailingPoliciesBatchSize = 10000
hostsDeleteBatchSize = 5000
)
// A large number of hosts could be changing teams at once, so we need to batch this operation to prevent excessive locks
var addHostsToTeamBatchSize = 10000
var (
hostSearchColumns = []string{"hostname", "computer_name", "uuid", "hardware_serial", "primary_ip"}
wildCardableHostSearchColumns = []string{"hostname", "computer_name"}
)
// TODO: should host search columns include display_name (requires join to host_display_names)?
// Fixme: We should not make implementation details of the database schema part of the API.
var defaultHostColumnTableAliases = map[string]string{
"created_at": "h.created_at",
"updated_at": "h.updated_at",
"issues": "host_issues.total_issues_count",
}
func defaultHostColumnTableAlias(s string) string {
if newCol, ok := defaultHostColumnTableAliases[s]; ok {
return newCol
}
return s
}
// NewHost creates a new host on the datastore.
//
// Currently only used for testing.
func (ds *Datastore) NewHost(ctx context.Context, host *fleet.Host) (*fleet.Host, error) {
err := ds.withTx(ctx, func(tx sqlx.ExtContext) error {
sqlStatement := `
INSERT INTO hosts (
osquery_host_id,
detail_updated_at,
label_updated_at,
policy_updated_at,
node_key,
hostname,
computer_name,
uuid,
platform,
osquery_version,
os_version,
uptime,
memory,
team_id,
distributed_interval,
logger_tls_period,
config_tls_refresh,
refetch_requested,
hardware_serial,
refetch_critical_queries_until
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`
result, err := tx.ExecContext(
ctx,
sqlStatement,
host.OsqueryHostID,
host.DetailUpdatedAt,
host.LabelUpdatedAt,
host.PolicyUpdatedAt,
host.NodeKey,
host.Hostname,
host.ComputerName,
host.UUID,
host.Platform,
host.OsqueryVersion,
host.OSVersion,
host.Uptime,
host.Memory,
host.TeamID,
host.DistributedInterval,
host.LoggerTLSPeriod,
host.ConfigTLSRefresh,
host.RefetchRequested,
host.HardwareSerial,
host.RefetchCriticalQueriesUntil,
)
if err != nil {
return ctxerr.Wrap(ctx, err, "new host")
}
id, _ := result.LastInsertId()
host.ID = uint(id)
_, err = tx.ExecContext(ctx,
`INSERT INTO host_seen_times (host_id, seen_time) VALUES (?,?)`,
host.ID, host.SeenTime,
)
if err != nil {
return ctxerr.Wrap(ctx, err, "new host seen time")
}
_, err = tx.ExecContext(ctx,
`INSERT INTO host_display_names (host_id, display_name) VALUES (?,?)`,
host.ID, host.DisplayName(),
)
if err != nil {
return ctxerr.Wrap(ctx, err, "host_display_names")
}
return nil
})
if err != nil {
return nil, err
}
return host, nil
}
func (ds *Datastore) SerialUpdateHost(ctx context.Context, host *fleet.Host) error {
errCh := make(chan error, 1)
defer close(errCh)
select {
case <-ctx.Done():
return ctx.Err()
case ds.writeCh <- itemToWrite{
ctx: ctx,
errCh: errCh,
item: host,
}:
return <-errCh
}
}
func (ds *Datastore) SaveHostPackStats(ctx context.Context, teamID *uint, hostID uint, stats []fleet.PackStats) error {
return saveHostPackStatsDB(ctx, ds.writer(ctx), teamID, hostID, stats)
}
func saveHostPackStatsDB(ctx context.Context, db *sqlx.DB, teamID *uint, hostID uint, stats []fleet.PackStats) error {
// NOTE: this implementation must be kept in sync with the async/batch version
// in AsyncBatchSaveHostsScheduledQueryStats (in scheduled_queries.go) - that is,
// the behaviour per host must be the same.
var (
userPacksArgs []interface{}
userPacksQueryCount = 0
scheduledQueriesArgs []interface{}
scheduledQueriesQueryCount = 0
)
for _, pack := range stats {
if pack.PackName == "Global" || (teamID != nil && pack.PackName == fmt.Sprintf("team-%d", *teamID)) {
for _, query := range pack.QueryStats {
scheduledQueriesQueryCount++
teamIDArg := uint(0)
if pack.PackName != "Global" {
teamIDArg = *teamID
}
// Handle rare case when wall_time_ms is missing (for osquery < 5.3.0)
if query.WallTimeMs == 0 && query.WallTime != 0 {
query.WallTimeMs = query.WallTime * 1000
}
scheduledQueriesArgs = append(scheduledQueriesArgs,
teamIDArg,
query.ScheduledQueryName,
hostID,
query.AverageMemory,
query.Denylisted,
query.Executions,
query.Interval,
query.LastExecuted,
query.OutputSize,
query.SystemTime,
query.UserTime,
query.WallTimeMs,
)
}
} else { // User 2017 packs
for _, query := range pack.QueryStats {
userPacksQueryCount++
// Handle rare case when wall_time_ms is missing (for osquery < 5.3.0)
if query.WallTimeMs == 0 && query.WallTime != 0 {
query.WallTimeMs = query.WallTime * 1000
}
userPacksArgs = append(userPacksArgs,
query.PackName,
query.ScheduledQueryName,
hostID,
query.AverageMemory,
query.Denylisted,
query.Executions,
query.Interval,
query.LastExecuted,
query.OutputSize,
query.SystemTime,
query.UserTime,
query.WallTimeMs,
)
}
}
}
if userPacksQueryCount == 0 && scheduledQueriesQueryCount == 0 {
return nil
}
if scheduledQueriesQueryCount > 0 {
// This query will import stats for queries (new format).
values := strings.TrimSuffix(strings.Repeat("((SELECT q.id FROM queries q WHERE COALESCE(q.team_id, 0) = ? AND q.name = ?),?,?,?,?,?,?,?,?,?,?),", scheduledQueriesQueryCount), ",")
sql := fmt.Sprintf(`
INSERT IGNORE INTO scheduled_query_stats (
scheduled_query_id,
host_id,
average_memory,
denylisted,
executions,
schedule_interval,
last_executed,
output_size,
system_time,
user_time,
wall_time
)
VALUES %s ON DUPLICATE KEY UPDATE
scheduled_query_id = VALUES(scheduled_query_id),
host_id = VALUES(host_id),
average_memory = VALUES(average_memory),
denylisted = VALUES(denylisted),
executions = VALUES(executions),
schedule_interval = VALUES(schedule_interval),
last_executed = VALUES(last_executed),
output_size = VALUES(output_size),
system_time = VALUES(system_time),
user_time = VALUES(user_time),
wall_time = VALUES(wall_time)
`, values)
if _, err := db.ExecContext(ctx, sql, scheduledQueriesArgs...); err != nil {
return ctxerr.Wrap(ctx, err, "insert query schedule stats")
}
}
if userPacksQueryCount > 0 {
// This query will import stats for 2017 packs.
// NOTE(lucas): If more than one scheduled query reference the same query then only one of the stats will be written.
values := strings.TrimSuffix(strings.Repeat("((SELECT sq.query_id FROM scheduled_queries sq JOIN packs p ON (sq.pack_id = p.id) WHERE p.pack_type IS NULL AND p.name = ? AND sq.name = ?),?,?,?,?,?,?,?,?,?,?),", userPacksQueryCount), ",")
sql := fmt.Sprintf(`
INSERT IGNORE INTO scheduled_query_stats (
scheduled_query_id,
host_id,
average_memory,
denylisted,
executions,
schedule_interval,
last_executed,
output_size,
system_time,
user_time,
wall_time
)
VALUES %s ON DUPLICATE KEY UPDATE
scheduled_query_id = VALUES(scheduled_query_id),
host_id = VALUES(host_id),
average_memory = VALUES(average_memory),
denylisted = VALUES(denylisted),
executions = VALUES(executions),
schedule_interval = VALUES(schedule_interval),
last_executed = VALUES(last_executed),
output_size = VALUES(output_size),
system_time = VALUES(system_time),
user_time = VALUES(user_time),
wall_time = VALUES(wall_time)
`, values)
if _, err := db.ExecContext(ctx, sql, userPacksArgs...); err != nil {
return ctxerr.Wrap(ctx, err, "insert pack stats")
}
}
return nil
}
// MySQL is really particular about using zero values or old values for
// timestamps, so we set a default value that is plenty far in the past, but
// hopefully accepted by most MySQL configurations.
//
// NOTE: #3229 proposes a better fix that uses *time.Time for
// ScheduledQueryStats.LastExecuted.
var pastDate = "2000-01-01T00:00:00Z"
// loadhostPacksStatsDB will load all the "2017 pack" stats for the given host. The scheduled
// queries that haven't run yet are returned with zero values.
func loadHostPackStatsDB(ctx context.Context, db sqlx.QueryerContext, hid uint, hostPlatform string) ([]fleet.PackStats, error) {
packs, err := listPacksForHost(ctx, db, hid)
if err != nil {
return nil, ctxerr.Wrapf(ctx, err, "list packs for host: %d", hid)
}
if len(packs) == 0 {
return nil, nil
}
packIDs := make([]uint, len(packs))
packTypes := make(map[uint]*string)
for i := range packs {
packIDs[i] = packs[i].ID
packTypes[packs[i].ID] = packs[i].Type
}
ds := dialect.From(goqu.I("scheduled_queries").As("sq")).Select(
goqu.I("sq.name").As("scheduled_query_name"),
goqu.I("sq.id").As("scheduled_query_id"),
goqu.I("sq.query_name").As("query_name"),
goqu.I("q.description").As("description"),
goqu.I("p.name").As("pack_name"),
goqu.I("p.id").As("pack_id"),
goqu.COALESCE(goqu.I("sqs.average_memory"), 0).As("average_memory"),
goqu.COALESCE(goqu.I("sqs.denylisted"), false).As("denylisted"),
goqu.COALESCE(goqu.I("sqs.executions"), 0).As("executions"),
goqu.I("sq.interval").As("schedule_interval"),
goqu.COALESCE(goqu.I("sqs.last_executed"), goqu.L("timestamp(?)", pastDate)).As("last_executed"),
goqu.COALESCE(goqu.I("sqs.output_size"), 0).As("output_size"),
goqu.COALESCE(goqu.I("sqs.system_time"), 0).As("system_time"),
goqu.COALESCE(goqu.I("sqs.user_time"), 0).As("user_time"),
goqu.COALESCE(goqu.I("sqs.wall_time"), 0).As("wall_time"),
).Join(
dialect.From("packs").As("p").Select(
goqu.I("id"),
goqu.I("name"),
).Where(goqu.I("id").In(packIDs)),
goqu.On(goqu.I("sq.pack_id").Eq(goqu.I("p.id"))),
).Join(
goqu.I("queries").As("q"),
goqu.On(goqu.I("sq.query_id").Eq(goqu.I("q.id"))),
).LeftJoin(
goqu.L(
`
(SELECT
stats.scheduled_query_id,
CAST(AVG(stats.average_memory) AS UNSIGNED) AS average_memory,
MAX(stats.denylisted) AS denylisted,
SUM(stats.executions) AS executions,
MAX(stats.last_executed) AS last_executed,
SUM(stats.output_size) AS output_size,
SUM(stats.system_time) AS system_time,
SUM(stats.user_time) AS user_time,
SUM(stats.wall_time) AS wall_time
FROM scheduled_query_stats stats WHERE stats.host_id = ? GROUP BY stats.scheduled_query_id) as sqs
`, hid,
),
goqu.On(goqu.I("sqs.scheduled_query_id").Eq(goqu.I("sq.query_id"))),
).Where(
goqu.Or(
// sq.platform empty or NULL means the scheduled query is set to
// run on all hosts.
goqu.I("sq.platform").Eq(""),
goqu.I("sq.platform").IsNull(),
// scheduled_queries.platform can be a comma-separated list of
// platforms, e.g. "darwin,windows".
goqu.L("FIND_IN_SET(?, sq.platform)", fleet.PlatformFromHost(hostPlatform)).Neq(0),
),
)
sql, args, err := ds.ToSQL()
if err != nil {
return nil, ctxerr.Wrap(ctx, err, "sql build")
}
var stats []fleet.ScheduledQueryStats
if err := sqlx.SelectContext(ctx, db, &stats, sql, args...); err != nil {
return nil, ctxerr.Wrap(ctx, err, "load pack stats")
}
packStats := map[uint]fleet.PackStats{}
for _, query := range stats {
pack := packStats[query.PackID]
pack.PackName = query.PackName
pack.PackID = query.PackID
pack.Type = getPackTypeFromDBField(packTypes[pack.PackID])
pack.QueryStats = append(pack.QueryStats, query)
packStats[pack.PackID] = pack
}
var ps []fleet.PackStats
for _, pack := range packStats {
ps = append(ps, pack)
}
return ps, nil
}
// loadHostScheduledQueryStatsDB will load all the scheduled query stats for the given host.
// The filter is split into two statements joined by a UNION ALL to take advantage of indexes.
// Using an OR in the WHERE clause causes a full table scan which causes issues with a large
// queries table due to the high volume of live queries (created by zero trust workflows)
func loadHostScheduledQueryStatsDB(ctx context.Context, db sqlx.QueryerContext, hid uint, hostPlatform string, teamID *uint) ([]fleet.QueryStats, error) {
var teamID_ uint
if teamID != nil {
teamID_ = *teamID
}
baseQuery := `
SELECT
q.id,
q.name,
q.description,
q.team_id,
q.schedule_interval AS schedule_interval,
q.discard_data,
q.automations_enabled,
MAX(qr.last_fetched) as last_fetched,
COALESCE(sqs.average_memory, 0) AS average_memory,
COALESCE(sqs.denylisted, false) AS denylisted,
COALESCE(sqs.executions, 0) AS executions,
COALESCE(sqs.last_executed, TIMESTAMP(?)) AS last_executed,
COALESCE(sqs.output_size, 0) AS output_size,
COALESCE(sqs.system_time, 0) AS system_time,
COALESCE(sqs.user_time, 0) AS user_time,
COALESCE(sqs.wall_time, 0) AS wall_time
FROM
queries q
LEFT JOIN
(SELECT
stats.scheduled_query_id,
CAST(AVG(stats.average_memory) AS UNSIGNED) AS average_memory,
MAX(stats.denylisted) AS denylisted,
SUM(stats.executions) AS executions,
MAX(stats.last_executed) AS last_executed,
SUM(stats.output_size) AS output_size,
SUM(stats.system_time) AS system_time,
SUM(stats.user_time) AS user_time,
SUM(stats.wall_time) AS wall_time
FROM scheduled_query_stats stats WHERE stats.host_id = ? GROUP BY stats.scheduled_query_id) as sqs ON (q.id = sqs.scheduled_query_id)
LEFT JOIN query_results qr ON (q.id = qr.query_id AND qr.host_id = ?)
`
filter1 := `
WHERE
(q.platform = '' OR q.platform IS NULL OR FIND_IN_SET(?, q.platform) != 0)
AND q.is_scheduled = 1
AND (q.automations_enabled IS TRUE OR (q.discard_data IS FALSE AND q.logging_type = ?))
AND (q.team_id IS NULL OR q.team_id = ?)
GROUP BY q.id
`
filter2 := `
WHERE EXISTS (
SELECT 1 FROM query_results
WHERE query_results.query_id = q.id
AND query_results.host_id = ?
)
GROUP BY q.id
`
finalColumns := `id, name, description, team_id, schedule_interval, discard_data, automations_enabled,
last_fetched, average_memory, denylisted, executions, last_executed, output_size, system_time,
user_time, wall_time`
sqlQuery := `SELECT ` + finalColumns + ` FROM (` +
baseQuery + filter1 + " UNION ALL " + baseQuery + filter2 + `) qs GROUP BY ` + finalColumns
args := []interface{}{
pastDate,
hid,
hid,
fleet.PlatformFromHost(hostPlatform),
fleet.LoggingSnapshot,
teamID_,
pastDate,
hid,
hid,
hid,
}
var stats []fleet.QueryStats
if err := sqlx.SelectContext(ctx, db, &stats, sqlQuery, args...); err != nil {
return nil, ctxerr.Wrap(ctx, err, "load query stats")
}
return stats, nil
}
func getPackTypeFromDBField(t *string) string {
if t == nil {
return "pack"
}
return *t
}
func loadHostUsersDB(ctx context.Context, db sqlx.QueryerContext, hostID uint) ([]fleet.HostUser, error) {
sql := `SELECT username, groupname, uid, user_type, shell FROM host_users WHERE host_id = ? and removed_at IS NULL`
var users []fleet.HostUser
if err := sqlx.SelectContext(ctx, db, &users, sql, hostID); err != nil {
return nil, ctxerr.Wrap(ctx, err, "load host users")
}
return users, nil
}
func (ds *Datastore) ListHostUsers(ctx context.Context, hostID uint) ([]fleet.HostUser, error) {
users, err := loadHostUsersDB(ctx, ds.reader(ctx), hostID)
if err != nil {
return nil, ctxerr.Wrap(ctx, err, "loading host users")
}
return users, nil
}
// hostRefs are the tables referenced by hosts.
//
// Defined here for testing purposes.
var hostRefs = []string{
"host_seen_times",
"host_software",
"host_users",
"host_emails",
"host_additional",
"scheduled_query_stats",
"label_membership",
"policy_membership",
"host_mdm",
"host_munki_info",
"host_device_auth",
"host_batteries",
"host_operating_system",
"host_orbit_info",
"host_munki_issues",
"host_display_names",
"windows_updates",
"host_disks",
"host_updates",
"host_disk_encryption_keys",
"host_software_installed_paths",
"query_results",
"host_activities",
"host_mdm_actions",
"host_calendar_events",
}
// NOTE: The following tables are explicity excluded from hostRefs list and accordingly are not
// deleted from when a host is deleted in Fleet:
// - host_dep_assignments
// - mdm tables (nano and windows) containing enrollment information, as we
// want to keep the enrollment relationship even if the host is temporarily
// deleted from the UI. Re-enrollment sometimes is not straightforward like it
// is for osquery/fleetd
// additionalHostRefsByUUID are host refs cannot be deleted using the host.id like the hostRefs
// above. They use the host.uuid instead. Additionally, the column name that refers to
// the host.uuid is not always named the same, so the map key is the table name
// and the map value is the column name to match to the host.uuid.
var additionalHostRefsByUUID = map[string]string{
"host_mdm_apple_profiles": "host_uuid",
"host_mdm_apple_bootstrap_packages": "host_uuid",
"host_mdm_windows_profiles": "host_uuid",
"host_mdm_apple_declarations": "host_uuid",
"host_mdm_apple_awaiting_configuration": "host_uuid",
"setup_experience_status_results": "host_uuid",
}
// additionalHostRefsSoftDelete are tables that reference a host but for which
// the rows are not deleted when the host is deleted, only a soft delete is
// performed by setting a timestamp column to the current time.
var additionalHostRefsSoftDelete = map[string]string{
"host_script_results": "host_deleted_at",
"host_software_installs": "host_deleted_at",
}
func (ds *Datastore) DeleteHost(ctx context.Context, hid uint) error {
return ds.withRetryTxx(ctx, func(tx sqlx.ExtContext) error {
return deleteHosts(ctx, tx, []uint{hid})
})
}
func deleteHosts(ctx context.Context, tx sqlx.ExtContext, hostIDs []uint) error {
if len(hostIDs) == 0 {
return nil
}
delHostRef := func(tx sqlx.ExtContext, table string) error {
stmt, args, err := sqlx.In(fmt.Sprintf("DELETE FROM %s WHERE host_id IN (?)", table), hostIDs)
if err != nil {
return ctxerr.Wrapf(ctx, err, "building delete statement for %s", table)
}
_, err = tx.ExecContext(ctx, stmt, args...)
if err != nil {
return ctxerr.Wrapf(ctx, err, "deleting %s for hosts %v", table, hostIDs)
}
return nil
}
// load just the host uuid for the MDM tables that rely on this to be cleared.
var hostUUIDs []string
stmt, args, err := sqlx.In(`SELECT uuid FROM hosts WHERE id IN (?)`, hostIDs)
if err != nil {
return ctxerr.Wrapf(ctx, err, "building select statement for host uuids")
}
if err := sqlx.SelectContext(ctx, tx, &hostUUIDs, stmt, args...); err != nil {
return ctxerr.Wrapf(ctx, err, "get uuid for hosts %v", hostIDs)
}
stmt, args, err = sqlx.In(`DELETE FROM hosts WHERE id IN (?)`, hostIDs)
if err != nil {
return ctxerr.Wrapf(ctx, err, "building delete statement for hosts %v", hostIDs)
}
_, err = tx.ExecContext(ctx, stmt, args...)
if err != nil {
return ctxerr.Wrapf(ctx, err, "delete hosts")
}
for _, table := range hostRefs {
err := delHostRef(tx, table)
if err != nil {
return err
}
}
stmt, args, err = sqlx.In(`DELETE FROM pack_targets WHERE type = ? AND target_id IN (?)`, fleet.TargetHost, hostIDs)
if err != nil {
return ctxerr.Wrapf(ctx, err, "building delete statement for pack_targets for hosts %v", hostIDs)
}
_, err = tx.ExecContext(ctx, stmt, args...)
if err != nil {
return ctxerr.Wrapf(ctx, err, "deleting pack_targets for hosts %v", hostIDs)
}
// no point trying the uuid-based tables if the host's uuid is missing
if len(hostUUIDs) != 0 {
for table, col := range additionalHostRefsByUUID {
stmt, args, err := sqlx.In(fmt.Sprintf("DELETE FROM `%s` WHERE `%s` IN (?)", table, col), hostUUIDs)
if err != nil {
return ctxerr.Wrapf(ctx, err, "building delete statement for %s for hosts %v", table, hostUUIDs)
}
if _, err := tx.ExecContext(ctx, stmt, args...); err != nil {
return ctxerr.Wrapf(ctx, err, "deleting %s for host uuids %v", table, hostUUIDs)
}
}
}
// perform the soft-deletion of host-referencing tables
for table, col := range additionalHostRefsSoftDelete {
stmt, args, err := sqlx.In(fmt.Sprintf("UPDATE `%s` SET `%s` = NOW() WHERE host_id IN (?)", table, col), hostIDs)
if err != nil {
return ctxerr.Wrapf(ctx, err, "building update statement for %s for hosts %v", table, hostIDs)
}
if _, err := tx.ExecContext(ctx, stmt, args...); err != nil {
return ctxerr.Wrapf(ctx, err, "soft-deleting %s for host ids %v", table, hostIDs)
}
}
return nil
}
func (ds *Datastore) Host(ctx context.Context, id uint) (*fleet.Host, error) {
sqlStatement := `
SELECT
h.id,
h.osquery_host_id,
h.created_at,
h.updated_at,
h.detail_updated_at,
h.node_key,
h.orbit_node_key,
h.hostname,
h.uuid,
h.platform,
h.osquery_version,
h.os_version,
h.build,
h.platform_like,
h.code_name,
h.uptime,
h.memory,
h.cpu_type,
h.cpu_subtype,
h.cpu_brand,
h.cpu_physical_cores,
h.cpu_logical_cores,
h.hardware_vendor,
h.hardware_model,
h.hardware_version,
h.hardware_serial,
h.computer_name,
h.primary_ip_id,
h.distributed_interval,
h.logger_tls_period,
h.config_tls_refresh,
h.primary_ip,
h.primary_mac,
h.label_updated_at,
h.last_enrolled_at,
h.refetch_requested,
h.refetch_critical_queries_until,
h.team_id,
h.policy_updated_at,
h.public_ip,
COALESCE(hd.gigs_disk_space_available, 0) as gigs_disk_space_available,
COALESCE(hd.percent_disk_space_available, 0) as percent_disk_space_available,
COALESCE(hd.gigs_total_disk_space, 0) as gigs_total_disk_space,
hd.encrypted as disk_encryption_enabled,
COALESCE(hst.seen_time, h.created_at) AS seen_time,
t.name AS team_name,
COALESCE(hu.software_updated_at, h.created_at) AS software_updated_at,
(CASE WHEN uptime = 0 THEN DATE('0001-01-01') ELSE DATE_SUB(h.detail_updated_at, INTERVAL uptime/1000 MICROSECOND) END) as last_restarted_at,
(
SELECT
additional
FROM
host_additional
WHERE
host_id = h.id
) AS additional,
COALESCE(host_issues.failing_policies_count, 0) AS failing_policies_count,
COALESCE(host_issues.critical_vulnerabilities_count, 0) AS critical_vulnerabilities_count,
COALESCE(host_issues.total_issues_count, 0) AS total_issues_count,
hoi.version AS orbit_version,
hoi.desktop_version AS fleet_desktop_version,
hoi.scripts_enabled AS scripts_enabled
` + hostMDMSelect + `
FROM
hosts h
LEFT JOIN teams t ON (h.team_id = t.id)
LEFT JOIN host_seen_times hst ON (h.id = hst.host_id)
LEFT JOIN host_updates hu ON (h.id = hu.host_id)
LEFT JOIN host_disks hd ON hd.host_id = h.id
LEFT JOIN host_orbit_info hoi ON hoi.host_id = h.id
LEFT JOIN host_issues ON h.id = host_issues.host_id
` + hostMDMJoin + `
WHERE
h.id = ?
LIMIT
1
`
args := []interface{}{id}
var host fleet.Host
err := sqlx.GetContext(ctx, ds.reader(ctx), &host, sqlStatement, args...)
if err != nil {
if err == sql.ErrNoRows {
return nil, ctxerr.Wrap(ctx, notFound("Host").WithID(id))
}
return nil, ctxerr.Wrap(ctx, err, "get host by id")
}
if host.DiskEncryptionEnabled != nil && !(*host.DiskEncryptionEnabled) && fleet.IsLinux(host.Platform) {
// omit disk encryption information for linux if it is not enabled, as we
// cannot know for sure that it is not encrypted (See
// https://github.com/fleetdm/fleet/issues/3906).
host.DiskEncryptionEnabled = nil
}
packStats, err := loadHostPackStatsDB(ctx, ds.reader(ctx), host.ID, host.Platform)
if err != nil {
return nil, err
}
host.PackStats = packStats
queriesStats, err := loadHostScheduledQueryStatsDB(ctx, ds.reader(ctx), host.ID, host.Platform, host.TeamID)
if err != nil {
return nil, err
}
var (
globalQueriesStats []fleet.QueryStats
hostTeamQueriesStats []fleet.QueryStats
)
for _, queryStats := range queriesStats {
if queryStats.TeamID == nil {
globalQueriesStats = append(globalQueriesStats, queryStats)
} else {
hostTeamQueriesStats = append(hostTeamQueriesStats, queryStats)
}
}
if len(globalQueriesStats) > 0 {
host.PackStats = append(host.PackStats, fleet.PackStats{
PackName: "Global",
Type: "global",
QueryStats: queryStatsToScheduledQueryStats(globalQueriesStats, "Global"),
})
}
if host.TeamID != nil && len(hostTeamQueriesStats) > 0 {
team, err := ds.Team(ctx, *host.TeamID)
if err != nil {
return nil, err
}
host.PackStats = append(host.PackStats, fleet.PackStats{
PackName: "Team: " + team.Name,
Type: fmt.Sprintf("team-%d", team.ID),
QueryStats: queryStatsToScheduledQueryStats(hostTeamQueriesStats, "Team: "+team.Name),
})
}
users, err := loadHostUsersDB(ctx, ds.reader(ctx), host.ID)
if err != nil {
return nil, err
}
host.Users = users
return &host, nil
}
func queryStatsToScheduledQueryStats(queriesStats []fleet.QueryStats, packName string) []fleet.ScheduledQueryStats {
scheduledQueriesStats := make([]fleet.ScheduledQueryStats, 0, len(queriesStats))
for _, queryStats := range queriesStats {
scheduledQueriesStats = append(scheduledQueriesStats, fleet.ScheduledQueryStats{
ScheduledQueryName: queryStats.Name,
ScheduledQueryID: queryStats.ID,
QueryName: queryStats.Name,
Description: queryStats.Description,
PackName: packName,
AverageMemory: queryStats.AverageMemory,
Denylisted: queryStats.Denylisted,
Executions: queryStats.Executions,
Interval: queryStats.Interval,
DiscardData: queryStats.DiscardData,
AutomationsEnabled: queryStats.AutomationsEnabled,
LastFetched: queryStats.LastFetched,
LastExecuted: queryStats.LastExecuted,
OutputSize: queryStats.OutputSize,
SystemTime: queryStats.SystemTime,
UserTime: queryStats.UserTime,
WallTime: queryStats.WallTime,
})
}
return scheduledQueriesStats
}
// hostMDMSelect is the SQL fragment used to construct the JSON object
// of MDM host data. It assumes that hostMDMJoin is included in the query.
const hostMDMSelect = `,
JSON_OBJECT(
'enrollment_status', hmdm.enrollment_status,
'dep_profile_error',
CASE
WHEN hdep.assign_profile_response = '` + string(fleet.DEPAssignProfileResponseFailed) + `' THEN CAST(TRUE AS JSON)
ELSE CAST(FALSE AS JSON)
END,
'server_url',
CASE
WHEN hmdm.is_server = 1 THEN NULL
ELSE hmdm.server_url
END,
'encryption_key_available',
CASE
/* roberto: this is the only way I have found for MySQL to
* return true and false instead of 0 and 1 in the JSON, the
* unmarshaller was having problems converting int values to
* booleans.
*/
WHEN hdek.decryptable IS NULL OR hdek.decryptable = 0 THEN CAST(FALSE AS JSON)
ELSE CAST(TRUE AS JSON)
END,
'raw_decryptable',
CASE
WHEN hdek.host_id IS NULL THEN -1
ELSE hdek.decryptable
END,
'connected_to_fleet',
CASE
WHEN h.platform = 'windows' THEN (` +
// NOTE: if you change any of the conditions in this
// query, please update the AreHostsConnectedToFleetMDM
// datastore method and any relevant filters.
`SELECT CASE WHEN EXISTS (
SELECT mwe.host_uuid
FROM mdm_windows_enrollments mwe
WHERE mwe.host_uuid = h.uuid
AND mwe.device_state = '` + microsoft_mdm.MDMDeviceStateEnrolled + `'
AND hmdm.enrolled = 1
)
THEN CAST(TRUE AS JSON)
ELSE CAST(FALSE AS JSON)
END
)
WHEN h.platform IN ('ios', 'ipados', 'darwin') THEN (` +
// NOTE: if you change any of the conditions in this
// query, please update the AreHostsConnectedToFleetMDM
// datastore method and any relevant filters.
`SELECT CASE WHEN EXISTS (
SELECT ne.id FROM nano_enrollments ne
WHERE ne.id = h.uuid
AND ne.enabled = 1
AND ne.type = 'Device'
AND hmdm.enrolled = 1
)
THEN CAST(TRUE AS JSON)
ELSE CAST(FALSE AS JSON)
END
)
ELSE CAST(FALSE AS JSON)
END,
'name', hmdm.name
) mdm_host_data
`
// hostMDMJoin is the SQL fragment used to join MDM-related tables to the hosts table. It is a
// dependency of the hostMDMSelect fragment.
const hostMDMJoin = `
LEFT JOIN (
SELECT
hm.is_server,
hm.enrolled,
hm.installed_from_dep,
hm.enrollment_status,
hm.server_url,
hm.mdm_id,
hm.host_id,
mdms.name
FROM
host_mdm hm
LEFT JOIN mobile_device_management_solutions mdms ON hm.mdm_id = mdms.id
) hmdm ON hmdm.host_id = h.id
LEFT JOIN host_disk_encryption_keys hdek ON hdek.host_id = h.id
LEFT JOIN host_dep_assignments hdep ON hdep.host_id = h.id
`
func amountEnrolledHostsByOSDB(ctx context.Context, db sqlx.QueryerContext) (byOS map[string][]fleet.HostsCountByOSVersion, totalCount int, err error) {
var hostsByOS []struct {
Platform string `db:"platform"`
OSVersion string `db:"os_version"`
NumHosts int `db:"num_hosts"`
}
const stmt = `
SELECT platform, os_version, count(*) as num_hosts
FROM hosts
GROUP BY platform, os_version
`
if err := sqlx.SelectContext(ctx, db, &hostsByOS, stmt); err != nil {
return nil, 0, err
}
byOS = make(map[string][]fleet.HostsCountByOSVersion)
for _, h := range hostsByOS {
totalCount += h.NumHosts
byVersion := byOS[h.Platform]
byVersion = append(byVersion, fleet.HostsCountByOSVersion{
Version: h.OSVersion,
NumEnrolled: h.NumHosts,
})
byOS[h.Platform] = byVersion
}
return byOS, totalCount, nil
}
func (ds *Datastore) ListHosts(ctx context.Context, filter fleet.TeamFilter, opt fleet.HostListOptions) ([]*fleet.Host, error) {
sql := `SELECT
h.id,
h.osquery_host_id,
h.created_at,
h.updated_at,
h.detail_updated_at,
h.node_key,
h.hostname,
h.uuid,
h.platform,
h.osquery_version,
h.os_version,
h.build,
h.platform_like,
h.code_name,
h.uptime,
h.memory,
h.cpu_type,
h.cpu_subtype,
h.cpu_brand,
h.cpu_physical_cores,
h.cpu_logical_cores,
h.hardware_vendor,
h.hardware_model,
h.hardware_version,
h.hardware_serial,
h.computer_name,
h.primary_ip_id,
h.distributed_interval,
h.logger_tls_period,
h.config_tls_refresh,
h.primary_ip,
h.primary_mac,
h.label_updated_at,
h.last_enrolled_at,
h.refetch_requested,
h.refetch_critical_queries_until,
h.team_id,
h.policy_updated_at,
h.public_ip,
h.orbit_node_key,
COALESCE(hd.gigs_disk_space_available, 0) as gigs_disk_space_available,
COALESCE(hd.percent_disk_space_available, 0) as percent_disk_space_available,
COALESCE(hd.gigs_total_disk_space, 0) as gigs_total_disk_space,
COALESCE(hst.seen_time, h.created_at) AS seen_time,