-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
tester.go
226 lines (188 loc) · 5.28 KB
/
tester.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
// 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.
// Package selftests holds selftests related files
package selftests
import (
"os"
"sync"
"time"
"github.com/hashicorp/go-multierror"
"go.uber.org/atomic"
"github.com/DataDog/datadog-agent/pkg/security/config"
"github.com/DataDog/datadog-agent/pkg/security/probe"
"github.com/DataDog/datadog-agent/pkg/security/proto/api"
"github.com/DataDog/datadog-agent/pkg/security/secl/compiler/eval"
"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/serializers"
"github.com/DataDog/datadog-agent/pkg/util/log"
)
// SelfTest represent one self test
type SelfTest interface {
GetRuleDefinition() *rules.RuleDefinition
GenerateEvent() error
HandleEvent(selfTestEvent)
IsSuccess() bool
}
// SelfTester represents all the state needed to conduct rule injection test at startup
type SelfTester struct {
sync.Mutex
config *config.RuntimeSecurityConfig
waitingForEvent *atomic.Bool
eventChan chan selfTestEvent
probe *probe.Probe
success []eval.RuleID
fails []eval.RuleID
lastTimestamp time.Time
selfTests []SelfTest
tmpDir string
done chan bool
selfTestRunning chan time.Duration
}
var _ rules.PolicyProvider = (*SelfTester)(nil)
// RunSelfTest runs the self test and return the result
func (t *SelfTester) RunSelfTest(timeout time.Duration) error {
t.Lock()
defer t.Unlock()
t.beginSelfTests(timeout)
for _, selfTest := range t.selfTests {
if err := selfTest.GenerateEvent(); err != nil {
log.Errorf("self test failed: %s", selfTest.GetRuleDefinition().ID)
}
}
return nil
}
// Start implements the policy provider interface
func (t *SelfTester) Start() {}
// GetStatus returns the result of the last performed self tests
func (t *SelfTester) GetStatus() *api.SelfTestsStatus {
t.Lock()
defer t.Unlock()
return &api.SelfTestsStatus{
LastTimestamp: t.lastTimestamp.Format(time.RFC822),
Success: t.success,
Fails: t.fails,
}
}
// CreateTargetDir creates temporary directory
func CreateTargetDir() (string, error) {
// Create temp directory to put target file in
tmpDir, err := os.MkdirTemp("", "datadog_agent_cws_self_test")
if err != nil {
return "", err
}
return tmpDir, nil
}
// WaitForResult wait for self test results
func (t *SelfTester) WaitForResult(cb func(success []eval.RuleID, fails []eval.RuleID, events map[eval.RuleID]*serializers.EventSerializer)) {
for timeout := range t.selfTestRunning {
timer := time.After(timeout)
var (
success []string
fails []string
events = make(map[eval.RuleID]*serializers.EventSerializer)
)
LOOP:
for {
select {
case <-t.done:
return
case event := <-t.eventChan:
t.Lock()
for _, selfTest := range t.selfTests {
if !selfTest.IsSuccess() {
selfTest.HandleEvent(event)
if selfTest.IsSuccess() {
id := selfTest.GetRuleDefinition().ID
events[id] = event.Event
}
}
}
t.Unlock()
// all test passed
if len(events) == len(t.selfTests) {
break LOOP
}
case <-timer:
break LOOP
}
}
t.Lock()
for _, selfTest := range t.selfTests {
id := selfTest.GetRuleDefinition().ID
if _, ok := events[id]; ok {
success = append(success, id)
} else {
fails = append(fails, id)
}
}
t.success, t.fails, t.lastTimestamp = success, fails, time.Now()
t.Unlock()
cb(success, fails, events)
t.endSelfTests()
}
}
// Close removes temp directories and files used by the self tester
func (t *SelfTester) Close() error {
close(t.selfTestRunning)
close(t.done)
if t.tmpDir != "" {
err := os.RemoveAll(t.tmpDir)
t.tmpDir = ""
return err
}
return nil
}
// LoadPolicies implements the PolicyProvider interface
func (t *SelfTester) LoadPolicies(_ []rules.MacroFilter, _ []rules.RuleFilter) ([]*rules.Policy, *multierror.Error) {
t.Lock()
defer t.Unlock()
p := &rules.Policy{
Name: policyName,
Source: policySource,
Version: policyVersion,
IsInternal: true,
}
for _, selftest := range t.selfTests {
p.AddRule(selftest.GetRuleDefinition())
}
return []*rules.Policy{p}, nil
}
func (t *SelfTester) beginSelfTests(timeout time.Duration) {
t.waitingForEvent.Store(true)
t.selfTestRunning <- timeout
}
func (t *SelfTester) endSelfTests() {
t.waitingForEvent.Store(false)
}
type selfTestEvent struct {
RuleID eval.RuleID
Filepath string
Event *serializers.EventSerializer
}
// IsExpectedEvent sends an event to the tester
func (t *SelfTester) IsExpectedEvent(rule *rules.Rule, event eval.Event, _ *probe.Probe) bool {
if t.waitingForEvent.Load() && rule.Definition.Policy.Source == policySource {
ev, ok := event.(*model.Event)
if !ok {
return true
}
s := serializers.NewEventSerializer(ev, rule.Opts)
if s == nil {
return false
}
selfTestEvent := selfTestEvent{
RuleID: rule.ID,
Event: s,
}
select {
case t.eventChan <- selfTestEvent:
default:
log.Debug("self test channel is full, discarding event.")
}
return true
}
return false
}