-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
1259 lines (1140 loc) · 39.5 KB
/
main.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
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
package main
import (
"archive/tar"
"compress/gzip"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/aquasecurity/tracee/tracee"
"github.com/syndtr/gocapability/capability"
"github.com/urfave/cli/v2"
)
var debug bool
var traceeInstallPath string
var buildPolicy string
// These vars are supposed to be injected at build time
var bpfBundleInjected string
var version string
func main() {
app := &cli.App{
Name: "Tracee",
Usage: "Trace OS events and syscalls using eBPF",
Version: version,
Action: func(c *cli.Context) error {
if c.Bool("list") {
printList()
return nil
}
cfg := tracee.TraceeConfig{
PerfBufferSize: c.Int("perf-buffer-size"),
BlobPerfBufferSize: c.Int("blob-perf-buffer-size"),
SecurityAlerts: c.Bool("security-alerts"),
}
pinObject, objectName, path, err := preparePinning(c.String("pin"))
if err != nil {
return err
}
cfg.PinObjectType = pinObject
cfg.PinPath = path
cfg.PinObjectName = objectName
output, err := prepareOutput(c.StringSlice("output"))
if err != nil {
return err
}
cfg.Output = &output
capture, err := prepareCapture(c.StringSlice("capture"))
if err != nil {
return err
}
cfg.Capture = &capture
filter, err := prepareFilter(c.StringSlice("trace"))
if err != nil {
return err
}
cfg.Filter = &filter
if c.Bool("security-alerts") {
cfg.Filter.EventsToTrace = append(cfg.Filter.EventsToTrace, tracee.MemProtAlertEventID)
}
bpfFile, err := getBPFObject()
if err != nil {
return err
}
cfg.BPFObjPath = bpfFile
if !checkRequiredCapabilities() {
return fmt.Errorf("Insufficient privileges to run")
}
t, err := tracee.New(cfg)
if err != nil {
// t is being closed internally
return fmt.Errorf("error creating Tracee: %v", err)
}
return t.Run()
},
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "list",
Aliases: []string{"l"},
Value: false,
Usage: "just list tracable events",
},
&cli.StringSliceFlag{
Name: "trace",
Aliases: []string{"t"},
Value: nil,
Usage: "select events to trace by defining trace expressions. run '--trace help' for more info.",
},
&cli.StringSliceFlag{
Name: "capture",
Aliases: []string{"c"},
Value: nil,
Usage: "capture artifacts that were written, executed or found to be suspicious. run '--capture help' for more info.",
},
&cli.StringSliceFlag{
Name: "output",
Aliases: []string{"o"},
Value: cli.NewStringSlice("format:table"),
Usage: "Control how and where output is printed. run '--output help' for more info.",
},
&cli.BoolFlag{
Name: "security-alerts",
Value: false,
Usage: "alert on security related events",
},
&cli.IntFlag{
Name: "perf-buffer-size",
Aliases: []string{"b"},
Value: 1024,
Usage: "size, in pages, of the internal perf ring buffer used to submit events from the kernel",
},
&cli.IntFlag{
Name: "blob-perf-buffer-size",
Value: 1024,
Usage: "size, in pages, of the internal perf ring buffer used to send blobs from the kernel",
},
&cli.BoolFlag{
Name: "debug",
Value: false,
Usage: "write verbose debug messages to standard output and retain intermediate artifacts",
Destination: &debug,
},
&cli.StringFlag{
Name: "install-path",
Value: "/tmp/tracee",
Usage: "path where tracee will install or lookup it's resources",
Destination: &traceeInstallPath,
},
&cli.StringFlag{
Name: "build-policy",
Value: "if-needed",
Usage: "when to build the bpf program. possible options: 'never'/'always'/'if-needed'",
Destination: &buildPolicy,
},
&cli.StringFlag{
Name: "pin",
Value: "",
Usage: "Provide pinning instruction in a format object_type:object_name:pin_path",
},
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func prepareOutput(outputSlice []string) (tracee.OutputConfig, error) {
outputHelp := `
Control how and where output is printed.
Possible options:
[format:]{table,table-verbose,json,gob,gotemplate=/path/to/template} output events in the specified format. for gotemplate, specify the mandatory template file
out-file:/path/to/file write the output to a specified file. the path to the file will be created if not existing and the file will be deleted if existing (deafult: stdout)
err-file:/path/to/file write the errors to a specified file. the path to the file will be created if not existing and the file will be deleted if existing (deafult: stderr)
option:{eot,stacktrace,detect-syscall,exec-env} augment output according to given options (default: none)
eot add a final event that signals the end of event stream. this is an empty event with "EventName" set to the ASCII code 4, which is "End Of Transmission"
stack-addresses include stack memory addresses for each event
detect-syscall when tracing kernel functions which are not syscalls, detect and show the original syscall that called that function
exec-env when tracing execve/execveat, show the environment variables that were used for execution
Examples:
--output json --output option:eot | output as json and add an EOT event
--output gotemplate=/path/to/my.tmpl | output as the provided go template
--output out-file:/my/out err-file:/my/err | output to /my/out and errors to /my/err
Use this flag multiple times to choose multiple capture options
`
res := tracee.OutputConfig{}
if len(outputSlice) == 1 && outputSlice[0] == "help" {
return res, fmt.Errorf(outputHelp)
}
for _, o := range outputSlice {
outputParts := strings.SplitN(o, ":", 2)
numParts := len(outputParts)
if numParts == 1 {
outputParts = append(outputParts, outputParts[0])
outputParts[0] = "format"
}
if outputParts[0] == "format" {
res.Format = outputParts[1]
} else if outputParts[0] == "out-file" {
res.OutPath = outputParts[1]
} else if outputParts[0] == "err-file" {
res.ErrPath = outputParts[1]
} else if outputParts[0] == "option" {
switch outputParts[1] {
case "eot":
res.EOT = true
case "stack-addresses":
res.StackAddresses = true
case "detect-syscall":
res.DetectSyscall = true
case "exec-env":
res.ExecEnv = true
default:
return res, fmt.Errorf("invalid output option: %s, use '--option help' for more info", outputParts[1])
}
}
}
if res.Format == "" {
res.Format = "table"
}
return res, nil
}
func prepareCapture(captureSlice []string) (tracee.CaptureConfig, error) {
captureHelp := `
Capture artifacts that were written, executed or found to be suspicious.
Captured artifacts will appear in the 'output-path' directory.
Possible options:
[artifact:]write[=/path/prefix*] capture written files. A filter can be given to only capture file writes whose path starts with some prefix (up to 50 characters). Up to 3 filters can be given.
[artifact:]exec capture executed files.
[artifact:]mem capture memory regions that had write+execute (w+x) protection, and then changed to execute (x) only.
[artifact:]all capture all of the above artifacts.
dir:/path/to/dir path where tracee will save produced artifacts. the artifact will be saved into an 'out' subdirectory. (default: /tmp/tracee).
clear-dir clear the captured artifacts output dir before starting (default: false).
Examples:
--capture exec | capture executed files into the default output directory
--capture all --capture dir:/my/dir --capture clear-dir | delete /my/dir/out and then capture all supported artifacts into it
--capture write=/usr/bin/* --capture write=/etc/* | capture files that were written into anywhere under /usr/bin/ or /etc/
Use this flag multiple times to choose multiple capture options
`
if len(captureSlice) == 1 && captureSlice[0] == "help" {
return tracee.CaptureConfig{}, fmt.Errorf(captureHelp)
}
capture := tracee.CaptureConfig{}
outDir := "/tmp/tracee"
clearDir := false
var filterFileWrite []string
for i := range captureSlice {
cap := captureSlice[i]
if strings.HasPrefix(cap, "artifact:write") ||
strings.HasPrefix(cap, "artifact:exec") ||
strings.HasPrefix(cap, "artifact:mem") ||
strings.HasPrefix(cap, "artifact:all") {
cap = strings.TrimPrefix(cap, "artifact:")
}
if cap == "write" {
capture.FileWrite = true
} else if strings.HasPrefix(cap, "write=") && strings.HasSuffix(cap, "*") {
capture.FileWrite = true
pathPrefix := strings.TrimSuffix(strings.TrimPrefix(cap, "write="), "*")
if len(pathPrefix) == 0 {
return tracee.CaptureConfig{}, fmt.Errorf("capture write filter cannot be empty")
}
filterFileWrite = append(filterFileWrite, pathPrefix)
} else if cap == "exec" {
capture.Exec = true
} else if cap == "mem" {
capture.Mem = true
} else if cap == "all" {
capture.FileWrite = true
capture.Exec = true
capture.Mem = true
} else if cap == "clear-dir" {
clearDir = true
} else if strings.HasPrefix(cap, "dir:") {
outDir = strings.TrimPrefix(cap, "dir:")
if len(outDir) == 0 {
return tracee.CaptureConfig{}, fmt.Errorf("capture output dir cannot be empty")
}
} else {
return tracee.CaptureConfig{}, fmt.Errorf("invalid capture option specified, use '--capture help' for more info")
}
}
capture.FilterFileWrite = filterFileWrite
capture.OutputPath = filepath.Join(outDir, "out")
if clearDir {
os.RemoveAll(capture.OutputPath)
}
return capture, nil
}
func preparePinning(pinning string) (string, string, string, error) {
if pinning == "" {
return "", "", "", nil
}
pinInfo := strings.Split(pinning, ":")
if len(pinInfo) != 3 {
return "", "", "", fmt.Errorf("In order to pin the object you should provide pin_object_type:pin_object_name:ping_object_path")
}
typeName := pinInfo[0]
objectName := pinInfo[1]
path := pinInfo[2]
if typeName != "map" {
return "", "", "", fmt.Errorf("Only map is allowed as pinning object")
}
return typeName, objectName, path, nil
}
func prepareFilter(filters []string) (tracee.Filter, error) {
filterHelp := `
Select which events to trace by defining trace expressions that operate on events or process metadata.
Only events that match all trace expressions will be traced (trace flags are ANDed).
The following types of expressions are supported:
Numerical expressions which compare numbers and allow the following operators: '=', '!=', '<', '>'.
Available numerical expressions: uid, pid, mntns, pidns.
String expressions which compares text and allow the following operators: '=', '!='.
Available string expressions: event, set, uts, comm.
Boolean expressions that check if a boolean is true and allow the following operator: '!'.
Available boolean expressions: container.
Event arguments can be accessed using 'event_name.event_arg' and provide a way to filter an event by its arguments.
Event arguments allow the following operators: '=', '!='.
Strings can be compared as a prefix if ending with '*'.
Event return value can be accessed using 'event_name.retval' and provide a way to filter an event by its return value.
Event return value expression has the same syntax as a numerical expression.
Non-boolean expressions can compare a field to multiple values separated by ','.
Multiple values are ORed if used with equals operator '=', but are ANDed if used with any other operator.
The field 'container' and 'pid' also support the special value 'new' which selects new containers or pids, respectively.
The field 'set' selects a set of events to trace according to predefined sets, which can be listed by using the 'list' flag.
The special 'follow' expression declares that not only processes that match the criteria will be traced, but also their descendants.
Examples:
--trace pid=new | only trace events from new processes
--trace pid=510,1709 | only trace events from pid 510 or pid 1709
--trace p=510 --trace p=1709 | only trace events from pid 510 or pid 1709 (same as above)
--trace container=new | only trace events from newly created containers
--trace container | only trace events from containers
--trace c | only trace events from containers (same as above)
--trace '!container' | only trace events from the host
--trace uid=0 | only trace events from uid 0
--trace mntns=4026531840 | only trace events from mntns id 4026531840
--trace pidns!=4026531836 | only trace events from pidns id not equal to 4026531840
--trace 'uid>0' | only trace events from uids greater than 0
--trace 'pid>0' --trace 'pid<1000' | only trace events from pids between 0 and 1000
--trace 'u>0' --trace u!=1000 | only trace events from uids greater than 0 but not 1000
--trace event=execve,open | only trace execve and open events
--trace set=fs | trace all file-system related events
--trace s=fs --trace e!=open,openat | trace all file-system related events, but not open(at)
--trace uts!=ab356bc4dd554 | don't trace events from uts name ab356bc4dd554
--trace comm=ls | only trace events from ls command
--trace close.fd=5 | only trace 'close' events that have 'fd' equals 5
--trace openat.pathname=/tmp* | only trace 'openat' events that have 'pathname' prefixed by "/tmp"
--trace openat.pathname!=/tmp/1,/bin/ls | don't trace 'openat' events that have 'pathname' equals /tmp/1 or /bin/ls
--trace comm=bash --trace follow | trace all events that originated from bash or from one of the processes spawned by bash
Note: some of the above operators have special meanings in different shells.
To 'escape' those operators, please use single quotes, e.g.: 'uid>0'
`
if len(filters) == 1 && filters[0] == "help" {
return tracee.Filter{}, fmt.Errorf(filterHelp)
}
filter := tracee.Filter{
UIDFilter: &tracee.UintFilter{
Equal: []uint64{},
NotEqual: []uint64{},
Less: tracee.LessNotSetUint,
Greater: tracee.GreaterNotSetUint,
Is32Bit: true,
},
PIDFilter: &tracee.UintFilter{
Equal: []uint64{},
NotEqual: []uint64{},
Less: tracee.LessNotSetUint,
Greater: tracee.GreaterNotSetUint,
Is32Bit: true,
},
NewPidFilter: &tracee.BoolFilter{},
MntNSFilter: &tracee.UintFilter{
Equal: []uint64{},
NotEqual: []uint64{},
Less: tracee.LessNotSetUint,
Greater: tracee.GreaterNotSetUint,
},
PidNSFilter: &tracee.UintFilter{
Equal: []uint64{},
NotEqual: []uint64{},
Less: tracee.LessNotSetUint,
Greater: tracee.GreaterNotSetUint,
},
UTSFilter: &tracee.StringFilter{
Equal: []string{},
NotEqual: []string{},
},
CommFilter: &tracee.StringFilter{
Equal: []string{},
NotEqual: []string{},
},
ContFilter: &tracee.BoolFilter{},
NewContFilter: &tracee.BoolFilter{},
RetFilter: &tracee.RetFilter{
Filters: make(map[int32]tracee.IntFilter),
},
ArgFilter: &tracee.ArgFilter{
Filters: make(map[int32]map[string]tracee.ArgFilterVal),
},
EventsToTrace: []int32{},
}
eventFilter := &tracee.StringFilter{Equal: []string{}, NotEqual: []string{}}
setFilter := &tracee.StringFilter{Equal: []string{}, NotEqual: []string{}}
eventsNameToID := make(map[string]int32, len(tracee.EventsIDToEvent))
for _, event := range tracee.EventsIDToEvent {
eventsNameToID[event.Name] = event.ID
}
for _, f := range filters {
filterName := f
operatorAndValues := ""
operatorIndex := strings.IndexAny(f, "=!<>")
if operatorIndex > 0 {
filterName = f[0:operatorIndex]
operatorAndValues = f[operatorIndex:]
}
if strings.Contains(f, ".retval") {
err := parseRetFilter(filterName, operatorAndValues, eventsNameToID, filter.RetFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if strings.Contains(f, ".") {
err := parseArgFilter(filterName, operatorAndValues, eventsNameToID, filter.ArgFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
// The filters which are more common (container, event, pid, set, uid) can be given using a prefix of them.
// Other filters should be given using their full name.
// To avoid collisions between filters that share the same prefix, put the filters which should have an exact match first!
if filterName == "comm" {
err := parseStringFilter(operatorAndValues, filter.CommFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if strings.HasPrefix("container", f) || (strings.HasPrefix("!container", f) && len(f) > 1) {
filter.NewPidFilter.Enabled = true
filter.NewPidFilter.Value = true
err := parseBoolFilter(f, filter.ContFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if strings.HasPrefix("container", filterName) {
if operatorAndValues == "=new" {
filter.NewPidFilter.Enabled = true
filter.NewPidFilter.Value = true
filter.NewContFilter.Enabled = true
filter.NewContFilter.Value = true
continue
}
if operatorAndValues == "!=new" {
filter.ContFilter.Enabled = true
filter.ContFilter.Value = true
filter.NewPidFilter.Enabled = true
filter.NewPidFilter.Value = true
filter.NewContFilter.Enabled = true
filter.NewContFilter.Value = false
continue
}
}
if strings.HasPrefix("event", filterName) {
err := parseStringFilter(operatorAndValues, eventFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if filterName == "mntns" {
err := parseUintFilter(operatorAndValues, filter.MntNSFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if filterName == "pidns" {
err := parseUintFilter(operatorAndValues, filter.PidNSFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if strings.HasPrefix("pid", filterName) {
if operatorAndValues == "=new" {
filter.NewPidFilter.Enabled = true
filter.NewPidFilter.Value = true
continue
}
if operatorAndValues == "!=new" {
filter.NewPidFilter.Enabled = true
filter.NewPidFilter.Value = false
continue
}
err := parseUintFilter(operatorAndValues, filter.PIDFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if strings.HasPrefix("set", filterName) {
err := parseStringFilter(operatorAndValues, setFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if filterName == "uts" {
err := parseStringFilter(operatorAndValues, filter.UTSFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if strings.HasPrefix("uid", filterName) {
err := parseUintFilter(operatorAndValues, filter.UIDFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if strings.HasPrefix("follow", f) {
filter.Follow = true
continue
}
return tracee.Filter{}, fmt.Errorf("invalid filter option specified, use '--filter help' for more info")
}
var err error
filter.EventsToTrace, err = prepareEventsToTrace(eventFilter, setFilter, eventsNameToID)
if err != nil {
return tracee.Filter{}, err
}
return filter, nil
}
func parseUintFilter(operatorAndValues string, uintFilter *tracee.UintFilter) error {
uintFilter.Enabled = true
if len(operatorAndValues) < 2 {
return fmt.Errorf("invalid operator and/or values given to filter: %s", operatorAndValues)
}
valuesString := string(operatorAndValues[1:])
operatorString := string(operatorAndValues[0])
if operatorString == "!" {
if len(operatorAndValues) < 3 {
return fmt.Errorf("invalid operator and/or values given to filter: %s", operatorAndValues)
}
operatorString = operatorAndValues[0:2]
valuesString = operatorAndValues[2:]
}
values := strings.Split(valuesString, ",")
for i := range values {
val, err := strconv.ParseUint(values[i], 10, 64)
if err != nil {
return fmt.Errorf("invalid filter value: %s", values[i])
}
if uintFilter.Is32Bit && (val > math.MaxUint32) {
return fmt.Errorf("filter value is too big: %s", values[i])
}
switch operatorString {
case "=":
uintFilter.Equal = append(uintFilter.Equal, val)
case "!=":
uintFilter.NotEqual = append(uintFilter.NotEqual, val)
case ">":
if (uintFilter.Greater == tracee.GreaterNotSetUint) || (val > uintFilter.Greater) {
uintFilter.Greater = val
}
case "<":
if (uintFilter.Less == tracee.LessNotSetUint) || (val < uintFilter.Less) {
uintFilter.Less = val
}
default:
return fmt.Errorf("invalid filter operator: %s", operatorString)
}
}
return nil
}
func parseIntFilter(operatorAndValues string, intFilter *tracee.IntFilter) error {
intFilter.Enabled = true
if len(operatorAndValues) < 2 {
return fmt.Errorf("invalid operator and/or values given to filter: %s", operatorAndValues)
}
valuesString := string(operatorAndValues[1:])
operatorString := string(operatorAndValues[0])
if operatorString == "!" {
if len(operatorAndValues) < 3 {
return fmt.Errorf("invalid operator and/or values given to filter: %s", operatorAndValues)
}
operatorString = operatorAndValues[0:2]
valuesString = operatorAndValues[2:]
}
values := strings.Split(valuesString, ",")
for i := range values {
val, err := strconv.ParseInt(values[i], 10, 64)
if err != nil {
return fmt.Errorf("invalid filter value: %s", values[i])
}
if intFilter.Is32Bit && (val > math.MaxInt32) {
return fmt.Errorf("filter value is too big: %s", values[i])
}
switch operatorString {
case "=":
intFilter.Equal = append(intFilter.Equal, val)
case "!=":
intFilter.NotEqual = append(intFilter.NotEqual, val)
case ">":
if (intFilter.Greater == tracee.GreaterNotSetInt) || (val > intFilter.Greater) {
intFilter.Greater = val
}
case "<":
if (intFilter.Less == tracee.LessNotSetInt) || (val < intFilter.Less) {
intFilter.Less = val
}
default:
return fmt.Errorf("invalid filter operator: %s", operatorString)
}
}
return nil
}
func parseStringFilter(operatorAndValues string, stringFilter *tracee.StringFilter) error {
stringFilter.Enabled = true
if len(operatorAndValues) < 2 {
return fmt.Errorf("invalid operator and/or values given to filter: %s", operatorAndValues)
}
valuesString := string(operatorAndValues[1:])
operatorString := string(operatorAndValues[0])
if operatorString == "!" {
if len(operatorAndValues) < 3 {
return fmt.Errorf("invalid operator and/or values given to filter: %s", operatorAndValues)
}
operatorString = operatorAndValues[0:2]
valuesString = operatorAndValues[2:]
}
values := strings.Split(valuesString, ",")
for i := range values {
switch operatorString {
case "=":
stringFilter.Equal = append(stringFilter.Equal, values[i])
case "!=":
stringFilter.NotEqual = append(stringFilter.NotEqual, values[i])
default:
return fmt.Errorf("invalid filter operator: %s", operatorString)
}
}
return nil
}
func parseBoolFilter(value string, boolFilter *tracee.BoolFilter) error {
boolFilter.Enabled = true
boolFilter.Value = false
if value[0] != '!' {
boolFilter.Value = true
}
return nil
}
func parseArgFilter(filterName string, operatorAndValues string, eventsNameToID map[string]int32, argFilter *tracee.ArgFilter) error {
argFilter.Enabled = true
// Event argument filter has the following format: "event.argname=argval"
// filterName have the format event.argname, and operatorAndValues have the format "=argval"
splitFilter := strings.Split(filterName, ".")
if len(splitFilter) != 2 {
return fmt.Errorf("invalid argument filter format %s%s", filterName, operatorAndValues)
}
eventName := splitFilter[0]
argName := splitFilter[1]
id, ok := eventsNameToID[eventName]
if !ok {
return fmt.Errorf("invalid argument filter event name: %s", eventName)
}
eventParams, ok := tracee.EventsIDToParams[id]
if !ok {
return fmt.Errorf("invalid argument filter event name: %s", eventName)
}
// check if argument name exists for this event
argFound := false
for i := range eventParams {
if eventParams[i].Name == argName {
argFound = true
break
}
}
if !argFound {
return fmt.Errorf("invalid argument filter argument name: %s", argName)
}
strFilter := &tracee.StringFilter{
Equal: []string{},
NotEqual: []string{},
}
// Treat operatorAndValues as a string filter to avoid code duplication
err := parseStringFilter(operatorAndValues, strFilter)
if err != nil {
return err
}
if _, ok := argFilter.Filters[id]; !ok {
argFilter.Filters[id] = make(map[string]tracee.ArgFilterVal)
}
if _, ok := argFilter.Filters[id][argName]; !ok {
argFilter.Filters[id][argName] = tracee.ArgFilterVal{}
}
val := argFilter.Filters[id][argName]
val.Equal = append(val.Equal, strFilter.Equal...)
val.NotEqual = append(val.NotEqual, strFilter.NotEqual...)
argFilter.Filters[id][argName] = val
return nil
}
func parseRetFilter(filterName string, operatorAndValues string, eventsNameToID map[string]int32, retFilter *tracee.RetFilter) error {
retFilter.Enabled = true
// Ret filter has the following format: "event.ret=val"
// filterName have the format event.retval, and operatorAndValues have the format "=val"
splitFilter := strings.Split(filterName, ".")
if len(splitFilter) != 2 || splitFilter[1] != "retval" {
return fmt.Errorf("invalid retval filter format %s%s", filterName, operatorAndValues)
}
eventName := splitFilter[0]
id, ok := eventsNameToID[eventName]
if !ok {
return fmt.Errorf("invalid retval filter event name: %s", eventName)
}
if _, ok := retFilter.Filters[id]; !ok {
retFilter.Filters[id] = tracee.IntFilter{
Equal: []int64{},
NotEqual: []int64{},
Less: tracee.LessNotSetInt,
Greater: tracee.GreaterNotSetInt,
}
}
intFilter := retFilter.Filters[id]
// Treat operatorAndValues as an int filter to avoid code duplication
err := parseIntFilter(operatorAndValues, &intFilter)
if err != nil {
return err
}
retFilter.Filters[id] = intFilter
return nil
}
func prepareEventsToTrace(eventFilter *tracee.StringFilter, setFilter *tracee.StringFilter, eventsNameToID map[string]int32) ([]int32, error) {
eventFilter.Enabled = true
eventsToTrace := eventFilter.Equal
excludeEvents := eventFilter.NotEqual
setsToTrace := setFilter.Equal
var res []int32
setsToEvents := make(map[string][]int32)
isExcluded := make(map[int32]bool)
for id, event := range tracee.EventsIDToEvent {
for _, set := range event.Sets {
setsToEvents[set] = append(setsToEvents[set], id)
}
}
for _, name := range excludeEvents {
id, ok := eventsNameToID[name]
if !ok {
return nil, fmt.Errorf("invalid event to exclude: %s", name)
}
isExcluded[id] = true
}
if len(eventsToTrace) == 0 && len(setsToTrace) == 0 {
setsToTrace = append(setsToTrace, "default")
}
res = make([]int32, 0, len(tracee.EventsIDToEvent))
for _, name := range eventsToTrace {
id, ok := eventsNameToID[name]
if !ok {
return nil, fmt.Errorf("invalid event to trace: %s", name)
}
res = append(res, id)
}
for _, set := range setsToTrace {
setEvents, ok := setsToEvents[set]
if !ok {
return nil, fmt.Errorf("invalid set to trace: %s", set)
}
for _, id := range setEvents {
if !isExcluded[id] {
res = append(res, id)
}
}
}
return res, nil
}
func checkRequiredCapabilities() bool {
caps, err := getSelfCapabilities()
if err != nil {
return false
}
return caps.Get(capability.EFFECTIVE, capability.CAP_SYS_ADMIN)
}
func getSelfCapabilities() (capability.Capabilities, error) {
cap, err := capability.NewPid2(0)
if err != nil {
return nil, err
}
err = cap.Load()
if err != nil {
return nil, err
}
return cap, nil
}
func fetchFormattedEventParams(eventID int32) string {
eventParams := tracee.EventsIDToParams[eventID]
var verboseEventParams string
verboseEventParams += "("
prefix := ""
for index, arg := range eventParams {
if index == 0 {
verboseEventParams += arg.Type + " " + arg.Name
prefix = ", "
continue
}
verboseEventParams += prefix + arg.Type + " " + arg.Name
}
verboseEventParams += ")"
return verboseEventParams
}
func getPad(padChar string, padLength int) (pad string) {
for i := 0; i < padLength; i++ {
pad += padChar
}
return
}
func printList() {
padChar, firstPadLen, secondPadLen := " ", 9, 36
titleHeaderPadFirst := getPad(padChar, firstPadLen)
titleHeaderPadSecond := getPad(padChar, secondPadLen)
var b strings.Builder
b.WriteString("System Calls: " + titleHeaderPadFirst + "Sets:" + titleHeaderPadSecond + "Arguments:\n")
b.WriteString("____________ " + titleHeaderPadFirst + "____ " + titleHeaderPadSecond + "_________" + "\n\n")
for i := 0; i < int(tracee.SysEnterEventID); i++ {
index := int32(i)
event, ok := tracee.EventsIDToEvent[index]
if !ok {
continue
}
if event.Sets != nil {
eventSets := fmt.Sprintf("%-22s %-40s %s\n", event.Name, fmt.Sprintf("%v", event.Sets), fetchFormattedEventParams(index))
b.WriteString(eventSets)
} else {
b.WriteString(event.Name + "\n")
}
}
b.WriteString("\n\nOther Events: " + titleHeaderPadFirst + "Sets:" + titleHeaderPadSecond + "Arguments:\n")
b.WriteString("____________ " + titleHeaderPadFirst + "____ " + titleHeaderPadSecond + "_________\n\n")
for i := int(tracee.SysEnterEventID); i < int(tracee.MaxEventID); i++ {
index := int32(i)
event := tracee.EventsIDToEvent[index]
if event.Sets != nil {
eventSets := fmt.Sprintf("%-22s %-40s %s\n", event.Name, fmt.Sprintf("%v", event.Sets), fetchFormattedEventParams(index))
b.WriteString(eventSets)
} else {
b.WriteString(event.Name + "\n")
}
}
fmt.Println(b.String())
}
// locateFile locates a file named file, or a directory if name is empty, and returns it's full path
// It first tries in the paths given by the dirs, and then a system lookup
func locateFile(file string, dirs []string) string {
var res string
for _, dir := range dirs {
if dir != "" {
fi, err := os.Stat(filepath.Join(dir, file))
if err == nil && ((file == "" && fi.IsDir()) || (file != "" && fi.Mode().IsRegular())) {
return filepath.Join(dir, file)
}
}
}
if file != "" && res == "" {
p, _ := exec.LookPath(file)
if p != "" {
return p
}
}
return ""
}
// getBPFObject finds or builds ebpf object file and returns it's path
func getBPFObject() (string, error) {
bpfPath, present := os.LookupEnv("TRACEE_BPF_FILE")
if present {
if _, err := os.Stat(bpfPath); os.IsNotExist(err) {
return "", fmt.Errorf("path given in TRACEE_BPF_FILE doesn't exist!")
}
return bpfPath, nil
}
bpfObjFileName := fmt.Sprintf("tracee.bpf.%s.%s.o", strings.ReplaceAll(tracee.UnameRelease(), ".", "_"), strings.ReplaceAll(version, ".", "_"))
exePath, err := os.Executable()
if err != nil {
return "", err
}
//locations to search for the bpf file, in the following order
searchPaths := []string{
filepath.Dir(exePath),
traceeInstallPath,
}
bpfObjFilePath := locateFile(bpfObjFileName, searchPaths)
if bpfObjFilePath != "" && debug {
fmt.Printf("found bpf object file at: %s\n", bpfObjFilePath)
}
if (bpfObjFilePath == "" && buildPolicy != "never") || buildPolicy == "always" {
if debug {
fmt.Printf("attempting to build the bpf object file\n")
}
bpfObjInstallPath := filepath.Join(traceeInstallPath, bpfObjFileName)
err = makeBPFObject(bpfObjInstallPath)
if err != nil {