-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
profile_dir.go
432 lines (361 loc) · 11.8 KB
/
profile_dir.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
//go:build linux
// Package profile holds profile related files
package profile
import (
"context"
"errors"
"fmt"
"maps"
"os"
"path"
"path/filepath"
"slices"
"sort"
"sync"
"time"
"github.com/DataDog/datadog-go/v5/statsd"
"github.com/fsnotify/fsnotify"
"github.com/skydive-project/go-debouncer"
proto "github.com/DataDog/agent-payload/v5/cws/dumpsv1"
"github.com/DataDog/datadog-agent/pkg/security/config"
"github.com/DataDog/datadog-agent/pkg/security/metrics"
cgroupModel "github.com/DataDog/datadog-agent/pkg/security/resolvers/cgroup/model"
"github.com/DataDog/datadog-agent/pkg/security/seclog"
)
var (
workloadSelectorDebounceDelay = 5 * time.Second
newFileDebounceDelay = 2 * time.Second
)
var profileExtension = "." + config.Profile.String()
// make sure the DirectoryProvider implements Provider
var _ Provider = (*DirectoryProvider)(nil)
type profileFSEntry struct {
path string
selector cgroupModel.WorkloadSelector
}
// DirectoryProvider is a ProfileProvider that fetches Security Profiles from the filesystem
type DirectoryProvider struct {
sync.Mutex
directory string
watcherEnabled bool
// attributes used by the inotify watcher
cancelFnc func()
watcher *fsnotify.Watcher
newFilesDebouncer *debouncer.Debouncer
newFiles map[string]bool
newFilesLock sync.Mutex
// we use a debouncer to forward new profiles to the profile manager in order to prevent a deadlock
workloadSelectorDebouncer *debouncer.Debouncer
onNewProfileCallback func(selector cgroupModel.WorkloadSelector, profile *proto.SecurityProfile)
// selectors is used to select the profiles we currently care about
selectors []cgroupModel.WorkloadSelector
// profileMapping is an in-memory mapping of the profiles currently on the file system
profileMapping map[cgroupModel.WorkloadSelector]profileFSEntry
}
// NewDirectoryProvider returns a new instance of DirectoryProvider
func NewDirectoryProvider(directory string, watch bool) (*DirectoryProvider, error) {
// check if the provided directory exists
if _, err := os.Stat(directory); err != nil {
if os.IsNotExist(err) {
if err = os.MkdirAll(directory, 0750); err != nil {
return nil, fmt.Errorf("can't create security profiles directory `%s`: %w", directory, err)
}
} else {
return nil, fmt.Errorf("can't load security profiles from `%s`: %w", directory, err)
}
}
dp := &DirectoryProvider{
directory: directory,
watcherEnabled: watch,
profileMapping: make(map[cgroupModel.WorkloadSelector]profileFSEntry),
newFiles: make(map[string]bool),
}
dp.workloadSelectorDebouncer = debouncer.New(workloadSelectorDebounceDelay, dp.onNewProfileDebouncerCallback)
dp.newFilesDebouncer = debouncer.New(newFileDebounceDelay, dp.onHandleFilesFromWatcher)
return dp, nil
}
// Start runs the directory provider
func (dp *DirectoryProvider) Start(ctx context.Context) error {
dp.workloadSelectorDebouncer.Start()
dp.newFilesDebouncer.Start()
// add watches
if dp.watcherEnabled {
var err error
if dp.watcher, err = fsnotify.NewWatcher(); err != nil {
return fmt.Errorf("couldn't setup inotify watcher: %w", err)
}
if err = dp.watcher.Add(dp.directory); err != nil {
_ = dp.watcher.Close()
return err
}
var childContext context.Context
childContext, dp.cancelFnc = context.WithCancel(ctx)
go dp.watch(childContext)
}
// start by loading the profiles in the configured directory
if err := dp.loadProfiles(); err != nil {
return fmt.Errorf("couldn't scan the security profiles directory: %w", err)
}
return nil
}
// Stop closes the directory provider
func (dp *DirectoryProvider) Stop() error {
dp.workloadSelectorDebouncer.Stop()
dp.newFilesDebouncer.Stop()
if dp.cancelFnc != nil {
dp.cancelFnc()
}
if dp.watcher != nil {
if err := dp.watcher.Close(); err != nil {
seclog.Errorf("couldn't close profile watcher: %v", err)
}
}
return nil
}
// UpdateWorkloadSelectors updates the selectors used to query profiles
func (dp *DirectoryProvider) UpdateWorkloadSelectors(selectors []cgroupModel.WorkloadSelector) {
dp.Lock()
defer dp.Unlock()
dp.selectors = selectors
if dp.onNewProfileCallback == nil {
return
}
dp.workloadSelectorDebouncer.Call()
}
func (dp *DirectoryProvider) onNewProfileDebouncerCallback() {
// we don't want to keep the lock for too long, especially not while calling the callback
dp.Lock()
selectors := make([]cgroupModel.WorkloadSelector, len(dp.selectors))
copy(selectors, dp.selectors)
profileMapping := maps.Clone(dp.profileMapping)
propagateCb := dp.onNewProfileCallback
dp.Unlock()
if propagateCb == nil {
return
}
for _, selector := range selectors {
for profileSelector, profilePath := range profileMapping {
if selector.Match(profileSelector) {
// read and parse profile
profile, err := LoadProtoFromFile(profilePath.path)
if err != nil {
seclog.Warnf("couldn't load profile %s: %v", profilePath.path, err)
continue
}
// propagate the new profile
propagateCb(profileSelector, profile)
}
}
}
}
// SetOnNewProfileCallback sets the onNewProfileCallback function
func (dp *DirectoryProvider) SetOnNewProfileCallback(onNewProfileCallback func(selector cgroupModel.WorkloadSelector, profile *proto.SecurityProfile)) {
dp.onNewProfileCallback = onNewProfileCallback
}
func (dp *DirectoryProvider) listProfiles() ([]string, error) {
files, err := os.ReadDir(dp.directory)
if err != nil {
return nil, err
}
var output []string
for _, profilePath := range files {
name := profilePath.Name()
if filepath.Ext(name) != profileExtension {
continue
}
output = append(output, filepath.Join(dp.directory, name))
}
sort.Slice(output, func(i, j int) bool {
return output[i] < output[j]
})
return output, nil
}
func (dp *DirectoryProvider) loadProfile(profilePath string) error {
profile, err := LoadProtoFromFile(profilePath)
if err != nil {
return fmt.Errorf("couldn't load profile %s: %w", profilePath, err)
}
if len(profile.ProfileContexts) == 0 {
return fmt.Errorf("couldn't load profile %s: it did not contains any version", profilePath)
}
imageName, imageTag := profile.Selector.GetImageName(), profile.Selector.GetImageTag()
if imageTag == "" || imageName == "" {
return fmt.Errorf("couldn't load profile %s: it did not contains any valid image_name (%s) or image_tag (%s)", profilePath, imageName, imageTag)
}
workloadSelector, err := cgroupModel.NewWorkloadSelector(imageName, imageTag)
if err != nil {
return err
}
profileManagerSelector := workloadSelector
profileManagerSelector.Tag = "*"
// lock selectors and profiles mapping
dp.Lock()
selectors := make([]cgroupModel.WorkloadSelector, len(dp.selectors))
copy(selectors, dp.selectors)
profileMapping := maps.Clone(dp.profileMapping)
propagateCb := dp.onNewProfileCallback
dp.Unlock()
// prioritize a persited profile over activity dumps
if existingProfile, ok := profileMapping[profileManagerSelector]; ok {
if existingProfile.selector.Tag == "*" && profile.Selector.GetImageTag() != "*" {
seclog.Debugf("ignoring %s: a persisted profile already exists for workload %s", profilePath, profileManagerSelector.String())
return nil
}
}
// update profile mapping
dp.profileMapping[profileManagerSelector] = profileFSEntry{
path: profilePath,
selector: workloadSelector,
}
seclog.Debugf("security profile %s loaded from file system", workloadSelector)
if propagateCb == nil {
return nil
}
// check if this profile matches a workload selector
for _, selector := range selectors {
if workloadSelector.Match(selector) {
propagateCb(workloadSelector, profile)
}
}
return nil
}
func (dp *DirectoryProvider) loadProfiles() error {
files, err := dp.listProfiles()
if err != nil {
return err
}
for _, profilePath := range files {
if err = dp.loadProfile(profilePath); err != nil {
seclog.Errorf("couldn't load profile: %v", err)
}
}
return nil
}
func (dp *DirectoryProvider) findProfile(path string) (cgroupModel.WorkloadSelector, bool) {
dp.Lock()
defer dp.Unlock()
for selector, profile := range dp.profileMapping {
if path == profile.path {
return selector, true
}
}
return cgroupModel.WorkloadSelector{}, false
}
func (dp *DirectoryProvider) getProfiles() map[cgroupModel.WorkloadSelector]profileFSEntry {
dp.Lock()
defer dp.Unlock()
return dp.profileMapping
}
// OnLocalStorageCleanup removes the provided files from the entries of the directory provider
func (dp *DirectoryProvider) OnLocalStorageCleanup(files []string) {
dp.Lock()
defer dp.Unlock()
fileMask := make(map[string]bool)
for _, file := range files {
if path.Ext(file) == profileExtension {
fileMask[file] = true
}
}
// iterate through the list of profiles and remove the entries that are about to be deleted from the file system
for selector, fsEntry := range dp.profileMapping {
if _, found := fileMask[fsEntry.path]; found {
delete(dp.profileMapping, selector)
delete(fileMask, fsEntry.path)
if len(fileMask) == 0 {
break
}
}
}
}
func (dp *DirectoryProvider) deleteProfile(selector cgroupModel.WorkloadSelector) {
dp.Lock()
defer dp.Unlock()
delete(dp.profileMapping, selector)
}
func (dp *DirectoryProvider) onHandleFilesFromWatcher() {
dp.newFilesLock.Lock()
defer dp.newFilesLock.Unlock()
for file := range dp.newFiles {
if err := dp.loadProfile(file); err != nil {
if errors.Is(err, cgroupModel.ErrNoImageProvided) {
seclog.Debugf("couldn't load new profile %s: %v", file, err)
} else {
seclog.Warnf("couldn't load new profile %s: %v", file, err)
}
continue
}
}
dp.newFiles = make(map[string]bool)
}
func (dp *DirectoryProvider) watch(ctx context.Context) {
go func() {
for {
select {
case <-ctx.Done():
return
case event, ok := <-dp.watcher.Events:
if !ok {
return
}
if event.Has(fsnotify.Create | fsnotify.Remove) {
files, err := dp.listProfiles()
if err != nil {
seclog.Errorf("couldn't list profiles: %v", err)
continue
}
if event.Has(fsnotify.Create) {
// look for the new profile
for _, file := range files {
if _, ok = dp.findProfile(file); ok {
continue
}
// add file in the list of new files
dp.newFilesLock.Lock()
dp.newFiles[file] = true
dp.newFilesLock.Unlock()
dp.newFilesDebouncer.Call()
}
} else if event.Has(fsnotify.Remove) {
// look for the deleted profile
for selector, profile := range dp.getProfiles() {
if slices.Contains(files, profile.path) {
continue
}
// delete profile
dp.deleteProfile(selector)
dp.newFilesLock.Lock()
delete(dp.newFiles, profile.path)
dp.newFilesLock.Unlock()
seclog.Debugf("security profile %s removed from profile mapping", selector)
}
}
} else if event.Has(fsnotify.Write) && filepath.Ext(event.Name) == profileExtension {
// add file in the list of new files
dp.newFilesLock.Lock()
dp.newFiles[event.Name] = true
dp.newFilesLock.Unlock()
dp.newFilesDebouncer.Call()
}
case _, ok := <-dp.watcher.Errors:
if !ok {
return
}
}
}
}()
}
// SendStats sends the metrics of the directory provider
func (dp *DirectoryProvider) SendStats(client statsd.ClientInterface) error {
dp.Lock()
defer dp.Unlock()
if value := len(dp.profileMapping); value > 0 {
if err := client.Gauge(metrics.MetricSecurityProfileDirectoryProviderCount, float64(value), []string{}, 1.0); err != nil {
return fmt.Errorf("couldn't send %s metric: %w", metrics.MetricSecurityProfileDirectoryProviderCount, err)
}
}
return nil
}