-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathaction_test.go
More file actions
1522 lines (1308 loc) · 48 KB
/
Copy pathaction_test.go
File metadata and controls
1522 lines (1308 loc) · 48 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
// 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 (
"context"
"errors"
"fmt"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"syscall"
"testing"
"time"
"github.com/avast/retry-go/v4"
"github.com/oliveagle/jsonpath"
"github.com/stretchr/testify/assert"
"go.uber.org/atomic"
"github.com/DataDog/datadog-agent/pkg/config/env"
"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/testutil/flake"
)
func TestActionKill(t *testing.T) {
SkipIfNotAvailable(t)
if !ebpfLessEnabled {
checkKernelCompatibility(t, "agent is running in container mode", func(_ *kernel.Version) bool {
return env.IsContainerized()
})
}
ruleDefs := []*rules.RuleDefinition{
{
ID: "kill_action_usr2",
Expression: `process.file.name == "syscall_tester" && open.file.path == "{{.Root}}/test-kill-action-usr2"`,
Actions: []*rules.ActionDefinition{
{
Kill: &rules.KillDefinition{
Signal: "SIGUSR2",
},
},
},
},
{
ID: "kill_action_kill",
Expression: `process.file.name == "syscall_tester" && open.file.path == "{{.Root}}/test-kill-action-kill"`,
Actions: []*rules.ActionDefinition{
{
Kill: &rules.KillDefinition{
Signal: "SIGKILL",
},
},
},
},
}
test, err := newTestModule(t, nil, ruleDefs)
if err != nil {
t.Fatal(err)
}
defer test.Close()
syscallTester, err := loadSyscallTester(t, test, "syscall_tester")
if err != nil {
t.Fatal(err)
}
t.Run("kill-action-usr2", func(t *testing.T) {
testFile, _, err := test.Path("test-kill-action-usr2")
if err != nil {
t.Fatal(err)
}
defer os.Remove(testFile)
err = test.GetEventSent(t, func() error {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGUSR1)
defer signal.Stop(sigCh)
timeoutCtx, cancel := context.WithTimeout(context.Background(), 7*time.Second)
defer cancel()
if err := runSyscallTesterFunc(
timeoutCtx, t, syscallTester,
"set-signal-handler", ";",
"open", testFile, ";",
"sleep", "1", ";",
"open", syscallTester, ";",
"wait-signal", ";",
"signal", "sigusr1", strconv.Itoa(int(os.Getpid())), ";",
"sleep", "1",
); err != nil {
t.Error(err)
}
select {
case <-sigCh:
case <-time.After(time.Second * 3):
t.Error("signal timeout")
}
return nil
}, func(_ *rules.Rule, _ *model.Event) bool {
return true
}, time.Second*3, "kill_action_usr2")
if err != nil {
t.Error(err)
}
err = retry.Do(func() error {
msg := test.msgSender.getMsg("kill_action_usr2")
if msg == nil {
return errors.New("not found")
}
validateMessageSchema(t, string(msg.Data))
jsonPathValidation(test, msg.Data, func(_ *testModule, obj interface{}) {
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.signal == 'SIGUSR2')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.status == 'performed')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
})
return nil
}, retry.Delay(200*time.Millisecond), retry.Attempts(30), retry.DelayType(retry.FixedDelay))
assert.NoError(t, err)
})
t.Run("kill-action-kill", func(t *testing.T) {
testFile, _, err := test.Path("test-kill-action-kill")
if err != nil {
t.Fatal(err)
}
defer os.Remove(testFile)
err = test.GetEventSent(t, func() error {
ch := make(chan bool, 1)
go func() {
timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := exec.CommandContext(timeoutCtx, syscallTester, "open", testFile, ";", "sleep", "1", ";", "open", syscallTester, ";", "sleep", "5")
_ = cmd.Run()
ch <- true
}()
select {
case <-ch:
case <-time.After(time.Second * 3):
t.Error("signal timeout")
}
return nil
}, func(_ *rules.Rule, _ *model.Event) bool {
return true
}, time.Second*5, "kill_action_kill")
if err != nil {
t.Error(err)
}
err = retry.Do(func() error {
msg := test.msgSender.getMsg("kill_action_kill")
if msg == nil {
return errors.New("not found")
}
validateMessageSchema(t, string(msg.Data))
jsonPathValidation(test, msg.Data, func(_ *testModule, obj interface{}) {
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.signal == 'SIGKILL')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.exited_at =~ /20.*/)]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.status == 'performed')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
})
return nil
}, retry.Delay(200*time.Millisecond), retry.Attempts(30), retry.DelayType(retry.FixedDelay))
assert.NoError(t, err)
})
}
func TestActionKillExcludeBinary(t *testing.T) {
SkipIfNotAvailable(t)
checkKernelCompatibility(t, "agent is running in container mode", func(_ *kernel.Version) bool {
return env.IsContainerized()
})
ruleDefs := []*rules.RuleDefinition{
{
ID: "kill_action_kill_exclude",
Expression: `exec.file.name == "sleep" && exec.argv in ["1234567"]`,
Actions: []*rules.ActionDefinition{
{
Kill: &rules.KillDefinition{
Signal: "SIGKILL",
},
},
},
},
}
executable := which(t, "sleep")
test, err := newTestModule(t, nil, ruleDefs, withStaticOpts(testOpts{enforcementExcludeBinary: executable}))
if err != nil {
t.Fatal(err)
}
defer test.Close()
sleepCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
killed := atomic.NewBool(false)
err = test.GetEventSent(t, func() error {
go func() {
cmd := exec.CommandContext(sleepCtx, "sleep", "1234567")
_ = cmd.Run()
killed.Store(true)
}()
return nil
}, func(_ *rules.Rule, _ *model.Event) bool {
return true
}, time.Second*5, "kill_action_kill_exclude")
if err != nil {
t.Error("should get an event")
}
if killed.Load() {
t.Error("shouldn't be killed")
}
}
func TestActionKillRuleSpecific(t *testing.T) {
SkipIfNotAvailable(t)
if !ebpfLessEnabled {
checkKernelCompatibility(t, "agent is running in container mode", func(_ *kernel.Version) bool {
return env.IsContainerized()
})
}
ruleDefs := []*rules.RuleDefinition{
{
ID: "kill_action_kill",
Expression: `process.file.name == "syscall_tester" && open.file.path == "{{.Root}}/test-kill-action-kill"`,
Actions: []*rules.ActionDefinition{
{
Kill: &rules.KillDefinition{
Signal: "SIGKILL",
},
},
},
},
{
ID: "kill_action_no_kill",
Expression: `process.file.name == "syscall_tester" && open.file.path == "{{.Root}}/test-kill-action-kill"`,
},
}
test, err := newTestModule(t, nil, ruleDefs)
if err != nil {
t.Fatal(err)
}
defer test.Close()
syscallTester, err := loadSyscallTester(t, test, "syscall_tester")
if err != nil {
t.Fatal(err)
}
testFile, _, err := test.Path("test-kill-action-kill")
if err != nil {
t.Fatal(err)
}
defer os.Remove(testFile)
err = test.GetEventSent(t, func() error {
ch := make(chan bool, 1)
go func() {
timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := exec.CommandContext(timeoutCtx, syscallTester, "open", testFile, ";", "sleep", "1", ";", "open", syscallTester, ";", "sleep", "5")
_ = cmd.Run()
ch <- true
}()
select {
case <-ch:
case <-time.After(time.Second * 3):
t.Error("signal timeout")
}
return nil
}, func(_ *rules.Rule, _ *model.Event) bool {
return true
}, time.Second*5, "kill_action_kill")
if err != nil {
t.Error(err)
}
err = retry.Do(func() error {
msg := test.msgSender.getMsg("kill_action_kill")
if msg == nil {
return errors.New("not found")
}
validateMessageSchema(t, string(msg.Data))
jsonPathValidation(test, msg.Data, func(_ *testModule, obj interface{}) {
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.signal == 'SIGKILL')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.exited_at =~ /20.*/)]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.status == 'performed')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
})
return nil
}, retry.Delay(200*time.Millisecond), retry.Attempts(30), retry.DelayType(retry.FixedDelay))
assert.NoError(t, err)
err = retry.Do(func() error {
msg := test.msgSender.getMsg("kill_action_no_kill")
if msg == nil {
return errors.New("not found")
}
validateMessageSchema(t, string(msg.Data))
jsonPathValidation(test, msg.Data, func(_ *testModule, obj interface{}) {
if _, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions`); err == nil {
t.Errorf("unexpected rule action %s", string(msg.Data))
}
})
return nil
}, retry.Delay(200*time.Millisecond), retry.Attempts(30), retry.DelayType(retry.FixedDelay))
assert.NoError(t, err)
}
func testActionKillDisarm(t *testing.T, test *testModule, sleep, syscallTester string, disarmerPeriod time.Duration) {
t.Helper()
testKillActionSuccess := func(t *testing.T, ruleID string, cmdFunc func(context.Context)) {
test.msgSender.flush()
err := test.GetEventSent(t, func() error {
ch := make(chan bool, 1)
go func() {
timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmdFunc(timeoutCtx)
ch <- true
}()
select {
case <-ch:
case <-time.After(time.Second * 8):
t.Error("signal timeout")
}
return nil
}, func(_ *rules.Rule, _ *model.Event) bool {
return true
}, time.Second*5, ruleID)
if err != nil {
t.Error(err)
}
err = retry.Do(func() error {
msg := test.msgSender.getMsg(ruleID)
if msg == nil {
return errors.New("not found")
}
validateMessageSchema(t, string(msg.Data))
jsonPathValidation(test, msg.Data, func(_ *testModule, obj interface{}) {
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.signal == 'SIGKILL')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.exited_at =~ /20.*/)]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.status == 'performed')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
})
return nil
}, retry.Delay(200*time.Millisecond), retry.Attempts(30), retry.DelayType(retry.FixedDelay))
assert.NoError(t, err)
}
testKillActionDisarmed := func(t *testing.T, ruleID string, cmdFunc func(context.Context)) {
test.msgSender.flush()
err := test.GetEventSent(t, func() error {
cmdFunc(nil)
return nil
}, func(_ *rules.Rule, _ *model.Event) bool {
return true
}, time.Second*5, ruleID)
if err != nil {
t.Error(err)
}
err = retry.Do(func() error {
msg := test.msgSender.getMsg(ruleID)
if msg == nil {
return errors.New("not found")
}
validateMessageSchema(t, string(msg.Data))
jsonPathValidation(test, msg.Data, func(_ *testModule, obj interface{}) {
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.signal == 'SIGKILL')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.status == 'rule_disarmed')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
})
return nil
}, retry.Delay(200*time.Millisecond), retry.Attempts(30), retry.DelayType(retry.FixedDelay))
assert.NoError(t, err)
}
t.Run("executable", func(t *testing.T) {
// test that we can kill processes with the same executable more than once
for i := 0; i < 2; i++ {
t.Logf("test iteration %d", i)
testKillActionSuccess(t, "kill_action_disarm_executable", func(ctx context.Context) {
cmd := exec.CommandContext(ctx, syscallTester, "sleep", "5")
cmd.Env = []string{"TARGETTOKILL=1"}
_ = cmd.Run()
})
}
// test that another executable disarms the kill action
testKillActionDisarmed(t, "kill_action_disarm_executable", func(_ context.Context) {
cmd := exec.Command(sleep, "1")
cmd.Env = []string{"TARGETTOKILL=1"}
_ = cmd.Run()
})
// test that the kill action is re-armed after both executable cache entries have expired
// sleep for: (TTL + cache flush period + 1s) to ensure the cache is flushed
time.Sleep(disarmerPeriod + 5*time.Second + 1*time.Second)
testKillActionSuccess(t, "kill_action_disarm_executable", func(_ context.Context) {
cmd := exec.Command(sleep, "1")
cmd.Env = []string{"TARGETTOKILL=1"}
_ = cmd.Run()
})
})
t.Run("container", func(t *testing.T) {
dockerInstance, err := test.StartADocker()
if err != nil {
t.Fatalf("failed to start a Docker instance: %v", err)
}
defer dockerInstance.stop()
// test that we can kill processes within the same container more than once
for i := 0; i < 2; i++ {
t.Logf("test iteration %d", i)
testKillActionSuccess(t, "kill_action_disarm_container", func(_ context.Context) {
cmd := dockerInstance.Command("env", []string{"-i", "-", "TARGETTOKILL=1", "sleep", "5"}, []string{})
_ = cmd.Run()
})
}
newDockerInstance, err := test.StartADocker()
if err != nil {
t.Fatalf("failed to start a second Docker instance: %v", err)
}
defer newDockerInstance.stop()
// test that another container disarms the kill action
testKillActionDisarmed(t, "kill_action_disarm_container", func(_ context.Context) {
cmd := newDockerInstance.Command("env", []string{"-i", "-", "TARGETTOKILL=1", "sleep", "1"}, []string{})
_ = cmd.Run()
})
// test that the kill action is re-armed after both container cache entries have expired
// sleep for: (TTL + cache flush period + 1s) to ensure the cache is flushed
time.Sleep(disarmerPeriod + 5*time.Second + 1*time.Second)
testKillActionSuccess(t, "kill_action_disarm_container", func(_ context.Context) {
cmd := newDockerInstance.Command("env", []string{"-i", "-", "TARGETTOKILL=1", "sleep", "5"}, []string{})
_ = cmd.Run()
})
})
}
func TestActionKillDisarm(t *testing.T) {
SkipIfNotAvailable(t)
if testEnvironment == DockerEnvironment {
t.Skip("Skip test spawning docker containers on docker")
}
if _, err := whichNonFatal("docker"); err != nil {
t.Skip("Skip test where docker is unavailable")
}
checkKernelCompatibility(t, "broken containerd support on Suse 12", func(kv *kernel.Version) bool {
return kv.IsSuse12Kernel()
})
checkKernelCompatibility(t, "agent is running in container mode", func(_ *kernel.Version) bool {
return env.IsContainerized()
})
sleep := which(t, "sleep")
const (
enforcementDisarmerPeriod = 4 * time.Second
)
ruleDefs := []*rules.RuleDefinition{
{
ID: "kill_action_disarm_executable",
Expression: `exec.envs in ["TARGETTOKILL"] && process.container.id == ""`,
Actions: []*rules.ActionDefinition{
{
Kill: &rules.KillDefinition{
Signal: "SIGKILL",
},
},
},
},
{
ID: "kill_action_disarm_container",
Expression: `exec.envs in ["TARGETTOKILL"] && process.container.id != ""`,
Actions: []*rules.ActionDefinition{
{
Kill: &rules.KillDefinition{
Signal: "SIGKILL",
},
},
},
},
}
test, err := newTestModule(t, nil, ruleDefs, withStaticOpts(testOpts{
enforcementDisarmerContainerEnabled: true,
enforcementDisarmerContainerMaxAllowed: 1,
enforcementDisarmerContainerPeriod: enforcementDisarmerPeriod,
enforcementDisarmerExecutableEnabled: true,
enforcementDisarmerExecutableMaxAllowed: 1,
enforcementDisarmerExecutablePeriod: enforcementDisarmerPeriod,
eventServerRetention: 1 * time.Nanosecond,
}))
if err != nil {
t.Fatal(err)
}
defer test.Close()
syscallTester, err := loadSyscallTester(t, test, "syscall_tester")
if err != nil {
t.Fatal(err)
}
testActionKillDisarm(t, test, sleep, syscallTester, enforcementDisarmerPeriod)
}
func TestActionHash(t *testing.T) {
SkipIfNotAvailable(t)
if testEnvironment == DockerEnvironment {
t.Skip("skipping in docker, not sharing the same pid ns and doesn't have a container ID")
}
ruleDefs := []*rules.RuleDefinition{
{
ID: "hash_action_open",
Expression: `open.file.path == "{{.Root}}/test-hash-action" && open.flags&O_CREAT == O_CREAT`,
Actions: []*rules.ActionDefinition{
{
Hash: &rules.HashDefinition{},
},
},
},
{
ID: "hash_action_exec",
Expression: `exec.file.path == "{{.Root}}/test-hash-action-exec_touch"`,
Actions: []*rules.ActionDefinition{
{
Hash: &rules.HashDefinition{},
},
},
},
}
test, err := newTestModule(t, nil, ruleDefs)
if err != nil {
t.Fatal(err)
}
defer test.Close()
testFile, _, err := test.Path("test-hash-action")
if err != nil {
t.Fatal(err)
}
// it's important that this ends with `touch` because for example ubuntu 25.10
// uses the suffix to know which "function/utility" is running
// https://github.com/uutils/coreutils/blob/909da503713f39f8e36b1ff077841c9cc13d920b/src/bin/coreutils.rs#L60
testExecutable, _, err := test.Path("test-hash-action-exec_touch")
if err != nil {
t.Fatal(err)
}
if err = copyFile(which(t, "touch"), testExecutable, 0755); err != nil {
t.Fatal(err)
}
defer os.Remove(testExecutable)
syscallTester, err := loadSyscallTester(t, test, "syscall_tester")
if err != nil {
t.Fatal(err)
}
done := make(chan bool, 10)
t.Run("open-process-exit", func(t *testing.T) {
test.msgSender.flush()
test.WaitSignalFromRule(t, func() error {
go func() {
timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := runSyscallTesterFunc(
timeoutCtx, t, syscallTester,
"slow-write", "2", testFile, "aaa",
); err != nil {
t.Error(err)
}
done <- true
}()
return nil
}, func(_ *model.Event, rule *rules.Rule) {
assertTriggeredRule(t, rule, "hash_action_open")
}, "hash_action_open")
err = retry.Do(func() error {
msg := test.msgSender.getMsg("hash_action_open")
if msg == nil {
return errors.New("not found")
}
validateMessageSchema(t, string(msg.Data))
jsonPathValidation(test, msg.Data, func(_ *testModule, obj interface{}) {
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.state == 'Done')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.trigger == 'process_exit')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
if el, err := jsonpath.JsonPathLookup(obj, `$.file.hashes`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
})
return nil
}, retry.Delay(500*time.Millisecond), retry.Attempts(30), retry.DelayType(retry.FixedDelay))
assert.NoError(t, err)
<-done
})
t.Run("open-timeout", func(t *testing.T) {
test.msgSender.flush()
test.WaitSignalFromRule(t, func() error {
go func() {
timeoutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := runSyscallTesterFunc(
timeoutCtx, t, syscallTester,
// exceed the file hasher timeout, use fork to force an event that will trigger the flush mechanism
"slow-write", "2", testFile, "aaa", ";", "sleep", "4", ";", "fork", ";", "sleep", "1",
); err != nil {
t.Error(err)
}
done <- true
}()
return nil
}, func(_ *model.Event, rule *rules.Rule) {
assertTriggeredRule(t, rule, "hash_action_open")
}, "hash_action_open")
err = retry.Do(func() error {
msg := test.msgSender.getMsg("hash_action_open")
if msg == nil {
return errors.New("not found")
}
validateMessageSchema(t, string(msg.Data))
jsonPathValidation(test, msg.Data, func(_ *testModule, obj interface{}) {
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.state == 'Done')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.trigger == 'timeout')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
if el, err := jsonpath.JsonPathLookup(obj, `$.file.hashes`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
})
return nil
}, retry.Delay(500*time.Millisecond), retry.Attempts(30), retry.DelayType(retry.FixedDelay))
assert.NoError(t, err)
<-done
})
t.Run("exec", func(t *testing.T) {
flake.MarkOnJobName(t, "ubuntu_25.10")
test.msgSender.flush()
test.WaitSignalFromRule(t, func() error {
cmd := exec.Command(testExecutable, "/tmp/aaa")
out, err := cmd.CombinedOutput()
if err != nil {
t.Logf("output: %s", string(out))
}
return err
}, func(_ *model.Event, rule *rules.Rule) {
assertTriggeredRule(t, rule, "hash_action_exec")
}, "hash_action_exec")
err = retry.Do(func() error {
msg := test.msgSender.getMsg("hash_action_exec")
if msg == nil {
return errors.New("not found")
}
validateMessageSchema(t, string(msg.Data))
jsonPathValidation(test, msg.Data, func(_ *testModule, obj interface{}) {
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.state == 'Done')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
if el, err := jsonpath.JsonPathLookup(obj, `$.agent.rule_actions[?(@.trigger == 'process_exit')]`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
if el, err := jsonpath.JsonPathLookup(obj, `$.file.hashes`); err != nil || el == nil || len(el.([]interface{})) == 0 {
t.Errorf("element not found %s => %v", string(msg.Data), err)
}
})
return nil
}, retry.Delay(500*time.Millisecond), retry.Attempts(30), retry.DelayType(retry.FixedDelay))
assert.NoError(t, err)
})
}
func TestActionKillWithSignature(t *testing.T) {
SkipIfNotAvailable(t)
if !ebpfLessEnabled {
checkKernelCompatibility(t, "agent is running in container mode", func(_ *kernel.Version) bool {
return env.IsContainerized()
})
}
// Create a temporary file that will be used in tail arguments
testFile, err := os.CreateTemp("", "test-kill-signature-*")
if err != nil {
t.Fatal(err)
}
testFilePath := testFile.Name()
testFile.Close()
defer os.Remove(testFilePath)
// Rule to trigger on exec of tail with the test file as argument
ruleDefs := []*rules.RuleDefinition{
{
ID: "test_exec_trigger",
Expression: `exec.file.name == "tail" && exec.argv in ["` + testFilePath + `"]`,
},
}
test, err := newTestModule(t, nil, ruleDefs)
if err != nil {
t.Fatal(err)
}
defer test.Close()
var capturedSignature string
var tailCmd *exec.Cmd
// Cleanup function to kill any remaining tail processes for this test file
cleanupTail := func() {
exec.Command("pkill", "-f", "tail -F "+testFilePath).Run()
}
defer cleanupTail()
// Start tail -F and wait for the rule to trigger
test.WaitSignalFromRule(t, func() error {
// Start tail
tailCmd = exec.Command("tail", "-F", testFilePath)
if err := tailCmd.Start(); err != nil {
return err
}
return nil
}, func(event *model.Event, rule *rules.Rule) {
assertTriggeredRule(t, rule, "test_exec_trigger")
// Capture the signature from the event
capturedSignature = event.FieldHandlers.ResolveSignature(event)
}, "test_exec_trigger")
// Verify we got a valid signature
if capturedSignature == "" {
t.Fatal("captured signature is empty")
}
// Verify that tail is still running
if tailCmd.ProcessState != nil && tailCmd.ProcessState.Exited() {
t.Fatal("tail process should still be running after first rule trigger")
}
// Create a new rule with kill action that matches the captured signature
firstTailPid := strconv.Itoa(tailCmd.Process.Pid)
newRuleDefs := []*rules.RuleDefinition{
{
ID: "test_exec_trigger",
Expression: `exec.file.name == "tail" && exec.argv in ["` + testFilePath + `"] && process.pid != ` + firstTailPid,
},
{
ID: "test_kill_with_signature",
Expression: `exec.file.name == "tail" && exec.argv in ["` + testFilePath + `"] && event.signature == "` + capturedSignature + `" && process.pid == ` + firstTailPid,
Actions: []*rules.ActionDefinition{
{
Kill: &rules.KillDefinition{
Signal: "SIGKILL",
Scope: "process",
DisableContainerDisarmer: true,
DisableExecutableDisarmer: true,
},
},
},
},
}
// Set the new policy and reload (without closing/restarting the module)
// On reload, exec events are replayed for running processes, so the kill rule should trigger
if err := setTestPolicy(commonCfgDir, nil, newRuleDefs); err != nil {
t.Fatalf("failed to set new policy: %v", err)
}
// Reload the policy and wait for the kill rule to trigger
// Use GetEventSent instead of WaitSignal because ActionReports are filled in HandleActions
// which is called AFTER RuleMatch (used by WaitSignal) but BEFORE SendEvent (used by GetEventSent)
err = test.GetEventSent(t, func() error {
err := test.reloadPolicies()
if err != nil {
return fmt.Errorf("failed to reload policies: %w", err)
}
// Trigger a small event to force the replay of cached events.
// The replay only happens in handleEvent when a new eBPF event arrives.
exec.Command("true").Run()
return nil
}, func(rule *rules.Rule, event *model.Event) bool {
assertTriggeredRule(t, rule, "test_kill_with_signature")
// Verify the kill action was performed using the event's action reports
assert.Equal(t, 1, len(event.ActionReports), "expected one action report")
if len(event.ActionReports) == 1 {
report := event.ActionReports[0]
if killReport, ok := report.(*sprobe.KillActionReport); ok {
assert.Equal(t, "SIGKILL", killReport.Signal, "unexpected signal")
assert.Equal(t, "process", killReport.Scope, "unexpected scope")
assert.Equal(t, sprobe.KillActionStatusPerformed, killReport.Status, "unexpected status")
}
}
return true
}, 10*time.Second, "test_kill_with_signature")
if err != nil {
t.Fatal(err)
}
// Verify that tail was killed
done := make(chan error, 1)
go func() {
done <- tailCmd.Wait()
}()
select {
case <-done:
case <-time.After(3 * time.Second):
t.Fatal("tail process should have been killed but is still running")
}
// Now start a new tail process - it should NOT be killed because it has a different signature
var tailCmd2 *exec.Cmd
test.WaitSignalFromRule(t, func() error {
tailCmd2 = exec.Command("tail", "-f", testFilePath)
return tailCmd2.Start()
}, func(_ *model.Event, rule *rules.Rule) {
// Only test_exec_trigger should match because the signature is different
assertTriggeredRule(t, rule, "test_exec_trigger")
}, "test_exec_trigger")
// Verify that the second tail is still running (not killed due to different signature)
done2 := make(chan error, 1)
go func() {
done2 <- tailCmd2.Wait()
}()
select {
case <-done2:
t.Fatal("second tail process should still be running (different signature)")
case <-time.After(3 * time.Second):
// Process is still running as expected
}
// Cleanup second tail
tailCmd2.Process.Kill()
<-done2 // Wait for the goroutine to finish instead of calling Wait() again
}
func TestActionKillContainerWithSignature(t *testing.T) {
SkipIfNotAvailable(t)
flake.MarkOnJobName(t, "cws_host")
if testEnvironment == DockerEnvironment {
t.Skip("Skip test spawning docker containers on docker")
}
checkKernelCompatibility(t, "skip on CentOS7", func(kv *kernel.Version) bool {
return kv.IsRH7Kernel()
})
if _, err := whichNonFatal("docker"); err != nil {
t.Skip("Skip test where docker is unavailable")
}
checkKernelCompatibility(t, "broken containerd support on Suse 12", func(kv *kernel.Version) bool {
return kv.IsSuse12Kernel()
})
checkKernelCompatibility(t, "agent is running in container mode", func(_ *kernel.Version) bool {
return env.IsContainerized()
})
// 1. Start a Docker container first
dockerInstance, err := newDockerCmdWrapper("/tmp", "/tmp", "alpine", "")
if err != nil {
t.Fatalf("failed to create docker wrapper: %v", err)
}
if _, err := dockerInstance.start(); err != nil {
t.Fatalf("failed to start docker: %v", err)
}
containerKilled := false
defer func() {
if !containerKilled {
dockerInstance.stop()
}
}()
// 2. Create a test file inside the container at a known path
testFilePath := "/tmp/test-container-kill-" + utils.RandString(8)
cmd := dockerInstance.Command("touch", []string{testFilePath}, []string{})
if err := cmd.Run(); err != nil {
t.Fatalf("failed to create test file in container: %v", err)
}
// 3. Initialize the test module with the rule pointing to the correct path
ruleDefs := []*rules.RuleDefinition{