-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
activity_dump.go
632 lines (556 loc) · 18.4 KB
/
activity_dump.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
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
// 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
// Package runtime holds runtime related files
package runtime
import (
"fmt"
"os"
"github.com/spf13/cobra"
"go.uber.org/fx"
"github.com/DataDog/datadog-agent/cmd/security-agent/command"
"github.com/DataDog/datadog-agent/comp/core"
"github.com/DataDog/datadog-agent/comp/core/config"
"github.com/DataDog/datadog-agent/comp/core/log"
"github.com/DataDog/datadog-agent/comp/core/log/logimpl"
"github.com/DataDog/datadog-agent/comp/core/secrets"
secagent "github.com/DataDog/datadog-agent/pkg/security/agent"
secconfig "github.com/DataDog/datadog-agent/pkg/security/config"
"github.com/DataDog/datadog-agent/pkg/security/proto/api"
activity_tree "github.com/DataDog/datadog-agent/pkg/security/security_profile/activity_tree"
"github.com/DataDog/datadog-agent/pkg/security/security_profile/dump"
"github.com/DataDog/datadog-agent/pkg/security/utils"
"github.com/DataDog/datadog-agent/pkg/util/fxutil"
)
type activityDumpCliParams struct {
*command.GlobalParams
name string
containerID string
comm string
file string
file2 string
timeout string
format string
differentiateArgs bool
localStorageDirectory string
localStorageFormats []string
localStorageCompression bool
remoteStorageFormats []string
remoteStorageCompression bool
remoteRequest bool
}
func activityDumpCommands(globalParams *command.GlobalParams) []*cobra.Command {
activityDumpCmd := &cobra.Command{
Use: "activity-dump",
Short: "activity dump command",
}
activityDumpCmd.AddCommand(generateCommands(globalParams)...)
activityDumpCmd.AddCommand(listCommands(globalParams)...)
activityDumpCmd.AddCommand(stopCommands(globalParams)...)
activityDumpCmd.AddCommand(diffCommands(globalParams)...)
return []*cobra.Command{activityDumpCmd}
}
func listCommands(globalParams *command.GlobalParams) []*cobra.Command {
activityDumpListCmd := &cobra.Command{
Use: "list",
Short: "get the list of running activity dumps",
RunE: func(cmd *cobra.Command, args []string) error {
return fxutil.OneShot(listActivityDumps,
fx.Supply(core.BundleParams{
ConfigParams: config.NewSecurityAgentParams(globalParams.ConfigFilePaths),
SecretParams: secrets.NewEnabledParams(),
LogParams: logimpl.ForOneShot(command.LoggerName, "info", true)}),
core.Bundle(),
)
},
}
return []*cobra.Command{activityDumpListCmd}
}
func stopCommands(globalParams *command.GlobalParams) []*cobra.Command {
cliParams := &activityDumpCliParams{
GlobalParams: globalParams,
}
activityDumpStopCmd := &cobra.Command{
Use: "stop",
Short: "stops the first activity dump that matches the provided selector",
RunE: func(cmd *cobra.Command, args []string) error {
return fxutil.OneShot(stopActivityDump,
fx.Supply(cliParams),
fx.Supply(core.BundleParams{
ConfigParams: config.NewSecurityAgentParams(globalParams.ConfigFilePaths),
SecretParams: secrets.NewEnabledParams(),
LogParams: logimpl.ForOneShot(command.LoggerName, "info", true)}),
core.Bundle(),
)
},
}
activityDumpStopCmd.Flags().StringVar(
&cliParams.name,
"name",
"",
"an activity dump name can be used to filter the activity dump.",
)
activityDumpStopCmd.Flags().StringVar(
&cliParams.containerID,
"container-id",
"",
"an containerID can be used to filter the activity dump.",
)
activityDumpStopCmd.Flags().StringVar(
&cliParams.comm,
"comm",
"",
"a process command can be used to filter the activity dump from a specific process.",
)
return []*cobra.Command{activityDumpStopCmd}
}
func generateCommands(globalParams *command.GlobalParams) []*cobra.Command {
activityDumpGenerateCmd := &cobra.Command{
Use: "generate",
Short: "generate command for activity dumps",
}
activityDumpGenerateCmd.AddCommand(generateDumpCommands(globalParams)...)
activityDumpGenerateCmd.AddCommand(generateEncodingCommands(globalParams)...)
return []*cobra.Command{activityDumpGenerateCmd}
}
func generateDumpCommands(globalParams *command.GlobalParams) []*cobra.Command {
cliParams := &activityDumpCliParams{
GlobalParams: globalParams,
}
activityDumpGenerateDumpCmd := &cobra.Command{
Use: "dump",
Short: "generate an activity dump",
RunE: func(cmd *cobra.Command, args []string) error {
return fxutil.OneShot(generateActivityDump,
fx.Supply(cliParams),
fx.Supply(core.BundleParams{
ConfigParams: config.NewSecurityAgentParams(globalParams.ConfigFilePaths),
SecretParams: secrets.NewEnabledParams(),
LogParams: logimpl.ForOneShot(command.LoggerName, "info", true)}),
core.Bundle(),
)
},
}
activityDumpGenerateDumpCmd.Flags().StringVar(
&cliParams.comm,
"comm",
"",
"a process command can be used to filter the activity dump from a specific process.",
)
activityDumpGenerateDumpCmd.Flags().StringVar(
&cliParams.containerID,
"container-id",
"",
"a container identifier can be used to filter the activity dump from a specific container.",
)
activityDumpGenerateDumpCmd.Flags().StringVar(
&cliParams.timeout,
"timeout",
"1m",
"timeout for the activity dump",
)
activityDumpGenerateDumpCmd.Flags().BoolVar(
&cliParams.differentiateArgs,
"differentiate-args",
true,
"add the arguments in the process node merge algorithm",
)
activityDumpGenerateDumpCmd.Flags().StringVar(
&cliParams.localStorageDirectory,
"output",
"/tmp/activity_dumps/",
"local storage output directory",
)
activityDumpGenerateDumpCmd.Flags().BoolVar(
&cliParams.localStorageCompression,
"compression",
false,
"defines if the local storage output should be compressed before persisting the data to disk",
)
activityDumpGenerateDumpCmd.Flags().StringArrayVar(
&cliParams.localStorageFormats,
"format",
[]string{},
fmt.Sprintf("local storage output formats. Available options are %v.", secconfig.AllStorageFormats()),
)
activityDumpGenerateDumpCmd.Flags().BoolVar(
&cliParams.remoteStorageCompression,
"remote-compression",
true,
"defines if the remote storage output should be compressed before sending the data",
)
activityDumpGenerateDumpCmd.Flags().StringArrayVar(
&cliParams.remoteStorageFormats,
"remote-format",
[]string{},
fmt.Sprintf("remote storage output formats. Available options are %v.", secconfig.AllStorageFormats()),
)
return []*cobra.Command{activityDumpGenerateDumpCmd}
}
func generateEncodingCommands(globalParams *command.GlobalParams) []*cobra.Command {
cliParams := &activityDumpCliParams{
GlobalParams: globalParams,
}
activityDumpGenerateEncodingCmd := &cobra.Command{
Use: "encoding",
Short: "encode an activity dump to the requested formats",
RunE: func(cmd *cobra.Command, args []string) error {
return fxutil.OneShot(generateEncodingFromActivityDump,
fx.Supply(cliParams),
fx.Supply(core.BundleParams{
ConfigParams: config.NewSecurityAgentParams(globalParams.ConfigFilePaths),
SecretParams: secrets.NewEnabledParams(),
LogParams: logimpl.ForOneShot(command.LoggerName, "info", true)}),
core.Bundle(),
)
},
}
activityDumpGenerateEncodingCmd.Flags().StringVar(
&cliParams.file,
"input",
"",
"path to the activity dump file",
)
_ = activityDumpGenerateEncodingCmd.MarkFlagRequired("input")
activityDumpGenerateEncodingCmd.Flags().StringVar(
&cliParams.localStorageDirectory,
"output",
"/tmp/activity_dumps/",
"local storage output directory",
)
activityDumpGenerateEncodingCmd.Flags().BoolVar(
&cliParams.localStorageCompression,
"compression",
false,
"defines if the local storage output should be compressed before persisting the data to disk",
)
activityDumpGenerateEncodingCmd.Flags().StringArrayVar(
&cliParams.localStorageFormats,
"format",
[]string{},
fmt.Sprintf("local storage output formats. Available options are %v.", secconfig.AllStorageFormats()),
)
activityDumpGenerateEncodingCmd.Flags().BoolVar(
&cliParams.remoteStorageCompression,
"remote-compression",
true,
"defines if the remote storage output should be compressed before sending the data",
)
activityDumpGenerateEncodingCmd.Flags().StringArrayVar(
&cliParams.remoteStorageFormats,
"remote-format",
[]string{},
fmt.Sprintf("remote storage output formats. Available options are %v.", secconfig.AllStorageFormats()),
)
activityDumpGenerateEncodingCmd.Flags().BoolVar(
&cliParams.remoteRequest,
"remote",
false,
"when set, the transcoding will be done by system-probe instead of the current security-agent instance",
)
return []*cobra.Command{activityDumpGenerateEncodingCmd}
}
func diffCommands(globalParams *command.GlobalParams) []*cobra.Command {
cliParams := &activityDumpCliParams{
GlobalParams: globalParams,
}
activityDumpDiffCmd := &cobra.Command{
Use: "diff",
Short: "compute the diff between two activity dumps",
RunE: func(cmd *cobra.Command, args []string) error {
return fxutil.OneShot(diffActivityDump,
fx.Supply(cliParams),
fx.Supply(core.BundleParams{
ConfigParams: config.NewSecurityAgentParams(globalParams.ConfigFilePaths),
SecretParams: secrets.NewEnabledParams(),
LogParams: logimpl.ForOneShot(command.LoggerName, "info", true)}),
core.Bundle(),
)
},
}
activityDumpDiffCmd.Flags().StringVar(
&cliParams.file,
"origin",
"",
"path to the first activity dump file",
)
activityDumpDiffCmd.Flags().StringVar(
&cliParams.file2,
"target",
"",
"path to the second activity dump file",
)
activityDumpDiffCmd.Flags().StringVar(
&cliParams.format,
"format",
"json",
"output formeat",
)
return []*cobra.Command{activityDumpDiffCmd}
}
const (
addedADNode activity_tree.NodeGenerationType = 100
removedADNode activity_tree.NodeGenerationType = 101
)
func markADSubtree(n *activity_tree.ProcessNode, state activity_tree.NodeGenerationType) {
n.GenerationType = state
for _, child := range n.Children {
markADSubtree(child, state)
}
}
func diffADDNSNodes(p1, p2 map[string]*activity_tree.DNSNode, states map[string]bool, processID utils.GraphID) (nodes map[string]*activity_tree.DNSNode) {
nodes = make(map[string]*activity_tree.DNSNode)
for domain, n := range p2 {
if p1[domain] != nil {
newNode := *n
nodes[domain] = &newNode
continue
}
states[processID.Derive(utils.NewNodeIDFromPtr(n)).String()] = true
nodes[domain] = n
}
for domain, n := range p1 {
if p2[domain] != nil {
continue
}
id := processID.Derive(utils.NewNodeIDFromPtr(n)).String()
states[id] = false
nodes[domain] = n
}
return nodes
}
func diffADSubtree(p1, p2 []*activity_tree.ProcessNode, states map[string]bool) (nodes []*activity_tree.ProcessNode) {
NEXT:
for _, n := range p2 {
for _, n2 := range p1 {
if n.Matches(&n2.Process, false, false) {
newNode := *n
processID := utils.NewGraphID(utils.NewNodeIDFromPtr(&newNode))
newNode.Children = diffADSubtree(n.Children, n2.Children, states)
newNode.DNSNames = diffADDNSNodes(n.DNSNames, n2.DNSNames, states, processID)
nodes = append(nodes, &newNode)
continue NEXT
}
}
nodes = append(nodes, n)
markADSubtree(n, addedADNode)
states[utils.NewGraphID(utils.NewNodeIDFromPtr(n)).String()] = true
}
NEXT2:
for _, n := range p1 {
for _, n2 := range p2 {
if n.Matches(&n2.Process, false, false) {
continue NEXT2
}
}
nodes = append(nodes, n)
markADSubtree(n, removedADNode)
states[utils.NewGraphID(utils.NewNodeIDFromPtr(n)).String()] = false
}
return
}
func computeActivityDumpDiff(p1, p2 *dump.ActivityDump, states map[string]bool) *dump.ActivityDump {
return &dump.ActivityDump{
ActivityTree: &activity_tree.ActivityTree{
ProcessNodes: diffADSubtree(p1.ActivityTree.ProcessNodes, p2.ActivityTree.ProcessNodes, states),
},
}
}
func diffActivityDump(_ log.Component, _ config.Component, _ secrets.Component, args *activityDumpCliParams) error {
ad := dump.NewEmptyActivityDump(nil)
if err := ad.Decode(args.file); err != nil {
return err
}
ad2 := dump.NewEmptyActivityDump(nil)
if err := ad2.Decode(args.file2); err != nil {
return err
}
states := make(map[string]bool)
diff := computeActivityDumpDiff(ad, ad2, states)
switch args.format {
case "dot":
graph := diff.ToGraph()
for i := range graph.Nodes {
n := graph.Nodes[i]
if state, found := states[n.ID.String()]; found {
if state {
n.FillColor = "green"
} else {
n.FillColor = "red"
}
}
}
buffer, err := graph.EncodeDOT(dump.ActivityDumpGraphTemplate)
if err != nil {
return err
}
os.Stdout.Write(buffer.Bytes())
case "protobuf":
buffer, err := diff.EncodeProtobuf()
if err != nil {
return err
}
os.Stdout.Write(buffer.Bytes())
case "json":
buffer, err := diff.EncodeJSON(" ")
if err != nil {
return err
}
fmt.Println(buffer.String())
default:
return fmt.Errorf("unknown format '%s'", args.format)
}
return nil
}
func generateActivityDump(_ log.Component, _ config.Component, _ secrets.Component, activityDumpArgs *activityDumpCliParams) error {
client, err := secagent.NewRuntimeSecurityClient()
if err != nil {
return fmt.Errorf("unable to create a runtime security client instance: %w", err)
}
defer client.Close()
storage, err := parseStorageRequest(activityDumpArgs)
if err != nil {
return err
}
output, err := client.GenerateActivityDump(&api.ActivityDumpParams{
Comm: activityDumpArgs.comm,
ContainerID: activityDumpArgs.containerID,
Timeout: activityDumpArgs.timeout,
DifferentiateArgs: activityDumpArgs.differentiateArgs,
Storage: storage,
})
if err != nil {
return fmt.Errorf("unable to send request to system-probe: %w", err)
}
if len(output.Error) > 0 {
return fmt.Errorf("activity dump generation request failed: %s", output.Error)
}
printSecurityActivityDumpMessage("", output)
return nil
}
func generateEncodingFromActivityDump(_ log.Component, _ config.Component, _ secrets.Component, activityDumpArgs *activityDumpCliParams) error {
var output *api.TranscodingRequestMessage
if activityDumpArgs.remoteRequest {
// send the encoding request to system-probe
client, err := secagent.NewRuntimeSecurityClient()
if err != nil {
return fmt.Errorf("encoding generation failed: %w", err)
}
defer client.Close()
// parse encoding request
storage, err := parseStorageRequest(activityDumpArgs)
if err != nil {
return err
}
output, err = client.GenerateEncoding(&api.TranscodingRequestParams{
ActivityDumpFile: activityDumpArgs.file,
Storage: storage,
})
if err != nil {
return fmt.Errorf("couldn't send request to system-probe: %w", err)
}
} else {
// encoding request will be handled locally
ad := dump.NewEmptyActivityDump(nil)
// open and parse input file
if err := ad.Decode(activityDumpArgs.file); err != nil {
return err
}
parsedRequests, err := parseStorageRequest(activityDumpArgs)
if err != nil {
return err
}
storageRequests, err := secconfig.ParseStorageRequests(parsedRequests)
if err != nil {
return fmt.Errorf("couldn't parse transcoding request for [%s]: %v", ad.GetSelectorStr(), err)
}
for _, request := range storageRequests {
ad.AddStorageRequest(request)
}
cfg, err := secconfig.NewConfig()
if err != nil {
return fmt.Errorf("couldn't load configuration: %w", err)
}
storage, err := dump.NewSecurityAgentCommandStorageManager(cfg)
if err != nil {
return fmt.Errorf("couldn't instantiate storage manager: %w", err)
}
err = storage.Persist(ad)
if err != nil {
return fmt.Errorf("couldn't persist dump from %s: %w", activityDumpArgs.file, err)
}
output = ad.ToTranscodingRequestMessage()
}
if len(output.GetError()) > 0 {
return fmt.Errorf("encoding generation failed: %s", output.GetError())
}
if len(output.GetStorage()) > 0 {
fmt.Printf("encoding generation succeeded:\n")
for _, storage := range output.GetStorage() {
printStorageRequestMessage("\t", storage)
}
} else {
fmt.Println("encoding generation succeeded: empty output")
}
return nil
}
func listActivityDumps(_ log.Component, _ config.Component, _ secrets.Component) error {
client, err := secagent.NewRuntimeSecurityClient()
if err != nil {
return fmt.Errorf("unable to create a runtime security client instance: %w", err)
}
defer client.Close()
output, err := client.ListActivityDumps()
if err != nil {
return fmt.Errorf("unable to send request to system-probe: %w", err)
}
if len(output.Error) > 0 {
return fmt.Errorf("activity dump list request failed: %s", output.Error)
}
if len(output.Dumps) > 0 {
fmt.Println("active dumps:")
for _, d := range output.Dumps {
printSecurityActivityDumpMessage("\t", d)
}
} else {
fmt.Println("no active dumps found")
}
return nil
}
func parseStorageRequest(activityDumpArgs *activityDumpCliParams) (*api.StorageRequestParams, error) {
// parse local storage formats
_, err := secconfig.ParseStorageFormats(activityDumpArgs.localStorageFormats)
if err != nil {
return nil, fmt.Errorf("couldn't parse local storage formats %v: %v", activityDumpArgs.localStorageFormats, err)
}
// parse remote storage formats
_, err = secconfig.ParseStorageFormats(activityDumpArgs.remoteStorageFormats)
if err != nil {
return nil, fmt.Errorf("couldn't parse remote storage formats %v: %v", activityDumpArgs.remoteStorageFormats, err)
}
return &api.StorageRequestParams{
LocalStorageDirectory: activityDumpArgs.localStorageDirectory,
LocalStorageCompression: activityDumpArgs.localStorageCompression,
LocalStorageFormats: activityDumpArgs.localStorageFormats,
RemoteStorageCompression: activityDumpArgs.remoteStorageCompression,
RemoteStorageFormats: activityDumpArgs.remoteStorageFormats,
}, nil
}
func stopActivityDump(_ log.Component, _ config.Component, _ secrets.Component, activityDumpArgs *activityDumpCliParams) error {
client, err := secagent.NewRuntimeSecurityClient()
if err != nil {
return fmt.Errorf("unable to create a runtime security client instance: %w", err)
}
defer client.Close()
output, err := client.StopActivityDump(activityDumpArgs.name, activityDumpArgs.containerID, activityDumpArgs.comm)
if err != nil {
return fmt.Errorf("unable to send request to system-probe: %w", err)
}
if len(output.Error) > 0 {
return fmt.Errorf("activity dump stop request failed: %s", output.Error)
}
fmt.Println("done!")
return nil
}