-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathmount_test.go
More file actions
616 lines (522 loc) · 18.3 KB
/
Copy pathmount_test.go
File metadata and controls
616 lines (522 loc) · 18.3 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
// 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 && functionaltests
// Package tests holds tests related files
package tests
import (
"fmt"
"os"
"path"
"strings"
"syscall"
"testing"
"time"
"github.com/moby/sys/mountinfo"
"github.com/stretchr/testify/assert"
"golang.org/x/sys/unix"
ebpfkernel "github.com/DataDog/datadog-agent/pkg/security/ebpf/kernel"
sprobe "github.com/DataDog/datadog-agent/pkg/security/probe"
"github.com/DataDog/datadog-agent/pkg/security/secl/model"
"github.com/DataDog/datadog-agent/pkg/security/secl/rules"
"github.com/DataDog/datadog-agent/pkg/security/utils"
"github.com/DataDog/datadog-agent/pkg/util/kernel"
"github.com/DataDog/datadog-agent/pkg/util/testutil/flake"
)
func TestMount(t *testing.T) {
SkipIfNotAvailable(t)
dstMntBasename := "test-dest-mount"
ruleDefs := []*rules.RuleDefinition{{
ID: "test_rule",
Expression: fmt.Sprintf(`chmod.file.path == "{{.Root}}/%s/test-mount"`, dstMntBasename),
}, {
ID: "test_rule_pending",
Expression: fmt.Sprintf(`chown.file.path == "{{.Root}}/%s/test-release"`, dstMntBasename),
}}
testDrive, err := newTestDrive(t, "xfs", []string{}, "")
if err != nil {
t.Fatal(err)
}
defer testDrive.Close()
test, err := newTestModule(t, nil, ruleDefs, withDynamicOpts(dynamicTestOpts{testDir: testDrive.Root()}))
if err != nil {
t.Fatal(err)
}
defer test.Close()
mntPath := testDrive.Path("test-mount")
os.MkdirAll(mntPath, 0755)
defer os.RemoveAll(mntPath)
dstMntPath := testDrive.Path(dstMntBasename)
os.MkdirAll(dstMntPath, 0755)
defer os.RemoveAll(dstMntPath)
var mntID uint32
t.Run("mount", func(t *testing.T) {
err = test.GetProbeEvent(func() error {
if err := syscall.Mount(mntPath, dstMntPath, "bind", syscall.MS_BIND, ""); err != nil {
return fmt.Errorf("could not create bind mount: %w", err)
}
return nil
}, func(event *model.Event) bool {
mntID = event.Mount.MountID
if !assert.Equal(t, "mount", event.GetType(), "wrong event type") {
return true
}
if !ebpfLessEnabled {
assert.Equal(t, false, event.Mount.Detached, "Mount should not be detached")
assert.Equal(t, true, event.Mount.Visible, "Mount should be visible")
assert.Equal(t, model.MountOriginEvent, event.Mount.Origin, "Incorrect mount source")
assert.NotEqual(t, 0, event.Mount.NamespaceInode, "Mount namespace inode not captured")
}
// filter by pid
if event.ProcessContext.Pid != testSuitePid {
return false
}
return assert.Equal(t, "/"+dstMntBasename, event.Mount.MountPointStr, "wrong mount point") &&
assert.Equal(t, "xfs", event.Mount.GetFSType(), "wrong mount fs type")
}, 3*time.Second, model.FileMountEventType)
if err != nil {
t.Fatal(err)
}
})
t.Run("mount_resolver", func(t *testing.T) {
file := testDrive.Path(dstMntBasename, "test-mount")
f, err := os.Create(file)
if err != nil {
t.Fatal(err)
}
if err = f.Close(); err != nil {
t.Fatal(err)
}
defer os.Remove(file)
test.WaitSignalFromRule(t, func() error {
return os.Chmod(file, 0707)
}, func(event *model.Event, _ *rules.Rule) {
assert.Equal(t, "chmod", event.GetType(), "wrong event type")
assert.Equal(t, file, event.Chmod.File.PathnameStr, "wrong path")
}, "test_rule")
})
releaseFile, err := os.Create(path.Join(dstMntPath, "test-release"))
if err != nil {
t.Fatal(err)
}
defer releaseFile.Close()
t.Run("umount", func(t *testing.T) {
err = test.GetProbeEvent(func() error {
// Test umount
if err = syscall.Unmount(dstMntPath, syscall.MNT_DETACH); err != nil {
return fmt.Errorf("could not unmount test-mount: %w", err)
}
return nil
}, func(event *model.Event) bool {
if !assert.Equal(t, "umount", event.GetType(), "wrong event type") {
return true
}
// filter by process
if event.ProcessContext.Pid != testSuitePid {
return false
}
return ebpfLessEnabled || assert.Equal(t, mntID, event.Umount.MountID, "wrong mount id")
}, 3*time.Second, model.FileUmountEventType)
if err != nil {
t.Error(err)
}
})
t.Run("release-mount", func(t *testing.T) {
test.WaitSignalFromRule(t, func() error {
return syscall.Fchownat(int(releaseFile.Fd()), "", 123, 123, unix.AT_EMPTY_PATH)
}, func(event *model.Event, rule *rules.Rule) {
assert.Equal(t, "chown", event.GetType(), "wrong event type")
assertTriggeredRule(t, rule, "test_rule_pending")
}, "test_rule_pending")
})
}
func TestMountPropagated(t *testing.T) {
SkipIfNotAvailable(t)
// - testroot
// / dir1
// / test-drive (xfs mount)
// / dir-bind-mounted (bind mount of testroot/dir1)
// / test-drive (propagated)
// / test-file
ruleDefs := []*rules.RuleDefinition{{
ID: "test_rule",
Expression: `chmod.file.path == "{{.Root}}/dir1-bind-mounted/test-drive/test-file"`,
}}
test, err := newTestModule(t, nil, ruleDefs, withForceReload())
if err != nil {
t.Fatal(err)
}
defer test.Close()
dir1Path, _, err := test.Path("dir1")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir1Path)
testDrivePath := path.Join(dir1Path, "test-drive")
if err := os.MkdirAll(testDrivePath, 0755); err != nil {
t.Fatal(err)
}
defer os.RemoveAll(testDrivePath)
testDrive, err := newTestDrive(t, "xfs", []string{}, testDrivePath)
if err != nil {
t.Fatal(err)
}
defer func() {
if testEnvironment == DockerEnvironment {
testDrive.Close()
return
}
if err := testDrive.DetachDevice(); err != nil {
fmt.Printf("failed to detach device: %v", err)
}
}()
dir1BindMntPath, _, err := test.Path("dir1-bind-mounted")
if err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(dir1BindMntPath, 0755); err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir1BindMntPath)
bindMnt := newTestMount(
dir1BindMntPath,
withSource(dir1Path),
withFlags(syscall.MS_BIND|syscall.MS_REC),
)
if err := bindMnt.mount(); err != nil {
t.Fatal(err)
}
defer func() {
testPropagatedDrivePath := path.Join(dir1BindMntPath, "test-drive")
if err := syscall.Unmount(testPropagatedDrivePath, syscall.MNT_FORCE); err != nil {
t.Logf("Failed to unmount %s", testPropagatedDrivePath)
}
if err := bindMnt.unmount(syscall.MNT_FORCE); err != nil {
t.Logf("Failed to umount %s", bindMnt.target)
}
}()
file, _, err := test.Path("dir1-bind-mounted/test-drive/test-file")
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(file, []byte{}, 0700); err != nil {
t.Fatal(err)
}
t.Run("bind-mounted-chmod", func(t *testing.T) {
test.WaitSignalFromRule(t, func() error {
return os.Chmod(file, 0700)
}, func(event *model.Event, _ *rules.Rule) {
assert.Equal(t, "chmod", event.GetType(), "wrong event type")
assert.Equal(t, file, event.Chmod.File.PathnameStr, "wrong path")
}, "test_rule")
})
}
func testMountSnapshot(t *testing.T) {
SkipIfNotAvailable(t)
// / testDrive
// / rootA
// / tmpfs-mount (tmpfs)
// / test-bind-source
// / test-bind-target (bind mount of test-bind-source)
// / rootB
// ... (same hierarchy as rootA)
// / test-bind-testdrive
testDrive, err := newTestDrive(t, "xfs", []string{}, "")
if err != nil {
t.Fatal(err)
}
defer testDrive.Close()
rootA := testDrive.Path("rootA")
rootB := testDrive.Path("rootB")
createHierarchy := func(root string) (tmpfsMount, bindMount *testMount, err error) {
defer func() {
if err != nil {
if bindMount != nil {
bindMount.unmount(0)
}
if tmpfsMount != nil {
tmpfsMount.unmount(0)
}
}
}()
tmpfsPath := path.Join(root, "tmpfs-mount")
if err = os.MkdirAll(tmpfsPath, 0755); err != nil {
return nil, nil, err
}
// tmpfs mount
tmpfsMount = newTestMount(
tmpfsPath,
withFSType("tmpfs"),
)
if err := tmpfsMount.mount(); err != nil {
return nil, nil, fmt.Errorf("could not create tmpfs mount: %s", err)
}
bindSourcePath := tmpfsMount.path("test-bind-source")
if err = os.Mkdir(bindSourcePath, 0755); err != nil {
return nil, nil, err
}
bindTargetPath := path.Join(root, "test-bind-target")
if err = os.Mkdir(bindTargetPath, 0755); err != nil {
return nil, nil, err
}
// bind mount
bindMount = newTestMount(
bindTargetPath,
withSource(bindSourcePath),
withFlags(syscall.MS_BIND),
)
if err = bindMount.mount(); err != nil {
return nil, nil, fmt.Errorf("could not create bind mount: %s", err)
}
return
}
tmpfsMountA, bindMountA, err := createHierarchy(rootA)
if err != nil {
t.Fatal(err)
}
defer tmpfsMountA.unmount(0)
defer bindMountA.unmount(0)
test, err := newTestModule(t, nil, nil, withDynamicOpts(dynamicTestOpts{testDir: testDrive.Root()}), withForceReload())
if err != nil {
t.Fatal(err)
}
defer test.Close()
p, ok := test.probe.PlatformProbe.(*sprobe.EBPFProbe)
if !ok {
t.Skip("not supported")
}
tmpfsMountB, bindMountB, err := createHierarchy(rootB)
if err != nil {
t.Fatal(err)
}
defer tmpfsMountB.unmount(0)
defer bindMountB.unmount(0)
mountResolver := p.Resolvers.MountResolver
pid := utils.Getpid()
mounts, err := kernel.ParseMountInfoFile(int32(pid))
if err != nil {
t.Fatal(err)
}
// we need to wait for the mount events of the hierarchy B to be processed
time.Sleep(5 * time.Second)
checkSnapshotAndModelMatch := func(mntInfo *mountinfo.Info) {
dev := utils.Mkdev(uint32(mntInfo.Major), uint32(mntInfo.Minor))
mount, mountSource, mountOrigin, err := mountResolver.ResolveMount(uint32(mntInfo.ID), pid)
if err != nil {
t.Error(err)
return
}
assert.Equal(t, model.MountSourceMountID, mountSource)
assert.NotEqual(t, model.MountOriginUnknown, mountOrigin)
assert.Equal(t, uint32(mntInfo.ID), mount.MountID, "snapshot and model mount ID mismatch")
assert.Equal(t, uint32(mntInfo.Parent), mount.ParentPathKey.MountID, "snapshot and model parent mount ID mismatch")
assert.Equal(t, dev, mount.Device, "snapshot and model device mismatch")
assert.Equal(t, mntInfo.FSType, mount.FSType, "snapshot and model fstype mismatch")
assert.Equal(t, mntInfo.Root, mount.RootStr, "snapshot and model root mismatch")
mountPointPath, mountSource, mountOrigin, err := mountResolver.ResolveMountPath(mount.MountID, pid)
if err != nil {
t.Errorf("failed to resolve mountpoint path of mountpoint with id %d", mount.MountID)
}
assert.Equal(t, mntInfo.Mountpoint, mountPointPath, "snapshot and model mountpoint path mismatch")
assert.Equal(t, model.MountSourceMountID, mountSource)
assert.NotEqual(t, model.MountOriginUnknown, mountOrigin)
}
mntResolved := 0
for _, mntInfo := range mounts {
if strings.HasSuffix(mntInfo.Mountpoint, "rootA/tmpfs-mount") {
mntResolved |= 1
checkSnapshotAndModelMatch(mntInfo)
} else if strings.HasSuffix(mntInfo.Mountpoint, "rootA/test-bind-target") {
mntResolved |= 2
checkSnapshotAndModelMatch(mntInfo)
} else if strings.HasSuffix(mntInfo.Mountpoint, "rootB/tmpfs-mount") {
mntResolved |= 4
checkSnapshotAndModelMatch(mntInfo)
} else if strings.HasSuffix(mntInfo.Mountpoint, "rootB/test-bind-target") {
mntResolved |= 8
checkSnapshotAndModelMatch(mntInfo)
}
}
assert.Equal(t, 1|2|4|8, mntResolved)
}
func TestMountSnapshotListmount(t *testing.T) {
SkipIfNotAvailable(t)
t.Setenv("DD_EVENT_MONITORING_CONFIG_SNAPSHOT_USING_LISTMOUNT", "true")
testMountSnapshot(t)
}
func TestMountSnapshotProcfs(t *testing.T) {
SkipIfNotAvailable(t)
t.Setenv("DD_EVENT_MONITORING_CONFIG_SNAPSHOT_USING_LISTMOUNT", "false")
testMountSnapshot(t)
}
func TestMountEvent(t *testing.T) {
SkipIfNotAvailable(t)
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
testDrive, err := newTestDrive(t, "xfs", []string{}, "")
if err != nil {
t.Fatal(err)
}
defer testDrive.Close()
tmpfsMountPointName := "tmpfs_mnt"
bindMountPointName := "bind_mnt"
bindMountSourceName := "bind_src"
ruleDefs := []*rules.RuleDefinition{
{
ID: "test_mount_tmpfs",
Expression: fmt.Sprintf(`mount.mountpoint.path == "{{.Root}}/%s" && mount.fs_type == "tmpfs" && process.file.path == "%s"`, tmpfsMountPointName, executable),
},
{
ID: "test_mount_bind",
Expression: fmt.Sprintf(`mount.mountpoint.path == "{{.Root}}/%s" && mount.source.path == "{{.Root}}/%s" && mount.fs_type == "%s" && process.file.path == "%s"`, bindMountPointName, bindMountSourceName, testDrive.FSType(), executable),
},
{
ID: "test_mount_in_container_root",
Expression: `mount.mountpoint.path == "/host_root" && mount.source.path == "/" && mount.fs_type != "overlay" && process.container.id != ""`,
},
}
test, err := newTestModule(t, nil, ruleDefs, withDynamicOpts(dynamicTestOpts{testDir: testDrive.Root()}))
if err != nil {
t.Fatal(err)
}
defer test.Close()
tmpfsMountPointPath := testDrive.Path(tmpfsMountPointName)
if err = os.Mkdir(tmpfsMountPointPath, 0755); err != nil {
t.Fatal(err)
}
bindMountPointPath := testDrive.Path(bindMountPointName)
if err = os.Mkdir(bindMountPointPath, 0755); err != nil {
t.Fatal(err)
}
bindMountSourcePath := testDrive.Path(bindMountSourceName)
if err = os.Mkdir(bindMountSourcePath, 0755); err != nil {
t.Fatal(err)
}
t.Run("mount-tmpfs", func(t *testing.T) {
tmpfsMount := newTestMount(
tmpfsMountPointPath,
withFSType("tmpfs"),
)
test.WaitSignalFromRule(t, func() error {
if err := tmpfsMount.mount(); err != nil {
return err
}
return tmpfsMount.unmount(syscall.MNT_FORCE)
}, func(event *model.Event, rule *rules.Rule) {
if !ebpfLessEnabled {
assert.Equal(t, model.MountOriginEvent, event.Mount.Origin, "Incorrect mount source")
assert.Equal(t, false, event.Mount.Detached, "Mount should not be detached")
assert.Equal(t, true, event.Mount.Visible, "Mount should be visible")
assert.NotEqual(t, 0, event.Mount.NamespaceInode, "Mount namespace inode not captured")
}
assertTriggeredRule(t, rule, "test_mount_tmpfs")
assertFieldEqual(t, event, "mount.mountpoint.path", tmpfsMountPointPath)
assertFieldEqual(t, event, "mount.fs_type", "tmpfs")
assertFieldEqual(t, event, "process.file.path", executable)
test.validateMountSchema(t, event)
validateSyscallContext(t, event, "$.syscall.mount.path")
validateSyscallContext(t, event, "$.syscall.mount.destination_path")
validateSyscallContext(t, event, "$.syscall.mount.fs_type")
}, "test_mount_tmpfs")
})
t.Run("mount-bind", func(t *testing.T) {
bindMount := newTestMount(
bindMountPointPath,
withSource(bindMountSourcePath),
withFlags(syscall.MS_BIND),
)
test.WaitSignalFromRule(t, func() error {
if err := bindMount.mount(); err != nil {
return err
}
return bindMount.unmount(syscall.MNT_FORCE)
}, func(event *model.Event, rule *rules.Rule) {
assertTriggeredRule(t, rule, "test_mount_bind")
if !ebpfLessEnabled {
assert.Equal(t, false, event.Mount.Detached, "Mount should not be detached")
assert.Equal(t, true, event.Mount.Visible, "Mount should be visible")
assert.Equal(t, model.MountOriginEvent, event.Mount.Origin, "Incorrect mount source")
assert.NotEqual(t, 0, event.Mount.NamespaceInode, "Mount namespace inode not captured")
}
assertFieldEqual(t, event, "mount.mountpoint.path", bindMountPointPath)
assertFieldEqual(t, event, "mount.source.path", bindMountSourcePath)
assertFieldEqual(t, event, "mount.fs_type", testDrive.FSType())
assertFieldEqual(t, event, "process.file.path", executable)
test.validateMountSchema(t, event)
validateSyscallContext(t, event, "$.syscall.mount.path")
validateSyscallContext(t, event, "$.syscall.mount.destination_path")
validateSyscallContext(t, event, "$.syscall.mount.fs_type")
}, "test_mount_bind")
})
const dockerMountDest = "/host_root"
t.Run("mount-in-container-root", func(t *testing.T) {
SkipIfNotAvailable(t)
flake.MarkOnJobName(t, "ubuntu_25.10")
if _, err := whichNonFatal("docker"); err != nil {
t.Skip("Skip test where docker is unavailable")
}
checkKernelCompatibility(t, "broken containerd support on Suse 12", func(kv *ebpfkernel.Version) bool {
return kv.IsSuse12Kernel()
})
wrapperTruePositive, err := newDockerCmdWrapper("/", dockerMountDest, "alpine", "")
if err != nil {
t.Fatalf("failed to start docker wrapper: %v", err)
}
test.WaitSignalFromRule(t, func() error {
if _, err := wrapperTruePositive.start(); err != nil {
return err
}
if _, err := wrapperTruePositive.stop(); err != nil {
return err
}
return nil
}, func(event *model.Event, rule *rules.Rule) {
assertTriggeredRule(t, rule, "test_mount_in_container_root")
assertFieldEqual(t, event, "mount.mountpoint.path", "/host_root")
assertFieldEqual(t, event, "mount.source.path", "/")
assertFieldNotEqual(t, event, "mount.fs_type", "overlay")
assertFieldNotEmpty(t, event, "process.container.id", "container id shouldn't be empty")
assert.NotEqual(t, 0, event.Mount.NamespaceInode, "Mount namespace inode not captured")
test.validateMountSchema(t, event)
validateSyscallContext(t, event, "$.syscall.mount.path")
validateSyscallContext(t, event, "$.syscall.mount.destination_path")
validateSyscallContext(t, event, "$.syscall.mount.fs_type")
}, "test_mount_in_container_root")
})
t.Run("mount-in-container-legitimate", func(t *testing.T) {
if _, err := whichNonFatal("docker"); err != nil {
t.Skip("Skip test where docker is unavailable")
}
checkKernelCompatibility(t, "broken containerd support on Suse 12", func(kv *ebpfkernel.Version) bool {
return kv.IsSuse12Kernel()
})
legitimateSourcePath := testDrive.Path("legitimate_source")
if err = os.Mkdir(legitimateSourcePath, 0755); err != nil {
t.Fatal(err)
}
wrapperFalsePositive, err := newDockerCmdWrapper(legitimateSourcePath, dockerMountDest, "alpine", "")
if err != nil {
t.Fatalf("failed to start docker wrapper: %v", err)
}
err = test.GetSignal(t, func() error {
if _, err := wrapperFalsePositive.start(); err != nil {
return err
}
if _, err := wrapperFalsePositive.stop(); err != nil {
return err
}
return nil
}, func(event *model.Event, rule *rules.Rule) {
t.Errorf("shouldn't get an event: event %s matched rule %s", test.debugEvent(event), rule.Expression)
assert.NotEqual(t, 0, event.Mount.NamespaceInode, "Mount namespace inode not captured")
})
if err == nil {
t.Error("shouldn't get an event")
} else if otherErr, ok := err.(ErrTimeout); !ok {
t.Fatal(otherErr)
}
})
}