forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
audit_linux.go
305 lines (261 loc) · 7.45 KB
/
audit_linux.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
package kernel
import (
"os"
"strings"
"time"
"github.com/pkg/errors"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/monitoring"
"github.com/elastic/beats/metricbeat/mb"
"github.com/elastic/beats/metricbeat/mb/parse"
"github.com/elastic/go-libaudit"
"github.com/elastic/go-libaudit/aucoalesce"
"github.com/elastic/go-libaudit/auparse"
)
const (
metricsetName = "audit.kernel"
logPrefix = "[" + metricsetName + "]"
reassemblerMaxInFlight = 5
reassemblerTimeout = 2 * time.Second
streamBufferLen = 64
)
var (
debugf = logp.MakeDebug(metricsetName)
auditMetrics = monitoring.Default.NewRegistry(metricsetName)
lostMetric = monitoring.NewInt(auditMetrics, "lost")
)
func init() {
if err := mb.Registry.AddMetricSet("audit", "kernel", New, parse.EmptyHostParser); err != nil {
panic(err)
}
}
// MetricSet listens for audit messages from the Linux kernel using a netlink
// socket. It buffers the messages to ensure ordering and then streams the
// output. MetricSet implements the mb.PushMetricSet interface, and therefore
// does not rely on polling.
type MetricSet struct {
mb.BaseMetricSet
config Config
client *libaudit.AuditClient
}
// New constructs a new MetricSet.
func New(base mb.BaseMetricSet) (mb.MetricSet, error) {
logp.Experimental("The %v metricset is a beta feature", metricsetName)
config := defaultConfig
if err := base.Module().UnpackConfig(&config); err != nil {
return nil, errors.Wrap(err, "failed to unpack the audit.kernel config")
}
debugf("%v the metricset is running as euid=%v", logPrefix, os.Geteuid())
client, err := libaudit.NewAuditClient(nil)
if err != nil {
return nil, errors.Wrap(err, "failed to create audit.kernel client")
}
lostMetric.Set(0)
return &MetricSet{
BaseMetricSet: base,
client: client,
config: config,
}, nil
}
// Run initializes the audit client and receives audit messages from the
// kernel until the reporter's done channel is closed.
func (ms *MetricSet) Run(reporter mb.PushReporter) {
defer ms.client.Close()
out, err := ms.receiveEvents(reporter.Done())
if err != nil {
reporter.Error(err)
logp.Err("%v %v", logPrefix, err)
return
}
for {
select {
case <-reporter.Done():
return
case msgs := <-out:
event, err := buildMapStr(msgs, ms.config)
if err != nil {
reporter.ErrorWith(err, event)
} else {
reporter.Event(event)
}
}
}
}
func (ms *MetricSet) initClient() error {
status, err := ms.client.GetStatus()
if err != nil {
return errors.Wrap(err, "failed to get audit status")
}
debugf("%v audit status from kernel at start: status=%+v", logPrefix, status)
if status.Enabled == 0 {
if err = ms.client.SetEnabled(true, libaudit.NoWait); err != nil {
return errors.Wrap(err, "failed to enable auditing in the kernel")
}
}
if status.RateLimit != ms.config.RateLimit {
if err = ms.client.SetRateLimit(ms.config.RateLimit, libaudit.NoWait); err != nil {
return errors.Wrap(err, "failed to set audit rate limit in kernel")
}
}
if status.BacklogLimit != ms.config.BacklogLimit {
if err = ms.client.SetBacklogLimit(ms.config.BacklogLimit, libaudit.NoWait); err != nil {
return errors.Wrap(err, "failed to set audit backlog limit in kernel")
}
}
if err := ms.client.SetPID(libaudit.NoWait); err != nil {
return errors.Wrap(err, "failed to set audit PID")
}
return nil
}
func (ms *MetricSet) receiveEvents(done <-chan struct{}) (<-chan []*auparse.AuditMessage, error) {
if err := ms.initClient(); err != nil {
return nil, err
}
out := make(chan []*auparse.AuditMessage, streamBufferLen)
reassembler, err := libaudit.NewReassembler(reassemblerMaxInFlight, reassemblerTimeout, &stream{done, out})
if err != nil {
return nil, errors.Wrap(err, "failed to create Reassembler")
}
go maintain(done, reassembler)
go func() {
defer close(out)
defer reassembler.Close()
for {
raw, err := ms.client.Receive(false)
if err != nil {
continue
}
if filterRecordType(raw.Type) {
continue
}
if err := reassembler.Push(raw.Type, raw.Data); err != nil {
debugf("%v dropping message record_type=%v message='%v': ",
logPrefix, raw.Type, string(raw.Data), err)
continue
}
}
}()
return out, nil
}
// maintain periodically evicts timed-out events from the Reassembler. This
// function will block until the done channel is closed or the Reassembler is
// closed.
func maintain(done <-chan struct{}, reassembler *libaudit.Reassembler) {
tick := time.NewTicker(500 * time.Millisecond)
defer tick.Stop()
for {
select {
case <-done:
return
case <-tick.C:
if err := reassembler.Maintain(); err != nil {
return
}
}
}
}
func filterRecordType(typ auparse.AuditMessageType) bool {
// Messages from 1300-2999 are valid audit message types.
if typ < auparse.AUDIT_USER_AUTH || typ > auparse.AUDIT_LAST_USER_MSG2 {
return true
}
return false
}
func buildMapStr(msgs []*auparse.AuditMessage, config Config) (common.MapStr, error) {
event, err := aucoalesce.CoalesceMessages(msgs)
if err != nil {
// Add messages on error so that it's possible to debug the problem.
m := common.MapStr{}
addMessages(msgs, m)
return m, err
}
if config.ResolveIDs {
aucoalesce.ResolveIDs(event)
}
m := common.MapStr{
"@timestamp": event.Timestamp,
"sequence": event.Sequence,
"category": event.Category.String(),
"record_type": strings.ToLower(event.Type.String()),
"result": event.Result,
"session": event.Session,
"data": event.Data,
}
if event.Subject.Primary != "" {
m.Put("actor.primary", event.Subject.Primary)
}
if event.Subject.Secondary != "" {
m.Put("actor.secondary", event.Subject.Secondary)
}
if len(event.Subject.Attributes) > 0 {
m.Put("actor.attrs", event.Subject.Attributes)
}
if len(event.Subject.SELinux) > 0 {
m.Put("actor.selinux", event.Subject.SELinux)
}
if event.Object.Primary != "" {
m.Put("thing.primary", event.Object.Primary)
}
if event.Object.Secondary != "" {
m.Put("thing.secondary", event.Object.Secondary)
}
if event.Object.What != "" {
m.Put("thing.what", event.Object.What)
}
if len(event.Object.SELinux) > 0 {
m.Put("thing.selinux", event.Object.SELinux)
}
if event.Action != "" {
m.Put("action", event.Action)
}
if event.How != "" {
m.Put("how", event.How)
}
if event.Key != "" {
m.Put("key", event.Key)
}
if len(event.Paths) > 0 {
m.Put("paths", event.Paths)
}
if len(event.Socket) > 0 {
m.Put("socket", event.Socket)
}
if config.RawMessage {
addMessages(msgs, m)
}
if config.Warnings && len(event.Warnings) > 0 {
warnings := make([]string, 0, len(event.Warnings))
for _, err := range event.Warnings {
warnings = append(warnings, err.Error())
}
m.Put("warnings", warnings)
}
return m, nil
}
func addMessages(msgs []*auparse.AuditMessage, m common.MapStr) {
if len(msgs) > 0 {
rawMsgs := make([]string, 0, len(msgs))
for _, msg := range msgs {
rawMsgs = append(rawMsgs, "type="+msg.RecordType.String()+" msg="+msg.RawData)
}
m["messages"] = rawMsgs
}
}
// stream type
// stream receives callbacks from the libaudit.Reassmbler for completed events
// or lost events that are detected by gaps in sequence numbers.
type stream struct {
done <-chan struct{}
out chan<- []*auparse.AuditMessage
}
func (s *stream) ReassemblyComplete(msgs []*auparse.AuditMessage) {
select {
case <-s.done:
return
case s.out <- msgs:
}
}
func (s *stream) EventsLost(count int) {
lostMetric.Add(int64(count))
}