/
tracee.go
1796 lines (1563 loc) · 50.7 KB
/
tracee.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 ebpf
import (
gocontext "context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"fmt"
"io"
"os"
"strconv"
"strings"
"sync/atomic"
"time"
"unsafe"
lru "github.com/hashicorp/golang-lru/v2"
"golang.org/x/sys/unix"
"kernel.org/pub/linux/libs/security/libcap/cap"
bpf "github.com/aquasecurity/libbpfgo"
"github.com/aquasecurity/libbpfgo/helpers"
"github.com/aquasecurity/tracee/pkg/bucketscache"
"github.com/aquasecurity/tracee/pkg/bufferdecoder"
"github.com/aquasecurity/tracee/pkg/capabilities"
"github.com/aquasecurity/tracee/pkg/cgroup"
"github.com/aquasecurity/tracee/pkg/containers"
"github.com/aquasecurity/tracee/pkg/ebpf/initialization"
"github.com/aquasecurity/tracee/pkg/ebpf/probes"
"github.com/aquasecurity/tracee/pkg/errfmt"
"github.com/aquasecurity/tracee/pkg/events"
"github.com/aquasecurity/tracee/pkg/events/derive"
"github.com/aquasecurity/tracee/pkg/events/sorting"
"github.com/aquasecurity/tracee/pkg/events/trigger"
"github.com/aquasecurity/tracee/pkg/filters"
"github.com/aquasecurity/tracee/pkg/logger"
"github.com/aquasecurity/tracee/pkg/metrics"
"github.com/aquasecurity/tracee/pkg/pcaps"
"github.com/aquasecurity/tracee/pkg/policy"
"github.com/aquasecurity/tracee/pkg/signatures/engine"
"github.com/aquasecurity/tracee/pkg/utils"
"github.com/aquasecurity/tracee/pkg/utils/proc"
"github.com/aquasecurity/tracee/pkg/utils/sharedobjs"
"github.com/aquasecurity/tracee/types/trace"
)
const (
pkgName = "tracee"
maxMemDumpLength = 127
)
type fileExecInfo struct {
LastCtime int64
Hash string
}
type eventConfig struct {
submit uint64 // event that should be submitted to userspace (by policies bitmap)
emit uint64 // event that should be emitted to the user (by policies bitmap)
}
// Tracee traces system calls and system events using eBPF
type Tracee struct {
config Config
bootTime uint64
startTime uint64
running atomic.Bool
done chan struct{} // signal to safely stop end-stage processing
OutDir *os.File // use utils.XXX functions to create or write to this file
stats metrics.Stats
sigEngine *engine.Engine
// Events
events map[events.ID]eventConfig
eventsSorter *sorting.EventsChronologicalSorter
eventProcessor map[events.ID][]func(evt *trace.Event) error
eventDerivations derive.Table
// Artifacts
fileHashes *lru.Cache[string, fileExecInfo]
capturedFiles map[string]int64
writtenFiles map[string]string
netCapturePcap *pcaps.Pcaps
// Internal Data
readFiles map[string]string
pidsInMntns bucketscache.BucketsCache // first n PIDs in each mountns
kernelSymbols helpers.KernelSymbolTable
// eBPF
bpfModule *bpf.Module
probes *probes.ProbeGroup
// BPF Maps
StackAddressesMap *bpf.BPFMap
FDArgPathMap *bpf.BPFMap
// Perf Buffers
eventsPerfMap *bpf.PerfBuffer // perf buffer for events
fileWrPerfMap *bpf.PerfBuffer // perf buffer for file writes
netCapPerfMap *bpf.PerfBuffer // perf buffer for network captures
bpfLogsPerfMap *bpf.PerfBuffer // perf buffer for bpf logs
// Events Channels
eventsChannel chan []byte // channel for events
fileCapturesChannel chan []byte // channel for file writes
netCapChannel chan []byte // channel for network captures
bpfLogsChannel chan []byte // channel for bpf logs
// Lost Events Channels
lostEvChannel chan uint64 // channel for lost events
lostCapturesChannel chan uint64 // channel for lost file writes
lostNetCapChannel chan uint64 // channel for lost network captures
lostBPFLogChannel chan uint64 // channel for lost bpf logs
// Containers
cgroups *cgroup.Cgroups
containers *containers.Containers
contPathResolver *containers.ContainerPathResolver
contSymbolsLoader *sharedobjs.ContainersSymbolsLoader
// Specific Events Needs
triggerContexts trigger.Context
readyCallback func(gocontext.Context)
}
func (t *Tracee) Stats() *metrics.Stats {
return &t.stats
}
// GetEssentialEventsList sets the default events used by tracee
func GetEssentialEventsList() map[events.ID]eventConfig {
// Set essential events
return map[events.ID]eventConfig{
events.SchedProcessExec: {},
events.SchedProcessExit: {},
events.SchedProcessFork: {},
events.CgroupMkdir: {submit: 0xFFFFFFFFFFFFFFFF},
events.CgroupRmdir: {submit: 0xFFFFFFFFFFFFFFFF},
}
}
// GetCaptureEventsList sets events used to capture data
func GetCaptureEventsList(cfg Config) map[events.ID]eventConfig {
captureEvents := make(map[events.ID]eventConfig)
// All capture events should be placed, at least for now, to
// all matched policies, or else the event won't be set to
// matched policy in eBPF and should_submit() won't submit
// the capture event to userland.
if cfg.Capture.Exec {
captureEvents[events.CaptureExec] = eventConfig{
submit: 0xFFFFFFFFFFFFFFFF,
}
}
if cfg.Capture.FileWrite.Capture {
captureEvents[events.CaptureFileWrite] = eventConfig{
submit: 0xFFFFFFFFFFFFFFFF,
}
}
if cfg.Capture.FileRead.Capture {
captureEvents[events.CaptureFileRead] = eventConfig{}
}
if cfg.Capture.Module {
captureEvents[events.CaptureModule] = eventConfig{
submit: 0xFFFFFFFFFFFFFFFF,
}
}
if cfg.Capture.Mem {
captureEvents[events.CaptureMem] = eventConfig{
submit: 0xFFFFFFFFFFFFFFFF,
}
}
if cfg.Capture.Bpf {
captureEvents[events.CaptureBpf] = eventConfig{
submit: 0xFFFFFFFFFFFFFFFF,
}
}
if pcaps.PcapsEnabled(cfg.Capture.Net) {
captureEvents[events.CaptureNetPacket] = eventConfig{
submit: 0xFFFFFFFFFFFFFFFF,
}
}
return captureEvents
}
func (t *Tracee) handleEventsDependencies(eventId events.ID, submitMap uint64) {
definition := events.Definitions.Get(eventId)
eDependencies := definition.Dependencies
for _, dependentEvent := range eDependencies.Events {
ec, ok := t.events[dependentEvent.EventID]
if !ok {
ec = eventConfig{}
t.handleEventsDependencies(dependentEvent.EventID, submitMap)
}
ec.submit |= submitMap
t.events[dependentEvent.EventID] = ec
}
}
// New creates a new Tracee instance based on a given valid Config. It is
// expected that it won't cause external system side effects (reads, writes,
// etc.)
func New(cfg Config) (*Tracee, error) {
err := cfg.Validate()
if err != nil {
return nil, errfmt.Errorf("validation error: %v", err)
}
// Create Tracee
t := &Tracee{
config: cfg,
done: make(chan struct{}),
writtenFiles: make(map[string]string),
readFiles: make(map[string]string),
capturedFiles: make(map[string]int64),
events: GetEssentialEventsList(),
}
// Initialize capabilities rings soon
err = capabilities.Initialize(t.config.Capabilities.BypassCaps)
if err != nil {
return t, errfmt.WrapError(err)
}
caps := capabilities.GetInstance()
// Pseudo events added by capture
for eventID, eCfg := range GetCaptureEventsList(cfg) {
t.events[eventID] = eCfg
}
// Events chosen by the user
for p := range t.config.Policies.Map() {
for e := range p.EventsToTrace {
var submit, emit uint64
if _, ok := t.events[e]; ok {
submit = t.events[e].submit
emit = t.events[e].emit
}
utils.SetBit(&submit, uint(p.ID))
utils.SetBit(&emit, uint(p.ID))
t.events[e] = eventConfig{submit: submit, emit: emit}
}
}
// Handle all essential events dependencies
for id, evt := range t.events {
t.handleEventsDependencies(id, evt.submit)
}
// Update capabilities rings with all events dependencies
for id := range t.events {
evt, ok := events.Definitions.GetSafe(id)
if !ok {
return t, errfmt.Errorf("could not get event %d", id)
}
for ringType, capArray := range evt.Dependencies.Capabilities {
var f func(values ...cap.Value) error
switch ringType {
case capabilities.Base:
f = caps.BaseRingAdd
case capabilities.EBPF:
f = caps.EBPFRingAdd
}
err = f(capArray[:]...)
if err != nil {
return t, errfmt.WrapError(err)
}
}
}
// Add/Drop capabilities to/from the Base ring (always effective)
capsToAdd, err := capabilities.ReqByString(t.config.Capabilities.AddCaps...)
if err != nil {
return t, errfmt.WrapError(err)
}
err = caps.BaseRingAdd(capsToAdd...)
if err != nil {
return t, errfmt.WrapError(err)
}
capsToDrop, err := capabilities.ReqByString(t.config.Capabilities.DropCaps...)
if err != nil {
return t, errfmt.WrapError(err)
}
err = caps.BaseRingRemove(capsToDrop...)
if err != nil {
return t, errfmt.WrapError(err)
}
// Register default event processors
t.registerEventProcessors()
// Start event triggering logic context
t.triggerContexts = trigger.NewContext()
// Export metrics to prometheus if enabled
if t.config.MetricsEnabled {
err := t.Stats().RegisterPrometheus()
if err != nil {
logger.Errorw("Registering prometheus metrics", "error", err)
}
}
return t, nil
}
// Init initialize tracee instance and it's various subsystems, potentially
// performing external system operations to initialize them. NOTE: any
// initialization logic, especially one that causes side effects, should go
// here and not New().
func (t *Tracee) Init() error {
// Initialize needed values
initReq, err := t.generateInitValues()
if err != nil {
return errfmt.Errorf("failed to generate required init values: %s", err)
}
// Init kernel symbols map
if initReq.kallsyms {
err = capabilities.GetInstance().Specific(
func() error {
return t.NewKernelSymbols()
},
cap.SYSLOG,
)
if err != nil {
return errfmt.WrapError(err)
}
}
t.validateKallsymsDependencies() // Canceling events missing kernel symbols
// Initialize buckets cache
var mntNSProcs map[int]int
if t.config.maxPidsCache == 0 {
t.config.maxPidsCache = 5 // TODO: configure this ? never set, default = 5
}
t.pidsInMntns.Init(t.config.maxPidsCache)
err = capabilities.GetInstance().Specific(
func() error {
mntNSProcs, err = proc.GetMountNSFirstProcesses()
return err
},
cap.DAC_OVERRIDE,
cap.SYS_PTRACE,
)
if err == nil {
for mountNS, pid := range mntNSProcs {
t.pidsInMntns.AddBucketItem(uint32(mountNS), uint32(pid))
}
} else {
logger.Debugw("Initializing buckets cache", "error", errfmt.WrapError(err))
}
// Initialize cgroups filesystems
t.cgroups, err = cgroup.NewCgroups()
if err != nil {
return errfmt.WrapError(err)
}
// Initialize containers enrichment logic
t.containers, err = containers.New(
t.cgroups,
t.config.Sockets,
"containers_map",
)
if err != nil {
return errfmt.Errorf("error initializing containers: %v", err)
}
if err := t.containers.Populate(); err != nil {
return errfmt.Errorf("error initializing containers: %v", err)
}
t.contPathResolver = containers.InitContainerPathResolver(&t.pidsInMntns)
t.contSymbolsLoader = sharedobjs.InitContainersSymbolsLoader(t.contPathResolver, 1024)
// Initialize event derivation logic
err = t.initDerivationTable()
if err != nil {
return errfmt.Errorf("error initializing event derivation map: %v", err)
}
// Initialize eBPF programs and maps
err = capabilities.GetInstance().EBPF(
func() error {
return t.initBPF()
},
)
if err != nil {
t.Close()
return errfmt.WrapError(err)
}
// Initialize hashes for files
t.fileHashes, err = lru.New[string, fileExecInfo](1024)
if err != nil {
t.Close()
return errfmt.WrapError(err)
}
// Initialize capture directory
if err := os.MkdirAll(t.config.Capture.OutputPath, 0755); err != nil {
t.Close()
return errfmt.Errorf("error creating output path: %v", err)
}
t.OutDir, err = utils.OpenExistingDir(t.config.Capture.OutputPath)
if err != nil {
t.Close()
return errfmt.Errorf("error opening out directory: %v", err)
}
// Initialize network capture (all needed pcap files)
t.netCapturePcap, err = pcaps.New(t.config.Capture.Net, t.OutDir)
if err != nil {
t.Close()
return errfmt.Errorf("error initializing network capture: %v", err)
}
// Get reference to stack trace addresses map
stackAddressesMap, err := t.bpfModule.GetMap("stack_addresses")
if err != nil {
t.Close()
return errfmt.Errorf("error getting access to 'stack_addresses' eBPF Map %v", err)
}
t.StackAddressesMap = stackAddressesMap
// Get reference to fd arg path map
fdArgPathMap, err := t.bpfModule.GetMap("fd_arg_path_map")
if err != nil {
t.Close()
return errfmt.Errorf("error getting access to 'fd_arg_path_map' eBPF Map %v", err)
}
t.FDArgPathMap = fdArgPathMap
// Initialize events sorting (pipeline step)
if t.config.Output.EventsSorting {
t.eventsSorter, err = sorting.InitEventSorter()
if err != nil {
return errfmt.WrapError(err)
}
}
// Tracee bpf code uses monotonic clock as event timestamp. Get current
// monotonic clock so tracee can calculate event timestamps relative to it.
var ts unix.Timespec
err = unix.ClockGettime(unix.CLOCK_MONOTONIC, &ts)
if err != nil {
return errfmt.Errorf("getting clock time %v", err)
}
startTime := ts.Nano()
// Calculate the boot time using the monotonic time (since this is the clock
// we're using as a timestamp) Note: this is NOT the real boot time, as the
// monotonic clock doesn't take into account system sleeps.
bootTime := time.Now().UnixNano() - startTime
// Initialize times
t.startTime = uint64(startTime)
t.bootTime = uint64(bootTime)
return nil
}
func (t *Tracee) generateInitValues() (InitValues, error) {
initVals := InitValues{}
for evt := range t.events {
def, exists := events.Definitions.GetSafe(evt)
if !exists {
return initVals, errfmt.Errorf("event with id %d doesn't exist", evt)
}
if def.Dependencies.KSymbols != nil {
initVals.kallsyms = true
}
}
return initVals, nil
}
// initTailCall initializes a given tailcall.
func (t *Tracee) initTailCall(tailCall *events.TailCall) error {
bpfMap, err := t.bpfModule.GetMap(tailCall.GetMapName())
if err != nil {
return errfmt.WrapError(err)
}
bpfProg, err := t.bpfModule.GetProgram(tailCall.GetProgName())
if err != nil {
return errfmt.Errorf("could not get BPF program %s: %v", tailCall.GetProgName(), err)
}
fd := bpfProg.FileDescriptor()
if fd < 0 {
return errfmt.Errorf("could not get BPF program FD for %s: %v", tailCall.GetProgName(), err)
}
// Attach internal syscall probes if needed.
for _, index := range tailCall.GetIndexes() {
def := events.Definitions.Get(events.ID(index))
if def.Syscall {
err := t.probes.Attach(probes.SyscallEnter__Internal)
if err != nil {
return errfmt.WrapError(err)
}
err = t.probes.Attach(probes.SyscallExit__Internal)
if err != nil {
return errfmt.WrapError(err)
}
}
err := bpfMap.Update(unsafe.Pointer(&index), unsafe.Pointer(&fd))
if err != nil {
return errfmt.WrapError(err)
}
}
return nil
}
// initDerivationTable initializes tracee's events.DerivationTable. For each
// event, represented through its ID, we declare to which other events it can be
// derived and the corresponding function to derive into that Event.
func (t *Tracee) initDerivationTable() error {
shouldSubmit := func(id events.ID) func() bool {
return func() bool { return t.events[id].submit > 0 }
}
t.eventDerivations = derive.Table{
events.CgroupMkdir: {
events.ContainerCreate: {
Enabled: shouldSubmit(events.ContainerCreate),
DeriveFunction: derive.ContainerCreate(t.containers),
},
},
events.CgroupRmdir: {
events.ContainerRemove: {
Enabled: shouldSubmit(events.ContainerRemove),
DeriveFunction: derive.ContainerRemove(t.containers),
},
},
events.PrintSyscallTable: {
events.HookedSyscalls: {
Enabled: shouldSubmit(events.PrintSyscallTable),
DeriveFunction: derive.DetectHookedSyscall(t.kernelSymbols),
},
},
events.PrintNetSeqOps: {
events.HookedSeqOps: {
Enabled: shouldSubmit(events.HookedSeqOps),
DeriveFunction: derive.HookedSeqOps(t.kernelSymbols),
},
},
events.HiddenKernelModuleSeeker: {
events.HiddenKernelModule: {
Enabled: shouldSubmit(events.HiddenKernelModuleSeeker),
DeriveFunction: derive.HiddenKernelModule(),
},
},
events.SharedObjectLoaded: {
events.SymbolsLoaded: {
Enabled: shouldSubmit(events.SymbolsLoaded),
DeriveFunction: derive.SymbolsLoaded(
t.contSymbolsLoader,
t.config.Policies,
),
},
events.SymbolsCollision: {
Enabled: shouldSubmit(events.SymbolsCollision),
DeriveFunction: derive.SymbolsCollision(
t.contSymbolsLoader,
t.config.Policies,
),
},
},
events.SchedProcessExec: {
events.SymbolsCollision: {
Enabled: shouldSubmit(events.SymbolsCollision),
DeriveFunction: derive.SymbolsCollision(
t.contSymbolsLoader,
t.config.Policies,
),
},
},
//
// Network Derivations
//
events.NetPacketIPBase: {
events.NetPacketIPv4: {
Enabled: shouldSubmit(events.NetPacketIPv4),
DeriveFunction: derive.NetPacketIPv4(),
},
events.NetPacketIPv6: {
Enabled: shouldSubmit(events.NetPacketIPv6),
DeriveFunction: derive.NetPacketIPv6(),
},
},
events.NetPacketTCPBase: {
events.NetPacketTCP: {
Enabled: shouldSubmit(events.NetPacketTCP),
DeriveFunction: derive.NetPacketTCP(),
},
},
events.NetPacketUDPBase: {
events.NetPacketUDP: {
Enabled: shouldSubmit(events.NetPacketUDP),
DeriveFunction: derive.NetPacketUDP(),
},
},
events.NetPacketICMPBase: {
events.NetPacketICMP: {
Enabled: shouldSubmit(events.NetPacketICMP),
DeriveFunction: derive.NetPacketICMP(),
},
},
events.NetPacketICMPv6Base: {
events.NetPacketICMPv6: {
Enabled: shouldSubmit(events.NetPacketICMPv6),
DeriveFunction: derive.NetPacketICMPv6(),
},
},
events.NetPacketDNSBase: {
events.NetPacketDNS: {
Enabled: shouldSubmit(events.NetPacketDNS),
DeriveFunction: derive.NetPacketDNS(),
},
events.NetPacketDNSRequest: {
Enabled: shouldSubmit(events.NetPacketDNSRequest),
DeriveFunction: derive.NetPacketDNSRequest(),
},
events.NetPacketDNSResponse: {
Enabled: shouldSubmit(events.NetPacketDNSResponse),
DeriveFunction: derive.NetPacketDNSResponse(),
},
},
events.NetPacketHTTPBase: {
events.NetPacketHTTP: {
Enabled: shouldSubmit(events.NetPacketHTTP),
DeriveFunction: derive.NetPacketHTTP(),
},
events.NetPacketHTTPRequest: {
Enabled: shouldSubmit(events.NetPacketHTTPRequest),
DeriveFunction: derive.NetPacketHTTPRequest(),
},
events.NetPacketHTTPResponse: {
Enabled: shouldSubmit(events.NetPacketHTTPResponse),
DeriveFunction: derive.NetPacketHTTPResponse(),
},
},
}
return nil
}
// RegisterEventDerivation registers an event derivation handler for tracee to use in the event pipeline
func (t *Tracee) RegisterEventDerivation(deriveFrom events.ID, deriveTo events.ID, deriveCondition func() bool, deriveLogic derive.DeriveFunction) error {
if t.eventDerivations == nil {
return errfmt.Errorf("tracee not initialized yet")
}
return t.eventDerivations.Register(deriveFrom, deriveTo, deriveCondition, deriveLogic)
}
// options config should match defined values in ebpf code
const (
optExecEnv uint32 = 1 << iota
optCaptureFilesWrite
optExtractDynCode
optStackAddresses
optCaptureModules
optCgroupV1
optProcessInfo
optTranslateFDFilePath
optCaptureBpf
optCaptureFileRead
)
func (t *Tracee) getOptionsConfig() uint32 {
var cOptVal uint32
if t.config.Output.ExecEnv {
cOptVal = cOptVal | optExecEnv
}
if t.config.Output.StackAddresses {
cOptVal = cOptVal | optStackAddresses
}
if t.config.Capture.FileWrite.Capture {
cOptVal = cOptVal | optCaptureFilesWrite
}
if t.config.Capture.FileRead.Capture {
cOptVal = cOptVal | optCaptureFileRead
}
if t.config.Capture.Module {
cOptVal = cOptVal | optCaptureModules
}
if t.config.Capture.Bpf {
cOptVal = cOptVal | optCaptureBpf
}
if t.config.Capture.Mem {
cOptVal = cOptVal | optExtractDynCode
}
switch t.cgroups.GetDefaultCgroup().(type) {
case *cgroup.CgroupV1:
cOptVal = cOptVal | optCgroupV1
}
if t.config.Output.ParseArgumentsFDs {
cOptVal = cOptVal | optTranslateFDFilePath
}
return cOptVal
}
func (t *Tracee) computeConfigValues() []byte {
// config_entry
configVal := make([]byte, 256)
// tracee_pid
binary.LittleEndian.PutUint32(configVal[0:4], uint32(os.Getpid()))
// options
binary.LittleEndian.PutUint32(configVal[4:8], t.getOptionsConfig())
// cgroup_v1_hid
binary.LittleEndian.PutUint32(configVal[8:12], uint32(t.containers.GetDefaultCgroupHierarchyID()))
// padding
binary.LittleEndian.PutUint32(configVal[12:16], 0)
for p := range t.config.Policies.Map() {
byteIndex := p.ID / 8
bitOffset := p.ID % 8
// filter enabled policies bitmap
if p.UIDFilter.Enabled() {
// uid_filter_enabled_scopes
configVal[16+byteIndex] |= 1 << bitOffset
}
if p.PIDFilter.Enabled() {
// pid_filter_enabled_scopes
configVal[24+byteIndex] |= 1 << bitOffset
}
if p.MntNSFilter.Enabled() {
// mnt_ns_filter_enabled_scopes
configVal[32+byteIndex] |= 1 << bitOffset
}
if p.PidNSFilter.Enabled() {
// pid_ns_filter_enabled_scopes
configVal[40+byteIndex] |= 1 << bitOffset
}
if p.UTSFilter.Enabled() {
// uts_ns_filter_enabled_scopes
configVal[48+byteIndex] |= 1 << bitOffset
}
if p.CommFilter.Enabled() {
// comm_filter_enabled_scopes
configVal[56+byteIndex] |= 1 << bitOffset
}
if p.ContIDFilter.Enabled() {
// cgroup_id_filter_enabled_scopes
configVal[64+byteIndex] |= 1 << bitOffset
}
if p.ContFilter.Enabled() {
// cont_filter_enabled_scopes
configVal[72+byteIndex] |= 1 << bitOffset
}
if p.NewContFilter.Enabled() {
// new_cont_filter_enabled_scopes
configVal[80+byteIndex] |= 1 << bitOffset
}
if p.NewPidFilter.Enabled() {
// new_pid_filter_enabled_scopes
configVal[88+byteIndex] |= 1 << bitOffset
}
if p.ProcessTreeFilter.Enabled() {
// proc_tree_filter_enabled_scopes
configVal[96+byteIndex] |= 1 << bitOffset
}
if p.BinaryFilter.Enabled() {
// bin_path_filter_enabled_scopes
configVal[104+byteIndex] |= 1 << bitOffset
}
if p.Follow {
// follow_filter_enabled_scopes
configVal[112+byteIndex] |= 1 << bitOffset
}
// filter out scopes bitmap
if p.UIDFilter.FilterOut() {
// uid_filter_out_scopes
configVal[120+byteIndex] |= 1 << bitOffset
}
if p.PIDFilter.FilterOut() {
// pid_filter_out_scopes
configVal[128+byteIndex] |= 1 << bitOffset
}
if p.MntNSFilter.FilterOut() {
// mnt_ns_filter_out_scopes
configVal[136+byteIndex] |= 1 << bitOffset
}
if p.PidNSFilter.FilterOut() {
// pid_ns_filter_out_scopes
configVal[144+byteIndex] |= 1 << bitOffset
}
if p.UTSFilter.FilterOut() {
// uts_ns_filter_out_scopes
configVal[152+byteIndex] |= 1 << bitOffset
}
if p.CommFilter.FilterOut() {
// comm_filter_out_scopes
configVal[160+byteIndex] |= 1 << bitOffset
}
if p.ContIDFilter.FilterOut() {
// cgroup_id_filter_out_scopes
configVal[168+byteIndex] |= 1 << bitOffset
}
if p.ContFilter.FilterOut() {
// cont_filter_out_scopes
configVal[176+byteIndex] |= 1 << bitOffset
}
if p.NewContFilter.FilterOut() {
// new_cont_filter_out_scopes
configVal[184+byteIndex] |= 1 << bitOffset
}
if p.NewPidFilter.FilterOut() {
// new_pid_filter_out_scopes
configVal[192+byteIndex] |= 1 << bitOffset
}
if p.ProcessTreeFilter.FilterOut() {
// proc_tree_filter_out_scopes
configVal[200+byteIndex] |= 1 << bitOffset
}
if p.BinaryFilter.FilterOut() {
// bin_path_filter_out_scopes
configVal[208+byteIndex] |= 1 << bitOffset
}
// enabled_scopes
configVal[216+byteIndex] |= 1 << bitOffset
}
// compute all policies internals
t.config.Policies.Compute()
// uid_max
binary.LittleEndian.PutUint64(configVal[224:232], t.config.Policies.UIDFilterMax())
// uid_min
binary.LittleEndian.PutUint64(configVal[232:240], t.config.Policies.UIDFilterMin())
// pid_max
binary.LittleEndian.PutUint64(configVal[240:248], t.config.Policies.PIDFilterMax())
// pid_min
binary.LittleEndian.PutUint64(configVal[248:256], t.config.Policies.PIDFilterMin())
return configVal
}
// validateKallsymsDependencies load all symbols required by events dependencies
// from the kallsyms file to check for missing symbols. If some symbols are
// missing, it will cancel their event with informative error message.
func (t *Tracee) validateKallsymsDependencies() {
var reqKsyms []string
symsToDependentEvents := make(map[string][]events.ID)
for id := range t.events {
event := events.Definitions.Get(id)
if event.Dependencies.KSymbols != nil {
for _, symDep := range *event.Dependencies.KSymbols {
reqKsyms = append(reqKsyms, symDep.Symbol)
if symDep.Required {
symEvents, ok := symsToDependentEvents[symDep.Symbol]
if ok {
symEvents = append(symEvents, id)
} else {
symEvents = []events.ID{id}
}
symsToDependentEvents[symDep.Symbol] = symEvents
}
}
}
}
kallsymsValues := LoadKallsymsValues(t.kernelSymbols, reqKsyms)
// Figuring out for each event if it has missing required symbols and which
missingSymsPerEvent := make(map[events.ID][]string)
for sym, depEventsIDs := range symsToDependentEvents {
_, ok := kallsymsValues[sym]
if ok {
continue
}
for _, depEventID := range depEventsIDs {
eventMissingSyms, ok := missingSymsPerEvent[depEventID]
if ok {
eventMissingSyms = append(eventMissingSyms, sym)
} else {
eventMissingSyms = []string{sym}
}
missingSymsPerEvent[depEventID] = eventMissingSyms
}
}
// Cancel events with missing symbols dependencies
for eventToCancel, missingDepSyms := range missingSymsPerEvent {
logger.Errorw("Event canceled because of missing kernel symbol dependency", "missing symbols", missingDepSyms, "event", events.Definitions.Get(eventToCancel).Name)
delete(t.events, eventToCancel)
}
}
func (t *Tracee) populateBPFMaps() error {
// Initialize events parameter types map
eventsParams := make(map[events.ID][]bufferdecoder.ArgType)
for id, eventDefinition := range events.Definitions.Events() {
params := eventDefinition.Params
for _, param := range params {
eventsParams[id] = append(eventsParams[id], bufferdecoder.GetParamType(param.Type))
}
}
// Prepare events map
eventsMap, err := t.bpfModule.GetMap("events_map")
if err != nil {
return errfmt.WrapError(err)
}
for id, ecfg := range t.events {
eventConfigVal := make([]byte, 16)
// bitmap of policies that require this event to be submitted
binary.LittleEndian.PutUint64(eventConfigVal[0:8], ecfg.submit)
// encoded event's parameter types
var paramTypes uint64
params := eventsParams[id]
for n, paramType := range params {
paramTypes = paramTypes | (uint64(paramType) << (8 * n))
}
binary.LittleEndian.PutUint64(eventConfigVal[8:16], paramTypes)
err := eventsMap.Update(unsafe.Pointer(&id), unsafe.Pointer(&eventConfigVal[0]))
if err != nil {
return errfmt.WrapError(err)
}
}
// Prepare 32bit to 64bit syscall number mapping
sys32to64BPFMap, err := t.bpfModule.GetMap("sys_32_to_64_map") // u32, u32
if err != nil {
return errfmt.WrapError(err)
}
for id, event := range events.Definitions.Events() {
id32BitU32 := uint32(event.ID32Bit) // ID32Bit is int32
idU32 := uint32(id) // ID is int32
if err := sys32to64BPFMap.Update(unsafe.Pointer(&id32BitU32), unsafe.Pointer(&idU32)); err != nil {
return errfmt.WrapError(err)
}
}
if t.kernelSymbols != nil {
err = t.UpdateBPFKsymbolsMap()
if err != nil {
return errfmt.WrapError(err)
}
}
// Initialize kconfig variables (map used instead of relying in libbpf's .kconfig automated maps)
// Note: this allows libbpf not to rely on the system kconfig file, tracee does the kconfig var identification job
bpfKConfigMap, err := t.bpfModule.GetMap("kconfig_map") // u32, u32
if err != nil {
return errfmt.WrapError(err)
}
kconfigValues, err := initialization.LoadKconfigValues(t.config.KernelConfig)
if err != nil {
return errfmt.WrapError(err)
}
for key, value := range kconfigValues {
keyU32 := uint32(key)
valueU32 := uint32(value)
err = bpfKConfigMap.Update(unsafe.Pointer(&keyU32), unsafe.Pointer(&valueU32))
if err != nil {
return errfmt.WrapError(err)
}
}