-
Notifications
You must be signed in to change notification settings - Fork 5k
Expand file tree
/
Copy pathpublisher.go
More file actions
433 lines (372 loc) · 11.3 KB
/
Copy pathpublisher.go
File metadata and controls
433 lines (372 loc) · 11.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
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package pub
import (
"sync"
"time"
"github.com/elastic/beats/v7/libbeat/beat"
"github.com/elastic/beats/v7/libbeat/beat/events"
"github.com/elastic/beats/v7/libbeat/processors"
"github.com/elastic/beats/v7/libbeat/processors/add_data_stream"
"github.com/elastic/beats/v7/x-pack/osquerybeat/internal/config"
"github.com/elastic/beats/v7/x-pack/osquerybeat/internal/ecs"
"github.com/elastic/elastic-agent-libs/logp"
"github.com/elastic/elastic-agent-libs/mapstr"
)
const (
eventModule = "osquery_manager"
)
type Publisher struct {
b *beat.Beat
log *logp.Logger
mx sync.Mutex
// client for osquery_manager.result
client beat.Client
// client for osquery_manager.action.responses
actionResponsesClient beat.Client
// client for osquery_manager.query_profile
queryProfileClient beat.Client
profileDropWarnLogged bool
}
func New(b *beat.Beat, log *logp.Logger) *Publisher {
return &Publisher{
b: b,
log: log,
}
}
func (p *Publisher) Configure(inputs []config.InputConfig) error {
if len(inputs) == 0 {
return nil
}
p.mx.Lock()
defer p.mx.Unlock()
// Setup configuration pointers to the clients and corresponding default datasets
// The osquery_manager.result is always first
if len(inputs) > 0 {
processors, err := p.processorsForInputConfig(inputs[0], config.DefaultDataset)
if err != nil {
return err
}
p.log.Debugf("Connect publisher for %s with processors: %d", config.DefaultDataset, len(processors.All()))
// Connect publisher
client, err := p.b.Publisher.ConnectWith(beat.ClientConfig{
Processing: beat.ProcessingConfig{
Processor: processors,
},
})
if err != nil {
return err
}
// Swap client
oldclient := p.client
p.client = client
if oldclient != nil {
oldclient.Close()
}
}
// Attach remaining DefaultActionResultsDataset if present
if len(inputs) > 1 {
processors, err := p.processorsForInputConfig(inputs[1], config.DefaultActionResponsesDataset)
if err != nil {
return err
}
p.log.Debugf("Connect publisher for %s with processors: %d", config.DefaultActionResponsesDataset, len(processors.All()))
// Connect publisher
client, err := p.b.Publisher.ConnectWith(beat.ClientConfig{
Processing: beat.ProcessingConfig{
Processor: processors,
},
})
if err != nil {
return err
}
// Swap client
oldclient := p.actionResponsesClient
p.actionResponsesClient = client
if oldclient != nil {
oldclient.Close()
}
} else {
if p.actionResponsesClient != nil {
p.actionResponsesClient.Close()
p.actionResponsesClient = nil
}
}
// Attach optional query profiling stream if present, identified by dataset.
// For query profile events to be published, the integration (e.g. Fleet policy) must include
// an input stream with dataset osquery_manager.query_profile. Otherwise profile events are dropped.
var profileInput *config.InputConfig
for i := range inputs {
if inputs[i].Datastream.Dataset == config.DefaultQueryProfileDataset {
profileInput = &inputs[i]
break
}
}
if profileInput != nil {
processors, err := p.processorsForInputConfig(*profileInput, config.DefaultQueryProfileDataset)
if err != nil {
return err
}
p.log.Debugf("Connect publisher for %s with processors: %d", config.DefaultQueryProfileDataset, len(processors.All()))
client, err := p.b.Publisher.ConnectWith(beat.ClientConfig{
Processing: beat.ProcessingConfig{
Processor: processors,
},
})
if err != nil {
return err
}
oldClient := p.queryProfileClient
p.queryProfileClient = client
p.profileDropWarnLogged = false
if oldClient != nil {
oldClient.Close()
}
} else {
if p.queryProfileClient != nil {
p.queryProfileClient.Close()
p.queryProfileClient = nil
}
}
return nil
}
func (p *Publisher) Publish(index, idValue, idFieldKey, responseID, spaceID, packID, packName, queryName string, meta map[string]interface{}, hits []map[string]interface{}, ecsm ecs.Mapping, reqData interface{}) {
p.mx.Lock()
defer p.mx.Unlock()
for _, hit := range hits {
event := hitToEvent(index, p.b.Info.Name, idValue, idFieldKey, responseID, spaceID, packID, packName, queryName, meta, hit, ecsm, reqData)
p.client.Publish(event)
}
p.log.Infof("%d events sent to index %s", len(hits), index)
}
func (p *Publisher) Close() {
p.mx.Lock()
defer p.mx.Unlock()
if p.client != nil {
p.client.Close()
p.client = nil
}
if p.actionResponsesClient != nil {
p.actionResponsesClient.Close()
p.actionResponsesClient = nil
}
if p.queryProfileClient != nil {
p.queryProfileClient.Close()
p.queryProfileClient = nil
}
}
func (p *Publisher) PublishActionResult(req map[string]interface{}, res map[string]interface{}) {
p.mx.Lock()
defer p.mx.Unlock()
if p.actionResponsesClient == nil {
p.log.Info("Action responses stream is not configured. Action response is dropped.")
return
}
fields := actionResultToEvent(req, res)
p.log.Debugf("Action response event is sent, fields: %#v", fields)
p.publishActionResponseEvent(fields, time.Now())
}
// PublishScheduledResponse publishes a synthetic response document for a scheduled query run (no action).
// Includes schedule_execution_count;
// native uses 1 + (run_time - start_date) / interval).
func (p *Publisher) PublishScheduledResponse(scheduleID, packID, packName, queryName, spaceID, responseID string, startedAt, completedAt, plannedScheduleTime time.Time, resultCount int, scheduleExecutionCount int64) {
p.mx.Lock()
defer p.mx.Unlock()
if p.actionResponsesClient == nil {
p.log.Debug("Action responses stream is not configured. Scheduled response is dropped.")
return
}
fields := map[string]interface{}{
"schedule_id": scheduleID,
"response_id": responseID,
"action_input_type": "osquery_scheduled",
"started_at": startedAt.Format(time.RFC3339Nano),
"completed_at": completedAt.Format(time.RFC3339Nano),
"planned_schedule_time": plannedScheduleTime.Format(time.RFC3339Nano),
"schedule_execution_count": scheduleExecutionCount,
"action_response": map[string]interface{}{
"osquery": map[string]interface{}{
"count": resultCount,
},
},
}
if packID != "" {
fields["pack_id"] = packID
}
if packName != "" {
fields["pack_name"] = packName
}
if queryName != "" {
fields["query_name"] = queryName
}
if spaceID != "" {
fields["space_id"] = spaceID
}
p.log.Debugf("Scheduled response event sent, schedule_id=%s, schedule_execution_count=%d", scheduleID, scheduleExecutionCount)
p.publishActionResponseEvent(fields, completedAt)
}
func (p *Publisher) publishActionResponseEvent(fields map[string]interface{}, timestamp time.Time) {
event := beat.Event{
Timestamp: timestamp,
Fields: fields,
}
p.actionResponsesClient.Publish(event)
}
func (p *Publisher) PublishQueryProfile(index, queryName, actionID, responseID string, profile map[string]interface{}, reqData interface{}) {
p.mx.Lock()
defer p.mx.Unlock()
if p.queryProfileClient == nil {
if !p.profileDropWarnLogged {
p.log.Info("Query profile stream is not configured. Query profile events will be dropped.")
p.profileDropWarnLogged = true
}
return
}
fields := mapstr.M{
"type": "osquery_profile",
"event": map[string]interface{}{
"module": eventModule,
},
"osquery_profile": profile,
}
if queryName != "" {
fields["query"] = map[string]interface{}{
"name": queryName,
}
}
if actionID != "" {
fields["action_id"] = actionID
}
if responseID != "" {
fields["response_id"] = responseID
}
if reqData != nil {
fields["action_data"] = reqData
}
event := beat.Event{
Timestamp: time.Now(),
Fields: fields,
}
if index != "" {
event.Meta = mapstr.M{events.FieldMetaRawIndex: index}
}
p.log.Debugf("Query profile event is sent, fields: %#v", fields)
p.queryProfileClient.Publish(event)
}
func actionResultToEvent(req, res map[string]interface{}) map[string]interface{} {
m := make(map[string]interface{}, 8)
copyKey := func(key string, src, dst map[string]interface{}) {
if v, ok := src[key]; ok {
dst[key] = v
}
}
copyKey("started_at", res, m)
copyKey("completed_at", res, m)
copyKey("error", res, m)
if v, ok := res["count"]; ok {
m["action_response"] = map[string]interface{}{
"osquery": map[string]interface{}{
"count": v,
},
}
}
if v, ok := req["id"]; ok {
m["action_id"] = v
}
if v, ok := req["input_type"]; ok {
m["action_input_type"] = v
}
if v, ok := req["data"]; ok {
m["action_data"] = v
}
return m
}
func (p *Publisher) processorsForInputConfig(inCfg config.InputConfig, defaultDataset string) (procs *processors.Processors, err error) {
procs = processors.NewList(p.log)
// Use only first input processor.
// When Processors is empty, the data_stream processor is not added; Fleet-managed inputs
// typically supply processors so the data stream is set correctly.
// Every input will have a processor that adds the elastic_agent info, we need only one
// Not expecting other processors at the moment and this needs to work for 7.13
if len(inCfg.Processors) > 0 {
// Attach the data_stream processor. This will append the data_stream attributes to the events.
// This is needed for the proper logstash auto-discovery of the destination datastream for the results.
ds := add_data_stream.DataStream{
Namespace: inCfg.Datastream.Namespace,
Dataset: inCfg.Datastream.Dataset,
Type: inCfg.Datastream.Type,
}
if ds.Namespace == "" {
ds.Namespace = config.DefaultNamespace
}
if ds.Dataset == "" {
ds.Dataset = defaultDataset
}
if ds.Type == "" {
ds.Type = config.DefaultType
}
procs.AddProcessor(add_data_stream.New(ds))
userProcs, err := processors.New(inCfg.Processors, p.log)
if err != nil {
return nil, err
}
procs.AddProcessors(*userProcs)
}
return procs, nil
}
func hitToEvent(index, eventType, idValue, idFieldKey, responseID, spaceID, packID, packName, queryName string, meta, hit map[string]interface{}, ecsm ecs.Mapping, reqData interface{}) beat.Event {
var fields mapstr.M
if len(ecsm) > 0 {
// Map ECS fields if the mapping is provided
fields = mapstr.M(ecsm.Map(hit))
} else {
fields = mapstr.M{}
}
// Add event.module for ECS
// There could be already "event" properties set, preserve them and set the "event.module"
var evf map[string]interface{}
ievf, ok := fields["event"]
if ok {
evf, ok = ievf.(map[string]interface{})
}
if !ok {
evf = make(map[string]interface{})
}
evf["module"] = eventModule
fields["event"] = evf
fields["type"] = eventType
if idFieldKey != "" {
fields[idFieldKey] = idValue
}
fields["osquery"] = hit
if meta != nil {
fields["osquery_meta"] = meta
}
event := beat.Event{
Timestamp: time.Now(),
Fields: fields,
}
if reqData != nil {
event.Fields["action_data"] = reqData
}
if responseID != "" {
event.Fields["response_id"] = responseID
}
if spaceID != "" {
event.Fields["space_id"] = spaceID
}
if packID != "" {
event.Fields["pack_id"] = packID
}
if packName != "" {
event.Fields["pack_name"] = packName
}
if queryName != "" {
event.Fields["query_name"] = queryName
}
if index != "" {
event.Meta = mapstr.M{events.FieldMetaRawIndex: index}
}
return event
}